diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 79680dd37886..426203e9c9e0 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -3,18 +3,31 @@ # See: https://help.github.com/articles/about-codeowners/ +* @gimantha + # Components -/compiler/ @sameerajayasoma @hasithaa -/langlib/ @sameerajayasoma @hasithaa -/semtypes/ @sameerajayasoma @hasithaa -/language-server/ @mohanvive @IMS94 -/ballerina-shell/ @mohanvive +/compiler/ @sameerajayasoma @hasithaa @gimantha @MaryamZi +/ballerina-shell/ @KavinduZoysa +/build-config/ @keizer619 /bvm/ @warunalakshitha -/observelib/ @nadundesilva -/cli/ @hevayo -/distribution/ @hevayo -/misc/ @hevayo -/project-api/ @hevayo @sameerajayasoma +/cli/ @azinneera +/distribution/ @keizer619 +/gradle/ @keizer619 +/langlib/ @sameerajayasoma @hasithaa @gimantha @MaryamZi +/semtypes/ @gimantha @MaryamZi +/language-server/ @KavinduZoysa +/misc/ballerina-bindgen/ @warunalakshitha +/misc/compiler-plugins/ @azinneera +/misc/debug-adapter/ @NipunaRanasinghe +/misc/docerina/ @keizer619 +/misc/identifier-util/ @warunalakshitha +/misc/json-to-record-converter/ @NipunaRanasinghe +/misc/semver-checker/ @NipunaRanasinghe +/misc/testerina/ @azinneera @Dilhasha +/misc/xml-to-record-converter/ @NipunaRanasinghe +/project-api/ @azinneera @sameerajayasoma +/performance/ @anuruddhal +/tests/ @gimantha @MaryamZi @KavinduZoysa @warunalakshitha @azinneera # CODEOWNERS file -/.github/CODEOWNERS @sameerajayasoma @hasithaa @anupama-pathirage @warunalakshitha @mohanvive @manuranga @hevayo +/.github/CODEOWNERS @sameerajayasoma @gimantha @MaryamZi @hasithaa diff --git a/.github/workflows/pull_request_full_build.yml b/.github/workflows/pull_request_full_build.yml index 2679e53676c4..1e24c1eb6cb9 100644 --- a/.github/workflows/pull_request_full_build.yml +++ b/.github/workflows/pull_request_full_build.yml @@ -43,6 +43,7 @@ jobs: with: name: Ballerina Lang Artifacts path: ~/.m2/ + include-hidden-files: true outputs: lang_version: ${{ steps.lang-version.outputs.version }} diff --git a/.github/workflows/stale_check.yml b/.github/workflows/stale_check.yml deleted file mode 100644 index 209dde589d47..000000000000 --- a/.github/workflows/stale_check.yml +++ /dev/null @@ -1,19 +0,0 @@ -name: 'Close stale pull requests' - -on: - schedule: - - cron: '30 19 * * *' - workflow_dispatch: - -jobs: - stale: - runs-on: ubuntu-latest - steps: - - uses: actions/stale@v9 - with: - stale-pr-message: 'This PR has been open for more than 15 days with no activity. This will be closed in 3 days unless the `stale` label is removed or commented.' - close-pr-message: 'Closed PR due to inactivity for more than 18 days.' - days-before-pr-stale: 15 - days-before-pr-close: 3 - days-before-issue-stale: -1 - days-before-issue-close: -1 diff --git a/ballerina-shell/modules/shell-cli/src/main/java/io/ballerina/shell/cli/ReplShellApplication.java b/ballerina-shell/modules/shell-cli/src/main/java/io/ballerina/shell/cli/ReplShellApplication.java index c64ca77f276b..eb0880b6455b 100644 --- a/ballerina-shell/modules/shell-cli/src/main/java/io/ballerina/shell/cli/ReplShellApplication.java +++ b/ballerina-shell/modules/shell-cli/src/main/java/io/ballerina/shell/cli/ReplShellApplication.java @@ -38,7 +38,11 @@ * * @since 2.0.0 */ -public class ReplShellApplication { +public final class ReplShellApplication { + + private ReplShellApplication() { + } + /** * Executes the repl shell. * diff --git a/ballerina-shell/modules/shell-cli/src/main/java/io/ballerina/shell/cli/jline/JlineTerminalAdapter.java b/ballerina-shell/modules/shell-cli/src/main/java/io/ballerina/shell/cli/jline/JlineTerminalAdapter.java index c37e27a58b17..9647488fb57f 100644 --- a/ballerina-shell/modules/shell-cli/src/main/java/io/ballerina/shell/cli/jline/JlineTerminalAdapter.java +++ b/ballerina-shell/modules/shell-cli/src/main/java/io/ballerina/shell/cli/jline/JlineTerminalAdapter.java @@ -26,6 +26,8 @@ import org.jline.utils.AttributedStringBuilder; import org.jline.utils.AttributedStyle; +import java.io.PrintWriter; + /** * Terminal adapter which encapsulates Jline. * @@ -56,10 +58,12 @@ public String readLine(String prefix, String postfix) throws ShellExitException } } + @SuppressWarnings("resource") @Override public void println(String text) { - lineReader.getTerminal().writer().println(text); - lineReader.getTerminal().writer().flush(); + PrintWriter writer = lineReader.getTerminal().writer(); + writer.println(text); + writer.flush(); } @Override diff --git a/ballerina-shell/modules/shell-cli/src/main/java/io/ballerina/shell/cli/jline/parser/ParserStateMachine.java b/ballerina-shell/modules/shell-cli/src/main/java/io/ballerina/shell/cli/jline/parser/ParserStateMachine.java index 6bbfeb773894..d17cdc75b0a5 100644 --- a/ballerina-shell/modules/shell-cli/src/main/java/io/ballerina/shell/cli/jline/parser/ParserStateMachine.java +++ b/ballerina-shell/modules/shell-cli/src/main/java/io/ballerina/shell/cli/jline/parser/ParserStateMachine.java @@ -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. @@ -65,12 +66,12 @@ public class ParserStateMachine { CLOSE_PAREN, OPEN_PAREN, CLOSE_SQ_BR, OPEN_SQ_BR); - private final Stack stack; + private final Deque stack; private ParserState state; public ParserStateMachine() { this.state = ParserState.NORMAL; - this.stack = new Stack<>(); + this.stack = new ArrayDeque<>(); } public void feed(char character) { @@ -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; @@ -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; @@ -310,6 +311,6 @@ public boolean isIncomplete() { return true; } // Otherwise, all brackets/backticks are closed is completion - return !stack.empty(); + return !stack.isEmpty(); } } diff --git a/ballerina-shell/modules/shell-cli/src/main/java/io/ballerina/shell/cli/utils/FileUtils.java b/ballerina-shell/modules/shell-cli/src/main/java/io/ballerina/shell/cli/utils/FileUtils.java index 79cad030a59d..e853db527f0a 100644 --- a/ballerina-shell/modules/shell-cli/src/main/java/io/ballerina/shell/cli/utils/FileUtils.java +++ b/ballerina-shell/modules/shell-cli/src/main/java/io/ballerina/shell/cli/utils/FileUtils.java @@ -34,9 +34,13 @@ * * @since 2.0.0 */ -public class FileUtils { +public final class FileUtils { + private static final String SPECIAL_DELIMITER = "\\A"; + private FileUtils() { + } + /** * Reads the file content from the resources. * diff --git a/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/invoker/ShellSnippetsInvoker.java b/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/invoker/ShellSnippetsInvoker.java index 6b7ea3d4e1d2..19543b828c74 100644 --- a/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/invoker/ShellSnippetsInvoker.java +++ b/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/invoker/ShellSnippetsInvoker.java @@ -43,6 +43,7 @@ import io.ballerina.shell.invoker.classload.context.ClassLoadContext; import io.ballerina.shell.snippet.Snippet; import io.ballerina.shell.utils.StringUtils; +import io.ballerina.tools.diagnostics.Diagnostic; import io.ballerina.tools.diagnostics.DiagnosticSeverity; import java.io.File; @@ -277,7 +278,7 @@ protected PackageCompilation compile(Project project) throws InvokerException { PackageCompilation packageCompilation = project.currentPackage().getCompilation(); DiagnosticResult diagnosticResult = packageCompilation.diagnosticResult(); - for (io.ballerina.tools.diagnostics.Diagnostic diagnostic : diagnosticResult.diagnostics()) { + for (Diagnostic diagnostic : diagnosticResult.diagnostics()) { DiagnosticSeverity severity = diagnostic.diagnosticInfo().severity(); if (severity == DiagnosticSeverity.ERROR) { containErrors = true; @@ -329,7 +330,7 @@ protected void compileImportStatement(String importStatement) throws InvokerExce * @return Whether the compilation contains MODULE_NOT_FOUND error. */ private boolean containsModuleNotFoundError(PackageCompilation compilation) { - for (io.ballerina.tools.diagnostics.Diagnostic diagnostic : compilation.diagnosticResult().diagnostics()) { + for (Diagnostic diagnostic : compilation.diagnosticResult().diagnostics()) { if (diagnostic.diagnosticInfo().code().equals(MODULE_NOT_FOUND_CODE)) { return true; } @@ -435,9 +436,9 @@ protected Object invokeScheduledMethod(ClassLoader classLoader, String className // Unexpected runtime error throw new InvokerPanicException(panic); } - if (result instanceof Throwable) { + if (result instanceof Throwable throwable) { // Function returned error (panic) - throw new InvokerPanicException((Throwable) result); + throw new InvokerPanicException(throwable); } return result; } catch (ClassNotFoundException e) { @@ -512,7 +513,7 @@ private Function createInvokerCallback(Method method) { * @param diagnostic Diagnostic to show. * @return The string with position highlighted. */ - private String highlightedDiagnostic(Module module, io.ballerina.tools.diagnostics.Diagnostic diagnostic) { + private String highlightedDiagnostic(Module module, Diagnostic diagnostic) { Optional documentId = module.documentIds().stream().findFirst(); Document document = module.document(documentId.orElseThrow()); return StringUtils.highlightDiagnostic(document.textDocument(), diagnostic); diff --git a/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/invoker/classload/ClassLoadInvoker.java b/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/invoker/classload/ClassLoadInvoker.java index f211eacdca97..4617ea0bf74d 100644 --- a/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/invoker/classload/ClassLoadInvoker.java +++ b/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/invoker/classload/ClassLoadInvoker.java @@ -227,16 +227,14 @@ public PackageCompilation getCompilation(Collection newSnippets) throws // Others are processed later. for (Snippet newSnippet : newSnippets) { - if (newSnippet instanceof ImportDeclarationSnippet) { - processImport((ImportDeclarationSnippet) newSnippet); + if (newSnippet instanceof ImportDeclarationSnippet importSnippet) { + processImport(importSnippet); - } else if (newSnippet instanceof VariableDeclarationSnippet) { - VariableDeclarationSnippet varDclnSnippet = (VariableDeclarationSnippet) newSnippet; + } else if (newSnippet instanceof VariableDeclarationSnippet varDclnSnippet) { variableNames.addAll(varDclnSnippet.names()); variableDeclarations.put(varDclnSnippet, varDclnSnippet.names()); - } else if (newSnippet instanceof ModuleMemberDeclarationSnippet) { - ModuleMemberDeclarationSnippet moduleDclnSnippet = (ModuleMemberDeclarationSnippet) newSnippet; + } else if (newSnippet instanceof ModuleMemberDeclarationSnippet moduleDclnSnippet) { Identifier moduleDeclarationName = moduleDclnSnippet.name(); moduleDeclarations.put(moduleDeclarationName, moduleDclnSnippet); availableModuleDeclarations.put(moduleDeclarationName, moduleDclnSnippet); @@ -244,8 +242,8 @@ public PackageCompilation getCompilation(Collection newSnippets) throws .map(Identifier::new).collect(Collectors.toSet()); newImports.put(moduleDeclarationName, usedPrefixes); - } else if (newSnippet instanceof ExecutableSnippet) { - executableSnippets.add((ExecutableSnippet) newSnippet); + } else if (newSnippet instanceof ExecutableSnippet executableSnippet) { + executableSnippets.add(executableSnippet); } else { throw new UnsupportedOperationException("Unimplemented snippet category."); @@ -560,7 +558,7 @@ private Collection globalVariableSymbols(Project project, return compilation.getSemanticModel(moduleId).moduleSymbols().stream() .filter(s -> s instanceof VariableSymbol || s instanceof FunctionSymbol) .map(GlobalVariableSymbol::fromSymbol) - .collect(Collectors.toList()); + .toList(); } /** diff --git a/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/invoker/classload/GlobalVariableSymbol.java b/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/invoker/classload/GlobalVariableSymbol.java index 6bd1b5d1f5af..74879ee30a78 100644 --- a/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/invoker/classload/GlobalVariableSymbol.java +++ b/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/invoker/classload/GlobalVariableSymbol.java @@ -42,10 +42,10 @@ public static GlobalVariableSymbol fromSymbol(Symbol symbol) { if (symbol.getName().isEmpty()) { throw new UnsupportedOperationException("Cannot create a global symbol without name"); } - if (symbol instanceof VariableSymbol) { - return new GlobalVariableSymbol(symbol.getName().get(), ((VariableSymbol) symbol).typeDescriptor()); - } else if (symbol instanceof FunctionSymbol) { - return new GlobalVariableSymbol(symbol.getName().get(), ((FunctionSymbol) symbol).typeDescriptor()); + if (symbol instanceof VariableSymbol variableSymbol) { + return new GlobalVariableSymbol(symbol.getName().get(), variableSymbol.typeDescriptor()); + } else if (symbol instanceof FunctionSymbol functionSymbol) { + return new GlobalVariableSymbol(symbol.getName().get(), functionSymbol.typeDescriptor()); } throw new UnsupportedOperationException("Symbol type not supported for creating global variable."); } diff --git a/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/invoker/classload/ImportsManager.java b/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/invoker/classload/ImportsManager.java index 06ac3c76bc10..829c6d9c635a 100644 --- a/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/invoker/classload/ImportsManager.java +++ b/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/invoker/classload/ImportsManager.java @@ -42,7 +42,6 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Matcher; import java.util.regex.Pattern; -import java.util.stream.Collectors; /** * Imports that were stored to be able to search with the prefix. @@ -364,7 +363,7 @@ private static List getBallerinaKeywords() { } }) .filter(Objects::nonNull) - .collect(Collectors.toList()); + .toList(); } catch (ClassNotFoundException e) { return Collections.emptyList(); } diff --git a/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/parser/ParserConstants.java b/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/parser/ParserConstants.java index a56297d31a91..bf03bbc1b2fd 100644 --- a/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/parser/ParserConstants.java +++ b/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/parser/ParserConstants.java @@ -25,7 +25,7 @@ * * @since 2.0.0 */ -public class ParserConstants { +public final class ParserConstants { public static final String WRAPPER_PREFIX = "__shell_wrapper__"; diff --git a/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/parser/SerialTreeParser.java b/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/parser/SerialTreeParser.java index ce933d37e90a..9aed29690285 100644 --- a/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/parser/SerialTreeParser.java +++ b/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/parser/SerialTreeParser.java @@ -120,8 +120,8 @@ public Collection parseDeclarations(String source) throws TreeParserExcept * Whether the declaration is allowed to be parsed. */ private boolean isModuleDeclarationAllowed(ModuleMemberDeclarationNode declarationNode) { - if (declarationNode instanceof FunctionDefinitionNode) { - String functionName = ((FunctionDefinitionNode) declarationNode).functionName().text(); + if (declarationNode instanceof FunctionDefinitionNode functionDefinitionNode) { + String functionName = functionDefinitionNode.functionName().text(); if (ParserConstants.isFunctionNameRestricted(functionName)) { addWarnDiagnostic("Found '" + functionName + "' function in the declarations.\n" + "Discarded '" + functionName + "' function without loading."); diff --git a/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/parser/trials/ModuleMemberTrial.java b/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/parser/trials/ModuleMemberTrial.java index 6ce131e0bbe1..15f978e41e0c 100644 --- a/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/parser/trials/ModuleMemberTrial.java +++ b/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/parser/trials/ModuleMemberTrial.java @@ -62,12 +62,12 @@ public Collection parse(String source) throws ParserTrialFailedException { ModulePartNode node = tree.rootNode(); NodeList members = node.members(); Iterator importIterator = node.imports().iterator(); - Iterator memberIterator = members.iterator(); + Iterator memberIterator = members.iterator(); while (importIterator.hasNext()) { nodes.add(importIterator.next()); } while (memberIterator.hasNext()) { - ModuleMemberDeclarationNode dclnNode = (ModuleMemberDeclarationNode) memberIterator.next(); + ModuleMemberDeclarationNode dclnNode = memberIterator.next(); validateModuleDeclaration(dclnNode); nodes.add(dclnNode); } @@ -75,8 +75,8 @@ public Collection parse(String source) throws ParserTrialFailedException { } private void validateModuleDeclaration(ModuleMemberDeclarationNode declarationNode) { - if (declarationNode instanceof FunctionDefinitionNode) { - String functionName = ((FunctionDefinitionNode) declarationNode).functionName().text(); + if (declarationNode instanceof FunctionDefinitionNode functionDefinitionNode) { + String functionName = functionDefinitionNode.functionName().text(); if (ParserConstants.isFunctionNameRestricted(functionName)) { String message = "Function name " + "'" + functionName + "'" + " not allowed in Ballerina Shell.\n"; throw new InvalidMethodException(message); diff --git a/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/preprocessor/SeparatorPreprocessor.java b/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/preprocessor/SeparatorPreprocessor.java index ab4ee1236003..4532bf022efb 100644 --- a/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/preprocessor/SeparatorPreprocessor.java +++ b/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/preprocessor/SeparatorPreprocessor.java @@ -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 @@ -51,7 +52,7 @@ public Collection process(String input) throws PreprocessorException { List snippets = new ArrayList<>(); StringBuilder builder = new StringBuilder(); - Stack brackets = new Stack<>(); + Deque brackets = new ArrayDeque<>(); boolean isInBacktickLiteral = false; boolean isInQuoteLiteral = false; diff --git a/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/snippet/factory/BasicSnippetFactory.java b/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/snippet/factory/BasicSnippetFactory.java index 371d7b7b51e8..15377f6db441 100644 --- a/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/snippet/factory/BasicSnippetFactory.java +++ b/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/snippet/factory/BasicSnippetFactory.java @@ -126,8 +126,7 @@ public class BasicSnippetFactory extends SnippetFactory { @Override public ImportDeclarationSnippet createImportSnippet(Node node) { - if (node instanceof ImportDeclarationNode) { - ImportDeclarationNode importDeclarationNode = (ImportDeclarationNode) node; + if (node instanceof ImportDeclarationNode importDeclarationNode) { return new ImportDeclarationSnippet(importDeclarationNode); } return null; @@ -143,10 +142,9 @@ public List createVariableDeclarationSnippets(Node n return null; } - if (node instanceof ModuleVariableDeclarationNode) { - dclnNode = (ModuleVariableDeclarationNode) node; - } else if (node instanceof VariableDeclarationNode) { - VariableDeclarationNode varNode = (VariableDeclarationNode) node; + if (node instanceof ModuleVariableDeclarationNode moduleVariableDeclarationNode) { + dclnNode = moduleVariableDeclarationNode; + } else if (node instanceof VariableDeclarationNode varNode) { VariableDeclarationNode newNode = null; NodeList qualifiers = NodeFactory.createEmptyNodeList(); // Only final qualifier is transferred. @@ -230,14 +228,14 @@ public ModuleMemberDeclarationSnippet createModuleMemberDeclarationSnippet(Node return null; } - if (node instanceof ModuleMemberDeclarationNode) { + if (node instanceof ModuleMemberDeclarationNode moduleMemberDeclarationNode) { assert MODULE_MEM_DCLNS.containsKey(node.getClass()); SnippetSubKind subKind = MODULE_MEM_DCLNS.get(node.getClass()); if (subKind.hasError()) { addErrorDiagnostic(subKind.getError()); throw new SnippetException(); } else if (subKind.isValid()) { - return new ModuleMemberDeclarationSnippet(subKind, (ModuleMemberDeclarationNode) node); + return new ModuleMemberDeclarationSnippet(subKind, moduleMemberDeclarationNode); } } return null; @@ -264,8 +262,8 @@ public StatementSnippet createStatementSnippet(Node node) throws SnippetExceptio @Override public ExpressionSnippet createExpressionSnippet(Node node) { - if (node instanceof ExpressionNode) { - return new ExpressionSnippet((ExpressionNode) node); + if (node instanceof ExpressionNode expressionNode) { + return new ExpressionSnippet(expressionNode); } return null; } @@ -277,11 +275,11 @@ public ExpressionSnippet createExpressionSnippet(Node node) { * @return node contains isolated keyword or not. */ private boolean containsIsolated(Node node) { - if (node instanceof ModuleVariableDeclarationNode) { - NodeList nodeList = ((ModuleVariableDeclarationNode) node).qualifiers(); + if (node instanceof ModuleVariableDeclarationNode moduleVariableDeclarationNode) { + NodeList nodeList = moduleVariableDeclarationNode.qualifiers(); return nodeList.stream().anyMatch(token -> token.kind() == SyntaxKind.ISOLATED_KEYWORD); - } else if (node instanceof FunctionDefinitionNode) { - NodeList nodeList = ((FunctionDefinitionNode) node).qualifierList(); + } else if (node instanceof FunctionDefinitionNode functionDefinitionNode) { + NodeList nodeList = functionDefinitionNode.qualifierList(); return nodeList.stream().anyMatch(token -> token.kind() == SyntaxKind.ISOLATED_KEYWORD); } @@ -289,23 +287,21 @@ private boolean containsIsolated(Node node) { } private boolean isSupportedAction(SyntaxKind nodeKind) { - switch (nodeKind) { - case REMOTE_METHOD_CALL_ACTION: - case BRACED_ACTION: - case CHECK_ACTION: - case START_ACTION: - case TRAP_ACTION: - case FLUSH_ACTION: - case ASYNC_SEND_ACTION: - case SYNC_SEND_ACTION: - case RECEIVE_ACTION: - case WAIT_ACTION: - case QUERY_ACTION: - case COMMIT_ACTION: - case CLIENT_RESOURCE_ACCESS_ACTION: - return true; - default: - return false; - } + return switch (nodeKind) { + case REMOTE_METHOD_CALL_ACTION, + BRACED_ACTION, + CHECK_ACTION, + START_ACTION, + TRAP_ACTION, + FLUSH_ACTION, + ASYNC_SEND_ACTION, + SYNC_SEND_ACTION, + RECEIVE_ACTION, + WAIT_ACTION, + QUERY_ACTION, + COMMIT_ACTION, + CLIENT_RESOURCE_ACCESS_ACTION -> true; + default -> false; + }; } } diff --git a/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/snippet/types/AbstractSnippet.java b/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/snippet/types/AbstractSnippet.java index 2f21c57fb11a..6ffbea9880d3 100644 --- a/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/snippet/types/AbstractSnippet.java +++ b/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/snippet/types/AbstractSnippet.java @@ -30,7 +30,7 @@ import java.util.Set; /** - * An abstract implementation of {@link io.ballerina.shell.snippet.Snippet}. + * An abstract implementation of {@link Snippet}. * * @param Type of the child root node * @since 2.0.0 diff --git a/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/snippet/types/ImportDeclarationSnippet.java b/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/snippet/types/ImportDeclarationSnippet.java index 988669c1784c..ec58593d5d2a 100644 --- a/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/snippet/types/ImportDeclarationSnippet.java +++ b/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/snippet/types/ImportDeclarationSnippet.java @@ -25,7 +25,6 @@ import io.ballerina.shell.utils.QuotedImport; import java.util.List; -import java.util.stream.Collectors; /** * Snippet that represent a import statement. @@ -59,7 +58,7 @@ public Identifier getPrefix() { */ public QuotedImport getImportedModule() { List moduleNames = rootNode.moduleName().stream().map(IdentifierToken::text) - .collect(Collectors.toList()); + .toList(); if (rootNode.orgName().isPresent()) { String orgName = rootNode.orgName().get().orgName().text(); return new QuotedImport(orgName, moduleNames); diff --git a/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/snippet/types/ModuleMemberDeclarationSnippet.java b/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/snippet/types/ModuleMemberDeclarationSnippet.java index 1e1eecff29b5..24f4e1aeb790 100644 --- a/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/snippet/types/ModuleMemberDeclarationSnippet.java +++ b/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/snippet/types/ModuleMemberDeclarationSnippet.java @@ -51,27 +51,26 @@ public ModuleMemberDeclarationSnippet(SnippetSubKind subKind, ModuleMemberDeclar * If the module declaration has no name, this will return null. */ public Identifier name() { - if (rootNode instanceof ClassDefinitionNode) { - String className = ((ClassDefinitionNode) rootNode).className().text(); + if (rootNode instanceof ClassDefinitionNode classDefinitionNode) { + String className = classDefinitionNode.className().text(); return new Identifier(className); - } else if (rootNode instanceof ConstantDeclarationNode) { - String constName = ((ConstantDeclarationNode) rootNode).variableName().text(); + } else if (rootNode instanceof ConstantDeclarationNode constantDeclarationNode) { + String constName = constantDeclarationNode.variableName().text(); return new Identifier(constName); - } else if (rootNode instanceof EnumDeclarationNode) { - String enumName = ((EnumDeclarationNode) rootNode).identifier().text(); + } else if (rootNode instanceof EnumDeclarationNode enumDeclarationNode) { + String enumName = enumDeclarationNode.identifier().text(); return new Identifier(enumName); - } else if (rootNode instanceof FunctionDefinitionNode) { - String funcName = ((FunctionDefinitionNode) rootNode).functionName().text(); + } else if (rootNode instanceof FunctionDefinitionNode functionDefinitionNode) { + String funcName = functionDefinitionNode.functionName().text(); return new Identifier(funcName); - } else if (rootNode instanceof ListenerDeclarationNode) { - String listenerName = ((ListenerDeclarationNode) rootNode).variableName().text(); + } else if (rootNode instanceof ListenerDeclarationNode listenerDeclarationNode) { + String listenerName = listenerDeclarationNode.variableName().text(); return new Identifier(listenerName); - } else if (rootNode instanceof ModuleXMLNamespaceDeclarationNode) { - ModuleXMLNamespaceDeclarationNode namespaceNode = (ModuleXMLNamespaceDeclarationNode) rootNode; + } else if (rootNode instanceof ModuleXMLNamespaceDeclarationNode namespaceNode) { return namespaceNode.namespacePrefix().map(Token::text).map(Identifier::new) .orElseGet(this::createAnonModuleName); - } else if (rootNode instanceof TypeDefinitionNode) { - String typeName = ((TypeDefinitionNode) rootNode).typeName().text(); + } else if (rootNode instanceof TypeDefinitionNode typeDefinitionNode) { + String typeName = typeDefinitionNode.typeName().text(); return new Identifier(typeName); } else { return createAnonModuleName(); diff --git a/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/utils/ModuleImporter.java b/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/utils/ModuleImporter.java index 7c95fdd39cce..e7184dc9e272 100644 --- a/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/utils/ModuleImporter.java +++ b/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/utils/ModuleImporter.java @@ -39,7 +39,6 @@ import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.stream.Collectors; /** * Support class to add required import statements. @@ -113,7 +112,7 @@ public List undefinedModules(Collection diagnostics) { } } - return moduleErrors.stream().distinct().collect(Collectors.toList()); + return moduleErrors.stream().distinct().toList(); } /** diff --git a/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/utils/QuotedImport.java b/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/utils/QuotedImport.java index 17a0585ba711..e4aeb69475bd 100644 --- a/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/utils/QuotedImport.java +++ b/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/utils/QuotedImport.java @@ -21,7 +21,6 @@ import java.util.List; import java.util.Objects; import java.util.StringJoiner; -import java.util.stream.Collectors; /** * An import that has quoted orgname and module names. @@ -36,7 +35,7 @@ public QuotedImport(String orgName, List moduleNames) { this.orgName = orgName; this.moduleNames = moduleNames.stream() .map(Identifier::new) - .collect(Collectors.toList()); + .toList(); } public QuotedImport(List moduleNames) { diff --git a/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/utils/StringUtils.java b/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/utils/StringUtils.java index f6799730d4d4..5cc82527c6a6 100644 --- a/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/utils/StringUtils.java +++ b/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/utils/StringUtils.java @@ -20,6 +20,7 @@ import io.ballerina.identifier.Utils; import io.ballerina.runtime.api.values.BError; +import io.ballerina.tools.diagnostics.Diagnostic; import io.ballerina.tools.text.LinePosition; import io.ballerina.tools.text.LineRange; import io.ballerina.tools.text.TextDocument; @@ -34,13 +35,17 @@ * * @since 2.0.0 */ -public class StringUtils { +public final class StringUtils { + private static final int MAX_VAR_STRING_LENGTH = 78; private static final String QUOTE = "'"; private static final String SPACE = " "; private static final String CARET = "^"; private static final String DASH = "-"; + private StringUtils() { + } + /** * Creates an quoted identifier to use for variable names. * @@ -85,8 +90,7 @@ public static String shortenedString(Object input) { * @param diagnostic Diagnostic to show. * @return The string with position highlighted. */ - public static String highlightDiagnostic(TextDocument textDocument, - io.ballerina.tools.diagnostics.Diagnostic diagnostic) { + public static String highlightDiagnostic(TextDocument textDocument, Diagnostic diagnostic) { LineRange lineRange = diagnostic.location().lineRange(); LinePosition startLine = lineRange.startLine(); LinePosition endLine = lineRange.endLine(); @@ -159,8 +163,8 @@ public static String getExpressionStringValue(Object object) { * @return Converted string. */ public static String getErrorStringValue(Throwable error) { - if (error instanceof BError) { - return ((BError) error).getErrorMessage() + " " + ((BError) error).getDetails(); + if (error instanceof BError bError) { + return bError.getErrorMessage() + " " + bError.getDetails(); } return error.getMessage(); } diff --git a/ballerina-shell/modules/shell-core/src/test/java/io/ballerina/shell/test/evaluator/base/TestInvoker.java b/ballerina-shell/modules/shell-core/src/test/java/io/ballerina/shell/test/evaluator/base/TestInvoker.java index 9de86a064d2d..86b23ef6ca5c 100644 --- a/ballerina-shell/modules/shell-core/src/test/java/io/ballerina/shell/test/evaluator/base/TestInvoker.java +++ b/ballerina-shell/modules/shell-core/src/test/java/io/ballerina/shell/test/evaluator/base/TestInvoker.java @@ -61,6 +61,7 @@ public String getStdOut() { return output.replace("\r\n", "\n"); } + @Override public void reset() { this.stdOutBaOs.reset(); } diff --git a/ballerina-shell/modules/shell-core/src/test/java/io/ballerina/shell/test/unit/EvaluatorMiscTest.java b/ballerina-shell/modules/shell-core/src/test/java/io/ballerina/shell/test/unit/EvaluatorMiscTest.java index 91356a2eae12..bded26f3afd6 100644 --- a/ballerina-shell/modules/shell-core/src/test/java/io/ballerina/shell/test/unit/EvaluatorMiscTest.java +++ b/ballerina-shell/modules/shell-core/src/test/java/io/ballerina/shell/test/unit/EvaluatorMiscTest.java @@ -31,7 +31,6 @@ import java.util.List; import java.util.Optional; import java.util.Set; -import java.util.stream.Collectors; /** * Misc functionality testing of evaluator. @@ -169,6 +168,6 @@ private List filterAvailableVariables(Evaluator evaluator) { return evaluator.availableVariables().stream().filter(s -> !s.equals("Variable declarations") && !s.equals("Final variable declarations") && !s.equals("Constant Variable Declarations")) - .collect(Collectors.toList()); + .toList(); } } diff --git a/ballerina-shell/modules/shell-rt/src/main/java/io/ballerina/shell/rt/InvokerMemory.java b/ballerina-shell/modules/shell-rt/src/main/java/io/ballerina/shell/rt/InvokerMemory.java index 82d5f4061812..676a57420a1d 100644 --- a/ballerina-shell/modules/shell-rt/src/main/java/io/ballerina/shell/rt/InvokerMemory.java +++ b/ballerina-shell/modules/shell-rt/src/main/java/io/ballerina/shell/rt/InvokerMemory.java @@ -28,10 +28,14 @@ * * @since 2.0.0 */ -public class InvokerMemory { +public final class InvokerMemory { + private static final String QUOTE = "'"; private static final HashMap> memory = new HashMap<>(); + private InvokerMemory() { + } + /** * Recalls the variable value. * This will return null if variable is not cached. diff --git a/bvm/ballerina-profiler/src/main/java/io/ballerina/runtime/profiler/Main.java b/bvm/ballerina-profiler/src/main/java/io/ballerina/runtime/profiler/Main.java index 54a66c4d805c..efbc0fbf4826 100644 --- a/bvm/ballerina-profiler/src/main/java/io/ballerina/runtime/profiler/Main.java +++ b/bvm/ballerina-profiler/src/main/java/io/ballerina/runtime/profiler/Main.java @@ -27,9 +27,13 @@ * * @since 2201.8.0 */ -public class Main { +public final class Main { + private static Profiler profiler; + private Main() { + } + public static void main(String[] args) throws ProfilerException { profiler = new Profiler(TimeUnit.MILLISECONDS.convert(System.nanoTime(), TimeUnit.NANOSECONDS)); profiler.start(args); diff --git a/bvm/ballerina-profiler/src/main/java/io/ballerina/runtime/profiler/Profiler.java b/bvm/ballerina-profiler/src/main/java/io/ballerina/runtime/profiler/Profiler.java index 38ce6b8dc788..d27a2cdf794f 100644 --- a/bvm/ballerina-profiler/src/main/java/io/ballerina/runtime/profiler/Profiler.java +++ b/bvm/ballerina-profiler/src/main/java/io/ballerina/runtime/profiler/Profiler.java @@ -41,7 +41,6 @@ import java.util.concurrent.TimeUnit; import java.util.jar.JarFile; import java.util.regex.Pattern; -import java.util.stream.Collectors; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; @@ -236,7 +235,7 @@ private void modifyJar() throws InterruptedException, IOException { final File userDirectory = new File(System.getProperty("user.dir")); // Get the user directory listAllFiles(userDirectory); // List all files in the user directory and its subdirectories // Get a list of the directories containing instrumented files - List changedDirectories = instrumentedFiles.stream().distinct().collect(Collectors.toList()); + List changedDirectories = instrumentedFiles.stream().distinct().toList(); loadDirectories(changedDirectories); } finally { for (String instrumentedFilePath : instrumentedPaths) { diff --git a/bvm/ballerina-profiler/src/main/java/io/ballerina/runtime/profiler/runtime/StackTraceMap.java b/bvm/ballerina-profiler/src/main/java/io/ballerina/runtime/profiler/runtime/StackTraceMap.java index e113cb20cf89..3160d9c7115b 100644 --- a/bvm/ballerina-profiler/src/main/java/io/ballerina/runtime/profiler/runtime/StackTraceMap.java +++ b/bvm/ballerina-profiler/src/main/java/io/ballerina/runtime/profiler/runtime/StackTraceMap.java @@ -28,7 +28,7 @@ * * @since 2201.8.0 */ -public class StackTraceMap { +public final class StackTraceMap { private static final AtomicInteger localVarIndex = new AtomicInteger(0); private static final ConcurrentHashMap stackTraceIndexMap = new ConcurrentHashMap<>(); diff --git a/bvm/ballerina-profiler/src/main/java/io/ballerina/runtime/profiler/ui/FileUtils.java b/bvm/ballerina-profiler/src/main/java/io/ballerina/runtime/profiler/ui/FileUtils.java index c7ebaa7f01da..542a5a0090d4 100644 --- a/bvm/ballerina-profiler/src/main/java/io/ballerina/runtime/profiler/ui/FileUtils.java +++ b/bvm/ballerina-profiler/src/main/java/io/ballerina/runtime/profiler/ui/FileUtils.java @@ -25,7 +25,7 @@ import java.nio.file.Path; import java.nio.file.Paths; -public class FileUtils { +public final class FileUtils { // Maximum wait time for the file to be created. This will wait 600*100 ms = 60 s. private static final int MAX_WAIT_TIME_FOR_FILE = 600; diff --git a/bvm/ballerina-profiler/src/main/java/io/ballerina/runtime/profiler/util/Constants.java b/bvm/ballerina-profiler/src/main/java/io/ballerina/runtime/profiler/util/Constants.java index ff30884b8ab1..af3f6811bc10 100644 --- a/bvm/ballerina-profiler/src/main/java/io/ballerina/runtime/profiler/util/Constants.java +++ b/bvm/ballerina-profiler/src/main/java/io/ballerina/runtime/profiler/util/Constants.java @@ -25,7 +25,8 @@ * * @since 2201.8.0 */ -public class Constants { +public final class Constants { + public static final String ANSI_RESET = "\u001B[0m"; public static final String ANSI_GRAY = "\033[37m"; public static final String ANSI_CYAN = "\033[1;38;2;32;182;176m"; diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/PredefinedTypes.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/PredefinedTypes.java index 2dc13a546404..3d0c7e49e7d5 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/PredefinedTypes.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/PredefinedTypes.java @@ -87,7 +87,7 @@ * * @since 2.0.0 */ -public class PredefinedTypes { +public final class PredefinedTypes { private static final Module EMPTY_MODULE = new Module(null, null, null); @@ -245,7 +245,7 @@ private static BAnydataType getAnydataType(List members, String typeName, ArrayList members = new ArrayList<>(); members.add(TYPE_XML); members.add(TYPE_READONLY); - var valueModule = new Module(BALLERINA_BUILTIN_PKG_PREFIX, VALUE_LANG_LIB, null); + Module valueModule = new Module(BALLERINA_BUILTIN_PKG_PREFIX, VALUE_LANG_LIB, null); BUnionType cloneable = new BUnionType(TypeConstants.CLONEABLE_TNAME, valueModule, members, false); cloneable.isCyclic = true; MapType internalCloneableMap = new BMapType(TypeConstants.MAP_TNAME, cloneable, valueModule); @@ -266,7 +266,7 @@ private static BAnydataType getAnydataType(List members, String typeName, members.add(TYPE_BOOLEAN); members.add(TYPE_STRING); members.add(TYPE_DECIMAL); - var valueModule = new Module(BALLERINA_BUILTIN_PKG_PREFIX, VALUE_LANG_LIB, null); + Module valueModule = new Module(BALLERINA_BUILTIN_PKG_PREFIX, VALUE_LANG_LIB, null); BUnionType jsonDecimal = new BUnionType(TypeConstants.JSON_DECIMAL_TNAME, valueModule, members, false); jsonDecimal.isCyclic = true; MapType internalJsonDecimalMap = new BMapType(TypeConstants.MAP_TNAME, jsonDecimal, valueModule); @@ -282,7 +282,7 @@ private static BAnydataType getAnydataType(List members, String typeName, members.add(TYPE_BOOLEAN); members.add(TYPE_STRING); members.add(TYPE_FLOAT); - var valueModule = new Module(BALLERINA_BUILTIN_PKG_PREFIX, VALUE_LANG_LIB, null); + Module valueModule = new Module(BALLERINA_BUILTIN_PKG_PREFIX, VALUE_LANG_LIB, null); BUnionType jsonFloat = new BUnionType(TypeConstants.JSON_FLOAT_TNAME, valueModule, members, false); jsonFloat.isCyclic = true; MapType internalJsonFloatMap = new BMapType(TypeConstants.MAP_TNAME, jsonFloat, valueModule); diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/Runtime.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/Runtime.java index 35f0117085f9..186331ad0e6d 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/Runtime.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/Runtime.java @@ -178,7 +178,7 @@ public abstract Object invokeMethodAsync(BObject object, String methodName, Stri public abstract void deregisterListener(BObject listener); - public abstract void registerStopHandler(BFunctionPointer stopHandler); + public abstract void registerStopHandler(BFunctionPointer stopHandler); /** * Invoke a Ballerina function pointer asynchronously. diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/TypeTags.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/TypeTags.java index 9f6b2cdbb192..94882acdee29 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/TypeTags.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/TypeTags.java @@ -22,7 +22,7 @@ * * @since 0.995.0 */ -public class TypeTags { +public final class TypeTags { public static final int INT_TAG = 1; public static final int BYTE_TAG = INT_TAG + 1; @@ -88,42 +88,35 @@ public class TypeTags { public static final int REG_EXP_TYPE_TAG = TYPE_REFERENCED_TYPE_TAG + 1; + private TypeTags() { + } + public static boolean isIntegerTypeTag(int tag) { // TODO : Fix byte type. Ideally, byte belongs to here. But we have modeled it differently. - switch (tag) { - case INT_TAG: - case SIGNED32_INT_TAG: - case SIGNED16_INT_TAG: - case SIGNED8_INT_TAG: - case UNSIGNED32_INT_TAG: - case UNSIGNED16_INT_TAG: - case UNSIGNED8_INT_TAG: - return true; - } - return false; + return switch (tag) { + case INT_TAG, + SIGNED32_INT_TAG, + SIGNED16_INT_TAG, + SIGNED8_INT_TAG, + UNSIGNED32_INT_TAG, + UNSIGNED16_INT_TAG, + UNSIGNED8_INT_TAG -> true; + default -> false; + }; } public static boolean isXMLTypeTag(int tag) { - - switch (tag) { - case XML_TAG: - case XML_ELEMENT_TAG: - case XML_COMMENT_TAG: - case XML_PI_TAG: - case XML_TEXT_TAG: - return true; - } - return false; + return switch (tag) { + case XML_TAG, XML_ELEMENT_TAG, XML_COMMENT_TAG, XML_PI_TAG, XML_TEXT_TAG -> true; + default -> false; + }; } public static boolean isStringTypeTag(int tag) { - - switch (tag) { - case STRING_TAG: - case CHAR_STRING_TAG: - return true; - } - return false; + return switch (tag) { + case STRING_TAG, CHAR_STRING_TAG -> true; + default -> false; + }; } } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/constants/RuntimeConstants.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/constants/RuntimeConstants.java index 50c81d633742..9dd918efebe1 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/constants/RuntimeConstants.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/constants/RuntimeConstants.java @@ -29,7 +29,7 @@ * * @since 0.90 */ -public class RuntimeConstants { +public final class RuntimeConstants { public static final String MAIN_FUNCTION_NAME = "main"; public static final String MODULE_INIT_CLASS_NAME = "$_init"; diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/constants/TypeConstants.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/constants/TypeConstants.java index 5433d38bfc6c..1ed999b25a15 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/constants/TypeConstants.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/constants/TypeConstants.java @@ -25,7 +25,7 @@ * * @since 0.995.0 */ -public class TypeConstants { +public final class TypeConstants { public static final String INT_TNAME = "int"; public static final String BYTE_TNAME = "byte"; diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/creators/ErrorCreator.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/creators/ErrorCreator.java index ff212255630b..386a27c17b7d 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/creators/ErrorCreator.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/creators/ErrorCreator.java @@ -38,10 +38,13 @@ * * @since 2.0.0 */ -public class ErrorCreator { +public final class ErrorCreator { private static final BString ERROR_MESSAGE_FIELD = StringUtils.fromString("message"); + private ErrorCreator() { + } + /** * Create an error with given reason. * @@ -79,7 +82,7 @@ public static BError createError(BString message, BString details) { } else { initialValues = new MappingInitialValueEntry[0]; } - MapValueImpl detailMap = new MapValueImpl(PredefinedTypes.TYPE_ERROR_DETAIL, initialValues); + MapValueImpl detailMap = new MapValueImpl<>(PredefinedTypes.TYPE_ERROR_DETAIL, initialValues); return createError(message, detailMap); } @@ -127,7 +130,7 @@ public static BError createError(Type type, BString message, BString details) { } else { initialValues = new MappingInitialValueEntry[0]; } - MapValueImpl detailMap = new MapValueImpl(PredefinedTypes.TYPE_ERROR_DETAIL, initialValues); + MapValueImpl detailMap = new MapValueImpl<>(PredefinedTypes.TYPE_ERROR_DETAIL, initialValues); return createError(type, message, null, detailMap); } @@ -138,8 +141,8 @@ public static BError createError(Type type, BString message, BString details) { * @return new error */ public static BError createError(Throwable error) { - if (error instanceof BError) { - return (BError) error; + if (error instanceof BError bError) { + return bError; } BError bError = createError(StringUtils.fromString(error.toString())); bError.setStackTrace(error.getStackTrace()); diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/creators/TypeCreator.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/creators/TypeCreator.java index fc3b277ee195..b041914300b6 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/creators/TypeCreator.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/creators/TypeCreator.java @@ -56,7 +56,7 @@ * * @since 2.0.0 */ -public class TypeCreator { +public final class TypeCreator { /** * Creates a new array type with given element type. diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/creators/ValueCreator.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/creators/ValueCreator.java index 15e81edb93c2..2ae086cf7621 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/creators/ValueCreator.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/creators/ValueCreator.java @@ -82,7 +82,7 @@ * * @since 1.1.0 */ -public class ValueCreator { +public final class ValueCreator { /** * Creates a new array with given array type. @@ -320,8 +320,8 @@ public static BDecimal createDecimalValue(String value, DecimalValueKind valueKi * @param type {@code FunctionType} of the function pointer * @return function pointer */ - public static BFunctionPointer createFPValue(Function function, FunctionType type) { - return new FPValue(function, type, null, false); + public static BFunctionPointer createFPValue(Function function, FunctionType type) { + return new FPValue<>(function, type, null, false); } /** @@ -332,8 +332,9 @@ public static BFunctionPointer createFPValue(Function function, FunctionType typ * @param strandName name for newly creating strand which is used to run the function pointer * @return function pointer */ - public static BFunctionPointer createFPValue(Function function, FunctionType type, String strandName) { - return new FPValue(function, type, strandName, false); + public static BFunctionPointer createFPValue(Function function, + FunctionType type, String strandName) { + return new FPValue<>(function, type, strandName, false); } // TODO: remove this with https://github.com/ballerina-platform/ballerina-lang/issues/40175 @@ -786,7 +787,7 @@ public static BMapInitialValueEntry createKeyFieldEntry(Object key, Object value * @param mappingValue mapping value * @return spread field entry */ - public static BMapInitialValueEntry createSpreadFieldEntry(BMap mappingValue) { + public static BMapInitialValueEntry createSpreadFieldEntry(BMap mappingValue) { return new MappingInitialValueEntry.SpreadFieldEntry(mappingValue); } @@ -957,8 +958,8 @@ public static BHandle createHandleValue(Object value) { * @param tableType table type * @return table value for given type */ - public static BTable createTableValue(TableType tableType) { - return new TableValueImpl(tableType); + public static BTable createTableValue(TableType tableType) { + return new TableValueImpl<>(tableType); } /** @@ -969,8 +970,8 @@ public static BTable createTableValue(TableType tableType) { * @param fieldNames table field names * @return table value for given type */ - public static BTable createTableValue(TableType tableType, BArray data, BArray fieldNames) { - return new TableValueImpl(tableType, (ArrayValue) data, (ArrayValue) fieldNames); + public static BTable createTableValue(TableType tableType, BArray data, BArray fieldNames) { + return new TableValueImpl<>(tableType, (ArrayValue) data, (ArrayValue) fieldNames); } private ValueCreator() { diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/flags/SymbolFlags.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/flags/SymbolFlags.java index 1f27d428c906..edf7cee02f93 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/flags/SymbolFlags.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/flags/SymbolFlags.java @@ -22,7 +22,7 @@ * * @since 0.95.7 */ -public class SymbolFlags { +public final class SymbolFlags { public static final long PUBLIC = 1; public static final long NATIVE = 2; @@ -42,6 +42,9 @@ public class SymbolFlags { public static final long ENUM = 8589934592L; public static final long ANY_FUNCTION = 549755813888L; + private SymbolFlags() { + } + public static boolean isFlagOn(long bitmask, long flag) { return (bitmask & flag) == flag; } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/flags/TypeFlags.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/flags/TypeFlags.java index a5902852f010..2b9822daf21d 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/flags/TypeFlags.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/flags/TypeFlags.java @@ -22,12 +22,15 @@ * * @since 1.1.0 */ -public class TypeFlags { +public final class TypeFlags { public static final int NILABLE = 1; public static final int ANYDATA = NILABLE << 1; public static final int PURETYPE = ANYDATA << 1; + private TypeFlags() { + } + public static boolean isFlagOn(int bitmask, int flag) { return (bitmask & flag) == flag; } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/types/Parameter.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/types/Parameter.java index a438db0b6057..3a93275de3cd 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/types/Parameter.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/types/Parameter.java @@ -42,11 +42,10 @@ public boolean equals(Object o) { return true; } - if (!(o instanceof Parameter)) { + if (!(o instanceof Parameter that)) { return false; } - Parameter that = (Parameter) o; return this.name.equals(that.name) && this.type.equals(that.type) && this.isDefault == that.isDefault; } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/utils/IdentifierUtils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/utils/IdentifierUtils.java index edbc873f7082..e5bdf708122f 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/utils/IdentifierUtils.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/utils/IdentifierUtils.java @@ -25,7 +25,7 @@ * * @since 2.0.0 */ -public class IdentifierUtils { +public final class IdentifierUtils { private IdentifierUtils() { } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/utils/JsonUtils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/utils/JsonUtils.java index 062c3332a8e4..e0f6b1d6ed55 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/utils/JsonUtils.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/utils/JsonUtils.java @@ -63,7 +63,10 @@ * * @since 2.0.0 */ -public class JsonUtils { +public final class JsonUtils { + + private JsonUtils() { + } /** * Parses the contents in the given {@link InputStream} and returns a json. @@ -152,7 +155,7 @@ public static Object parse(Reader reader, NonStringValueProcessingMode mode) thr * @param bTable {@link BTable} to be converted to JSON * @return JSON representation of the provided bTable */ - public static Object parse(BTable bTable) { + public static Object parse(BTable bTable) { return JsonInternalUtils.toJSON(bTable); } @@ -338,10 +341,10 @@ private static Object getJsonObject(Object value, List unresolved newValue = convertArrayToJson((BArray) value, unresolvedValues); break; case TypeTags.TABLE_TAG: - BTable bTable = (BTable) value; + BTable bTable = (BTable) value; Type constrainedType = TypeUtils.getImpliedType(((TableType) sourceType).getConstrainedType()); if (constrainedType.getTag() == TypeTags.MAP_TAG) { - newValue = convertMapConstrainedTableToJson((BTable) value, unresolvedValues); + newValue = convertMapConstrainedTableToJson((BTable) value, unresolvedValues); } else { try { newValue = JsonInternalUtils.toJSON(bTable); @@ -361,12 +364,12 @@ private static Object getJsonObject(Object value, List unresolved return newValue; } - private static Object convertMapConstrainedTableToJson(BTable value, List unresolvedValues) { + private static Object convertMapConstrainedTableToJson(BTable value, List unresolvedValues) { BArray membersArray = ValueCreator.createArrayValue(PredefinedTypes.TYPE_JSON_ARRAY); - BIterator itr = value.getIterator(); + BIterator itr = value.getIterator(); while (itr.hasNext()) { BArray tupleValue = (BArray) itr.next(); - BMap mapValue = ((BMap) tupleValue.get(0)); + BMap mapValue = ((BMap) tupleValue.get(0)); Object member = convertMapToJson(mapValue, unresolvedValues); membersArray.append(member); } @@ -376,7 +379,7 @@ private static Object convertMapConstrainedTableToJson(BTable value, List map, List unresolvedValues) { BMap newMap = ValueCreator.createMapValue(TypeCreator.createMapType(PredefinedTypes.TYPE_JSON)); - for (Map.Entry entry : map.entrySet()) { + for (Map.Entry entry : map.entrySet()) { Object newValue = convertToJsonType(entry.getValue(), unresolvedValues); newMap.put(StringUtils.fromString(entry.getKey().toString()), newValue); } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/utils/StringUtils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/utils/StringUtils.java index 09f701755ab1..44e6f75ab783 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/utils/StringUtils.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/utils/StringUtils.java @@ -57,7 +57,7 @@ * * @since 0.95.3 */ -public class StringUtils { +public final class StringUtils { /** * Convert input stream to String. @@ -237,20 +237,19 @@ public static String getJsonString(Object value) { Object jsonValue = JsonUtils.convertToJson(value); Type type = TypeUtils.getImpliedType(TypeChecker.getType(jsonValue)); - switch (type.getTag()) { - case TypeTags.NULL_TAG: - return "null"; - case TypeTags.STRING_TAG: - return stringToJson((BString) jsonValue); - case TypeTags.MAP_TAG: - MapValueImpl mapValue = (MapValueImpl) jsonValue; - return mapValue.getJSONString(); - case TypeTags.ARRAY_TAG: + return switch (type.getTag()) { + case TypeTags.NULL_TAG -> "null"; + case TypeTags.STRING_TAG -> stringToJson((BString) jsonValue); + case TypeTags.MAP_TAG -> { + MapValueImpl mapValue = (MapValueImpl) jsonValue; + yield mapValue.getJSONString(); + } + case TypeTags.ARRAY_TAG -> { ArrayValue arrayValue = (ArrayValue) jsonValue; - return arrayValue.getJSONString(); - default: - return String.valueOf(jsonValue); - } + yield arrayValue.getJSONString(); + } + default -> String.valueOf(jsonValue); + }; } private static String stringToJson(BString value) { diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/utils/TypeUtils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/utils/TypeUtils.java index 731b73b35e2d..71fc7f2c8a9d 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/utils/TypeUtils.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/utils/TypeUtils.java @@ -50,75 +50,54 @@ * * @since 2.0.0 */ -public class TypeUtils { +public final class TypeUtils { private TypeUtils() { } public static boolean isValueType(Type type) { Type referredType = TypeUtils.getImpliedType(type); - switch (referredType.getTag()) { - case TypeTags.INT_TAG: - case TypeTags.BYTE_TAG: - case TypeTags.FLOAT_TAG: - case TypeTags.DECIMAL_TAG: - case TypeTags.BOOLEAN_TAG: - case TypeTags.STRING_TAG: - return true; - case TypeTags.FINITE_TYPE_TAG: + return switch (referredType.getTag()) { + case TypeTags.INT_TAG, + TypeTags.BYTE_TAG, + TypeTags.FLOAT_TAG, + TypeTags.DECIMAL_TAG, + TypeTags.BOOLEAN_TAG, + TypeTags.STRING_TAG -> true; + case TypeTags.FINITE_TYPE_TAG -> { for (Object value : ((BFiniteType) referredType).valueSpace) { if (!isValueType(TypeChecker.getType(value))) { - return false; + yield false; } } - return true; - default: - return false; - - } + yield true; + } + default -> false; + }; } public static Type getTypeFromName(String typeName) { - switch (typeName) { - case TypeConstants.INT_TNAME: - return TYPE_INT; - case TypeConstants.BYTE_TNAME: - return TYPE_BYTE; - case TypeConstants.FLOAT_TNAME: - return TYPE_FLOAT; - case TypeConstants.DECIMAL_TNAME: - return TYPE_DECIMAL; - case TypeConstants.STRING_TNAME: - return TYPE_STRING; - case TypeConstants.BOOLEAN_TNAME: - return TYPE_BOOLEAN; - case TypeConstants.JSON_TNAME: - return TYPE_JSON; - case TypeConstants.XML_TNAME: - return TYPE_XML; - case TypeConstants.MAP_TNAME: - return TYPE_MAP; - case TypeConstants.FUTURE_TNAME: - return TYPE_FUTURE; - case TypeConstants.STREAM_TNAME: - return TYPE_STREAM; - case TypeConstants.ANY_TNAME: - return TYPE_ANY; - case TypeConstants.TYPEDESC_TNAME: - return TYPE_TYPEDESC; - case TypeConstants.NULL_TNAME: - return TYPE_NULL; - case TypeConstants.XML_ATTRIBUTES_TNAME: - return TYPE_XML_ATTRIBUTES; - case TypeConstants.ERROR: - return TYPE_ERROR; - case TypeConstants.ANYDATA_TNAME: - return TYPE_ANYDATA; - case TypeConstants.NEVER_TNAME: - return TYPE_NEVER; - default: - throw new IllegalStateException("Unknown type name"); - } + return switch (typeName) { + case TypeConstants.INT_TNAME -> TYPE_INT; + case TypeConstants.BYTE_TNAME -> TYPE_BYTE; + case TypeConstants.FLOAT_TNAME -> TYPE_FLOAT; + case TypeConstants.DECIMAL_TNAME -> TYPE_DECIMAL; + case TypeConstants.STRING_TNAME -> TYPE_STRING; + case TypeConstants.BOOLEAN_TNAME -> TYPE_BOOLEAN; + case TypeConstants.JSON_TNAME -> TYPE_JSON; + case TypeConstants.XML_TNAME -> TYPE_XML; + case TypeConstants.MAP_TNAME -> TYPE_MAP; + case TypeConstants.FUTURE_TNAME -> TYPE_FUTURE; + case TypeConstants.STREAM_TNAME -> TYPE_STREAM; + case TypeConstants.ANY_TNAME -> TYPE_ANY; + case TypeConstants.TYPEDESC_TNAME -> TYPE_TYPEDESC; + case TypeConstants.NULL_TNAME -> TYPE_NULL; + case TypeConstants.XML_ATTRIBUTES_TNAME -> TYPE_XML_ATTRIBUTES; + case TypeConstants.ERROR -> TYPE_ERROR; + case TypeConstants.ANYDATA_TNAME -> TYPE_ANYDATA; + case TypeConstants.NEVER_TNAME -> TYPE_NEVER; + default -> throw new IllegalStateException("Unknown type name"); + }; } public static Type fromString(String typeName) { diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/utils/ValueUtils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/utils/ValueUtils.java index 0728d1460d9b..b5c1cc3f2cd2 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/utils/ValueUtils.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/utils/ValueUtils.java @@ -31,7 +31,7 @@ * * @since 2201.5.0 */ -public class ValueUtils { +public final class ValueUtils { private ValueUtils() {} diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/utils/XmlUtils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/utils/XmlUtils.java index ea7731763dd4..3f65db5552a8 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/utils/XmlUtils.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/utils/XmlUtils.java @@ -34,7 +34,7 @@ * * @since 2.0.0 */ -public class XmlUtils { +public final class XmlUtils { private XmlUtils() {} @@ -95,8 +95,8 @@ public static BXml parse(Reader reader) { * @param table {@link BTable} to convert * @return converted {@link BXml} */ - public static BXml parse(BTable table) { - return XmlFactory.tableToXML((TableValueImpl) table); + public static BXml parse(BTable table) { + return XmlFactory.tableToXML((TableValueImpl) table); } /** diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/values/BFuture.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/values/BFuture.java index 4dd5a683febd..4997c9b9d61e 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/values/BFuture.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/values/BFuture.java @@ -1,75 +1,75 @@ - /* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - package io.ballerina.runtime.api.values; +/* + * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package io.ballerina.runtime.api.values; - import io.ballerina.runtime.api.async.Callback; - import io.ballerina.runtime.internal.scheduling.Strand; +import io.ballerina.runtime.api.async.Callback; +import io.ballerina.runtime.internal.scheduling.Strand; - /** - *

- * Represent a Ballerina future in Java. - *

- * - * @since 1.1.0 - */ - public interface BFuture extends BValue { +/** + *

+ * Represent a Ballerina future in Java. + *

+ * + * @since 1.1.0 + */ +public interface BFuture extends BValue { - /** - * Abort execution of the Ballerina strand that the future is attached. - * The abortion occurs only after the next yield point. - */ - void cancel(); + /** + * Abort execution of the Ballerina strand that the future is attached. + * The abortion occurs only after the next yield point. + */ + void cancel(); - // TODO: remove this with https://github.com/ballerina-platform/ballerina-lang/issues/40175 - /** - * Returns the strand that the future is attached to. - * - * @return strand - * @deprecated - */ - @Deprecated(since = "2201.6.0", forRemoval = true) - Strand getStrand(); + // TODO: remove this with https://github.com/ballerina-platform/ballerina-lang/issues/40175 + /** + * Returns the strand that the future is attached to. + * + * @return strand + * @deprecated + */ + @Deprecated(since = "2201.6.0", forRemoval = true) + Strand getStrand(); - /** - * Returns the result value of the future. - * - * @return result value - */ - Object getResult(); + /** + * Returns the result value of the future. + * + * @return result value + */ + Object getResult(); - /** - * Returns completion status of the Ballerina strand that the future is attached. - * - * @return true if future is completed - */ - boolean isDone(); + /** + * Returns completion status of the Ballerina strand that the future is attached. + * + * @return true if future is completed + */ + boolean isDone(); - /** - * Returns {@code Throwable} if the attached strand panic. - * - * @return panic error or null if not panic occurred - */ - Throwable getPanic(); + /** + * Returns {@code Throwable} if the attached strand panic. + * + * @return panic error or null if not panic occurred + */ + Throwable getPanic(); - /** - * Returns {@link Callback} listening on the completion of this future. - * - * @return registered {@link Callback} - */ - Callback getCallback(); - } + /** + * Returns {@link Callback} listening on the completion of this future. + * + * @return registered {@link Callback} + */ + Callback getCallback(); +} diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/values/BMap.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/values/BMap.java index ee4039010776..1eb65cc3fab8 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/values/BMap.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/values/BMap.java @@ -190,7 +190,7 @@ public interface BMap extends BRefValue, BCollection { long getDefaultableIntValue(BString key); - Object merge(BMap v2, boolean checkMergeability); + Object merge(BMap v2, boolean checkMergeability); void populateInitialValue(K key, V value); } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/values/BObject.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/values/BObject.java index 6ccfc34dc041..09720948fe33 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/values/BObject.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/values/BObject.java @@ -66,6 +66,7 @@ default Type getOriginalType() { boolean getBooleanValue(BString fieldName); + @SuppressWarnings("rawtypes") BMap getMapValue(BString fieldName); BObject getObjectValue(BString fieldName); diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/values/BString.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/values/BString.java index 4450cda817ca..b7308732d7bc 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/values/BString.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/api/values/BString.java @@ -38,6 +38,6 @@ public interface BString { BString substring(int beginIndex, int endIndex); - BIterator getIterator(); + BIterator getIterator(); } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/AnnotationUtils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/AnnotationUtils.java index d80da4349667..78e81eb271b1 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/AnnotationUtils.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/AnnotationUtils.java @@ -39,7 +39,10 @@ * * @since 0.995.0 */ -public class AnnotationUtils { +public final class AnnotationUtils { + + private AnnotationUtils() { + } /** * Method to retrieve annotations of the type from the global annotation map and set it to the type. @@ -47,13 +50,11 @@ public class AnnotationUtils { * @param globalAnnotMap The global annotation map * @param bType The type for which annotations need to be set */ - public static void processAnnotations(MapValue globalAnnotMap, Type bType) { - if (!(bType instanceof BAnnotatableType)) { + public static void processAnnotations(MapValue globalAnnotMap, Type bType) { + if (!(bType instanceof BAnnotatableType type)) { return; } - BAnnotatableType type = (BAnnotatableType) bType; - BString annotationKey = StringUtils.fromString(type.getAnnotationKey()); if (globalAnnotMap.containsKey(annotationKey)) { type.setAnnotations((MapValue) globalAnnotMap.get(annotationKey)); @@ -93,33 +94,34 @@ private static void setMethodAnnotations(MapValue globalAnnotMa } } - public static void processObjectCtorAnnotations(BObjectType bType, MapValue globalAnnotMap, Strand strand) { + public static void processObjectCtorAnnotations(BObjectType bType, + MapValue globalAnnotMap, Strand strand) { BString annotationKey = StringUtils.fromString(bType.getAnnotationKey()); if (globalAnnotMap.containsKey(annotationKey)) { Object annot = globalAnnotMap.get(annotationKey); // If annotations are already set via desugard service-decl, skip. - Object annotValue = ((FPValue) annot).call(new Object[]{strand}); + Object annotValue = ((FPValue) annot).call(new Object[]{strand}); bType.setAnnotations((MapValue) annotValue); } for (MethodType attachedFunction : bType.getMethods()) { processObjectMethodLambdaAnnotation(globalAnnotMap, strand, attachedFunction); } - if (bType instanceof BServiceType) { - var serviceType = (BServiceType) bType; - for (var resourceFunction : serviceType.getResourceMethods()) { + if (bType instanceof BServiceType serviceType) { + for (ResourceMethodType resourceFunction : serviceType.getResourceMethods()) { processObjectMethodLambdaAnnotation(globalAnnotMap, strand, resourceFunction); } } } - private static void processObjectMethodLambdaAnnotation(MapValue globalAnnotMap, Strand strand, + private static void processObjectMethodLambdaAnnotation(MapValue globalAnnotMap, Strand strand, MethodType attachedFunction) { BString annotationKey = StringUtils.fromString(attachedFunction.getAnnotationKey()); if (globalAnnotMap.containsKey(annotationKey)) { ((BMethodType) attachedFunction) - .setAnnotations((MapValue) ((FPValue) globalAnnotMap.get(annotationKey)) + .setAnnotations( + (MapValue) ((FPValue) globalAnnotMap.get(annotationKey)) .call(new Object[]{strand})); } } @@ -131,7 +133,8 @@ private static void processObjectMethodLambdaAnnotation(MapValue globalAnnotMap, * @param globalAnnotMap The global annotation map * @param name The function name that acts as the annotation key */ - public static void processFPValueAnnotations(FPValue fpValue, MapValue globalAnnotMap, String name) { + public static void processFPValueAnnotations(FPValue fpValue, + MapValue globalAnnotMap, String name) { BAnnotatableType type = (BAnnotatableType) fpValue.getType(); BString nameKey = StringUtils.fromString(name); if (globalAnnotMap.containsKey(nameKey)) { @@ -145,7 +148,7 @@ public static void processFPValueAnnotations(FPValue fpValue, MapValue globalAnn * @param fpValue function pointer to be invoked * @return true if should run concurrently */ - public static boolean isConcurrent(FPValue fpValue) { + public static boolean isConcurrent(FPValue fpValue) { return fpValue.isConcurrent; } @@ -156,7 +159,7 @@ public static boolean isConcurrent(FPValue fpValue) { * @param defaultName default strand name * @return annotated strand name */ - public static String getStrandName(FPValue fpValue, String defaultName) { + public static String getStrandName(FPValue fpValue, String defaultName) { if (fpValue.strandName != null) { return fpValue.strandName; } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/BalRuntime.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/BalRuntime.java index 03dd7fa0e3ee..e721fbc45b07 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/BalRuntime.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/BalRuntime.java @@ -175,7 +175,7 @@ public BFuture invokeMethodAsyncSequentially(BObject object, String methodName, AsyncUtils.getArgsWithDefaultValues(scheduler, objectVal, methodName, new Callback() { @Override public void notifySuccess(Object result) { - Function func = getFunction((Object[]) result, objectVal, methodName); + Function func = getFunction((Object[]) result, objectVal, methodName); scheduler.scheduleToObjectGroup(new Object[1], func, future); } @@ -224,7 +224,7 @@ public BFuture invokeMethodAsyncConcurrently(BObject object, String methodName, AsyncUtils.getArgsWithDefaultValues(scheduler, objectVal, methodName, new Callback() { @Override public void notifySuccess(Object result) { - Function func = getFunction((Object[]) result, objectVal, methodName); + Function func = getFunction((Object[]) result, objectVal, methodName); scheduler.schedule(new Object[1], func, future); } @@ -281,7 +281,7 @@ public BFuture invokeMethodAsync(BObject object, String methodName, String stran AsyncUtils.getArgsWithDefaultValues(scheduler, objectVal, methodName, new Callback() { @Override public void notifySuccess(Object result) { - Function func = getFunction((Object[]) result, objectVal, methodName); + Function func = getFunction((Object[]) result, objectVal, methodName); if (isIsolated) { scheduler.schedule(new Object[1], func, future); } else { @@ -349,16 +349,17 @@ public void deregisterListener(BObject listener) { } @Override - public void registerStopHandler(BFunctionPointer stopHandler) { + public void registerStopHandler(BFunctionPointer stopHandler) { scheduler.getRuntimeRegistry().registerStopHandler(stopHandler); } - private Function getFunction(Object[] argsWithDefaultValues, ObjectValue objectVal, String methodName) { - Function func; + private Function getFunction(Object[] argsWithDefaultValues, + ObjectValue objectVal, String methodName) { + Function func; if (argsWithDefaultValues.length == 1) { - func = o -> objectVal.call((Strand) (((Object[]) o)[0]), methodName, argsWithDefaultValues[0]); + func = o -> objectVal.call((Strand) ((o)[0]), methodName, argsWithDefaultValues[0]); } else { - func = o -> objectVal.call((Strand) (((Object[]) o)[0]), methodName, argsWithDefaultValues); + func = o -> objectVal.call((Strand) ((o)[0]), methodName, argsWithDefaultValues); } return func; } @@ -414,7 +415,7 @@ private void invokeMethod(String functionName, Callback callback, Type returnTyp Object... args) { ValueCreator valueCreator = ValueCreator.getValueCreator(ValueCreator.getLookupKey(module.getOrg(), module.getName(), module.getMajorVersion(), module.isTestPkg())); - Function func = o -> valueCreator.call((Strand) (((Object[]) o)[0]), functionName, args); + Function func = o -> valueCreator.call((Strand) (o[0]), functionName, args); FutureValue future = scheduler.createFuture(null, callback, null, returnType, strandName, null); Object[] argsWithStrand = new Object[args.length + 1]; argsWithStrand[0] = future.strand; diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/BalStringUtils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/BalStringUtils.java index 0639d4dfd512..fb6d5c4540c6 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/BalStringUtils.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/BalStringUtils.java @@ -50,7 +50,8 @@ * * @since 2.0.0 */ -public class BalStringUtils { +public final class BalStringUtils { + private static boolean hasCycles = false; private BalStringUtils() {} @@ -146,14 +147,13 @@ public static Object parseArrayExpressionStringValue(String exprValue, BLink par */ public static Object parseMapExpressionStringValue(String exprValue, BLink parent) { List list = getElements(exprValue); - MapValueImpl eleMap = new MapValueImpl(new BMapType(TYPE_ANYDATA)); + MapValueImpl eleMap = new MapValueImpl<>(new BMapType(TYPE_ANYDATA)); if (list.isEmpty()) { return eleMap; } CycleUtils.Node node = new CycleUtils.Node(eleMap, parent); Set typeSet = new HashSet<>(); - for (int i = 0; i < list.size(); i++) { - String e = list.get(i); + for (String e : list) { int colonIndex = e.indexOf(':'); int quotesCount = 0; for (int j = 0; j < e.length(); j++) { @@ -176,12 +176,12 @@ public static Object parseMapExpressionStringValue(String exprValue, BLink paren } if (typeSet.size() > 1) { BUnionType type = new BUnionType(new ArrayList<>(typeSet)); - MapValueImpl result = new MapValueImpl(new BMapType(type)); + MapValueImpl result = new MapValueImpl<>(new BMapType(type)); result.putAll(eleMap); return result; } else { Type type = typeSet.iterator().next(); - MapValueImpl result = new MapValueImpl(new BMapType(type)); + MapValueImpl result = new MapValueImpl<>(new BMapType(type)); result.putAll(eleMap); return result; } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/CloneUtils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/CloneUtils.java index 9f2fa277ffe2..3a41e8eefb85 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/CloneUtils.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/CloneUtils.java @@ -35,7 +35,7 @@ * * @since 1.0.0 */ -public class CloneUtils { +public final class CloneUtils { static final String NEWLINE_WITH_TABS = "\n\t\t"; static final String TWO_SPACES = " "; @@ -54,11 +54,10 @@ public static Object cloneValue(Object value) { return null; } - if (!(value instanceof BRefValue)) { + if (!(value instanceof BRefValue refValue)) { return value; } - BRefValue refValue = (BRefValue) value; return refValue.copy(new HashMap<>()); } @@ -74,11 +73,10 @@ public static Object cloneReadOnly(Object value) { return null; } - if (!(value instanceof BRefValue)) { + if (!(value instanceof BRefValue refValue)) { return value; } - BRefValue refValue = (BRefValue) value; return refValue.frozenCopy(new HashMap<>()); } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/ErrorUtils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/ErrorUtils.java index 613af41f7dc7..447cd9772637 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/ErrorUtils.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/ErrorUtils.java @@ -42,7 +42,7 @@ * @since 2.0.0 */ -public class ErrorUtils { +public final class ErrorUtils { private static final BString ERROR_MESSAGE_FIELD = StringUtils.fromString("message"); private static final BString ERROR_CAUSE_FIELD = StringUtils.fromString("cause"); @@ -78,14 +78,14 @@ public static ErrorValue createInteropError(Throwable e) { } else { initialValues = new MappingInitialValueEntry[0]; } - BMap detailMap = new MapValueImpl(PredefinedTypes.TYPE_ERROR_DETAIL, initialValues); + BMap detailMap = new MapValueImpl<>(PredefinedTypes.TYPE_ERROR_DETAIL, initialValues); return (ErrorValue) createError(StringUtils.fromString(e.getClass().getName()), detailMap); } public static Object handleResourceError(Object returnValue) { - if (returnValue instanceof BError) { - throw (BError) returnValue; + if (returnValue instanceof BError error) { + throw error; } return returnValue; } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/FloatUtils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/FloatUtils.java index 2f3229eed662..ac1af0ccb240 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/FloatUtils.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/FloatUtils.java @@ -26,7 +26,10 @@ * * @since 2201.1.0 */ -public class FloatUtils { +public final class FloatUtils { + + private FloatUtils() { + } public static BString getBStringIfInfiniteOrNaN(double x) { if (Double.isInfinite(x) || Double.isNaN(x)) { diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/IteratorUtils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/IteratorUtils.java index bbf468df8f32..867b0a355c9d 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/IteratorUtils.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/IteratorUtils.java @@ -34,7 +34,10 @@ * * @since 1.2.0 */ -public class IteratorUtils { +public final class IteratorUtils { + + private IteratorUtils() { + } /** * Returns the pure type and anydata type flags if they are available, otherwise 0. This is only used to check if diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/JsonGenerator.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/JsonGenerator.java index b602c2595f5d..19b2f59af74d 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/JsonGenerator.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/JsonGenerator.java @@ -288,8 +288,8 @@ public void serialize(Object json) throws IOException { switch (TypeUtils.getImpliedType(TypeChecker.getType(json)).getTag()) { case TypeTags.ARRAY_TAG: - if (json instanceof StreamingJsonValue) { - ((StreamingJsonValue) json).serialize(this); + if (json instanceof StreamingJsonValue streamingJsonValue) { + streamingJsonValue.serialize(this); break; } this.writeStartArray(); diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/JsonInternalUtils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/JsonInternalUtils.java index 8487c7254435..b2970e598c45 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/JsonInternalUtils.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/JsonInternalUtils.java @@ -71,7 +71,7 @@ * @since 0.995.0 */ @SuppressWarnings("unchecked") -public class JsonInternalUtils { +public final class JsonInternalUtils { public static final String OBJECT = "object"; public static final String ARRAY = "array"; @@ -225,10 +225,10 @@ public static void setElement(Object json, String elementName, Object element) { * @return returns true if provided JSON is a JSON Array. */ public static boolean isJSONArray(Object json) { - if (!(json instanceof BRefValue)) { + if (!(json instanceof BRefValue refValue)) { return false; } - return TypeUtils.getImpliedType(((BRefValue) json).getType()).getTag() == TypeTags.ARRAY_TAG; + return TypeUtils.getImpliedType(refValue.getType()).getTag() == TypeTags.ARRAY_TAG; } /** @@ -238,11 +238,11 @@ public static boolean isJSONArray(Object json) { * @return returns true if provided JSON is a JSON Object. */ public static boolean isJSONObject(Object json) { - if (!(json instanceof BRefValue)) { + if (!(json instanceof BRefValue refValue)) { return false; } - Type type = TypeUtils.getImpliedType(((BRefValue) json).getType()); + Type type = TypeUtils.getImpliedType(refValue.getType()); int typeTag = type.getTag(); return typeTag == TypeTags.MAP_TAG || typeTag == TypeTags.RECORD_TYPE_TAG; } @@ -392,24 +392,20 @@ public static Object convertUnionTypeToJSON(Object source, JsonType targetType) } Type type = TypeUtils.getImpliedType(TypeChecker.getType(source)); - switch (type.getTag()) { - case TypeTags.INT_TAG: - case TypeTags.FLOAT_TAG: - case TypeTags.DECIMAL_TAG: - case TypeTags.STRING_TAG: - case TypeTags.BOOLEAN_TAG: - case TypeTags.JSON_TAG: - return source; - case TypeTags.NULL_TAG: - return null; - case TypeTags.MAP_TAG: - case TypeTags.OBJECT_TYPE_TAG: - case TypeTags.RECORD_TYPE_TAG: - return convertMapToJSON((MapValueImpl) source, targetType); - default: - throw ErrorHelper.getRuntimeException(ErrorCodes.INCOMPATIBLE_TYPE, - PredefinedTypes.TYPE_JSON, type); - } + return switch (type.getTag()) { + case TypeTags.INT_TAG, + TypeTags.FLOAT_TAG, + TypeTags.DECIMAL_TAG, + TypeTags.STRING_TAG, + TypeTags.BOOLEAN_TAG, + TypeTags.JSON_TAG -> source; + case TypeTags.NULL_TAG -> null; + case TypeTags.MAP_TAG, + TypeTags.OBJECT_TYPE_TAG, + TypeTags.RECORD_TYPE_TAG -> convertMapToJSON((MapValueImpl) source, targetType); + default -> throw ErrorHelper.getRuntimeException(ErrorCodes.INCOMPATIBLE_TYPE, + PredefinedTypes.TYPE_JSON, type); + }; } /** @@ -467,7 +463,7 @@ public static BError getErrorIfUnmergeable(Object j1, Object j2, List detailMap = new MapValueImpl(PredefinedTypes.TYPE_ERROR_DETAIL, + MapValueImpl detailMap = new MapValueImpl<>(PredefinedTypes.TYPE_ERROR_DETAIL, initialValues); return ErrorCreator.createError(ErrorReasons.MERGE_JSON_ERROR, detailMap); } @@ -507,13 +503,12 @@ public static Object mergeJson(Object j1, Object j2, boolean checkMergeability) * of the JSON array. Otherwise the method will throw a {@link BError}. */ public static ArrayValue convertJSONToBArray(Object json, BArrayType targetArrayType) { - if (!(json instanceof ArrayValue)) { + if (!(json instanceof ArrayValue jsonArray)) { throw ErrorHelper.getRuntimeException(ErrorCodes.INCOMPATIBLE_TYPE, getComplexObjectTypeName(ARRAY), getTypeName(json)); } Type targetElementType = TypeUtils.getImpliedType(targetArrayType.getElementType()); - ArrayValue jsonArray = (ArrayValue) json; switch (targetElementType.getTag()) { case TypeTags.INT_TAG: return jsonArrayToBIntArray(jsonArray); @@ -546,7 +541,7 @@ public static ArrayValue convertJSONToBArray(Object json, BArrayType targetArray * @param table {@link BTable} to be converted * @return JSON representation of the provided table */ - public static Object toJSON(BTable table) { + public static Object toJSON(BTable table) { TableJsonDataSource jsonDataSource = new TableJsonDataSource(table); return jsonDataSource.build(); } @@ -567,12 +562,12 @@ public static BError createJsonConversionError(Throwable throwable, String prefi * @return BInteger value of the JSON, if its a integer or a long JSON node. Error, otherwise. */ private static long jsonNodeToInt(Object json) { - if (!(json instanceof Long)) { + if (!(json instanceof Long l)) { throw ErrorHelper.getRuntimeException(ErrorCodes.INCOMPATIBLE_TYPE_FOR_CASTING_JSON, PredefinedTypes.TYPE_INT, getTypeName(json)); } - return (Long) json; + return l; } /** @@ -582,12 +577,12 @@ private static long jsonNodeToInt(Object json) { * @return BFloat value of the JSON, if its a double or a float JSON node. Error, otherwise. */ private static double jsonNodeToFloat(Object json) { - if (json instanceof Integer) { - return ((Integer) json).longValue(); - } else if (json instanceof Double) { - return (Double) json; - } else if (json instanceof DecimalValue) { - return ((DecimalValue) json).floatValue(); + if (json instanceof Integer i) { + return i.longValue(); + } else if (json instanceof Double d) { + return d; + } else if (json instanceof DecimalValue decimalValue) { + return decimalValue.floatValue(); } else { throw ErrorHelper.getRuntimeException(ErrorCodes.INCOMPATIBLE_TYPE_FOR_CASTING_JSON, PredefinedTypes.TYPE_FLOAT, getTypeName(json)); @@ -602,14 +597,14 @@ private static double jsonNodeToFloat(Object json) { */ private static DecimalValue jsonNodeToDecimal(Object json) { BigDecimal decimal; - if (json instanceof Integer) { - decimal = new BigDecimal(((Integer) json).longValue()); - } else if (json instanceof Double) { - decimal = BigDecimal.valueOf((Double) json); - } else if (json instanceof BigDecimal) { - decimal = (BigDecimal) json; - } else if (json instanceof DecimalValue) { - return (DecimalValue) json; + if (json instanceof Integer i) { + decimal = new BigDecimal(i.longValue()); + } else if (json instanceof Double d) { + decimal = BigDecimal.valueOf(d); + } else if (json instanceof BigDecimal bigDecimal) { + decimal = bigDecimal; + } else if (json instanceof DecimalValue decimalValue) { + return decimalValue; } else { throw ErrorHelper.getRuntimeException(ErrorCodes.INCOMPATIBLE_TYPE_FOR_CASTING_JSON, PredefinedTypes.TYPE_DECIMAL, getTypeName(json)); @@ -625,11 +620,11 @@ private static DecimalValue jsonNodeToDecimal(Object json) { * @return Boolean value of the JSON, if its a boolean node. Error, otherwise. */ private static boolean jsonNodeToBoolean(Object json) { - if (!(json instanceof Boolean)) { + if (!(json instanceof Boolean b)) { throw ErrorHelper.getRuntimeException(ErrorCodes.INCOMPATIBLE_TYPE_FOR_CASTING_JSON, PredefinedTypes.TYPE_BOOLEAN, getTypeName(json)); } - return (Boolean) json; + return b; } private static ArrayValue jsonArrayToBIntArray(ArrayValue arrayNode) { @@ -832,11 +827,10 @@ public ObjectPair(Object lhsObject, Object rhsObject) { @Override public boolean equals(Object obj) { - if (!(obj instanceof ObjectPair)) { + if (!(obj instanceof ObjectPair other)) { return false; } - ObjectPair other = (ObjectPair) obj; return this.lhsObject == other.lhsObject && this.rhsObject == other.rhsObject; } } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/JsonParser.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/JsonParser.java index 8e5e60956672..86accb0d6c14 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/JsonParser.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/JsonParser.java @@ -86,7 +86,7 @@ * * @since 2201.9.0 */ -public class JsonParser { +public final class JsonParser { private static final ThreadLocal tlStateMachine = ThreadLocal.withInitial(JsonStateMachine::new); diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/Lists.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/Lists.java index 4d8221643933..2a545f6b5739 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/Lists.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/Lists.java @@ -29,28 +29,24 @@ * * @since 0.995.0 */ -public class Lists { +public final class Lists { + + private Lists() { + } public static Object get(ArrayValue array, long index) { if (array.getType().getTag() != TypeTags.ARRAY_TAG) { return array.getRefValue(index); } - switch (TypeUtils.getImpliedType(((BArrayType) array.getType()).getElementType()).getTag()) { - case TypeTags.BOOLEAN_TAG: - return Boolean.valueOf(array.getBoolean(index)); - case TypeTags.BYTE_TAG: - return new Long(array.getByte(index)); - case TypeTags.FLOAT_TAG: - return new Double(array.getFloat(index)); - case TypeTags.DECIMAL_TAG: - return array.getRefValue(index); - case TypeTags.INT_TAG: - return new Long((int) array.getInt(index)); - case TypeTags.STRING_TAG: - return new String(array.getString(index)); - default: - return array.getRefValue(index); - } + return switch (TypeUtils.getImpliedType(((BArrayType) array.getType()).getElementType()).getTag()) { + case TypeTags.BOOLEAN_TAG -> array.getBoolean(index); + case TypeTags.BYTE_TAG -> (long) array.getByte(index); + case TypeTags.FLOAT_TAG -> array.getFloat(index); + case TypeTags.DECIMAL_TAG -> array.getRefValue(index); + case TypeTags.INT_TAG -> array.getInt(index); + case TypeTags.STRING_TAG -> array.getString(index); + default -> array.getRefValue(index); + }; } } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/MapUtils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/MapUtils.java index 730910c05232..2b062de290e8 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/MapUtils.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/MapUtils.java @@ -46,7 +46,10 @@ * * @since 0.995.0 */ -public class MapUtils { +public final class MapUtils { + + private MapUtils() { + } public static void handleMapStore(MapValue mapValue, BString fieldName, Object value) { updateMapValue(TypeUtils.getImpliedType(mapValue.getType()), mapValue, fieldName, value); @@ -66,8 +69,9 @@ public static void handleInherentTypeViolatingMapUpdate(Object value, BMapType m expType, valuesType)); } - public static boolean handleInherentTypeViolatingRecordUpdate(MapValue mapValue, BString fieldName, Object value, - BRecordType recType, boolean initialValue) { + public static boolean handleInherentTypeViolatingRecordUpdate( + MapValue mapValue, BString fieldName, Object value, + BRecordType recType, boolean initialValue) { Field recField = recType.getFields().get(fieldName.getValue()); Type recFieldType; diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/MathUtils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/MathUtils.java index ca33da211432..8908919cd75d 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/MathUtils.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/MathUtils.java @@ -27,10 +27,13 @@ * * @since 1.0 */ -public class MathUtils { +public final class MathUtils { private static final BString DIVIDE_BY_ZERO_ERROR = StringUtils.fromString(" / by zero"); + private MathUtils() { + } + public static long divide(long numerator, long denominator) { try { if (numerator == Long.MIN_VALUE && denominator == -1) { diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/TableJsonDataSource.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/TableJsonDataSource.java index 87c8a9e4965b..2d4580a13dd7 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/TableJsonDataSource.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/TableJsonDataSource.java @@ -47,14 +47,14 @@ */ public class TableJsonDataSource implements JsonDataSource { - private BTable tableValue; + private BTable tableValue; private JSONObjectGenerator objGen; - public TableJsonDataSource(BTable tableValue) { + public TableJsonDataSource(BTable tableValue) { this(tableValue, new DefaultJSONObjectGenerator()); } - private TableJsonDataSource(BTable tableValue, JSONObjectGenerator objGen) { + private TableJsonDataSource(BTable tableValue, JSONObjectGenerator objGen) { this.tableValue = tableValue; this.objGen = objGen; } @@ -81,11 +81,11 @@ public Object next() { @Override public Object build() { ArrayValue values = new ArrayValueImpl(new BArrayType(PredefinedTypes.TYPE_JSON)); - BIterator itr = this.tableValue.getIterator(); + BIterator itr = this.tableValue.getIterator(); while (itr.hasNext()) { TupleValueImpl tupleValue = (TupleValueImpl) itr.next(); //Retrieve table value from key-value tuple - BMap record = ((BMap) tupleValue.get(1)); + BMap record = ((BMap) tupleValue.get(1)); try { values.append(this.objGen.transform(record)); } catch (IOException e) { @@ -104,7 +104,7 @@ private static class DefaultJSONObjectGenerator implements JSONObjectGenerator { @Override public Object transform(BMap record) { MapValue objNode = new MapValueImpl<>(new BMapType(PredefinedTypes.TYPE_JSON)); - for (Map.Entry entry : record.entrySet()) { + for (Map.Entry entry : record.entrySet()) { Type type = TypeChecker.getType(entry.getValue()); BString keyName = StringUtils.fromString(entry.getKey().toString()); constructJsonData(record, objNode, keyName, type); @@ -152,7 +152,7 @@ private static void constructJsonData(BMap record, MapValue jsonData = new MapValueImpl<>(new BMapType(PredefinedTypes.TYPE_JSON)); - for (Map.Entry entry : record.getMapValue(key).entrySet()) { + for (Map.Entry entry : record.getMapValue(key).entrySet()) { Type internalType = TypeChecker.getType(entry.getValue()); BString internalKeyName = StringUtils.fromString(entry.getKey().toString()); constructJsonData(record.getMapValue(key), jsonData, internalKeyName, internalType); diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/TableOmDataSource.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/TableOmDataSource.java index 0dce761f0d0b..090bec991ec0 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/TableOmDataSource.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/TableOmDataSource.java @@ -51,11 +51,11 @@ public class TableOmDataSource extends AbstractPushOMDataSource { private static final String DEFAULT_ROOT_WRAPPER = "results"; private static final String DEFAULT_ROW_WRAPPER = "result"; - private TableValueImpl table; + private TableValueImpl table; private String rootWrapper; private String rowWrapper; - public TableOmDataSource(TableValueImpl table, String rootWrapper, String rowWrapper) { + public TableOmDataSource(TableValueImpl table, String rootWrapper, String rowWrapper) { this.table = table; this.rootWrapper = rootWrapper != null ? rootWrapper : DEFAULT_ROOT_WRAPPER; this.rowWrapper = rowWrapper != null ? rowWrapper : DEFAULT_ROW_WRAPPER; @@ -64,13 +64,13 @@ public TableOmDataSource(TableValueImpl table, String rootWrapper, String rowWra @Override public void serialize(XMLStreamWriter xmlStreamWriter) throws XMLStreamException { xmlStreamWriter.writeStartElement("", this.rootWrapper, ""); - IteratorValue itr = this.table.getIterator(); + IteratorValue itr = this.table.getIterator(); while (itr.hasNext()) { table.getIterator().next(); xmlStreamWriter.writeStartElement("", this.rowWrapper, ""); TupleValueImpl tupleValue = (TupleValueImpl) itr.next(); - MapValueImpl record = ((MapValueImpl) tupleValue.get(0)); + MapValueImpl record = ((MapValueImpl) tupleValue.get(0)); BStructureType structType = (BStructureType) record.getType(); BField[] structFields = null; @@ -90,7 +90,8 @@ public void serialize(XMLStreamWriter xmlStreamWriter) throws XMLStreamException xmlStreamWriter.flush(); } - private void writeElement(MapValueImpl record, XMLStreamWriter xmlStreamWriter, String name, int type, int index, + private void writeElement(MapValueImpl record, + XMLStreamWriter xmlStreamWriter, String name, int type, int index, BField[] structFields) throws XMLStreamException { boolean isArray = false; xmlStreamWriter.writeStartElement("", name, ""); @@ -125,7 +126,7 @@ private void writeElement(MapValueImpl record, XMLStreamWriter xmlStreamWriter, BArray structData = record.getArrayValue(key); processArray(xmlStreamWriter, structData); } else { - BMap structData = record.getMapValue(key); + BMap structData = record.getMapValue(key); processStruct(xmlStreamWriter, structData, structFields, index); } break; @@ -154,7 +155,7 @@ private void processArray(XMLStreamWriter xmlStreamWriter, BArray array) throws } } - private void processStruct(XMLStreamWriter xmlStreamWriter, BMap structData, + private void processStruct(XMLStreamWriter xmlStreamWriter, BMap structData, BField[] structFields, int index) throws XMLStreamException { boolean structError = true; Type internalType = TypeUtils.getImpliedType(structFields[index].getFieldType()); @@ -167,8 +168,8 @@ private void processStruct(XMLStreamWriter xmlStreamWriter, BMap structData, BString internalKeyName = StringUtils.fromString(internalStructFields[i].getFieldName()); Object val = structData.get(internalKeyName); xmlStreamWriter.writeStartElement("", internalStructFields[i].getFieldName(), ""); - if (val instanceof MapValueImpl) { - processStruct(xmlStreamWriter, (MapValueImpl) val, internalStructFields, i); + if (val instanceof MapValueImpl mapValue) { + processStruct(xmlStreamWriter, mapValue, internalStructFields, i); } else { xmlStreamWriter.writeCharacters(val.toString()); } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/TableUtils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/TableUtils.java index a2f762774b6b..cd4bade3c1c5 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/TableUtils.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/TableUtils.java @@ -41,7 +41,10 @@ * @since 1.3.0 */ -public class TableUtils { +public final class TableUtils { + + private TableUtils() { + } /** * Generates a hash value which is same for the same shape. @@ -57,7 +60,7 @@ public static Long hash(Object obj, Node parent) { return 0L; } - if (obj instanceof BRefValue) { + if (obj instanceof BRefValue refValue) { Node node = new Node(obj, parent); @@ -66,19 +69,18 @@ public static Long hash(Object obj, Node parent) { .getErrorDetails(ErrorCodes.CYCLIC_VALUE_REFERENCE, TypeChecker.getType(obj))); } - BRefValue refValue = (BRefValue) obj; Type refType = TypeUtils.getImpliedType(refValue.getType()); if (refType.getTag() == TypeTags.MAP_TAG || refType.getTag() == TypeTags.RECORD_TYPE_TAG) { - MapValue mapValue = (MapValue) refValue; - for (Object entry : mapValue.entrySet()) { - result = 31 * result + hash(((Map.Entry) entry).getKey(), node) + - (((Map.Entry) entry).getValue() == null ? 0 : hash(((Map.Entry) entry).getValue(), + MapValue mapValue = (MapValue) refValue; + for (Map.Entry entry : mapValue.entrySet()) { + result = 31 * result + hash(entry.getKey(), node) + + (entry.getValue() == null ? 0 : hash(entry.getValue(), node)); } return result; } else if (refType.getTag() == TypeTags.ARRAY_TAG || refType.getTag() == TypeTags.TUPLE_TAG) { ArrayValue arrayValue = (ArrayValue) refValue; - IteratorValue arrayIterator = arrayValue.getIterator(); + IteratorValue arrayIterator = arrayValue.getIterator(); while (arrayIterator.hasNext()) { result = 31 * result + hash(arrayIterator.next(), node); } @@ -89,8 +91,8 @@ public static Long hash(Object obj, Node parent) { refType.getTag() == TypeTags.XMLNS_TAG) { return (long) refValue.toString().hashCode(); } else if (refType.getTag() == TypeTags.TABLE_TAG) { - TableValue tableValue = (TableValue) refValue; - IteratorValue tableIterator = tableValue.getIterator(); + TableValue tableValue = (TableValue) refValue; + IteratorValue tableIterator = tableValue.getIterator(); while (tableIterator.hasNext()) { result = 31 * result + hash(tableIterator.next(), node); } @@ -100,8 +102,8 @@ public static Long hash(Object obj, Node parent) { } else { return (long) obj.hashCode(); } - } else if (obj instanceof Long) { - return (long) obj; + } else if (obj instanceof Long l) { + return l; } else { return (long) obj.hashCode(); } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/TypeChecker.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/TypeChecker.java index b4090f2592ea..908c590b9fe5 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/TypeChecker.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/TypeChecker.java @@ -137,7 +137,7 @@ * @since 0.995.0 */ @SuppressWarnings({"rawtypes"}) -public class TypeChecker { +public final class TypeChecker { private static final byte MAX_TYPECAST_ERROR_COUNT = 20; private static final String REG_EXP_TYPENAME = "RegExp"; @@ -360,8 +360,8 @@ public static Type getType(Object value) { return TYPE_STRING; } else if (value instanceof Boolean) { return TYPE_BOOLEAN; - } else if (value instanceof BObject) { - return ((BObject) value).getOriginalType(); + } else if (value instanceof BObject bObject) { + return bObject.getOriginalType(); } return ((BValue) value).getType(); @@ -435,60 +435,66 @@ public static boolean isReferenceEqual(Object lhsValue, Object rhsValue) { Type lhsType = getImpliedType(getType(lhsValue)); Type rhsType = getImpliedType(getType(rhsValue)); - switch (lhsType.getTag()) { - case TypeTags.FLOAT_TAG: + return switch (lhsType.getTag()) { + case TypeTags.FLOAT_TAG -> { if (rhsType.getTag() != TypeTags.FLOAT_TAG) { - return false; + yield false; } - return lhsValue.equals(((Number) rhsValue).doubleValue()); - case TypeTags.DECIMAL_TAG: + yield lhsValue.equals(((Number) rhsValue).doubleValue()); + } + case TypeTags.DECIMAL_TAG -> { if (rhsType.getTag() != TypeTags.DECIMAL_TAG) { - return false; - } - return checkDecimalExactEqual((DecimalValue) lhsValue, (DecimalValue) rhsValue); - case TypeTags.INT_TAG: - case TypeTags.BYTE_TAG: - case TypeTags.BOOLEAN_TAG: - case TypeTags.STRING_TAG: - return isEqual(lhsValue, rhsValue); - case TypeTags.XML_TAG: - case TypeTags.XML_COMMENT_TAG: - case TypeTags.XML_ELEMENT_TAG: - case TypeTags.XML_PI_TAG: - case TypeTags.XML_TEXT_TAG: + yield false; + } + yield checkDecimalExactEqual((DecimalValue) lhsValue, (DecimalValue) rhsValue); + } + case TypeTags.INT_TAG, + TypeTags.BYTE_TAG, + TypeTags.BOOLEAN_TAG, + TypeTags.STRING_TAG -> isEqual(lhsValue, rhsValue); + case TypeTags.XML_TAG, + TypeTags.XML_COMMENT_TAG, + TypeTags.XML_ELEMENT_TAG, + TypeTags.XML_PI_TAG, + TypeTags.XML_TEXT_TAG -> { if (!TypeTags.isXMLTypeTag(rhsType.getTag())) { - return false; + yield false; } - return isXMLValueRefEqual((XmlValue) lhsValue, (XmlValue) rhsValue); - case TypeTags.HANDLE_TAG: + yield isXMLValueRefEqual((XmlValue) lhsValue, (XmlValue) rhsValue); + } + case TypeTags.HANDLE_TAG -> { if (rhsType.getTag() != TypeTags.HANDLE_TAG) { - return false; + yield false; } - return isHandleValueRefEqual(lhsValue, rhsValue); - case TypeTags.FUNCTION_POINTER_TAG: - return lhsType.getPackage().equals(rhsType.getPackage()) && - lhsType.getName().equals(rhsType.getName()) && rhsType.equals(lhsType); - default: - if (lhsValue instanceof RegExpValue && rhsValue instanceof RegExpValue) { - return ((RegExpValue) lhsValue).equals(rhsValue, new HashSet<>()); + yield isHandleValueRefEqual(lhsValue, rhsValue); + } + case TypeTags.FUNCTION_POINTER_TAG -> lhsType.getPackage().equals(rhsType.getPackage()) && + lhsType.getName().equals(rhsType.getName()) && rhsType.equals(lhsType); + default -> { + if (lhsValue instanceof RegExpValue lhsRegExpValue && rhsValue instanceof RegExpValue) { + yield lhsRegExpValue.equals(rhsValue, new HashSet<>()); } - return false; - } + yield false; + } + }; } private static boolean isXMLValueRefEqual(XmlValue lhsValue, XmlValue rhsValue) { - if (lhsValue.getNodeType() == XmlNodeType.SEQUENCE && lhsValue.isSingleton()) { + boolean isLhsXmlSequence = lhsValue.getNodeType() == XmlNodeType.SEQUENCE; + boolean isRhsXmlSequence = rhsValue.getNodeType() == XmlNodeType.SEQUENCE; + + if (isLhsXmlSequence && isRhsXmlSequence) { + return isXMLSequenceRefEqual((XmlSequence) lhsValue, (XmlSequence) rhsValue); + } + if (isLhsXmlSequence && lhsValue.isSingleton()) { return ((XmlSequence) lhsValue).getChildrenList().get(0) == rhsValue; } - if (rhsValue.getNodeType() == XmlNodeType.SEQUENCE && rhsValue.isSingleton()) { + if (isRhsXmlSequence && rhsValue.isSingleton()) { return ((XmlSequence) rhsValue).getChildrenList().get(0) == lhsValue; } if (lhsValue.getNodeType() != rhsValue.getNodeType()) { return false; } - if (lhsValue.getNodeType() == XmlNodeType.SEQUENCE && rhsValue.getNodeType() == XmlNodeType.SEQUENCE) { - return isXMLSequenceRefEqual((XmlSequence) lhsValue, (XmlSequence) rhsValue); - } if (lhsValue.getNodeType() == XmlNodeType.TEXT && rhsValue.getNodeType() == XmlNodeType.TEXT) { return isEqual(lhsValue, rhsValue); } @@ -525,8 +531,8 @@ public static TypedescValue getTypedesc(Object value) { if (isSimpleBasicType(type)) { return new TypedescValueImpl(new BFiniteType(value.toString(), Set.of(value), 0)); } - if (value instanceof BRefValue) { - return (TypedescValue) ((BRefValue) value).getTypedesc(); + if (value instanceof BRefValue bRefValue) { + return (TypedescValue) bRefValue.getTypedesc(); } return new TypedescValueImpl(type); } @@ -540,10 +546,10 @@ public static TypedescValue getTypedesc(Object value) { */ public static Object getAnnotValue(TypedescValue typedescValue, BString annotTag) { Type describingType = typedescValue.getDescribingType(); - if (!(describingType instanceof BAnnotatableType)) { + if (!(describingType instanceof BAnnotatableType annotatableType)) { return null; } - return ((BAnnotatableType) describingType).getAnnotation(annotTag); + return annotatableType.getAnnotation(annotTag); } /** @@ -606,62 +612,53 @@ public static boolean checkIsType(Type sourceType, Type targetType, List sourceTypeTag == targetTypeTag; + case TypeTags.STRING_TAG -> TypeTags.isStringTypeTag(sourceTypeTag); + case TypeTags.XML_TEXT_TAG -> { if (sourceTypeTag == TypeTags.XML_TAG) { - return ((BXmlType) sourceType).constraint.getTag() == TypeTags.NEVER_TAG; - } - return sourceTypeTag == targetTypeTag; - case TypeTags.INT_TAG: - return sourceTypeTag == TypeTags.INT_TAG || sourceTypeTag == TypeTags.BYTE_TAG || - (sourceTypeTag >= TypeTags.SIGNED8_INT_TAG && sourceTypeTag <= TypeTags.UNSIGNED32_INT_TAG); - case TypeTags.SIGNED16_INT_TAG: - return sourceTypeTag == TypeTags.BYTE_TAG || - (sourceTypeTag >= TypeTags.SIGNED8_INT_TAG && sourceTypeTag <= TypeTags.SIGNED16_INT_TAG); - case TypeTags.SIGNED32_INT_TAG: - return sourceTypeTag == TypeTags.BYTE_TAG || - (sourceTypeTag >= TypeTags.SIGNED8_INT_TAG && sourceTypeTag <= TypeTags.SIGNED32_INT_TAG); - case TypeTags.UNSIGNED8_INT_TAG: - return sourceTypeTag == TypeTags.BYTE_TAG || sourceTypeTag == TypeTags.UNSIGNED8_INT_TAG; - case TypeTags.UNSIGNED16_INT_TAG: - return sourceTypeTag == TypeTags.BYTE_TAG || sourceTypeTag == TypeTags.UNSIGNED8_INT_TAG || - sourceTypeTag == TypeTags.UNSIGNED16_INT_TAG; - case TypeTags.UNSIGNED32_INT_TAG: - return sourceTypeTag == TypeTags.BYTE_TAG || sourceTypeTag == TypeTags.UNSIGNED8_INT_TAG || - sourceTypeTag == TypeTags.UNSIGNED16_INT_TAG || sourceTypeTag == TypeTags.UNSIGNED32_INT_TAG; - case TypeTags.ANY_TAG: - return checkIsAnyType(sourceType); - case TypeTags.ANYDATA_TAG: - return sourceType.isAnydata(); - case TypeTags.SERVICE_TAG: - return checkIsServiceType(sourceType, targetType, - unresolvedTypes == null ? new ArrayList<>() : unresolvedTypes); - case TypeTags.HANDLE_TAG: - return sourceTypeTag == TypeTags.HANDLE_TAG; - case TypeTags.READONLY_TAG: - return checkIsType(sourceType, PredefinedTypes.ANY_AND_READONLY_OR_ERROR_TYPE, unresolvedTypes); - case TypeTags.XML_ELEMENT_TAG: - case TypeTags.XML_COMMENT_TAG: - case TypeTags.XML_PI_TAG: - return targetTypeTag == sourceTypeTag; - case TypeTags.INTERSECTION_TAG: - return checkIsType(sourceType, ((BIntersectionType) targetType).getEffectiveType(), unresolvedTypes); - case TypeTags.TYPE_REFERENCED_TYPE_TAG: - return checkIsType(sourceType, ((BTypeReferenceType) targetType).getReferredType(), unresolvedTypes); - default: - return checkIsRecursiveType(sourceType, targetType, - unresolvedTypes == null ? new ArrayList<>() : unresolvedTypes); - } + yield ((BXmlType) sourceType).constraint.getTag() == TypeTags.NEVER_TAG; + } + yield sourceTypeTag == targetTypeTag; + } + case TypeTags.INT_TAG -> sourceTypeTag == TypeTags.INT_TAG || sourceTypeTag == TypeTags.BYTE_TAG || + (sourceTypeTag >= TypeTags.SIGNED8_INT_TAG && sourceTypeTag <= TypeTags.UNSIGNED32_INT_TAG); + case TypeTags.SIGNED16_INT_TAG -> sourceTypeTag == TypeTags.BYTE_TAG || + (sourceTypeTag >= TypeTags.SIGNED8_INT_TAG && sourceTypeTag <= TypeTags.SIGNED16_INT_TAG); + case TypeTags.SIGNED32_INT_TAG -> sourceTypeTag == TypeTags.BYTE_TAG || + (sourceTypeTag >= TypeTags.SIGNED8_INT_TAG && sourceTypeTag <= TypeTags.SIGNED32_INT_TAG); + case TypeTags.UNSIGNED8_INT_TAG -> + sourceTypeTag == TypeTags.BYTE_TAG || sourceTypeTag == TypeTags.UNSIGNED8_INT_TAG; + case TypeTags.UNSIGNED16_INT_TAG -> + sourceTypeTag == TypeTags.BYTE_TAG || sourceTypeTag == TypeTags.UNSIGNED8_INT_TAG || + sourceTypeTag == TypeTags.UNSIGNED16_INT_TAG; + case TypeTags.UNSIGNED32_INT_TAG -> + sourceTypeTag == TypeTags.BYTE_TAG || sourceTypeTag == TypeTags.UNSIGNED8_INT_TAG || + sourceTypeTag == TypeTags.UNSIGNED16_INT_TAG || + sourceTypeTag == TypeTags.UNSIGNED32_INT_TAG; + case TypeTags.ANY_TAG -> checkIsAnyType(sourceType); + case TypeTags.ANYDATA_TAG -> sourceType.isAnydata(); + case TypeTags.SERVICE_TAG -> checkIsServiceType(sourceType, targetType, + unresolvedTypes == null ? new ArrayList<>() : unresolvedTypes); + case TypeTags.HANDLE_TAG -> sourceTypeTag == TypeTags.HANDLE_TAG; + case TypeTags.READONLY_TAG -> + checkIsType(sourceType, PredefinedTypes.ANY_AND_READONLY_OR_ERROR_TYPE, unresolvedTypes); + case TypeTags.XML_ELEMENT_TAG, + TypeTags.XML_COMMENT_TAG, + TypeTags.XML_PI_TAG -> targetTypeTag == sourceTypeTag; + case TypeTags.INTERSECTION_TAG -> + checkIsType(sourceType, ((BIntersectionType) targetType).getEffectiveType(), unresolvedTypes); + case TypeTags.TYPE_REFERENCED_TYPE_TAG -> + checkIsType(sourceType, ((BTypeReferenceType) targetType).getReferredType(), unresolvedTypes); + default -> checkIsRecursiveType(sourceType, targetType, + unresolvedTypes == null ? new ArrayList<>() : unresolvedTypes); + }; } private static boolean checkIsType(Object sourceVal, Type sourceType, Type targetType, @@ -698,15 +695,12 @@ private static boolean checkIsType(Object sourceVal, Type sourceType, Type targe return false; } - switch (targetTypeTag) { - case TypeTags.ANY_TAG: - return checkIsAnyType(sourceType); - case TypeTags.READONLY_TAG: - return isInherentlyImmutableType(sourceType) || sourceType.isReadOnly(); - default: - return checkIsRecursiveTypeOnValue(sourceVal, sourceType, targetType, sourceTypeTag, targetTypeTag, - unresolvedTypes == null ? new ArrayList<>() : unresolvedTypes); - } + return switch (targetTypeTag) { + case TypeTags.ANY_TAG -> checkIsAnyType(sourceType); + case TypeTags.READONLY_TAG -> isInherentlyImmutableType(sourceType) || sourceType.isReadOnly(); + default -> checkIsRecursiveTypeOnValue(sourceVal, sourceType, targetType, sourceTypeTag, targetTypeTag, + unresolvedTypes == null ? new ArrayList<>() : unresolvedTypes); + }; } // Private methods @@ -722,72 +716,56 @@ private static boolean checkTypeDescType(Type sourceType, BTypedescType targetTy } private static boolean checkIsRecursiveType(Type sourceType, Type targetType, List unresolvedTypes) { - switch (targetType.getTag()) { - case TypeTags.MAP_TAG: - return checkIsMapType(sourceType, (BMapType) targetType, unresolvedTypes); - case TypeTags.STREAM_TAG: - return checkIsStreamType(sourceType, (BStreamType) targetType, unresolvedTypes); - case TypeTags.TABLE_TAG: - return checkIsTableType(sourceType, (BTableType) targetType, unresolvedTypes); - case TypeTags.JSON_TAG: - return checkIsJSONType(sourceType, unresolvedTypes); - case TypeTags.RECORD_TYPE_TAG: - return checkIsRecordType(sourceType, (BRecordType) targetType, unresolvedTypes); - case TypeTags.FUNCTION_POINTER_TAG: - return checkIsFunctionType(sourceType, (BFunctionType) targetType); - case TypeTags.ARRAY_TAG: - return checkIsArrayType(sourceType, (BArrayType) targetType, unresolvedTypes); - case TypeTags.TUPLE_TAG: - return checkIsTupleType(sourceType, (BTupleType) targetType, unresolvedTypes); - case TypeTags.UNION_TAG: - return checkIsUnionType(sourceType, (BUnionType) targetType, unresolvedTypes); - case TypeTags.OBJECT_TYPE_TAG: - return checkObjectEquivalency(sourceType, (BObjectType) targetType, unresolvedTypes); - case TypeTags.FINITE_TYPE_TAG: - return checkIsFiniteType(sourceType, (BFiniteType) targetType); - case TypeTags.FUTURE_TAG: - return checkIsFutureType(sourceType, (BFutureType) targetType, unresolvedTypes); - case TypeTags.ERROR_TAG: - return checkIsErrorType(sourceType, (BErrorType) targetType, unresolvedTypes); - case TypeTags.TYPEDESC_TAG: - return checkTypeDescType(sourceType, (BTypedescType) targetType, unresolvedTypes); - case TypeTags.XML_TAG: - return checkIsXMLType(sourceType, targetType, unresolvedTypes); - default: - // other non-recursive types shouldn't reach here - return false; - } + return switch (targetType.getTag()) { + case TypeTags.MAP_TAG -> checkIsMapType(sourceType, (BMapType) targetType, unresolvedTypes); + case TypeTags.STREAM_TAG -> checkIsStreamType(sourceType, (BStreamType) targetType, unresolvedTypes); + case TypeTags.TABLE_TAG -> checkIsTableType(sourceType, (BTableType) targetType, unresolvedTypes); + case TypeTags.JSON_TAG -> checkIsJSONType(sourceType, unresolvedTypes); + case TypeTags.RECORD_TYPE_TAG -> checkIsRecordType(sourceType, (BRecordType) targetType, unresolvedTypes); + case TypeTags.FUNCTION_POINTER_TAG -> checkIsFunctionType(sourceType, (BFunctionType) targetType); + case TypeTags.ARRAY_TAG -> checkIsArrayType(sourceType, (BArrayType) targetType, unresolvedTypes); + case TypeTags.TUPLE_TAG -> checkIsTupleType(sourceType, (BTupleType) targetType, unresolvedTypes); + case TypeTags.UNION_TAG -> checkIsUnionType(sourceType, (BUnionType) targetType, unresolvedTypes); + case TypeTags.OBJECT_TYPE_TAG -> + checkObjectEquivalency(sourceType, (BObjectType) targetType, unresolvedTypes); + case TypeTags.FINITE_TYPE_TAG -> checkIsFiniteType(sourceType, (BFiniteType) targetType); + case TypeTags.FUTURE_TAG -> checkIsFutureType(sourceType, (BFutureType) targetType, unresolvedTypes); + case TypeTags.ERROR_TAG -> checkIsErrorType(sourceType, (BErrorType) targetType, unresolvedTypes); + case TypeTags.TYPEDESC_TAG -> checkTypeDescType(sourceType, (BTypedescType) targetType, unresolvedTypes); + case TypeTags.XML_TAG -> checkIsXMLType(sourceType, targetType, unresolvedTypes); + // other non-recursive types shouldn't reach here + default -> false; + }; } private static boolean checkIsRecursiveTypeOnValue(Object sourceVal, Type sourceType, Type targetType, int sourceTypeTag, int targetTypeTag, List unresolvedTypes) { - switch (targetTypeTag) { - case TypeTags.ANYDATA_TAG: + return switch (targetTypeTag) { + case TypeTags.ANYDATA_TAG -> { if (sourceTypeTag == TypeTags.OBJECT_TYPE_TAG) { - return false; + yield false; } - return checkRecordBelongsToAnydataType((MapValue) sourceVal, (BRecordType) sourceType, unresolvedTypes); - case TypeTags.MAP_TAG: - return checkIsMapType(sourceVal, sourceType, (BMapType) targetType, unresolvedTypes); - case TypeTags.JSON_TAG: - return checkIsMapType(sourceVal, sourceType, - new BMapType(targetType.isReadOnly() ? TYPE_READONLY_JSON : - TYPE_JSON), unresolvedTypes); - case TypeTags.RECORD_TYPE_TAG: - return checkIsRecordType(sourceVal, sourceType, (BRecordType) targetType, unresolvedTypes); - case TypeTags.UNION_TAG: + yield checkRecordBelongsToAnydataType((MapValue) sourceVal, (BRecordType) sourceType, unresolvedTypes); + } + case TypeTags.MAP_TAG -> checkIsMapType(sourceVal, sourceType, (BMapType) targetType, unresolvedTypes); + case TypeTags.JSON_TAG -> checkIsMapType(sourceVal, sourceType, + new BMapType(targetType.isReadOnly() ? TYPE_READONLY_JSON : + TYPE_JSON), unresolvedTypes); + case TypeTags.RECORD_TYPE_TAG -> + checkIsRecordType(sourceVal, sourceType, (BRecordType) targetType, unresolvedTypes); + case TypeTags.UNION_TAG -> { for (Type type : ((BUnionType) targetType).getMemberTypes()) { if (checkIsType(sourceVal, sourceType, type, unresolvedTypes)) { - return true; + yield true; } } - return false; - case TypeTags.OBJECT_TYPE_TAG: - return checkObjectEquivalency(sourceVal, sourceType, (BObjectType) targetType, unresolvedTypes); - default: - return false; - } + yield false; + } + case TypeTags.OBJECT_TYPE_TAG -> + checkObjectEquivalency(sourceVal, sourceType, (BObjectType) targetType, unresolvedTypes); + default -> false; + }; } private static boolean isFiniteTypeMatch(BFiniteType sourceType, Type targetType) { @@ -818,22 +796,20 @@ private static boolean checkIsUnionType(Type sourceType, BUnionType targetType, } unresolvedTypes.add(pair); - switch (sourceType.getTag()) { - case TypeTags.UNION_TAG: - case TypeTags.JSON_TAG: - case TypeTags.ANYDATA_TAG: - return isUnionTypeMatch((BUnionType) sourceType, targetType, unresolvedTypes); - case TypeTags.FINITE_TYPE_TAG: - return isFiniteTypeMatch((BFiniteType) sourceType, targetType); - default: + return switch (sourceType.getTag()) { + case TypeTags.UNION_TAG, + TypeTags.JSON_TAG, + TypeTags.ANYDATA_TAG -> isUnionTypeMatch((BUnionType) sourceType, targetType, unresolvedTypes); + case TypeTags.FINITE_TYPE_TAG -> isFiniteTypeMatch((BFiniteType) sourceType, targetType); + default -> { for (Type type : targetType.getMemberTypes()) { if (checkIsType(sourceType, type, unresolvedTypes)) { - return true; + yield true; } } - return false; - - } + yield false; + } + }; } private static boolean checkIsMapType(Type sourceType, BMapType targetType, List unresolvedTypes) { @@ -856,16 +832,13 @@ private static boolean checkIsMapType(Object sourceVal, Type sourceType, BMapTyp List unresolvedTypes) { Type targetConstrainedType = targetType.getConstrainedType(); sourceType = getImpliedType(sourceType); - switch (sourceType.getTag()) { - case TypeTags.MAP_TAG: - return checkConstraints(((BMapType) sourceType).getConstrainedType(), targetConstrainedType, - unresolvedTypes); - case TypeTags.RECORD_TYPE_TAG: - return checkIsMapType((MapValue) sourceVal, (BRecordType) sourceType, unresolvedTypes, - targetConstrainedType); - default: - return false; - } + return switch (sourceType.getTag()) { + case TypeTags.MAP_TAG -> checkConstraints(((BMapType) sourceType).getConstrainedType(), + targetConstrainedType, unresolvedTypes); + case TypeTags.RECORD_TYPE_TAG -> checkIsMapType((MapValue) sourceVal, (BRecordType) sourceType, + unresolvedTypes, targetConstrainedType); + default -> false; + }; } private static boolean checkIsMapType(MapValue sourceVal, BRecordType sourceType, List unresolvedTypes, @@ -1100,14 +1073,11 @@ private static boolean checkIsJSONType(Type sourceType, List unresolve private static boolean checkIsRecordType(Type sourceType, BRecordType targetType, List unresolvedTypes) { sourceType = getImpliedType(sourceType); - switch (sourceType.getTag()) { - case TypeTags.RECORD_TYPE_TAG: - return checkIsRecordType((BRecordType) sourceType, targetType, unresolvedTypes); - case TypeTags.MAP_TAG: - return checkIsRecordType((BMapType) sourceType, targetType, unresolvedTypes); - default: - return false; - } + return switch (sourceType.getTag()) { + case TypeTags.RECORD_TYPE_TAG -> checkIsRecordType((BRecordType) sourceType, targetType, unresolvedTypes); + case TypeTags.MAP_TAG -> checkIsRecordType((BMapType) sourceType, targetType, unresolvedTypes); + default -> false; + }; } private static boolean checkIsRecordType(BRecordType sourceRecordType, BRecordType targetType, @@ -1204,7 +1174,7 @@ private static boolean checkIsRecordType(BMapType sourceType, BRecordType target Type constraintType = sourceType.getConstrainedType(); for (Field field : targetType.getFields().values()) { - var flags = field.getFlags(); + long flags = field.getFlags(); if (!SymbolFlags.isFlagOn(flags, SymbolFlags.OPTIONAL)) { return false; } @@ -1264,14 +1234,12 @@ private static boolean checkRecordBelongsToAnydataType(MapValue sourceVal, BReco private static boolean checkIsRecordType(Object sourceVal, Type sourceType, BRecordType targetType, List unresolvedTypes) { sourceType = getImpliedType(sourceType); - switch (sourceType.getTag()) { - case TypeTags.RECORD_TYPE_TAG: - return checkIsRecordType((MapValue) sourceVal, (BRecordType) sourceType, targetType, unresolvedTypes); - case TypeTags.MAP_TAG: - return checkIsRecordType((BMapType) sourceType, targetType, unresolvedTypes); - default: - return false; - } + return switch (sourceType.getTag()) { + case TypeTags.RECORD_TYPE_TAG -> + checkIsRecordType((MapValue) sourceVal, (BRecordType) sourceType, targetType, unresolvedTypes); + case TypeTags.MAP_TAG -> checkIsRecordType((BMapType) sourceType, targetType, unresolvedTypes); + default -> false; + }; } private static boolean checkIsRecordType(MapValue sourceRecordValue, BRecordType sourceRecordType, @@ -1604,22 +1572,21 @@ private static boolean checkIsTupleType(Type sourceType, BTupleType targetType, private static boolean checkIsAnyType(Type sourceType) { sourceType = getImpliedType(sourceType); - switch (sourceType.getTag()) { - case TypeTags.ERROR_TAG: - case TypeTags.READONLY_TAG: - return false; - case TypeTags.UNION_TAG: - case TypeTags.ANYDATA_TAG: - case TypeTags.JSON_TAG: + return switch (sourceType.getTag()) { + case TypeTags.ERROR_TAG, + TypeTags.READONLY_TAG -> false; + case TypeTags.UNION_TAG, + TypeTags.ANYDATA_TAG, + TypeTags.JSON_TAG -> { for (Type memberType : ((BUnionType) sourceType).getMemberTypes()) { if (!checkIsAnyType(memberType)) { - return false; + yield false; } } - return true; - default: - return true; - } + yield true; + } + default -> true; + }; } private static boolean checkIsFiniteType(Type sourceType, BFiniteType targetType) { @@ -1927,7 +1894,7 @@ private static boolean checkIsServiceType(Type sourceType, Type targetType, List } if (sourceType.getTag() == TypeTags.OBJECT_TYPE_TAG) { - var flags = ((BObjectType) sourceType).flags; + long flags = ((BObjectType) sourceType).flags; return (flags & SymbolFlags.SERVICE) == SymbolFlags.SERVICE; } @@ -1940,27 +1907,24 @@ public static boolean isInherentlyImmutableType(Type sourceType) { return true; } - switch (sourceType.getTag()) { - case TypeTags.XML_TEXT_TAG: - case TypeTags.FINITE_TYPE_TAG: // Assuming a finite type will only have members from simple basic types. - case TypeTags.READONLY_TAG: - case TypeTags.NULL_TAG: - case TypeTags.NEVER_TAG: - case TypeTags.ERROR_TAG: - case TypeTags.INVOKABLE_TAG: - case TypeTags.SERVICE_TAG: - case TypeTags.TYPEDESC_TAG: - case TypeTags.FUNCTION_POINTER_TAG: - case TypeTags.HANDLE_TAG: - case TypeTags.REG_EXP_TYPE_TAG: - return true; - case TypeTags.XML_TAG: - return ((BXmlType) sourceType).constraint.getTag() == TypeTags.NEVER_TAG; - case TypeTags.TYPE_REFERENCED_TYPE_TAG: - return isInherentlyImmutableType(((BTypeReferenceType) sourceType).getReferredType()); - default: - return false; - } + return switch (sourceType.getTag()) { + case TypeTags.XML_TEXT_TAG, + TypeTags.FINITE_TYPE_TAG, // Assuming a finite type will only have members from simple basic types. + TypeTags.READONLY_TAG, + TypeTags.NULL_TAG, + TypeTags.NEVER_TAG, + TypeTags.ERROR_TAG, + TypeTags.INVOKABLE_TAG, + TypeTags.SERVICE_TAG, + TypeTags.TYPEDESC_TAG, + TypeTags.FUNCTION_POINTER_TAG, + TypeTags.HANDLE_TAG, + TypeTags.REG_EXP_TYPE_TAG -> true; + case TypeTags.XML_TAG -> ((BXmlType) sourceType).constraint.getTag() == TypeTags.NEVER_TAG; + case TypeTags.TYPE_REFERENCED_TYPE_TAG -> + isInherentlyImmutableType(((BTypeReferenceType) sourceType).getReferredType()); + default -> false; + }; } public static boolean isSelectivelyImmutableType(Type type, Set unresolvedTypes) { @@ -2198,85 +2162,78 @@ private static boolean checkIsLikeOnValue(List errors, Object sourceValu break; } - switch (targetTypeTag) { - case TypeTags.READONLY_TAG: - return true; - case TypeTags.BYTE_TAG: + return switch (targetTypeTag) { + case TypeTags.READONLY_TAG -> true; + case TypeTags.BYTE_TAG -> { if (TypeTags.isIntegerTypeTag(sourceTypeTag)) { - return isByteLiteral((Long) sourceValue); + yield isByteLiteral((Long) sourceValue); } - return allowNumericConversion && TypeConverter.isConvertibleToByte(sourceValue); - case TypeTags.INT_TAG: - return allowNumericConversion && TypeConverter.isConvertibleToInt(sourceValue); - case TypeTags.SIGNED32_INT_TAG: - case TypeTags.SIGNED16_INT_TAG: - case TypeTags.SIGNED8_INT_TAG: - case TypeTags.UNSIGNED32_INT_TAG: - case TypeTags.UNSIGNED16_INT_TAG: - case TypeTags.UNSIGNED8_INT_TAG: + yield allowNumericConversion && TypeConverter.isConvertibleToByte(sourceValue); + } + case TypeTags.INT_TAG -> allowNumericConversion && TypeConverter.isConvertibleToInt(sourceValue); + case TypeTags.SIGNED32_INT_TAG, + TypeTags.SIGNED16_INT_TAG, + TypeTags.SIGNED8_INT_TAG, + TypeTags.UNSIGNED32_INT_TAG, + TypeTags.UNSIGNED16_INT_TAG, + TypeTags.UNSIGNED8_INT_TAG -> { if (TypeTags.isIntegerTypeTag(sourceTypeTag)) { - return TypeConverter.isConvertibleToIntSubType(sourceValue, targetType); - } - return allowNumericConversion && TypeConverter.isConvertibleToIntSubType(sourceValue, targetType); - case TypeTags.FLOAT_TAG: - case TypeTags.DECIMAL_TAG: - return allowNumericConversion && TypeConverter.isConvertibleToFloatingPointTypes(sourceValue); - case TypeTags.CHAR_STRING_TAG: - return TypeConverter.isConvertibleToChar(sourceValue); - case TypeTags.RECORD_TYPE_TAG: - return checkIsLikeRecordType(sourceValue, (BRecordType) targetType, unresolvedValues, - allowNumericConversion, varName, errors); - case TypeTags.TABLE_TAG: - return checkIsLikeTableType(sourceValue, (BTableType) targetType, unresolvedValues, - allowNumericConversion); - case TypeTags.JSON_TAG: - return checkIsLikeJSONType(sourceValue, sourceType, (BJsonType) targetType, unresolvedValues, - allowNumericConversion); - case TypeTags.MAP_TAG: - return checkIsLikeMapType(sourceValue, (BMapType) targetType, unresolvedValues, allowNumericConversion); - case TypeTags.STREAM_TAG: - return checkIsLikeStreamType(sourceValue, (BStreamType) targetType); - case TypeTags.ARRAY_TAG: - return checkIsLikeArrayType(sourceValue, (BArrayType) targetType, unresolvedValues, - allowNumericConversion); - case TypeTags.TUPLE_TAG: - return checkIsLikeTupleType(sourceValue, (BTupleType) targetType, unresolvedValues, - allowNumericConversion); - case TypeTags.ERROR_TAG: - return checkIsLikeErrorType(sourceValue, (BErrorType) targetType, unresolvedValues, - allowNumericConversion); - case TypeTags.ANYDATA_TAG: - return checkIsLikeAnydataType(sourceValue, sourceType, unresolvedValues, allowNumericConversion); - case TypeTags.FINITE_TYPE_TAG: - return checkFiniteTypeAssignable(sourceValue, sourceType, (BFiniteType) targetType, - unresolvedValues, allowNumericConversion); - case TypeTags.XML_ELEMENT_TAG: - case TypeTags.XML_COMMENT_TAG: - case TypeTags.XML_PI_TAG: - case TypeTags.XML_TEXT_TAG: + yield TypeConverter.isConvertibleToIntSubType(sourceValue, targetType); + } + yield allowNumericConversion && TypeConverter.isConvertibleToIntSubType(sourceValue, targetType); + } + case TypeTags.FLOAT_TAG, + TypeTags.DECIMAL_TAG -> + allowNumericConversion && TypeConverter.isConvertibleToFloatingPointTypes(sourceValue); + case TypeTags.CHAR_STRING_TAG -> TypeConverter.isConvertibleToChar(sourceValue); + case TypeTags.RECORD_TYPE_TAG -> + checkIsLikeRecordType(sourceValue, (BRecordType) targetType, unresolvedValues, + allowNumericConversion, varName, errors); + case TypeTags.TABLE_TAG -> checkIsLikeTableType(sourceValue, (BTableType) targetType, unresolvedValues, + allowNumericConversion); + case TypeTags.JSON_TAG -> + checkIsLikeJSONType(sourceValue, sourceType, (BJsonType) targetType, unresolvedValues, + allowNumericConversion); + case TypeTags.MAP_TAG -> + checkIsLikeMapType(sourceValue, (BMapType) targetType, unresolvedValues, allowNumericConversion); + case TypeTags.STREAM_TAG -> checkIsLikeStreamType(sourceValue, (BStreamType) targetType); + case TypeTags.ARRAY_TAG -> checkIsLikeArrayType(sourceValue, (BArrayType) targetType, unresolvedValues, + allowNumericConversion); + case TypeTags.TUPLE_TAG -> checkIsLikeTupleType(sourceValue, (BTupleType) targetType, unresolvedValues, + allowNumericConversion); + case TypeTags.ERROR_TAG -> checkIsLikeErrorType(sourceValue, (BErrorType) targetType, unresolvedValues, + allowNumericConversion); + case TypeTags.ANYDATA_TAG -> + checkIsLikeAnydataType(sourceValue, sourceType, unresolvedValues, allowNumericConversion); + case TypeTags.FINITE_TYPE_TAG -> + checkFiniteTypeAssignable(sourceValue, sourceType, (BFiniteType) targetType, + unresolvedValues, allowNumericConversion); + case TypeTags.XML_ELEMENT_TAG, + TypeTags.XML_COMMENT_TAG, + TypeTags.XML_PI_TAG, + TypeTags.XML_TEXT_TAG -> { if (TypeTags.isXMLTypeTag(sourceTypeTag)) { - return checkIsLikeXmlValueSingleton((XmlValue) sourceValue, targetType); + yield checkIsLikeXmlValueSingleton((XmlValue) sourceValue, targetType); } - return false; - case TypeTags.XML_TAG: + yield false; + } + case TypeTags.XML_TAG -> { if (TypeTags.isXMLTypeTag(sourceTypeTag)) { - return checkIsLikeXMLSequenceType((XmlValue) sourceValue, targetType); + yield checkIsLikeXMLSequenceType((XmlValue) sourceValue, targetType); } - return false; - case TypeTags.UNION_TAG: - return checkIsLikeUnionType(errors, sourceValue, (BUnionType) targetType, unresolvedValues, - allowNumericConversion, varName); - case TypeTags.INTERSECTION_TAG: - return checkIsLikeOnValue(errors, sourceValue, sourceType, - ((BIntersectionType) targetType).getEffectiveType(), unresolvedValues, allowNumericConversion, - varName); - case TypeTags.TYPE_REFERENCED_TYPE_TAG: - return checkIsLikeOnValue(errors, sourceValue, sourceType, - ((BTypeReferenceType) targetType).getReferredType(), unresolvedValues, allowNumericConversion, - varName); - default: - return false; - } + yield false; + } + case TypeTags.UNION_TAG -> + checkIsLikeUnionType(errors, sourceValue, (BUnionType) targetType, unresolvedValues, + allowNumericConversion, varName); + case TypeTags.INTERSECTION_TAG -> checkIsLikeOnValue(errors, sourceValue, sourceType, + ((BIntersectionType) targetType).getEffectiveType(), unresolvedValues, allowNumericConversion, + varName); + case TypeTags.TYPE_REFERENCED_TYPE_TAG -> checkIsLikeOnValue(errors, sourceValue, sourceType, + ((BTypeReferenceType) targetType).getReferredType(), unresolvedValues, allowNumericConversion, + varName); + default -> false; + }; } private static boolean checkIsLikeUnionType(List errors, Object sourceValue, BUnionType targetType, @@ -2337,16 +2294,12 @@ private static boolean checkIsLikeUnionType(List errors, Object sourceVa } private static XmlNodeType getXmlNodeType(Type type) { - switch (getImpliedType(type).getTag()) { - case TypeTags.XML_ELEMENT_TAG: - return XmlNodeType.ELEMENT; - case TypeTags.XML_COMMENT_TAG: - return XmlNodeType.COMMENT; - case TypeTags.XML_PI_TAG: - return XmlNodeType.PI; - default: - return XmlNodeType.TEXT; - } + return switch (getImpliedType(type).getTag()) { + case TypeTags.XML_ELEMENT_TAG -> XmlNodeType.ELEMENT; + case TypeTags.XML_COMMENT_TAG -> XmlNodeType.COMMENT; + case TypeTags.XML_PI_TAG -> XmlNodeType.PI; + default -> XmlNodeType.TEXT; + }; } private static boolean checkIsLikeXmlValueSingleton(XmlValue xmlSource, Type targetType) { @@ -2441,17 +2394,15 @@ private static boolean checkIsLikeAnydataType(Object sourceValue, Type sourceTyp case TypeTags.ARRAY_TAG: ArrayValue arr = (ArrayValue) sourceValue; BArrayType arrayType = (BArrayType) getImpliedType(arr.getType()); - switch (getImpliedType(arrayType.getElementType()).getTag()) { - case TypeTags.INT_TAG: - case TypeTags.FLOAT_TAG: - case TypeTags.DECIMAL_TAG: - case TypeTags.STRING_TAG: - case TypeTags.BOOLEAN_TAG: - case TypeTags.BYTE_TAG: - return true; - default: - return isLikeAnydataType(arr.getValues(), unresolvedValues, allowNumericConversion); - } + return switch (getImpliedType(arrayType.getElementType()).getTag()) { + case TypeTags.INT_TAG, + TypeTags.FLOAT_TAG, + TypeTags.DECIMAL_TAG, + TypeTags.STRING_TAG, + TypeTags.BOOLEAN_TAG, + TypeTags.BYTE_TAG -> true; + default -> isLikeAnydataType(arr.getValues(), unresolvedValues, allowNumericConversion); + }; case TypeTags.TUPLE_TAG: return isLikeAnydataType(((ArrayValue) sourceValue).getValues(), unresolvedValues, allowNumericConversion); @@ -2540,10 +2491,10 @@ static boolean isUnsigned8LiteralValue(Long longObject) { static boolean isCharLiteralValue(Object object) { String value; - if (object instanceof BString) { - value = ((BString) object).getValue(); - } else if (object instanceof String) { - value = (String) object; + if (object instanceof BString bString) { + value = bString.getValue(); + } else if (object instanceof String s) { + value = s; } else { return false; } @@ -2552,11 +2503,10 @@ static boolean isCharLiteralValue(Object object) { private static boolean checkIsLikeArrayType(Object sourceValue, BArrayType targetType, List unresolvedValues, boolean allowNumericConversion) { - if (!(sourceValue instanceof ArrayValue)) { + if (!(sourceValue instanceof ArrayValue source)) { return false; } - ArrayValue source = (ArrayValue) sourceValue; Type targetTypeElementType = targetType.getElementType(); if (source.getType().getTag() == TypeTags.ARRAY_TAG) { Type sourceElementType = ((BArrayType) source.getType()).getElementType(); @@ -2606,11 +2556,11 @@ private static boolean checkIsLikeArrayType(Object sourceValue, BArrayType targe private static boolean checkIsLikeMapType(Object sourceValue, BMapType targetType, List unresolvedValues, boolean allowNumericConversion) { - if (!(sourceValue instanceof MapValueImpl)) { + if (!(sourceValue instanceof MapValueImpl sourceMapValue)) { return false; } - for (Object mapEntry : ((MapValueImpl) sourceValue).values()) { + for (Object mapEntry : sourceMapValue.values()) { if (!checkIsLikeType(null, mapEntry, targetType.getConstrainedType(), unresolvedValues, allowNumericConversion, null)) { return false; @@ -2620,11 +2570,11 @@ private static boolean checkIsLikeMapType(Object sourceValue, BMapType targetTyp } private static boolean checkIsLikeStreamType(Object sourceValue, BStreamType targetType) { - if (!(sourceValue instanceof StreamValue)) { + if (!(sourceValue instanceof StreamValue streamValue)) { return false; } - BStreamType streamType = (BStreamType) ((StreamValue) sourceValue).getType(); + BStreamType streamType = (BStreamType) streamValue.getType(); return streamType.getConstrainedType() == targetType.getConstrainedType(); } @@ -2687,7 +2637,7 @@ private static boolean checkIsMappingLikeJsonType(MapValueImpl sourceValue, BJso private static boolean checkIsLikeRecordType(Object sourceValue, BRecordType targetType, List unresolvedValues, boolean allowNumericConversion, String varName, List errors) { - if (!(sourceValue instanceof MapValueImpl)) { + if (!(sourceValue instanceof MapValueImpl sourceMapValue)) { return false; } @@ -2710,7 +2660,7 @@ private static boolean checkIsLikeRecordType(Object sourceValue, BRecordType tar String fieldNameLong = TypeConverter.getLongFieldName(varName, fieldName); Field targetField = targetType.getFields().get(fieldName); - if (!(((MapValueImpl) sourceValue).containsKey(StringUtils.fromString(fieldName))) && + if (!(sourceMapValue.containsKey(StringUtils.fromString(fieldName))) && !SymbolFlags.isFlagOn(targetField.getFlags(), SymbolFlags.OPTIONAL)) { addErrorMessage((errors == null) ? 0 : errors.size(), "missing required field '" + fieldNameLong + "' of type '" + targetField.getFieldType().toString() + "' in record '" + targetType + "'", @@ -2722,7 +2672,7 @@ private static boolean checkIsLikeRecordType(Object sourceValue, BRecordType tar } } - for (Object object : ((MapValueImpl) sourceValue).entrySet()) { + for (Object object : sourceMapValue.entrySet()) { Map.Entry valueEntry = (Map.Entry) object; String fieldName = valueEntry.getKey().toString(); String fieldNameLong = TypeConverter.getLongFieldName(varName, fieldName); @@ -2767,10 +2717,9 @@ private static void addErrorMessage(int initialErrorCount, String errorMessage, private static boolean checkIsLikeTableType(Object sourceValue, BTableType targetType, List unresolvedValues, boolean allowNumericConversion) { - if (!(sourceValue instanceof TableValueImpl)) { + if (!(sourceValue instanceof TableValueImpl tableValue)) { return false; } - TableValueImpl tableValue = (TableValueImpl) sourceValue; BTableType sourceType = (BTableType) getImpliedType(tableValue.getType()); if (targetType.getKeyType() != null && sourceType.getFieldNames().length == 0) { return false; @@ -2814,8 +2763,8 @@ private static boolean checkFiniteTypeAssignable(Object sourceValue, Type source return false; } - protected static boolean isFiniteTypeValue(Object sourceValue, Type sourceType, Object valueSpaceItem, - boolean allowNumericConversion) { + static boolean isFiniteTypeValue(Object sourceValue, Type sourceType, Object valueSpaceItem, + boolean allowNumericConversion) { Type valueSpaceItemType = getType(valueSpaceItem); int sourceTypeTag = getImpliedType(sourceType).getTag(); int valueSpaceItemTypeTag = getImpliedType(valueSpaceItemType).getTag(); @@ -3008,8 +2957,8 @@ private static boolean checkValueEquals(Object lhsValue, Object rhsValue, Set unanalyzedTypes) { !(typeTag == TypeTags.CHAR_STRING_TAG || typeTag == TypeTags.NEVER_TAG)) { return true; } - switch (typeTag) { - case TypeTags.STREAM_TAG: - case TypeTags.MAP_TAG: - case TypeTags.ANY_TAG: - return true; - case TypeTags.ARRAY_TAG: - return checkFillerValue((BArrayType) type, unanalyzedTypes); - case TypeTags.FINITE_TYPE_TAG: - return checkFillerValue((BFiniteType) type); - case TypeTags.OBJECT_TYPE_TAG: - case TypeTags.SERVICE_TAG: - return checkFillerValue((BObjectType) type); - case TypeTags.RECORD_TYPE_TAG: - return checkFillerValue((BRecordType) type, unanalyzedTypes); - case TypeTags.TUPLE_TAG: - return checkFillerValue((BTupleType) type, unanalyzedTypes); - case TypeTags.UNION_TAG: - return checkFillerValue((BUnionType) type, unanalyzedTypes); - case TypeTags.TYPE_REFERENCED_TYPE_TAG: - return hasFillerValue(((BTypeReferenceType) type).getReferredType(), unanalyzedTypes); - case TypeTags.INTERSECTION_TAG: - return hasFillerValue(((BIntersectionType) type).getEffectiveType(), unanalyzedTypes); - default: - return false; - } + return switch (typeTag) { + case TypeTags.STREAM_TAG, + TypeTags.MAP_TAG, + TypeTags.ANY_TAG -> true; + case TypeTags.ARRAY_TAG -> checkFillerValue((BArrayType) type, unanalyzedTypes); + case TypeTags.FINITE_TYPE_TAG -> checkFillerValue((BFiniteType) type); + case TypeTags.OBJECT_TYPE_TAG, + TypeTags.SERVICE_TAG -> checkFillerValue((BObjectType) type); + case TypeTags.RECORD_TYPE_TAG -> checkFillerValue((BRecordType) type, unanalyzedTypes); + case TypeTags.TUPLE_TAG -> checkFillerValue((BTupleType) type, unanalyzedTypes); + case TypeTags.UNION_TAG -> checkFillerValue((BUnionType) type, unanalyzedTypes); + case TypeTags.TYPE_REFERENCED_TYPE_TAG -> + hasFillerValue(((BTypeReferenceType) type).getReferredType(), unanalyzedTypes); + case TypeTags.INTERSECTION_TAG -> + hasFillerValue(((BIntersectionType) type).getEffectiveType(), unanalyzedTypes); + default -> false; + }; } private static boolean checkFillerValue(BTupleType tupleType, List unAnalyzedTypes) { diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/TypeConverter.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/TypeConverter.java index 22140da471cd..82f3ffbdb370 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/TypeConverter.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/TypeConverter.java @@ -94,7 +94,7 @@ * * @since 0.995.0 */ -public class TypeConverter { +public final class TypeConverter { private static final String NAN = "NaN"; private static final String POSITIVE_INFINITY = "Infinity"; @@ -108,106 +108,78 @@ public class TypeConverter { public static Object convertValues(Type targetType, Object inputValue) { Type inputType = TypeChecker.getType(inputValue); - switch (targetType.getTag()) { - case TypeTags.INT_TAG: - case TypeTags.SIGNED32_INT_TAG: - case TypeTags.SIGNED16_INT_TAG: - case TypeTags.SIGNED8_INT_TAG: - case TypeTags.UNSIGNED32_INT_TAG: - case TypeTags.UNSIGNED16_INT_TAG: - case TypeTags.UNSIGNED8_INT_TAG: - return anyToInt(inputValue, () -> - ErrorUtils.createNumericConversionError(inputValue, PredefinedTypes.TYPE_INT)); - case TypeTags.DECIMAL_TAG: - return anyToDecimal(inputValue, () -> - ErrorUtils.createNumericConversionError(inputValue, PredefinedTypes.TYPE_DECIMAL)); - case TypeTags.FLOAT_TAG: - return anyToFloat(inputValue, () -> - ErrorUtils.createNumericConversionError(inputValue, PredefinedTypes.TYPE_FLOAT)); - case TypeTags.STRING_TAG: - return StringUtils.fromString(anyToString(inputValue)); - case TypeTags.BOOLEAN_TAG: - return anyToBoolean(inputValue, () -> - ErrorUtils.createNumericConversionError(inputValue, PredefinedTypes.TYPE_BOOLEAN)); - case TypeTags.BYTE_TAG: - return anyToByte(inputValue, () -> - ErrorUtils.createNumericConversionError(inputValue, PredefinedTypes.TYPE_BYTE)); - default: - throw ErrorCreator.createError(ErrorReasons.NUMBER_CONVERSION_ERROR, - ErrorHelper.getErrorDetails( - ErrorCodes.INCOMPATIBLE_SIMPLE_TYPE_CONVERT_OPERATION, - inputType, inputValue, targetType)); - } + return switch (targetType.getTag()) { + case TypeTags.INT_TAG, + TypeTags.SIGNED32_INT_TAG, + TypeTags.SIGNED16_INT_TAG, + TypeTags.SIGNED8_INT_TAG, + TypeTags.UNSIGNED32_INT_TAG, + TypeTags.UNSIGNED16_INT_TAG, + TypeTags.UNSIGNED8_INT_TAG -> anyToInt(inputValue, () -> + ErrorUtils.createNumericConversionError(inputValue, PredefinedTypes.TYPE_INT)); + case TypeTags.DECIMAL_TAG -> anyToDecimal(inputValue, () -> + ErrorUtils.createNumericConversionError(inputValue, PredefinedTypes.TYPE_DECIMAL)); + case TypeTags.FLOAT_TAG -> anyToFloat(inputValue, () -> + ErrorUtils.createNumericConversionError(inputValue, PredefinedTypes.TYPE_FLOAT)); + case TypeTags.STRING_TAG -> StringUtils.fromString(anyToString(inputValue)); + case TypeTags.BOOLEAN_TAG -> anyToBoolean(inputValue, () -> + ErrorUtils.createNumericConversionError(inputValue, PredefinedTypes.TYPE_BOOLEAN)); + case TypeTags.BYTE_TAG -> anyToByte(inputValue, () -> + ErrorUtils.createNumericConversionError(inputValue, PredefinedTypes.TYPE_BYTE)); + default -> throw ErrorCreator.createError(ErrorReasons.NUMBER_CONVERSION_ERROR, + ErrorHelper.getErrorDetails( + ErrorCodes.INCOMPATIBLE_SIMPLE_TYPE_CONVERT_OPERATION, inputType, inputValue, targetType)); + }; } public static Object castValues(Type targetType, Object inputValue) { - switch (targetType.getTag()) { - case TypeTags.SIGNED32_INT_TAG: - return anyToSigned32(inputValue); - case TypeTags.SIGNED16_INT_TAG: - return anyToSigned16(inputValue); - case TypeTags.SIGNED8_INT_TAG: - return anyToSigned8(inputValue); - case TypeTags.UNSIGNED32_INT_TAG: - return anyToUnsigned32(inputValue); - case TypeTags.UNSIGNED16_INT_TAG: - return anyToUnsigned16(inputValue); - case TypeTags.UNSIGNED8_INT_TAG: - return anyToUnsigned8(inputValue); - case TypeTags.INT_TAG: - return anyToIntCast(inputValue, () -> - ErrorUtils.createTypeCastError(inputValue, PredefinedTypes.TYPE_INT)); - case TypeTags.DECIMAL_TAG: - return anyToDecimalCast(inputValue, () -> - ErrorUtils.createTypeCastError(inputValue, PredefinedTypes.TYPE_DECIMAL)); - case TypeTags.FLOAT_TAG: - return anyToFloatCast(inputValue, () -> - ErrorUtils.createTypeCastError(inputValue, PredefinedTypes.TYPE_FLOAT)); - case TypeTags.STRING_TAG: - return anyToStringCast(inputValue, () -> - ErrorUtils.createTypeCastError(inputValue, PredefinedTypes.TYPE_STRING)); - case TypeTags.BOOLEAN_TAG: - return anyToBooleanCast(inputValue, () -> - ErrorUtils.createTypeCastError(inputValue, PredefinedTypes.TYPE_BOOLEAN)); - case TypeTags.BYTE_TAG: - return anyToByteCast(inputValue, () -> - ErrorUtils.createTypeCastError(inputValue, PredefinedTypes.TYPE_BYTE)); - default: - throw ErrorUtils.createTypeCastError(inputValue, targetType); - } + return switch (targetType.getTag()) { + case TypeTags.SIGNED32_INT_TAG -> anyToSigned32(inputValue); + case TypeTags.SIGNED16_INT_TAG -> anyToSigned16(inputValue); + case TypeTags.SIGNED8_INT_TAG -> anyToSigned8(inputValue); + case TypeTags.UNSIGNED32_INT_TAG -> anyToUnsigned32(inputValue); + case TypeTags.UNSIGNED16_INT_TAG -> anyToUnsigned16(inputValue); + case TypeTags.UNSIGNED8_INT_TAG -> anyToUnsigned8(inputValue); + case TypeTags.INT_TAG -> anyToIntCast(inputValue, () -> + ErrorUtils.createTypeCastError(inputValue, PredefinedTypes.TYPE_INT)); + case TypeTags.DECIMAL_TAG -> anyToDecimalCast(inputValue, () -> + ErrorUtils.createTypeCastError(inputValue, PredefinedTypes.TYPE_DECIMAL)); + case TypeTags.FLOAT_TAG -> anyToFloatCast(inputValue, () -> + ErrorUtils.createTypeCastError(inputValue, PredefinedTypes.TYPE_FLOAT)); + case TypeTags.STRING_TAG -> anyToStringCast(inputValue, () -> + ErrorUtils.createTypeCastError(inputValue, PredefinedTypes.TYPE_STRING)); + case TypeTags.BOOLEAN_TAG -> anyToBooleanCast(inputValue, () -> + ErrorUtils.createTypeCastError(inputValue, PredefinedTypes.TYPE_BOOLEAN)); + case TypeTags.BYTE_TAG -> anyToByteCast(inputValue, () -> + ErrorUtils.createTypeCastError(inputValue, PredefinedTypes.TYPE_BYTE)); + default -> throw ErrorUtils.createTypeCastError(inputValue, targetType); + }; } static boolean isConvertibleToByte(Object value) { Type inputType = TypeChecker.getType(value); - switch (inputType.getTag()) { - case TypeTags.BYTE_TAG: - return true; - case TypeTags.INT_TAG: - return TypeChecker.isByteLiteral((long) value); - case TypeTags.FLOAT_TAG: + return switch (inputType.getTag()) { + case TypeTags.BYTE_TAG -> true; + case TypeTags.INT_TAG -> TypeChecker.isByteLiteral((long) value); + case TypeTags.FLOAT_TAG -> { Double doubleValue = (Double) value; - return isFloatWithinIntRange(doubleValue) && TypeChecker.isByteLiteral(doubleValue.longValue()); - case TypeTags.DECIMAL_TAG: - return isDecimalWithinIntRange((DecimalValue) value) - && TypeChecker.isByteLiteral(((DecimalValue) value).value().longValue()); - default: - return false; - } + yield isFloatWithinIntRange(doubleValue) && TypeChecker.isByteLiteral(doubleValue.longValue()); + } + case TypeTags.DECIMAL_TAG -> isDecimalWithinIntRange((DecimalValue) value) && + TypeChecker.isByteLiteral(((DecimalValue) value).value().longValue()); + default -> false; + }; } static boolean isConvertibleToInt(Object value) { Type inputType = TypeChecker.getType(value); - switch (inputType.getTag()) { - case TypeTags.BYTE_TAG: - case TypeTags.INT_TAG: - return true; - case TypeTags.FLOAT_TAG: - return isFloatWithinIntRange((double) value); - case TypeTags.DECIMAL_TAG: - return isDecimalWithinIntRange((DecimalValue) value); - default: - return false; - } + return switch (inputType.getTag()) { + case TypeTags.BYTE_TAG, + TypeTags.INT_TAG -> true; + case TypeTags.FLOAT_TAG -> isFloatWithinIntRange((double) value); + case TypeTags.DECIMAL_TAG -> isDecimalWithinIntRange((DecimalValue) value); + default -> false; + }; } static boolean isConvertibleToIntSubType(Object value, Type targetType) { @@ -259,15 +231,10 @@ static boolean isConvertibleToChar(Object value) { static boolean isConvertibleToFloatingPointTypes(Object value) { Type inputType = TypeChecker.getType(value); - switch (inputType.getTag()) { - case TypeTags.BYTE_TAG: - case TypeTags.INT_TAG: - case TypeTags.FLOAT_TAG: - case TypeTags.DECIMAL_TAG: - return true; - default: - return false; - } + return switch (inputType.getTag()) { + case TypeTags.BYTE_TAG, TypeTags.INT_TAG, TypeTags.FLOAT_TAG, TypeTags.DECIMAL_TAG -> true; + default -> false; + }; } public static Type getConvertibleType(Object inputValue, Type targetType, String varName, @@ -450,7 +417,7 @@ public static Type getConvertibleFiniteType(Object inputValue, BFiniteType targe private static boolean isConvertibleToRecordType(Object sourceValue, BRecordType targetType, String varName, Set unresolvedValues, List errors, boolean allowNumericConversion) { - if (!(sourceValue instanceof MapValueImpl)) { + if (!(sourceValue instanceof MapValueImpl sourceMapValueImpl)) { return false; } @@ -468,8 +435,7 @@ private static boolean isConvertibleToRecordType(Object sourceValue, BRecordType targetFieldTypes.put(field.getKey(), field.getValue().getFieldType()); } - MapValueImpl sourceMapValueImpl = (MapValueImpl) sourceValue; - for (Map.Entry targetTypeEntry : targetFieldTypes.entrySet()) { + for (Map.Entry targetTypeEntry : targetFieldTypes.entrySet()) { String fieldName = targetTypeEntry.getKey().toString(); String fieldNameLong = getLongFieldName(varName, fieldName); @@ -487,8 +453,7 @@ private static boolean isConvertibleToRecordType(Object sourceValue, BRecordType } } - for (Object object : sourceMapValueImpl.entrySet()) { - Map.Entry valueEntry = (Map.Entry) object; + for (Map.Entry valueEntry : sourceMapValueImpl.entrySet()) { String fieldName = valueEntry.getKey().toString(); String fieldNameLong = getLongFieldName(varName, fieldName); int initialErrorCount = errors.size(); @@ -528,7 +493,7 @@ private static boolean isConvertibleToRecordType(Object sourceValue, BRecordType return returnVal; } - protected static String getShortSourceValue(Object sourceValue) { + static String getShortSourceValue(Object sourceValue) { if (sourceValue == null) { return "()"; } @@ -542,7 +507,7 @@ protected static String getShortSourceValue(Object sourceValue) { return sourceValueName; } - protected static String getLongFieldName(String varName, String fieldName) { + static String getLongFieldName(String varName, String fieldName) { if (varName == null) { return fieldName; } else { @@ -619,8 +584,7 @@ private static boolean isConvertibleToMapType(Object sourceValue, BMapType targe } boolean returnVal = true; - for (Object object : ((MapValueImpl) sourceValue).entrySet()) { - Map.Entry valueEntry = (Map.Entry) object; + for (Map.Entry valueEntry : ((MapValueImpl) sourceValue).entrySet()) { String fieldNameLong = getLongFieldName(varName, valueEntry.getKey().toString()); int initialErrorCount = errors.size(); if (getConvertibleType(valueEntry.getValue(), targetType.getConstrainedType(), fieldNameLong, @@ -640,10 +604,9 @@ private static boolean isConvertibleToMapType(Object sourceValue, BMapType targe private static boolean isConvertibleToArrayType(Object sourceValue, BArrayType targetType, Set unresolvedValues, String varName, List errors, boolean allowNumericConversion) { - if (!(sourceValue instanceof ArrayValue)) { + if (!(sourceValue instanceof ArrayValue source)) { return false; } - ArrayValue source = (ArrayValue) sourceValue; int targetSize = targetType.getSize(); long sourceSize = source.getLength(); if (targetType.getState() == ArrayType.ArrayState.CLOSED && targetSize < sourceSize) { @@ -689,11 +652,10 @@ private static boolean isConvertibleToArrayType(Object sourceValue, BArrayType t private static boolean isConvertibleToTupleType(Object sourceValue, BTupleType targetType, Set unresolvedValues, String varName, List errors, boolean allowNumericConversion) { - if (!(sourceValue instanceof ArrayValue)) { + if (!(sourceValue instanceof ArrayValue source)) { return false; } - ArrayValue source = (ArrayValue) sourceValue; List targetTypes = targetType.getTupleTypes(); int sourceTypeSize = source.size(); int targetTypeSize = targetTypes.size(); @@ -750,19 +712,19 @@ private static String getElementIndex(String varName, int index) { } static long anyToInt(Object sourceVal, Supplier errorFunc) { - if (sourceVal instanceof Long) { - return (Long) sourceVal; - } else if (sourceVal instanceof Double) { - return floatToInt((double) sourceVal); - } else if (sourceVal instanceof Integer) { - return ((Integer) sourceVal).longValue(); - } else if (sourceVal instanceof Boolean) { - return (Boolean) sourceVal ? 1 : 0; - } else if (sourceVal instanceof DecimalValue) { - return ((DecimalValue) sourceVal).intValue(); - } else if (sourceVal instanceof String) { + if (sourceVal instanceof Long l) { + return l; + } else if (sourceVal instanceof Double d) { + return floatToInt(d); + } else if (sourceVal instanceof Integer i) { + return i.longValue(); + } else if (sourceVal instanceof Boolean b) { + return b ? 1 : 0; + } else if (sourceVal instanceof DecimalValue decimalValue) { + return decimalValue.intValue(); + } else if (sourceVal instanceof String s) { try { - return Long.parseLong((String) sourceVal); + return Long.parseLong(s); } catch (NumberFormatException e) { throw errorFunc.get(); } @@ -772,14 +734,14 @@ static long anyToInt(Object sourceVal, Supplier errorFunc) { } static long anyToIntCast(Object sourceVal, Supplier errorFunc) { - if (sourceVal instanceof Long) { - return (Long) sourceVal; - } else if (sourceVal instanceof Double) { - return floatToInt((double) sourceVal); - } else if (sourceVal instanceof Integer) { - return ((Integer) sourceVal).longValue(); - } else if (sourceVal instanceof DecimalValue) { - return ((DecimalValue) sourceVal).intValue(); + if (sourceVal instanceof Long l) { + return l; + } else if (sourceVal instanceof Double d) { + return floatToInt(d); + } else if (sourceVal instanceof Integer i) { + return i.longValue(); + } else if (sourceVal instanceof DecimalValue decimalValue) { + return decimalValue.intValue(); } else { throw errorFunc.get(); } @@ -801,19 +763,19 @@ static long anyToIntSubTypeCast(Object sourceVal, Type type, Supplier er } static double anyToFloat(Object sourceVal, Supplier errorFunc) { - if (sourceVal instanceof Long) { - return ((Long) sourceVal).doubleValue(); - } else if (sourceVal instanceof Double) { - return (Double) sourceVal; - } else if (sourceVal instanceof Integer) { - return ((Integer) sourceVal).floatValue(); - } else if (sourceVal instanceof Boolean) { - return (Boolean) sourceVal ? 1.0 : 0.0; - } else if (sourceVal instanceof DecimalValue) { - return ((DecimalValue) sourceVal).floatValue(); - } else if (sourceVal instanceof String) { + if (sourceVal instanceof Long l) { + return l.doubleValue(); + } else if (sourceVal instanceof Double d) { + return d; + } else if (sourceVal instanceof Integer i) { + return i.floatValue(); + } else if (sourceVal instanceof Boolean b) { + return b ? 1.0 : 0.0; + } else if (sourceVal instanceof DecimalValue decimalValue) { + return decimalValue.floatValue(); + } else if (sourceVal instanceof String s) { try { - return Double.parseDouble((String) sourceVal); + return Double.parseDouble(s); } catch (NumberFormatException e) { throw errorFunc.get(); } @@ -823,33 +785,33 @@ static double anyToFloat(Object sourceVal, Supplier errorFunc) { } static double anyToFloatCast(Object sourceVal, Supplier errorFunc) { - if (sourceVal instanceof Long) { - return ((Long) sourceVal).doubleValue(); - } else if (sourceVal instanceof Double) { - return (Double) sourceVal; - } else if (sourceVal instanceof Integer) { - return ((Integer) sourceVal).floatValue(); - } else if (sourceVal instanceof DecimalValue) { - return ((DecimalValue) sourceVal).floatValue(); + if (sourceVal instanceof Long l) { + return l.doubleValue(); + } else if (sourceVal instanceof Double d) { + return d; + } else if (sourceVal instanceof Integer i) { + return i.floatValue(); + } else if (sourceVal instanceof DecimalValue decimalValue) { + return decimalValue.floatValue(); } else { throw errorFunc.get(); } } static boolean anyToBoolean(Object sourceVal, Supplier errorFunc) { - if (sourceVal instanceof Long) { - return (long) sourceVal != 0; - } else if (sourceVal instanceof Double) { - return (Double) sourceVal != 0.0; - } else if (sourceVal instanceof Integer) { - return (int) sourceVal != 0; - } else if (sourceVal instanceof Boolean) { - return (boolean) sourceVal; - } else if (sourceVal instanceof DecimalValue) { - return ((DecimalValue) sourceVal).booleanValue(); - } else if (sourceVal instanceof String) { + if (sourceVal instanceof Long l) { + return l != 0; + } else if (sourceVal instanceof Double d) { + return d != 0.0; + } else if (sourceVal instanceof Integer i) { + return i != 0; + } else if (sourceVal instanceof Boolean b) { + return b; + } else if (sourceVal instanceof DecimalValue decimalValue) { + return decimalValue.booleanValue(); + } else if (sourceVal instanceof String s) { try { - return Boolean.parseBoolean((String) sourceVal); + return Boolean.parseBoolean(s); } catch (NumberFormatException e) { throw errorFunc.get(); } @@ -968,15 +930,10 @@ public static boolean hasFloatOrDecimalLiteralSuffix(String value) { return false; } - switch (value.charAt(length - 1)) { - case 'F': - case 'f': - case 'D': - case 'd': - return true; - default: - return false; - } + return switch (value.charAt(length - 1)) { + case 'F', 'f', 'D', 'd' -> true; + default -> false; + }; } public static Boolean stringToBoolean(String value) throws NumberFormatException { @@ -1040,19 +997,19 @@ private static void checkIsValidFloat(double sourceVal, Type targetType) { } static int anyToByte(Object sourceVal, Supplier errorFunc) { - if (sourceVal instanceof Long) { - return intToByte((Long) sourceVal); - } else if (sourceVal instanceof Double) { - return floatToByte((Double) sourceVal); - } else if (sourceVal instanceof Integer) { - return (int) sourceVal; - } else if (sourceVal instanceof Boolean) { - return ((Boolean) sourceVal ? 1 : 0); - } else if (sourceVal instanceof DecimalValue) { - return ((DecimalValue) sourceVal).byteValue(); - } else if (sourceVal instanceof String) { + if (sourceVal instanceof Long l) { + return intToByte(l); + } else if (sourceVal instanceof Double d) { + return floatToByte(d); + } else if (sourceVal instanceof Integer i) { + return i; + } else if (sourceVal instanceof Boolean b) { + return (b ? 1 : 0); + } else if (sourceVal instanceof DecimalValue decimalValue) { + return decimalValue.byteValue(); + } else if (sourceVal instanceof String s) { try { - return Integer.parseInt((String) sourceVal); + return Integer.parseInt(s); } catch (NumberFormatException e) { throw errorFunc.get(); } @@ -1062,16 +1019,16 @@ static int anyToByte(Object sourceVal, Supplier errorFunc) { } static int anyToByteCast(Object sourceVal, Supplier errorFunc) { - if (sourceVal instanceof Long) { - return intToByte((Long) sourceVal); - } else if (sourceVal instanceof Byte) { - return ((Byte) sourceVal).intValue(); - } else if (sourceVal instanceof Double) { - return floatToByte((Double) sourceVal); - } else if (sourceVal instanceof Integer) { - return (int) sourceVal; - } else if (sourceVal instanceof DecimalValue) { - return ((DecimalValue) sourceVal).byteValue(); + if (sourceVal instanceof Long l) { + return intToByte(l); + } else if (sourceVal instanceof Byte b) { + return b.intValue(); + } else if (sourceVal instanceof Double d) { + return floatToByte(d); + } else if (sourceVal instanceof Integer i) { + return i; + } else if (sourceVal instanceof DecimalValue decimalValue) { + return decimalValue.byteValue(); } else { throw errorFunc.get(); } @@ -1079,18 +1036,18 @@ static int anyToByteCast(Object sourceVal, Supplier errorFunc) { } private static String anyToString(Object sourceVal) { - if (sourceVal instanceof Long) { - return Long.toString((Long) sourceVal); - } else if (sourceVal instanceof Double) { - return Double.toString((Double) sourceVal); - } else if (sourceVal instanceof Integer) { - return Long.toString((Integer) sourceVal); - } else if (sourceVal instanceof Boolean) { - return Boolean.toString((Boolean) sourceVal); - } else if (sourceVal instanceof DecimalValue) { - return ((DecimalValue) sourceVal).stringValue(null); - } else if (sourceVal instanceof String) { - return (String) sourceVal; + if (sourceVal instanceof Long l) { + return Long.toString(l); + } else if (sourceVal instanceof Double d) { + return Double.toString(d); + } else if (sourceVal instanceof Integer i) { + return Long.toString(i); + } else if (sourceVal instanceof Boolean b) { + return Boolean.toString(b); + } else if (sourceVal instanceof DecimalValue decimalValue) { + return decimalValue.stringValue(null); + } else if (sourceVal instanceof String s) { + return s; } else if (sourceVal == null) { return "()"; } @@ -1099,39 +1056,39 @@ private static String anyToString(Object sourceVal) { } private static String anyToStringCast(Object sourceVal, Supplier errorFunc) { - if (sourceVal instanceof String) { - return (String) sourceVal; + if (sourceVal instanceof String s) { + return s; } throw errorFunc.get(); } static DecimalValue anyToDecimal(Object sourceVal, Supplier errorFunc) { - if (sourceVal instanceof Long) { - return DecimalValue.valueOf((Long) sourceVal); - } else if (sourceVal instanceof Double) { - return DecimalValue.valueOf((Double) sourceVal); - } else if (sourceVal instanceof Integer) { - return DecimalValue.valueOf((Integer) sourceVal); - } else if (sourceVal instanceof Boolean) { - return DecimalValue.valueOf((Boolean) sourceVal); - } else if (sourceVal instanceof DecimalValue) { - return (DecimalValue) sourceVal; + if (sourceVal instanceof Long l) { + return DecimalValue.valueOf(l); + } else if (sourceVal instanceof Double d) { + return DecimalValue.valueOf(d); + } else if (sourceVal instanceof Integer i) { + return DecimalValue.valueOf(i); + } else if (sourceVal instanceof Boolean b) { + return DecimalValue.valueOf(b); + } else if (sourceVal instanceof DecimalValue decimalValue) { + return decimalValue; } throw errorFunc.get(); } static DecimalValue anyToDecimalCast(Object sourceVal, Supplier errorFunc) { - if (sourceVal instanceof Long) { - return DecimalValue.valueOf((Long) sourceVal); - } else if (sourceVal instanceof Double) { - return DecimalValue.valueOf((Double) sourceVal); - } else if (sourceVal instanceof Integer) { - return DecimalValue.valueOf((Integer) sourceVal); - } else if (sourceVal instanceof DecimalValue) { - return (DecimalValue) sourceVal; - } else if (sourceVal instanceof String) { - return new DecimalValue((String) sourceVal); + if (sourceVal instanceof Long l) { + return DecimalValue.valueOf(l); + } else if (sourceVal instanceof Double d) { + return DecimalValue.valueOf(d); + } else if (sourceVal instanceof Integer i) { + return DecimalValue.valueOf(i); + } else if (sourceVal instanceof DecimalValue decimalValue) { + return decimalValue; + } else if (sourceVal instanceof String s) { + return new DecimalValue(s); } throw errorFunc.get(); } @@ -1139,64 +1096,64 @@ static DecimalValue anyToDecimalCast(Object sourceVal, Supplier errorFun // JBallerina related casts static byte anyToJByteCast(Object sourceVal, Supplier errorFunc) { - if (sourceVal instanceof Byte) { - return (Byte) sourceVal; + if (sourceVal instanceof Byte bVal) { + return bVal; } else { throw errorFunc.get(); } } static char anyToJCharCast(Object sourceVal, Supplier errorFunc) { - if (sourceVal instanceof Character) { - return (Character) sourceVal; + if (sourceVal instanceof Character cVal) { + return cVal; } else { throw errorFunc.get(); } } static short anyToJShortCast(Object sourceVal, Supplier errorFunc) { - if (sourceVal instanceof Short) { - return (Short) sourceVal; + if (sourceVal instanceof Short sVal) { + return sVal; } else { throw errorFunc.get(); } } static int anyToJIntCast(Object sourceVal, Supplier errorFunc) { - if (sourceVal instanceof Integer) { - return (Integer) sourceVal; + if (sourceVal instanceof Integer iVal) { + return iVal; } else { throw errorFunc.get(); } } static long anyToJLongCast(Object sourceVal, Supplier errorFunc) { - if (sourceVal instanceof Long) { - return (Long) sourceVal; + if (sourceVal instanceof Long lVal) { + return lVal; } else { throw errorFunc.get(); } } static float anyToJFloatCast(Object sourceVal, Supplier errorFunc) { - if (sourceVal instanceof Float) { - return (Float) sourceVal; + if (sourceVal instanceof Float fVal) { + return fVal; } else { throw errorFunc.get(); } } static double anyToJDoubleCast(Object sourceVal, Supplier errorFunc) { - if (sourceVal instanceof Double) { - return (Double) sourceVal; + if (sourceVal instanceof Double dVal) { + return dVal; } else { throw errorFunc.get(); } } static boolean anyToJBooleanCast(Object sourceVal, Supplier errorFunc) { - if (sourceVal instanceof Boolean) { - return (Boolean) sourceVal; + if (sourceVal instanceof Boolean bVal) { + return bVal; } else { throw errorFunc.get(); } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/ValueComparisonUtils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/ValueComparisonUtils.java index 917b36729d2b..13f1010ceabc 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/ValueComparisonUtils.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/ValueComparisonUtils.java @@ -34,7 +34,10 @@ * * @since 2.0.0 */ -public class ValueComparisonUtils { +public final class ValueComparisonUtils { + + private ValueComparisonUtils() { + } /** * Check if left hand side ordered type value is less than right hand side ordered type value. @@ -305,14 +308,11 @@ private static int compareFloatValues(double lhsValue, double rhsValue, boolean } private static boolean checkDecimalGreaterThan(DecimalValue lhsValue, DecimalValue rhsValue) { - switch (lhsValue.valueKind) { - case ZERO: - case OTHER: - return (isDecimalRealNumber(rhsValue) && - lhsValue.decimalValue().compareTo(rhsValue.decimalValue()) > 0); - default: - return false; - } + return switch (lhsValue.valueKind) { + case ZERO, + OTHER -> (isDecimalRealNumber(rhsValue) && + lhsValue.decimalValue().compareTo(rhsValue.decimalValue()) > 0); + }; } private static boolean isDecimalRealNumber(DecimalValue decimalValue) { diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/ValueConverter.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/ValueConverter.java index 23ec858e2643..d29f432d9712 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/ValueConverter.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/ValueConverter.java @@ -72,7 +72,7 @@ * * @since 2201.5.0 */ -public class ValueConverter { +public final class ValueConverter { private ValueConverter() {} @@ -263,7 +263,7 @@ private static Object convertArray(BArray array, Type targetType, Type targetRef BArray data = ValueCreator .createArrayValue(tableValues, TypeCreator.createArrayType(tableType.getConstrainedType())); BArray fieldNames = StringUtils.fromStringArray(tableType.getFieldNames()); - return new TableValueImpl(targetRefType, (ArrayValue) data, (ArrayValue) fieldNames); + return new TableValueImpl<>(targetRefType, (ArrayValue) data, (ArrayValue) fieldNames); default: break; } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/ValueUtils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/ValueUtils.java index f2438efb18c1..82b4bb194a99 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/ValueUtils.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/ValueUtils.java @@ -53,7 +53,7 @@ * * @since 2.0.0 */ -public class ValueUtils { +public final class ValueUtils { private static final PrintStream errStream = System.err; @@ -183,8 +183,8 @@ public static BMap createRecordValue(Module packageId, String r for (Map.Entry fieldEntry : valueMap.entrySet()) { Object val = fieldEntry.getValue(); // TODO: Remove the following String to BString conversion. - if (val instanceof String) { - val = StringUtils.fromString((String) val); + if (val instanceof String s) { + val = StringUtils.fromString(s); } recordValue.populateInitialValue(StringUtils.fromString(fieldEntry.getKey()), val); } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/XmlFactory.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/XmlFactory.java index 898735fb674a..96f87420135c 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/XmlFactory.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/XmlFactory.java @@ -63,7 +63,7 @@ * * @since 0.995.0 */ -public class XmlFactory { +public final class XmlFactory { public static final StAXParserConfiguration STAX_PARSER_CONFIGURATION = StAXParserConfiguration.STANDALONE; public static final String PARSE_ERROR = "failed to parse xml"; @@ -216,7 +216,7 @@ public static XmlValue concatenate(XmlValue firstSeq, XmlValue secondSeq) { * @param table {@link io.ballerina.runtime.internal.values.TableValue} to convert * @return converted {@link XmlValue} */ - public static BXml tableToXML(TableValueImpl table) { + public static BXml tableToXML(TableValueImpl table) { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); XMLStreamWriter streamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(outputStream); @@ -506,7 +506,7 @@ private static OMElement stringToOM(OMFactory omFactory, String xmlFragment) thr * * @since 1.2 */ - public static class XMLTextUnescape { + public static final class XMLTextUnescape { private XMLTextUnescape() {} diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/XmlValidator.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/XmlValidator.java index 735d21fe5b8b..0d9e69977bd8 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/XmlValidator.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/XmlValidator.java @@ -27,7 +27,7 @@ * * @since 0.995.0 */ -public class XmlValidator { +public final class XmlValidator { /* * Constants @@ -188,31 +188,31 @@ public class XmlValidator { } // remove special characters - for (int i = 0; i < specialChar.length; i++) { - CHARS[specialChar[i]] = (byte) (CHARS[specialChar[i]] & ~MASK_CONTENT); + for (int k : specialChar) { + CHARS[k] = (byte) (CHARS[k] & ~MASK_CONTENT); } // set space characters - for (int i = 0; i < spaceChar.length; i++) { - CHARS[spaceChar[i]] |= MASK_SPACE; + for (int k : spaceChar) { + CHARS[k] |= MASK_SPACE; } // set name start characters - for (int i = 0; i < nameStartChar.length; i++) { - CHARS[nameStartChar[i]] |= MASK_NAME_START | MASK_NAME | MASK_NCNAME_START | MASK_NCNAME; + for (int k : nameStartChar) { + CHARS[k] |= MASK_NAME_START | MASK_NAME | MASK_NCNAME_START | MASK_NCNAME; } for (int i = 0; i < letterRange.length; i += 2) { for (int j = letterRange[i]; j <= letterRange[i + 1]; j++) { CHARS[j] |= MASK_NAME_START | MASK_NAME | MASK_NCNAME_START | MASK_NCNAME; } } - for (int i = 0; i < letterChar.length; i++) { - CHARS[letterChar[i]] |= MASK_NAME_START | MASK_NAME | MASK_NCNAME_START | MASK_NCNAME; + for (int k : letterChar) { + CHARS[k] |= MASK_NAME_START | MASK_NAME | MASK_NCNAME_START | MASK_NCNAME; } // set name characters - for (int i = 0; i < nameChar.length; i++) { - CHARS[nameChar[i]] |= MASK_NAME | MASK_NCNAME; + for (int k : nameChar) { + CHARS[k] |= MASK_NAME | MASK_NCNAME; } for (int i = 0; i < digitRange.length; i += 2) { for (int j = digitRange[i]; j <= digitRange[i + 1]; j++) { @@ -224,24 +224,24 @@ public class XmlValidator { CHARS[j] |= MASK_NAME | MASK_NCNAME; } } - for (int i = 0; i < combiningCharChar.length; i++) { - CHARS[combiningCharChar[i]] |= MASK_NAME | MASK_NCNAME; + for (int k : combiningCharChar) { + CHARS[k] |= MASK_NAME | MASK_NCNAME; } for (int i = 0; i < extenderRange.length; i += 2) { for (int j = extenderRange[i]; j <= extenderRange[i + 1]; j++) { CHARS[j] |= MASK_NAME | MASK_NCNAME; } } - for (int i = 0; i < extenderChar.length; i++) { - CHARS[extenderChar[i]] |= MASK_NAME | MASK_NCNAME; + for (int k : extenderChar) { + CHARS[k] |= MASK_NAME | MASK_NCNAME; } // remove ':' from allowable MASK_NCNAME_START and MASK_NCNAME chars CHARS[':'] &= ~(MASK_NCNAME_START | MASK_NCNAME); // set Pubid characters - for (int i = 0; i < pubidChar.length; i++) { - CHARS[pubidChar[i]] |= MASK_PUBID; + for (int k : pubidChar) { + CHARS[k] |= MASK_PUBID; } for (int i = 0; i < pubidRange.length; i += 2) { for (int j = pubidRange[i]; j <= pubidRange[i + 1]; j++) { @@ -250,6 +250,9 @@ public class XmlValidator { } } + private XmlValidator() { + } + /* * Public Methods. */ diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/cli/CliUtil.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/cli/CliUtil.java index 353d00189704..d677e3b42be0 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/cli/CliUtil.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/cli/CliUtil.java @@ -34,7 +34,7 @@ /** * Contains the util functions for CLI parsing. */ -public class CliUtil { +public final class CliUtil { private static final String INVALID_ARGUMENT_ERROR = "invalid argument '%s' for parameter '%s', expected %s value"; @@ -64,33 +64,26 @@ static Object getUnionValue(Type type, String value, String parameterName) { } static Object getBValue(Type type, String value, String parameterName) { - switch (TypeUtils.getImpliedType(type).getTag()) { - case TypeTags.STRING_TAG: - return StringUtils.fromString(value); - case TypeTags.CHAR_STRING_TAG: - return getCharValue(value, parameterName); - case TypeTags.INT_TAG: - case TypeTags.SIGNED32_INT_TAG: - case TypeTags.SIGNED16_INT_TAG: - case TypeTags.SIGNED8_INT_TAG: - case TypeTags.UNSIGNED32_INT_TAG: - case TypeTags.UNSIGNED16_INT_TAG: - case TypeTags.UNSIGNED8_INT_TAG: - return getIntegerValue(value, parameterName); - case TypeTags.BYTE_TAG: - return getByteValue(value, parameterName); - case TypeTags.FLOAT_TAG: - return getFloatValue(value, parameterName); - case TypeTags.DECIMAL_TAG: - return getDecimalValue(value, parameterName); - case TypeTags.TYPE_REFERENCED_TYPE_TAG: - return getBValue(TypeUtils.getImpliedType(type), value, parameterName); - case TypeTags.BOOLEAN_TAG: - throw ErrorCreator.createError(StringUtils.fromString("the option '" + parameterName + "' of type " + - "'boolean' is expected without a value")); - default: - throw getUnsupportedTypeException(type); - } + return switch (TypeUtils.getImpliedType(type).getTag()) { + case TypeTags.STRING_TAG -> StringUtils.fromString(value); + case TypeTags.CHAR_STRING_TAG -> getCharValue(value, parameterName); + case TypeTags.INT_TAG, + TypeTags.SIGNED32_INT_TAG, + TypeTags.SIGNED16_INT_TAG, + TypeTags.SIGNED8_INT_TAG, + TypeTags.UNSIGNED32_INT_TAG, + TypeTags.UNSIGNED16_INT_TAG, + TypeTags.UNSIGNED8_INT_TAG -> getIntegerValue(value, parameterName); + case TypeTags.BYTE_TAG -> getByteValue(value, parameterName); + case TypeTags.FLOAT_TAG -> getFloatValue(value, parameterName); + case TypeTags.DECIMAL_TAG -> getDecimalValue(value, parameterName); + case TypeTags.TYPE_REFERENCED_TYPE_TAG -> getBValue(TypeUtils.getImpliedType(type), value, parameterName); + case TypeTags.BOOLEAN_TAG -> + throw ErrorCreator.createError( + StringUtils.fromString("the option '" + parameterName + "' of type " + + "'boolean' is expected without a value")); + default -> throw getUnsupportedTypeException(type); + }; } private static Object getCharValue(String argument, String parameterName) { diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/commons/TypeValuePair.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/commons/TypeValuePair.java index e081a73a2c9e..783366fad499 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/commons/TypeValuePair.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/commons/TypeValuePair.java @@ -40,10 +40,9 @@ public boolean equals(Object o) { if (o == this) { return true; } - if (!(o instanceof TypeValuePair)) { + if (!(o instanceof TypeValuePair other)) { return false; } - TypeValuePair other = (TypeValuePair) o; boolean sourceValueEquals = (this.sourceValue == null && other.sourceValue == null) || (this.sourceValue != null && this.sourceValue.equals(other.sourceValue)); boolean targetTypeEquals = (this.targetType == null && other.targetType == null) diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/configurable/ConfigMap.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/configurable/ConfigMap.java index 36684efd0bab..933afc55a8d1 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/configurable/ConfigMap.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/configurable/ConfigMap.java @@ -26,7 +26,8 @@ * * @since 2.0.0 */ -public class ConfigMap { +public final class ConfigMap { + private static Map configurableMap = new HashMap<>(); private ConfigMap() {} diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/configurable/providers/ConfigUtils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/configurable/providers/ConfigUtils.java index f64355c5a5a6..4c559b4594cf 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/configurable/providers/ConfigUtils.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/configurable/providers/ConfigUtils.java @@ -40,7 +40,7 @@ /* * Util class that contain methods that are common for env vars, cli configuration. */ -public class ConfigUtils { +public final class ConfigUtils { private ConfigUtils() { } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/configurable/providers/cli/CliConstants.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/configurable/providers/cli/CliConstants.java index dab0f6cff317..818608a893c5 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/configurable/providers/cli/CliConstants.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/configurable/providers/cli/CliConstants.java @@ -23,7 +23,7 @@ * * @since 2.0.0 */ -public class CliConstants { +public final class CliConstants { static final String CLI_PREFIX = "-C"; diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/configurable/providers/env/EnvVarProvider.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/configurable/providers/env/EnvVarProvider.java index 63194d79965e..78cc5992c94f 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/configurable/providers/env/EnvVarProvider.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/configurable/providers/env/EnvVarProvider.java @@ -333,7 +333,7 @@ private EnvVar markAndGetEnvVar(String key, VariableKey variableKey, String valu return new EnvVar(key, value); } - public class EnvVar { + public static class EnvVar { public String key; public String value; diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/configurable/providers/toml/ConfigValueCreator.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/configurable/providers/toml/ConfigValueCreator.java index e68b45d216ff..7c2c7164b131 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/configurable/providers/toml/ConfigValueCreator.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/configurable/providers/toml/ConfigValueCreator.java @@ -195,18 +195,11 @@ private BArray getStructuredValueArray(TomlNode tomlValue, ArrayType arrayType, } private ListInitialValueEntry.ExpressionEntry[] getListEntries(TomlNode tomlValue, Type elementType) { - ListInitialValueEntry.ExpressionEntry[] entries; - switch (tomlValue.kind()) { - case ARRAY: - entries = createInitialValuesFromArrayNode((TomlArrayValueNode) tomlValue, elementType); - break; - case TABLE_ARRAY: - entries = createInitialValuesFromTableArrayNode((TomlTableArrayNode) tomlValue, elementType); - break; - default: - entries = getListEntries(((TomlKeyValueNode) tomlValue).value(), elementType); - } - return entries; + return switch (tomlValue.kind()) { + case ARRAY -> createInitialValuesFromArrayNode((TomlArrayValueNode) tomlValue, elementType); + case TABLE_ARRAY -> createInitialValuesFromTableArrayNode((TomlTableArrayNode) tomlValue, elementType); + default -> getListEntries(((TomlKeyValueNode) tomlValue).value(), elementType); + }; } private BArray createArrayFromSimpleTomlValue(TomlArrayValueNode tomlValue, ArrayType arrayType, @@ -224,27 +217,20 @@ private BArray createArrayFromSimpleTomlValue(TomlArrayValueNode tomlValue, Arra } private Object getElementValue(Type elementType, TomlNode tomlValueNode) { - Object balValue; Type refElementType = TypeUtils.getImpliedType(elementType); - switch (refElementType.getTag()) { - case TypeTags.ARRAY_TAG: + return switch (refElementType.getTag()) { + case TypeTags.ARRAY_TAG -> { ArrayType arrayType = (ArrayType) refElementType; - balValue = createArrayFromSimpleTomlValue( + yield createArrayFromSimpleTomlValue( (TomlArrayValueNode) tomlValueNode, arrayType, TypeUtils.getImpliedType(arrayType.getElementType())); - break; - case TypeTags.ANYDATA_TAG: - case TypeTags.UNION_TAG: - case TypeTags.JSON_TAG: - balValue = createUnionValue(tomlValueNode, (BUnionType) refElementType); - break; - case TypeTags.TUPLE_TAG: - balValue = createTupleValue(tomlValueNode, (TupleType) refElementType); - break; - default: - balValue = createBalValue(elementType, (TomlValueNode) tomlValueNode); - } - return balValue; + } + case TypeTags.ANYDATA_TAG, + TypeTags.UNION_TAG, + TypeTags.JSON_TAG -> createUnionValue(tomlValueNode, (BUnionType) refElementType); + case TypeTags.TUPLE_TAG -> createTupleValue(tomlValueNode, (TupleType) refElementType); + default -> createBalValue(elementType, (TomlValueNode) tomlValueNode); + }; } private BMap createRecordValue(TomlNode tomlNode, Type type) { @@ -331,23 +317,18 @@ private ListInitialValueEntry.ExpressionEntry[] createInitialValuesFromTableArra private Object createBalValue(Type type, TomlValueNode tomlValueNode) { Object tomlValue = ((TomlBasicValueNode) tomlValueNode).getValue(); - switch (TypeUtils.getImpliedType(type).getTag()) { - case TypeTags.BYTE_TAG: - return ((Long) tomlValue).intValue(); - case TypeTags.DECIMAL_TAG: - return ValueCreator.createDecimalValue(BigDecimal.valueOf((Double) tomlValue)); - case TypeTags.STRING_TAG: - return StringUtils.fromString((String) tomlValue); - case TypeTags.XML_ATTRIBUTES_TAG: - case TypeTags.XML_COMMENT_TAG: - case TypeTags.XML_ELEMENT_TAG: - case TypeTags.XML_PI_TAG: - case TypeTags.XML_TAG: - case TypeTags.XML_TEXT_TAG: - return createReadOnlyXmlValue((String) tomlValue); - default: - return tomlValue; - } + return switch (TypeUtils.getImpliedType(type).getTag()) { + case TypeTags.BYTE_TAG -> ((Long) tomlValue).intValue(); + case TypeTags.DECIMAL_TAG -> ValueCreator.createDecimalValue(BigDecimal.valueOf((Double) tomlValue)); + case TypeTags.STRING_TAG -> StringUtils.fromString((String) tomlValue); + case TypeTags.XML_ATTRIBUTES_TAG, + TypeTags.XML_COMMENT_TAG, + TypeTags.XML_ELEMENT_TAG, + TypeTags.XML_PI_TAG, + TypeTags.XML_TAG, + TypeTags.XML_TEXT_TAG -> createReadOnlyXmlValue((String) tomlValue); + default -> tomlValue; + }; } private BMap createMapValue(TomlNode tomlValue, MapType mapType) { diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/configurable/providers/toml/TomlConfigValue.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/configurable/providers/toml/TomlConfigValue.java index 95c8263e837d..2904df9439fd 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/configurable/providers/toml/TomlConfigValue.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/configurable/providers/toml/TomlConfigValue.java @@ -39,8 +39,8 @@ public TomlConfigValue(Object value, Type type) { @Override public Object getValue() { - if (value instanceof TomlNode) { - return valueCreator.createValue((TomlNode) value, type); + if (value instanceof TomlNode tomlNode) { + return valueCreator.createValue(tomlNode, type); } return value; } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/configurable/providers/toml/TomlConstants.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/configurable/providers/toml/TomlConstants.java index 1658a2b47eb6..bdd8de1bdbfc 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/configurable/providers/toml/TomlConstants.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/configurable/providers/toml/TomlConstants.java @@ -28,7 +28,8 @@ * * @since 2.0.0 */ -public class TomlConstants { +public final class TomlConstants { + public static final String CONFIG_FILE_NAME = "Config.toml"; public static final String ENV_VAR_PREFIX = "BAL_CONFIG_VAR_"; public static final String CONFIG_FILES_ENV_VARIABLE = "BAL_CONFIG_FILES"; diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/configurable/providers/toml/Utils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/configurable/providers/toml/Utils.java index feae819df6db..86d2615bc0b5 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/configurable/providers/toml/Utils.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/configurable/providers/toml/Utils.java @@ -78,7 +78,7 @@ * * @since 2.0.0 */ -public class Utils { +public final class Utils { private static final Type TYPE_READONLY_ANYDATA_INTERSECTION = new BIntersectionType(null, new Type[]{TYPE_READONLY_ANYDATA}, @@ -88,59 +88,40 @@ private Utils() { } static Object getTomlTypeString(TomlNode tomlNode) { - switch (tomlNode.kind()) { - case STRING: - return "string"; - case INTEGER: - return "int"; - case DOUBLE: - return "float"; - case BOOLEAN: - return "boolean"; - case ARRAY: - return "array"; - case TABLE: - case INLINE_TABLE: - return "record"; - case TABLE_ARRAY: - return "table"; - case KEY_VALUE: - return getTomlTypeString(((TomlKeyValueNode) tomlNode).value()); - default: - return "unsupported type"; - } + return switch (tomlNode.kind()) { + case STRING -> "string"; + case INTEGER -> "int"; + case DOUBLE -> "float"; + case BOOLEAN -> "boolean"; + case ARRAY -> "array"; + case TABLE, INLINE_TABLE -> "record"; + case TABLE_ARRAY -> "table"; + case KEY_VALUE -> getTomlTypeString(((TomlKeyValueNode) tomlNode).value()); + default -> "unsupported type"; + }; } static Object getBalValueFromToml(TomlNode tomlNode, Set visitedNodes, BUnionType unionType, Set invalidTomlLines, String variableName) { visitedNodes.add(tomlNode); - switch (tomlNode.kind()) { - case STRING: - return validateAndGetStringValue((TomlStringValueNode) tomlNode, unionType, invalidTomlLines, - variableName); - case INTEGER: - return ((TomlLongValueNode) tomlNode).getValue(); - case DOUBLE: - return validateAndGetDoubleValue((TomlDoubleValueNodeNode) tomlNode, unionType, invalidTomlLines, - variableName); - case BOOLEAN: - return ((TomlBooleanValueNode) tomlNode).getValue(); - case KEY_VALUE: - return getBalValueFromToml(((TomlKeyValueNode) tomlNode).value(), visitedNodes, unionType, - invalidTomlLines, variableName); - case ARRAY: - return getAnydataArray((TomlArrayValueNode) tomlNode, visitedNodes, invalidTomlLines, variableName); - case TABLE: - return getAnydataMap((TomlTableNode) tomlNode, visitedNodes, invalidTomlLines, variableName); - case TABLE_ARRAY: - return getMapAnydataArray((TomlTableArrayNode) tomlNode, visitedNodes, invalidTomlLines, variableName); - case INLINE_TABLE: - return getAnydataMap(((TomlInlineTableValueNode) tomlNode).toTable(), visitedNodes, invalidTomlLines, - variableName); - default: - // should not come here - return null; - } + return switch (tomlNode.kind()) { + case STRING -> validateAndGetStringValue( + (TomlStringValueNode) tomlNode, unionType, invalidTomlLines, variableName); + case INTEGER -> ((TomlLongValueNode) tomlNode).getValue(); + case DOUBLE -> validateAndGetDoubleValue( + (TomlDoubleValueNodeNode) tomlNode, unionType, invalidTomlLines, variableName); + case BOOLEAN -> ((TomlBooleanValueNode) tomlNode).getValue(); + case KEY_VALUE -> getBalValueFromToml( + ((TomlKeyValueNode) tomlNode).value(), visitedNodes, unionType, invalidTomlLines, variableName); + case ARRAY -> getAnydataArray((TomlArrayValueNode) tomlNode, visitedNodes, invalidTomlLines, variableName); + case TABLE -> getAnydataMap((TomlTableNode) tomlNode, visitedNodes, invalidTomlLines, variableName); + case TABLE_ARRAY -> getMapAnydataArray( + (TomlTableArrayNode) tomlNode, visitedNodes, invalidTomlLines, variableName); + case INLINE_TABLE -> getAnydataMap( + ((TomlInlineTableValueNode) tomlNode).toTable(), visitedNodes, invalidTomlLines, variableName); + // should not come here + default -> null; + }; } private static Object getAnydataMap(TomlTableNode tomlNode, Set visitedNodes, @@ -183,38 +164,31 @@ private static Object getMapAnydataArray(TomlTableArrayNode tomlNode, Set kind == TomlType.INTEGER; + case TypeTags.BOOLEAN_TAG -> kind == TomlType.BOOLEAN; + case TypeTags.FLOAT_TAG, + TypeTags.DECIMAL_TAG -> kind == TomlType.DOUBLE; + case TypeTags.STRING_TAG, + TypeTags.UNION_TAG, + TypeTags.XML_ATTRIBUTES_TAG, + TypeTags.XML_COMMENT_TAG, + TypeTags.XML_ELEMENT_TAG, + TypeTags.XML_PI_TAG, + TypeTags.XML_TAG, + TypeTags.XML_TEXT_TAG -> kind == TomlType.STRING; + case TypeTags.ARRAY_TAG, + TypeTags.TUPLE_TAG -> kind == TomlType.ARRAY; + case TypeTags.MAP_TAG, + TypeTags.RECORD_TYPE_TAG -> kind == TomlType.INLINE_TABLE || kind == TomlType.TABLE; + case TypeTags.TABLE_TAG -> kind == TomlType.TABLE_ARRAY || kind == TomlType.ARRAY; + case TypeTags.INTERSECTION_TAG -> { Type effectiveType = ((IntersectionType) expectedType).getEffectiveType(); - return checkEffectiveTomlType(kind, effectiveType, variableName); - default: - throw new ConfigException(CONFIG_TYPE_NOT_SUPPORTED, variableName, expectedType.toString()); - } + yield checkEffectiveTomlType(kind, effectiveType, variableName); + } + default -> throw new ConfigException(CONFIG_TYPE_NOT_SUPPORTED, variableName, expectedType.toString()); + }; } static boolean isSimpleType(int typeTag) { @@ -241,31 +215,23 @@ static LineRange getOneBasedLineRange(LineRange lineRange) { } public static Type getTypeFromTomlValue(TomlNode tomlNode) { - switch (tomlNode.kind()) { - case STRING: - return PredefinedTypes.TYPE_STRING; - case INTEGER: - return PredefinedTypes.TYPE_INT; - case DOUBLE: - return PredefinedTypes.TYPE_FLOAT; - case BOOLEAN: - return PredefinedTypes.TYPE_BOOLEAN; - case KEY_VALUE: - return getTypeFromTomlValue(((TomlKeyValueNode) tomlNode).value()); - case ARRAY: + return switch (tomlNode.kind()) { + case STRING -> PredefinedTypes.TYPE_STRING; + case INTEGER -> PredefinedTypes.TYPE_INT; + case DOUBLE -> PredefinedTypes.TYPE_FLOAT; + case BOOLEAN -> PredefinedTypes.TYPE_BOOLEAN; + case KEY_VALUE -> getTypeFromTomlValue(((TomlKeyValueNode) tomlNode).value()); + case ARRAY -> { if (containsInlineTable((TomlArrayValueNode) tomlNode)) { - return TypeCreator.createArrayType(TypeCreator.createMapType(TYPE_ANYDATA), true); + yield TypeCreator.createArrayType(TypeCreator.createMapType(TYPE_ANYDATA), true); } - return TypeCreator.createArrayType(TYPE_ANYDATA, true); - case TABLE: - case INLINE_TABLE: - return TypeCreator.createMapType(TYPE_ANYDATA, true); - case TABLE_ARRAY: - return TypeCreator.createArrayType(TypeCreator.createMapType(TYPE_ANYDATA), true); - default: - // should not come here - return null; - } + yield TypeCreator.createArrayType(TYPE_ANYDATA, true); + } + case TABLE, INLINE_TABLE -> TypeCreator.createMapType(TYPE_ANYDATA, true); + case TABLE_ARRAY -> TypeCreator.createArrayType(TypeCreator.createMapType(TYPE_ANYDATA), true); + // should not come here + default -> null; + }; } private static boolean containsInlineTable(TomlArrayValueNode tomlNode) { @@ -385,14 +351,11 @@ static boolean isXMLType(Type type) { } static Type getEffectiveType(Type type) { - switch (type.getTag()) { - case TypeTags.INTERSECTION_TAG: - return ((IntersectionType) type).getEffectiveType(); - case TypeTags.TYPE_REFERENCED_TYPE_TAG: - return getEffectiveType(((ReferenceType) type).getReferredType()); - default: - return type; - } + return switch (type.getTag()) { + case TypeTags.INTERSECTION_TAG -> ((IntersectionType) type).getEffectiveType(); + case TypeTags.TYPE_REFERENCED_TYPE_TAG -> getEffectiveType(((ReferenceType) type).getReferredType()); + default -> type; + }; } private static boolean isMappingType(int typeTag) { @@ -412,23 +375,17 @@ public static Object getFiniteBalValue(TomlNode tomlNode, Set visitedN BFiniteType finiteType, Set invalidTomlLines, String variableName) { visitedNodes.add(tomlNode); - switch (tomlNode.kind()) { - case STRING: - return StringUtils.fromString(((TomlStringValueNode) tomlNode).getValue()); - case INTEGER: - return ((TomlLongValueNode) tomlNode).getValue(); - case DOUBLE: - return validateAndGetFiniteDoubleValue((TomlDoubleValueNodeNode) tomlNode, finiteType, invalidTomlLines, - variableName); - case BOOLEAN: - return ((TomlBooleanValueNode) tomlNode).getValue(); - case KEY_VALUE: - return getFiniteBalValue(((TomlKeyValueNode) tomlNode).value(), visitedNodes, finiteType, - invalidTomlLines, variableName); - default: - // should not come here - return null; - } + return switch (tomlNode.kind()) { + case STRING -> StringUtils.fromString(((TomlStringValueNode) tomlNode).getValue()); + case INTEGER -> ((TomlLongValueNode) tomlNode).getValue(); + case DOUBLE -> validateAndGetFiniteDoubleValue( + (TomlDoubleValueNodeNode) tomlNode, finiteType, invalidTomlLines, variableName); + case BOOLEAN -> ((TomlBooleanValueNode) tomlNode).getValue(); + case KEY_VALUE -> getFiniteBalValue( + ((TomlKeyValueNode) tomlNode).value(), visitedNodes, finiteType, invalidTomlLines, variableName); + // should not come here + default -> null; + }; } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/errors/ErrorHelper.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/errors/ErrorHelper.java index ae1fa77d9947..f28cbc6167a5 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/errors/ErrorHelper.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/errors/ErrorHelper.java @@ -36,7 +36,7 @@ * * @since 2201.7.0 */ -public class ErrorHelper { +public final class ErrorHelper { private static final ResourceBundle messageBundle = ResourceBundle.getBundle("MessagesBundle", Locale.getDefault()); private static final BString ERROR_MESSAGE_FIELD = StringUtils.fromString("message"); @@ -53,7 +53,8 @@ public static BError getRuntimeException(BString reason, ErrorCodes errorCodes, MappingInitialValueEntry[] initialValues = new MappingInitialValueEntry[1]; initialValues[0] = new MappingInitialValueEntry.KeyValueEntry(ERROR_MESSAGE_FIELD, StringUtils .fromString(MessageFormat.format(messageBundle.getString(errorCodes.messageKey()), params))); - MapValueImpl errorDetail = new MapValueImpl(PredefinedTypes.TYPE_ERROR_DETAIL, initialValues); + MapValueImpl errorDetail = + new MapValueImpl<>(PredefinedTypes.TYPE_ERROR_DETAIL, initialValues); return ErrorCreator.createError(reason, errorDetail); } @@ -67,7 +68,7 @@ public static BMap getErrorDetails(ErrorCodes errorCodes, Objec initialValues[0] = new MappingInitialValueEntry.KeyValueEntry(ERROR_MESSAGE_FIELD, StringUtils.fromString(MessageFormat.format(messageBundle.getString( errorCodes.messageKey()), params))); - return new MapValueImpl(PredefinedTypes.TYPE_ERROR_DETAIL, initialValues); + return new MapValueImpl<>(PredefinedTypes.TYPE_ERROR_DETAIL, initialValues); } public static BString getErrorMessage(String messageFormat, Object... params) { @@ -97,10 +98,10 @@ public static void handleXMLException(String operation, Throwable e) { } private static boolean isBErrorWithMessageDetail(Throwable e) { - if (!(e instanceof BError)) { + if (!(e instanceof BError error)) { return false; } - return hasMessageDetail((BError) e); + return hasMessageDetail(error); } public static boolean hasMessageDetail(BError bError) { diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/errors/ErrorReasons.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/errors/ErrorReasons.java index ed8e8f0540f5..ef56be56c717 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/errors/ErrorReasons.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/errors/ErrorReasons.java @@ -35,7 +35,7 @@ * * @since 0.990.0 */ -public class ErrorReasons { +public final class ErrorReasons { private ErrorReasons() {} diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/launch/LaunchUtils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/launch/LaunchUtils.java index 8ecd1a6d728c..da78817910b3 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/launch/LaunchUtils.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/launch/LaunchUtils.java @@ -59,7 +59,7 @@ * * @since 1.0 */ -public class LaunchUtils { +public final class LaunchUtils { private static final PrintStream outStream = System.out; diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/regexp/RegExpFactory.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/regexp/RegExpFactory.java index 7198f608b69c..fae1ba5c768a 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/regexp/RegExpFactory.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/regexp/RegExpFactory.java @@ -43,7 +43,7 @@ * * @since 2201.3.0 */ -public class RegExpFactory { +public final class RegExpFactory { private RegExpFactory() { } @@ -137,10 +137,9 @@ public static RegExpValue translateRegExpConstructs(RegExpValue regExpValue) { disjunction = getNonCapturingGroupDisjunction(); } for (Object s : disjunction.getRegExpSeqList()) { - if (!(s instanceof RegExpSequence)) { + if (!(s instanceof RegExpSequence seq)) { continue; } - RegExpSequence seq = (RegExpSequence) s; translateRegExpTerms(seq.getRegExpTermsList()); } return new RegExpValue(disjunction); @@ -159,15 +158,14 @@ private static RegExpDisjunction getNonCapturingGroupDisjunction() { private static void translateRegExpTerms(RegExpTerm[] terms) { for (RegExpTerm t : terms) { - if (!(t instanceof RegExpAtomQuantifier)) { + if (!(t instanceof RegExpAtomQuantifier atomQuantifier)) { continue; } - RegExpAtomQuantifier atomQuantifier = (RegExpAtomQuantifier) t; Object reAtom = atomQuantifier.getReAtom(); - if (reAtom instanceof RegExpLiteralCharOrEscape) { - atomQuantifier.setReAtom(translateLiteralCharOrEscape((RegExpLiteralCharOrEscape) reAtom)); - } else if (reAtom instanceof RegExpCharacterClass) { - atomQuantifier.setReAtom(translateCharacterClass((RegExpCharacterClass) reAtom)); + if (reAtom instanceof RegExpLiteralCharOrEscape regExpLiteralCharOrEscape) { + atomQuantifier.setReAtom(translateLiteralCharOrEscape(regExpLiteralCharOrEscape)); + } else if (reAtom instanceof RegExpCharacterClass regExpCharacterClass) { + atomQuantifier.setReAtom(translateCharacterClass(regExpCharacterClass)); } } } @@ -206,8 +204,7 @@ private static RegExpAtom translateCharacterClass(RegExpCharacterClass charClass int c = charAtoms.length; for (int i = 0; i < c; i++) { Object charAtom = charAtoms[i]; - if (charAtom instanceof RegExpCharSetRange) { - RegExpCharSetRange range = (RegExpCharSetRange) charAtom; + if (charAtom instanceof RegExpCharSetRange range) { range.setLhsCharSetAtom(translateCharInCharacterClass(range.getLhsCharSetAtom())); range.setRhsCharSetAom(translateCharInCharacterClass(range.getRhsCharSetAtom())); continue; @@ -220,10 +217,10 @@ private static RegExpAtom translateCharacterClass(RegExpCharacterClass charClass } private static Object translateVisitor(Object node) { - if (node instanceof RegExpLiteralCharOrEscape) { - return translateLiteralCharOrEscape((RegExpLiteralCharOrEscape) node); - } else if (node instanceof String) { - return translateCharInCharacterClass((String) node); + if (node instanceof RegExpLiteralCharOrEscape regExpLiteralCharOrEscape) { + return translateLiteralCharOrEscape(regExpLiteralCharOrEscape); + } else if (node instanceof String s) { + return translateCharInCharacterClass(s); } return node; } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/regexp/Terminals.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/regexp/Terminals.java index bff37ce9a593..7af7ba636eb4 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/regexp/Terminals.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/regexp/Terminals.java @@ -22,7 +22,8 @@ * * @since 2201.3.0 */ -public class Terminals { +public final class Terminals { + public static final char MINUS = '-'; public static final char BACKSLASH = '\\'; public static final char BITWISE_XOR = '^'; diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/regexp/TreeBuilder.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/regexp/TreeBuilder.java index c42e26cdc6c8..dfc830b92229 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/regexp/TreeBuilder.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/regexp/TreeBuilder.java @@ -114,33 +114,23 @@ private RegExpTerm readRegTerm() { return readRegAssertion(); } - RegExpAtom reAtom; - switch (nextToken.kind) { - case RE_LITERAL_CHAR: - case RE_NUMERIC_ESCAPE: - case RE_CONTROL_ESCAPE: - case COMMA_TOKEN: - case DOT_TOKEN: - case DIGIT: - case MINUS_TOKEN: - case COLON_TOKEN: - reAtom = readRegChars(); - break; - case BACK_SLASH_TOKEN: - reAtom = readRegEscapeChar(); - break; - case OPEN_BRACKET_TOKEN: - reAtom = readRegCharacterClass(); - break; - case OPEN_PAREN_TOKEN: - reAtom = readRegCapturingGroups(); - break; - default: - // Here the token is a syntax char, which is invalid. Syntax char tokens should be - // proceeded by backslashes. - throw ErrorCreator.createError(ErrorHelper.getErrorMessage( - ErrorCodes.REGEXP_MISSING_BACKSLASH.messageKey(), nextToken.value)); - } + RegExpAtom reAtom = switch (nextToken.kind) { + case RE_LITERAL_CHAR, + RE_NUMERIC_ESCAPE, + RE_CONTROL_ESCAPE, + COMMA_TOKEN, + DOT_TOKEN, + DIGIT, + MINUS_TOKEN, + COLON_TOKEN -> readRegChars(); + case BACK_SLASH_TOKEN -> readRegEscapeChar(); + case OPEN_BRACKET_TOKEN -> readRegCharacterClass(); + case OPEN_PAREN_TOKEN -> readRegCapturingGroups(); + // Here the token is a syntax char, which is invalid. Syntax char tokens should be + // proceeded by backslashes. + default -> throw ErrorCreator.createError(ErrorHelper.getErrorMessage( + ErrorCodes.REGEXP_MISSING_BACKSLASH.messageKey(), nextToken.value)); + }; RegExpQuantifier quantifier = readOptionalQuantifier(); if (quantifier == null) { @@ -164,31 +154,30 @@ private RegExpLiteralCharOrEscape readRegEscapeChar() { private String readRegEscape(Token backSlash) { Token nextToken = peek(); - switch (nextToken.kind) { - case RE_PROPERTY: - return readRegUnicodePropertyEscape(backSlash.value); - case BITWISE_XOR_TOKEN: - case DOLLAR_TOKEN: - case BACK_SLASH_TOKEN: - case DOT_TOKEN: - case ASTERISK_TOKEN: - case PLUS_TOKEN: - case QUESTION_MARK_TOKEN: - case OPEN_PAREN_TOKEN: - case CLOSE_PAREN_TOKEN: - case OPEN_BRACKET_TOKEN: - case CLOSE_BRACKET_TOKEN: - case OPEN_BRACE_TOKEN: - case CLOSE_BRACE_TOKEN: - case PIPE_TOKEN: - return readRegQuoteEscape(backSlash.value); - default: + return switch (nextToken.kind) { + case RE_PROPERTY -> readRegUnicodePropertyEscape(backSlash.value); + case BITWISE_XOR_TOKEN, + DOLLAR_TOKEN, + BACK_SLASH_TOKEN, + DOT_TOKEN, + ASTERISK_TOKEN, + PLUS_TOKEN, + QUESTION_MARK_TOKEN, + OPEN_PAREN_TOKEN, + CLOSE_PAREN_TOKEN, + OPEN_BRACKET_TOKEN, + CLOSE_BRACKET_TOKEN, + OPEN_BRACE_TOKEN, + CLOSE_BRACE_TOKEN, + PIPE_TOKEN -> readRegQuoteEscape(backSlash.value); + default -> { if (isReSimpleCharClassCode(nextToken)) { - return readRegSimpleCharClassEscape(backSlash.value); + yield readRegSimpleCharClassEscape(backSlash.value); } throw ErrorCreator.createError(ErrorHelper.getErrorMessage( ErrorCodes.REGEXP_INVALID_CHAR_AFTER_BACKSLASH.messageKey(), nextToken.value)); - } + } + }; } /** @@ -434,15 +423,10 @@ private String readCharacterClassEnd() { private RegExpQuantifier readOptionalQuantifier() { Token nextToken = peek(); - switch (nextToken.kind) { - case QUESTION_MARK_TOKEN: - case ASTERISK_TOKEN: - case PLUS_TOKEN: - case OPEN_BRACE_TOKEN: - return readReQuantifier(); - default: - return null; - } + return switch (nextToken.kind) { + case QUESTION_MARK_TOKEN, ASTERISK_TOKEN, PLUS_TOKEN, OPEN_BRACE_TOKEN -> readReQuantifier(); + default -> null; + }; } private RegExpQuantifier readReQuantifier() { @@ -562,45 +546,31 @@ private String readCloseParenthesis() { } private boolean isEndOfReDisjunction(TokenKind kind) { - switch (kind) { - case EOF_TOKEN: - case CLOSE_PAREN_TOKEN: - return true; - default: - return false; - } + return switch (kind) { + case EOF_TOKEN, CLOSE_PAREN_TOKEN -> true; + default -> false; + }; } private boolean isEndOfReSequence(TokenKind kind) { - switch (kind) { - case EOF_TOKEN: - case PIPE_TOKEN: - case CLOSE_PAREN_TOKEN: - return true; - default: - return false; - } + return switch (kind) { + case EOF_TOKEN, PIPE_TOKEN, CLOSE_PAREN_TOKEN -> true; + default -> false; + }; } private boolean isCharacterClassEnd(TokenKind kind) { - switch (kind) { - case EOF_TOKEN: - case CLOSE_BRACKET_TOKEN: - return true; - default: - return false; - } + return switch (kind) { + case EOF_TOKEN, CLOSE_BRACKET_TOKEN -> true; + default -> false; + }; } private boolean isReCharSetLiteralChar(String tokenText) { - switch (tokenText) { - case "\\": - case "-": - case "]": - return false; - default: - return true; - } + return switch (tokenText) { + case "\\", "-", "]" -> false; + default -> true; + }; } private boolean isEndOfFlagExpression(TokenKind kind) { @@ -612,15 +582,11 @@ private boolean isEndOfReFlags(TokenKind kind) { } private boolean isEndOfDigits(TokenKind kind, boolean isLeastDigits) { - switch (kind) { - case CLOSE_BRACE_TOKEN: - case EOF_TOKEN: - return true; - case COMMA_TOKEN: - return isLeastDigits; - default: - return false; - } + return switch (kind) { + case CLOSE_BRACE_TOKEN, EOF_TOKEN -> true; + case COMMA_TOKEN -> isLeastDigits; + default -> false; + }; } static boolean isIncorrectCharRange(String lhsValue, String rhsValue) { @@ -634,32 +600,20 @@ static boolean isReSimpleCharClassCode(Token token) { if (token.kind != TokenKind.RE_LITERAL_CHAR) { return false; } - switch (token.value) { - case "d": - case "D": - case "s": - case "S": - case "w": - case "W": - return true; - default: - return false; - } + return switch (token.value) { + case "d", "D", "s", "S", "w", "W" -> true; + default -> false; + }; } static boolean isReFlag(Token nextToken) { if (nextToken.kind != TokenKind.RE_LITERAL_CHAR) { return false; } - switch (nextToken.value) { - case "m": - case "s": - case "i": - case "x": - return true; - default: - return false; - } + return switch (nextToken.value) { + case "m", "s", "i", "x" -> true; + default -> false; + }; } private BString getErrorMsg(Token nextToken) { diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/regexp/TreeTraverser.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/regexp/TreeTraverser.java index 599be7f5775c..4a7bdfbcaca3 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/regexp/TreeTraverser.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/regexp/TreeTraverser.java @@ -41,18 +41,14 @@ public TreeTraverser(CharReader charReader) { } public Token nextToken() { - switch (this.mode) { - case RE_DISJUNCTION: - return readTokenInReDisjunction(); - case RE_UNICODE_PROP_ESCAPE: - case RE_UNICODE_GENERAL_CATEGORY_NAME: - return readTokenInReUnicodePropertyEscape(); - case RE_UNICODE_PROPERTY_VALUE: - return readTokenInReUnicodePropertyValue(); - default: - // Should not reach here. - return null; - } + return switch (this.mode) { + case RE_DISJUNCTION -> readTokenInReDisjunction(); + case RE_UNICODE_PROP_ESCAPE, + RE_UNICODE_GENERAL_CATEGORY_NAME -> readTokenInReUnicodePropertyEscape(); + case RE_UNICODE_PROPERTY_VALUE -> readTokenInReUnicodePropertyValue(); + // Should not reach here. + default -> null; + }; } /** @@ -81,47 +77,31 @@ private Token readTokenInReDisjunction() { int nextChar = peek(); this.reader.advance(); - switch (nextChar) { - case Terminals.BITWISE_XOR: - return getRegExpToken(TokenKind.BITWISE_XOR_TOKEN); - case Terminals.DOLLAR: - return getRegExpToken(TokenKind.DOLLAR_TOKEN); - case Terminals.DOT: - return getRegExpToken(TokenKind.DOT_TOKEN); - case Terminals.ASTERISK: - return getRegExpToken(TokenKind.ASTERISK_TOKEN); - case Terminals.PLUS: - return getRegExpToken(TokenKind.PLUS_TOKEN); - case Terminals.QUESTION_MARK: - return getRegExpToken(TokenKind.QUESTION_MARK_TOKEN); - case Terminals.BACKSLASH: - return processEscape(); - case Terminals.OPEN_BRACKET: - return getRegExpToken(TokenKind.OPEN_BRACKET_TOKEN); - case Terminals.CLOSE_BRACKET: - return getRegExpToken(TokenKind.CLOSE_BRACKET_TOKEN); - case Terminals.OPEN_BRACE: - return getRegExpToken(TokenKind.OPEN_BRACE_TOKEN); - case Terminals.CLOSE_BRACE: - return getRegExpToken(TokenKind.CLOSE_BRACE_TOKEN); - case Terminals.OPEN_PARENTHESIS: - return getRegExpToken(TokenKind.OPEN_PAREN_TOKEN); - case Terminals.CLOSE_PARENTHESIS: - return getRegExpToken(TokenKind.CLOSE_PAREN_TOKEN); - case Terminals.COMMA: - return getRegExpToken(TokenKind.COMMA_TOKEN); - case Terminals.MINUS: - return getRegExpToken(TokenKind.MINUS_TOKEN); - case Terminals.COLON: - return getRegExpToken(TokenKind.COLON_TOKEN); - case Terminals.PIPE: - return getRegExpToken(TokenKind.PIPE_TOKEN); - default: + return switch (nextChar) { + case Terminals.BITWISE_XOR -> getRegExpToken(TokenKind.BITWISE_XOR_TOKEN); + case Terminals.DOLLAR -> getRegExpToken(TokenKind.DOLLAR_TOKEN); + case Terminals.DOT -> getRegExpToken(TokenKind.DOT_TOKEN); + case Terminals.ASTERISK -> getRegExpToken(TokenKind.ASTERISK_TOKEN); + case Terminals.PLUS -> getRegExpToken(TokenKind.PLUS_TOKEN); + case Terminals.QUESTION_MARK -> getRegExpToken(TokenKind.QUESTION_MARK_TOKEN); + case Terminals.BACKSLASH -> processEscape(); + case Terminals.OPEN_BRACKET -> getRegExpToken(TokenKind.OPEN_BRACKET_TOKEN); + case Terminals.CLOSE_BRACKET -> getRegExpToken(TokenKind.CLOSE_BRACKET_TOKEN); + case Terminals.OPEN_BRACE -> getRegExpToken(TokenKind.OPEN_BRACE_TOKEN); + case Terminals.CLOSE_BRACE -> getRegExpToken(TokenKind.CLOSE_BRACE_TOKEN); + case Terminals.OPEN_PARENTHESIS -> getRegExpToken(TokenKind.OPEN_PAREN_TOKEN); + case Terminals.CLOSE_PARENTHESIS -> getRegExpToken(TokenKind.CLOSE_PAREN_TOKEN); + case Terminals.COMMA -> getRegExpToken(TokenKind.COMMA_TOKEN); + case Terminals.MINUS -> getRegExpToken(TokenKind.MINUS_TOKEN); + case Terminals.COLON -> getRegExpToken(TokenKind.COLON_TOKEN); + case Terminals.PIPE -> getRegExpToken(TokenKind.PIPE_TOKEN); + default -> { if (isDigit(nextChar)) { - return getRegExpText(TokenKind.DIGIT); + yield getRegExpText(TokenKind.DIGIT); } - return getRegExpText(TokenKind.RE_LITERAL_CHAR); - } + yield getRegExpText(TokenKind.RE_LITERAL_CHAR); + } + }; } /** @@ -496,25 +476,10 @@ public void endMode() { * @return true, if the character is ReSyntaxChar. false otherwise. */ private static boolean isReSyntaxChar(int c) { - switch (c) { - case '^': - case '$': - case '\\': - case '.': - case '*': - case '+': - case '?': - case '(': - case ')': - case '[': - case ']': - case '{': - case '}': - case '|': - return true; - default: - return false; - } + return switch (c) { + case '^', '$', '\\', '.', '*', '+', '?', '(', ')', '[', ']', '{', '}', '|' -> true; + default -> false; + }; } /** @@ -528,17 +493,10 @@ private static boolean isReSyntaxChar(int c) { * @return true, if the character is ReSimpleCharClassCode. false otherwise. */ private static boolean isReSimpleCharClassCode(int c) { - switch (c) { - case 'd': - case 'D': - case 's': - case 'S': - case 'w': - case 'W': - return true; - default: - return false; - } + return switch (c) { + case 'd', 'D', 's', 'S', 'w', 'W' -> true; + default -> false; + }; } private static boolean isHexDigit(int c) { diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/AsyncUtils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/AsyncUtils.java index ead9ae63867b..945f60e47513 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/AsyncUtils.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/AsyncUtils.java @@ -45,6 +45,7 @@ import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; @@ -52,7 +53,7 @@ /** * Util functions for async invocations. */ -public class AsyncUtils { +public final class AsyncUtils { /** * Block the current strand to execute asynchronously. @@ -80,7 +81,7 @@ public static CompletableFuture markAsync() { * @param scheduler The scheduler for invoking functions * @return Future Value */ - public static FutureValue invokeFunctionPointerAsync(BFunctionPointer func, String strandName, + public static FutureValue invokeFunctionPointerAsync(BFunctionPointer func, String strandName, StrandMetadata metadata, Object[] args, Function resultHandleFunction, Scheduler scheduler) { @@ -129,7 +130,7 @@ public void notifyFailure(BError error) { * @param returnValueSupplier Suppler used to set the final return value for the parent function invocation. * @param scheduler The scheduler for invoking functions */ - public static void invokeFunctionPointerAsyncIteratively(BFunctionPointer func, String strandName, + public static void invokeFunctionPointerAsyncIteratively(BFunctionPointer func, String strandName, StrandMetadata metadata, int noOfIterations, Supplier argsSupplier, Consumer futureResultConsumer, @@ -215,7 +216,7 @@ private static void callDefaultValueFunction(Scheduler scheduler, Callback callb List argsWithDefaultValues, Parameter parameter) { String funcName = parameter.defaultFunctionName; - Function defaultFunc = o -> valueCreator.call((Strand) (((Object[]) o)[0]), funcName, + Function defaultFunc = o -> valueCreator.call((Strand) (((Object[]) o)[0]), funcName, argsWithDefaultValues.toArray()); Callback defaultFunctionCallback = new Callback() { @Override @@ -253,7 +254,7 @@ private static MethodType getObjectMethodType(String methodName, ObjectType obje return methodTypesMap.get(methodName); } - private static void scheduleNextFunction(BFunctionPointer func, BFunctionType funcType, Strand parent, + private static void scheduleNextFunction(BFunctionPointer func, BFunctionType funcType, Strand parent, String strandName, StrandMetadata metadata, int noOfIterations, AtomicInteger callCount, Supplier argsSupplier, Consumer futureResultConsumer, @@ -288,7 +289,7 @@ public void notifyFailure(BError error) { }, argsSupplier.get()); } - private static void invokeFunctionPointerAsync(BFunctionPointer func, Strand parent, + private static void invokeFunctionPointerAsync(BFunctionPointer func, Strand parent, FutureValue future, Object[] args, AsyncFunctionCallback callback, Scheduler scheduler) { future.callback = callback; @@ -312,7 +313,7 @@ private static void handleRuntimeErrors(Strand parent, BError error) { parent.scheduler.unblockStrand(parent); } - private static class Unblocker implements java.util.function.BiConsumer { + private static class Unblocker implements BiConsumer { private final Strand strand; diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/ItemGroup.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/ItemGroup.java index 5ad72bfd838f..4e67edd384fb 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/ItemGroup.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/ItemGroup.java @@ -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; @@ -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 items = new Stack<>(); + Deque items = new ArrayDeque<>(); /** * Indicates this item is already in runnable list/executing or not. diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/RuntimeRegistry.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/RuntimeRegistry.java index c490d9cf7efd..1b916ae629df 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/RuntimeRegistry.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/RuntimeRegistry.java @@ -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; @@ -43,7 +44,7 @@ public class RuntimeRegistry { private final Scheduler scheduler; private final Set listenerSet = ConcurrentHashMap.newKeySet(); - private final Stack> stopHandlerStack = new Stack<>(); + private final Deque> stopHandlerStack = new ConcurrentLinkedDeque<>(); private static final PrintStream outStream = System.err; @@ -63,7 +64,7 @@ public synchronized void deregisterListener(BObject listener) { } } - public synchronized void registerStopHandler(BFunctionPointer stopHandler) { + public synchronized void registerStopHandler(BFunctionPointer stopHandler) { stopHandlerStack.push(stopHandler); } @@ -78,7 +79,7 @@ private synchronized void invokeListenerGracefulStop(Strand strand, Scheduler sc if (iterator.hasNext()) { ListenerCallback callback = new ListenerCallback(strand, scheduler, iterator); BObject listener = iterator.next(); - Function func = o -> listener.call((Strand) ((Object[]) o)[0], "gracefulStop"); + Function func = o -> listener.call((Strand) (o)[0], "gracefulStop"); scheduler.schedule(new Object[1], func, null, callback, null, null, null, strand.getMetadata()); } else { @@ -90,7 +91,7 @@ private synchronized void invokeStopHandlerFunction(Strand strand, Scheduler sch if (stopHandlerStack.isEmpty()) { return; } - BFunctionPointer bFunctionPointer = stopHandlerStack.pop(); + BFunctionPointer bFunctionPointer = stopHandlerStack.pop(); StopHandlerCallback callback = new StopHandlerCallback(strand, scheduler); final FutureValue future = scheduler.createFuture(strand, callback, null, ((BFunctionType) TypeUtils.getImpliedType(bFunctionPointer.getType())).retType, null, diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/Scheduler.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/Scheduler.java index 112832b002bf..699ed781a833 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/Scheduler.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/Scheduler.java @@ -136,12 +136,14 @@ public static Map getCurrentStrands() { * @param metadata meta data of new strand * @return {@link FutureValue} reference to the given function pointer invocation. */ - public FutureValue scheduleFunction(Object[] params, BFunctionPointer fp, Strand parent, Type returnType, + public FutureValue scheduleFunction(Object[] params, + BFunctionPointer fp, Strand parent, Type returnType, String strandName, StrandMetadata metadata) { return schedule(params, fp.getFunction(), parent, null, null, returnType, strandName, metadata); } - public FutureValue scheduleFunction(Object[] params, BFunctionPointer fp, Strand parent, Type returnType, + public FutureValue scheduleFunction(Object[] params, + BFunctionPointer fp, Strand parent, Type returnType, String strandName, StrandMetadata metadata , Callback callback) { return schedule(params, fp.getFunction(), parent, callback, null, returnType, strandName, metadata); } @@ -157,13 +159,14 @@ public FutureValue scheduleFunction(Object[] params, BFunctionPointer fp, * @param metadata meta data of new strand * @return {@link FutureValue} reference to the given function invocation. */ - public FutureValue scheduleLocal(Object[] params, BFunctionPointer fp, Strand parent, Type returnType, + public FutureValue scheduleLocal(Object[] params, BFunctionPointer fp, Strand parent, Type returnType, String strandName, StrandMetadata metadata) { FutureValue future = createFuture(parent, null, null, returnType, strandName, metadata); return scheduleLocal(params, fp, parent, future); } - public FutureValue scheduleLocal(Object[] params, BFunctionPointer fp, Strand parent, FutureValue future) { + public FutureValue scheduleLocal(Object[] params, BFunctionPointer fp, + Strand parent, FutureValue future) { params[0] = future.strand; SchedulerItem item = new SchedulerItem(fp.getFunction(), params, future); future.strand.schedulerItem = item; @@ -173,14 +176,15 @@ public FutureValue scheduleLocal(Object[] params, BFunctionPointer fp, Str return future; } - public FutureValue scheduleToObjectGroup(Object[] params, Function function, Strand parent, + public FutureValue scheduleToObjectGroup(Object[] params, Function function, Strand parent, Callback callback, Map properties, Type returnType, String strandName, StrandMetadata metadata) { FutureValue future = createFuture(parent, callback, properties, returnType, strandName, metadata); return scheduleToObjectGroup(params, function, future); } - public FutureValue scheduleToObjectGroup(Object[] params, Function function, FutureValue future) { + public FutureValue scheduleToObjectGroup(Object[] params, Function function, + FutureValue future) { params[0] = future.strand; SchedulerItem item = new SchedulerItem(function, params, future); future.strand.schedulerItem = item; @@ -204,7 +208,7 @@ public FutureValue scheduleToObjectGroup(Object[] params, Function function, Fut * @param metadata meta data of new strand * @return Reference to the scheduled task */ - public FutureValue schedule(Object[] params, Function function, Strand parent, Callback callback, + public FutureValue schedule(Object[] params, Function function, Strand parent, Callback callback, Map properties, Type returnType, String strandName, StrandMetadata metadata) { FutureValue future = createFuture(parent, callback, properties, returnType, strandName, metadata); @@ -222,13 +226,13 @@ public FutureValue schedule(Object[] params, Function function, Strand parent, C * @param metadata meta data of new strand * @return Reference to the scheduled task */ - public FutureValue schedule(Object[] params, Function function, Strand parent, Callback callback, + public FutureValue schedule(Object[] params, Function function, Strand parent, Callback callback, String strandName, StrandMetadata metadata) { FutureValue future = createFuture(parent, callback, null, PredefinedTypes.TYPE_NULL, strandName, metadata); return schedule(params, function, future); } - public FutureValue schedule(Object[] params, Function function, FutureValue future) { + public FutureValue schedule(Object[] params, Function function, FutureValue future) { params[0] = future.strand; SchedulerItem item = new SchedulerItem(function, params, future); future.strand.schedulerItem = item; @@ -252,7 +256,7 @@ public FutureValue schedule(Object[] params, Function function, FutureValue futu * @return Reference to the scheduled task */ @Deprecated - public FutureValue schedule(Object[] params, Consumer consumer, Strand parent, Callback callback, + public FutureValue schedule(Object[] params, Consumer consumer, Strand parent, Callback callback, String strandName, StrandMetadata metadata) { FutureValue future = createFuture(parent, callback, null, PredefinedTypes.TYPE_NULL, strandName, metadata); params[0] = future.strand; @@ -335,7 +339,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(); diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/SchedulerItem.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/SchedulerItem.java index 88b21e0f71a0..f8bbbded6d16 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/SchedulerItem.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/SchedulerItem.java @@ -29,19 +29,19 @@ * @since 0.995.0 */ class SchedulerItem { - private Function function; + private Function function; private Object[] params; final FutureValue future; boolean parked; - public SchedulerItem(Function function, Object[] params, FutureValue future) { + public SchedulerItem(Function function, Object[] params, FutureValue future) { this.future = future; this.function = function; this.params = params; } @Deprecated - public SchedulerItem(Consumer consumer, Object[] params, FutureValue future) { + public SchedulerItem(Consumer consumer, Object[] params, FutureValue future) { this.future = future; this.function = val -> { consumer.accept(val); diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/State.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/State.java index 7f9d1d1c0628..fa88e1592eb7 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/State.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/State.java @@ -1,4 +1,4 @@ - /* +/* * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, @@ -17,25 +17,25 @@ */ package io.ballerina.runtime.internal.scheduling; - /** - * Maintains the Strand state. - * - * @since 1.0.0 - */ - public enum State { - RUNNABLE(1), - YIELD(1 << 1), - BLOCK_AND_YIELD(YIELD.status | (1 << 2)), - BLOCK_ON_AND_YIELD(BLOCK_AND_YIELD.status | (1 << 3)), - DONE(1 << 4); +/** + * Maintains the Strand state. + * + * @since 1.0.0 + */ +public enum State { + RUNNABLE(1), + YIELD(1 << 1), + BLOCK_AND_YIELD(YIELD.status | (1 << 2)), + BLOCK_ON_AND_YIELD(BLOCK_AND_YIELD.status | (1 << 3)), + DONE(1 << 4); - private final int status; + private final int status; - public int getStatus() { - return status; - } + public int getStatus() { + return status; + } - State(int status) { - this.status = status; - } - } + State(int status) { + this.status = status; + } +} diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/Strand.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/Strand.java index df347a897fef..0e9e972752a4 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/Strand.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/Strand.java @@ -164,11 +164,10 @@ private TransactionLocalContext createTrxContextBranch(TransactionLocalContext c } public void handleChannelError(ChannelDetails[] channels, ErrorValue error) { - for (int i = 0; i < channels.length; i++) { - ChannelDetails channelDetails = channels[i]; + for (ChannelDetails channelDetails : channels) { WorkerDataChannel channel = getWorkerDataChannel(channelDetails); - if (channels[i].send) { + if (channelDetails.send) { channel.setSendError(error); } else { channel.setReceiveError(error); diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/WaitAnyContext.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/WaitAnyContext.java index 4fa14cbda8fb..750d3540b4b4 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/WaitAnyContext.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/WaitAnyContext.java @@ -1,47 +1,47 @@ - /* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - package io.ballerina.runtime.internal.scheduling; +/* + * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package io.ballerina.runtime.internal.scheduling; - import io.ballerina.runtime.api.PredefinedTypes; - import io.ballerina.runtime.internal.TypeChecker; +import io.ballerina.runtime.api.PredefinedTypes; +import io.ballerina.runtime.internal.TypeChecker; - /** - * WaitContext for Wait for any action. - * - * @since 1.0.0 - */ - public class WaitAnyContext extends WaitContext { +/** + * WaitContext for Wait for any action. + * + * @since 1.0.0 + */ +public class WaitAnyContext extends WaitContext { - WaitAnyContext(SchedulerItem schedulerItem) { - super(schedulerItem); - } + WaitAnyContext(SchedulerItem schedulerItem) { + super(schedulerItem); + } - @Override - boolean handlePanic() { - waitCount.set(0); - return true; - } + @Override + boolean handlePanic() { + waitCount.set(0); + return true; + } - @Override - boolean waitCompleted(Object result) { - if (TypeChecker.checkIsType(result, PredefinedTypes.TYPE_ERROR)) { - return waitCount.decrementAndGet() == 0; - } - return true; - } - } + @Override + boolean waitCompleted(Object result) { + if (TypeChecker.checkIsType(result, PredefinedTypes.TYPE_ERROR)) { + return waitCount.decrementAndGet() == 0; + } + return true; + } +} diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/WaitContext.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/WaitContext.java index 2d691fa87f33..7fba62f2581b 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/WaitContext.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/WaitContext.java @@ -1,58 +1,57 @@ - /* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - package io.ballerina.runtime.internal.scheduling; - - import java.util.concurrent.atomic.AtomicInteger; - import java.util.concurrent.locks.ReentrantLock; - - /** - * This context is shared among the strands to notify that a - * certain strand is waiting on another strand. - * - * @since 1.0.0 - */ - public abstract class WaitContext { - - SchedulerItem schedulerItem; - boolean runnable; - boolean completed; - boolean intermediate; - private final ReentrantLock contextLock; - AtomicInteger waitCount; - - - WaitContext(SchedulerItem schedulerItem) { - this.schedulerItem = schedulerItem; - this.contextLock = new ReentrantLock(); - this.waitCount = new AtomicInteger(); - this.intermediate = true; - - } - - void lock() { - this.contextLock.lock(); - } - - void unLock() { - this.contextLock.unlock(); - } - - abstract boolean handlePanic(); - - abstract boolean waitCompleted(Object result); - } +/* + * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package io.ballerina.runtime.internal.scheduling; + +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.locks.ReentrantLock; + +/** + * This context is shared among the strands to notify that a + * certain strand is waiting on another strand. + * + * @since 1.0.0 + */ +public abstract class WaitContext { + + SchedulerItem schedulerItem; + boolean runnable; + boolean completed; + boolean intermediate; + private final ReentrantLock contextLock; + AtomicInteger waitCount; + + + WaitContext(SchedulerItem schedulerItem) { + this.schedulerItem = schedulerItem; + this.contextLock = new ReentrantLock(); + this.waitCount = new AtomicInteger(); + this.intermediate = true; + } + + void lock() { + this.contextLock.lock(); + } + + void unLock() { + this.contextLock.unlock(); + } + + abstract boolean handlePanic(); + + abstract boolean waitCompleted(Object result); +} diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/WaitMultipleContext.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/WaitMultipleContext.java index 4cca0c544961..cee19b56db05 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/WaitMultipleContext.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/WaitMultipleContext.java @@ -1,41 +1,41 @@ - /* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - package io.ballerina.runtime.internal.scheduling; +/* + * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package io.ballerina.runtime.internal.scheduling; - /** - * WaitContext for Wait for all action. - * - * @since 1.0.0 - */ - public class WaitMultipleContext extends WaitContext { +/** + * WaitContext for Wait for all action. + * + * @since 1.0.0 + */ +public class WaitMultipleContext extends WaitContext { - WaitMultipleContext(SchedulerItem schedulerItem) { - super(schedulerItem); - } + WaitMultipleContext(SchedulerItem schedulerItem) { + super(schedulerItem); + } - @Override - boolean handlePanic() { - waitCount.set(0); - return true; - } + @Override + boolean handlePanic() { + waitCount.set(0); + return true; + } - @Override - boolean waitCompleted(Object result) { - return waitCount.decrementAndGet() == 0; - } - } + @Override + boolean waitCompleted(Object result) { + return waitCount.decrementAndGet() == 0; + } +} diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/WorkerUtils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/WorkerUtils.java index 0cbbf3cd5747..44f5091d9431 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/WorkerUtils.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/WorkerUtils.java @@ -1,46 +1,46 @@ - /* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - package io.ballerina.runtime.internal.scheduling; +/* + * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package io.ballerina.runtime.internal.scheduling; - import io.ballerina.runtime.api.PredefinedTypes; - import io.ballerina.runtime.internal.TypeChecker; - import io.ballerina.runtime.internal.values.ChannelDetails; - import io.ballerina.runtime.internal.values.ErrorValue; - import io.ballerina.runtime.internal.values.RefValue; +import io.ballerina.runtime.api.PredefinedTypes; +import io.ballerina.runtime.internal.TypeChecker; +import io.ballerina.runtime.internal.values.ChannelDetails; +import io.ballerina.runtime.internal.values.ErrorValue; +import io.ballerina.runtime.internal.values.RefValue; - /** - * Worker related utility methods for jBallerina runtime. - * - * @since 0.995.0 - */ - public class WorkerUtils { +/** + * Worker related utility methods for jBallerina runtime. + * + * @since 0.995.0 + */ +public final class WorkerUtils { - /** - * Notify worker data channels if this is a error return in a union type. - * @param value return value - * @param strand current strand - * @param channels worker date channels that current worker interacts - */ - public static void handleWorkerError(RefValue value, Strand strand, ChannelDetails[] channels) { - if (TypeChecker.checkIsType(value, PredefinedTypes.TYPE_ERROR)) { - strand.handleChannelError(channels, (ErrorValue) value); - } - } + /** + * Notify worker data channels if this is a error return in a union type. + * @param value return value + * @param strand current strand + * @param channels worker date channels that current worker interacts + */ + public static void handleWorkerError(RefValue value, Strand strand, ChannelDetails[] channels) { + if (TypeChecker.checkIsType(value, PredefinedTypes.TYPE_ERROR)) { + strand.handleChannelError(channels, (ErrorValue) value); + } + } - private WorkerUtils() {} - } + private WorkerUtils() {} +} diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/troubleshoot/StrandDump.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/troubleshoot/StrandDump.java index 74c1f0b7ba81..10b83c05004d 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/troubleshoot/StrandDump.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/troubleshoot/StrandDump.java @@ -35,7 +35,7 @@ * * @since 2201.2.0 */ -public class StrandDump { +public final class StrandDump { public static String getStrandDump() { Map availableStrands = Scheduler.getCurrentStrands(); diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BArrayType.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BArrayType.java index e987aa6717cf..d73fb58f5a82 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BArrayType.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BArrayType.java @@ -128,8 +128,7 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (obj instanceof BArrayType) { - BArrayType other = (BArrayType) obj; + if (obj instanceof BArrayType other) { if (other.state == ArrayState.CLOSED && this.size != other.size) { return false; } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BErrorType.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BErrorType.java index a05a0f3a236c..59cf32500a3d 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BErrorType.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BErrorType.java @@ -73,11 +73,10 @@ public void setDetailType(Type detailType) { @Override public boolean equals(Object obj) { - if (!super.equals(obj) || !(obj instanceof BErrorType)) { + if (!super.equals(obj) || !(obj instanceof BErrorType other)) { return false; } - BErrorType other = (BErrorType) obj; if (detailType == other.detailType) { return true; } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BFiniteType.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BFiniteType.java index 72bbded21b24..c232100029f9 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BFiniteType.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BFiniteType.java @@ -184,10 +184,9 @@ public boolean equals(Object o) { if (this == o) { return true; } - if (!(o instanceof BFiniteType)) { + if (!(o instanceof BFiniteType that)) { return false; } - BFiniteType that = (BFiniteType) o; return this.valueSpace.size() == that.valueSpace.size() && this.valueSpace.containsAll(that.valueSpace); } } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BFunctionType.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BFunctionType.java index bb66f58477d0..9916e0ba4da4 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BFunctionType.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BFunctionType.java @@ -115,15 +115,13 @@ public boolean equals(Object o) { if (this == o) { return true; } - if (!(o instanceof BFunctionType)) { + if (!(o instanceof BFunctionType that)) { return false; } if (!super.equals(o)) { return false; } - BFunctionType that = (BFunctionType) o; - boolean isSourceAnyFunction = SymbolFlags.isFlagOn(this.flags, SymbolFlags.ANY_FUNCTION); boolean isTargetAnyFunction = SymbolFlags.isFlagOn(that.flags, SymbolFlags.ANY_FUNCTION); @@ -180,9 +178,9 @@ public String toString() { if (parameters != null) { addParamListToString(parameters, stringRep); } - if (restType instanceof BArrayType) { + if (restType instanceof BArrayType bArrayType) { stringRep.append(","); - stringRep.append(((BArrayType) restType).getElementType().toString()); + stringRep.append(bArrayType.getElementType().toString()); stringRep.append("..."); } stringRep.append(")"); diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BFutureType.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BFutureType.java index 38e6bc656b04..df747fc1865c 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BFutureType.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BFutureType.java @@ -70,7 +70,7 @@ public int getTag() { @Override public boolean equals(Object obj) { - if (!(obj instanceof BFutureType)) { + if (!(obj instanceof BFutureType other)) { return false; } @@ -78,7 +78,6 @@ public boolean equals(Object obj) { return false; } - BFutureType other = (BFutureType) obj; if (constraint == other.constraint) { return true; } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BIntersectionType.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BIntersectionType.java index 4466deca75e0..c2112f4a4578 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BIntersectionType.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BIntersectionType.java @@ -145,11 +145,10 @@ public boolean equals(Object o) { return true; } - if (!(o instanceof BIntersectionType)) { + if (!(o instanceof BIntersectionType that)) { return false; } - BIntersectionType that = (BIntersectionType) o; if (this.constituentTypes.size() != that.constituentTypes.size()) { return false; } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BMapType.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BMapType.java index c9178bdaed0f..c69aaa56c144 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BMapType.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BMapType.java @@ -124,12 +124,10 @@ public String toString() { @Override public boolean equals(Object obj) { - if (!super.equals(obj) || !(obj instanceof BMapType)) { + if (!super.equals(obj) || !(obj instanceof BMapType other)) { return false; } - BMapType other = (BMapType) obj; - if (this.readonly != other.readonly) { return false; } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BParameterizedType.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BParameterizedType.java index b0ce380d03e5..d167d3692cd1 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BParameterizedType.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BParameterizedType.java @@ -58,12 +58,10 @@ public boolean equals(Object obj) { if (this == obj) { return true; } - if (!(obj instanceof BParameterizedType)) { + if (!(obj instanceof BParameterizedType otherParameterizedType)) { return false; } - BParameterizedType otherParameterizedType = (BParameterizedType) obj; - return paramIndex == otherParameterizedType.paramIndex && paramValueType.equals(otherParameterizedType.getParamValueType()); } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BResourceMethodType.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BResourceMethodType.java index 5c6a68d7c5ad..b2f1fe3e37f2 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BResourceMethodType.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BResourceMethodType.java @@ -19,6 +19,7 @@ import io.ballerina.runtime.api.Module; import io.ballerina.runtime.api.types.MethodType; +import io.ballerina.runtime.api.types.Parameter; import io.ballerina.runtime.api.types.ResourceMethodType; import io.ballerina.runtime.api.types.Type; @@ -53,9 +54,9 @@ public String toString() { } StringJoiner sj = new StringJoiner(",", "resource function " + accessor + " " + rp.toString() + "(", ") returns (" + type.retType + ")"); - for (int i = 0; i < parameters.length; i++) { - Type type = parameters[i].type; - sj.add(type.getName() + " " + parameters[i].name); + for (Parameter parameter : parameters) { + Type type = parameter.type; + sj.add(type.getName() + " " + parameter.name); } return sj.toString(); } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BStreamType.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BStreamType.java index e44d4ac30102..5b5d7b91389b 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BStreamType.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BStreamType.java @@ -120,11 +120,10 @@ public String toString() { @Override public boolean equals(Object obj) { - if (!super.equals(obj) || !(obj instanceof BStreamType)) { + if (!super.equals(obj) || !(obj instanceof BStreamType other)) { return false; } - BStreamType other = (BStreamType) obj; if (constraint == other.constraint && completionType == other.completionType) { return true; } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BTableType.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BTableType.java index e97ddc8a6c52..1aae344cfd3e 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BTableType.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BTableType.java @@ -114,11 +114,10 @@ public String toString() { @Override public boolean equals(Object obj) { - if (!super.equals(obj) || !(obj instanceof BTableType)) { + if (!super.equals(obj) || !(obj instanceof BTableType other)) { return false; } - BTableType other = (BTableType) obj; if (constraint == other.constraint && keyType == other.keyType) { return true; } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BTupleType.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BTupleType.java index 847a83914dba..21fb42a59f92 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BTupleType.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BTupleType.java @@ -229,10 +229,9 @@ public boolean equals(Object o) { if (this == o) { return true; } - if (!(o instanceof BTupleType)) { + if (!(o instanceof BTupleType that)) { return false; } - BTupleType that = (BTupleType) o; if (this.isCyclic || that.isCyclic) { if (this.isCyclic != that.isCyclic) { diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BType.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BType.java index 6467e9c106f3..5d2aba9ddc8f 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BType.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BType.java @@ -93,8 +93,7 @@ public boolean equals(Object obj) { return true; } - if (obj instanceof BType) { - BType other = (BType) obj; + if (obj instanceof BType other) { if (!this.typeName.equals(other.getName())) { return false; diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BTypeIdSet.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BTypeIdSet.java index f80780d87586..f08e2d340f8f 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BTypeIdSet.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BTypeIdSet.java @@ -96,8 +96,7 @@ public boolean equals(Object obj) { return true; } - if (obj instanceof BTypeId) { - BTypeId that = (BTypeId) obj; + if (obj instanceof BTypeId that) { return this.name.equals(that.name) && this.pkg.equals(that.pkg); } return false; diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BTypeReferenceType.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BTypeReferenceType.java index f43cd540dc0e..4d228b2d78f6 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BTypeReferenceType.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BTypeReferenceType.java @@ -66,8 +66,8 @@ public boolean equals(Object obj) { return true; } - if (obj instanceof BTypeReferenceType) { - return this.referredType.equals(((BTypeReferenceType) obj).getReferredType()); + if (obj instanceof BTypeReferenceType typeReferenceType) { + return this.referredType.equals(typeReferenceType.getReferredType()); } return false; } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BTypedescType.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BTypedescType.java index bb23197dd12b..a6988bc263cb 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BTypedescType.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BTypedescType.java @@ -64,8 +64,8 @@ public boolean equals(Object obj) { if (this == obj) { return true; } - if (obj instanceof BTypedescType) { - return constraint.equals(((BTypedescType) obj).getConstraint()); + if (obj instanceof BTypedescType typedescType) { + return constraint.equals(typedescType.getConstraint()); } return false; } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BUnionType.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BUnionType.java index 71eee472a63c..3f957eac231a 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BUnionType.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BUnionType.java @@ -363,12 +363,10 @@ public boolean equals(Object o) { return true; } - if (!(o instanceof BUnionType)) { + if (!(o instanceof BUnionType that)) { return false; } - BUnionType that = (BUnionType) o; - if (this.isCyclic || that.isCyclic) { if (this.isCyclic != that.isCyclic) { return false; @@ -442,28 +440,24 @@ public void mergeUnionType(BUnionType unionType) { } this.isCyclic = true; for (Type member : unionType.getMemberTypes()) { - if (member instanceof BArrayType) { - BArrayType arrayType = (BArrayType) member; + if (member instanceof BArrayType arrayType) { if (TypeUtils.getImpliedType(arrayType.getElementType()) == unionType) { BArrayType newArrayType = new BArrayType(this, this.readonly); this.addMember(newArrayType); continue; } - } else if (member instanceof BMapType) { - BMapType mapType = (BMapType) member; + } else if (member instanceof BMapType mapType) { if (mapType.getConstrainedType() == unionType) { BMapType newMapType = new BMapType(this, this.readonly); this.addMember(newMapType); continue; } - } else if (member instanceof BTableType) { - BTableType tableType = (BTableType) member; + } else if (member instanceof BTableType tableType) { if (tableType.getConstrainedType() == unionType) { BTableType newTableType = new BTableType(this, tableType.isReadOnly()); this.addMember(newTableType); continue; - } else if (tableType.getConstrainedType() instanceof BMapType) { - BMapType mapType = (BMapType) tableType.getConstrainedType(); + } else if (tableType.getConstrainedType() instanceof BMapType mapType) { if (mapType.getConstrainedType() == unionType) { BMapType newMapType = new BMapType(this); BTableType newTableType = new BTableType(newMapType, diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BXmlType.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BXmlType.java index 187c15dfb6c2..c48c9d085594 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BXmlType.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/types/BXmlType.java @@ -99,11 +99,10 @@ public boolean isAnydata() { @Override public boolean equals(Object obj) { - if (!(this == obj && obj instanceof BXmlType)) { + if (!(this == obj && obj instanceof BXmlType other)) { return false; } - BXmlType other = (BXmlType) obj; if (constraint == other.constraint) { return true; } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/util/CompatibilityChecker.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/util/CompatibilityChecker.java index 52f075851702..e5ed38a11e16 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/util/CompatibilityChecker.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/util/CompatibilityChecker.java @@ -26,12 +26,15 @@ * @since 1.0.1 */ -public class CompatibilityChecker { +public final class CompatibilityChecker { private static final String JAVA_VERSION = "java.version"; private static final String VERSION_ZERO = "0"; private static final PrintStream stderr = System.err; + private CompatibilityChecker() { + } + /** * Check for the compatibility of a given java version against the current java runtime version. * This assumes the versions are in the following formats: diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/util/LargeStructureUtils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/util/LargeStructureUtils.java index 20a86e2b2841..252b866237a0 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/util/LargeStructureUtils.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/util/LargeStructureUtils.java @@ -30,7 +30,7 @@ * * @since 2201.8.0 */ -public class LargeStructureUtils { +public final class LargeStructureUtils { private LargeStructureUtils() {} @@ -59,7 +59,7 @@ public static void setKeyValueEntry(HandleValue arrayList, Object key, Object va public static void setSpreadFieldEntry(HandleValue arrayList, Object spreadFieldEntry, long index) { BMapInitialValueEntry[] arr = (BMapInitialValueEntry[]) arrayList.getValue(); - arr[(int) index] = new MappingInitialValueEntry.SpreadFieldEntry((BMap) spreadFieldEntry); + arr[(int) index] = new MappingInitialValueEntry.SpreadFieldEntry((BMap) spreadFieldEntry); } } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/util/RuntimeUtils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/util/RuntimeUtils.java index 11d4dc9d767f..a89fae22b26b 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/util/RuntimeUtils.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/util/RuntimeUtils.java @@ -54,7 +54,7 @@ * @since 0.995.0 */ -public class RuntimeUtils { +public final class RuntimeUtils { private static final String CRASH_LOGGER = "b7a.log.crash"; private static final PrintStream errStream = System.err; @@ -130,8 +130,8 @@ public ParamInfo(boolean hasDefaultable, String name, Type type) { } public static void handleBErrorAndExit(Throwable throwable) { - if (throwable instanceof ErrorValue) { - printToConsole((ErrorValue) throwable); + if (throwable instanceof ErrorValue errorValue) { + printToConsole(errorValue); } Runtime.getRuntime().exit(1); } @@ -142,8 +142,8 @@ public static void handleAllRuntimeErrorsAndExit(Throwable throwable) { } public static void handleAllRuntimeErrors(Throwable throwable) { - if (throwable instanceof ErrorValue) { - printToConsole((ErrorValue) throwable); + if (throwable instanceof ErrorValue errorValue) { + printToConsole(errorValue); } else { logBadSad(throwable); } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/util/StringUtils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/util/StringUtils.java index 6cb05a948a15..fa44bae7cf50 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/util/StringUtils.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/util/StringUtils.java @@ -47,7 +47,7 @@ * * @since 2201.6.0 */ -public class StringUtils { +public final class StringUtils { public static final String STR_CYCLE = "..."; public static final String TO_STRING = "toString"; @@ -77,7 +77,7 @@ public static String getStringVal(Object value, BLink parent) { return STR_CYCLE; } if (type.getTag() == TypeTags.MAP_TAG || type.getTag() == TypeTags.RECORD_TYPE_TAG) { - MapValueImpl mapValue = (MapValueImpl) value; + MapValueImpl mapValue = (MapValueImpl) value; return mapValue.stringValue(parent); } if (type.getTag() == TypeTags.ARRAY_TAG || type.getTag() == TypeTags.TUPLE_TAG) { @@ -136,7 +136,7 @@ public static String getExpressionStringVal(Object value, BLink parent) { return STR_CYCLE + "[" + node.getIndex() + "]"; } if (type.getTag() == TypeTags.MAP_TAG || type.getTag() == TypeTags.RECORD_TYPE_TAG) { - MapValueImpl mapValue = (MapValueImpl) value; + MapValueImpl mapValue = (MapValueImpl) value; return mapValue.expressionStringValue(parent); } if (type.getTag() == TypeTags.ARRAY_TAG || type.getTag() == TypeTags.TUPLE_TAG) { diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/AbstractArrayValue.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/AbstractArrayValue.java index ab78a93e9d74..ab80640c69d0 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/AbstractArrayValue.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/AbstractArrayValue.java @@ -164,7 +164,7 @@ public String getJSONString() { * {@inheritDoc} */ @Override - public IteratorValue getIterator() { + public IteratorValue getIterator() { return new ArrayIterator(this); } @@ -279,7 +279,7 @@ protected void prepareForAddForcefully(int intIndex, int currentArraySize) { * * @since 0.995.0 */ - static class ArrayIterator implements IteratorValue { + static class ArrayIterator implements IteratorValue { ArrayValue array; long cursor = 0; long length; diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/AbstractObjectValue.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/AbstractObjectValue.java index 068b97bb03a4..07d20399f30d 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/AbstractObjectValue.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/AbstractObjectValue.java @@ -132,9 +132,10 @@ public boolean getBooleanValue(BString fieldName) { return (boolean) get(fieldName); } + @SuppressWarnings("rawtypes") @Override public BMap getMapValue(BString fieldName) { - return (MapValueImpl) get(fieldName); + return (MapValueImpl) get(fieldName); } @Override diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/ArrayValueImpl.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/ArrayValueImpl.java index 83263e70c56a..e983854997ef 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/ArrayValueImpl.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/ArrayValueImpl.java @@ -185,57 +185,63 @@ public BTypedesc getTypedesc() { @Override public Object reverse() { - switch (elementType.getTag()) { - case TypeTags.INT_TAG: - case TypeTags.SIGNED32_INT_TAG: - case TypeTags.SIGNED16_INT_TAG: - case TypeTags.SIGNED8_INT_TAG: - case TypeTags.UNSIGNED32_INT_TAG: - case TypeTags.UNSIGNED16_INT_TAG: - case TypeTags.UNSIGNED8_INT_TAG: + return switch (elementType.getTag()) { + case TypeTags.INT_TAG, + TypeTags.SIGNED32_INT_TAG, + TypeTags.SIGNED16_INT_TAG, + TypeTags.SIGNED8_INT_TAG, + TypeTags.UNSIGNED32_INT_TAG, + TypeTags.UNSIGNED16_INT_TAG, + TypeTags.UNSIGNED8_INT_TAG -> { for (int i = size - 1, j = 0; j < size / 2; i--, j++) { long temp = intValues[j]; intValues[j] = intValues[i]; intValues[i] = temp; } - return intValues; - case TypeTags.STRING_TAG: - case TypeTags.CHAR_STRING_TAG: + yield intValues; + } + case TypeTags.STRING_TAG, + TypeTags.CHAR_STRING_TAG -> { for (int i = size - 1, j = 0; j < size / 2; i--, j++) { BString temp = bStringValues[j]; bStringValues[j] = bStringValues[i]; bStringValues[i] = temp; } - return bStringValues; - case TypeTags.FLOAT_TAG: + yield bStringValues; + } + case TypeTags.FLOAT_TAG -> { for (int i = size - 1, j = 0; j < size / 2; i--, j++) { double temp = floatValues[j]; floatValues[j] = floatValues[i]; floatValues[i] = temp; } - return floatValues; - case TypeTags.BOOLEAN_TAG: + yield floatValues; + } + case TypeTags.BOOLEAN_TAG -> { for (int i = size - 1, j = 0; j < size / 2; i--, j++) { boolean temp = booleanValues[j]; booleanValues[j] = booleanValues[i]; booleanValues[i] = temp; } - return booleanValues; - case TypeTags.BYTE_TAG: + yield booleanValues; + } + case TypeTags.BYTE_TAG -> { for (int i = size - 1, j = 0; j < size / 2; i--, j++) { byte temp = byteValues[j]; byteValues[j] = byteValues[i]; byteValues[i] = temp; } - return byteValues; - default: + yield byteValues; + } + default -> { for (int i = size - 1, j = 0; j < size / 2; i--, j++) { Object temp = refValues[j]; refValues[j] = refValues[i]; refValues[i] = temp; } - return refValues; - } + yield refValues; + } + }; } public ArrayValueImpl(ArrayType type, long size) { @@ -306,27 +312,21 @@ public ArrayValueImpl(Type type, long size, BListInitialValueEntry[] initialValu @Override public Object get(long index) { rangeCheckForGet(index, size); - switch (this.elementReferredType.getTag()) { - case TypeTags.INT_TAG: - case TypeTags.SIGNED32_INT_TAG: - case TypeTags.SIGNED16_INT_TAG: - case TypeTags.SIGNED8_INT_TAG: - case TypeTags.UNSIGNED32_INT_TAG: - case TypeTags.UNSIGNED16_INT_TAG: - case TypeTags.UNSIGNED8_INT_TAG: - return intValues[(int) index]; - case TypeTags.BOOLEAN_TAG: - return booleanValues[(int) index]; - case TypeTags.BYTE_TAG: - return Byte.toUnsignedInt(byteValues[(int) index]); - case TypeTags.FLOAT_TAG: - return floatValues[(int) index]; - case TypeTags.STRING_TAG: - case TypeTags.CHAR_STRING_TAG: - return bStringValues[(int) index]; - default: - return refValues[(int) index]; - } + return switch (this.elementReferredType.getTag()) { + case TypeTags.INT_TAG, + TypeTags.SIGNED32_INT_TAG, + TypeTags.SIGNED16_INT_TAG, + TypeTags.SIGNED8_INT_TAG, + TypeTags.UNSIGNED32_INT_TAG, + TypeTags.UNSIGNED16_INT_TAG, + TypeTags.UNSIGNED8_INT_TAG -> intValues[(int) index]; + case TypeTags.BOOLEAN_TAG -> booleanValues[(int) index]; + case TypeTags.BYTE_TAG -> Byte.toUnsignedInt(byteValues[(int) index]); + case TypeTags.FLOAT_TAG -> floatValues[(int) index]; + case TypeTags.STRING_TAG, + TypeTags.CHAR_STRING_TAG -> bStringValues[(int) index]; + default -> refValues[(int) index]; + }; } public Object getRefValue(int index) { @@ -906,8 +906,8 @@ public Object copy(Map refs) { valueArray = new ArrayValueImpl(values, arrayType); IntStream.range(0, this.size).forEach(i -> { Object value = this.refValues[i]; - if (value instanceof BRefValue) { - values[i] = ((BRefValue) value).copy(refs); + if (value instanceof BRefValue refValue) { + values[i] = refValue.copy(refs); } else { values[i] = value; } @@ -1076,8 +1076,8 @@ public void freezeDirect() { if (this.elementType == null || this.elementReferredType.getTag() > TypeTags.BOOLEAN_TAG) { for (int i = 0; i < this.size; i++) { Object value = this.getRefValue(i); - if (value instanceof BRefValue) { - ((BRefValue) value).freezeDirect(); + if (value instanceof BRefValue refValue) { + refValue.freezeDirect(); } } } @@ -1088,7 +1088,7 @@ public void freezeDirect() { * {@inheritDoc} */ @Override - public IteratorValue getIterator() { + public IteratorValue getIterator() { return new ArrayIterator(this); } @@ -1339,51 +1339,39 @@ private void unshiftArray(long index, int unshiftByN, int arrLength) { } private Object getArrayFromType(int typeTag) { - switch (typeTag) { - case TypeTags.INT_TAG: - case TypeTags.SIGNED32_INT_TAG: - case TypeTags.SIGNED16_INT_TAG: - case TypeTags.SIGNED8_INT_TAG: - case TypeTags.UNSIGNED32_INT_TAG: - case TypeTags.UNSIGNED16_INT_TAG: - case TypeTags.UNSIGNED8_INT_TAG: - return intValues; - case TypeTags.BOOLEAN_TAG: - return booleanValues; - case TypeTags.BYTE_TAG: - return byteValues; - case TypeTags.FLOAT_TAG: - return floatValues; - case TypeTags.STRING_TAG: - case TypeTags.CHAR_STRING_TAG: - return bStringValues; - default: - return refValues; - } + return switch (typeTag) { + case TypeTags.INT_TAG, + TypeTags.SIGNED32_INT_TAG, + TypeTags.SIGNED16_INT_TAG, + TypeTags.SIGNED8_INT_TAG, + TypeTags.UNSIGNED32_INT_TAG, + TypeTags.UNSIGNED16_INT_TAG, + TypeTags.UNSIGNED8_INT_TAG -> intValues; + case TypeTags.BOOLEAN_TAG -> booleanValues; + case TypeTags.BYTE_TAG -> byteValues; + case TypeTags.FLOAT_TAG -> floatValues; + case TypeTags.STRING_TAG, + TypeTags.CHAR_STRING_TAG -> bStringValues; + default -> refValues; + }; } private int getCurrentArrayLength() { - switch (elementType.getTag()) { - case TypeTags.INT_TAG: - case TypeTags.SIGNED32_INT_TAG: - case TypeTags.SIGNED16_INT_TAG: - case TypeTags.SIGNED8_INT_TAG: - case TypeTags.UNSIGNED32_INT_TAG: - case TypeTags.UNSIGNED16_INT_TAG: - case TypeTags.UNSIGNED8_INT_TAG: - return intValues.length; - case TypeTags.BOOLEAN_TAG: - return booleanValues.length; - case TypeTags.BYTE_TAG: - return byteValues.length; - case TypeTags.FLOAT_TAG: - return floatValues.length; - case TypeTags.STRING_TAG: - case TypeTags.CHAR_STRING_TAG: - return bStringValues.length; - default: - return refValues.length; - } + return switch (elementType.getTag()) { + case TypeTags.INT_TAG, + TypeTags.SIGNED32_INT_TAG, + TypeTags.SIGNED16_INT_TAG, + TypeTags.SIGNED8_INT_TAG, + TypeTags.UNSIGNED32_INT_TAG, + TypeTags.UNSIGNED16_INT_TAG, + TypeTags.UNSIGNED8_INT_TAG -> intValues.length; + case TypeTags.BOOLEAN_TAG -> booleanValues.length; + case TypeTags.BYTE_TAG -> byteValues.length; + case TypeTags.FLOAT_TAG -> floatValues.length; + case TypeTags.STRING_TAG, + TypeTags.CHAR_STRING_TAG -> bStringValues.length; + default -> refValues.length; + }; } @Override diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/BmpStringValue.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/BmpStringValue.java index 7654836e633a..38f3b6603f78 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/BmpStringValue.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/BmpStringValue.java @@ -1,75 +1,75 @@ - /* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ +/* + * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package io.ballerina.runtime.internal.values; import io.ballerina.runtime.api.values.BString; - /** - * Represent ballerina strings containing only unicode basic multilingual plane characters. - * - * @since 1.0.5 - */ - public class BmpStringValue extends StringValue { +/** + * Represent ballerina strings containing only unicode basic multilingual plane characters. + * + * @since 1.0.5 + */ +public class BmpStringValue extends StringValue { - public BmpStringValue(String value) { - super(value, false); - } + public BmpStringValue(String value) { + super(value, false); + } - @Override - public int getCodePoint(int index) { - return value.charAt(index); - } + @Override + public int getCodePoint(int index) { + return value.charAt(index); + } - @Override - public int length() { - return value.length(); - } + @Override + public int length() { + return value.length(); + } - @Override - public BString concat(BString str) { - StringValue stringValue = (StringValue) str; - if (stringValue.isNonBmp) { - int[] otherSurrogates = ((NonBmpStringValue) str).getSurrogates(); - int[] newSurrogates = new int[otherSurrogates.length]; - int length = length(); - for (int i = 0; i < otherSurrogates.length; i++) { - newSurrogates[i] = otherSurrogates[i] + length; - } - return new NonBmpStringValue(this.value + str.getValue(), newSurrogates); - } - return new BmpStringValue(this.value + str.getValue()); - } + @Override + public BString concat(BString str) { + StringValue stringValue = (StringValue) str; + if (stringValue.isNonBmp) { + int[] otherSurrogates = ((NonBmpStringValue) str).getSurrogates(); + int[] newSurrogates = new int[otherSurrogates.length]; + int length = length(); + for (int i = 0; i < otherSurrogates.length; i++) { + newSurrogates[i] = otherSurrogates[i] + length; + } + return new NonBmpStringValue(this.value + str.getValue(), newSurrogates); + } + return new BmpStringValue(this.value + str.getValue()); + } - @Override - public Long indexOf(BString str, int fromIndex) { - long index = value.indexOf(str.getValue(), fromIndex); - return index >= 0 ? index : null; - } + @Override + public Long indexOf(BString str, int fromIndex) { + long index = value.indexOf(str.getValue(), fromIndex); + return index >= 0 ? index : null; + } - @Override - public Long lastIndexOf(BString str, int fromIndex) { - long index = value.lastIndexOf(str.getValue(), fromIndex); - return index >= 0 ? index : null; - } + @Override + public Long lastIndexOf(BString str, int fromIndex) { + long index = value.lastIndexOf(str.getValue(), fromIndex); + return index >= 0 ? index : null; + } - @Override - public BString substring(int beginIndex, int endIndex) { - return new BmpStringValue(value.substring(beginIndex, endIndex)); - } - } + @Override + public BString substring(int beginIndex, int endIndex) { + return new BmpStringValue(value.substring(beginIndex, endIndex)); + } +} diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/ChannelDetails.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/ChannelDetails.java index 9f01d027a179..1bbbba69adbc 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/ChannelDetails.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/ChannelDetails.java @@ -1,51 +1,51 @@ - /* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - package io.ballerina.runtime.internal.values; +/* + * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package io.ballerina.runtime.internal.values; - /** - * Represents a channel info. - * - * @since 0.995.0 - */ - public class ChannelDetails { +/** + * Represents a channel info. + * + * @since 0.995.0 + */ +public class ChannelDetails { - public String name; - public boolean channelInSameStrand; - public boolean send; + public String name; + public boolean channelInSameStrand; + public boolean send; - public ChannelDetails(String name, boolean channelInSameStrand, boolean send) { - this.name = name; - this.channelInSameStrand = channelInSameStrand; - this.send = send; - } + public ChannelDetails(String name, boolean channelInSameStrand, boolean send) { + this.name = name; + this.channelInSameStrand = channelInSameStrand; + this.send = send; + } - @Override - public String toString() { - return name; - } + @Override + public String toString() { + return name; + } - @Override - public int hashCode() { - return name.hashCode(); - } + @Override + public int hashCode() { + return name.hashCode(); + } - @Override - public boolean equals(Object o) { - return (o instanceof ChannelDetails) && (((ChannelDetails) o).name.equals(this.name)); - } - } + @Override + public boolean equals(Object o) { + return (o instanceof ChannelDetails channelDetails) && (channelDetails.name.equals(this.name)); + } +} diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/CharIterator.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/CharIterator.java index 9e5c4cea6bf1..e1201b121294 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/CharIterator.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/CharIterator.java @@ -23,7 +23,7 @@ * * @since 2.0 */ -public class CharIterator implements IteratorValue { +public class CharIterator implements IteratorValue { StringValue value; long cursor = 0; @@ -37,7 +37,7 @@ public class CharIterator implements IteratorValue { } @Override - public Object next() { + public String next() { long currentIndex = this.cursor++; if (value.isNonBmp) { return getNonBmpCharWithSurrogates(currentIndex); diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/CollectionValue.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/CollectionValue.java index 262a781e8885..e321a62e9141 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/CollectionValue.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/CollectionValue.java @@ -32,5 +32,5 @@ public interface CollectionValue extends BCollection { @Override - IteratorValue getIterator(); + IteratorValue getIterator(); } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/ErrorValue.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/ErrorValue.java index d415a5ae56a4..dd534b85352e 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/ErrorValue.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/ErrorValue.java @@ -143,8 +143,8 @@ private String getCauseToString(BLink parent) { private String getDetailsToString(BLink parent) { StringJoiner sj = new StringJoiner(","); - for (Object key : ((MapValue) details).getKeys()) { - Object value = ((MapValue) details).get(key); + for (Object key : ((MapValue) details).getKeys()) { + Object value = ((MapValue) details).get(key); if (value == null) { sj.add(key + "=null"); } else { @@ -175,8 +175,8 @@ private String getModuleNameToString() { private String getDetailsToBalString(BLink parent) { StringJoiner sj = new StringJoiner(","); - for (Object key : ((MapValue) details).getKeys()) { - Object value = ((MapValue) details).get(key); + for (Object key : ((MapValue) details).getKeys()) { + Object value = ((MapValue) details).get(key); sj.add(key + "=" + getExpressionStringVal(value, parent)); } return "," + sj; @@ -261,8 +261,8 @@ public BString getErrorMessage() { */ @Override public Object getDetails() { - if (details instanceof BRefValue) { - return ((BRefValue) details).frozenCopy(new HashMap<>()); + if (details instanceof BRefValue bRefValue) { + return bRefValue.frozenCopy(new HashMap<>()); } return details; } @@ -401,7 +401,7 @@ private boolean isEmptyDetail() { if (details == null) { return true; } - return (details instanceof MapValue) && ((MapValue) details).isEmpty(); + return (details instanceof MapValue mapValue) && mapValue.isEmpty(); } private Optional filterStackTraceElement(StackTraceElement stackFrame, int currentIndex) { diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/FPValue.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/FPValue.java index 25c1b0e0a83f..beedcc984d45 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/FPValue.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/FPValue.java @@ -73,7 +73,7 @@ public BFuture asyncCall(Object[] args, StrandMetadata metaData) { @Override public BFuture asyncCall(Object[] args, Function resultHandleFunction, StrandMetadata metaData) { - return AsyncUtils.invokeFunctionPointerAsync(this, this.strandName, metaData, + return AsyncUtils.invokeFunctionPointerAsync((BFunctionPointer) this, this.strandName, metaData, args, resultHandleFunction, Scheduler.getStrand().scheduler); } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/FutureValue.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/FutureValue.java index 231225853c85..44a9c34da136 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/FutureValue.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/FutureValue.java @@ -1,170 +1,170 @@ - /* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - package io.ballerina.runtime.internal.values; - - import io.ballerina.runtime.api.async.Callback; - import io.ballerina.runtime.api.types.Type; - import io.ballerina.runtime.api.values.BFuture; - import io.ballerina.runtime.api.values.BLink; - import io.ballerina.runtime.api.values.BTypedesc; - import io.ballerina.runtime.internal.scheduling.Strand; - import io.ballerina.runtime.internal.types.BFutureType; - import io.ballerina.runtime.internal.util.StringUtils; - - import java.util.Map; - import java.util.StringJoiner; - - /** - *

- * Represent a Ballerina future in Java. - *

- *

- * Note: This is an internal API and may change in future versions. - *

- * - * @since 0.995.0 - */ - public class FutureValue implements BFuture, RefValue { - - private BTypedesc typedesc; - - public Strand strand; - - public Object result; - - public boolean isDone; - - public Throwable panic; - - public Callback callback; - - private boolean waited; - - Type type; - - @Deprecated - public FutureValue(Strand strand, Callback callback, Type constraint) { - this.strand = strand; - this.callback = callback; - this.type = new BFutureType(constraint); - } - - @Override - public String stringValue(BLink parent) { - StringJoiner sj = new StringJoiner(",", "{", "}"); - sj.add("isDone:" + isDone); - if (isDone) { - sj.add("result:" + StringUtils.getStringVal(result, parent)); - } - if (panic != null) { - sj.add("panic:" + panic.getLocalizedMessage()); - } - return "future " + sj; - } - - @Override - public String expressionStringValue(BLink parent) { - return stringValue(parent); - } - - @Override - public Type getType() { - return this.type; - } - - @Override - public Object copy(Map refs) { - throw new UnsupportedOperationException(); - } - - @Override - public Object frozenCopy(Map refs) { - throw new UnsupportedOperationException(); - } - - @Override - public BTypedesc getTypedesc() { - if (this.typedesc == null) { - this.typedesc = new TypedescValueImpl(this.type); - } - return typedesc; - } - - @Override - public void cancel() { - this.strand.cancel = true; - } - - /** - * Returns the strand that the future is attached to. - * @return {@code Strand} - */ - @Override - public Strand getStrand() { - return this.strand; - } - - /** - * Returns the result value of the future. - * @return result value - */ - @Override - public Object getResult() { - return this.result; - } - - /** - * Returns completion status of the {@code Strand} that the future is attached. - * @return true if future is completed - */ - @Override - public boolean isDone() { - return this.isDone; - } - - /** - * Returns {@code Throwable} if the attached strand panic. - * @return panic error or null if not panic occurred - */ - @Override - public Throwable getPanic() { - return this.panic; - } - - /** - * {@code CallableUnitCallback} listening on the completion of this future. - * @return registered {@code CallableUnitCallback} - */ - @Override - public Callback getCallback() { - return this.callback; - } - - @Override - public String toString() { - return stringValue(null); - } - - public boolean hasWaited() { - return waited; - } - - public void setWaited(boolean waited) { - this.waited = waited; - } - } +/* + * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package io.ballerina.runtime.internal.values; + +import io.ballerina.runtime.api.async.Callback; +import io.ballerina.runtime.api.types.Type; +import io.ballerina.runtime.api.values.BFuture; +import io.ballerina.runtime.api.values.BLink; +import io.ballerina.runtime.api.values.BTypedesc; +import io.ballerina.runtime.internal.scheduling.Strand; +import io.ballerina.runtime.internal.types.BFutureType; +import io.ballerina.runtime.internal.util.StringUtils; + +import java.util.Map; +import java.util.StringJoiner; + +/** + *

+ * Represent a Ballerina future in Java. + *

+ *

+ * Note: This is an internal API and may change in future versions. + *

+ * + * @since 0.995.0 + */ +public class FutureValue implements BFuture, RefValue { + + private BTypedesc typedesc; + + public Strand strand; + + public Object result; + + public boolean isDone; + + public Throwable panic; + + public Callback callback; + + private boolean waited; + + Type type; + + @Deprecated + public FutureValue(Strand strand, Callback callback, Type constraint) { + this.strand = strand; + this.callback = callback; + this.type = new BFutureType(constraint); + } + + @Override + public String stringValue(BLink parent) { + StringJoiner sj = new StringJoiner(",", "{", "}"); + sj.add("isDone:" + isDone); + if (isDone) { + sj.add("result:" + StringUtils.getStringVal(result, parent)); + } + if (panic != null) { + sj.add("panic:" + panic.getLocalizedMessage()); + } + return "future " + sj; + } + + @Override + public String expressionStringValue(BLink parent) { + return stringValue(parent); + } + + @Override + public Type getType() { + return this.type; + } + + @Override + public Object copy(Map refs) { + throw new UnsupportedOperationException(); + } + + @Override + public Object frozenCopy(Map refs) { + throw new UnsupportedOperationException(); + } + + @Override + public BTypedesc getTypedesc() { + if (this.typedesc == null) { + this.typedesc = new TypedescValueImpl(this.type); + } + return typedesc; + } + + @Override + public void cancel() { + this.strand.cancel = true; + } + + /** + * Returns the strand that the future is attached to. + * @return {@code Strand} + */ + @Override + public Strand getStrand() { + return this.strand; + } + + /** + * Returns the result value of the future. + * @return result value + */ + @Override + public Object getResult() { + return this.result; + } + + /** + * Returns completion status of the {@code Strand} that the future is attached. + * @return true if future is completed + */ + @Override + public boolean isDone() { + return this.isDone; + } + + /** + * Returns {@code Throwable} if the attached strand panic. + * @return panic error or null if not panic occurred + */ + @Override + public Throwable getPanic() { + return this.panic; + } + + /** + * {@code CallableUnitCallback} listening on the completion of this future. + * @return registered {@code CallableUnitCallback} + */ + @Override + public Callback getCallback() { + return this.callback; + } + + @Override + public String toString() { + return stringValue(null); + } + + public boolean hasWaited() { + return waited; + } + + public void setWaited(boolean waited) { + this.waited = waited; + } +} diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/IteratorValue.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/IteratorValue.java index 924748e14728..8004a431ad5f 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/IteratorValue.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/IteratorValue.java @@ -34,8 +34,9 @@ *

* * @since 0.995.0 + * @param Type of the value returned by the iterator */ -public interface IteratorValue extends RefValue, BIterator { +public interface IteratorValue extends RefValue, BIterator { BTypedesc TYPEDESC = new TypedescValueImpl(PredefinedTypes.TYPE_ITERATOR); diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/MapValueImpl.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/MapValueImpl.java index 699747cf318d..53b0e46f92f2 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/MapValueImpl.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/MapValueImpl.java @@ -130,8 +130,8 @@ public MapValueImpl() { @Override public Long getIntValue(BString key) { Object value = get(key); - if (value instanceof Integer) { // field is an int subtype - return ((Integer) value).longValue(); + if (value instanceof Integer i) { // field is an int subtype + return i.longValue(); } return (Long) value; } @@ -221,7 +221,7 @@ public V fillAndGet(Object key) { // The type should be a record or map for filling read. if (this.referredType.getTag() == TypeTags.RECORD_TYPE_TAG) { BRecordType recordType = (BRecordType) this.referredType; - Map fields = recordType.getFields(); + Map fields = recordType.getFields(); if (fields.containsKey(key.toString())) { expectedType = ((BField) fields.get(key.toString())).getFieldType(); } else { @@ -248,7 +248,7 @@ public V fillAndGet(Object key) { } @Override - public Object merge(BMap v2, boolean checkMergeability) { + public Object merge(BMap v2, boolean checkMergeability) { if (checkMergeability) { BError errorIfUnmergeable = JsonInternalUtils.getErrorIfUnmergeable(this, v2, new ArrayList<>()); if (errorIfUnmergeable != null) { @@ -293,18 +293,13 @@ public V put(K key, V value) { return putValue(key, value); } - String errMessage = ""; - switch (getImpliedType(getType()).getTag()) { - case TypeTags.RECORD_TYPE_TAG: - errMessage = "Invalid update of record field: "; - break; - case TypeTags.MAP_TAG: - errMessage = "Invalid map insertion: "; - break; - } + String errMessage = switch (getImpliedType(getType()).getTag()) { + case TypeTags.RECORD_TYPE_TAG -> "Invalid update of record field: "; + case TypeTags.MAP_TAG -> "Invalid map insertion: "; + default -> ""; + }; throw ErrorCreator.createError(getModulePrefixedReason(MAP_LANG_LIB, INVALID_UPDATE_ERROR_IDENTIFIER), - StringUtils - .fromString(errMessage).concat(ErrorHelper.getErrorMessage( + StringUtils.fromString(errMessage).concat(ErrorHelper.getErrorMessage( INVALID_READONLY_VALUE_UPDATE))); } @@ -590,8 +585,8 @@ public void freezeDirect() { this.referredType = ReadOnlyUtils.setImmutableTypeAndGetEffectiveType(this.referredType); this.values().forEach(val -> { - if (val instanceof BRefValue) { - ((BRefValue) val).freezeDirect(); + if (val instanceof BRefValue bRefValue) { + bRefValue.freezeDirect(); } }); this.typedesc = null; @@ -610,7 +605,7 @@ public String getJSONString() { } @Override - public IteratorValue getIterator() { + public IteratorValue getIterator() { return new MapIterator<>(new LinkedHashSet<>(this.entrySet()).iterator()); } @@ -622,7 +617,7 @@ public IteratorValue getIterator() { * * @since 0.995.0 */ - static class MapIterator implements IteratorValue { + static class MapIterator implements IteratorValue { Iterator> iterator; diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/MappingInitialValueEntry.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/MappingInitialValueEntry.java index de940b334394..3c51b8df6ed6 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/MappingInitialValueEntry.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/MappingInitialValueEntry.java @@ -56,9 +56,9 @@ public KeyValueEntry(Object key, Object value) { */ public static class SpreadFieldEntry extends MappingInitialValueEntry { - public BMap values; + public BMap values; - public SpreadFieldEntry(BMap mappingValue) { + public SpreadFieldEntry(BMap mappingValue) { this.values = mappingValue; } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/NonBmpStringValue.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/NonBmpStringValue.java index 38e4dc50cb6e..2210dfa05257 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/NonBmpStringValue.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/NonBmpStringValue.java @@ -1,131 +1,131 @@ - /* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - package io.ballerina.runtime.internal.values; +/* + * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package io.ballerina.runtime.internal.values; - import io.ballerina.runtime.api.utils.StringUtils; +import io.ballerina.runtime.api.utils.StringUtils; import io.ballerina.runtime.api.values.BString; import java.util.Arrays; - /** - * Represent ballerina strings containing at least one non basic multilingual plane unicode character. - * - * @since 1.0.5 - */ - public class NonBmpStringValue extends StringValue { +/** + * Represent ballerina strings containing at least one non basic multilingual plane unicode character. + * + * @since 1.0.5 + */ +public class NonBmpStringValue extends StringValue { - private final int[] surrogates; + private final int[] surrogates; - public NonBmpStringValue(String value, int[] surrogatePairLocations) { - super(value, true); - surrogates = surrogatePairLocations; - } + public NonBmpStringValue(String value, int[] surrogatePairLocations) { + super(value, true); + surrogates = surrogatePairLocations; + } + + @Override + public int getCodePoint(int index) { + if ((index < 0) || (index >= value.length() - surrogates.length)) { + throw new StringIndexOutOfBoundsException(index); + } + + int offset = index; + for (int surrogate : surrogates) { + if (surrogate < index) { + offset++; + } else if (surrogate > index) { + break; + } else { + return Character.toCodePoint(value.charAt(offset), value.charAt(offset + 1)); + } + } + return value.charAt(offset); + } + + @Override + public int length() { + return value.length() - surrogates.length; + } + + @Override + public BString concat(BString str) { + StringValue stringValue = (StringValue) str; + if (stringValue.isNonBmp) { + NonBmpStringValue other = (NonBmpStringValue) str; + int[] both = Arrays.copyOf(surrogates, surrogates.length + other.surrogates.length); + int length = length(); + for (int i = 0; i < other.surrogates.length; i++) { + both[i + surrogates.length] = other.surrogates[i] + length; + } + return new NonBmpStringValue(this.value + other.value, both); + } + return new NonBmpStringValue(this.value + str.getValue(), surrogates); + } + + public int[] getSurrogates() { + return surrogates.clone(); + } @Override - public int getCodePoint(int index) { - if ((index < 0) || (index >= value.length() - surrogates.length)) { - throw new StringIndexOutOfBoundsException(index); + public Long indexOf(BString str, int fromIndex) { + int offset = getOffset(fromIndex); + long index = value.indexOf(str.getValue(), offset); + if (index < 0) { + return null; } - - int offset = index; - for (int surrogate : surrogates) { - if (surrogate < index) { - offset++; - } else if (surrogate > index) { - break; - } else { - return Character.toCodePoint(value.charAt(offset), value.charAt(offset + 1)); + for (int i = 0; i < index; i++) { + char c = value.charAt(i); + if (Character.isHighSurrogate(c)) { + index--; } } - return value.charAt(offset); + return index; } @Override - public int length() { - return value.length() - surrogates.length; + public Long lastIndexOf(BString str, int fromIndex) { + int offset = getOffset(fromIndex); + long index = value.lastIndexOf(str.getValue(), offset); + if (index < 0) { + return null; + } + for (int i = 0; i < index; i++) { + char c = value.charAt(i); + if (Character.isHighSurrogate(c)) { + index--; + } + } + return index; + } + @Override + public BString substring(int beginIndex, int endIndex) { + int beginOffset = getOffset(beginIndex); + int endOffset = getOffset(endIndex); + return StringUtils.fromString(value.substring(beginOffset, endOffset)); } - @Override - public BString concat(BString str) { - StringValue stringValue = (StringValue) str; - if (stringValue.isNonBmp) { - NonBmpStringValue other = (NonBmpStringValue) str; - int[] both = Arrays.copyOf(surrogates, surrogates.length + other.surrogates.length); - int length = length(); - for (int i = 0; i < other.surrogates.length; i++) { - both[i + surrogates.length] = other.surrogates[i] + length; + private int getOffset(int fromIndex) { + int offset = fromIndex; + for (int surrogate : surrogates) { + if (surrogate < fromIndex) { + offset++; + } else { + break; } - return new NonBmpStringValue(this.value + other.value, both); } - return new NonBmpStringValue(this.value + str.getValue(), surrogates); + return offset; } - - public int[] getSurrogates() { - return surrogates.clone(); - } - - @Override - public Long indexOf(BString str, int fromIndex) { - int offset = getOffset(fromIndex); - long index = value.indexOf(str.getValue(), offset); - if (index < 0) { - return null; - } - for (int i = 0; i < index; i++) { - char c = value.charAt(i); - if (Character.isHighSurrogate(c)) { - index--; - } - } - return index; - } - - @Override - public Long lastIndexOf(BString str, int fromIndex) { - int offset = getOffset(fromIndex); - long index = value.lastIndexOf(str.getValue(), offset); - if (index < 0) { - return null; - } - for (int i = 0; i < index; i++) { - char c = value.charAt(i); - if (Character.isHighSurrogate(c)) { - index--; - } - } - return index; - } - @Override - public BString substring(int beginIndex, int endIndex) { - int beginOffset = getOffset(beginIndex); - int endOffset = getOffset(endIndex); - return StringUtils.fromString(value.substring(beginOffset, endOffset)); - } - - private int getOffset(int fromIndex) { - int offset = fromIndex; - for (int surrogate : surrogates) { - if (surrogate < fromIndex) { - offset++; - } else { - break; - } - } - return offset; - } - } +} diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/ReadOnlyUtils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/ReadOnlyUtils.java index 5e527b31679f..819cca998c51 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/ReadOnlyUtils.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/ReadOnlyUtils.java @@ -66,7 +66,7 @@ * * @since 1.3.0 */ -public class ReadOnlyUtils { +public final class ReadOnlyUtils { /** * Method to handle an update to a value, that is invalid due to the value being immutable. diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/RegExpAtomQuantifier.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/RegExpAtomQuantifier.java index 2ca954b78553..21a3bef34c66 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/RegExpAtomQuantifier.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/RegExpAtomQuantifier.java @@ -61,8 +61,8 @@ public void setReQuantifier(RegExpQuantifier reQuantifier) { private Object getValidReAtom(Object reAtom) { // If reAtom is an instance of BString it's an insertion. Hence, we need to parse it and check whether it's a // valid insertion. - if (reAtom instanceof BString) { - validateInsertion((BString) reAtom); + if (reAtom instanceof BString bString) { + validateInsertion(bString); } return reAtom; } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/RegExpCharSet.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/RegExpCharSet.java index 79d1e2612697..ff1b4d75f9a7 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/RegExpCharSet.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/RegExpCharSet.java @@ -49,8 +49,8 @@ private Object[] getCharSetAtomsList(ArrayValue charSetAtoms) { Object[] atoms = new Object[size]; for (int i = 0; i < size; i++) { Object atom = charSetAtoms.get(i); - if (atom instanceof BString) { - atoms[i] = ((BString) atom).getValue(); + if (atom instanceof BString bString) { + atoms[i] = bString.getValue(); continue; } atoms[i] = atom; diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/RegExpDisjunction.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/RegExpDisjunction.java index 96f0cbfb0cf5..54cde1be1df8 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/RegExpDisjunction.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/RegExpDisjunction.java @@ -55,8 +55,8 @@ public String stringValue(BLink parent) { if (t == null) { break; } - if (t instanceof String) { - terms.add(((String) t)); + if (t instanceof String s) { + terms.add(s); continue; } terms.add(getStringVal(t, parent)); diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/StreamingJsonValue.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/StreamingJsonValue.java index af14dd66f4a9..e532436f0c9e 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/StreamingJsonValue.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/StreamingJsonValue.java @@ -200,7 +200,7 @@ private void buildDatasource() { } @Override - public IteratorValue getIterator() { + public IteratorValue getIterator() { return new ArrayIterator(this); } @@ -209,7 +209,7 @@ public IteratorValue getIterator() { * * @since 0.995.0 */ - static class StreamingJsonIterator implements IteratorValue { + static class StreamingJsonIterator implements IteratorValue { StreamingJsonValue array; long cursor = 0; diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/StringValue.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/StringValue.java index a00c1c0e0575..a96fcacd5a07 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/StringValue.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/StringValue.java @@ -55,7 +55,7 @@ public Object frozenCopy(Map refs) { } @Override - public IteratorValue getIterator() { + public IteratorValue getIterator() { return new CharIterator(this); } @@ -94,8 +94,8 @@ public boolean equals(Object str) { if (str == this) { return true; } - if (str instanceof BString) { - return ((BString) str).getValue().equals(value); + if (str instanceof BString bString) { + return bString.getValue().equals(value); } return false; } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/TableValueImpl.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/TableValueImpl.java index 510608521d8a..540f6371e222 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/TableValueImpl.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/TableValueImpl.java @@ -149,7 +149,7 @@ public TableValueImpl(TableType tableType, ArrayValue fieldNames) { } private void addData(ArrayValue data) { - BIterator itr = data.getIterator(); + BIterator itr = data.getIterator(); while (itr.hasNext()) { Object next = itr.next(); valueHolder.addData((V) next); @@ -157,7 +157,7 @@ private void addData(ArrayValue data) { } @Override - public IteratorValue getIterator() { + public IteratorValue getIterator() { return new TableIterator(); } @@ -178,7 +178,7 @@ public Object copy(Map refs) { clone.fieldNames = fieldNames; } - IteratorValue itr = getIterator(); + IteratorValue itr = getIterator(); while (itr.hasNext()) { TupleValueImpl tupleValue = (TupleValueImpl) itr.next(); Object value = tupleValue.get(1); @@ -255,7 +255,7 @@ public Set> entrySet() { for (List> entry: entries.values()) { entrySet.addAll(entry); } - return new LinkedHashSet(entries.values()); + return entrySet; } @Override @@ -410,8 +410,8 @@ private String createExpressionStringValueDataEntry(Iterator> struct = itr.next(); @@ -510,7 +510,7 @@ public boolean equals(Object o, Set visitedValues) { return true; } - private class TableIterator implements IteratorValue { + private class TableIterator implements IteratorValue { private long cursor; TableIterator() { @@ -562,12 +562,12 @@ public V putData(K key, V data) { } public V putData(V data) { - checkInherentTypeViolation((MapValue) data, tableType); + checkInherentTypeViolation((MapValue) data, tableType); ArrayList newData = new ArrayList<>(); newData.add(data); - Map.Entry entry = new AbstractMap.SimpleEntry(data, data); + Map.Entry entry = new AbstractMap.SimpleEntry<>((K) data, data); List> entryList = new ArrayList<>(); entryList.add(entry); UUID uuid = UUID.randomUUID(); @@ -608,7 +608,7 @@ public KeyHashValueHolder() { @Override public void addData(V data) { - MapValue dataMap = (MapValue) data; + MapValue dataMap = (MapValue) data; checkInherentTypeViolation(dataMap, tableType); K key = this.keyWrapper.wrapKey(dataMap); @@ -621,7 +621,7 @@ public void addData(V data) { maxIntKey = ((Long) TypeChecker.anyToInt(key)).intValue(); } - Map.Entry entry = new AbstractMap.SimpleEntry(key, data); + Map.Entry entry = new AbstractMap.SimpleEntry<>(key, data); Long hash = TableUtils.hash(key, null); if (entries.containsKey(hash)) { @@ -652,8 +652,8 @@ public V getData(K key) { @Override public V putData(K key, V data) { - Map.Entry entry = new AbstractMap.SimpleEntry(key, data); - Object actualKey = this.keyWrapper.wrapKey((MapValue) data); + Map.Entry entry = new AbstractMap.SimpleEntry<>(key, data); + Object actualKey = this.keyWrapper.wrapKey((MapValue) data); Long actualHash = TableUtils.hash(actualKey, null); Long hash = TableUtils.hash(key, null); @@ -681,7 +681,7 @@ private V putNewData(K key, V value, Map.Entry entry, Long hash) { @Override public V putData(V data) { - MapValue dataMap = (MapValue) data; + MapValue dataMap = (MapValue) data; checkInherentTypeViolation(dataMap, tableType); K key = this.keyWrapper.wrapKey(dataMap); Map.Entry entry = new AbstractMap.SimpleEntry<>(key, data); @@ -774,7 +774,7 @@ public DefaultKeyWrapper() { } } - public K wrapKey(MapValue data) { + public K wrapKey(MapValue data) { return (K) data.get(StringUtils.fromString(fieldNames[0])); } } @@ -797,7 +797,7 @@ public MultiKeyWrapper() { } @Override - public K wrapKey(MapValue data) { + public K wrapKey(MapValue data) { TupleValueImpl arr = (TupleValueImpl) ValueCreator .createTupleValue((BTupleType) keyType); for (int i = 0; i < fieldNames.length; i++) { @@ -830,7 +830,7 @@ private void updateIndexKeyMappings(Long hash, K key, V value) { } // This method checks for inherent table type violation - private void checkInherentTypeViolation(MapValue dataMap, TableType type) { + private void checkInherentTypeViolation(MapValue dataMap, TableType type) { if (!TypeChecker.checkIsType(dataMap.getType(), type.getConstrainedType())) { BString reason = getModulePrefixedReason(TABLE_LANG_LIB, INHERENT_TYPE_VIOLATION_ERROR_IDENTIFIER); BString detail = StringUtils.fromString("value type '" + dataMap.getType() + "' inconsistent with the " + diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/TupleValueImpl.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/TupleValueImpl.java index baf8b1029ff4..922b1ce59a21 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/TupleValueImpl.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/TupleValueImpl.java @@ -266,8 +266,8 @@ public boolean getBoolean(long index) { @Override public byte getByte(long index) { Object value = get(index); - if (value instanceof Long) { - return ((Long) value).byteValue(); + if (value instanceof Long l) { + return l.byteValue(); } return (Byte) value; } @@ -426,10 +426,12 @@ public Object shift(long index) { return shift(index, "shift"); } + @Override public Object pop(long index) { return shift(index, "pop"); } + @Override public Object remove(long index) { return shift(index, "remove"); } @@ -530,8 +532,8 @@ public Object copy(Map refs) { refs.put(this, refValueArray); IntStream.range(0, this.size).forEach(i -> { Object value = this.refValues[i]; - if (value instanceof BRefValue) { - values[i] = ((BRefValue) value).copy(refs); + if (value instanceof BRefValue bRefValue) { + values[i] = bRefValue.copy(refs); } else { values[i] = value; } @@ -617,8 +619,8 @@ public void freezeDirect() { this.tupleType = (TupleType) TypeUtils.getImpliedType(type); for (int i = 0; i < this.size; i++) { Object value = this.get(i); - if (value instanceof BRefValue) { - ((BRefValue) value).freezeDirect(); + if (value instanceof BRefValue bRefValue) { + bRefValue.freezeDirect(); } } this.typedesc = null; @@ -628,7 +630,7 @@ public void freezeDirect() { * {@inheritDoc} */ @Override - public IteratorValue getIterator() { + public IteratorValue getIterator() { return new ArrayIterator(this); } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/TypedescValueImpl.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/TypedescValueImpl.java index bea73113906a..39dc6347600a 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/TypedescValueImpl.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/TypedescValueImpl.java @@ -25,6 +25,7 @@ import io.ballerina.runtime.api.values.BLink; import io.ballerina.runtime.api.values.BListInitialValueEntry; import io.ballerina.runtime.api.values.BMapInitialValueEntry; +import io.ballerina.runtime.api.values.BString; import io.ballerina.runtime.api.values.BTypedesc; import io.ballerina.runtime.internal.scheduling.Strand; import io.ballerina.runtime.internal.types.BAnnotatableType; @@ -53,8 +54,8 @@ public class TypedescValueImpl implements TypedescValue { final Type type; final Type describingType; // Type of the value describe by this typedesc. - public MapValue[] closures; - public MapValue annotations; + public MapValue[] closures; + public MapValue annotations; private BTypedesc typedesc; public TypedescValueImpl(Type describingType) { @@ -62,13 +63,13 @@ public TypedescValueImpl(Type describingType) { this.describingType = describingType; } - public TypedescValueImpl(Type describingType, MapValue[] closures) { + public TypedescValueImpl(Type describingType, MapValue[] closures) { this.type = new BTypedescType(describingType); this.describingType = describingType; this.closures = closures; } - public TypedescValueImpl(Type describingType, MapValue[] closures, MapValue annotations) { + public TypedescValueImpl(Type describingType, MapValue[] closures, MapValue annotations) { this(describingType, closures); this.annotations = annotations; ((BAnnotatableType) describingType).setAnnotations(annotations); diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/XmlComment.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/XmlComment.java index 24725ac7bca8..00cab7fe4d6b 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/XmlComment.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/XmlComment.java @@ -47,9 +47,9 @@ public XmlComment(String data, boolean readonly) { } @Override - public IteratorValue getIterator() { + public IteratorValue getIterator() { XmlComment that = this; - return new IteratorValue() { + return new IteratorValue<>() { boolean read = false; @Override public boolean hasNext() { @@ -57,7 +57,7 @@ public boolean hasNext() { } @Override - public Object next() { + public XmlComment next() { if (!read) { this.read = true; return that; diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/XmlItem.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/XmlItem.java index 345e40f8779f..596a091cbc78 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/XmlItem.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/XmlItem.java @@ -385,7 +385,7 @@ private BError createXMLCycleError() { StringUtils.fromString("Cycle detected")); } - private void mergeAdjoiningTextNodesIntoList(List leftList, List appendingList) { + private void mergeAdjoiningTextNodesIntoList(List leftList, List appendingList) { XmlText lastChild = (XmlText) leftList.get(leftList.size() - 1); String firstChildContent = appendingList.get(0).getTextValue(); String mergedTextContent = lastChild.getTextValue() + firstChildContent; @@ -509,8 +509,7 @@ public Object copy(Map refs) { MapValue attributesMap = xmlItem.getAttributesMap(); MapValue copy = (MapValue) this.getAttributesMap().copy(refs); - if (attributesMap instanceof MapValueImpl) { - MapValueImpl map = (MapValueImpl) attributesMap; + if (attributesMap instanceof MapValueImpl map) { map.putAll((Map) copy); } else { for (Map.Entry entry : copy.entrySet()) { @@ -663,9 +662,9 @@ public BXmlSequence getChildrenSeq() { } @Override - public IteratorValue getIterator() { + public IteratorValue getIterator() { XmlItem that = this; - return new IteratorValue() { + return new IteratorValue<>() { boolean read = false; @Override @@ -674,7 +673,7 @@ public boolean hasNext() { } @Override - public Object next() { + public XmlItem next() { if (read) { throw new NoSuchElementException(); } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/XmlNonElementItem.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/XmlNonElementItem.java index 0a40cc982b3c..8a404e5b755e 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/XmlNonElementItem.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/XmlNonElementItem.java @@ -176,15 +176,15 @@ public void removeChildren(String qname) { public abstract OMNode value(); @Override - public IteratorValue getIterator() { - return new IteratorValue() { + public IteratorValue getIterator() { + return new IteratorValue<>() { @Override public boolean hasNext() { return false; } @Override - public Object next() { + public Void next() { throw new NoSuchElementException(); } }; diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/XmlPi.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/XmlPi.java index 764b4e88d460..61f8982271fb 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/XmlPi.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/XmlPi.java @@ -51,9 +51,9 @@ public XmlPi(String data, String target, boolean readonly) { } @Override - public IteratorValue getIterator() { + public IteratorValue getIterator() { XmlPi that = this; - return new IteratorValue() { + return new IteratorValue<>() { boolean read = false; @Override public boolean hasNext() { @@ -61,7 +61,7 @@ public boolean hasNext() { } @Override - public Object next() { + public XmlPi next() { if (!read) { this.read = true; return that; diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/XmlSequence.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/XmlSequence.java index 126983bd1884..03347dfa93c6 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/XmlSequence.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/XmlSequence.java @@ -31,6 +31,7 @@ import io.ballerina.runtime.api.values.BXmlSequence; import io.ballerina.runtime.internal.CycleUtils; import io.ballerina.runtime.internal.IteratorUtils; +import io.ballerina.runtime.internal.XmlFactory; import io.ballerina.runtime.internal.errors.ErrorCodes; import io.ballerina.runtime.internal.errors.ErrorHelper; import io.ballerina.runtime.internal.types.BArrayType; @@ -70,8 +71,12 @@ public XmlSequence() { this.type = PredefinedTypes.TYPE_XML_NEVER; } - public XmlSequence(List children) { - this.children = children; + public XmlSequence(List values) { + if (values.isEmpty()) { + this.children = values; + return; + } + setSequenceMembersConcatenatingAdjacentTextItems(values); } public XmlSequence(BXml child) { @@ -214,7 +219,7 @@ public void setAttributes(BMap attributes) { */ @Override public XmlValue elements() { - List elementsSeq = new ArrayList(); + List elementsSeq = new ArrayList<>(); for (BXml child : children) { if (child.getNodeType() == XmlNodeType.ELEMENT) { elementsSeq.add(child); @@ -612,8 +617,8 @@ public boolean isFrozen() { } @Override - public IteratorValue getIterator() { - return new IteratorValue() { + public IteratorValue getIterator() { + return new IteratorValue<>() { Iterator iterator = children.iterator(); @Override @@ -622,12 +627,35 @@ public boolean hasNext() { } @Override - public Object next() { + public BXml next() { return iterator.next(); } }; } + private void setSequenceMembersConcatenatingAdjacentTextItems(List values) { + ArrayList members = new ArrayList<>(); + boolean isPreviousValueText = false; + StringBuilder text = new StringBuilder(); + for (BXml value : values) { + if (value.getNodeType() == XmlNodeType.TEXT) { + isPreviousValueText = true; + text.append(value.getTextValue()); + continue; + } + if (isPreviousValueText) { + members.add(XmlFactory.createXMLText(StringUtils.fromString(text.toString()))); + isPreviousValueText = false; + text.setLength(0); + } + members.add(value); + } + if (!text.isEmpty()) { + members.add(XmlFactory.createXMLText(StringUtils.fromString(text.toString()))); + } + this.children = members; + } + private Type getSequenceType(Type tempExprType) { return switch (tempExprType.getTag()) { case TypeTags.XML_ELEMENT_TAG -> PredefinedTypes.TYPE_XML_ELEMENT_SEQUENCE; @@ -643,8 +671,8 @@ private void initializeIteratorNextReturnType() { childrenType = children.get(0).getType(); } else { Set types = new HashSet<>(); - for (int i = 0; i < children.size(); i++) { - types.add(children.get(i).getType()); + for (BXml child : children) { + types.add(child.getType()); } childrenType = new BUnionType(new ArrayList<>(types)); } @@ -671,9 +699,8 @@ public boolean equals(Object o, Set visitedValues) { if (o instanceof XmlSequence rhsXMLSequence) { return isXMLSequenceChildrenEqual(this.getChildrenList(), rhsXMLSequence.getChildrenList()); } - if (o instanceof XmlItem) { - return this.getChildrenList().size() == 1 && - isEqual(this.getChildrenList().get(0), o); + if (this.isSingleton() && (o instanceof XmlValue)) { + return isEqual(this.getChildrenList().get(0), o); } return this.getChildrenList().isEmpty() && TypeUtils.getType(o) == PredefinedTypes.TYPE_XML_NEVER; } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/XmlText.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/XmlText.java index 396d9807abb0..d1ea4cd8306d 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/XmlText.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/XmlText.java @@ -92,9 +92,9 @@ public OMNode value() { } @Override - public IteratorValue getIterator() { + public IteratorValue getIterator() { XmlText that = this; - return new IteratorValue() { + return new IteratorValue<>() { boolean read = false; @Override public boolean hasNext() { @@ -102,7 +102,7 @@ public boolean hasNext() { } @Override - public Object next() { + public XmlText next() { if (!read) { this.read = true; return that; @@ -127,11 +127,11 @@ public boolean equals(Object obj) { */ @Override public boolean equals(Object o, Set visitedValues) { - if (o instanceof XmlText rhsXMLText) { - return this.getTextValue().equals(rhsXMLText.getTextValue()); + if ((o instanceof XmlText) || isXmlSequenceWithSingletonTextValue(o)) { + return this.getTextValue().equals(((XmlValue) o).getTextValue()); } - return this.getType() == PredefinedTypes.TYPE_XML_NEVER && (o instanceof XmlSequence) && - ((XmlSequence) o).getChildrenList().isEmpty(); + return this.getType() == PredefinedTypes.TYPE_XML_NEVER && (o instanceof XmlSequence xmlSequence) && + xmlSequence.getChildrenList().isEmpty(); } @Override @@ -143,4 +143,11 @@ public int hashCode() { public Type getType() { return this.type; } + + private boolean isXmlSequenceWithSingletonTextValue(Object o) { + if (!(o instanceof XmlSequence sequence)) { + return false; + } + return sequence.isSingleton() && sequence.getItem(0).getNodeType() == XmlNodeType.TEXT; + } } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/XmlValue.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/XmlValue.java index f6a3b813f4ea..23443629ca47 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/XmlValue.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/XmlValue.java @@ -244,8 +244,8 @@ public Object frozenCopy(Map refs) { @Override public void serialize(OutputStream outputStream) { try { - if (outputStream instanceof BallerinaXmlSerializer) { - ((BallerinaXmlSerializer) outputStream).write(this); + if (outputStream instanceof BallerinaXmlSerializer xmlSerializer) { + xmlSerializer.write(this); } else { BallerinaXmlSerializer xmlSerializer = new BallerinaXmlSerializer(outputStream); xmlSerializer.write(this); diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/ObservabilityConstants.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/ObservabilityConstants.java index ccda1782adff..c519b3185f66 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/ObservabilityConstants.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/ObservabilityConstants.java @@ -24,7 +24,7 @@ * Open Tracing Specification. *

*/ -public class ObservabilityConstants { +public final class ObservabilityConstants { private ObservabilityConstants() { } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/ObserveUtils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/ObserveUtils.java index dcc52ccd6b5a..759bf3f0210b 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/ObserveUtils.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/ObserveUtils.java @@ -63,7 +63,8 @@ * * @since 0.985.0 */ -public class ObserveUtils { +public final class ObserveUtils { + private static final List observers = new CopyOnWriteArrayList<>(); private static final boolean enabled; private static final boolean metricsEnabled; @@ -96,6 +97,9 @@ public class ObserveUtils { enabled = metricsEnabled || tracingEnabled; } + private ObserveUtils() { + } + private static T readConfig(VariableKey specificKey, VariableKey inheritedKey, T defaultValue) { T value; if (ConfigMap.containsKey(specificKey)) { diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/metrics/DefaultMetricRegistry.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/metrics/DefaultMetricRegistry.java index 4004e6888571..f088a929ba8d 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/metrics/DefaultMetricRegistry.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/metrics/DefaultMetricRegistry.java @@ -24,10 +24,13 @@ /** * Hold a default {@link MetricRegistry} instance, which is used by Metric APIs. */ -public class DefaultMetricRegistry { +public final class DefaultMetricRegistry { private static MetricRegistry instance = new MetricRegistry(new NoOpMetricProvider()); + private DefaultMetricRegistry() { + } + /** * Get the default {@link MetricRegistry}. * diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/metrics/MetricConstants.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/metrics/MetricConstants.java index c2f16d24da44..e6e29a1272df 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/metrics/MetricConstants.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/metrics/MetricConstants.java @@ -21,7 +21,7 @@ * Defines the types of the metrics supported. * @since 0.980.0 */ -public class MetricConstants { +public final class MetricConstants { private MetricConstants() {} diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/metrics/PolledGauge.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/metrics/PolledGauge.java index 58bfcbd99e87..e59bca0886a8 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/metrics/PolledGauge.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/metrics/PolledGauge.java @@ -67,25 +67,25 @@ public Builder description(String description) { } @Override - public Builder tags(String... keyValues) { + public Builder tags(String... keyValues) { Tags.tags(this.tags, keyValues); return this; } @Override - public Builder tags(Iterable tags) { + public Builder tags(Iterable tags) { Tags.tags(this.tags, tags); return this; } @Override - public Builder tag(String key, String value) { + public Builder tag(String key, String value) { Tags.tags(this.tags, key, value); return this; } @Override - public Builder tags(Map tags) { + public Builder tags(Map tags) { Tags.tags(this.tags, tags); return this; } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/metrics/Tags.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/metrics/Tags.java index 03468bdc3255..8314ecbecd5a 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/metrics/Tags.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/metrics/Tags.java @@ -23,7 +23,7 @@ /** * Utility methods to add tags to an existing list of {@link Tag Tags}. */ -public class Tags { +public final class Tags { private Tags() { } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/tracer/TraceConstants.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/tracer/TraceConstants.java index c3d811e3ff4f..1b74c86b47e8 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/tracer/TraceConstants.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/tracer/TraceConstants.java @@ -25,7 +25,7 @@ * * @since 0.964.1 */ -public class TraceConstants { +public final class TraceConstants { private TraceConstants() { } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/tracer/TracingUtils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/tracer/TracingUtils.java index 819c8e171902..1747c16ac9b4 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/tracer/TracingUtils.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/tracer/TracingUtils.java @@ -34,7 +34,7 @@ /** * Util class to hold tracing specific util methods. */ -public class TracingUtils { +public final class TracingUtils { private TracingUtils() { } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/transactions/TransactionConstants.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/transactions/TransactionConstants.java index f7ee5d9e9d8a..e8cfd5af24ac 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/transactions/TransactionConstants.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/transactions/TransactionConstants.java @@ -31,7 +31,8 @@ * * @since 1.0 */ -public class TransactionConstants { +public final class TransactionConstants { + //Co-ordinator functions public static final String COORDINATOR_ABORT_TRANSACTION = "abortTransaction"; @@ -72,4 +73,7 @@ public class TransactionConstants { public static final String TIMESTAMP_OBJECT_VALUE_FIELD = "timeValue"; public static final int DEFAULT_TRX_AUTO_COMMIT_TIMEOUT = 120; public static final int DEFAULT_TRX_CLEANUP_TIMEOUT = 600; + + private TransactionConstants() { + } } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/transactions/TransactionLocalContext.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/transactions/TransactionLocalContext.java index 64973ab681ab..3dad3d68f0e9 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/transactions/TransactionLocalContext.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/transactions/TransactionLocalContext.java @@ -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. @@ -41,8 +42,8 @@ public class TransactionLocalContext { private Map allowedTransactionRetryCounts; private Map currentTransactionRetryCounts; private Map transactionContextStore; - private Stack transactionBlockIdStack; - private Stack transactionFailure; + private Deque transactionBlockIdStack; + private Deque transactionFailure; private static final TransactionResourceManager transactionResourceManager = TransactionResourceManager.getInstance(); private boolean isResourceParticipant; @@ -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()); @@ -104,7 +105,7 @@ public void addCurrentTransactionBlockId(String blockId) { } public boolean hasTransactionBlock() { - return !transactionBlockIdStack.empty(); + return !transactionBlockIdStack.isEmpty(); } public String getURL() { @@ -211,7 +212,7 @@ public void markFailure() { } public TransactionFailure getAndClearFailure() { - if (transactionFailure.empty()) { + if (transactionFailure.isEmpty()) { return null; } TransactionFailure failure = transactionFailure.pop(); @@ -220,7 +221,7 @@ public TransactionFailure getAndClearFailure() { } public TransactionFailure getFailure() { - if (transactionFailure.empty()) { + if (transactionFailure.isEmpty()) { return null; } return transactionFailure.peek(); diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/transactions/TransactionResourceManager.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/transactions/TransactionResourceManager.java index da7c241b5116..743c1dc2fd58 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/transactions/TransactionResourceManager.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/transactions/TransactionResourceManager.java @@ -95,8 +95,8 @@ public class TransactionResourceManager { private Map trxRegistry; private Map xidRegistry; - private Map> committedFuncRegistry; - private Map> abortedFuncRegistry; + private Map>> committedFuncRegistry; + private Map>> abortedFuncRegistry; private ConcurrentSkipListSet failedResourceParticipantSet = new ConcurrentSkipListSet<>(); private ConcurrentSkipListSet failedLocalParticipantSet = new ConcurrentSkipListSet<>(); @@ -259,7 +259,7 @@ public void register(String transactionId, String transactionBlockId, BallerinaT * @param transactionBlockId the block id of the transaction * @param fpValue the function pointer for the committed function */ - public void registerCommittedFunction(String transactionBlockId, BFunctionPointer fpValue) { + public void registerCommittedFunction(String transactionBlockId, BFunctionPointer fpValue) { if (fpValue != null) { committedFuncRegistry.computeIfAbsent(transactionBlockId, list -> new ArrayList<>()).add(fpValue); } @@ -271,7 +271,7 @@ public void registerCommittedFunction(String transactionBlockId, BFunctionPointe * @param transactionBlockId the block id of the transaction * @param fpValue the function pointer for the aborted function */ - public void registerAbortedFunction(String transactionBlockId, BFunctionPointer fpValue) { + public void registerAbortedFunction(String transactionBlockId, BFunctionPointer fpValue) { if (fpValue != null) { abortedFuncRegistry.computeIfAbsent(transactionBlockId, list -> new ArrayList<>()).add(fpValue); } @@ -532,7 +532,7 @@ public void notifyTransactionAbort(String transactionBlockId) { * @return Array of rollback handlers */ public BArray getRegisteredRollbackHandlerList() { - List abortFunctions = + List> abortFunctions = abortedFuncRegistry.get(Scheduler.getStrand().currentTrxContext.getGlobalTransactionId()); if (abortFunctions != null && !abortFunctions.isEmpty()) { Collections.reverse(abortFunctions); @@ -548,7 +548,7 @@ public BArray getRegisteredRollbackHandlerList() { * @return Array of commit handlers */ public BArray getRegisteredCommitHandlerList() { - List commitFunctions = + List> commitFunctions = committedFuncRegistry.get(Scheduler.getStrand().currentTrxContext.getGlobalTransactionId()); if (commitFunctions != null && !commitFunctions.isEmpty()) { Collections.reverse(commitFunctions); diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/transactions/TransactionUtils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/transactions/TransactionUtils.java index 37d17656df56..33b0f88edcdc 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/transactions/TransactionUtils.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/transactions/TransactionUtils.java @@ -47,12 +47,15 @@ * * @since 1.0 */ -public class TransactionUtils { +public final class TransactionUtils { private static final StrandMetadata TRX_METADATA = new StrandMetadata(BALLERINA_BUILTIN_PKG_PREFIX, TRANSACTION_PACKAGE_NAME, TRANSACTION_PACKAGE_VERSION, "onAbort"); + private TransactionUtils() { + } + public static void notifyTransactionAbort(Strand strand, String globalTransactionId, String transactionBlockId) { executeFunction(strand.scheduler, TransactionUtils.class.getClassLoader(), TRANSACTION_PACKAGE_FQN, TRANSACTION_BLOCK_CLASS_NAME, COORDINATOR_ABORT_TRANSACTION, globalTransactionId, diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/transactions/XIDGenerator.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/transactions/XIDGenerator.java index bd3b05674d87..4131ba35b8d5 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/transactions/XIDGenerator.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/transactions/XIDGenerator.java @@ -25,7 +25,7 @@ * * @since 1.0 */ -public class XIDGenerator { +public final class XIDGenerator { private static final SecureRandom secureRand = new SecureRandom(); private static final AtomicInteger formatIdIdGenerator = new AtomicInteger(); diff --git a/bvm/ballerina-runtime/src/test/java/io/ballerina/runtime/test/RuntimeUtilTests.java b/bvm/ballerina-runtime/src/test/java/io/ballerina/runtime/test/RuntimeUtilTests.java index f004dfb8fcb9..2d862f8909be 100644 --- a/bvm/ballerina-runtime/src/test/java/io/ballerina/runtime/test/RuntimeUtilTests.java +++ b/bvm/ballerina-runtime/src/test/java/io/ballerina/runtime/test/RuntimeUtilTests.java @@ -49,8 +49,8 @@ public void testVerifyJavaCompatibilityNegative() { // versions in the format" {compiledVersion, runtimeVersion, supportedVersionRange} String[][] versions = { { "1.8.0_144", "1.7.0_1", "1.8.*" }, { "1.8.0_144", "9", "1.8.*" }, { "9.0.1", "10.0.2.1", "9.0.*" }, { "9", "10.0.2.1", "9.0.*" }, { "10", "9", "10.0.*" } }; - for (int i = 0; i < versions.length; i++) { - testVersionsNegative(versions[i][0], versions[i][1], versions[i][2]); + for (String[] version : versions) { + testVersionsNegative(version[0], version[1], version[2]); } } @@ -59,8 +59,8 @@ public void testVerifyJavaCompatibilityPositive() { // versions in the format" {compiledVersion, runtimeVersion} String[][] versions = { { "1.8.0_144", "1.8.0_144" }, { "1.8.0_144", "1.8.0_221" }, { "9.0_221", "9" }, { "9", "9.0_221" }, { "10.0.1", "10.0.2.1" }, { "10", "10" } }; - for (int i = 0; i < versions.length; i++) { - testVersionsPositive(versions[i][0], versions[i][1]); + for (String[] version : versions) { + testVersionsPositive(version[0], version[1]); } } diff --git a/bvm/ballerina-runtime/src/test/java/io/ballerina/runtime/test/TestUtils.java b/bvm/ballerina-runtime/src/test/java/io/ballerina/runtime/test/TestUtils.java index 7d703830a2b9..b663f5b4ab6d 100644 --- a/bvm/ballerina-runtime/src/test/java/io/ballerina/runtime/test/TestUtils.java +++ b/bvm/ballerina-runtime/src/test/java/io/ballerina/runtime/test/TestUtils.java @@ -31,7 +31,10 @@ * Utils class for runtime unit tests. * @since 2.0.0 */ -public class TestUtils { +public final class TestUtils { + + private TestUtils() { + } public static Path getConfigPath(String configFileName) { return Paths.get(RuntimeUtils.USER_DIR, "src", "test", "resources", "config_files", configFileName); diff --git a/cli/ballerina-cli/src/main/java/io/ballerina/cli/cmd/CommandUtil.java b/cli/ballerina-cli/src/main/java/io/ballerina/cli/cmd/CommandUtil.java index 27212ddfeb2a..8db23f80deec 100644 --- a/cli/ballerina-cli/src/main/java/io/ballerina/cli/cmd/CommandUtil.java +++ b/cli/ballerina-cli/src/main/java/io/ballerina/cli/cmd/CommandUtil.java @@ -104,7 +104,8 @@ * * @since 2.0.0 */ -public class CommandUtil { +public final class CommandUtil { + public static final String ORG_NAME = "ORG_NAME"; public static final String PKG_NAME = "PKG_NAME"; public static final String DIST_VERSION = "DIST_VERSION"; @@ -126,6 +127,9 @@ public class CommandUtil { private static boolean exitWhenFinish; private static String platform; + private CommandUtil() { + } + static void setPrintStream(PrintStream errStream) { CommandUtil.errStream = errStream; } @@ -872,21 +876,22 @@ private static void createDefaultDevContainer(Path path) throws IOException { public static List getTemplates() { try { Path templateDir = getTemplatePath(); - Stream walk = Files.walk(templateDir, 1); + try (Stream walk = Files.walk(templateDir, 1)) { - List templates = walk.filter(Files::isDirectory) + List templates = walk.filter(Files::isDirectory) .filter(directory -> !templateDir.equals(directory)) .map(directory -> directory.getFileName()) .filter(Objects::nonNull) .map(Path::toString) - .collect(Collectors.toList()); + .toList(); - if (null != jarFs) { - return templates.stream().map(t -> t - .replace(jarFs.getSeparator(), "")) - .collect(Collectors.toList()); - } else { - return templates; + if (null != jarFs) { + return templates.stream().map(t -> t + .replace(jarFs.getSeparator(), "")) + .toList(); + } else { + return templates; + } } } catch (IOException | URISyntaxException e) { @@ -1000,7 +1005,7 @@ private static void initToolPackage(Path path, String packageName) throws IOExce Files.writeString(balToolToml, balToolManifest); } - protected static PackageVersion findLatest(List packageVersions) { + private static PackageVersion findLatest(List packageVersions) { if (packageVersions.isEmpty()) { return null; } @@ -1011,7 +1016,7 @@ protected static PackageVersion findLatest(List packageVersions) return latestVersion; } - protected static PackageVersion getLatest(PackageVersion v1, PackageVersion v2) { + private static PackageVersion getLatest(PackageVersion v1, PackageVersion v2) { SemanticVersion semVer1 = v1.value(); SemanticVersion semVer2 = v2.value(); boolean isV1PreReleaseVersion = semVer1.isPreReleaseVersion(); @@ -1035,7 +1040,7 @@ public static List getPackageVersions(Path balaPackagePath) { return pathToVersions(versions); } - protected static List pathToVersions(List versions) { + private static List pathToVersions(List versions) { List availableVersions = new ArrayList<>(); versions.stream().map(path -> Optional.ofNullable(path) .map(Path::getFileName) @@ -1084,8 +1089,10 @@ private static String removeLastCharacter(String str) { public static String checkTemplateFilesExists(String template, Path packagePath) throws URISyntaxException, IOException { Path templateDir = getTemplatePath().resolve(template); - Stream paths = Files.list(templateDir); - List templateFilePathList = paths.toList(); + List templateFilePathList; + try (Stream paths = Files.list(templateDir)) { + templateFilePathList = paths.toList(); + } StringBuilder existingFiles = new StringBuilder(); for (Path path : templateFilePathList) { Optional fileNameOptional = Optional.ofNullable(path.getFileName()).map(Path::toString); diff --git a/cli/ballerina-cli/src/main/java/io/ballerina/cli/cmd/Constants.java b/cli/ballerina-cli/src/main/java/io/ballerina/cli/cmd/Constants.java index f07d647eaa9f..ea52c012f1d0 100644 --- a/cli/ballerina-cli/src/main/java/io/ballerina/cli/cmd/Constants.java +++ b/cli/ballerina-cli/src/main/java/io/ballerina/cli/cmd/Constants.java @@ -22,7 +22,8 @@ * * @since 2.0.0 */ -public class Constants { +public final class Constants { + public static final String BUILD_COMMAND = "build"; public static final String RUN_COMMAND = "run"; public static final String DOC_COMMAND = "doc"; @@ -61,4 +62,7 @@ public class Constants { public static final String DEBUG_OPTION = "--debug"; public static final String VERSION_SHORT_OPTION = "-v"; public static final String HELP_SHORT_OPTION = "-h"; + + private Constants() { + } } diff --git a/cli/ballerina-cli/src/main/java/io/ballerina/cli/cmd/PullCommand.java b/cli/ballerina-cli/src/main/java/io/ballerina/cli/cmd/PullCommand.java index 1b201d6c8c3e..79fb92c02971 100644 --- a/cli/ballerina-cli/src/main/java/io/ballerina/cli/cmd/PullCommand.java +++ b/cli/ballerina-cli/src/main/java/io/ballerina/cli/cmd/PullCommand.java @@ -30,6 +30,7 @@ import io.ballerina.projects.internal.model.Repository; import io.ballerina.projects.util.ProjectConstants; import io.ballerina.projects.util.ProjectUtils; +import org.apache.commons.io.FileUtils; import org.ballerinalang.central.client.CentralAPIClient; import org.ballerinalang.central.client.CentralClientConstants; import org.ballerinalang.central.client.exceptions.CentralClientException; @@ -311,8 +312,7 @@ private void pullFromMavenRepo(Settings settings, String orgName, String package JsonObject resultObj = new Gson().fromJson(bufferedReader, JsonObject.class); String platform = resultObj.get(PLATFORM).getAsString(); Path actualBalaPath = mavenBalaCachePath.resolve(platform); - org.apache.commons.io.FileUtils.copyDirectory(temporaryExtractionPath.toFile(), - actualBalaPath.toFile()); + FileUtils.copyDirectory(temporaryExtractionPath.toFile(), actualBalaPath.toFile()); } } catch (MavenResolverClientException e) { errStream.println("unexpected error occurred while pulling package:" + e.getMessage()); diff --git a/cli/ballerina-cli/src/main/java/io/ballerina/cli/launcher/BallerinaCliCommands.java b/cli/ballerina-cli/src/main/java/io/ballerina/cli/launcher/BallerinaCliCommands.java index 8d36f6b0ad62..e65001c91377 100644 --- a/cli/ballerina-cli/src/main/java/io/ballerina/cli/launcher/BallerinaCliCommands.java +++ b/cli/ballerina-cli/src/main/java/io/ballerina/cli/launcher/BallerinaCliCommands.java @@ -22,11 +22,14 @@ * * @since 0.970.0 */ -public class BallerinaCliCommands { +public final class BallerinaCliCommands { public static final String DEFAULT = "default"; public static final String HELP = "help"; public static final String VERSION = "version"; public static final String RUN = "run"; public static final String HOME = "home"; + + private BallerinaCliCommands() { + } } diff --git a/cli/ballerina-cli/src/main/java/io/ballerina/cli/launcher/LauncherUtils.java b/cli/ballerina-cli/src/main/java/io/ballerina/cli/launcher/LauncherUtils.java index 17cb285e382e..f4b163040d58 100644 --- a/cli/ballerina-cli/src/main/java/io/ballerina/cli/launcher/LauncherUtils.java +++ b/cli/ballerina-cli/src/main/java/io/ballerina/cli/launcher/LauncherUtils.java @@ -47,7 +47,10 @@ * * @since 0.8.0 */ -public class LauncherUtils { +public final class LauncherUtils { + + private LauncherUtils() { + } public static Path getSourceRootPath(String sourceRoot) { // Get source root path. @@ -84,8 +87,8 @@ public static BLauncherException createLauncherException(String errorMsg) { public static BLauncherException createLauncherException(String errorPrefix, Throwable cause) { String message; - if (cause instanceof BError) { - message = ((BError) cause).getPrintableStackTrace(); + if (cause instanceof BError bError) { + message = bError.getPrintableStackTrace(); } else { StringWriter sw = new StringWriter(); cause.printStackTrace(new PrintWriter(sw)); diff --git a/cli/ballerina-cli/src/main/java/io/ballerina/cli/launcher/Main.java b/cli/ballerina-cli/src/main/java/io/ballerina/cli/launcher/Main.java index 292f42f2bb0f..4b0d8a039e21 100644 --- a/cli/ballerina-cli/src/main/java/io/ballerina/cli/launcher/Main.java +++ b/cli/ballerina-cli/src/main/java/io/ballerina/cli/launcher/Main.java @@ -45,7 +45,8 @@ * * @since 0.8.0 */ -public class Main { +public final class Main { + private static final String UNMATCHED_ARGUMENT_PREFIX = "Unmatched argument"; private static final String MISSING_REQUIRED_PARAMETER_PREFIX = "Missing required parameter"; private static final String COMPILATION_ERROR_MESSAGE = "compilation contains errors"; @@ -53,6 +54,9 @@ public class Main { private static final PrintStream errStream = System.err; private static final PrintStream outStream = System.out; + private Main() { + } + public static void main(String... args) { try { Optional optionalInvokedCmd = getInvokedCmd(args); diff --git a/cli/ballerina-cli/src/main/java/io/ballerina/cli/launcher/util/BCompileUtil.java b/cli/ballerina-cli/src/main/java/io/ballerina/cli/launcher/util/BCompileUtil.java index 70e75a5df50f..d54baa503df6 100644 --- a/cli/ballerina-cli/src/main/java/io/ballerina/cli/launcher/util/BCompileUtil.java +++ b/cli/ballerina-cli/src/main/java/io/ballerina/cli/launcher/util/BCompileUtil.java @@ -26,7 +26,10 @@ * * @since 0.94 */ -public class BCompileUtil { +public final class BCompileUtil { + + private BCompileUtil() { + } public static String readFileAsString(String path) throws IOException { StringBuilder sb = new StringBuilder(); diff --git a/cli/ballerina-cli/src/main/java/io/ballerina/cli/launcher/util/BalToolsUtil.java b/cli/ballerina-cli/src/main/java/io/ballerina/cli/launcher/util/BalToolsUtil.java index d0bce40181ea..d92abf44ff4e 100644 --- a/cli/ballerina-cli/src/main/java/io/ballerina/cli/launcher/util/BalToolsUtil.java +++ b/cli/ballerina-cli/src/main/java/io/ballerina/cli/launcher/util/BalToolsUtil.java @@ -44,7 +44,6 @@ import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.stream.Collectors; import java.util.stream.Stream; import static io.ballerina.cli.cmd.Constants.ADD_COMMAND; @@ -96,7 +95,8 @@ * * @since 2201.8.0 */ -public class BalToolsUtil { +public final class BalToolsUtil { + private static final String TOOL = "tool"; private static final String LIBS = "libs"; @@ -122,6 +122,9 @@ public class BalToolsUtil { .resolve(REPOSITORIES_DIR).resolve(CENTRAL_REPOSITORY_CACHE_NAME) .resolve(ProjectConstants.BALA_DIR_NAME); + private BalToolsUtil() { + } + public static boolean isNonBuiltInToolCommand(String commandName) { return isToolCommand(commandName) && !builtInToolCommands.contains(commandName); } @@ -185,7 +188,7 @@ private static List getToolCommandJarAndDependencyJars(String commandName) .resolve(TOOL).resolve(LIBS) .toFile())) .flatMap(List::stream) - .collect(Collectors.toList()); + .toList(); } Optional toolOpt = balToolsManifest.getActiveTool(commandName); @@ -276,7 +279,7 @@ public static void updateOldBalToolsToml() { } catch (ProjectException ignore) { return false; } - })).map(File::getName).collect(Collectors.toList()); + })).map(File::getName).toList(); Optional latestVersion = getLatestVersion(versions); versions.stream().forEach(version -> { diff --git a/cli/ballerina-cli/src/main/java/io/ballerina/cli/task/CreateTestExecutableTask.java b/cli/ballerina-cli/src/main/java/io/ballerina/cli/task/CreateTestExecutableTask.java index 947e23792859..03a12e07f211 100644 --- a/cli/ballerina-cli/src/main/java/io/ballerina/cli/task/CreateTestExecutableTask.java +++ b/cli/ballerina-cli/src/main/java/io/ballerina/cli/task/CreateTestExecutableTask.java @@ -43,6 +43,7 @@ import java.io.File; import java.io.IOException; import java.io.PrintStream; +import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; @@ -341,7 +342,7 @@ private void writeCmdArgsToFile(Path path, Target target, Path testSuiteJsonPath // Write the cmdArgs to a file in path Path writingPath = path.resolve(ProjectConstants.TEST_RUNTIME_MAIN_ARGS_FILE); - try (BufferedWriter writer = java.nio.file.Files.newBufferedWriter(writingPath)) { + try (BufferedWriter writer = Files.newBufferedWriter(writingPath)) { for (String arg : cmdArgs) { writer.write(arg); writer.newLine(); diff --git a/cli/ballerina-cli/src/main/java/io/ballerina/cli/task/RunBuildToolsTask.java b/cli/ballerina-cli/src/main/java/io/ballerina/cli/task/RunBuildToolsTask.java index 75a5c96ff471..843b035b61d0 100644 --- a/cli/ballerina-cli/src/main/java/io/ballerina/cli/task/RunBuildToolsTask.java +++ b/cli/ballerina-cli/src/main/java/io/ballerina/cli/task/RunBuildToolsTask.java @@ -368,6 +368,6 @@ private static List getToolCommandJarAndDependencyJars(List res .resolve(TOOL).resolve(LIBS) .toFile())) .flatMap(List::stream) - .collect(Collectors.toList()); + .toList(); } } diff --git a/cli/ballerina-cli/src/main/java/io/ballerina/cli/task/RunTestsTask.java b/cli/ballerina-cli/src/main/java/io/ballerina/cli/task/RunTestsTask.java index 78c3a005a4ea..d6f54a96534d 100644 --- a/cli/ballerina-cli/src/main/java/io/ballerina/cli/task/RunTestsTask.java +++ b/cli/ballerina-cli/src/main/java/io/ballerina/cli/task/RunTestsTask.java @@ -54,7 +54,6 @@ import java.util.Map; import java.util.Set; import java.util.regex.Pattern; -import java.util.stream.Collectors; import java.util.stream.Stream; import static io.ballerina.cli.launcher.LauncherUtils.createLauncherException; @@ -336,7 +335,10 @@ public String getAgentCommand(Target target, Package currentPackage, Set private List getAllSourceFilePaths(String projectRootString) throws IOException { List sourceFilePaths = new ArrayList<>(); - List paths = Files.walk(Paths.get(projectRootString), 3).toList(); + List paths; + try (Stream stream = Files.walk(Paths.get(projectRootString), 3)) { + paths = stream.toList(); + } if (isWindows) { projectRootString = projectRootString.replace(PATH_SEPARATOR, EXCLUDES_PATTERN_PATH_SEPARATOR); @@ -359,7 +361,7 @@ private List getAllSourceFilePaths(String projectRootString) throws IOExce private static List filterPathStream(Stream pathStream, String combinedPattern) { return pathStream.filter( FileSystems.getDefault().getPathMatcher("glob:" + combinedPattern)::matches) - .collect(Collectors.toList()); + .toList(); } private void getclassFromSourceFilePath(List sourcePatternList, Package currentPackage, diff --git a/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/BrowserLauncher.java b/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/BrowserLauncher.java index 0172fa5c59a4..04304c3eb4a5 100644 --- a/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/BrowserLauncher.java +++ b/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/BrowserLauncher.java @@ -22,7 +22,7 @@ * * @since 2.0.0 */ -class BrowserLauncher { +final class BrowserLauncher { private BrowserLauncher() { } diff --git a/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/BuildUtils.java b/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/BuildUtils.java index caab4d34c6de..a1da4720f8c8 100644 --- a/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/BuildUtils.java +++ b/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/BuildUtils.java @@ -28,7 +28,11 @@ * @since 2201.9.0 */ -public class BuildUtils { +public final class BuildUtils { + + private BuildUtils() { + } + public static void notifyPlugins(Project project, Target target) { ServiceLoader processorServiceLoader = ServiceLoader.load(CompilerPlugin.class); for (CompilerPlugin plugin : processorServiceLoader) { diff --git a/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/CentralUtils.java b/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/CentralUtils.java index dc387b8d63d8..9383d241ce34 100644 --- a/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/CentralUtils.java +++ b/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/CentralUtils.java @@ -38,7 +38,7 @@ * * @since 2.0.0 */ -public class CentralUtils { +public final class CentralUtils { private static final String BALLERINA_CENTRAL_PRODUCTION_URL = "https://central.ballerina.io"; private static final String BALLERINA_CENTRAL_STAGING_URL = "https://staging-central.ballerina.io"; diff --git a/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/DebugUtils.java b/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/DebugUtils.java index 340f367a9b40..66fc823ad664 100644 --- a/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/DebugUtils.java +++ b/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/DebugUtils.java @@ -10,12 +10,15 @@ * * @since 2.0.0 */ -public class DebugUtils { +public final class DebugUtils { private static final String DEBUG_ARGS_JAVA = "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y"; private static final String JAVA_VERSION_PROP = "java.version"; private static final String COMPATIBLE_JRE_VERSION = "17"; + private DebugUtils() { + } + /** * Evaluates whether the ballerina program should be running on debug mode. * diff --git a/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/FileUtils.java b/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/FileUtils.java index 18b6d2306cbb..552a6d71566e 100644 --- a/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/FileUtils.java +++ b/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/FileUtils.java @@ -36,7 +36,11 @@ * * @since 2.0.0 */ -public class FileUtils { +public final class FileUtils { + + private FileUtils() { + } + /** * Get the name of the without the extension. * diff --git a/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/GraalVMCompatibilityUtils.java b/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/GraalVMCompatibilityUtils.java index 3edf9219ddd5..83ac291c8730 100644 --- a/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/GraalVMCompatibilityUtils.java +++ b/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/GraalVMCompatibilityUtils.java @@ -35,7 +35,10 @@ * * @since 2201.7.0 */ -public class GraalVMCompatibilityUtils { +public final class GraalVMCompatibilityUtils { + + private GraalVMCompatibilityUtils() { + } private static boolean hasExternalPlatformDependencies(io.ballerina.projects.Package pkg) { // Check if external platform dependencies are defined diff --git a/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/NativeUtils.java b/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/NativeUtils.java index 97992829f6ae..2a4eae1000d1 100644 --- a/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/NativeUtils.java +++ b/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/NativeUtils.java @@ -61,7 +61,6 @@ import java.util.Map; import java.util.StringJoiner; import java.util.jar.JarOutputStream; -import java.util.stream.Collectors; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; @@ -89,7 +88,8 @@ * * @since 2.3.0 */ -public class NativeUtils { +public final class NativeUtils { + private static final String MODULE_INIT_CLASS_NAME = "$_init"; private static final String TEST_EXEC_FUNCTION = "__execute__"; public static final String OS = System.getProperty("os.name").toLowerCase(Locale.getDefault()); @@ -109,6 +109,9 @@ public class NativeUtils { "io.ballerina.runtime.api.values.BString" }); + private NativeUtils() { + } + //Add dynamically loading classes and methods to reflection config public static void createReflectConfig(Path nativeConfigPath, Package currentPackage, Map testSuiteMap) throws IOException { @@ -169,9 +172,7 @@ public static void createReflectConfig(Path nativeConfigPath, Package currentPac if (mockedFunctionClassFile.isFile()) { BufferedReader br = Files.newBufferedReader(mockedFunctionClassPath, StandardCharsets.UTF_8); Gson gsonRead = new Gson(); - Map testFileMockedFunctionMapping = gsonRead.fromJson(br, - new TypeToken>() { - }.getType()); + Map testFileMockedFunctionMapping = gsonRead.fromJson(br, new TypeToken<>() { }); if (!testFileMockedFunctionMapping.isEmpty()) { ReflectConfigClass originalTestFileRefConfClz; for (Map.Entry testFileMockedFunctionMappingEntry : @@ -191,12 +192,12 @@ public static void createReflectConfig(Path nativeConfigPath, Package currentPac } HashSet methodSet = getMethodSet(qualifiedTestClass); originalTestFileRefConfClz = new ReflectConfigClass(qualifiedTestClassName); - for (int i = 0; i < mockedFunctions.length; i++) { - if (!methodSet.contains(mockedFunctions[i])) { + for (String mockedFunction : mockedFunctions) { + if (!methodSet.contains(mockedFunction)) { continue; } originalTestFileRefConfClz.addReflectConfigClassMethod( - new ReflectConfigClassMethod(mockedFunctions[i])); + new ReflectConfigClassMethod(mockedFunction)); originalTestFileRefConfClz.setUnsafeAllocated(true); originalTestFileRefConfClz.setAllDeclaredFields(true); originalTestFileRefConfClz.setQueryAllDeclaredMethods(true); @@ -601,9 +602,8 @@ public static String getClassPath(Map testSuiteMap) { dependencies.addAll(testSuiteEntry.getValue().getTestExecutionDependencies()); } - dependencies = dependencies.stream().distinct().collect(Collectors.toList()); - dependencies = dependencies.stream().map((x) -> convertWinPathToUnixFormat(addQuotationMarkToString(x))) - .collect(Collectors.toList()); + dependencies = dependencies.stream().distinct() + .map((x) -> convertWinPathToUnixFormat(addQuotationMarkToString(x))).toList(); StringJoiner classPath = new StringJoiner(File.pathSeparator); dependencies.forEach(classPath::add); diff --git a/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/OsUtils.java b/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/OsUtils.java index 8280c003cae3..5d79c8a4ee38 100644 --- a/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/OsUtils.java +++ b/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/OsUtils.java @@ -23,10 +23,13 @@ * * @since 2.0.0 */ -public class OsUtils { +public final class OsUtils { private static final String OS = System.getProperty("os.name").toLowerCase(Locale.getDefault()); + private OsUtils() { + } + public static boolean isWindows() { return (OS.contains("win")); } diff --git a/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/PrintUtils.java b/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/PrintUtils.java index 54ae8cda1855..6c59d8ddabeb 100644 --- a/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/PrintUtils.java +++ b/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/PrintUtils.java @@ -35,7 +35,7 @@ * * @since 2.0.0 */ -public class PrintUtils { +public final class PrintUtils { private static final PrintStream outStream = System.out; diff --git a/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/RunCommandExecutor.java b/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/RunCommandExecutor.java index 803f4f61b6fb..1b3644692ee0 100644 --- a/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/RunCommandExecutor.java +++ b/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/RunCommandExecutor.java @@ -45,6 +45,7 @@ public RunCommandExecutor(RunCommand runCommand, PrintStream outStream) { this.runtimePanic = false; } + @Override public void run() { // We use the original runCommand instance with the watch field set to false. That will preserve all the // build options passed by the developer. diff --git a/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/TestUtils.java b/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/TestUtils.java index facd0066b192..a353342ada34 100644 --- a/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/TestUtils.java +++ b/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/TestUtils.java @@ -62,12 +62,12 @@ import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.StringJoiner; -import java.util.stream.Collectors; import static io.ballerina.cli.launcher.LauncherUtils.createLauncherException; import static org.ballerinalang.test.runtime.util.TesterinaConstants.COVERAGE_DIR; @@ -90,7 +90,10 @@ * * @since 2.3.0 */ -public class TestUtils { +public final class TestUtils { + + private TestUtils() { + } public static void generateCoverage(Project project, TestReport testReport, JBallerinaBackend jBallerinaBackend, String includesInCoverage, String coverageReportFormat, @@ -106,11 +109,11 @@ public static void generateCoverage(Project project, TestReport testReport, JBal Map moduleCoverageMap = initializeCoverageMap(project); // Following lists will hold the coverage information needed for the coverage XML file generation. - List packageSourceCoverageList = new ArrayList(); - List packageNativeClassCoverageList = new ArrayList(); - List packageBalClassCoverageList = new ArrayList(); - List packageExecData = new ArrayList(); - List packageSessionInfo = new ArrayList(); + List packageSourceCoverageList = new ArrayList<>(); + List packageNativeClassCoverageList = new ArrayList<>(); + List packageBalClassCoverageList = new ArrayList<>(); + List packageExecData = new ArrayList<>(); + List packageSessionInfo = new ArrayList<>(); for (ModuleId moduleId : project.currentPackage().moduleIds()) { Module module = project.currentPackage().module(moduleId); CoverageReport coverageReport = new CoverageReport(module, moduleCoverageMap, @@ -120,9 +123,9 @@ public static void generateCoverage(Project project, TestReport testReport, JBal coverageModules.get(module.moduleName().toString()), exclusionClassList); } // Traverse coverage map and add module wise coverage to test report - for (Map.Entry mapElement : moduleCoverageMap.entrySet()) { - String moduleName = (String) mapElement.getKey(); - ModuleCoverage moduleCoverage = (ModuleCoverage) mapElement.getValue(); + for (Map.Entry mapElement : moduleCoverageMap.entrySet()) { + String moduleName = mapElement.getKey(); + ModuleCoverage moduleCoverage = mapElement.getValue(); testReport.addCoverage(moduleName, moduleCoverage); } if (CodeCoverageUtils.isRequestedReportFormat(coverageReportFormat, @@ -479,11 +482,10 @@ private static String getFunctionToMockClassName(String id) { */ public static String getClassPath(JBallerinaBackend jBallerinaBackend, Package currentPackage) { JarResolver jarResolver = jBallerinaBackend.jarResolver(); + Set jars = new HashSet<>(getModuleJarPaths(jBallerinaBackend, currentPackage)); - List dependencies = getTestDependencyPaths(currentPackage, jarResolver); - - List jarList = getModuleJarPaths(jBallerinaBackend, currentPackage); - dependencies.removeAll(jarList); + List dependencies = getTestDependencyPaths(currentPackage, jarResolver) + .stream().filter(dependency -> !jars.contains(dependency)).toList(); StringJoiner classPath = joinClassPaths(dependencies); return classPath.toString(); @@ -519,7 +521,7 @@ public static List getTestDependencyPaths(Package currentPackage, JarResol } } } - return dependencies.stream().distinct().collect(Collectors.toList()); + return dependencies.stream().distinct().toList(); } /** @@ -546,7 +548,7 @@ public static List getModuleJarPaths(JBallerinaBackend jBallerinaBackend, } } - return moduleJarPaths.stream().distinct().collect(Collectors.toList()); + return moduleJarPaths.stream().distinct().toList(); } private static PlatformLibrary getCodeGeneratedTestLibrary(JBallerinaBackend jBallerinaBackend, diff --git a/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/TokenUpdater.java b/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/TokenUpdater.java index 45029c9dd0c6..1041b115f7aa 100644 --- a/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/TokenUpdater.java +++ b/cli/ballerina-cli/src/main/java/io/ballerina/cli/utils/TokenUpdater.java @@ -41,7 +41,7 @@ * * @since 1.2.0 */ -public class TokenUpdater { +public final class TokenUpdater { private static PrintStream errStream = System.err; private static PrintStream outStream = System.out; diff --git a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/AddCommandTest.java b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/AddCommandTest.java index be8e7c04670c..b3b01d39e7fa 100644 --- a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/AddCommandTest.java +++ b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/AddCommandTest.java @@ -38,6 +38,7 @@ public class AddCommandTest extends BaseCommandTest { private Path projectPath; private Path modulesPath; + @Override @BeforeClass public void setup() throws IOException { super.setup(); diff --git a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/BaseCommandTest.java b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/BaseCommandTest.java index 9505cfc31587..795ded5d5033 100644 --- a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/BaseCommandTest.java +++ b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/BaseCommandTest.java @@ -37,6 +37,7 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; +import java.util.stream.Stream; import static io.ballerina.projects.util.ProjectConstants.CENTRAL_REPOSITORY_CACHE_NAME; @@ -126,7 +127,7 @@ protected void cacheBalaToCentralRepository(Path balaProjectDirectory, String or Path balaDestPath = centralRepoPath.resolve(org).resolve(name).resolve(version).resolve(platform); Files.createDirectories(balaDestPath); - try (var files = Files.walk(balaProjectDirectory)) { + try (Stream files = Files.walk(balaProjectDirectory)) { files.forEach(a -> { Path b = Paths.get(String.valueOf(balaDestPath), a.toString().substring(balaProjectDirectory.toString().length())); diff --git a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/BuildCommandTest.java b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/BuildCommandTest.java index 9a6fd98552aa..d3cda0caba6f 100644 --- a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/BuildCommandTest.java +++ b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/BuildCommandTest.java @@ -74,6 +74,7 @@ public class BuildCommandTest extends BaseCommandTest { Environment environment = EnvironmentBuilder.getBuilder().setUserHome(customUserHome).build(); ProjectEnvironmentBuilder projectEnvironmentBuilder = ProjectEnvironmentBuilder.getBuilder(environment); + @Override @BeforeClass public void setup() throws IOException { super.setup(); diff --git a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/BuildNativeImageCommandTest.java b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/BuildNativeImageCommandTest.java index 2e95c1aab006..de34ef7c8c37 100644 --- a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/BuildNativeImageCommandTest.java +++ b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/BuildNativeImageCommandTest.java @@ -48,6 +48,7 @@ public class BuildNativeImageCommandTest extends BaseCommandTest { private Path testDistCacheDirectory; ProjectEnvironmentBuilder projectEnvironmentBuilder; + @Override @BeforeClass public void setup() throws IOException { super.setup(); diff --git a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/CleanCommandTest.java b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/CleanCommandTest.java index a3503b645a59..2602697508d7 100644 --- a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/CleanCommandTest.java +++ b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/CleanCommandTest.java @@ -42,6 +42,7 @@ public class CleanCommandTest extends BaseCommandTest { private Path testResources; + @Override @BeforeClass public void setup() throws IOException { super.setup(); diff --git a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/CommandOutputUtils.java b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/CommandOutputUtils.java index b7c48399bb58..d6db5cd7f148 100644 --- a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/CommandOutputUtils.java +++ b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/CommandOutputUtils.java @@ -38,7 +38,7 @@ * * @since 2.0.0 */ -public class CommandOutputUtils { +public final class CommandOutputUtils { private static final Path commandOutputsDir = Paths .get("src", "test", "resources", "test-resources", "command-outputs"); diff --git a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/DocCommandTest.java b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/DocCommandTest.java index 22ab61e0fbb7..cdc7ae08ffa4 100644 --- a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/DocCommandTest.java +++ b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/DocCommandTest.java @@ -40,6 +40,7 @@ public class DocCommandTest extends BaseCommandTest { private Path testResources; + @Override @BeforeClass public void setup() throws IOException { super.setup(); @@ -55,17 +56,23 @@ public void setup() throws IOException { } @Test(description = "Test doc command on a ballerina project.") - public void testDocCommand() throws IOException { + public void testDocCommand() { Path projectPath = this.testResources.resolve("doc_project"); System.setProperty("user.dir", projectPath.toString()); + Path destinationPath = projectPath.resolve("target") + .resolve("apidocs").resolve("foo").resolve("winery").resolve("0.1.0"); DocCommand docCommand = new DocCommand(this.printStream, this.printStream, false); docCommand.execute(); - Assert.assertTrue(Files.exists(this.testResources.resolve("doc_project").resolve("target") - .resolve("apidocs").resolve("foo").resolve("winery").resolve("0.1.0").resolve("index.html"))); + Assert.assertTrue(Files.exists(destinationPath.resolve("api-docs.js"))); + Assert.assertTrue(Files.exists(destinationPath.resolve("api-docs.json"))); - Files.delete(this.testResources.resolve("doc_project").resolve("target") - .resolve("apidocs").resolve("foo").resolve("winery").resolve("0.1.0").resolve("index.html")); + /* Verify if all the UI components are present. */ + Assert.assertTrue(Files.exists(destinationPath.resolve("bundle.js"))); + Assert.assertTrue(Files.exists(destinationPath.resolve("favicon.ico"))); + Assert.assertTrue(Files.exists(destinationPath.resolve("globals.css"))); + Assert.assertTrue(Files.exists(destinationPath.resolve("index.html"))); + Assert.assertTrue(Files.exists(destinationPath.resolve("vercel.svg"))); } @Test(description = "Test doc command on a ballerina project with custom target dir.") diff --git a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/GraphCommandTest.java b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/GraphCommandTest.java index 0cff73b57023..e75483758f24 100644 --- a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/GraphCommandTest.java +++ b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/GraphCommandTest.java @@ -63,6 +63,7 @@ public class GraphCommandTest extends BaseCommandTest { private Path testDistCacheDirectory; private ProjectEnvironmentBuilder projectEnvironmentBuilder; + @Override @BeforeClass public void setup() throws IOException { super.setup(); diff --git a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/NewCommandTest.java b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/NewCommandTest.java index e852274bca97..4b629d382738 100644 --- a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/NewCommandTest.java +++ b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/NewCommandTest.java @@ -69,6 +69,7 @@ public Object[][] provideInvalidProjectNames() { }; } + @Override @BeforeClass public void setup() throws IOException { super.setup(); diff --git a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/PackCommandTest.java b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/PackCommandTest.java index 83be2d4d609e..db46b804948a 100644 --- a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/PackCommandTest.java +++ b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/PackCommandTest.java @@ -45,6 +45,7 @@ public class PackCommandTest extends BaseCommandTest { private static final Path logFile = Paths.get("build/logs/log_creator_combined_plugin/compiler-plugin.txt") .toAbsolutePath(); + @Override @BeforeClass public void setup() throws IOException { super.setup(); diff --git a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/ProfileCommandTest.java b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/ProfileCommandTest.java index 0396b0af7480..950b39dd8cca 100644 --- a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/ProfileCommandTest.java +++ b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/ProfileCommandTest.java @@ -32,7 +32,9 @@ import org.wso2.ballerinalang.util.RepoUtils; import picocli.CommandLine; +import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.PrintStream; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Files; @@ -63,6 +65,7 @@ public void setupSuite() throws IOException { Files.writeString(logFile, ""); } + @Override @BeforeClass public void setup() throws IOException { super.setup(); @@ -84,8 +87,8 @@ public void testRunBalProjectWithProfileFlag() throws IOException { Path projectPath = this.testResources.resolve("projectForProfile").resolve("package_a"); System.setProperty(USER_DIR_PROPERTY, projectPath.toString()); - java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream(); - System.setOut(new java.io.PrintStream(out)); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + System.setOut(new PrintStream(out)); ProfileCommand profileCommand = new ProfileCommand(projectPath, printStream, false); profileCommand.execute(); @@ -108,8 +111,8 @@ public void testRunBalProjectWithProfileFlagWithBuildTools() throws IOException Path projectPath = this.testResources.resolve("projectForProfile").resolve("package_b"); System.setProperty(USER_DIR_PROPERTY, projectPath.toString()); - java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream(); - System.setOut(new java.io.PrintStream(out)); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + System.setOut(new PrintStream(out)); ProfileCommand profileCommand = new ProfileCommand(projectPath, printStream, false); profileCommand.execute(); diff --git a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/ProjectWatcherTest.java b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/ProjectWatcherTest.java index 2aa25fcd6806..80ee3056b6af 100644 --- a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/ProjectWatcherTest.java +++ b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/ProjectWatcherTest.java @@ -33,6 +33,7 @@ public class ProjectWatcherTest extends BaseCommandTest { private Thread watcherThread; private AtomicReference watcher; + @Override @BeforeClass public void setup() throws IOException { super.setup(); @@ -302,6 +303,7 @@ public void testRunWatchBalProjectWithInvalidFileChanges() throws IOException, I Assert.assertEquals(actualOutput, expectedOutput); } + @Override @AfterMethod public void afterMethod() { try { diff --git a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/PushCommandTest.java b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/PushCommandTest.java index f3cf82e0b936..52c40e13027f 100644 --- a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/PushCommandTest.java +++ b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/PushCommandTest.java @@ -62,6 +62,7 @@ public class PushCommandTest extends BaseCommandTest { private static final String POM_EXTENSION = ".pom"; private Path testResources; + @Override @BeforeClass public void setup() throws IOException { super.setup(); diff --git a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/RunBuildToolsTaskTest.java b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/RunBuildToolsTaskTest.java index ecfd5eb8cb6e..65e7d15ddac8 100644 --- a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/RunBuildToolsTaskTest.java +++ b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/RunBuildToolsTaskTest.java @@ -62,6 +62,7 @@ public class RunBuildToolsTaskTest extends BaseCommandTest { private static final Path LOG_FILE = Paths.get("build/logs/log_creator_combined_plugin/compiler-plugin.txt") .toAbsolutePath(); + @Override @BeforeClass public void setup() throws IOException { super.setup(); diff --git a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/RunCommandTest.java b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/RunCommandTest.java index 8c5f2043aa17..b157d0e487e4 100644 --- a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/RunCommandTest.java +++ b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/RunCommandTest.java @@ -19,9 +19,11 @@ import org.wso2.ballerinalang.util.RepoUtils; import picocli.CommandLine; +import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileFilter; import java.io.IOException; +import java.io.PrintStream; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Files; @@ -52,6 +54,7 @@ public void setupSuite() throws IOException { Files.writeString(logFile, ""); } + @Override @BeforeClass public void setup() throws IOException { super.setup(); @@ -360,8 +363,8 @@ public void testRunBalProjectWithDumpGraphFlag() throws IOException { Path projectPath = dumpGraphResourcePath.resolve("package_a"); System.setProperty("user.dir", projectPath.toString()); - java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream(); - System.setOut(new java.io.PrintStream(out)); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + System.setOut(new PrintStream(out)); RunCommand runCommand = new RunCommand(projectPath, printStream, false); new CommandLine(runCommand).parseArgs("--dump-graph"); diff --git a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/TestCommandTest.java b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/TestCommandTest.java index 26ff683c1d4c..5b8695ad3be4 100644 --- a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/TestCommandTest.java +++ b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/TestCommandTest.java @@ -57,6 +57,7 @@ import java.util.Arrays; import java.util.List; import java.util.Objects; +import java.util.stream.Stream; import static io.ballerina.cli.cmd.CommandOutputUtils.getOutput; import static io.ballerina.cli.cmd.CommandOutputUtils.readFileAsString; @@ -80,6 +81,7 @@ public class TestCommandTest extends BaseCommandTest { private Path testDistCacheDirectory; ProjectEnvironmentBuilder projectEnvironmentBuilder; + @Override @BeforeClass public void setup() throws IOException { super.setup(); @@ -511,7 +513,7 @@ public void testEmissionOfTestableFatJarForProjectWithMocking() throws IOExcepti Path mainArgsFile = testableJar.getParent().resolve(TEST_RUNTIME_MAIN_ARGS_FILE); Assert.assertTrue(Files.exists(mainArgsFile)); //should exist only one testable jar - try (var testableJars = Files.list(testableJar.getParent())) { + try (Stream testableJars = Files.list(testableJar.getParent())) { Assert.assertEquals(testableJars.filter(path -> path.toString().endsWith(".jar")) .map(Path::toFile).toList().size(), 1); } @@ -574,7 +576,7 @@ public void testEmissionOfSingleFatJarForCloudAndGraalVM() throws IOException { Path mainArgsFile = testableJar.getParent().resolve(TEST_RUNTIME_MAIN_ARGS_FILE); Assert.assertTrue(Files.exists(mainArgsFile)); //should exist only one testable jar - try (var testableJars = Files.list(testableJar.getParent())) { + try (Stream testableJars = Files.list(testableJar.getParent())) { Assert.assertEquals(testableJars.filter(path -> path.toString().endsWith(".jar")) .map(Path::toFile).toList().size(), 1); } @@ -596,9 +598,9 @@ public void testEmissionOfMultipleFatJarsForProjectWithMockingForCloudAndGraalVM Path mainArgsFile = targetDir.resolve("bin").resolve("tests").resolve(TEST_RUNTIME_MAIN_ARGS_FILE); Assert.assertTrue(Files.exists(mainArgsFile)); //should exist only one testable jar - try (var files = Files.list(mainArgsFile.getParent())) { + try (Stream files = Files.list(mainArgsFile.getParent())) { List testableJars = files.filter(path -> path.toString().endsWith(".jar")) - .map(Path::toFile).toList(); + .map(Path::toFile).toList(); Assert.assertEquals(testableJars.size(), 2); //2 because default module and 1 sub module List jarFileNames = Arrays.asList("projectWithMocks-testable.jar", "projectWithMocks.mod1-testable.jar"); @@ -624,7 +626,7 @@ public void testExecutionOfMultipleTestableFatJarsForProjectWithTestsAndMocks() mainArgs.set(TesterinaConstants.RunTimeArgs.TEST_SUITE_JSON_PATH, TestUtils.getJsonFilePathInFatJar("/")); mainArgs.set(TesterinaConstants.RunTimeArgs.TARGET_DIR, projectPath.resolve("target").toString()); - try (var files = Files.list(mainArgsFile.getParent())) { + try (Stream files = Files.list(mainArgsFile.getParent())) { List testableJars = files.filter(path -> path.toString().endsWith(".jar")).toList(); for (Path testableJar : testableJars) { List pbArgs = new ArrayList<>(TestUtils.getInitialCmdArgs(null, null)); diff --git a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/TestNativeImageCommandTest.java b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/TestNativeImageCommandTest.java index bf703fc6de89..7326d1e1da28 100644 --- a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/TestNativeImageCommandTest.java +++ b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/TestNativeImageCommandTest.java @@ -33,6 +33,7 @@ public class TestNativeImageCommandTest extends BaseCommandTest { private static final Path LOG_FILE = Paths.get("build/logs/log_creator_combined_plugin/compiler-plugin.txt") .toAbsolutePath(); + @Override @BeforeClass public void setup() throws IOException { super.setup(); diff --git a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/ToolCommandTest.java b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/ToolCommandTest.java index 9187b001d639..96347c2eedd8 100644 --- a/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/ToolCommandTest.java +++ b/cli/ballerina-cli/src/test/java/io/ballerina/cli/cmd/ToolCommandTest.java @@ -51,6 +51,7 @@ public class ToolCommandTest extends BaseCommandTest { private Path testResources; + @Override @BeforeClass public void setup() throws IOException { super.setup(); diff --git a/cli/central-client/src/main/java/org/ballerinalang/central/client/CentralClientConstants.java b/cli/central-client/src/main/java/org/ballerinalang/central/client/CentralClientConstants.java index 5328e70727c2..6aad12746440 100644 --- a/cli/central-client/src/main/java/org/ballerinalang/central/client/CentralClientConstants.java +++ b/cli/central-client/src/main/java/org/ballerinalang/central/client/CentralClientConstants.java @@ -22,7 +22,7 @@ * * @since 1.2.0 */ -public class CentralClientConstants { +public final class CentralClientConstants { private CentralClientConstants() { } diff --git a/cli/central-client/src/main/java/org/ballerinalang/central/client/Utils.java b/cli/central-client/src/main/java/org/ballerinalang/central/client/Utils.java index 1f968a104cc6..15a2ebbfb4a4 100644 --- a/cli/central-client/src/main/java/org/ballerinalang/central/client/Utils.java +++ b/cli/central-client/src/main/java/org/ballerinalang/central/client/Utils.java @@ -60,6 +60,7 @@ import java.util.HashMap; import java.util.List; import java.util.Optional; +import java.util.stream.Stream; import static org.ballerinalang.central.client.CentralClientConstants.APPLICATION_JSON; import static org.ballerinalang.central.client.CentralClientConstants.BALLERINA_DEV_CENTRAL; @@ -78,7 +79,7 @@ /** * Utils class for this package. */ -public class Utils { +public final class Utils { private static final int BUFFER_SIZE = 1024; public static final String DEPRECATED_META_FILE_NAME = "deprecated.txt"; @@ -146,24 +147,30 @@ public static void createBalaInHomeRepo(Response balaDownloadResponse, Path pkgP // .ballerina/bala_cache/// try { - if (Files.isDirectory(balaCacheWithPkgPath) && Files.list(balaCacheWithPkgPath).findAny().isPresent()) { - // update the existing deprecation details - Path deprecatedFilePath = balaCacheWithPkgPath.resolve(DEPRECATED_META_FILE_NAME); - if (deprecatedFilePath.toFile().exists() && deprecationMsg == null) { - // delete deprecated file if it exists - Files.delete(deprecatedFilePath); - } else if (deprecationMsg != null) { - // write deprecation details to the file - try (BufferedWriter writer = new BufferedWriter(new FileWriter(deprecatedFilePath.toFile(), - Charset.defaultCharset()))) { - writer.write(deprecationMsg); - } + if (Files.isDirectory(balaCacheWithPkgPath)) { + boolean hasChildren; + try (Stream paths = Files.list(balaCacheWithPkgPath)) { + hasChildren = paths.findAny().isPresent(); } + if (hasChildren) { + // update the existing deprecation details + Path deprecatedFilePath = balaCacheWithPkgPath.resolve(DEPRECATED_META_FILE_NAME); + if (deprecatedFilePath.toFile().exists() && deprecationMsg == null) { + // delete deprecated file if it exists + Files.delete(deprecatedFilePath); + } else if (deprecationMsg != null) { + // write deprecation details to the file + try (BufferedWriter writer = new BufferedWriter(new FileWriter(deprecatedFilePath.toFile(), + Charset.defaultCharset()))) { + writer.write(deprecationMsg); + } + } - downloadBody.ifPresent(ResponseBody::close); - throw new PackageAlreadyExistsException( - logFormatter.formatLog("package already exists in the home repository: " + - balaCacheWithPkgPath.toString()), validPkgVersion); + downloadBody.ifPresent(ResponseBody::close); + throw new PackageAlreadyExistsException( + logFormatter.formatLog("package already exists in the home repository: " + + balaCacheWithPkgPath.toString()), validPkgVersion); + } } } catch (IOException e) { downloadBody.ifPresent(ResponseBody::close); @@ -419,8 +426,7 @@ private static void writeDeprecatedMsg(Path metaFilePath, LogFormatter logFormat * @return converted list of strings */ static List getAsList(String arrayString) { - return new Gson().fromJson(arrayString, new TypeToken>() { - }.getType()); + return new Gson().fromJson(arrayString, new TypeToken<>() { }); } /** @@ -459,7 +465,11 @@ private static void extractBala(Path balaFilePath, Path balaFileDestPath, String try (FileSystem zipFileSystem = FileSystems.newFileSystem(zipURI, new HashMap<>())) { Path packageRoot = zipFileSystem.getPath("/"); - List paths = Files.walk(packageRoot).filter(path -> path != packageRoot).toList(); + List paths; + try (Stream pathStream = Files.walk(packageRoot)) { + paths = pathStream.filter(path -> path != packageRoot).toList(); + } + for (Path path : paths) { Path destPath = balaFileDestPath.resolve(packageRoot.relativize(path).toString()); // Handle overwriting existing bala diff --git a/cli/central-client/src/main/java/org/ballerinalang/central/client/model/PackageResolutionRequest.java b/cli/central-client/src/main/java/org/ballerinalang/central/client/model/PackageResolutionRequest.java index 8b1cd8ed6dd0..e8882fbca8da 100644 --- a/cli/central-client/src/main/java/org/ballerinalang/central/client/model/PackageResolutionRequest.java +++ b/cli/central-client/src/main/java/org/ballerinalang/central/client/model/PackageResolutionRequest.java @@ -25,7 +25,6 @@ import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; - import java.io.IOException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; @@ -154,18 +153,14 @@ public void write(final JsonWriter jsonWriter, @Nullable final String s) @Override @Nonnull - @SuppressWarnings("EnumSwitchStatementWhichMissesCases") public String read(final JsonReader jsonReader) throws IOException { final JsonToken token = jsonReader.peek(); - switch (token) { - case NULL: - return ""; - case STRING: - return jsonReader.nextString(); - default: - throw new IllegalStateException("Unexpected token: " + token); - } + return switch (token) { + case NULL -> ""; + case STRING -> jsonReader.nextString(); + default -> throw new IllegalStateException("Unexpected token: " + token); + }; } } diff --git a/cli/central-client/src/test/java/org/ballerinalang/central/client/TestUtils.java b/cli/central-client/src/test/java/org/ballerinalang/central/client/TestUtils.java index 537b34dedef1..7e66fdef72af 100644 --- a/cli/central-client/src/test/java/org/ballerinalang/central/client/TestUtils.java +++ b/cli/central-client/src/test/java/org/ballerinalang/central/client/TestUtils.java @@ -30,9 +30,7 @@ import org.testng.annotations.Test; import java.io.File; -import java.io.FileInputStream; import java.io.IOException; -import java.io.InputStream; import java.net.HttpURLConnection; import java.nio.file.Files; import java.nio.file.Path; @@ -43,6 +41,7 @@ import java.util.Comparator; import java.util.Iterator; import java.util.List; +import java.util.stream.Stream; import static org.ballerinalang.central.client.CentralClientConstants.ACCEPT; import static org.ballerinalang.central.client.CentralClientConstants.ACCEPT_ENCODING; @@ -106,8 +105,6 @@ public void testGetAsList(String versionList, List expectedArray) { public void testWriteBalaFile() throws IOException, CentralClientException { final String balaName = "sf-any.bala"; Path balaFile = UTILS_TEST_RESOURCES.resolve(balaName); - File initialFile = new File(String.valueOf(balaFile)); - InputStream targetStream = new FileInputStream(initialFile); Request mockRequest = new Request.Builder() .get() @@ -158,8 +155,6 @@ public void testValidatePackageVersion(String version, boolean isValid) throws C public void testCreateBalaInHomeRepo() throws IOException, CentralClientException { final String balaName = "sf-any.bala"; Path balaFile = UTILS_TEST_RESOURCES.resolve(balaName); - File initialFile = new File(String.valueOf(balaFile)); - InputStream targetStream = new FileInputStream(initialFile); Request mockRequest = new Request.Builder() .get() @@ -191,8 +186,6 @@ public void testCreateBalaInHomeRepo() throws IOException, CentralClientExceptio public void testCreateBalaInHomeRepoWhenBalaExists() throws IOException { final String balaName = "sf-any.bala"; Path balaFile = UTILS_TEST_RESOURCES.resolve(balaName); - File initialFile = new File(String.valueOf(balaFile)); - InputStream targetStream = new FileInputStream(initialFile); Request mockRequest = new Request.Builder() .get() @@ -235,9 +228,8 @@ private void cleanBalaCache() { } static void cleanDirectory(Path path) { - try { - Files.walk(path) - .sorted(Comparator.reverseOrder()) + try (Stream paths = Files.walk(path)) { + paths.sorted(Comparator.reverseOrder()) .map(Path::toFile) .filter(item -> !item.getPath().equals(path.toString())) .forEach(File::delete); diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/BallerinaKeywordsProvider.java b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/BallerinaKeywordsProvider.java index e512173f4b23..27bdb6383148 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/BallerinaKeywordsProvider.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/BallerinaKeywordsProvider.java @@ -20,20 +20,23 @@ import java.util.Collections; import java.util.List; import java.util.Objects; -import java.util.stream.Collectors; /** * Provides the set of Ballerina Reserved Keywords to be used at the symbol factory. * * @since 2.0.0 */ -public class BallerinaKeywordsProvider { +public final class BallerinaKeywordsProvider { + public static final List BALLERINA_KEYWORDS; static { BALLERINA_KEYWORDS = getBallerinaKeywords(); } + private BallerinaKeywordsProvider() { + } + private static List getBallerinaKeywords() { // NOTE: This is a temporary fix to retrieve lexer defined keywords until we come up with an appropriate API. // The same implementation can be found in the language server common utils. @@ -51,7 +54,7 @@ private static List getBallerinaKeywords() { } }) .filter(Objects::nonNull) - .collect(Collectors.toList()); + .toList(); } catch (ClassNotFoundException e) { return Collections.emptyList(); } diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/BallerinaSemanticModel.java b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/BallerinaSemanticModel.java index 41650e96b605..73bf9e881f9b 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/BallerinaSemanticModel.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/BallerinaSemanticModel.java @@ -688,15 +688,16 @@ private boolean isIgnorableSelfSymbol(Name name, BSymbol symbol, BSymbol symbolE } private boolean isFilteredVarSymbol(BSymbol symbol, Set states) { - return symbol instanceof BVarSymbol && !states.contains(((BVarSymbol) symbol).state); + return symbol instanceof BVarSymbol varSymbol && !states.contains(varSymbol.state); } private boolean isObjectConstructorExpr(BLangNode node) { - return node instanceof BLangClassDefinition && ((BLangClassDefinition) node).flagSet.contains(Flag.OBJECT_CTOR); + return node instanceof BLangClassDefinition classDefinition && + classDefinition.flagSet.contains(Flag.OBJECT_CTOR); } private boolean isAnonFunctionExpr(BLangNode node) { - return (node instanceof BLangFunction && ((BLangFunction) node).flagSet.contains(Flag.LAMBDA)) + return (node instanceof BLangFunction bLangFunction && bLangFunction.flagSet.contains(Flag.LAMBDA)) || node instanceof BLangArrowFunction; } diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/ExpectedTypeFinder.java b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/ExpectedTypeFinder.java index c53ed026ecdd..c19429826ce3 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/ExpectedTypeFinder.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/ExpectedTypeFinder.java @@ -132,7 +132,6 @@ import java.util.Objects; import java.util.Optional; import java.util.function.Predicate; -import java.util.stream.Collectors; import static io.ballerina.compiler.api.impl.PositionUtil.isPosWithinOpenCloseLineRanges; import static io.ballerina.compiler.api.impl.PositionUtil.isPosWithinRange; @@ -227,9 +226,7 @@ public Optional transform(SpecificFieldNode node) { return Optional.empty(); } - if (bLangNode instanceof BLangRecordLiteral.BLangRecordVarNameField) { - BLangRecordLiteral.BLangRecordVarNameField bLangNodeRecLiteral = - (BLangRecordLiteral.BLangRecordVarNameField) bLangNode; + if (bLangNode instanceof BLangRecordLiteral.BLangRecordVarNameField bLangNodeRecLiteral) { if (bLangNodeRecLiteral.symbol != null && node.parent().kind() == SyntaxKind.MAPPING_CONSTRUCTOR) { BLangExpression bLangExpression = bLangNodeRecLiteral.impConversionExpr; if (bLangExpression != null && bLangExpression.getBType().getKind() == TypeKind.ANY) { @@ -306,11 +303,10 @@ public Optional transform(BinaryExpressionNode node) { } BLangNode bLangNode = nodeFinder.lookup(this.bLangCompilationUnit, node.lineRange()); - if (!(bLangNode instanceof BLangBinaryExpr)) { + if (!(bLangNode instanceof BLangBinaryExpr bLangBinaryExpr)) { return Optional.empty(); } - BLangBinaryExpr bLangBinaryExpr = (BLangBinaryExpr) bLangNode; BLangExpression rhs = bLangBinaryExpr.rhsExpr; BLangExpression lhs = bLangBinaryExpr.lhsExpr; BType rhsExpType = rhs.expectedType; @@ -367,12 +363,12 @@ public Optional transform(QualifiedNameReferenceNode node) { return Optional.empty(); } - if (bLangNode instanceof BLangSimpleVarRef && ((BLangSimpleVarRef) bLangNode).symbol != null) { - return getTypeFromBType(((BLangSimpleVarRef) bLangNode).symbol.getType()); + if (bLangNode instanceof BLangSimpleVarRef simpleVarRef && ((BLangSimpleVarRef) bLangNode).symbol != null) { + return getTypeFromBType(simpleVarRef.symbol.getType()); } - if (bLangNode instanceof BLangUserDefinedType && ((BLangUserDefinedType) bLangNode).symbol != null) { - return getTypeFromBType(((BLangUserDefinedType) bLangNode).symbol.getType()); + if (bLangNode instanceof BLangUserDefinedType userDefinedType && userDefinedType.symbol != null) { + return getTypeFromBType(userDefinedType.symbol.getType()); } return Optional.empty(); @@ -393,14 +389,14 @@ public Optional transform(ExplicitAnonymousFunctionExpressionNode no @Override public Optional transform(ImplicitAnonymousFunctionExpressionNode node) { BLangNode bLangNode = nodeFinder.lookup(this.bLangCompilationUnit, node.lineRange()); - if (!(bLangNode instanceof BLangArrowFunction)) { + if (!(bLangNode instanceof BLangArrowFunction arrowFunction)) { return Optional.empty(); } if (!node.rightDoubleArrow().isMissing() && node.rightDoubleArrow().lineRange().endLine().offset() <= linePosition.offset()) { // Cursor is at the expression node. - BType funcType = ((BLangArrowFunction) bLangNode).funcType; + BType funcType = arrowFunction.funcType; if (funcType == null) { return Optional.empty(); } @@ -516,16 +512,14 @@ public Optional transform(ImplicitNewExpressionNode node) { Token closeParen = parenthesizedArgList.get().closeParenToken(); // Check if the line position is within the parameter context. if (isWithinParenthesis(openParen, closeParen)) { - if (!(bLangNode instanceof BLangTypeInit)) { + if (!(bLangNode instanceof BLangTypeInit bLangTypeInit)) { return getExpectedType(bLangNode); } - BLangTypeInit bLangTypeInit = (BLangTypeInit) bLangNode; - if (!(bLangTypeInit.initInvocation instanceof BLangInvocation)) { + if (!(bLangTypeInit.initInvocation instanceof BLangInvocation initInvocation)) { return getExpectedType(bLangNode); } - BLangInvocation initInvocation = (BLangInvocation) bLangTypeInit.initInvocation; if (initInvocation.symbol == null) { throw new IllegalStateException(); } @@ -564,8 +558,8 @@ public Optional transform(IfElseStatementNode node) { } if (isPosWithinRange(linePosition, node.condition().lineRange()) && - bLangNode instanceof BLangIf) { - return getExpectedType(((BLangIf) bLangNode).expr); + bLangNode instanceof BLangIf bLangIf) { + return getExpectedType(bLangIf.expr); } return Optional.empty(); @@ -579,8 +573,8 @@ public Optional transform(WhileStatementNode node) { } if (isPosWithinRange(linePosition, node.condition().lineRange()) - && bLangNode instanceof BLangWhile) { - return getExpectedType(((BLangWhile) bLangNode).expr); + && bLangNode instanceof BLangWhile bLangWhile) { + return getExpectedType(bLangWhile.expr); } return Optional.empty(); @@ -699,11 +693,10 @@ public Optional transform(MappingConstructorExpressionNode node) { @Override public Optional transform(WaitActionNode node) { BLangNode bLangNode = nodeFinder.lookup(this.bLangCompilationUnit, node.lineRange()); - if (!(bLangNode instanceof BLangWaitExpr)) { + if (!(bLangNode instanceof BLangWaitExpr waitExpr)) { return Optional.empty(); } - BLangWaitExpr waitExpr = (BLangWaitExpr) bLangNode; for (BLangExpression bLangExpression : waitExpr.exprList) { if (isPosWithinRange(linePosition, bLangExpression.getPosition().lineRange())) { return getExpectedType(bLangExpression); @@ -750,22 +743,21 @@ public Optional transform(NamedArgumentNode node) { @Override public Optional transform(TableConstructorExpressionNode node) { BLangNode bLangNode = nodeFinder.lookup(this.bLangCompilationUnit, node.lineRange()); - if (!(bLangNode instanceof BLangTableConstructorExpr)) { + if (!(bLangNode instanceof BLangTableConstructorExpr bLangTableConstructorExpr)) { return Optional.empty(); } - BLangTableConstructorExpr bLangTableConstructorExpr = (BLangTableConstructorExpr) bLangNode; if (node.keySpecifier().isPresent() && isWithinParenthesis(node.keySpecifier().get().openParenToken(), node.keySpecifier().get().closeParenToken())) { BType expectedType = bLangTableConstructorExpr.expectedType; - if (expectedType instanceof BTableType) { + if (expectedType instanceof BTableType tableType) { return Optional.of(typesFactory.getTypeDescriptor(Objects. - requireNonNullElse(((BTableType) expectedType).constraint, expectedType))); + requireNonNullElse(tableType.constraint, expectedType))); } - if (expectedType instanceof BTypeReferenceType) { - BType referredType = ((BTypeReferenceType) expectedType).referredType; + if (expectedType instanceof BTypeReferenceType referenceType) { + BType referredType = referenceType.referredType; return Optional.of(typesFactory.getTypeDescriptor(Objects. requireNonNullElse(((BTableType) referredType).constraint, expectedType))); } @@ -797,11 +789,11 @@ public Optional transform(RecordFieldWithDefaultValueNode node) { @Override public Optional transform(SelectClauseNode node) { BLangNode bLangNode = nodeFinder.lookup(bLangCompilationUnit, node.lineRange()); - if (!(bLangNode instanceof BLangSelectClause)) { + if (!(bLangNode instanceof BLangSelectClause selectClause)) { return Optional.empty(); } - BType expectedType = ((BLangExpression) ((BLangSelectClause) bLangNode).getExpression()).expectedType; + BType expectedType = ((BLangExpression) selectClause.getExpression()).expectedType; return getTypeFromBType(expectedType); } @@ -876,10 +868,9 @@ public Optional transform(ClientResourceAccessActionNode clientResou Optional arguments = clientResourceAccessActionNode.arguments(); if (arguments.isPresent() && isWithinParenthesis(arguments.get().openParenToken(), arguments.get().closeParenToken())) { - if (!(bLangNode instanceof BLangInvocation)) { + if (!(bLangNode instanceof BLangInvocation bLangInvocation)) { return getExpectedType(bLangNode); } - BLangInvocation bLangInvocation = (BLangInvocation) bLangNode; if (bLangInvocation.symbol == null) { return Optional.empty(); } @@ -956,8 +947,8 @@ private Optional getExpectedType(BLangNode node) { bType = ((BLangRecordLiteral) node).expectedType; break; case SIMPLE_VARIABLE_REF: - if (node instanceof BLangRecordLiteral) { - BLangExpression bLangExpression = ((BLangRecordLiteral) node).impConversionExpr; + if (node instanceof BLangRecordLiteral recordLiteral) { + BLangExpression bLangExpression = recordLiteral.impConversionExpr; if (bLangExpression != null && bLangExpression.getBType().getKind() == TypeKind.ANY) { bType = bLangExpression.getBType(); break; @@ -1070,7 +1061,7 @@ private List getModuleSymbols(QualifiedNameReferenceNode qNameRef, Optional module = searchModuleForAlias(alias); return module.map(moduleSymbol -> moduleSymbol.allSymbols().stream() .filter(predicate) - .collect(Collectors.toList())) + .toList()) .orElseGet(ArrayList::new); } diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/LangLibrary.java b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/LangLibrary.java index 302ef304c309..98dd7af33a89 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/LangLibrary.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/LangLibrary.java @@ -149,32 +149,24 @@ private void populateMethodList(List list, Map TypeKind.INT.typeName(); + case ARRAY, TUPLE -> "array"; + case RECORD, MAP -> TypeKind.MAP.typeName(); + case FLOAT, + DECIMAL, + STRING, + BOOLEAN, + STREAM, + OBJECT, + ERROR, + FUTURE, + TYPEDESC, + XML, + TABLE, + REGEXP -> typeKind.typeName(); + default -> LANG_VALUE; + }; } private static void addLangLibMethods(String basicType, BPackageSymbol langLibModule, diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/NodeFinder.java b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/NodeFinder.java index dfb11e0de401..e885d26aa376 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/NodeFinder.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/NodeFinder.java @@ -1583,9 +1583,8 @@ private boolean isClassForService(TopLevelNode node) { } private boolean isWithinNodeMetaData(TopLevelNode node) { - if (node instanceof AnnotatableNode) { - List nodes = - (List) ((AnnotatableNode) node).getAnnotationAttachments(); + if (node instanceof AnnotatableNode annotatableNode) { + List nodes = annotatableNode.getAnnotationAttachments(); for (AnnotationAttachmentNode annotAttachment : nodes) { if (PositionUtil.isRangeWithinNode(this.range, annotAttachment.getPosition())) { diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/PositionUtil.java b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/PositionUtil.java index e9772f33764c..a87e6f56eca8 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/PositionUtil.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/PositionUtil.java @@ -27,7 +27,10 @@ * * @since 2.0.0 */ -class PositionUtil { +final class PositionUtil { + + private PositionUtil() { + } static boolean withinBlock(LinePosition cursorPos, Location symbolPosition) { if (symbolPosition == null) { diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/ReferenceFinder.java b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/ReferenceFinder.java index 760d26ce9e14..902bb75932b8 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/ReferenceFinder.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/ReferenceFinder.java @@ -213,7 +213,6 @@ import java.util.ArrayList; import java.util.List; -import java.util.stream.Collectors; import static org.ballerinalang.model.symbols.SymbolOrigin.VIRTUAL; @@ -265,10 +264,10 @@ public void visit(BLangPackage pkgNode) { find(pkgNode.typeDefinitions); find(pkgNode.classDefinitions.stream() .filter(c -> !isGeneratedClassDefForService(c)) - .collect(Collectors.toList())); + .toList()); find(pkgNode.functions.stream() .filter(f -> !f.flagSet.contains(Flag.LAMBDA)) - .collect(Collectors.toList())); + .toList()); if (!(pkgNode instanceof BLangTestablePackage)) { find(pkgNode.getTestablePkg()); diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/SymbolFactory.java b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/SymbolFactory.java index 77558f0d0e4a..c457b9a5f73f 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/SymbolFactory.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/SymbolFactory.java @@ -151,7 +151,7 @@ public Symbol getBCompiledSymbol(BSymbol symbol, String name) { throw new IllegalArgumentException("Symbol is 'null'"); } - if (symbol instanceof BVarSymbol) { + if (symbol instanceof BVarSymbol varSymbol) { if (symbol.kind == SymbolKind.FUNCTION && !isFunctionPointer(symbol)) { if (Symbols.isFlagOn(symbol.flags, Flags.ATTACHED)) { if (Symbols.isFlagOn(symbol.flags, Flags.RESOURCE)) { @@ -161,32 +161,32 @@ public Symbol getBCompiledSymbol(BSymbol symbol, String name) { } return createFunctionSymbol((BInvokableSymbol) symbol, name); } - if (symbol instanceof BConstantSymbol) { - return createConstantSymbol((BConstantSymbol) symbol, name); + if (symbol instanceof BConstantSymbol constantSymbol) { + return createConstantSymbol(constantSymbol, name); } if (symbol.kind == SymbolKind.WORKER) { return createWorkerSymbol((BWorkerSymbol) symbol, name); } if (symbol.owner instanceof BRecordTypeSymbol) { - return createRecordFieldSymbol((BVarSymbol) symbol); + return createRecordFieldSymbol(varSymbol); } if (symbol.owner instanceof BClassSymbol) { - return createClassFieldSymbol((BVarSymbol) symbol); + return createClassFieldSymbol(varSymbol); } if (symbol.owner instanceof BObjectTypeSymbol) { - return createObjectFieldSymbol((BVarSymbol) symbol); + return createObjectFieldSymbol(varSymbol); } if (Symbols.isFlagOn(symbol.flags, Flags.REQUIRED_PARAM)) { - return createBallerinaParameter((BVarSymbol) symbol, ParameterKind.REQUIRED); + return createBallerinaParameter(varSymbol, ParameterKind.REQUIRED); } if (Symbols.isFlagOn(symbol.flags, Flags.DEFAULTABLE_PARAM)) { - return createBallerinaParameter((BVarSymbol) symbol, ParameterKind.DEFAULTABLE); + return createBallerinaParameter(varSymbol, ParameterKind.DEFAULTABLE); } if (Symbols.isFlagOn(symbol.flags, Flags.INCLUDED)) { - return createBallerinaParameter((BVarSymbol) symbol, ParameterKind.INCLUDED_RECORD); + return createBallerinaParameter(varSymbol, ParameterKind.INCLUDED_RECORD); } if (Symbols.isFlagOn(symbol.flags, Flags.REST_PARAM)) { - return createBallerinaParameter((BVarSymbol) symbol, ParameterKind.REST); + return createBallerinaParameter(varSymbol, ParameterKind.REST); } if (symbol.kind == SymbolKind.PATH_PARAMETER) { return createPathParamSymbol(name, symbol, PathSegment.Kind.PATH_PARAMETER); @@ -196,26 +196,26 @@ public Symbol getBCompiledSymbol(BSymbol symbol, String name) { } // If the symbol is a wildcard('_'), a variable symbol will not be created. - if (((BVarSymbol) symbol).isWildcard) { + if (varSymbol.isWildcard) { return null; } // return the variable symbol - return createVariableSymbol((BVarSymbol) symbol, name); + return createVariableSymbol(varSymbol, name); } if (symbol instanceof BTypeSymbol) { if (symbol.kind == SymbolKind.ANNOTATION) { return createAnnotationSymbol((BAnnotationSymbol) symbol); } - if (symbol instanceof BPackageSymbol) { - return createModuleSymbol((BPackageSymbol) symbol, name); + if (symbol instanceof BPackageSymbol packageSymbol) { + return createModuleSymbol(packageSymbol, name); } - if (symbol instanceof BClassSymbol) { - return createClassSymbol((BClassSymbol) symbol, name); + if (symbol instanceof BClassSymbol classSymbol) { + return createClassSymbol(classSymbol, name); } - if (symbol instanceof BEnumSymbol) { - return createEnumSymbol((BEnumSymbol) symbol, name); + if (symbol instanceof BEnumSymbol enumSymbol) { + return createEnumSymbol(enumSymbol, name); } // For a type reference type symbol (SymTag.TYPE_REF) @@ -635,17 +635,16 @@ private BallerinaConstantValue createConstantValue(BLangConstantValue constantVa return null; } - if (constantValue.value instanceof BLangConstantValue) { - return createConstantValue((BLangConstantValue) constantValue.value); + if (constantValue.value instanceof BLangConstantValue bLangConstantValue) { + return createConstantValue(bLangConstantValue); } - if (constantValue.value instanceof HashMap) { - Map constValueMap = (Map) constantValue.value; + if (constantValue.value instanceof HashMap constValueMap) { Map constSymbolMap = new LinkedHashMap<>(); constValueMap.forEach((key, value) -> { BallerinaConstantValue newConstValue; - if (value instanceof BLangConstantValue) { - newConstValue = createConstantValue((BLangConstantValue) value); + if (value instanceof BLangConstantValue bLangConstantValue) { + newConstValue = createConstantValue(bLangConstantValue); constSymbolMap.put((String) key, newConstValue); } }); @@ -766,8 +765,8 @@ private String getMethodName(BInvokableSymbol method, BObjectTypeSymbol owner) { for (BAttachedFunction mthd : methods) { if (method == mthd.symbol) { - if (mthd instanceof BResourceFunction) { - return ((BResourceFunction) mthd).accessor.value; + if (mthd instanceof BResourceFunction bResourceFunction) { + return bResourceFunction.accessor.value; } return mthd.symbol.getOriginalName().getValue(); } diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/SymbolFinder.java b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/SymbolFinder.java index da60c0ea4670..edbe77ed9de5 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/SymbolFinder.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/SymbolFinder.java @@ -1684,13 +1684,13 @@ public void visit(BLangInvocation.BLangResourceAccessInvocation resourceAccessIn // The assumption is that if it's moduled-qualified, it must be a public symbol. // Hence, the owner would be a package symbol. - if (resourceAccessInvocation.symbol != null && - setEnclosingNode(resourceAccessInvocation.symbol.owner, resourceAccessInvocation.pkgAlias.pos)) { + BSymbol symbol = resourceAccessInvocation.symbol; + if (symbol != null && setEnclosingNode(symbol.owner, resourceAccessInvocation.pkgAlias.pos)) { return; } if (this.symbolAtCursor == null) { - setEnclosingNode(resourceAccessInvocation.symbol, resourceAccessInvocation.resourceAccessPathSegments.pos); + setEnclosingNode(symbol, resourceAccessInvocation.name.pos); } } @@ -1830,10 +1830,9 @@ private boolean isLambdaFunction(TopLevelNode node) { } private boolean isWithinNodeMetaData(TopLevelNode node) { - if (node instanceof AnnotatableNode) { + if (node instanceof AnnotatableNode annotatableNode) { - List nodes = - (List) ((AnnotatableNode) node).getAnnotationAttachments(); + List nodes = annotatableNode.getAnnotationAttachments(); for (AnnotationAttachmentNode annotAttachment : nodes) { if (PositionUtil.withinBlock(this.cursorPos, annotAttachment.getPosition())) { @@ -1842,8 +1841,8 @@ private boolean isWithinNodeMetaData(TopLevelNode node) { } } - if (node instanceof DocumentableNode) { - BLangMarkdownDocumentation markdown = ((DocumentableNode) node).getMarkdownDocumentationAttachment(); + if (node instanceof DocumentableNode documentableNode) { + BLangMarkdownDocumentation markdown = documentableNode.getMarkdownDocumentationAttachment(); if (markdown != null) { LinkedList parameters = markdown.getParameters(); for (BLangMarkdownParameterDocumentation parameter : parameters) { diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/SyntaxNodeToLocationMapper.java b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/SyntaxNodeToLocationMapper.java index eb7e47e7fe28..62ec2b7efb01 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/SyntaxNodeToLocationMapper.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/SyntaxNodeToLocationMapper.java @@ -187,7 +187,10 @@ public Optional transform(RestParameterNode restParameterNode) { @Override public Optional transform(ClientResourceAccessActionNode clientResourceAccessActionNode) { - return Optional.of(clientResourceAccessActionNode.slashToken().location()); + if (clientResourceAccessActionNode.methodName().isEmpty()) { + return Optional.of(clientResourceAccessActionNode.slashToken().location()); + } + return Optional.of(clientResourceAccessActionNode.methodName().get().location()); } @Override diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/symbols/BallerinaConstantSymbol.java b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/symbols/BallerinaConstantSymbol.java index 923f6394568e..9e0a696feecd 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/symbols/BallerinaConstantSymbol.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/symbols/BallerinaConstantSymbol.java @@ -33,7 +33,6 @@ import java.util.HashMap; import java.util.List; -import java.util.Map; import java.util.Optional; import java.util.StringJoiner; @@ -125,20 +124,19 @@ private String stringValueOf(BallerinaConstantValue value) { return null; } - if (value.value() instanceof BallerinaConstantValue) { - return stringValueOf((BallerinaConstantValue) value.value()); + if (value.value() instanceof BallerinaConstantValue ballerinaConstantValue) { + return stringValueOf(ballerinaConstantValue); } - if (value.value() instanceof HashMap) { + if (value.value() instanceof HashMap map) { StringJoiner joiner = new StringJoiner(", ", "{", "}"); - Map map = (Map) value.value(); map.forEach((k, v) -> { StringBuilder builder = new StringBuilder(); builder.append(k).append(": "); - if (v instanceof BallerinaConstantValue) { - builder.append(stringValueOf((BallerinaConstantValue) v)); + if (v instanceof BallerinaConstantValue ballerinaConstantValue) { + builder.append(stringValueOf(ballerinaConstantValue)); } else { builder.append(toStringVal(v, value.valueType())); } diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/symbols/BallerinaModule.java b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/symbols/BallerinaModule.java index f18114278173..24f094f6754d 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/symbols/BallerinaModule.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/symbols/BallerinaModule.java @@ -262,11 +262,10 @@ public boolean equals(Object obj) { return true; } - if (!(obj instanceof ModuleSymbol)) { + if (!(obj instanceof ModuleSymbol symbol)) { return false; } - ModuleSymbol symbol = (ModuleSymbol) obj; return this.id().equals(symbol.id()); } diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/symbols/BallerinaObjectTypeSymbol.java b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/symbols/BallerinaObjectTypeSymbol.java index fb637b99512e..c7eb00b3a536 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/symbols/BallerinaObjectTypeSymbol.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/symbols/BallerinaObjectTypeSymbol.java @@ -111,8 +111,7 @@ public Map methods() { Map methods = new LinkedHashMap<>(); for (BAttachedFunction attachedFunc : ((BObjectTypeSymbol) this.getBType().tsymbol).attachedFuncs) { - if (attachedFunc instanceof BResourceFunction) { - BResourceFunction resFn = (BResourceFunction) attachedFunc; + if (attachedFunc instanceof BResourceFunction resFn) { String resPath = resFn.pathSegmentSymbols.stream() .map(p -> p.name.value).collect(Collectors.joining("/")); methods.put(resFn.accessor.value + " " + resPath, diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/symbols/BallerinaResourceMethodSymbol.java b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/symbols/BallerinaResourceMethodSymbol.java index c1510e5b316d..370a20a6c2f4 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/symbols/BallerinaResourceMethodSymbol.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/symbols/BallerinaResourceMethodSymbol.java @@ -144,8 +144,8 @@ public T apply(SymbolTransformer transformer) { private BResourceFunction getBResourceFunction(List methods, BInvokableSymbol internalSymbol) { for (BAttachedFunction method : methods) { - if (internalSymbol == method.symbol && method instanceof BResourceFunction) { - return (BResourceFunction) method; + if (internalSymbol == method.symbol && method instanceof BResourceFunction bResourceFunction) { + return bResourceFunction; } } diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/symbols/BallerinaServiceDeclarationSymbol.java b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/symbols/BallerinaServiceDeclarationSymbol.java index df2db95ac618..df06197ba142 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/symbols/BallerinaServiceDeclarationSymbol.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/symbols/BallerinaServiceDeclarationSymbol.java @@ -142,8 +142,7 @@ public Map fieldDescriptors() { Map methods = new LinkedHashMap<>(); for (BAttachedFunction method : classSymbol.attachedFuncs) { - if (method instanceof BResourceFunction) { - BResourceFunction resFn = (BResourceFunction) method; + if (method instanceof BResourceFunction resFn) { StringJoiner stringJoiner = new StringJoiner("/"); for (BResourcePathSegmentSymbol pathSegmentSym : resFn.pathSegmentSymbols) { diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/symbols/BallerinaSymbol.java b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/symbols/BallerinaSymbol.java index 0bd8766412a5..2c30110360ff 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/symbols/BallerinaSymbol.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/symbols/BallerinaSymbol.java @@ -149,11 +149,10 @@ public boolean equals(Object obj) { return true; } - if (!(obj instanceof Symbol)) { + if (!(obj instanceof Symbol symbol)) { return false; } - Symbol symbol = (Symbol) obj; return nameEquals(symbol.getName().orElse(null)) && isSameModule(this.getModule(), symbol.getModule()) && isSameLocation(this.getLocation(), symbol.getLocation()) diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/symbols/TypesFactory.java b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/symbols/TypesFactory.java index 892b9e6d355c..3c0705554eda 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/symbols/TypesFactory.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/symbols/TypesFactory.java @@ -173,8 +173,8 @@ private TypeSymbol createTypeDescriptor(BType bType, BTypeSymbol tSymbol) { case BYTE: return new BallerinaByteTypeSymbol(this.context, bType); case INT: - if (bType instanceof BIntSubType) { - return createIntSubType((BIntSubType) bType); + if (bType instanceof BIntSubType intSubType) { + return createIntSubType(intSubType); } return new BallerinaIntTypeSymbol(this.context, bType); case FLOAT: @@ -182,15 +182,15 @@ private TypeSymbol createTypeDescriptor(BType bType, BTypeSymbol tSymbol) { case DECIMAL: return new BallerinaDecimalTypeSymbol(this.context, bType); case STRING: - if (bType instanceof BStringSubType) { - return new BallerinaStringCharTypeSymbol(this.context, (BStringSubType) bType); + if (bType instanceof BStringSubType stringSubType) { + return new BallerinaStringCharTypeSymbol(this.context, stringSubType); } return new BallerinaStringTypeSymbol(this.context, bType); case ANY: return new BallerinaAnyTypeSymbol(this.context, (BAnyType) bType); case ANYDATA: - if (bType instanceof BRegexpType) { - return new BallerinaRegexpTypeSymbol(this.context, (BRegexpType) bType); + if (bType instanceof BRegexpType regexpType) { + return new BallerinaRegexpTypeSymbol(this.context, regexpType); } return new BallerinaAnydataTypeSymbol(this.context, (BAnydataType) bType); case HANDLE: @@ -202,8 +202,8 @@ private TypeSymbol createTypeDescriptor(BType bType, BTypeSymbol tSymbol) { case TABLE: return new BallerinaTableTypeSymbol(this.context, (BTableType) bType); case XML: - if (bType instanceof BXMLSubType) { - return createXMLSubType((BXMLSubType) bType); + if (bType instanceof BXMLSubType subType) { + return createXMLSubType(subType); } return new BallerinaXMLTypeSymbol(this.context, (BXMLType) bType); case OBJECT: @@ -265,37 +265,25 @@ private TypeSymbol createTypeDescriptor(BType bType, BTypeSymbol tSymbol) { } private IntTypeSymbol createIntSubType(BIntSubType internalType) { - switch (internalType.tag) { - case UNSIGNED8_INT: - return new BallerinaIntUnsigned8TypeSymbol(this.context, internalType); - case SIGNED8_INT: - return new BallerinaIntSigned8TypeSymbol(this.context, internalType); - case UNSIGNED16_INT: - return new BallerinaIntUnsigned16TypeSymbol(this.context, internalType); - case SIGNED16_INT: - return new BallerinaIntSigned16TypeSymbol(this.context, internalType); - case UNSIGNED32_INT: - return new BallerinaIntUnsigned32TypeSymbol(this.context, internalType); - case SIGNED32_INT: - return new BallerinaIntSigned32TypeSymbol(this.context, internalType); - } - - throw new IllegalStateException("Invalid integer subtype type tag: " + internalType.tag); + return switch (internalType.tag) { + case UNSIGNED8_INT -> new BallerinaIntUnsigned8TypeSymbol(this.context, internalType); + case SIGNED8_INT -> new BallerinaIntSigned8TypeSymbol(this.context, internalType); + case UNSIGNED16_INT -> new BallerinaIntUnsigned16TypeSymbol(this.context, internalType); + case SIGNED16_INT -> new BallerinaIntSigned16TypeSymbol(this.context, internalType); + case UNSIGNED32_INT -> new BallerinaIntUnsigned32TypeSymbol(this.context, internalType); + case SIGNED32_INT -> new BallerinaIntSigned32TypeSymbol(this.context, internalType); + default -> throw new IllegalStateException("Invalid integer subtype type tag: " + internalType.tag); + }; } private XMLTypeSymbol createXMLSubType(BXMLSubType internalType) { - switch (internalType.tag) { - case XML_ELEMENT: - return new BallerinaXMLElementTypeSymbol(this.context, internalType); - case XML_PI: - return new BallerinaXMLProcessingInstructionTypeSymbol(this.context, internalType); - case XML_COMMENT: - return new BallerinaXMLCommentTypeSymbol(this.context, internalType); - case XML_TEXT: - return new BallerinaXMLTextTypeSymbol(this.context, internalType); - } - - throw new IllegalStateException("Invalid XML subtype type tag: " + internalType.tag); + return switch (internalType.tag) { + case XML_ELEMENT -> new BallerinaXMLElementTypeSymbol(this.context, internalType); + case XML_PI -> new BallerinaXMLProcessingInstructionTypeSymbol(this.context, internalType); + case XML_COMMENT -> new BallerinaXMLCommentTypeSymbol(this.context, internalType); + case XML_TEXT -> new BallerinaXMLTextTypeSymbol(this.context, internalType); + default -> throw new IllegalStateException("Invalid XML subtype type tag: " + internalType.tag); + }; } public boolean isTypeReference(BType bType, BSymbol tSymbol, boolean rawTypeOnly) { @@ -325,74 +313,34 @@ public boolean isTypeReference(BType bType, BSymbol tSymbol, boolean rawTypeOnly } public static TypeDescKind getTypeDescKind(TypeKind bTypeKind) { - switch (bTypeKind) { - case ANY: - return TypeDescKind.ANY; - case ANYDATA: - return TypeDescKind.ANYDATA; - case ARRAY: - return TypeDescKind.ARRAY; - case BOOLEAN: - return TypeDescKind.BOOLEAN; - case BYTE: - return TypeDescKind.BYTE; - case DECIMAL: - return TypeDescKind.DECIMAL; - case FLOAT: - return TypeDescKind.FLOAT; - case HANDLE: - return TypeDescKind.HANDLE; - case INT: - return TypeDescKind.INT; - case NEVER: - return TypeDescKind.NEVER; - case NIL: - return TypeDescKind.NIL; - case STRING: - return TypeDescKind.STRING; - case JSON: - return TypeDescKind.JSON; - case XML: - return TypeDescKind.XML; - case FUNCTION: - return TypeDescKind.FUNCTION; - case FUTURE: - return TypeDescKind.FUTURE; - case MAP: - return TypeDescKind.MAP; - case OBJECT: - return TypeDescKind.OBJECT; - case STREAM: - return TypeDescKind.STREAM; - case TUPLE: - return TypeDescKind.TUPLE; - case TYPEDESC: - return TypeDescKind.TYPEDESC; - case UNION: - return TypeDescKind.UNION; - case INTERSECTION: - return TypeDescKind.INTERSECTION; - case ERROR: - return TypeDescKind.ERROR; - case NONE: - case OTHER: - return TypeDescKind.NONE; - case PARAMETERIZED: - case ANNOTATION: - case BLOB: - case CHANNEL: - case CONNECTOR: - case ENDPOINT: - case FINITE: - case PACKAGE: - case READONLY: - case SERVICE: - case TABLE: - case TYPEPARAM: - case VOID: - default: - return null; - } + return switch (bTypeKind) { + case ANY -> TypeDescKind.ANY; + case ANYDATA -> TypeDescKind.ANYDATA; + case ARRAY -> TypeDescKind.ARRAY; + case BOOLEAN -> TypeDescKind.BOOLEAN; + case BYTE -> TypeDescKind.BYTE; + case DECIMAL -> TypeDescKind.DECIMAL; + case FLOAT -> TypeDescKind.FLOAT; + case HANDLE -> TypeDescKind.HANDLE; + case INT -> TypeDescKind.INT; + case NEVER -> TypeDescKind.NEVER; + case NIL -> TypeDescKind.NIL; + case STRING -> TypeDescKind.STRING; + case JSON -> TypeDescKind.JSON; + case XML -> TypeDescKind.XML; + case FUNCTION -> TypeDescKind.FUNCTION; + case FUTURE -> TypeDescKind.FUTURE; + case MAP -> TypeDescKind.MAP; + case OBJECT -> TypeDescKind.OBJECT; + case STREAM -> TypeDescKind.STREAM; + case TUPLE -> TypeDescKind.TUPLE; + case TYPEDESC -> TypeDescKind.TYPEDESC; + case UNION -> TypeDescKind.UNION; + case INTERSECTION -> TypeDescKind.INTERSECTION; + case ERROR -> TypeDescKind.ERROR; + case NONE, OTHER -> TypeDescKind.NONE; + default -> null; + }; } private static boolean isCustomError(BSymbol tSymbol) { @@ -400,31 +348,29 @@ private static boolean isCustomError(BSymbol tSymbol) { } private static boolean isBuiltinNamedType(int tag) { - switch (tag) { - case INT: - case BYTE: - case FLOAT: - case DECIMAL: - case STRING: - case BOOLEAN: - case JSON: - case XML: - case NIL: - case ANY: - case ANYDATA: - case HANDLE: - case READONLY: - case NEVER: - case MAP: - case STREAM: - case TYPEDESC: - case TABLE: - case ERROR: - case FUTURE: - case SEMANTIC_ERROR: - return true; - } - - return false; + return switch (tag) { + case INT, + BYTE, + FLOAT, + DECIMAL, + STRING, + BOOLEAN, + JSON, + XML, + NIL, + ANY, + ANYDATA, + HANDLE, + READONLY, + NEVER, + MAP, + STREAM, + TYPEDESC, + TABLE, + ERROR, + FUTURE, + SEMANTIC_ERROR -> true; + default -> false; + }; } } diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/symbols/resourcepath/BallerinaPathSegmentList.java b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/symbols/resourcepath/BallerinaPathSegmentList.java index e5a7d77413bb..f9c96bff3ad7 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/symbols/resourcepath/BallerinaPathSegmentList.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/symbols/resourcepath/BallerinaPathSegmentList.java @@ -138,19 +138,11 @@ public List list() { for (int i = 0, pathParamCount = 0, pathSegmentCount = this.internalPathSegmentSymbols.size(); i < pathSegmentCount; i++) { BResourcePathSegmentSymbol pathSegmentSymbol = this.internalPathSegmentSymbols.get(i); - PathSegment segment; - switch (pathSegmentSymbol.getName().getValue()) { - case "$^": - case "^": - segment = pathParams.get(pathParamCount++); - break; - case "^^": - case "$^^": - segment = pathRestParameter().get(); - break; - default: - segment = symbolFactory.createPathNameSymbol(pathSegmentSymbol); - } + PathSegment segment = switch (pathSegmentSymbol.getName().getValue()) { + case "$^", "^" -> pathParams.get(pathParamCount++); + case "^^", "$^^" -> pathRestParameter().get(); + default -> symbolFactory.createPathNameSymbol(pathSegmentSymbol); + }; segments.add(segment); } diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaArrayTypeBuilder.java b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaArrayTypeBuilder.java index e39e679d200c..72702a3e9105 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaArrayTypeBuilder.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaArrayTypeBuilder.java @@ -101,8 +101,8 @@ private BType getBType(TypeSymbol type) { throw new IllegalArgumentException("Array member type descriptor can not be null"); } - if (type instanceof AbstractTypeSymbol) { - return ((AbstractTypeSymbol) type).getBType(); + if (type instanceof AbstractTypeSymbol abstractTypeSymbol) { + return abstractTypeSymbol.getBType(); } throw new IllegalArgumentException("Invalid array member type descriptor provided"); diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaFunctionTypeBuilder.java b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaFunctionTypeBuilder.java index cc530e2c1b2b..178519d7121a 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaFunctionTypeBuilder.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaFunctionTypeBuilder.java @@ -122,8 +122,7 @@ private BVarSymbol getRestParamSymbol(ParameterSymbol restParam, BType restType) } BSymbol internalSymbol = ((BallerinaSymbol) restParam).getInternalSymbol(); - if (internalSymbol instanceof BVarSymbol) { - BVarSymbol varSymbol = (BVarSymbol) internalSymbol; + if (internalSymbol instanceof BVarSymbol varSymbol) { varSymbol.type = restType; return varSymbol; } @@ -150,8 +149,8 @@ private List getParamSymbols(List parameterSymbols) List params = new ArrayList<>(); for (ParameterSymbol parameterSymbol : parameterSymbols) { BSymbol internalSymbol = ((BallerinaSymbol) parameterSymbol).getInternalSymbol(); - if (internalSymbol instanceof BVarSymbol) { - params.add((BVarSymbol) internalSymbol); + if (internalSymbol instanceof BVarSymbol bVarSymbol) { + params.add(bVarSymbol); } } @@ -168,8 +167,8 @@ private List getParamTypes(List parameterSymbols) { } private BType getBType(TypeSymbol typeSymbol) { - if (typeSymbol instanceof AbstractTypeSymbol) { - return ((AbstractTypeSymbol) typeSymbol).getBType(); + if (typeSymbol instanceof AbstractTypeSymbol abstractTypeSymbol) { + return abstractTypeSymbol.getBType(); } throw new IllegalArgumentException("Invalid type provided"); @@ -180,8 +179,8 @@ private BType getReturnBType(TypeSymbol returnTypeSymbol) { return symTable.nilType; } - if (returnTypeSymbol instanceof AbstractTypeSymbol) { - return ((AbstractTypeSymbol) returnTypeSymbol).getBType(); + if (returnTypeSymbol instanceof AbstractTypeSymbol abstractTypeSymbol) { + return abstractTypeSymbol.getBType(); } throw new IllegalArgumentException("Invalid return type provided"); @@ -255,8 +254,8 @@ public ParameterSymbol build() { } private BType getBType(TypeSymbol typeSymbol) { - if (typeSymbol instanceof AbstractTypeSymbol) { - return ((AbstractTypeSymbol) typeSymbol).getBType(); + if (typeSymbol instanceof AbstractTypeSymbol abstractTypeSymbol) { + return abstractTypeSymbol.getBType(); } throw new IllegalArgumentException("Invalid type provided"); diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaFutureTypeBuilder.java b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaFutureTypeBuilder.java index 6cf35d04f6c2..073cf34788a8 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaFutureTypeBuilder.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaFutureTypeBuilder.java @@ -76,8 +76,8 @@ private BType getBType(TypeSymbol typeSymbol) { return null; } - if (typeSymbol instanceof AbstractTypeSymbol) { - return ((AbstractTypeSymbol) typeSymbol).getBType(); + if (typeSymbol instanceof AbstractTypeSymbol abstractTypeSymbol) { + return abstractTypeSymbol.getBType(); } return symTable.noType; diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaObjectTypeBuilder.java b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaObjectTypeBuilder.java index f1c67ebaba80..831998e3df26 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaObjectTypeBuilder.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaObjectTypeBuilder.java @@ -176,10 +176,10 @@ symbolName, symbolName, symTable.rootPkgSymbol.pkgID, getBInvokableType(objectMe } private BInvokableType getBInvokableType(FunctionTypeSymbol type) { - if (type instanceof AbstractTypeSymbol) { - BType bType = ((AbstractTypeSymbol) type).getBType(); - if (bType instanceof BInvokableType) { - return (BInvokableType) bType; + if (type instanceof AbstractTypeSymbol abstractTypeSymbol) { + BType bType = abstractTypeSymbol.getBType(); + if (bType instanceof BInvokableType bInvokableType) { + return bInvokableType; } } @@ -212,8 +212,8 @@ ownerObjectTypeSymbol.pkgID, getBType(objectField.getType()), ownerObjectTypeSym private BType getBType(TypeSymbol typeSymbol) { if (typeSymbol != null) { - if (typeSymbol instanceof AbstractTypeSymbol) { - return ((AbstractTypeSymbol) typeSymbol).getBType(); + if (typeSymbol instanceof AbstractTypeSymbol abstractTypeSymbol) { + return abstractTypeSymbol.getBType(); } } @@ -222,8 +222,8 @@ private BType getBType(TypeSymbol typeSymbol) { private BType getTypeInclusionBType(TypeSymbol typeSymbol) { if (typeSymbol != null) { - if (typeSymbol instanceof AbstractTypeSymbol) { - return ((AbstractTypeSymbol) typeSymbol).getBType(); + if (typeSymbol instanceof AbstractTypeSymbol abstractTypeSymbol) { + return abstractTypeSymbol.getBType(); } throw new IllegalArgumentException("Invalid type provided"); diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaRecordTypeBuilder.java b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaRecordTypeBuilder.java index e3541c1f3de3..33c88117390f 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaRecordTypeBuilder.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaRecordTypeBuilder.java @@ -245,8 +245,8 @@ private List getTypeInclusions(List typeInclusio private BType getBType(TypeSymbol typeSymbol) { if (typeSymbol != null) { - if (typeSymbol instanceof AbstractTypeSymbol) { - return ((AbstractTypeSymbol) typeSymbol).getBType(); + if (typeSymbol instanceof AbstractTypeSymbol abstractTypeSymbol) { + return abstractTypeSymbol.getBType(); } throw new IllegalArgumentException("Invalid type provided"); diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaSingletonTypeBuilder.java b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaSingletonTypeBuilder.java index 5fe02a612b22..148ebbed813b 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaSingletonTypeBuilder.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaSingletonTypeBuilder.java @@ -89,23 +89,16 @@ public SingletonTypeSymbol build() { } private boolean isValidValueType(Object value, TypeSymbol typeSymbol) { - switch (typeSymbol.typeKind()) { - case STRING: - return value instanceof String || value instanceof Character; - case INT: - return value instanceof Integer; - case DECIMAL: - case FLOAT: - return value instanceof Float || value instanceof Double; - case BYTE: - return value instanceof Byte; - case BOOLEAN: - return value instanceof Boolean; - case NIL: - return value.equals("()"); - } + return switch (typeSymbol.typeKind()) { + case STRING -> value instanceof String || value instanceof Character; + case INT -> value instanceof Integer; + case DECIMAL, FLOAT -> value instanceof Float || value instanceof Double; + case BYTE -> value instanceof Byte; + case BOOLEAN -> value instanceof Boolean; + case NIL -> value.equals("()"); + default -> false; + }; - return false; } private BType getValueBType(TypeSymbol typeSymbol) { @@ -113,8 +106,8 @@ private BType getValueBType(TypeSymbol typeSymbol) { return symTable.noType; } - if (typeSymbol instanceof AbstractTypeSymbol) { - return ((AbstractTypeSymbol) typeSymbol).getBType(); + if (typeSymbol instanceof AbstractTypeSymbol abstractTypeSymbol) { + return abstractTypeSymbol.getBType(); } return symTable.anyType; diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaStreamTypeBuilder.java b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaStreamTypeBuilder.java index c6ea682f5c5d..e71fc54136c9 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaStreamTypeBuilder.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaStreamTypeBuilder.java @@ -86,16 +86,16 @@ private BType getValueBType(TypeSymbol valueType) { return symTable.anyType; } - if (valueType instanceof AbstractTypeSymbol) { - return ((AbstractTypeSymbol) valueType).getBType(); + if (valueType instanceof AbstractTypeSymbol abstractTypeSymbol) { + return abstractTypeSymbol.getBType(); } return symTable.noType; } private BType getCompletionBType(TypeSymbol completionType) { - if (completionType instanceof AbstractTypeSymbol) { - return ((AbstractTypeSymbol) completionType).getBType(); + if (completionType instanceof AbstractTypeSymbol abstractTypeSymbol) { + return abstractTypeSymbol.getBType(); } return symTable.nilType; diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaTableTypeBuilder.java b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaTableTypeBuilder.java index da222627a608..18af7c102770 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaTableTypeBuilder.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaTableTypeBuilder.java @@ -123,8 +123,8 @@ public TableTypeSymbol build() { private boolean isValidFieldNameList(List fieldNames, TypeSymbol rowType) { // check if a key field name exist in the rowType's record fields as a readonly field. - if (rowType instanceof RecordTypeSymbol) { - Map fieldDescriptors = ((RecordTypeSymbol) rowType).fieldDescriptors(); + if (rowType instanceof RecordTypeSymbol recordTypeSymbol) { + Map fieldDescriptors = recordTypeSymbol.fieldDescriptors(); for (String fieldName : fieldNames) { if (!fieldDescriptors.containsKey(fieldName)) { return false; @@ -144,8 +144,8 @@ private boolean isValidFieldNameList(List fieldNames, TypeSymbol rowType private boolean isReadOnlyField(RecordFieldSymbol recordField) { TypeSymbol typeDescriptor = recordField.typeDescriptor(); - if (typeDescriptor instanceof AbstractTypeSymbol) { - BType bType = ((AbstractTypeSymbol) typeDescriptor).getBType(); + if (typeDescriptor instanceof AbstractTypeSymbol abstractTypeSymbol) { + BType bType = abstractTypeSymbol.getBType(); return Symbols.isFlagOn(bType.flags, Flags.READONLY); } @@ -192,16 +192,16 @@ private BType checkKeyConstraintBType(TypeSymbol keyType, TypeSymbol rowType) { private boolean isValidKeyConstraintType(TypeSymbol fieldType, TypeSymbol keyType) { if ((fieldType.typeKind() == keyType.typeKind() || keyType.subtypeOf(fieldType)) - && fieldType instanceof AbstractTypeSymbol) { - return Symbols.isFlagOn(((AbstractTypeSymbol) fieldType).getBType().flags, Flags.READONLY); + && fieldType instanceof AbstractTypeSymbol abstractTypeSymbol) { + return Symbols.isFlagOn(abstractTypeSymbol.getBType().flags, Flags.READONLY); } return false; } private BType getKeyBType(TypeSymbol typeSymbol) { - if (typeSymbol instanceof AbstractTypeSymbol) { - return ((AbstractTypeSymbol) typeSymbol).getBType(); + if (typeSymbol instanceof AbstractTypeSymbol abstractTypeSymbol) { + return abstractTypeSymbol.getBType(); } throw new IllegalArgumentException("Invalid key type parameter provided"); @@ -214,12 +214,11 @@ private BType getRowBType(TypeSymbol rowType, boolean isKeyless) { BType rowBType = getBType(rowType); if (types.isAssignable(rowBType, symTable.mapType)) { - if (rowBType instanceof BRecordType) { - if (isKeyless || isValidRowRecordType((BRecordType) rowBType)) { + if (rowBType instanceof BRecordType bRecordType) { + if (isKeyless || isValidRowRecordType(bRecordType)) { return rowBType; } - } else if (rowBType instanceof BMapType) { - BMapType rowMapType = (BMapType) rowBType; + } else if (rowBType instanceof BMapType rowMapType) { BType mapTypeConstraint = rowMapType.getConstraint(); if (types.isAssignable(mapTypeConstraint, symTable.pureType)) { return rowBType; @@ -245,9 +244,9 @@ private boolean isValidRowRecordType(BRecordType rowBType) { private BType getBType(TypeSymbol typeSymbol) { if (typeSymbol != null) { - if (typeSymbol instanceof AbstractTypeSymbol + if (typeSymbol instanceof AbstractTypeSymbol abstractTypeSymbol && typeSymbol.subtypeOf(typesFactory.getTypeDescriptor(symTable.anyType))) { - return ((AbstractTypeSymbol) typeSymbol).getBType(); + return abstractTypeSymbol.getBType(); } throw new IllegalArgumentException("Invalid type parameter provided"); diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaTupleTypeBuilder.java b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaTupleTypeBuilder.java index 144de73a9fa2..9b401688b982 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaTupleTypeBuilder.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaTupleTypeBuilder.java @@ -100,13 +100,13 @@ private BType getMemberType(TypeSymbol memberType) { throw new IllegalArgumentException("Member type provided to the Tuple type descriptor can not be null."); } - if (memberType instanceof AbstractTypeSymbol) { - return ((AbstractTypeSymbol) memberType).getBType(); + if (memberType instanceof AbstractTypeSymbol abstractTypeSymbol) { + return abstractTypeSymbol.getBType(); } return symTable.noType; } private BType getRestType(TypeSymbol restType) { - return restType instanceof AbstractTypeSymbol ? ((AbstractTypeSymbol) restType).getBType() : null; + return restType instanceof AbstractTypeSymbol abstractTypeSymbol ? abstractTypeSymbol.getBType() : null; } } diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaTypeDescTypeBuilder.java b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaTypeDescTypeBuilder.java index 5629708e8a74..d387090e8562 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaTypeDescTypeBuilder.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaTypeDescTypeBuilder.java @@ -72,8 +72,8 @@ public TypeDescTypeSymbol build() { private BType getBType(TypeSymbol typeSymbol) { if (typeSymbol != null) { - if (typeSymbol instanceof AbstractTypeSymbol) { - return ((AbstractTypeSymbol) typeSymbol).getBType(); + if (typeSymbol instanceof AbstractTypeSymbol abstractTypeSymbol) { + return abstractTypeSymbol.getBType(); } return symTable.noType; } diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaUnionTypeBuilder.java b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaUnionTypeBuilder.java index c98dfd00437e..fd0d90aec70a 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaUnionTypeBuilder.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/type/builders/BallerinaUnionTypeBuilder.java @@ -91,16 +91,16 @@ private BType[] getMemberBTypes() { List bTypeList = new ArrayList<>(); for (TypeSymbol memberType : memberTypes) { - if (memberType instanceof AbstractTypeSymbol) { - bTypeList.add(((AbstractTypeSymbol) memberType).getBType()); + if (memberType instanceof AbstractTypeSymbol abstractTypeSymbol) { + bTypeList.add(abstractTypeSymbol.getBType()); continue; } if ((memberType instanceof ClassSymbol || memberType instanceof ConstantSymbol || memberType instanceof EnumSymbol) - && memberType instanceof BallerinaSymbol) { - bTypeList.add(((BallerinaSymbol) memberType).getInternalSymbol().getType()); + && memberType instanceof BallerinaSymbol ballerinaSymbol) { + bTypeList.add(ballerinaSymbol.getInternalSymbol().getType()); continue; } diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/util/SymbolUtils.java b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/util/SymbolUtils.java index c48b6416cc0e..dcef4293e015 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/util/SymbolUtils.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/util/SymbolUtils.java @@ -44,7 +44,10 @@ /** * Common util methods related to symbols. */ -public class SymbolUtils { +public final class SymbolUtils { + + private SymbolUtils() { + } public static String unescapeUnicode(String value) { if (value.startsWith("'")) { @@ -57,34 +60,22 @@ public static Optional getTypeDescriptor(Symbol symbol) { if (symbol == null) { return Optional.empty(); } - switch (symbol.kind()) { - case TYPE_DEFINITION: - return Optional.ofNullable(((TypeDefinitionSymbol) symbol).typeDescriptor()); - case VARIABLE: - return Optional.ofNullable(((VariableSymbol) symbol).typeDescriptor()); - case PARAMETER: - return Optional.ofNullable(((ParameterSymbol) symbol).typeDescriptor()); - case ANNOTATION: - return ((AnnotationSymbol) symbol).typeDescriptor(); - case FUNCTION: - case METHOD: - return Optional.ofNullable(((FunctionSymbol) symbol).typeDescriptor()); - case CONSTANT: - case ENUM_MEMBER: - return Optional.ofNullable(((ConstantSymbol) symbol).typeDescriptor()); - case CLASS: - return Optional.of((ClassSymbol) symbol); - case RECORD_FIELD: - return Optional.ofNullable(((RecordFieldSymbol) symbol).typeDescriptor()); - case OBJECT_FIELD: - return Optional.of(((ObjectFieldSymbol) symbol).typeDescriptor()); - case CLASS_FIELD: - return Optional.of(((ClassFieldSymbol) symbol).typeDescriptor()); - case TYPE: - return Optional.of((TypeSymbol) symbol); - default: - return Optional.empty(); - } + return switch (symbol.kind()) { + case TYPE_DEFINITION -> Optional.ofNullable(((TypeDefinitionSymbol) symbol).typeDescriptor()); + case VARIABLE -> Optional.ofNullable(((VariableSymbol) symbol).typeDescriptor()); + case PARAMETER -> Optional.ofNullable(((ParameterSymbol) symbol).typeDescriptor()); + case ANNOTATION -> ((AnnotationSymbol) symbol).typeDescriptor(); + case FUNCTION, + METHOD -> Optional.ofNullable(((FunctionSymbol) symbol).typeDescriptor()); + case CONSTANT, + ENUM_MEMBER -> Optional.ofNullable(((ConstantSymbol) symbol).typeDescriptor()); + case CLASS -> Optional.of((ClassSymbol) symbol); + case RECORD_FIELD -> Optional.ofNullable(((RecordFieldSymbol) symbol).typeDescriptor()); + case OBJECT_FIELD -> Optional.of(((ObjectFieldSymbol) symbol).typeDescriptor()); + case CLASS_FIELD -> Optional.of(((ClassFieldSymbol) symbol).typeDescriptor()); + case TYPE -> Optional.of((TypeSymbol) symbol); + default -> Optional.empty(); + }; } /** @@ -94,24 +85,20 @@ public static Optional getTypeDescriptor(Symbol symbol) { * @return The bound type based on the kind of the input BType. Returns null if the kind is not supported. */ public static BType getTypeParamBoundType(BType type) { - switch (type.getKind()) { - case MAP: - return ((BMapType) type).constraint; - case ARRAY: - return ((BArrayType) type).eType; - case TABLE: - return ((BTableType) type).constraint; - case STREAM: - return ((BStreamType) type).constraint; - case XML: - if (type.tag == TypeTags.XML) { - return ((BXMLType) type).constraint; - } - return type; - // The following explicitly mentioned type kinds should be supported, but they are not for the moment. - case ERROR: - default: - return null; - } + return switch (type.getKind()) { + case MAP -> ((BMapType) type).constraint; + case ARRAY -> ((BArrayType) type).eType; + case TABLE -> ((BTableType) type).constraint; + case STREAM -> ((BStreamType) type).constraint; + case XML -> { + if (type.tag == TypeTags.XML) { + yield ((BXMLType) type).constraint; + } + yield type; + } + // The following explicitly mentioned type kinds should be supported, but they are not for the moment. + case ERROR -> null; + default -> null; + }; } } diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/values/BallerinaConstantValue.java b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/values/BallerinaConstantValue.java index 12f2db7d0fff..68224d6872ae 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/values/BallerinaConstantValue.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/impl/values/BallerinaConstantValue.java @@ -61,8 +61,7 @@ public boolean equals(Object o) { return false; } - if (o instanceof BallerinaConstantValue) { - BallerinaConstantValue that = (BallerinaConstantValue) o; + if (o instanceof BallerinaConstantValue that) { if (this.valueType != that.valueType) { return false; diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/symbols/TypeDescKind.java b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/symbols/TypeDescKind.java index ca5f066b3e1b..2ff3aa166685 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/symbols/TypeDescKind.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/compiler/api/symbols/TypeDescKind.java @@ -77,32 +77,26 @@ public String getName() { } public boolean isIntegerType() { - switch (this) { - case INT: - case INT_SIGNED8: - case INT_UNSIGNED8: - case INT_SIGNED16: - case INT_UNSIGNED16: - case INT_SIGNED32: - case INT_UNSIGNED32: - case BYTE: - return true; - } + return switch (this) { + case INT, + INT_SIGNED8, + INT_UNSIGNED8, + INT_SIGNED16, + INT_UNSIGNED16, + INT_SIGNED32, + INT_UNSIGNED32, + BYTE -> true; + default -> false; + }; - return false; } public boolean isXMLType() { - switch (this) { - case XML: - case XML_COMMENT: - case XML_ELEMENT: - case XML_PROCESSING_INSTRUCTION: - case XML_TEXT: - return true; - } + return switch (this) { + case XML, XML_COMMENT, XML_ELEMENT, XML_PROCESSING_INSTRUCTION, XML_TEXT -> true; + default -> false; + }; - return false; } public boolean isStringType() { diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/Bootstrap.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/Bootstrap.java index d2b6e25ba7b7..e4c6a9f15902 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/Bootstrap.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/Bootstrap.java @@ -22,6 +22,7 @@ import io.ballerina.projects.environment.ResolutionRequest; import io.ballerina.projects.environment.ResolutionResponse; import org.ballerinalang.model.elements.PackageID; +import org.wso2.ballerinalang.compiler.PackageCache; import org.wso2.ballerinalang.compiler.semantics.analyzer.SymbolResolver; import org.wso2.ballerinalang.compiler.semantics.model.SymbolTable; import org.wso2.ballerinalang.compiler.semantics.model.symbols.BPackageSymbol; @@ -238,8 +239,7 @@ private ResolutionRequest toResolutionRequest(PackageID packageID) { } private BPackageSymbol getSymbolFromCache(CompilerContext context, PackageID packageID) { - org.wso2.ballerinalang.compiler.PackageCache pkgCache = - org.wso2.ballerinalang.compiler.PackageCache.getInstance(context); + PackageCache pkgCache = PackageCache.getInstance(context); BLangPackage bLangPackage = pkgCache.get(packageID); if (bLangPackage != null) { return bLangPackage.symbol; diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/CompilerPluginContextIml.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/CompilerPluginContextIml.java index c3e8da242019..b3d1ba54f6d4 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/CompilerPluginContextIml.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/CompilerPluginContextIml.java @@ -17,6 +17,7 @@ */ package io.ballerina.projects; +import io.ballerina.compiler.syntax.tree.Node; import io.ballerina.projects.plugins.CodeAnalyzer; import io.ballerina.projects.plugins.CodeGenerator; import io.ballerina.projects.plugins.CodeModifier; @@ -43,8 +44,8 @@ class CompilerPluginContextIml implements CompilerPluginContext { private final List codeModifiers = new ArrayList<>(); private final List lifecycleListeners = new ArrayList<>(); private final List codeActions = new ArrayList<>(); - private Map compilerPluginUserData = new HashMap(); - private final List completionProviders = new ArrayList<>(); + private Map compilerPluginUserData = new HashMap<>(); + private final List> completionProviders = new ArrayList<>(); CompilerPluginContextIml(CompilerPluginInfo compilerPluginInfo) { this.compilerPluginInfo = compilerPluginInfo; @@ -82,7 +83,7 @@ public void addCodeAction(CodeAction codeAction) { } @Override - public void addCompletionProvider(CompletionProvider completionProvider) { + public void addCompletionProvider(CompletionProvider completionProvider) { completionProviders.add(completionProvider); } @@ -106,7 +107,7 @@ public List codeActions() { return codeActions; } - public List completionProviders() { + public List> completionProviders() { return completionProviders; } diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/CompilerPluginManager.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/CompilerPluginManager.java index 6f2ba751ac43..9e4145a098f7 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/CompilerPluginManager.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/CompilerPluginManager.java @@ -26,7 +26,6 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; -import java.util.stream.Collectors; /** * Responsible for loading and maintaining engaged compiler plugins. @@ -171,7 +170,7 @@ private static CompilerPluginInfo loadCompilerPlugin(CompilerPluginDescriptor pl List jarLibraryPaths = pluginDescriptor.getCompilerPluginDependencies() .stream() .map(Paths::get) - .collect(Collectors.toList()); + .toList(); CompilerPlugin compilerPlugin; try { @@ -192,7 +191,7 @@ private static List getDirectDependencies(ResolvedPackageDependency roo return dependencyGraph.getDirectDependencies(rootPkgNode) .stream() .map(ResolvedPackageDependency::packageInstance) - .collect(Collectors.toList()); + .toList(); } private static List initializePlugins(List compilerPlugins, diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/CompletionManager.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/CompletionManager.java index ba53edad7e5f..fc84ee51c37d 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/CompletionManager.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/CompletionManager.java @@ -41,7 +41,6 @@ import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.stream.Collectors; /** * Manages interaction with completion providers via compiler plugins. @@ -54,11 +53,13 @@ public class CompletionManager { private CompletionManager(List compilerPluginContexts) { completionProviders = new HashMap<>(); compilerPluginContexts.forEach(compilerPluginContextIml -> { - for (CompletionProvider completionProvider : compilerPluginContextIml.completionProviders()) { + for (CompletionProvider completionProvider : + compilerPluginContextIml.completionProviders()) { for (Class attachmentPoint : completionProvider.getSupportedNodes()) { List completionProviderList = completionProviders.computeIfAbsent(attachmentPoint, k -> new ArrayList<>()); - completionProviderList.add(new CompletionProviderDescriptor(completionProvider, + completionProviderList.add(new CompletionProviderDescriptor( + (CompletionProvider) completionProvider, compilerPluginContextIml.compilerPluginInfo())); } } @@ -159,7 +160,7 @@ private List getModulesOfActiveListeners(CompletionContext context } return Optional.of(listenerType); }).filter(listenerType -> listenerType.isPresent() && listenerType.get().getModule().isPresent()) - .map(listenerType -> listenerType.get().getModule().get()).collect(Collectors.toList()); + .map(listenerType -> listenerType.get().getModule().get()).toList(); } private TypeSymbol getRawType(TypeSymbol typeDescriptor) { @@ -204,7 +205,7 @@ static class CompletionProviderDescriptor { private final CompletionProvider completionProvider; private final CompilerPluginInfo compilerPluginInfo; - public CompletionProviderDescriptor(CompletionProvider completionProvider, + public CompletionProviderDescriptor(CompletionProvider completionProvider, CompilerPluginInfo compilerPluginInfo) { this.completionProvider = completionProvider; this.compilerPluginInfo = compilerPluginInfo; diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/ConfigReader.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/ConfigReader.java index 3a688369e253..fc35b719b2de 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/ConfigReader.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/ConfigReader.java @@ -50,14 +50,16 @@ import java.util.Map; import java.util.Optional; import java.util.Set; -import java.util.stream.Collectors; /** * Util class to read configurable variables defined in a package. * * @since 2.0.0 */ -public class ConfigReader { +public final class ConfigReader { + + private ConfigReader() { + } /** * Retrieve all the configurable variables for a package. @@ -196,8 +198,7 @@ private static void getConfigVars(Module module, Collection sc // Filter configurable variables if (symbol != null && symbol.tag == SymTag.VARIABLE && Symbols.isFlagOn(symbol.flags, Flags.CONFIGURABLE)) { - if (symbol instanceof BVarSymbol) { - BVarSymbol varSymbol = (BVarSymbol) symbol; + if (symbol instanceof BVarSymbol varSymbol) { if ((validConfigs != null && validConfigs.contains(varSymbol)) || validConfigs == null) { // Get description String description = getDescriptionValue(varSymbol, module); @@ -241,8 +242,9 @@ private static void populateConfigVars(BPackageSymbol pkgSymbol, Set symbol = symbol.type.tsymbol; } if (symbol != null && symbol.tag == SymTag.VARIABLE - && Symbols.isFlagOn(symbol.flags, Flags.CONFIGURABLE) && symbol instanceof BVarSymbol) { - configVars.add((BVarSymbol) symbol); + && Symbols.isFlagOn(symbol.flags, Flags.CONFIGURABLE) && + symbol instanceof BVarSymbol bVarSymbol) { + configVars.add(bVarSymbol); } } } @@ -300,16 +302,13 @@ private static Node getVariableNode(int position, Map synt for (Map.Entry syntaxTreeEntry : syntaxTreeMap.entrySet()) { if (syntaxTreeEntry.getValue().containsModulePart()) { ModulePartNode modulePartNode = syntaxTreeMap.get(syntaxTreeEntry.getKey()).rootNode(); - List filteredVarNodes = modulePartNode.members().stream() - .filter(node -> node.kind() == SyntaxKind.MODULE_VAR_DECL && - node instanceof ModuleVariableDeclarationNode) - .collect(Collectors.toList()); - for (Node node : filteredVarNodes) { - if (node.location().lineRange().startLine().line() <= position && - node.location().lineRange().endLine().line() >= position) { - return node; - } - } + return modulePartNode.members().stream() + .filter(node -> node.kind() == SyntaxKind.MODULE_VAR_DECL && + node instanceof ModuleVariableDeclarationNode && + node.location().lineRange().startLine().line() <= position && + node.location().lineRange().endLine().line() >= position) + .findFirst() + .orElse(null); } } return null; diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/Diagnostics.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/Diagnostics.java index 15fce09fc326..0f93cd199cd3 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/Diagnostics.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/Diagnostics.java @@ -22,14 +22,16 @@ import java.util.Collection; import java.util.function.Predicate; -import java.util.stream.Collectors; /** * This class contains various static methods that operate on {@code Diagnostic} instances. * * @since 2.0.0 */ -public class Diagnostics { +public final class Diagnostics { + + private Diagnostics() { + } public static Collection filterErrors(Collection diagnostics) { return filterDiagnostics(diagnostics, DiagnosticSeverity.ERROR); @@ -69,7 +71,7 @@ private static Collection filterDiagnostics(Collection d Predicate predicate) { return diagnostics.stream() .filter(predicate) - .collect(Collectors.toList()); + .toList(); } private static boolean hasDiagnosticsWithSeverity(Collection diagnostics, diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/JBallerinaBackend.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/JBallerinaBackend.java index 4facf9078f8c..6ecd546befeb 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/JBallerinaBackend.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/JBallerinaBackend.java @@ -72,7 +72,6 @@ import java.util.jar.JarFile; import java.util.jar.JarInputStream; import java.util.jar.Manifest; -import java.util.stream.Collectors; import static io.ballerina.projects.util.FileUtils.getFileNameWithoutExtension; import static io.ballerina.projects.util.ProjectConstants.BIN_DIR_NAME; @@ -290,7 +289,7 @@ public Collection platformLibraryDependencies(PackageId package return getPlatformLibraries(packageId) .stream() .filter(platformLibrary -> platformLibrary.scope() == scope) - .collect(Collectors.toList()); + .toList(); } private List getPlatformLibraries(PackageId packageId) { diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/JBallerinaBalaWriter.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/JBallerinaBalaWriter.java index 7c49f2660322..25aeaefb1914 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/JBallerinaBalaWriter.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/JBallerinaBalaWriter.java @@ -277,7 +277,7 @@ private boolean hasPlatformDependencies(Map pl } private Optional readCompilerPluginToml() { - Optional compilerPluginToml = backend.packageContext().project() + Optional compilerPluginToml = backend.packageContext().project() .currentPackage().compilerPluginToml(); if (compilerPluginToml.isPresent()) { diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/Module.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/Module.java index 48065a73e1b4..51b6d7e516cf 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/Module.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/Module.java @@ -146,7 +146,7 @@ public Optional moduleMd() { return this.moduleMd; } - private static class DocumentIterable implements Iterable { + private static class DocumentIterable implements Iterable { private final Collection documentList; public DocumentIterable(Collection documentList) { @@ -159,7 +159,7 @@ public Iterator iterator() { } @Override - public Spliterator spliterator() { + public Spliterator spliterator() { return this.documentList.spliterator(); } } diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/ModuleContext.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/ModuleContext.java index 7a43f6bf4b07..73b0754c448d 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/ModuleContext.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/ModuleContext.java @@ -31,6 +31,7 @@ import org.ballerinalang.model.elements.Flag; import org.ballerinalang.model.elements.PackageID; import org.wso2.ballerinalang.compiler.BIRPackageSymbolEnter; +import org.wso2.ballerinalang.compiler.PackageCache; import org.wso2.ballerinalang.compiler.bir.writer.BIRBinaryWriter; import org.wso2.ballerinalang.compiler.diagnostic.BLangDiagnosticLocation; import org.wso2.ballerinalang.compiler.semantics.analyzer.SymbolEnter; @@ -44,6 +45,8 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; import java.util.Collection; import java.util.Collections; import java.util.HashSet; @@ -53,6 +56,7 @@ import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.function.Supplier; import static org.ballerinalang.model.tree.SourceKind.REGULAR_SOURCE; import static org.ballerinalang.model.tree.SourceKind.TEST_SOURCE; @@ -367,8 +371,7 @@ static void compileInternal(ModuleContext moduleContext, CompilerContext compile moduleContext.bootstrap.loadLangLib(compilerContext, moduleCompilationId); } - org.wso2.ballerinalang.compiler.PackageCache packageCache = - org.wso2.ballerinalang.compiler.PackageCache.getInstance(compilerContext); + PackageCache packageCache = PackageCache.getInstance(compilerContext); SymbolEnter symbolEnter = SymbolEnter.getInstance(compilerContext); CompilerPhaseRunner compilerPhaseRunner = CompilerPhaseRunner.getInstance(compilerContext); @@ -398,8 +401,12 @@ static void compileInternal(ModuleContext moduleContext, CompilerContext compile packageCache.putSymbol(pkgNode.packageID, pkgNode.symbol); compilerPhaseRunner.performTypeCheckPhases(pkgNode); } catch (Throwable t) { - assert false : "Compilation failed due to" + - (t.getMessage() != null ? ": " + t.getMessage() : " an unhandled exception"); + assert false : "Compilation failed due to " + ((Supplier) () -> { + StringWriter errors = new StringWriter(); + t.printStackTrace(new PrintWriter(errors)); + return errors.toString(); + }).get(); + compilerPhaseRunner.addDiagnosticForUnhandledException(pkgNode, t); } moduleContext.bLangPackage = pkgNode; @@ -417,8 +424,11 @@ static void generateCodeInternal(ModuleContext moduleContext, try { compilerPhaseRunner.performBirGenPhases(moduleContext.bLangPackage); } catch (Throwable t) { - assert false : "Compilation failed due to" + - (t.getMessage() != null ? ": " + t.getMessage() : " an unhandled exception"); + assert false : "Compilation failed due to " + ((Supplier) () -> { + StringWriter errors = new StringWriter(); + t.printStackTrace(new PrintWriter(errors)); + return errors.toString(); + }).get(); compilerPhaseRunner.addDiagnosticForUnhandledException(moduleContext.bLangPackage, t); return; } @@ -505,8 +515,7 @@ static void resolveDependenciesFromBALAInternal(ModuleContext moduleContext) { } static void loadPackageSymbolInternal(ModuleContext moduleContext, CompilerContext compilerContext) { - org.wso2.ballerinalang.compiler.PackageCache packageCache = - org.wso2.ballerinalang.compiler.PackageCache.getInstance(compilerContext); + PackageCache packageCache = PackageCache.getInstance(compilerContext); BIRPackageSymbolEnter birPackageSymbolEnter = BIRPackageSymbolEnter.getInstance(compilerContext); PackageID moduleCompilationId = moduleContext.descriptor().moduleCompilationId(); diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/Package.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/Package.java index 7611ca1e83a0..c92df7c1fcf4 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/Package.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/Package.java @@ -414,7 +414,7 @@ public PackageResolution getResolution(ResolutionOptions resolutionOptions) { return this.packageContext.getResolution(newCompOptions, true); } - private static class ModuleIterable implements Iterable { + private static class ModuleIterable implements Iterable { private final Collection moduleList; @@ -428,7 +428,7 @@ public Iterator iterator() { } @Override - public Spliterator spliterator() { + public Spliterator spliterator() { return this.moduleList.spliterator(); } } diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/PackageResolution.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/PackageResolution.java index 90cb5f5f536f..c59091c276ba 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/PackageResolution.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/PackageResolution.java @@ -246,7 +246,7 @@ public Collection allDependencies() { .stream() // Remove root package from this list. .filter(resolvedPkg -> resolvedPkg.packageId() != rootPackageContext.packageId()) - .collect(Collectors.toList()); + .toList(); return dependenciesWithTransitives; } @@ -410,7 +410,7 @@ private DependencyGraph buildPackageGraph(DependencyG .filter(depNode -> !depNode.equals(rootNode) // Remove root node from the requests && !depNode.errorNode()) // Remove error nodes from the requests .map(this::createFromDepNode) - .collect(Collectors.toList()); + .toList(); Collection resolutionResponses = packageResolver.resolvePackages(resolutionRequests, resolutionOptions); @@ -447,7 +447,7 @@ private DependencyGraph buildPackageGraph(DependencyG .map(directDepNode -> resolvedPkgContainer.get( directDepNode.pkgDesc().org(), directDepNode.pkgDesc().name())) .flatMap(Optional::stream) - .collect(Collectors.toList()); + .toList(); depGraphBuilder.addDependencies(resolvedPkg, directPkgDependencies); } } @@ -552,7 +552,7 @@ private ModuleResolver createModuleResolver(PackageContext rootPackageContext, List moduleNames = rootPackageContext.moduleIds().stream() .map(rootPackageContext::moduleContext) .map(ModuleContext::moduleName) - .collect(Collectors.toList()); + .toList(); return new ModuleResolver(rootPackageContext.descriptor(), moduleNames, blendedManifest, projectEnvContext.getService(PackageResolver.class), resolutionOptions); } diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/ProjectEnvironmentBuilder.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/ProjectEnvironmentBuilder.java index 2f753a110783..6c37a0f6de9b 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/ProjectEnvironmentBuilder.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/ProjectEnvironmentBuilder.java @@ -59,18 +59,12 @@ public ProjectEnvironment build(Project project) { if (compilationCacheFactory != null) { compilationCache = compilationCacheFactory.createCompilationCache(project); } else { - switch (project.kind()) { - case BUILD_PROJECT: - compilationCache = BuildProjectCompilationCache.from(project); - break; - case SINGLE_FILE_PROJECT: - compilationCache = TempDirCompilationCache.from(project); - break; - case BALA_PROJECT: - throw new IllegalStateException("BALAProject should always be created with a CompilationCache"); - default: - throw new UnsupportedOperationException("Unsupported ProjectKind: " + project.kind()); - } + compilationCache = switch (project.kind()) { + case BUILD_PROJECT -> BuildProjectCompilationCache.from(project); + case SINGLE_FILE_PROJECT -> TempDirCompilationCache.from(project); + case BALA_PROJECT -> + throw new IllegalStateException("BALAProject should always be created with a CompilationCache"); + }; } services.put(CompilationCache.class, compilationCache); return new DefaultProjectEnvironment(project, environment, services); diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/directory/ProjectLoader.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/directory/ProjectLoader.java index 8ab9c19e13cc..baf85563d5a2 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/directory/ProjectLoader.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/directory/ProjectLoader.java @@ -35,7 +35,10 @@ * * @since 2.0.0 */ -public class ProjectLoader { +public final class ProjectLoader { + + private ProjectLoader() { + } public static Project loadProject(Path path) { return loadProject(path, ProjectEnvironmentBuilder.getDefaultBuilder(), BuildOptions.builder().build()); diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/BalToolsManifestBuilder.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/BalToolsManifestBuilder.java index 0ec73e7c110f..daca246ac75c 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/BalToolsManifestBuilder.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/BalToolsManifestBuilder.java @@ -53,7 +53,7 @@ public class BalToolsManifestBuilder { private final Map oldTools; private BalToolsManifestBuilder(TomlDocument balToolsToml) { - oldTools = new HashMap(); + oldTools = new HashMap<>(); this.balToolsToml = Optional.ofNullable(balToolsToml); this.balToolsManifest = parseAsBalToolsManifest(); } diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/BalaFiles.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/BalaFiles.java index 9aa21e2b4f01..c9f6349e9ef9 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/BalaFiles.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/BalaFiles.java @@ -82,7 +82,8 @@ * * @since 2.0.0 */ -public class BalaFiles { +public final class BalaFiles { + private static final Gson gson = new Gson(); // TODO change class name to utils @@ -204,7 +205,7 @@ private static List loadOtherModules(String pkgName, Path packagePat .filter(Files::isDirectory) .map(modulePath -> modulePath.getFileName().toString()) .map(fullModuleName -> loadModule(pkgName, fullModuleName, packagePath)) - .collect(Collectors.toList()); + .toList(); } catch (IOException e) { throw new ProjectException("Failed to read modules from directory: " + modulesDirPath, e); } @@ -653,7 +654,7 @@ private static ModuleDescriptor getModuleDescriptorFromDependencyEntry(ModuleDep private static List createModDescriptorList(List modDepEntries) { return modDepEntries.stream() .map(BalaFiles::getModuleDescriptorFromDependencyEntry) - .collect(Collectors.toList()); + .toList(); } private static DependencyGraphJson readDependencyGraphJson(Path dependencyGraphJsonPath) { diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/BlendedManifest.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/BlendedManifest.java index 7cb06b7c2dd1..f8387d892b41 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/BlendedManifest.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/BlendedManifest.java @@ -38,7 +38,6 @@ import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.stream.Collectors; import static io.ballerina.projects.PackageVersion.BUILTIN_PACKAGE_VERSION; @@ -187,7 +186,7 @@ private static Collection moduleNames(DependencyManifest.Package depende return dependency.modules() .stream() .map(DependencyManifest.Module::moduleName) - .collect(Collectors.toList()); + .toList(); } private static Collection moduleNames(PackageManifest.Dependency dependency, @@ -196,7 +195,7 @@ private static Collection moduleNames(PackageManifest.Dependency depende dependency.org(), dependency.name(), dependency.version()); return moduleDescriptors.stream() .map(moduleDesc -> moduleDesc.name().toString()) - .collect(Collectors.toList()); + .toList(); } public Optional lockedDependency(PackageOrg org, PackageName name) { @@ -235,7 +234,7 @@ private Optional dependency(PackageOrg org, PackageName name, Depend private Collection dependencies(DependencyOrigin origin) { return depContainer.getAll().stream() .filter(dep -> dep.origin == origin) - .collect(Collectors.toList()); + .toList(); } public DiagnosticResult diagnosticResult() { diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/DotGraphs.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/DotGraphs.java index 00418b610bbf..54a026643c04 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/DotGraphs.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/DotGraphs.java @@ -38,7 +38,7 @@ * * @since 2.0.0 */ -public class DotGraphs { +public final class DotGraphs { private DotGraphs() { } diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/ManifestUtils.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/ManifestUtils.java index d5aeafbd3828..e72747296f28 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/ManifestUtils.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/ManifestUtils.java @@ -33,7 +33,7 @@ * * @since 2.0.0 */ -public class ManifestUtils { +public final class ManifestUtils { private ManifestUtils() { } diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/PackageConfigCreator.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/PackageConfigCreator.java index 9c2350c54a6e..b9b527f00681 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/PackageConfigCreator.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/PackageConfigCreator.java @@ -46,14 +46,17 @@ import java.util.Map; import java.util.Objects; import java.util.Set; -import java.util.stream.Collectors; +import java.util.stream.Stream; /** * Creates a {@code PackageConfig} instance from the given {@code PackageData} instance. * * @since 2.0.0 */ -public class PackageConfigCreator { +public final class PackageConfigCreator { + + private PackageConfigCreator() { + } public static PackageConfig createBuildProjectConfig(Path projectDirPath, boolean disableSyntaxTree) { ProjectFiles.validateBuildProjectDirPath(projectDirPath); @@ -143,14 +146,12 @@ private static PackageConfig createPackageConfig(PackageData packageData, PackageName packageName = packageManifest.name(); PackageId packageId = PackageId.create(packageName.value()); - List moduleConfigs = packageData.otherModules() - .stream() - .map(moduleData -> createModuleConfig(packageManifest.descriptor(), moduleData, - packageId, moduleDependencyGraph)) - .collect(Collectors.toList()); + List moduleConfigs = Stream.concat(packageData.otherModules().stream() + .map(moduleData -> createModuleConfig(packageManifest.descriptor(), moduleData, + packageId, moduleDependencyGraph)), + Stream.of(createDefaultModuleConfig(packageManifest.descriptor(), + packageData.defaultModule(), packageId, moduleDependencyGraph))).toList(); - moduleConfigs.add(createDefaultModuleConfig(packageManifest.descriptor(), - packageData.defaultModule(), packageId, moduleDependencyGraph)); DocumentConfig ballerinaToml = packageData.ballerinaToml() .map(data -> createDocumentConfig(data, null)).orElse(null); @@ -237,7 +238,7 @@ private static List getResourceConfigs(List resources, Pat // TODO: no need Remove duplicate paths before processing Set distinctResources = new HashSet<>(resources); return distinctResources.stream().map( - distinctResource -> createResourceConfig(distinctResource, packagePath)).collect(Collectors.toList()); + distinctResource -> createResourceConfig(distinctResource, packagePath)).toList(); } private static ResourceConfig createResourceConfig(Path path, Path packagePath) { @@ -250,7 +251,7 @@ private static List getDocumentConfigs(ModuleId moduleId, List createDocumentConfig(srcDoc, moduleId)) - .collect(Collectors.toList()); + .toList(); } static DocumentConfig createDocumentConfig(DocumentData documentData, ModuleId moduleId) { diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/PackageContainer.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/PackageContainer.java index 388e70059a10..253f4189a3ec 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/PackageContainer.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/PackageContainer.java @@ -25,7 +25,6 @@ import java.util.Map; import java.util.NoSuchElementException; import java.util.Optional; -import java.util.stream.Collectors; /** * A container for various package representation that provides efficient access to packages. @@ -81,6 +80,6 @@ public Collection getAll() { .stream() .map(Map::values) .flatMap(Collection::stream) - .collect(Collectors.toList()); + .toList(); } } diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/PackageDependencyGraphBuilder.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/PackageDependencyGraphBuilder.java index ca46468fc549..5677f676cbe9 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/PackageDependencyGraphBuilder.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/PackageDependencyGraphBuilder.java @@ -43,7 +43,6 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; -import java.util.stream.Collectors; /** * This class is responsible for creating the Package dependency graph with no version conflicts. @@ -145,7 +144,7 @@ public boolean containsNode(PackageDescriptor node) { public Collection getAllDependencies() { return vertices.values().stream() .filter(vertex -> !vertex.equals(rootDepNode)) - .collect(Collectors.toList()); + .toList(); } public DependencyGraph buildGraph() { @@ -176,7 +175,7 @@ public DependencyGraph buildGraph() { public Collection getUnresolvedNodes() { Collection unresolvedNodes = unresolvedVertices.stream() .map(vertices::get) - .collect(Collectors.toList()); + .toList(); this.unresolvedVertices = new HashSet<>(); return unresolvedNodes; } diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/PackageVersionContainer.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/PackageVersionContainer.java index 1078e6318708..b7f26b6b79b3 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/PackageVersionContainer.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/PackageVersionContainer.java @@ -26,7 +26,6 @@ import java.util.HashMap; import java.util.Map; import java.util.Optional; -import java.util.stream.Collectors; /** * A container for various package representation that provides efficient access to packages. @@ -82,6 +81,6 @@ public Collection getAll() { .flatMap(Collection::stream) .map(Map::values) .flatMap(Collection::stream) - .collect(Collectors.toList()); + .toList(); } } diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/ProjectFiles.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/ProjectFiles.java index 595d5a22c3a5..b76b2fdcb02d 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/ProjectFiles.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/ProjectFiles.java @@ -53,7 +53,8 @@ * * @since 2.0.0 */ -public class ProjectFiles { +public final class ProjectFiles { + public static final PathMatcher BAL_EXTENSION_MATCHER = FileSystems.getDefault().getPathMatcher("glob:**.bal"); public static final PathMatcher BALA_EXTENSION_MATCHER = @@ -76,11 +77,8 @@ public static PackageData loadBuildProjectPackageData(Path packageDirPath) { ModuleData defaultModule = loadModule(packageDirPath); List otherModules = loadOtherModules(packageDirPath); List newModules = loadNewGeneratedModules(packageDirPath); - if (otherModules.isEmpty()) { - otherModules = newModules; - } else { - otherModules.addAll(newModules); - } + otherModules = Stream.concat(otherModules.stream(), newModules.stream()).toList(); + DocumentData ballerinaToml = loadDocument(packageDirPath.resolve(ProjectConstants.BALLERINA_TOML)); DocumentData dependenciesToml = loadDocument(packageDirPath.resolve(ProjectConstants.DEPENDENCIES_TOML)); DocumentData cloudToml = loadDocument(packageDirPath.resolve(ProjectConstants.CLOUD_TOML)); @@ -125,7 +123,7 @@ private static List loadNewGeneratedModules(Path packageDirPath) { return true; }) .map(ProjectFiles::loadModule) - .collect(Collectors.toList()); + .toList(); } catch (IOException e) { throw new ProjectException(e); } @@ -173,9 +171,9 @@ private static List loadOtherModules(Path packageDirPath) { private static ModuleData loadModule(Path moduleDirPath) { List srcDocs = loadDocuments(moduleDirPath); - List testSrcDocs; Path testDirPath = moduleDirPath.resolve("tests"); - testSrcDocs = Files.isDirectory(testDirPath) ? loadTestDocuments(testDirPath) : new ArrayList<>(); + List testSrcDocs = Files.isDirectory(testDirPath) ? loadTestDocuments(testDirPath) : + new ArrayList<>(); // If the module is not a newly generated module, explicitly load generated sources if (!ProjectConstants.GENERATED_MODULES_ROOT.equals(Optional.of( @@ -260,7 +258,7 @@ public static List loadResources(Path packagePath) { try (Stream pathStream = Files.walk(resourcesPath, 10)) { return pathStream .filter(Files::isRegularFile) - .collect(Collectors.toList()); + .toList(); } catch (IOException e) { throw new ProjectException(e); } diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/configschema/TypeConverter.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/configschema/TypeConverter.java index ad128e640726..716597db309d 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/configschema/TypeConverter.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/configschema/TypeConverter.java @@ -90,7 +90,7 @@ JsonObject getType(BType type) { String typeVal = getSimpleType(type); typeNode.addProperty(TYPE, typeVal); } else { - if (TypeTags.INTERSECTION == type.tag && type instanceof BIntersectionType) { + if (TypeTags.INTERSECTION == type.tag && type instanceof BIntersectionType intersectionType) { BType effectiveType = Types.getImpliedType(type); if (TypeTags.isSimpleBasicType(effectiveType.tag)) { String typeVal = getSimpleType(effectiveType); @@ -111,31 +111,31 @@ JsonObject getType(BType type) { visitedTypeMap.put(effectiveType.toString(), new VisitedType()); } - if (TypeTags.ARRAY == effectiveType.tag && effectiveType instanceof BArrayType) { - generateArrayType(typeNode, (BArrayType) effectiveType); + if (TypeTags.ARRAY == effectiveType.tag && effectiveType instanceof BArrayType arrayType) { + generateArrayType(typeNode, arrayType); } - if (TypeTags.RECORD == effectiveType.tag && effectiveType instanceof BRecordType) { - typeNode = generateRecordType((BRecordType) effectiveType, (BIntersectionType) type); + if (TypeTags.RECORD == effectiveType.tag && effectiveType instanceof BRecordType recordType) { + typeNode = generateRecordType(recordType, intersectionType); } - if (TypeTags.MAP == effectiveType.tag && effectiveType instanceof BMapType) { - generateMapType(typeNode, (BMapType) effectiveType); + if (TypeTags.MAP == effectiveType.tag && effectiveType instanceof BMapType mapType) { + generateMapType(typeNode, mapType); } - if (TypeTags.UNION == effectiveType.tag && effectiveType instanceof BUnionType) { - generateUnionType(typeNode, (BUnionType) effectiveType); + if (TypeTags.UNION == effectiveType.tag && effectiveType instanceof BUnionType unionType) { + generateUnionType(typeNode, unionType); } - if (TypeTags.TABLE == effectiveType.tag && effectiveType instanceof BTableType) { - generateTableType(typeNode, (BTableType) effectiveType); + if (TypeTags.TABLE == effectiveType.tag && effectiveType instanceof BTableType tableType) { + generateTableType(typeNode, tableType); } completeVisitedTypeEntry(effectiveType.toString(), typeNode); - } else if (TypeTags.UNION == type.tag && type instanceof BUnionType) { + } else if (TypeTags.UNION == type.tag && type instanceof BUnionType unionType) { // Handles enums - generateUnionType(typeNode, (BUnionType) type); + generateUnionType(typeNode, unionType); } // When the type is a union of singletons - if (TypeTags.FINITE == type.tag && type instanceof BFiniteType) { + if (TypeTags.FINITE == type.tag && type instanceof BFiniteType finiteType) { JsonArray enumArray = new JsonArray(); // Singletons can be mapped to enum in JSON - getEnumArray(enumArray, (BFiniteType) type); + getEnumArray(enumArray, finiteType); typeNode.add("enum", enumArray); } } @@ -248,13 +248,13 @@ private void updateUnionMembers(LinkedHashSet members, JsonArray memberAr (TypeTags.INTERSECTION == member.tag && member instanceof BIntersectionType)) { JsonObject memberObj = getType(member); memberArray.add(memberObj); - } else if (TypeTags.FINITE == member.tag && member instanceof BFiniteType) { - getEnumArray(enumArray, (BFiniteType) member); - } else if (TypeTags.TYPEREFDESC == member.tag && member instanceof BTypeReferenceType) { + } else if (TypeTags.FINITE == member.tag && member instanceof BFiniteType finiteType) { + getEnumArray(enumArray, finiteType); + } else if (TypeTags.TYPEREFDESC == member.tag && member instanceof BTypeReferenceType typeReferenceType) { // When union member refers to another union type, update those union members as well - BType referredType = ((BTypeReferenceType) member).referredType; - if (TypeTags.UNION == referredType.tag && referredType instanceof BUnionType) { - LinkedHashSet subMembers = ((BUnionType) referredType).getMemberTypes(); + BType referredType = typeReferenceType.referredType; + if (TypeTags.UNION == referredType.tag && referredType instanceof BUnionType unionType) { + LinkedHashSet subMembers = unionType.getMemberTypes(); updateUnionMembers(subMembers, memberArray, enumArray); } } @@ -270,21 +270,21 @@ private void updateUnionMembers(LinkedHashSet members, JsonArray memberAr private static void getEnumArray(JsonArray enumArray, BFiniteType finiteType) { Object[] values = finiteType.getValueSpace().toArray(); for (Object finiteValue : values) { - if (finiteValue instanceof BLangNumericLiteral) { - BType bType = ((BLangNumericLiteral) finiteValue).getBType(); + if (finiteValue instanceof BLangNumericLiteral numericLiteral) { + BType bType = numericLiteral.getBType(); // In the BLangNumericLiteral the integer typed values are represented as numeric values // while the decimal values are represented as String - Object value = ((BLangNumericLiteral) finiteValue).getValue(); + Object value = numericLiteral.getValue(); if (TypeTags.isIntegerTypeTag(bType.tag)) { // Any integer can be considered as a long and added as a numeric value to the enum array - if (value instanceof Long) { - enumArray.add((Long) value); + if (value instanceof Long l) { + enumArray.add(l); } } else { enumArray.add(Double.parseDouble(value.toString())); } - } else if (finiteValue instanceof BLangLiteral) { - enumArray.add(((BLangLiteral) finiteValue).getValue().toString()); + } else if (finiteValue instanceof BLangLiteral bLangLiteral) { + enumArray.add(bLangLiteral.getValue().toString()); } } } @@ -301,17 +301,12 @@ private static String getSimpleType(BType type) { } else if (TypeTags.isStringTypeTag(type.tag)) { return "string"; } else { - switch (type.tag) { - case FLOAT: - case DECIMAL: - return "number"; - case BOOLEAN: - return "boolean"; - case BYTE: - return "integer"; - default: - return ""; - } + return switch (type.tag) { + case FLOAT, DECIMAL -> "number"; + case BOOLEAN -> "boolean"; + case BYTE -> "integer"; + default -> ""; + }; } } diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/environment/DefaultPackageResolver.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/environment/DefaultPackageResolver.java index 2087202311b1..42256bc7fc74 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/environment/DefaultPackageResolver.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/environment/DefaultPackageResolver.java @@ -165,7 +165,7 @@ public Collection resolvePackageMetadata(Collection centralLoadRequests = requests.stream() .filter(r -> !r.packageDescriptor().isBuiltInPackage()) - .collect(Collectors.toList()); + .toList(); Collection latestVersionsInCentral = centralRepo.getPackageMetadata(centralLoadRequests, options); @@ -207,7 +207,7 @@ public Collection resolvePackages(Collection resolvePackage(request, options)) - .collect(Collectors.toList()); + .toList(); } private ResolutionResponse resolvePackage(ResolutionRequest resolutionReq, ResolutionOptions options) { diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/model/BalToolDescriptor.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/model/BalToolDescriptor.java index b31bf54151d9..0fcdfa938ddf 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/model/BalToolDescriptor.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/model/BalToolDescriptor.java @@ -36,7 +36,6 @@ import java.util.Collections; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; import java.util.stream.Stream; /** @@ -201,7 +200,7 @@ private static List getDependenciesInDir(String pa return getToolJarsMatchingPattern(pattern, parentPath.get()).stream() .map(path1 -> new BalToolDescriptor.Dependency(path1.toString())) - .collect(Collectors.toList()); + .toList(); } private static List getToolJarsMatchingPattern(String pattern, Path parentPath) { diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/plugins/CompilerPlugins.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/plugins/CompilerPlugins.java index df4d15075e91..9c79bfcb0685 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/plugins/CompilerPlugins.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/plugins/CompilerPlugins.java @@ -41,7 +41,8 @@ * * @since 2.0.0 */ -public class CompilerPlugins { +public final class CompilerPlugins { + static List builtInPlugins = new ArrayList<>(); private CompilerPlugins() { diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/repositories/AbstractPackageRepository.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/repositories/AbstractPackageRepository.java index 45a6152f356b..f9c59655922a 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/repositories/AbstractPackageRepository.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/repositories/AbstractPackageRepository.java @@ -35,7 +35,6 @@ import java.util.ArrayList; import java.util.Collection; -import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; @@ -149,15 +148,16 @@ private ImportModuleResponse getImportModuleLoadResponse(ImportModuleRequest imp private ImportModuleResponse getImportModuleResponse(ImportModuleRequest importModuleRequest, PackageName packageName, List packageVersions) { - Comparator comparator = (v1, v2) -> { - + packageVersions.sort((v1, v2) -> { + if (v1.equals(v2)) { + return 0; + } PackageVersion latest = getLatest(v1, v2); if (v1 == latest) { return -1; } return 1; - }; - packageVersions.sort(comparator); + }); for (PackageVersion packageVersion : packageVersions) { Collection moduleDescriptors = getModules( diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/repositories/RemotePackageRepository.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/repositories/RemotePackageRepository.java index ed0f2a48fd24..0e5a05f6fb48 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/repositories/RemotePackageRepository.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/repositories/RemotePackageRepository.java @@ -416,18 +416,11 @@ private static DependencyGraph createPackageDependencyGraph( private PackageResolutionRequest toPackageResolutionRequest(Collection resolutionRequests) { PackageResolutionRequest packageResolutionRequest = new PackageResolutionRequest(); for (ResolutionRequest resolutionRequest : resolutionRequests) { - PackageResolutionRequest.Mode mode = PackageResolutionRequest.Mode.HARD; - switch (resolutionRequest.packageLockingMode()) { - case HARD: - mode = PackageResolutionRequest.Mode.HARD; - break; - case MEDIUM: - mode = PackageResolutionRequest.Mode.MEDIUM; - break; - case SOFT: - mode = PackageResolutionRequest.Mode.SOFT; - break; - } + PackageResolutionRequest.Mode mode = switch (resolutionRequest.packageLockingMode()) { + case HARD -> PackageResolutionRequest.Mode.HARD; + case MEDIUM -> PackageResolutionRequest.Mode.MEDIUM; + case SOFT -> PackageResolutionRequest.Mode.SOFT; + }; String version = resolutionRequest.version().map(v -> v.value().toString()).orElse(""); packageResolutionRequest.addPackage(resolutionRequest.orgName().value(), resolutionRequest.packageName().value(), diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/plugins/CompilerPluginContext.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/plugins/CompilerPluginContext.java index 2ecce201b29d..326628f29887 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/plugins/CompilerPluginContext.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/plugins/CompilerPluginContext.java @@ -17,6 +17,7 @@ */ package io.ballerina.projects.plugins; +import io.ballerina.compiler.syntax.tree.Node; import io.ballerina.projects.plugins.codeaction.CodeAction; import io.ballerina.projects.plugins.completion.CompletionProvider; @@ -69,7 +70,7 @@ public interface CompilerPluginContext { * * @param completionProvider the {@link CompletionProvider} instance */ - void addCompletionProvider(CompletionProvider completionProvider); + void addCompletionProvider(CompletionProvider completionProvider); /** * Returns user data for the compiler plugin. diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/plugins/codeaction/PositionedActionContext.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/plugins/codeaction/PositionedActionContext.java index 075b1f105ba2..5bb7365eb073 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/plugins/codeaction/PositionedActionContext.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/plugins/codeaction/PositionedActionContext.java @@ -39,7 +39,7 @@ public interface PositionedActionContext { /** * Get the file path. * - * @return {@link java.nio.file.Path} file path + * @return {@link Path} file path */ Path filePath(); diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/plugins/completion/CompletionUtil.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/plugins/completion/CompletionUtil.java index fd7cacb6c8a4..88f08a1b51b6 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/plugins/completion/CompletionUtil.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/plugins/completion/CompletionUtil.java @@ -20,11 +20,14 @@ * * @since 2201.7.0 */ -public class CompletionUtil { +public final class CompletionUtil { public static final String LINE_BREAK = System.lineSeparator(); public static final String PADDING = "\t"; + private CompletionUtil() { + } + public static String getPlaceHolderText(int index, String defaultValue) { return "${" + index + ":" + defaultValue + "}"; } diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/util/BuildToolUtils.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/util/BuildToolUtils.java index ec9e87dee624..0d68e70e11e6 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/util/BuildToolUtils.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/util/BuildToolUtils.java @@ -56,7 +56,8 @@ * * @since 2201.9.0 */ -public class BuildToolUtils { +public final class BuildToolUtils { + private BuildToolUtils() {} /** diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/util/DependencyUtils.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/util/DependencyUtils.java index 41a637b7a96d..5bd9e06496fe 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/util/DependencyUtils.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/util/DependencyUtils.java @@ -25,7 +25,7 @@ * * @since 2.0.0 */ -public class DependencyUtils { +public final class DependencyUtils { private DependencyUtils() { diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/util/FileUtils.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/util/FileUtils.java index 0e3208a5326b..7aeba0b3936b 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/util/FileUtils.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/util/FileUtils.java @@ -59,11 +59,14 @@ * * @since 2.0.0 */ -public class FileUtils { +public final class FileUtils { private static final String PNG_HEX_HEADER = "89504E470D0A1A0A"; private static final PathMatcher FILE_MATCHER = FileSystems.getDefault().getPathMatcher("glob:**/Ballerina.toml"); + private FileUtils() { + } + /** * Get the name of the without the extension. * @@ -169,8 +172,10 @@ public static void deletePath(Path path) throws IOException { } if (Files.isDirectory(path)) { - for (Path dir : Files.list(path).toList()) { - deletePath(dir); + try (Stream paths = Files.list(path)) { + for (Path dir : paths.toList()) { + deletePath(dir); + } } } @@ -309,7 +314,8 @@ public static void replaceTemplateName(Path path, String templateName, String pa Files.write(path, content.getBytes(StandardCharsets.UTF_8)); } } catch (IOException e) { - throw new RuntimeException("Error while replacing template name in module import statements: " + path, e); + throw new RuntimeException( + "Error while replacing template name in module import statements: " + path, e); } } } diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/util/ProjectConstants.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/util/ProjectConstants.java index a27d5e3f88d2..ec059e250ae7 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/util/ProjectConstants.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/util/ProjectConstants.java @@ -21,7 +21,7 @@ * * @since 2.0.0 */ -public class ProjectConstants { +public final class ProjectConstants { private ProjectConstants() {} diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/util/ProjectPaths.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/util/ProjectPaths.java index 885c3c33939e..f61afc07fbdc 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/util/ProjectPaths.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/util/ProjectPaths.java @@ -33,7 +33,10 @@ * * @since 2.0.0 */ -public class ProjectPaths { +public final class ProjectPaths { + + private ProjectPaths() { + } /** * Finds the root directory of a Ballerina package using the filepath provided. @@ -238,15 +241,13 @@ public static boolean isBalFile(Path filepath) { */ private static boolean isBallerinaRelatedToml(Path filepath) { String fileName = Optional.of(filepath.getFileName()).get().toString(); - switch (fileName) { - case ProjectConstants.BALLERINA_TOML: - case ProjectConstants.CLOUD_TOML: - case ProjectConstants.CONFIGURATION_TOML: - case ProjectConstants.DEPENDENCIES_TOML: - return true; - default: - return false; - } + return switch (fileName) { + case ProjectConstants.BALLERINA_TOML, + ProjectConstants.CLOUD_TOML, + ProjectConstants.CONFIGURATION_TOML, + ProjectConstants.DEPENDENCIES_TOML -> true; + default -> false; + }; } /** diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/util/ProjectUtils.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/util/ProjectUtils.java index b135f8b27a76..5a852a292f00 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/util/ProjectUtils.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/util/ProjectUtils.java @@ -93,7 +93,6 @@ import java.util.jar.Manifest; import java.util.regex.Matcher; import java.util.regex.Pattern; -import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; @@ -128,7 +127,8 @@ * * @since 2.0.0 */ -public class ProjectUtils { +public final class ProjectUtils { + private static final String USER_HOME = "user.home"; private static final Pattern separatedIdentifierPattern = Pattern.compile("^[a-zA-Z0-9_.]*$"); private static final Pattern onlyDotsPattern = Pattern.compile("^[.]+$"); @@ -137,6 +137,9 @@ public class ProjectUtils { private static final Pattern separatedIdentifierWithHyphenPattern = Pattern.compile("^[a-zA-Z0-9_.-]*$"); private static String projectLoadingDiagnostic; + private ProjectUtils() { + } + /** * Validates the org-name. * @@ -1247,7 +1250,7 @@ private static boolean isCorrectPatternPathMatch(Path absolutePath, Path package private static List filterPathStream(Stream pathStream, String combinedPattern) { return pathStream.filter( FileSystems.getDefault().getPathMatcher("glob:" + combinedPattern)::matches) - .collect(Collectors.toList()); + .toList(); } private static String getGlobFormatPattern(String pattern) { diff --git a/compiler/ballerina-lang/src/main/java/org/ballerinalang/codegen/BallerinaAnnotationProcessor.java b/compiler/ballerina-lang/src/main/java/org/ballerinalang/codegen/BallerinaAnnotationProcessor.java index 366860a335e7..dd0805b8ddcb 100644 --- a/compiler/ballerina-lang/src/main/java/org/ballerinalang/codegen/BallerinaAnnotationProcessor.java +++ b/compiler/ballerina-lang/src/main/java/org/ballerinalang/codegen/BallerinaAnnotationProcessor.java @@ -206,19 +206,11 @@ private void processJavaSPIServices(RoundEnvironment roundEnv) { private void createServiceFile(String interfaceName, List implClasses) { Filer filer = this.processingEnv.getFiler(); - Writer writer = null; - try { - writer = filer.createResource(StandardLocation.CLASS_OUTPUT, "", JAVA_SPI_SERVICES_BASE_PATH + - interfaceName).openWriter(); + try (Writer writer = filer.createResource(StandardLocation.CLASS_OUTPUT, "", JAVA_SPI_SERVICES_BASE_PATH + + interfaceName).openWriter()) { writer.write(String.join("\n", implClasses)); } catch (IOException e) { throw new RuntimeException("Error creating Java SPI services file: " + e.getMessage(), e); - } finally { - if (writer != null) { - try { - writer.close(); - } catch (IOException ignore) { } - } } } @@ -262,7 +254,7 @@ private interface NativeElementCodeDef { /** * @since 0.94 */ - private class NativeFunctionCodeDef implements NativeElementCodeDef { + private static class NativeFunctionCodeDef implements NativeElementCodeDef { public String org; @@ -298,7 +290,7 @@ public String code() { /** * @since 0.94 */ - private class NativeActionCodeDef extends NativeFunctionCodeDef { + private static class NativeActionCodeDef extends NativeFunctionCodeDef { public String connectorName; diff --git a/compiler/ballerina-lang/src/main/java/org/ballerinalang/compiler/CompilerPhase.java b/compiler/ballerina-lang/src/main/java/org/ballerinalang/compiler/CompilerPhase.java index 8d4897fd871d..7e850e50a6ae 100644 --- a/compiler/ballerina-lang/src/main/java/org/ballerinalang/compiler/CompilerPhase.java +++ b/compiler/ballerina-lang/src/main/java/org/ballerinalang/compiler/CompilerPhase.java @@ -57,30 +57,19 @@ public enum CompilerPhase { } public static CompilerPhase fromValue(String value) { - switch (value) { - case "define": - return DEFINE; - case "typeCheck": - return TYPE_CHECK; - case "codeAnalyze": - return CODE_ANALYZE; - case "documentationAnalyze": - return DOCUMENTATION_ANALYZE; - case "constantPropagation": - return CONSTANT_PROPAGATION; - case "compilerPlugin": - return COMPILER_PLUGIN; - case "desugar": - return DESUGAR; - case "codeGen": - return CODE_GEN; - case "birGen": - return BIR_GEN; - case "birEmit": - return BIR_EMIT; - default: - throw new IllegalArgumentException("invalid compiler phase: " + value); - } + return switch (value) { + case "define" -> DEFINE; + case "typeCheck" -> TYPE_CHECK; + case "codeAnalyze" -> CODE_ANALYZE; + case "documentationAnalyze" -> DOCUMENTATION_ANALYZE; + case "constantPropagation" -> CONSTANT_PROPAGATION; + case "compilerPlugin" -> COMPILER_PLUGIN; + case "desugar" -> DESUGAR; + case "codeGen" -> CODE_GEN; + case "birGen" -> BIR_GEN; + case "birEmit" -> BIR_EMIT; + default -> throw new IllegalArgumentException("invalid compiler phase: " + value); + }; } @Override diff --git a/compiler/ballerina-lang/src/main/java/org/ballerinalang/model/TreeBuilder.java b/compiler/ballerina-lang/src/main/java/org/ballerinalang/model/TreeBuilder.java index 68b530b7b2ac..c5a6b5ee7cd9 100644 --- a/compiler/ballerina-lang/src/main/java/org/ballerinalang/model/TreeBuilder.java +++ b/compiler/ballerina-lang/src/main/java/org/ballerinalang/model/TreeBuilder.java @@ -386,7 +386,10 @@ * * @since 0.94 */ -public class TreeBuilder { +public final class TreeBuilder { + + private TreeBuilder() { + } public static CompilationUnitNode createCompilationUnit() { return new BLangCompilationUnit(); diff --git a/compiler/ballerina-lang/src/main/java/org/ballerinalang/model/TreeUtils.java b/compiler/ballerina-lang/src/main/java/org/ballerinalang/model/TreeUtils.java index c02bf05e5a19..52e1781686c0 100644 --- a/compiler/ballerina-lang/src/main/java/org/ballerinalang/model/TreeUtils.java +++ b/compiler/ballerina-lang/src/main/java/org/ballerinalang/model/TreeUtils.java @@ -25,8 +25,8 @@ /** * This contains model tree related utility functions. */ -public class TreeUtils { - +public final class TreeUtils { + private static Map stringTypeKindMap = new HashMap<>(); static { @@ -55,6 +55,9 @@ public class TreeUtils { stringTypeKindMap.put("readonly", TypeKind.READONLY); } + private TreeUtils() { + } + public static TypeKind stringToTypeKind(String typeName) { return stringTypeKindMap.get(typeName); } diff --git a/compiler/ballerina-lang/src/main/java/org/ballerinalang/model/elements/PackageID.java b/compiler/ballerina-lang/src/main/java/org/ballerinalang/model/elements/PackageID.java index f33bc65873cc..3c2f49be0890 100644 --- a/compiler/ballerina-lang/src/main/java/org/ballerinalang/model/elements/PackageID.java +++ b/compiler/ballerina-lang/src/main/java/org/ballerinalang/model/elements/PackageID.java @@ -166,7 +166,7 @@ private List createNameComps(Name name) { if (name == Names.DEFAULT_PACKAGE) { return Lists.of(Names.DEFAULT_PACKAGE); } - return Arrays.stream(name.value.split("\\.")).map(Name::new).collect(Collectors.toList()); + return Arrays.stream(name.value.split("\\.")).map(Name::new).toList(); } /** diff --git a/compiler/ballerina-lang/src/main/java/org/ballerinalang/model/symbols/SymbolOrigin.java b/compiler/ballerina-lang/src/main/java/org/ballerinalang/model/symbols/SymbolOrigin.java index 838e288f0c4a..22123b431ac7 100644 --- a/compiler/ballerina-lang/src/main/java/org/ballerinalang/model/symbols/SymbolOrigin.java +++ b/compiler/ballerina-lang/src/main/java/org/ballerinalang/model/symbols/SymbolOrigin.java @@ -110,17 +110,12 @@ public byte value() { * @return The corresponding enum value if there's a corresponding value. If not, an exception is thrown. */ public static SymbolOrigin toOrigin(byte value) { - switch (value) { - case 1: - return BUILTIN; - case 2: - return SOURCE; - case 3: - return COMPILED_SOURCE; - case 4: - return VIRTUAL; - default: - throw new IllegalStateException("Invalid symbol origin value: " + value); - } + return switch (value) { + case 1 -> BUILTIN; + case 2 -> SOURCE; + case 3 -> COMPILED_SOURCE; + case 4 -> VIRTUAL; + default -> throw new IllegalStateException("Invalid symbol origin value: " + value); + }; } } diff --git a/compiler/ballerina-lang/src/main/java/org/ballerinalang/model/tree/expressions/XMLNavigationAccess.java b/compiler/ballerina-lang/src/main/java/org/ballerinalang/model/tree/expressions/XMLNavigationAccess.java index 9e1ac67d5b15..789cb8e58bdd 100644 --- a/compiler/ballerina-lang/src/main/java/org/ballerinalang/model/tree/expressions/XMLNavigationAccess.java +++ b/compiler/ballerina-lang/src/main/java/org/ballerinalang/model/tree/expressions/XMLNavigationAccess.java @@ -50,16 +50,12 @@ enum NavAccessType { } public static NavAccessType fromInt(int number) { - switch (number) { - case 0: - return CHILD_ELEMS; - case 1: - return CHILDREN; - case 2: - return DESCENDANTS; - default: - throw new IllegalArgumentException(); - } + return switch (number) { + case 0 -> CHILD_ELEMS; + case 1 -> CHILDREN; + case 2 -> DESCENDANTS; + default -> throw new IllegalArgumentException(); + }; } } diff --git a/compiler/ballerina-lang/src/main/java/org/ballerinalang/repository/PackageSource.java b/compiler/ballerina-lang/src/main/java/org/ballerinalang/repository/PackageSource.java index 7438bfdaf9df..44a613423b53 100644 --- a/compiler/ballerina-lang/src/main/java/org/ballerinalang/repository/PackageSource.java +++ b/compiler/ballerina-lang/src/main/java/org/ballerinalang/repository/PackageSource.java @@ -49,6 +49,6 @@ public interface PackageSource extends PackageEntity { * * @return the package source entries iterator */ - List getPackageSourceEntries(); + List getPackageSourceEntries(); } diff --git a/compiler/ballerina-lang/src/main/java/org/ballerinalang/repository/fs/ClasspathPackageRepository.java b/compiler/ballerina-lang/src/main/java/org/ballerinalang/repository/fs/ClasspathPackageRepository.java index 4002fe988c8e..116735705c35 100644 --- a/compiler/ballerina-lang/src/main/java/org/ballerinalang/repository/fs/ClasspathPackageRepository.java +++ b/compiler/ballerina-lang/src/main/java/org/ballerinalang/repository/fs/ClasspathPackageRepository.java @@ -70,7 +70,8 @@ private static Path generatePath(Class providerClassRef, Strin throw new RuntimeException(e); } } - + + @SuppressWarnings("resource") private static void initFS(URI uri) throws IOException { if (JAR_URI_SCHEME.equals(uri.getScheme())) { Map env = new HashMap<>(); diff --git a/compiler/ballerina-lang/src/main/java/org/ballerinalang/repository/fs/GeneralFSPackageRepository.java b/compiler/ballerina-lang/src/main/java/org/ballerinalang/repository/fs/GeneralFSPackageRepository.java index ed06d85e6e16..a7ddf1f68c7f 100644 --- a/compiler/ballerina-lang/src/main/java/org/ballerinalang/repository/fs/GeneralFSPackageRepository.java +++ b/compiler/ballerina-lang/src/main/java/org/ballerinalang/repository/fs/GeneralFSPackageRepository.java @@ -39,7 +39,7 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Set; -import java.util.stream.Collectors; +import java.util.stream.Stream; /** * This represents a general file system based {@link PackageRepository}. @@ -136,7 +136,11 @@ public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) th return FileVisitResult.SKIP_SUBTREE; } List nameComps = new ArrayList<>(); - if (Files.list(dir).filter(f -> isBALFile(f)).count() > 0) { + boolean balFilesExist; + try (Stream paths = Files.list(dir)) { + balFilesExist = paths.filter(f -> isBALFile(f)).count() > 0; + } + if (balFilesExist) { int dirNameCount = dir.getNameCount(); if (dirNameCount > baseNameCount) { dir.subpath(baseNameCount, dirNameCount).forEach( @@ -233,8 +237,8 @@ public PackageID getPackageId() { @Override public List getEntryNames() { if (this.cachedEntryNames == null) { - try { - List files = Files.walk(this.pkgPath, 1).filter( + try (Stream paths = Files.walk(this.pkgPath, 1)) { + List files = paths.filter( Files::isRegularFile).filter(e -> e.getFileName().toString().endsWith(BAL_SOURCE_EXT)). toList(); this.cachedEntryNames = new ArrayList<>(files.size()); @@ -253,8 +257,8 @@ public CompilerInput getPackageSourceEntry(String name) { } @Override - public List getPackageSourceEntries() { - return this.getEntryNames().stream().map(e -> new FSCompilerInput(e)).collect(Collectors.toList()); + public List getPackageSourceEntries() { + return this.getEntryNames().stream().map(e -> new FSCompilerInput(e)).toList(); } /** @@ -315,7 +319,7 @@ public String getName() { * * @since 0.94 */ - public class FSPackageEntityNotAvailableException extends Exception { + public static class FSPackageEntityNotAvailableException extends Exception { private static final long serialVersionUID = 1528033476455781589L; diff --git a/compiler/ballerina-lang/src/main/java/org/ballerinalang/spi/SystemPackageRepositoryProvider.java b/compiler/ballerina-lang/src/main/java/org/ballerinalang/spi/SystemPackageRepositoryProvider.java index 4e22d9d300f8..b62fed8f6b4d 100644 --- a/compiler/ballerina-lang/src/main/java/org/ballerinalang/spi/SystemPackageRepositoryProvider.java +++ b/compiler/ballerina-lang/src/main/java/org/ballerinalang/spi/SystemPackageRepositoryProvider.java @@ -22,6 +22,7 @@ import java.net.URI; import java.net.URISyntaxException; +import java.nio.file.Path; /** * This represents the Java SPI interface for a Ballerina system package repository provider. @@ -43,6 +44,6 @@ static URI getClassUri(Object obj) { * * @return the loaded {@link PackageRepository} object */ - Repo loadRepository(); + Repo loadRepository(); } diff --git a/compiler/ballerina-lang/src/main/java/org/ballerinalang/toml/model/Dependency.java b/compiler/ballerina-lang/src/main/java/org/ballerinalang/toml/model/Dependency.java index 731cbd909c3c..80e7ae5b67ef 100644 --- a/compiler/ballerina-lang/src/main/java/org/ballerinalang/toml/model/Dependency.java +++ b/compiler/ballerina-lang/src/main/java/org/ballerinalang/toml/model/Dependency.java @@ -76,10 +76,9 @@ public boolean equals(Object o) { if (this == o) { return true; } - if (!(o instanceof Dependency)) { + if (!(o instanceof Dependency that)) { return false; } - Dependency that = (Dependency) o; return this.toString().equals(that.toString()); } diff --git a/compiler/ballerina-lang/src/main/java/org/ballerinalang/toml/model/LockFileImport.java b/compiler/ballerina-lang/src/main/java/org/ballerinalang/toml/model/LockFileImport.java index 816cc672727b..0193e5e3be49 100644 --- a/compiler/ballerina-lang/src/main/java/org/ballerinalang/toml/model/LockFileImport.java +++ b/compiler/ballerina-lang/src/main/java/org/ballerinalang/toml/model/LockFileImport.java @@ -70,10 +70,9 @@ public boolean equals(Object o) { if (this == o) { return true; } - if (!(o instanceof LockFileImport)) { + if (!(o instanceof LockFileImport that)) { return false; } - LockFileImport that = (LockFileImport) o; return Objects.equals(org_name, that.org_name) && Objects.equals(getName(), that.getName()) && Objects.equals(getVersion(), that.getVersion()); diff --git a/compiler/ballerina-lang/src/main/java/org/ballerinalang/toml/model/Manifest.java b/compiler/ballerina-lang/src/main/java/org/ballerinalang/toml/model/Manifest.java index 2d8f2b08fc7f..4e6174a690c7 100644 --- a/compiler/ballerina-lang/src/main/java/org/ballerinalang/toml/model/Manifest.java +++ b/compiler/ballerina-lang/src/main/java/org/ballerinalang/toml/model/Manifest.java @@ -59,15 +59,14 @@ public List getDependencies() { dependency.setMetadata(convertObjectToDependencyMetadata(entry.getValue())); return dependency; }) - .collect(Collectors.toList()); + .toList(); } private DependencyMetadata convertObjectToDependencyMetadata(Object obj) { DependencyMetadata metadata = new DependencyMetadata(); - if (obj instanceof String) { - metadata.setVersion((String) obj); - } else if (obj instanceof Map) { - Map metadataMap = (Map) obj; + if (obj instanceof String s) { + metadata.setVersion(s); + } else if (obj instanceof Map metadataMap) { if (metadataMap.keySet().contains("version") && metadataMap.get("version") instanceof String) { metadata.setVersion((String) metadataMap.get("version")); } diff --git a/compiler/ballerina-lang/src/main/java/org/ballerinalang/toml/parser/ManifestProcessor.java b/compiler/ballerina-lang/src/main/java/org/ballerinalang/toml/parser/ManifestProcessor.java index 60278d150a9b..a96513a560a2 100644 --- a/compiler/ballerina-lang/src/main/java/org/ballerinalang/toml/parser/ManifestProcessor.java +++ b/compiler/ballerina-lang/src/main/java/org/ballerinalang/toml/parser/ManifestProcessor.java @@ -228,11 +228,11 @@ public static byte[] addDependenciesToManifest(ByteArrayInputStream manifestStre if (toml.containsKey("dependencies")) { Object tomlDepsAsObject = toml.get("dependencies"); Map updatedDependencies = new HashMap<>(); - if (tomlDepsAsObject instanceof HashMap) { + if (tomlDepsAsObject instanceof HashMap tomlDeps) { // taking care of double quoted dependency names - Map tomlDeps = (HashMap) tomlDepsAsObject; - for (Map.Entry dep : tomlDeps.entrySet()) { - updatedDependencies.put(dep.getKey().replaceAll("^\"|\"$", ""), dep.getValue()); + for (Map.Entry dep : tomlDeps.entrySet()) { + updatedDependencies.put( + ((String) dep.getKey()).replaceAll("^\"|\"$", ""), dep.getValue()); } dependencies = updatedDependencies; } diff --git a/compiler/ballerina-lang/src/main/java/org/ballerinalang/toml/util/PathUtils.java b/compiler/ballerina-lang/src/main/java/org/ballerinalang/toml/util/PathUtils.java index 95e28f90c063..956e39a6026b 100644 --- a/compiler/ballerina-lang/src/main/java/org/ballerinalang/toml/util/PathUtils.java +++ b/compiler/ballerina-lang/src/main/java/org/ballerinalang/toml/util/PathUtils.java @@ -23,9 +23,13 @@ * This class can be used to handle different path possibilities in the toml for native-libs and dependencies. * */ -public class PathUtils { +public final class PathUtils { + private static final String OS = System.getProperty("os.name").toLowerCase(Locale.getDefault()); + private PathUtils() { + } + public static String getPath(String path) { if (path != null) { if (OS.contains("win")) { diff --git a/compiler/ballerina-lang/src/main/java/org/ballerinalang/util/BLangCompilerConstants.java b/compiler/ballerina-lang/src/main/java/org/ballerinalang/util/BLangCompilerConstants.java index 58f229cd9574..f9e4dba15afa 100644 --- a/compiler/ballerina-lang/src/main/java/org/ballerinalang/util/BLangCompilerConstants.java +++ b/compiler/ballerina-lang/src/main/java/org/ballerinalang/util/BLangCompilerConstants.java @@ -23,7 +23,7 @@ * * @since 1.1.0 */ -public class BLangCompilerConstants { +public final class BLangCompilerConstants { public static final String ITERABLE_COLLECTION_ITERATOR_FUNC = "iterator"; public static final String RETRY_MANAGER_OBJECT_SHOULD_RETRY_FUNC = "shouldRetry"; diff --git a/compiler/ballerina-lang/src/main/java/org/ballerinalang/util/BootstrapRunner.java b/compiler/ballerina-lang/src/main/java/org/ballerinalang/util/BootstrapRunner.java index 643612c04ff6..2c69a1cb79a4 100644 --- a/compiler/ballerina-lang/src/main/java/org/ballerinalang/util/BootstrapRunner.java +++ b/compiler/ballerina-lang/src/main/java/org/ballerinalang/util/BootstrapRunner.java @@ -40,7 +40,7 @@ /** * Creates jars in file system using bootstrap pack and create class loader hierarchy for them. */ -public class BootstrapRunner { +public final class BootstrapRunner { private static final PrintStream out = System.out; private static final PrintStream err = System.err; @@ -50,6 +50,9 @@ public class BootstrapRunner { private static final String COMPILER_BACKEND_LLVM = "ballerina.compiler_backend_llvm.$_init"; private static String javaCommand = System.getProperty("java.command"); + private BootstrapRunner() { + } + public static void loadTargetAndGenerateJarBinary(String entryBir, String jarOutputPath, boolean dumpBir, HashSet moduleDependencySet, String... birCachePaths) { //Load all Jars from module dependency set. diff --git a/compiler/ballerina-lang/src/main/java/org/ballerinalang/util/FunctionFlags.java b/compiler/ballerina-lang/src/main/java/org/ballerinalang/util/FunctionFlags.java index 10bbb5578c92..15421edcd4f0 100644 --- a/compiler/ballerina-lang/src/main/java/org/ballerinalang/util/FunctionFlags.java +++ b/compiler/ballerina-lang/src/main/java/org/ballerinalang/util/FunctionFlags.java @@ -20,12 +20,15 @@ /** * This represents the function related flags. The flags are set/get using bit masks. */ -public class FunctionFlags { +public final class FunctionFlags { public static final int NOTHING = 0; public static final int ASYNC = 1; public static final int OBSERVED = ASYNC << 1; + private FunctionFlags() { + } + public static boolean isAsync(int flags) { return (flags & FunctionFlags.ASYNC) == FunctionFlags.ASYNC; } diff --git a/compiler/ballerina-lang/src/main/java/org/ballerinalang/util/Transactions.java b/compiler/ballerina-lang/src/main/java/org/ballerinalang/util/Transactions.java index fd297022218c..18f1130cb859 100644 --- a/compiler/ballerina-lang/src/main/java/org/ballerinalang/util/Transactions.java +++ b/compiler/ballerina-lang/src/main/java/org/ballerinalang/util/Transactions.java @@ -24,11 +24,15 @@ * * @since 0.95.5 */ -public class Transactions { +public final class Transactions { + public static final String TRANSACTION_ANNOTATION_NAME = "transactions" + ORG_NAME_SEPARATOR + "Participant"; public static final String TRX_ONCOMMIT_FUNC = "oncommit"; public static final String TRX_ONABORT_FUNC = "onabort"; + private Transactions() { + } + public static boolean isTransactionsAnnotation(String orgName, String pkgName) { StringBuilder pathBuilder = new StringBuilder(); String createdPath = pathBuilder.append(orgName).append(ORG_NAME_SEPARATOR).append(pkgName).toString(); @@ -74,18 +78,13 @@ public int value() { } public static TransactionStatus getConst(int statusValue) { - switch (statusValue) { - case 0: - return BLOCK_END; - case 1: - return END; - case -1: - return FAILED; - case -2: - return ABORTED; - default: - throw new IllegalArgumentException(); - } + return switch (statusValue) { + case 0 -> BLOCK_END; + case 1 -> END; + case -1 -> FAILED; + case -2 -> ABORTED; + default -> throw new IllegalArgumentException(); + }; } } } diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/BIRPackageSymbolEnter.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/BIRPackageSymbolEnter.java index eefda2a6da58..ba939e2b7441 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/BIRPackageSymbolEnter.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/BIRPackageSymbolEnter.java @@ -397,7 +397,7 @@ private void defineFunction(DataInputStream dataInStream) throws IOException { String funcName = getStringCPEntryValue(dataInStream); String funcOrigName = getStringCPEntryValue(dataInStream); String workerName = getStringCPEntryValue(dataInStream); - var flags = dataInStream.readLong(); + long flags = dataInStream.readLong(); byte origin = dataInStream.readByte(); BInvokableType funcType = (BInvokableType) readBType(dataInStream); @@ -533,7 +533,7 @@ private void defineTypeDef(DataInputStream dataInStream) throws IOException { String typeDefName = getStringCPEntryValue(dataInStream); String typeDefOrigName = getStringCPEntryValue(dataInStream); - var flags = dataInStream.readLong(); + long flags = dataInStream.readLong(); byte origin = dataInStream.readByte(); byte[] docBytes = readDocBytes(dataInStream); @@ -693,7 +693,7 @@ private BAnnotationSymbol defineAnnotation(DataInputStream dataInStream) throws String name = getStringCPEntryValue(dataInStream); String originalName = getStringCPEntryValue(dataInStream); - var flags = dataInStream.readLong(); + long flags = dataInStream.readLong(); byte origin = dataInStream.readByte(); Location pos = readPosition(dataInStream); @@ -751,7 +751,7 @@ private BAnnotationAttachmentSymbol defineAnnotationAttachmentSymbol(DataInputSt private void defineConstant(DataInputStream dataInStream) throws IOException { String constantName = getStringCPEntryValue(dataInStream); - var flags = dataInStream.readLong(); + long flags = dataInStream.readLong(); byte origin = dataInStream.readByte(); Location pos = readPosition(dataInStream); @@ -869,7 +869,7 @@ private void definePackageLevelVariables(DataInputStream dataInStream) throws IO Location pos = readPosition(dataInStream); dataInStream.readByte(); // Read and ignore the kind as it is anyway global variable String varName = getStringCPEntryValue(dataInStream); - var flags = dataInStream.readLong(); + long flags = dataInStream.readLong(); byte origin = dataInStream.readByte(); byte[] docBytes = readDocBytes(dataInStream); @@ -916,7 +916,7 @@ private void setParamSymbols(BInvokableSymbol invokableSymbol, DataInputStream d BInvokableType invokableType = (BInvokableType) invokableSymbol.type; for (int i = 0; i < requiredParamCount; i++) { String paramName = getStringCPEntryValue(dataInStream); - var flags = dataInStream.readLong(); + long flags = dataInStream.readLong(); BVarSymbol varSymbol = new BVarSymbol(flags, Names.fromString(paramName), this.env.pkgSymbol.pkgID, invokableType.paramTypes.get(i), invokableSymbol, symTable.builtinPos, COMPILED_SOURCE); @@ -1154,7 +1154,7 @@ private BInvokableType setTSymbolForInvokableType(BInvokableType bInvokableType, int params = inputStream.readInt(); for (int i = 0; i < params; i++) { String paramName = getStringCPEntryValue(inputStream); - var paramFlags = inputStream.readLong(); + long paramFlags = inputStream.readLong(); byte[] docBytes = readDocBytes(inputStream); BType fieldType = readTypeFromCp(); @@ -1170,7 +1170,7 @@ private BInvokableType setTSymbolForInvokableType(BInvokableType bInvokableType, boolean hasRestParam = inputStream.readBoolean(); if (hasRestParam) { String fieldName = getStringCPEntryValue(inputStream); - var fieldFlags = inputStream.readLong(); + long fieldFlags = inputStream.readLong(); byte[] docBytes = readDocBytes(inputStream); BType fieldType = readTypeFromCp(); @@ -1193,7 +1193,7 @@ private BInvokableType setTSymbolForInvokableType(BInvokableType bInvokableType, private BInvokableSymbol getSymbolOfClosure() throws IOException { String name = getStringCPEntryValue(inputStream); - var flags = inputStream.readLong(); + long flags = inputStream.readLong(); BType type = readTypeFromCp(); int pkgCpIndex = inputStream.readInt(); PackageID pkgId = getPackageId(pkgCpIndex); @@ -1206,7 +1206,7 @@ private BInvokableSymbol getSymbolOfClosure() throws IOException { int parameters = inputStream.readInt(); for (int i = 0; i < parameters; i++) { String fieldName = getStringCPEntryValue(inputStream); - var fieldFlags = inputStream.readLong(); + long fieldFlags = inputStream.readLong(); byte[] docBytes = readDocBytes(inputStream); BType fieldType = readTypeFromCp(); BVarSymbol varSymbol = new BVarSymbol(fieldFlags, Names.fromString(fieldName), pkgId, fieldType, null, @@ -1220,7 +1220,7 @@ private BInvokableSymbol getSymbolOfClosure() throws IOException { public BType readType(int cpI) throws IOException { byte tag = inputStream.readByte(); Name name = Names.fromString(getStringCPEntryValue(inputStream)); - var flags = inputStream.readLong(); + long flags = inputStream.readLong(); // Read the type flags to identify if type reference types are nullable. int typeFlags = inputStream.readInt(); @@ -1284,7 +1284,7 @@ public BType readType(int cpI) throws IOException { int recordFields = inputStream.readInt(); for (int i = 0; i < recordFields; i++) { String fieldName = getStringCPEntryValue(inputStream); - var fieldFlags = inputStream.readLong(); + long fieldFlags = inputStream.readLong(); byte[] docBytes = readDocBytes(inputStream); @@ -1474,7 +1474,7 @@ public BType readType(int cpI) throws IOException { } unionType.setOriginalMemberTypes(originalMemberTypes); - var poppedUnionType = compositeStack.pop(); + Object poppedUnionType = compositeStack.pop(); assert poppedUnionType == unionType; boolean isEnum = inputStream.readBoolean(); @@ -1600,7 +1600,7 @@ public BType readType(int cpI) throws IOException { return bFutureType; case TypeTags.FINITE: String finiteTypeName = getStringCPEntryValue(inputStream); - var finiteTypeFlags = inputStream.readLong(); + long finiteTypeFlags = inputStream.readLong(); BTypeSymbol symbol = Symbols.createTypeSymbol(SymTag.FINITE_TYPE, finiteTypeFlags, Names.fromString(finiteTypeName), env.pkgSymbol.pkgID, null, env.pkgSymbol, symTable.builtinPos, @@ -1643,8 +1643,8 @@ public BType readType(int cpI) throws IOException { int fieldCount = inputStream.readInt(); for (int i = 0; i < fieldCount; i++) { String fieldName = getStringCPEntryValue(inputStream); - var fieldFlags = inputStream.readLong(); - var defaultable = inputStream.readBoolean(); + long fieldFlags = inputStream.readLong(); + boolean defaultable = inputStream.readBoolean(); byte[] docBytes = readDocBytes(inputStream); BType fieldType = readTypeFromCp(); @@ -1803,7 +1803,7 @@ private void populateIntersectionTypeReferencedFunctions(DataInputStream inputSt BObjectTypeSymbol objectSymbol) throws IOException { String attachedFuncName = getStringCPEntryValue(inputStream); String attachedFuncOrigName = getStringCPEntryValue(inputStream); - var attachedFuncFlags = inputStream.readLong(); + long attachedFuncFlags = inputStream.readLong(); BInvokableType attachedFuncType = (BInvokableType) readTypeFromCp(); Name funcName = Names.fromString(Symbols.getAttachedFuncSymbolName( objectSymbol.name.value, attachedFuncName)); diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/FileSystemProgramDirectory.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/FileSystemProgramDirectory.java index 629a625e42d2..90bddfaa827a 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/FileSystemProgramDirectory.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/FileSystemProgramDirectory.java @@ -44,7 +44,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.stream.Collectors; import java.util.stream.Stream; import static org.wso2.ballerinalang.util.LambdaExceptionUtils.rethrow; @@ -83,7 +82,7 @@ public List getSourceFileNames() { fileNames = stream.map(ProjectDirs::getLastComp) .filter(ProjectDirs::isSourceFile) .map(Path::toString) - .collect(Collectors.toList()); + .toList(); } return fileNames; } catch (SecurityException | AccessDeniedException e) { @@ -174,15 +173,9 @@ public Converter getConverter() { } private String getTopLevelDirNameInPackage(CompilerOutputEntry.Kind kind, FileSystem fs) { - switch (kind) { - case SRC: - case BIR: - case OBJ: - return kind.getValue(); - case ROOT: - return fs.getSeparator(); - - } - return null; + return switch (kind) { + case SRC, BIR, OBJ -> kind.getValue(); + case ROOT -> fs.getSeparator(); + }; } } diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/FileSystemProjectDirectory.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/FileSystemProjectDirectory.java index a22d0cb9b704..23509921e643 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/FileSystemProjectDirectory.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/FileSystemProjectDirectory.java @@ -42,7 +42,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.stream.Collectors; import java.util.stream.Stream; import static org.ballerinalang.repository.CompilerOutputEntry.Kind; @@ -94,7 +93,7 @@ public List getSourcePackageNames() { .filter(ProjectDirs::containsSourceFiles) .map(ProjectDirs::getLastComp) .map(Path::toString) - .collect(Collectors.toList()); + .toList(); } } catch (SecurityException | AccessDeniedException e) { throw new BLangCompilerException("permission denied: " + projectDirPath.toString()); @@ -208,15 +207,9 @@ private void addCompilerOutputEntry(FileSystem fs, CompilerOutputEntry outputEnt } private String getTopLevelDirNameInPackage(Kind kind, FileSystem fs) { - switch (kind) { - case SRC: - case BIR: - case OBJ: - return kind.getValue(); - case ROOT: - return fs.getSeparator(); - - } - return null; + return switch (kind) { + case SRC, BIR, OBJ -> kind.getValue(); + case ROOT -> fs.getSeparator(); + }; } } diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/BIRGenEnv.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/BIRGenEnv.java index 655cbb12ca82..9cf1bb8eafa0 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/BIRGenEnv.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/BIRGenEnv.java @@ -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. @@ -59,7 +60,7 @@ class BIRGenEnv { BIRBasicBlock enclOnFailEndBB; BIRBasicBlock enclInnerOnFailEndBB; - Stack> trapBlocks = new Stack<>(); + Deque> trapBlocks = new ArrayDeque<>(); Map> varDclsByBlock = new HashMap<>(); @@ -67,7 +68,7 @@ class BIRGenEnv { // 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 unlockVars = new Stack<>(); + Deque 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. diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/BIRGenUtils.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/BIRGenUtils.java index d033016cba9c..e4c4554216ba 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/BIRGenUtils.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/BIRGenUtils.java @@ -28,7 +28,7 @@ * * @since 2201.6.0 */ -public class BIRGenUtils { +public final class BIRGenUtils { private BIRGenUtils () { diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/JvmCodeGenUtil.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/JvmCodeGenUtil.java index 2b3344d2627d..9d98ea87c7f0 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/JvmCodeGenUtil.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/JvmCodeGenUtil.java @@ -153,7 +153,8 @@ /** * The common functions used in CodeGen. */ -public class JvmCodeGenUtil { +public final class JvmCodeGenUtil { + public static final Unifier UNIFIER = new Unifier(); private static final Pattern JVM_RESERVED_CHAR_SET = Pattern.compile("[.:/<>]"); public static final String SCOPE_PREFIX = "_SCOPE_"; @@ -200,10 +201,16 @@ public static String cleanupPathSeparators(String name) { public static String rewriteVirtualCallTypeName(String value, BType objectType) { objectType = getImpliedType(objectType); - // The call name will be in the format of`objectTypeName.funcName` for attached functions of imported modules. - // Therefore, We need to remove the type name. - if (!objectType.tsymbol.name.value.isEmpty() && value.startsWith(objectType.tsymbol.name.value)) { - value = value.replace(objectType.tsymbol.name.value + ".", "").trim(); + String typeName = objectType.tsymbol.name.value; + Name originalName = objectType.tsymbol.originalName; + if (value.startsWith(typeName)) { + // The call name will be in the format of`objectTypeName.funcName` for attached functions of imported + // modules. Therefore, We need to remove the type name. + value = value.replace(typeName + ".", "").trim(); + } else if (originalName != null && value.startsWith(originalName.value)) { + // The call name will be in the format of`objectTypeOriginalName.funcName` for attached functions of + // object definitions. Therefore, We need to remove it. + value = value.replace(originalName + ".", "").trim(); } return Utils.encodeFunctionIdentifier(value); } @@ -559,10 +566,10 @@ public static void genYieldCheck(MethodVisitor mv, LabelGenerator labelGen, BIRN mv.visitJumpInsn(GOTO, gotoLabel); } - protected static void generateSetYieldedStatus(MethodVisitor mv, LabelGenerator labelGen, String funcName, - int yieldLocationVarIndex, Location terminatorPos, - String fullyQualifiedFuncName, String yieldStatus, - int yieldStatusVarIndex) { + static void generateSetYieldedStatus(MethodVisitor mv, LabelGenerator labelGen, String funcName, + int yieldLocationVarIndex, Location terminatorPos, + String fullyQualifiedFuncName, String yieldStatus, + int yieldStatusVarIndex) { Label yieldLocationLabel = new Label(); mv.visitJumpInsn(IFEQ, yieldLocationLabel); diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/JvmConstants.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/JvmConstants.java index a685a4eafa6d..f510a244f281 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/JvmConstants.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/JvmConstants.java @@ -29,7 +29,7 @@ * * @since 1.2.0 */ -public class JvmConstants { +public final class JvmConstants { // jvm values public API classes public static final String B_XML_QNAME = "io/ballerina/runtime/api/values/BXmlQName"; diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/JvmDesugarPhase.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/JvmDesugarPhase.java index b406cce3835e..7d00e3cf63ae 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/JvmDesugarPhase.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/JvmDesugarPhase.java @@ -56,7 +56,7 @@ * * @since 1.2.0 */ -public class JvmDesugarPhase { +public final class JvmDesugarPhase { private JvmDesugarPhase() { } diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/JvmSignatures.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/JvmSignatures.java index 905e422db221..69ece2dae70f 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/JvmSignatures.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/JvmSignatures.java @@ -133,7 +133,7 @@ * * @since 1.2.0 */ -public class JvmSignatures { +public final class JvmSignatures { public static final String INIT_ERROR_WITH_TYPE = "(L" + TYPE + ";L" + B_STRING_VALUE + ";L" + BERROR + ";L" + OBJECT + ";)V"; diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/JvmTerminatorGen.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/JvmTerminatorGen.java index 22ed371eb9b1..27938d6c9f82 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/JvmTerminatorGen.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/JvmTerminatorGen.java @@ -920,21 +920,21 @@ private void genAsyncCallTerm(BIRTerminator.AsyncCall callIns, int localVarOffse } Object strandAnnot = ((BIRNode.BIRConstAnnotationAttachment) annotationAttachment).annotValue.value; - if (strandAnnot instanceof Map) { - Map recordValue = (Map) strandAnnot; + if (strandAnnot instanceof Map recordValue) { if (recordValue.containsKey(STRAND_THREAD)) { - if (STRAND_VALUE_ANY.equals(recordValue.get(STRAND_THREAD).value)) { + if (STRAND_VALUE_ANY.equals(((BIRNode.ConstValue) recordValue.get(STRAND_THREAD)).value)) { concurrent = true; } } if (recordValue.containsKey(STRAND_NAME)) { - strandName = recordValue.get(STRAND_NAME).value.toString(); + strandName = ((BIRNode.ConstValue) recordValue.get(STRAND_NAME)).value.toString(); } if (recordValue.containsKey(STRAND_POLICY_NAME)) { - if (!DEFAULT_STRAND_DISPATCHER.equals(recordValue.get(STRAND_POLICY_NAME).value)) { + if (!DEFAULT_STRAND_DISPATCHER.equals( + ((BIRNode.ConstValue) recordValue.get(STRAND_POLICY_NAME)).value)) { throw new BLangCompilerException("Unsupported policy. Only 'DEFAULT' policy is " + "supported by jBallerina runtime."); } diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/JvmValueGen.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/JvmValueGen.java index 4fbaa635a1e2..f0802f68060d 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/JvmValueGen.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/JvmValueGen.java @@ -153,8 +153,8 @@ static void injectDefaultParamInitsToAttachedFuncs(BIRNode.BIRPackage module, In private static void desugarObjectMethods(List attachedFuncs, InitMethodGen initMethodGen) { for (BIRNode.BIRFunction birFunc : attachedFuncs) { if (JvmCodeGenUtil.isExternFunc(birFunc)) { - if (birFunc instanceof JMethodBIRFunction) { - desugarInteropFuncs((JMethodBIRFunction) birFunc, initMethodGen); + if (birFunc instanceof JMethodBIRFunction jMethodBIRFunction) { + desugarInteropFuncs(jMethodBIRFunction, initMethodGen); initMethodGen.resetIds(); } else if (!(birFunc instanceof JFieldBIRFunction)) { initMethodGen.resetIds(); diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/interop/AnnotationProc.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/interop/AnnotationProc.java index f5cc4668def1..bba8a1a8a9b1 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/interop/AnnotationProc.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/interop/AnnotationProc.java @@ -43,13 +43,16 @@ * * @since 1.2.0 */ -public class AnnotationProc { +public final class AnnotationProc { public static final String NAME_FIELD_NAME = "name"; public static final String CLASS_FIELD_NAME = "class"; public static final String PARAM_TYPES_FIELD_NAME = "paramTypes"; public static final String DIMENSIONS_FIELD_NAME = "dimensions"; + private AnnotationProc() { + } + static InteropValidationRequest getInteropAnnotValue(BIRFunction birFunc) { BIRAnnotationAttachment annotAttach = getInteropAnnotAttachment(birFunc); @@ -135,13 +138,13 @@ private static List buildParamTypeConstraints(BIRNode.ConstValue annotVal for (BIRNode.ConstValue annotArrayElement : annotArrayElements) { JType jType; Object elementValue = annotArrayElement.value; - if (elementValue instanceof String) { - jType = getJTypeFromTypeName((String) elementValue); - } else if (elementValue instanceof Map) { - Map annotValueMap = (Map) elementValue; - String elementClass = (String) getLiteralValueFromAnnotValue(annotValueMap.get(CLASS_FIELD_NAME)); - byte dimensions = ((Long) getLiteralValueFromAnnotValue(annotValueMap.get(DIMENSIONS_FIELD_NAME))) - .byteValue(); + if (elementValue instanceof String s) { + jType = getJTypeFromTypeName(s); + } else if (elementValue instanceof Map annotValueMap) { + String elementClass = (String) getLiteralValueFromAnnotValue( + (BIRNode.ConstValue) annotValueMap.get(CLASS_FIELD_NAME)); + byte dimensions = ((Long) getLiteralValueFromAnnotValue( + (BIRNode.ConstValue) annotValueMap.get(DIMENSIONS_FIELD_NAME))).byteValue(); jType = getJArrayTypeFromTypeName(elementClass, dimensions); } else { throw new BLangCompilerException("unexpected annotation value: " + annotArrayElement); diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/interop/ExternalMethodGen.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/interop/ExternalMethodGen.java index 91614ec0dcf3..5d25387eb63e 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/interop/ExternalMethodGen.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/interop/ExternalMethodGen.java @@ -47,15 +47,15 @@ * * @since 1.2.0 */ -public class ExternalMethodGen { +public final class ExternalMethodGen { public static void genJMethodForBExternalFunc(BIRFunction birFunc, ClassWriter cw, BIRPackage birModule, BType attachedType, MethodGen methodGen, JvmPackageGen jvmPackageGen, JvmTypeGen jvmTypeGen, JvmCastGen jvmCastGen, JvmConstantsGen jvmConstantsGen, String moduleClassName, AsyncDataCollector lambdaGenMetadata, Types types) { - if (birFunc instanceof JFieldBIRFunction) { - genJFieldForInteropField((JFieldBIRFunction) birFunc, cw, birModule.packageID, jvmPackageGen, jvmTypeGen, + if (birFunc instanceof JFieldBIRFunction jFieldBIRFunction) { + genJFieldForInteropField(jFieldBIRFunction, cw, birModule.packageID, jvmPackageGen, jvmTypeGen, jvmCastGen, jvmConstantsGen, lambdaGenMetadata, types); } else { methodGen.genJMethodForBFunc(birFunc, cw, birModule, jvmTypeGen, jvmCastGen, jvmConstantsGen, @@ -73,8 +73,8 @@ public static void injectDefaultParamInits(BIRPackage module, InitMethodGen init while (count < funcSize) { BIRFunction birFunc = functions.get(count); count = count + 1; - if (birFunc instanceof JMethodBIRFunction) { - desugarInteropFuncs((JMethodBIRFunction) birFunc, initMethodGen); + if (birFunc instanceof JMethodBIRFunction jMethodBIRFunction) { + desugarInteropFuncs(jMethodBIRFunction, initMethodGen); initMethodGen.resetIds(); } else if (!(birFunc instanceof JFieldBIRFunction)) { initMethodGen.resetIds(); diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/interop/InteropMethodGen.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/interop/InteropMethodGen.java index 753a8ba3eadf..4d30424e3221 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/interop/InteropMethodGen.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/interop/InteropMethodGen.java @@ -128,7 +128,7 @@ * * @since 1.2.0 */ -public class InteropMethodGen { +public final class InteropMethodGen { static void genJFieldForInteropField(JFieldBIRFunction birFunc, ClassWriter classWriter, PackageID birModule, JvmPackageGen jvmPackageGen, JvmTypeGen jvmTypeGen, JvmCastGen jvmCastGen, diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/interop/JInterop.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/interop/JInterop.java index 9d684346d8c5..fdd34827b364 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/interop/JInterop.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/interop/JInterop.java @@ -43,7 +43,7 @@ * * @since 1.2.0 */ -class JInterop { +final class JInterop { static final String INTEROP_ANNOT_ORG = "ballerina"; static final String INTEROP_ANNOT_MODULE = "jballerina.java"; diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/methodgen/MethodGenUtils.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/methodgen/MethodGenUtils.java index fdb17dbbb156..57aab825ef70 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/methodgen/MethodGenUtils.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/methodgen/MethodGenUtils.java @@ -53,7 +53,8 @@ * * @since 2.0.0 */ -public class MethodGenUtils { +public final class MethodGenUtils { + public static final String FRAMES = "frames"; static final String INIT_FUNCTION_SUFFIX = "."; static final String STOP_FUNCTION_SUFFIX = "."; diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/model/JTypeTags.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/model/JTypeTags.java index eb21a5a1c54d..085fa07495a8 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/model/JTypeTags.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/model/JTypeTags.java @@ -22,7 +22,7 @@ * * @since 1.2.0 */ -public class JTypeTags { +public final class JTypeTags { public static final int JBYTE = 1; public static final int JCHAR = 2; diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/split/constants/JvmConstantGenCommons.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/split/constants/JvmConstantGenCommons.java index 8e02aaebc076..15e5903d2558 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/split/constants/JvmConstantGenCommons.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/split/constants/JvmConstantGenCommons.java @@ -36,7 +36,7 @@ * * @since 2201.2.0 */ -public class JvmConstantGenCommons { +public final class JvmConstantGenCommons { private JvmConstantGenCommons() { } diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/emit/EmitterUtils.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/emit/EmitterUtils.java index 38f0b8205ad2..80a2053f718b 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/emit/EmitterUtils.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/emit/EmitterUtils.java @@ -35,7 +35,7 @@ * * @since 1.2.0 */ -class EmitterUtils { +final class EmitterUtils { private EmitterUtils() {} diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/emit/InstructionEmitter.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/emit/InstructionEmitter.java index 7607540f0cac..66aa82d80495 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/emit/InstructionEmitter.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/emit/InstructionEmitter.java @@ -48,7 +48,7 @@ * * @since 1.2.0 */ -class InstructionEmitter { +final class InstructionEmitter { private static final byte INITIAL_VALUE_COUNT = 10; diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/emit/TypeEmitter.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/emit/TypeEmitter.java index 4106bd0a899f..c1f634476a63 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/emit/TypeEmitter.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/emit/TypeEmitter.java @@ -60,10 +60,13 @@ * * @since 1.2.0 */ -class TypeEmitter { +final class TypeEmitter { static final Map B_TYPES = new HashMap<>(); + private TypeEmitter() { + } + static String emitType(BType bType, int tabs) { return switch (bType.tag) { diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/model/BIRNode.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/model/BIRNode.java index d2862f16aa9a..729faf0f4500 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/model/BIRNode.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/model/BIRNode.java @@ -163,12 +163,10 @@ public boolean equals(Object other) { return true; } - if (!(other instanceof BIRVariableDcl)) { + if (!(other instanceof BIRVariableDcl otherVarDecl)) { return false; } - BIRVariableDcl otherVarDecl = (BIRVariableDcl) other; - // Here we assume names are unique. return this.name.equals(otherVarDecl.name); } diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/model/BIRNonTerminator.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/model/BIRNonTerminator.java index e8cf5958eb63..d33d3eba6ad2 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/model/BIRNonTerminator.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/model/BIRNonTerminator.java @@ -236,8 +236,7 @@ public BIROperand[] getRhsOperands() { int i = 0; operands[i++] = rhsOp; for (BIRMappingConstructorEntry mappingEntry : initialValues) { - if (mappingEntry instanceof BIRMappingConstructorKeyValueEntry) { - BIRMappingConstructorKeyValueEntry entry = (BIRMappingConstructorKeyValueEntry) mappingEntry; + if (mappingEntry instanceof BIRMappingConstructorKeyValueEntry entry) { operands[i++] = entry.keyOp; operands[i++] = entry.valueOp; } else { @@ -254,8 +253,7 @@ public void setRhsOperands(BIROperand[] operands) { this.rhsOp = operands[0]; int i = 1; for (BIRMappingConstructorEntry mappingEntry : initialValues) { - if (mappingEntry instanceof BIRMappingConstructorKeyValueEntry) { - BIRMappingConstructorKeyValueEntry entry = (BIRMappingConstructorKeyValueEntry) mappingEntry; + if (mappingEntry instanceof BIRMappingConstructorKeyValueEntry entry) { entry.keyOp = operands[i++]; entry.valueOp = operands[i++]; } else { diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/model/BIROperand.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/model/BIROperand.java index d6ef9fb3fe93..6070e0046e7f 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/model/BIROperand.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/model/BIROperand.java @@ -42,11 +42,11 @@ public boolean equals(Object other) { return true; } - if (!(other instanceof BIROperand)) { + if (!(other instanceof BIROperand birOperand)) { return false; } - return this.variableDcl.equals(((BIROperand) other).variableDcl); + return this.variableDcl.equals(birOperand.variableDcl); } @Override diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/optimizer/BIROptimizer.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/optimizer/BIROptimizer.java index 216019271234..61a755adf31f 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/optimizer/BIROptimizer.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/optimizer/BIROptimizer.java @@ -50,7 +50,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import java.util.stream.Collectors; /** * Optimize BIR. @@ -278,9 +277,8 @@ public void visit(BIRFunction birFunction) { birFunction.errorTable.forEach(ee -> this.optimizeNode(ee, funcOpEnv)); // Remove unused temp vars - birFunction.localVars = birFunction.localVars.stream() - .filter(l -> l.kind != VarKind.TEMP || !funcOpEnv.tempVars - .containsKey(l)).collect(Collectors.toList()); + birFunction.localVars = new ArrayList<>(birFunction.localVars.stream() + .filter(l -> l.kind != VarKind.TEMP || !funcOpEnv.tempVars.containsKey(l)).toList()); // Reuse lhs temp vars Set replaceableVarSet = new HashSet<>(); reuseTempVariables(birFunction.localVars, funcOpEnv.tempVarsList, replaceableVarSet); diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/writer/BIRTypeWriter.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/writer/BIRTypeWriter.java index d316746f5d8f..c429eba1ff33 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/writer/BIRTypeWriter.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/writer/BIRTypeWriter.java @@ -176,12 +176,12 @@ public void visit(BFiniteType bFiniteType) { buff.writeLong(tsymbol.flags); buff.writeInt(bFiniteType.getValueSpace().size()); for (BLangExpression valueLiteral : bFiniteType.getValueSpace()) { - if (!(valueLiteral instanceof BLangLiteral)) { + if (!(valueLiteral instanceof BLangLiteral bLangLiteral)) { throw new AssertionError( "Type serialization is not implemented for finite type with value: " + valueLiteral.getKind()); } writeTypeCpIndex(valueLiteral.getBType()); - writeValue(((BLangLiteral) valueLiteral).value, valueLiteral.getBType()); + writeValue(bLangLiteral.value, valueLiteral.getBType()); } } @@ -363,9 +363,9 @@ public void visit(BUnionType bUnionType) { writeMembers(bUnionType.getMemberTypes()); writeMembers(bUnionType.getOriginalMemberTypes()); - if (tsymbol instanceof BEnumSymbol) { + if (tsymbol instanceof BEnumSymbol enumSymbol) { buff.writeBoolean(true); - writeEnumSymbolInfo((BEnumSymbol) tsymbol); + writeEnumSymbolInfo(enumSymbol); } else { buff.writeBoolean(false); } diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/writer/BIRWriterUtils.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/writer/BIRWriterUtils.java index c08e66fe135a..8d915cbfc348 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/writer/BIRWriterUtils.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/writer/BIRWriterUtils.java @@ -43,7 +43,10 @@ * * @since 2.0.0 */ -public class BIRWriterUtils { +public final class BIRWriterUtils { + + private BIRWriterUtils() { + } public static void writePosition(Location pos, ByteBuf buf, ConstantPool cp) { int sLine = Integer.MIN_VALUE; diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/writer/ConstantPool.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/writer/ConstantPool.java index 26d47684d4b8..bba3434f9d2a 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/writer/ConstantPool.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/writer/ConstantPool.java @@ -85,6 +85,9 @@ private void overwriteSize(byte[] bytes) { private void writeToStream(DataOutputStream stream) throws IOException { stream.writeInt(-1); + + // cpEntries are modified while iterating over them + // noinspection ForLoopReplaceableByForEach for (int i = 0; i < cpEntries.size(); i++) { CPEntry cpEntry = cpEntries.get(i); stream.writeByte(cpEntry.entryType.value); diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/ASTBuilderUtil.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/ASTBuilderUtil.java index be7720ed29b5..d36bb7fe379e 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/ASTBuilderUtil.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/ASTBuilderUtil.java @@ -115,7 +115,6 @@ import java.util.ArrayList; import java.util.EnumSet; import java.util.List; -import java.util.stream.Collectors; import static org.ballerinalang.model.symbols.SymbolOrigin.VIRTUAL; @@ -124,7 +123,10 @@ * * @since 0.965.0 */ -public class ASTBuilderUtil { +public final class ASTBuilderUtil { + + private ASTBuilderUtil() { + } /** * Prepend generated code to given body. @@ -901,7 +903,7 @@ public static BInvokableSymbol duplicateFunctionDeclarationSymbol(BInvokableSymb dupFuncSymbol.params = invokableSymbol.params.stream() .map(param -> duplicateParamSymbol(param, dupFuncSymbol)) - .collect(Collectors.toList()); + .toList(); if (dupFuncSymbol.restParam != null) { dupFuncSymbol.restParam = duplicateParamSymbol(invokableSymbol.restParam, dupFuncSymbol); } diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/AnnotationDesugar.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/AnnotationDesugar.java index e1573d5e91a1..6fa8f65020e6 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/AnnotationDesugar.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/AnnotationDesugar.java @@ -98,7 +98,6 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; -import java.util.stream.Collectors; import static io.ballerina.runtime.api.constants.RuntimeConstants.UNDERSCORE; import static org.ballerinalang.model.symbols.SymbolOrigin.VIRTUAL; @@ -180,6 +179,8 @@ void rewritePackageAnnotations(BLangPackage pkgNode, SymbolEnv env) { private void defineClassAnnotations(BLangPackage pkgNode, SymbolEnv env2, BLangFunction initFunction) { List topLevelNodes = pkgNode.topLevelNodes; + // topLevelNodes are modified while iterating over them + // noinspection ForLoopReplaceableByForEach for (int i = 0, topLevelNodesSize = topLevelNodes.size(); i < topLevelNodesSize; i++) { TopLevelNode topLevelNode = topLevelNodes.get(i); if (topLevelNode.getKind() != NodeKind.CLASS_DEFN) { @@ -218,7 +219,7 @@ private void defineClassAnnotations(BLangPackage pkgNode, SymbolEnv env2, BLangF } SymbolEnv classEnv = SymbolEnv.createClassEnv(classDef, scope, env); - BLangLambdaFunction lambdaFunction = defineAnnotations(pos, classDef, pkgNode, classEnv, pkgID, + BLangLambdaFunction lambdaFunction = defineAnnotations(classDef, pkgNode, classEnv, pkgID, owner); if (lambdaFunction != null) { BType type = classDef.getBType(); @@ -310,8 +311,8 @@ private void addIntrospectionInfoAnnotation(BLangClassDefinition serviceClass, S BSymbol annSymbol = symResolver.lookupSymbolInAnnotationSpace(symTable.pkgEnvMap.get(symTable.rootPkgSymbol), Names.fromString(SERVICE_INTROSPECTION_INFO_ANN)); annSymbol.origin = SymbolOrigin.BUILTIN; - if (annSymbol instanceof BAnnotationSymbol) { - annoAttachment.annotationSymbol = (BAnnotationSymbol) annSymbol; + if (annSymbol instanceof BAnnotationSymbol bAnnotationSymbol) { + annoAttachment.annotationSymbol = bAnnotationSymbol; } BLangIdentifier identifierNode = (BLangIdentifier) TreeBuilder.createIdentifierNode(); @@ -356,8 +357,8 @@ private void addIntrospectionInfoAnnotation(BLangClassDefinition serviceClass, S BSymbol fieldSymbol = symResolver.resolveStructField(position, pkgEnv, Names.fromString(SERVICE_NAME), bStructSymbol); - if (fieldSymbol instanceof BVarSymbol) { - descriptorKeyValue.key.fieldSymbol = (BVarSymbol) fieldSymbol; + if (fieldSymbol instanceof BVarSymbol bVarSymbol) { + descriptorKeyValue.key.fieldSymbol = bVarSymbol; } if (valueLiteral != null) { descriptorKeyValue.valueExpr = valueLiteral; @@ -377,27 +378,28 @@ private String generateServiceHashCode(BLangClassDefinition serviceClass) { return String.format("%d", Objects.hash(serviceName, moduleId, lineRange)); } - private BLangLambdaFunction defineAnnotations(Location pos, BLangClassDefinition classDef, BLangPackage pkgNode, + private BLangLambdaFunction defineAnnotations(BLangClassDefinition classDef, BLangPackage pkgNode, SymbolEnv env, PackageID pkgID, BSymbol owner) { BLangFunction function = null; BLangRecordLiteral mapLiteral = null; boolean isLocalObjectCtor = classDef.flagSet.contains(Flag.OBJECT_CTOR); if (!classDef.annAttachments.isEmpty()) { - function = defineFunction(pos, pkgID, owner); - mapLiteral = ASTBuilderUtil.createEmptyRecordLiteral(pos, symTable.mapType); - addAnnotsToLiteral(classDef.annAttachments, mapLiteral, pos, env, isLocalObjectCtor); + Location annotPos = classDef.annAttachments.get(0).pos; + function = defineFunction(annotPos, pkgID, owner); + mapLiteral = ASTBuilderUtil.createEmptyRecordLiteral(annotPos, symTable.mapType); + addAnnotsToLiteral(classDef.annAttachments, mapLiteral, annotPos, env, isLocalObjectCtor); } for (BLangSimpleVariable field : classDef.fields) { BLangLambdaFunction paramAnnotLambda = - defineAnnotations(field.annAttachments, pos, pkgNode, env, pkgID, owner, isLocalObjectCtor); + defineAnnotations(field.annAttachments, pkgNode, env, pkgID, owner, isLocalObjectCtor); if (paramAnnotLambda == null) { continue; } if (function == null) { - function = defineFunction(pos, pkgID, owner); - mapLiteral = ASTBuilderUtil.createEmptyRecordLiteral(pos, symTable.mapType); + function = defineFunction(paramAnnotLambda.pos, pkgID, owner); + mapLiteral = ASTBuilderUtil.createEmptyRecordLiteral(paramAnnotLambda.pos, symTable.mapType); } String fieldName = FIELD + DOT + field.name.value; @@ -471,7 +473,7 @@ private void defineTypeAnnotations(BLangPackage pkgNode, SymbolEnv env, BLangFun || typeNode.getKind() == NodeKind.TUPLE_TYPE_NODE) { lambdaFunction = defineAnnotations(typeDef, pkgNode, typeEnv, pkgID, owner); } else { - lambdaFunction = defineAnnotations(typeDef, typeDef.pos, pkgNode, typeEnv, pkgID, owner); + lambdaFunction = defineAnnotations(getAnnotationList(typeDef), pkgNode, env, pkgID, owner, false); } if (lambdaFunction != null) { @@ -560,19 +562,13 @@ private void attachSchedulerPolicy(BLangFunction function) { } } - private BLangLambdaFunction defineAnnotations(AnnotatableNode node, Location location, - BLangPackage pkgNode, SymbolEnv env, PackageID pkgID, BSymbol owner) { - return defineAnnotations(getAnnotationList(node), location, pkgNode, env, pkgID, owner, false); - } - private List getAnnotationList(AnnotatableNode node) { return node.getAnnotationAttachments().stream() .map(annotAttachment -> (BLangAnnotationAttachment) annotAttachment) - .collect(Collectors.toList()); + .toList(); } private BLangLambdaFunction defineAnnotations(List annAttachments, - Location location, BLangPackage pkgNode, SymbolEnv env, PackageID pkgID, @@ -581,10 +577,11 @@ private BLangLambdaFunction defineAnnotations(List an return null; } - BLangFunction function = defineFunction(location, pkgID, owner); + Location pos = annAttachments.get(0).pos; + BLangFunction function = defineFunction(pos, pkgID, owner); BLangRecordLiteral mapLiteral = ASTBuilderUtil.createEmptyRecordLiteral(function.pos, symTable.mapType); SymbolEnv funcEnv = SymbolEnv.createFunctionEnv(function, function.symbol.scope, env); - addAnnotsToLiteral(annAttachments, mapLiteral, location, funcEnv, isLocalObjectCtor); + addAnnotsToLiteral(annAttachments, mapLiteral, pos, funcEnv, isLocalObjectCtor); if (mapLiteral.fields.isEmpty()) { return null; @@ -599,7 +596,7 @@ private BLangLambdaFunction defineAnnotations(BLangTypeDefinition typeDef, BLang BLangRecordLiteral mapLiteral = null; if (!typeDef.annAttachments.isEmpty()) { - function = defineFunction(typeDef.pos, pkgID, owner); + function = defineFunction(typeDef.annAttachments.get(0).pos, pkgID, owner); mapLiteral = ASTBuilderUtil.createEmptyRecordLiteral(function.pos, symTable.mapType); addAnnotsToLiteral(typeDef.annAttachments, mapLiteral, typeDef.pos, env, false); } @@ -610,11 +607,11 @@ private BLangLambdaFunction defineAnnotations(BLangTypeDefinition typeDef, BLang fields = ((BLangStructureTypeNode) typeDef.typeNode).fields; } for (BLangSimpleVariable field : fields) { - BLangLambdaFunction paramAnnotLambda = defineAnnotations(field.annAttachments, field.pos, pkgNode, env, + BLangLambdaFunction paramAnnotLambda = defineAnnotations(field.annAttachments, pkgNode, env, pkgID, owner, false); if (paramAnnotLambda != null) { if (function == null) { - function = defineFunction(typeDef.pos, pkgID, owner); + function = defineFunction(paramAnnotLambda.pos, pkgID, owner); mapLiteral = ASTBuilderUtil.createEmptyRecordLiteral(function.pos, symTable.mapType); } @@ -639,7 +636,7 @@ public BLangLambdaFunction defineFieldAnnotations(List fiel boolean annotFunctionDefined = false; for (BLangSimpleVariable field : fields) { - BLangLambdaFunction fieldAnnotLambda = defineAnnotations(field.annAttachments, field.pos, pkgNode, env, + BLangLambdaFunction fieldAnnotLambda = defineAnnotations(field.annAttachments, pkgNode, env, pkgID, owner, false); if (fieldAnnotLambda != null) { BInvokableSymbol invokableSymbol = @@ -647,7 +644,7 @@ public BLangLambdaFunction defineFieldAnnotations(List fiel owner.getKind() == SymbolKind.PACKAGE); env.scope.define(invokableSymbol.name, invokableSymbol); if (!annotFunctionDefined) { - function = defineFunction(pos, pkgID, owner); + function = defineFunction(fieldAnnotLambda.pos, pkgID, owner); mapLiteral = ASTBuilderUtil.createEmptyRecordLiteral(function.pos, symTable.mapType); annotFunctionDefined = true; } @@ -673,18 +670,18 @@ private BLangLambdaFunction defineAnnotations(BLangFunction bLangFunction, BLang SymbolEnv funcEnv = SymbolEnv.createFunctionEnv(bLangFunction, bLangFunction.symbol.scope, env); if (!bLangFunction.annAttachments.isEmpty()) { - function = defineFunction(bLangFunction.pos, pkgID, owner); + function = defineFunction(bLangFunction.annAttachments.get(0).pos, pkgID, owner); mapLiteral = ASTBuilderUtil.createEmptyRecordLiteral(function.pos, symTable.mapType); addAnnotsToLiteral(bLangFunction.annAttachments, mapLiteral, bLangFunction.pos, funcEnv, false); annotFunctionDefined = true; } for (BLangSimpleVariable param : getParams(bLangFunction)) { - BLangLambdaFunction paramAnnotLambda = defineAnnotations(param.annAttachments, param.pos, pkgNode, funcEnv, + BLangLambdaFunction paramAnnotLambda = defineAnnotations(param.annAttachments, pkgNode, funcEnv, pkgID, owner, false); if (paramAnnotLambda != null) { if (!annotFunctionDefined) { - function = defineFunction(bLangFunction.pos, pkgID, owner); + function = defineFunction(paramAnnotLambda.pos, pkgID, owner); mapLiteral = ASTBuilderUtil.createEmptyRecordLiteral(function.pos, symTable.mapType); annotFunctionDefined = true; } @@ -696,12 +693,12 @@ private BLangLambdaFunction defineAnnotations(BLangFunction bLangFunction, BLang if (!bLangFunction.returnTypeAnnAttachments.isEmpty()) { if (!annotFunctionDefined) { - function = defineFunction(bLangFunction.pos, pkgID, owner); + function = defineFunction(bLangFunction.returnTypeAnnAttachments.get(0).pos, pkgID, owner); mapLiteral = ASTBuilderUtil.createEmptyRecordLiteral(function.pos, symTable.mapType); annotFunctionDefined = true; } - BLangFunction retFunction = defineFunction(bLangFunction.pos, pkgID, owner); + BLangFunction retFunction = defineFunction(function.pos, pkgID, owner); BLangRecordLiteral retMapLiteral = ASTBuilderUtil.createEmptyRecordLiteral(function.pos, symTable.mapType); addAnnotsToLiteral(bLangFunction.returnTypeAnnAttachments, retMapLiteral, bLangFunction.pos, funcEnv, false); @@ -731,8 +728,8 @@ private void addVarArgsAnnotation(BLangFunction mainFunc, SymbolEnv env) { mainFunc.addAnnotationAttachment(annoAttachment); final SymbolEnv pkgEnv = symTable.pkgEnvMap.get(mainFunc.symbol.getEnclosingSymbol()); BSymbol annSymbol = symResolver.lookupSymbolInAnnotationSpace(pkgEnv, Names.fromString(DEFAULTABLE_ANN)); - if (annSymbol instanceof BAnnotationSymbol) { - annoAttachment.annotationSymbol = (BAnnotationSymbol) annSymbol; + if (annSymbol instanceof BAnnotationSymbol bAnnotationSymbol) { + annoAttachment.annotationSymbol = bAnnotationSymbol; } BLangIdentifier identifierNode = (BLangIdentifier) TreeBuilder.createIdentifierNode(); annoAttachment.annotationName = identifierNode; @@ -786,8 +783,8 @@ private void addVarArgsAnnotation(BLangFunction mainFunc, SymbolEnv env) { descriptorKeyValue.key = new BLangRecordLiteral.BLangRecordKey(keyLiteral); BSymbol fieldSymbol = symResolver.resolveStructField(mainFunc.pos, pkgEnv, Names.fromString(ARG_NAMES), bStructSymbol); - if (fieldSymbol instanceof BVarSymbol) { - descriptorKeyValue.key.fieldSymbol = (BVarSymbol) fieldSymbol; + if (fieldSymbol instanceof BVarSymbol bVarSymbol) { + descriptorKeyValue.key.fieldSymbol = bVarSymbol; } if (valueLiteral != null) { descriptorKeyValue.valueExpr = valueLiteral; @@ -868,7 +865,7 @@ private void addAnnotsToLiteral(List nodeAttachments, // }; // // Adds // { ..., v1: true, ... } - addTrueAnnot(attachments.get(annotationSymbol).get(0), mapLiteral, isLocalObjectCtor); + addTrueAnnot(attachments.get(annotationSymbol).get(0), mapLiteral); } else if (Types.getImpliedType(attachedType).tag != TypeTags.ARRAY) { // annotation FooRecord v1 on type; OR annotation map v1 on type; // @v1 { @@ -879,7 +876,7 @@ private void addAnnotsToLiteral(List nodeAttachments, // }; // // Adds // { ..., v1: { value: 1 }, ... } - addSingleAnnot(attachments.get(annotationSymbol).get(0), mapLiteral, isLocalObjectCtor); + addSingleAnnot(attachments.get(annotationSymbol).get(0), mapLiteral); } else { // annotation FooRecord[] v1 on type; OR annotation map[] v1 on type; // @v1 { @@ -908,7 +905,7 @@ private BInvokableSymbol createInvokableSymbol(BLangFunction function, PackageID functionSymbol.retType = function.returnTypeNode.getBType(); functionSymbol.params = function.requiredParams.stream() .map(param -> param.symbol) - .collect(Collectors.toList()); + .toList(); functionSymbol.scope = new Scope(functionSymbol); functionSymbol.restParam = function.restParam != null ? function.restParam.symbol : null; functionSymbol.type = new BInvokableType(Collections.emptyList(), @@ -930,8 +927,7 @@ private BLangSimpleVariable createGlobalAnnotationMapVar(BLangPackage pkgNode) { return annotationMap; } - private void addTrueAnnot(BLangAnnotationAttachment attachment, BLangRecordLiteral recordLiteral, - boolean isLocalObjectCtor) { + private void addTrueAnnot(BLangAnnotationAttachment attachment, BLangRecordLiteral recordLiteral) { // Handle scenarios where type is a subtype of `true` explicitly or implicitly (by omission). // add { ..., v1: true, ... } BLangExpression expression = ASTBuilderUtil.wrapToConversionExpr(symTable.trueType, @@ -942,8 +938,7 @@ private void addTrueAnnot(BLangAnnotationAttachment attachment, BLangRecordLiter addAnnotValueToLiteral(recordLiteral, attachment.annotationSymbol.bvmAlias(), expression, attachment.pos); } - private void addSingleAnnot(BLangAnnotationAttachment attachment, BLangRecordLiteral recordLiteral, - boolean isLocalObjectCtor) { + private void addSingleAnnot(BLangAnnotationAttachment attachment, BLangRecordLiteral recordLiteral) { // Handle scenarios where type is a subtype of `map` or `record{any|error...;}`. // create: add { ..., v1: { value: 1 } ... } or { ..., v1: C1 ... } where C1 is a constant reference addAnnotValueToLiteral(recordLiteral, attachment.annotationSymbol.bvmAlias(), attachment.expr, attachment.pos); @@ -1172,7 +1167,7 @@ public BLangAnnotationAttachment createStrandAnnotationWithThreadAny(Location po return annotAttachment; } - private class LocationData { + private static class LocationData { public PackageID pkgID; public BSymbol owner; public Location pos; diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/ClassClosureDesugar.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/ClassClosureDesugar.java index c57c896e92c3..ac4477a039a2 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/ClassClosureDesugar.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/ClassClosureDesugar.java @@ -371,19 +371,14 @@ private BLangAssignment createAssignmentToClosureMap(BLangSimpleVariableDef varD private BVarSymbol createMapSymbolIfAbsent(BLangNode node, int closureMapCount) { NodeKind kind = node.getKind(); - switch (kind) { - case BLOCK_FUNCTION_BODY: - return createMapSymbolIfAbsent((BLangBlockFunctionBody) node, closureMapCount); - case BLOCK: - return createMapSymbolIfAbsent((BLangBlockStmt) node, closureMapCount); - case FUNCTION: - return createMapSymbolIfAbsent((BLangFunction) node, closureMapCount); - case RESOURCE_FUNC: - return createMapSymbolIfAbsent((BLangResourceFunction) node, closureMapCount); - case CLASS_DEFN: - return createMapSymbolIfAbsent((BLangClassDefinition) node, closureMapCount); - } - return null; + return switch (kind) { + case BLOCK_FUNCTION_BODY -> createMapSymbolIfAbsent((BLangBlockFunctionBody) node, closureMapCount); + case BLOCK -> createMapSymbolIfAbsent((BLangBlockStmt) node, closureMapCount); + case FUNCTION -> createMapSymbolIfAbsent((BLangFunction) node, closureMapCount); + case RESOURCE_FUNC -> createMapSymbolIfAbsent((BLangResourceFunction) node, closureMapCount); + case CLASS_DEFN -> createMapSymbolIfAbsent((BLangClassDefinition) node, closureMapCount); + default -> null; + }; } private BVarSymbol createMapSymbolIfAbsent(BLangBlockFunctionBody body, int closureMapCount) { diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/ClosureDesugar.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/ClosureDesugar.java index f3c4aa6328c0..bedf07625c9d 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/ClosureDesugar.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/ClosureDesugar.java @@ -775,19 +775,14 @@ private BVarSymbol findClosureMapSymbol(int absoluteLevel) { private BVarSymbol createMapSymbolIfAbsent(BLangNode node, int closureMapCount) { NodeKind kind = node.getKind(); - switch (kind) { - case BLOCK_FUNCTION_BODY: - return createMapSymbolIfAbsent((BLangBlockFunctionBody) node, closureMapCount); - case BLOCK: - return createMapSymbolIfAbsent((BLangBlockStmt) node, closureMapCount); - case FUNCTION: - return createMapSymbolIfAbsent((BLangFunction) node, closureMapCount); - case RESOURCE_FUNC: - return createMapSymbolIfAbsent((BLangResourceFunction) node, closureMapCount); - case CLASS_DEFN: - return createMapSymbolIfAbsent((BLangClassDefinition) node, closureMapCount); - } - return null; + return switch (kind) { + case BLOCK_FUNCTION_BODY -> createMapSymbolIfAbsent((BLangBlockFunctionBody) node, closureMapCount); + case BLOCK -> createMapSymbolIfAbsent((BLangBlockStmt) node, closureMapCount); + case FUNCTION -> createMapSymbolIfAbsent((BLangFunction) node, closureMapCount); + case RESOURCE_FUNC -> createMapSymbolIfAbsent((BLangResourceFunction) node, closureMapCount); + case CLASS_DEFN -> createMapSymbolIfAbsent((BLangClassDefinition) node, closureMapCount); + default -> null; + }; } private BVarSymbol createMapSymbolIfAbsent(BLangBlockFunctionBody body, int closureMapCount) { diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/ClosureGenerator.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/ClosureGenerator.java index d5fc03ba9651..ea16981eec54 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/ClosureGenerator.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/ClosureGenerator.java @@ -209,10 +209,10 @@ import java.util.Set; import static org.ballerinalang.model.symbols.SymbolOrigin.VIRTUAL; +import static org.wso2.ballerinalang.compiler.util.CompilerUtils.isInParameterList; import static org.wso2.ballerinalang.compiler.util.Constants.DOLLAR; import static org.wso2.ballerinalang.compiler.util.Constants.RECORD_DELIMITER; import static org.wso2.ballerinalang.compiler.util.Constants.UNDERSCORE; -import static org.wso2.ballerinalang.compiler.util.CompilerUtils.isInParameterList; /** * ClosureGenerator for creating closures for default values. @@ -421,36 +421,19 @@ public void visit(BLangRecordTypeNode recordTypeNode) { rewrite(field, recordTypeNode.typeDefEnv); } recordTypeNode.restFieldType = rewrite(recordTypeNode.restFieldType, env); - // In the current implementation, closures generated for default values in inclusions defined in a - // separate module are unidentifiable. - // Due to that, if the inclusions are in different modules, we generate closures again. - // Will be fixed with #41949 issue. - generateClosuresForDefaultValuesInTypeInclusionsFromDifferentModule(recordTypeNode); + generateClosuresForNonOverriddenFields(recordTypeNode); result = recordTypeNode; } - private List getFieldNames(List fields) { - List fieldNames = new ArrayList<>(); - for (BLangSimpleVariable field : fields) { - fieldNames.add(field.name.getValue()); - } - return fieldNames; - } - - private void generateClosuresForDefaultValuesInTypeInclusionsFromDifferentModule( - BLangRecordTypeNode recordTypeNode) { + private void generateClosuresForNonOverriddenFields(BLangRecordTypeNode recordTypeNode) { if (recordTypeNode.typeRefs.isEmpty()) { return; } List fieldNames = getFieldNames(recordTypeNode.fields); BTypeSymbol typeSymbol = recordTypeNode.getBType().tsymbol; String typeName = recordTypeNode.symbol.name.value; - PackageID packageID = typeSymbol.pkgID; for (BLangType type : recordTypeNode.typeRefs) { BType bType = type.getBType(); - if (packageID.equals(bType.tsymbol.pkgID)) { - continue; - } BRecordType recordType = (BRecordType) Types.getReferredType(bType); Map defaultValuesOfTypeRef = ((BRecordTypeSymbol) recordType.tsymbol).defaultValues; @@ -467,6 +450,14 @@ private void generateClosuresForDefaultValuesInTypeInclusionsFromDifferentModule } } + private List getFieldNames(List fields) { + List fieldNames = new ArrayList<>(); + for (BLangSimpleVariable field : fields) { + fieldNames.add(field.name.getValue()); + } + return fieldNames; + } + @Override public void visit(BLangTupleTypeNode tupleTypeNode) { BTypeSymbol typeSymbol = tupleTypeNode.getBType().tsymbol; @@ -755,25 +746,21 @@ private String generateName(String name, BLangNode parent) { if (parent == null) { return DOLLAR + name; } - switch (parent.getKind()) { - case CLASS_DEFN: - return generateName(((BLangClassDefinition) parent).name.getValue() + UNDERSCORE + name, parent.parent); - case FUNCTION: - name = ((BLangFunction) parent).symbol.name.value.replace(".", UNDERSCORE) + UNDERSCORE + name; - return generateName(name, parent.parent); - case RESOURCE_FUNC: - return generateName(((BLangResourceFunction) parent).name.value + UNDERSCORE + name, parent.parent); - case VARIABLE: - return generateName(((BLangSimpleVariable) parent).name.getValue() + UNDERSCORE + name, parent.parent); - case TYPE_DEFINITION: - return generateName(((BLangTypeDefinition) parent).name.getValue() + UNDERSCORE + name, parent.parent); - case RECORD_TYPE: - name = RECORD_DELIMITER + ((BLangRecordTypeNode) parent).symbol.name.getValue() + RECORD_DELIMITER - + name; - return generateName(name, parent.parent); - default: - return generateName(name, parent.parent); - } + return switch (parent.getKind()) { + case CLASS_DEFN -> + generateName(((BLangClassDefinition) parent).name.getValue() + UNDERSCORE + name, parent.parent); + case FUNCTION -> generateName(((BLangFunction) parent).symbol.name.value.replace(".", UNDERSCORE) + + UNDERSCORE + name, parent.parent); + case RESOURCE_FUNC -> + generateName(((BLangResourceFunction) parent).name.value + UNDERSCORE + name, parent.parent); + case VARIABLE -> + generateName(((BLangSimpleVariable) parent).name.getValue() + UNDERSCORE + name, parent.parent); + case TYPE_DEFINITION -> + generateName(((BLangTypeDefinition) parent).name.getValue() + UNDERSCORE + name, parent.parent); + case RECORD_TYPE -> generateName(RECORD_DELIMITER + ((BLangRecordTypeNode) parent).symbol.name.getValue() + + RECORD_DELIMITER + name, parent.parent); + default -> generateName(name, parent.parent); + }; } @Override public void visit(BLangTupleVariable varNode) { diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/DeclarativeAuthDesugar.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/DeclarativeAuthDesugar.java index e8b5e642da1c..2b8533ea8cf3 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/DeclarativeAuthDesugar.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/DeclarativeAuthDesugar.java @@ -145,10 +145,9 @@ void addAuthDesugarFunctionInvocation(BLangFunction functionNode, SymbolEnv env, // Relevant listener will handle this error. BSymbol methodSym = symResolver.lookupMethodInModule(packageSymbol, Names.fromString(AUTHENTICATE_RESOURCE), env); - if (methodSym == symTable.notFoundSymbol || !(methodSym instanceof BInvokableSymbol)) { + if (methodSym == symTable.notFoundSymbol || !(methodSym instanceof BInvokableSymbol invocationSymbol)) { return; } - BInvokableSymbol invocationSymbol = (BInvokableSymbol) methodSym; Location pos = functionNode.getPosition(); // Create method invocation. diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/Desugar.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/Desugar.java index f6cf065c909e..8aa47375a4d7 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/Desugar.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/Desugar.java @@ -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; @@ -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; @@ -397,7 +398,7 @@ public class Desugar extends BLangNodeVisitor { private ClassClosureDesugar classClosureDesugar; private LargeMethodSplitter largeMethodSplitter; - public Stack enclLocks = new Stack<>(); + public Deque enclLocks = new ArrayDeque<>(); private BLangOnFailClause onFailClause; private boolean shouldReturnErrors; private int transactionBlockCount; @@ -423,8 +424,8 @@ public class Desugar extends BLangNodeVisitor { private Set channelsWithinIfStmt = new LinkedHashSet<>(); // Safe navigation related variables - private Stack matchStmtStack = new Stack<>(); - Stack accessExprStack = new Stack<>(); + private Deque matchStmtStack = new ArrayDeque<>(); + Deque accessExprStack = new ArrayDeque<>(); private BLangMatchClause successClause; private BLangAssignment safeNavigationAssignment; static boolean isJvmTarget = false; @@ -978,8 +979,8 @@ private List desugarGlobalVariables(BLangPackage pkgNode, BLangBl List statements = ((BLangBlockStmt) blockStatementNode).stmts; int statementSize = statements.size(); - for (int i = 0; i < statementSize; i++) { - addToGlobalVariableList(statements.get(i), initFnBody, globalVar, desugaredGlobalVarList); + for (BLangStatement bLangStatement : statements) { + addToGlobalVariableList(bLangStatement, initFnBody, globalVar, desugaredGlobalVarList); } break; case RECORD_VARIABLE: @@ -1840,7 +1841,7 @@ private void createVarDefStmts(BLangRecordVariable parentRecordVariable, BLangBl List keysToRemove = parentRecordVariable.variableList.stream() .map(var -> var.getKey().getValue()) - .collect(Collectors.toList()); + .toList(); BLangSimpleVariable filteredDetail = generateRestFilter(variableReference, pos, keysToRemove, restParamType, parentBlockStmt); @@ -1947,7 +1948,7 @@ private void createVarDefStmts(BLangErrorVariable parentErrorVariable, BLangBloc pos, detailTempVarDef.var.symbol); List keysToRemove = parentErrorVariable.detail.stream() .map(detail -> detail.key.getValue()) - .collect(Collectors.toList()); + .toList(); BLangSimpleVariable filteredDetail = generateRestFilter(detailVarRef, parentErrorVariable.pos, keysToRemove, parentErrorVariable.restDetail.getBType(), @@ -2119,7 +2120,7 @@ private BLangLambdaFunction generateEntriesToMapLambda(Location pos, BType const functionSymbol.retType = function.returnTypeNode.getBType(); functionSymbol.params = function.requiredParams.stream() .map(param -> param.symbol) - .collect(Collectors.toList()); + .toList(); functionSymbol.scope = env.scope; functionSymbol.type = new BInvokableType(Collections.singletonList(getStringAnyTupleType()), constraint, null); function.symbol = functionSymbol; @@ -2349,7 +2350,7 @@ private BLangLambdaFunction createFuncToFilterOutRestParam(BLangRecordVariable r Location location) { List fieldNamesToRemove = recordVariable.variableList.stream() .map(var -> var.getKey().getValue()) - .collect(Collectors.toList()); + .toList(); return createFuncToFilterOutRestParam(fieldNamesToRemove, location); } @@ -2405,7 +2406,7 @@ private BInvokableSymbol createReturnTrueStatement(Location pos, BLangFunction f functionSymbol.retType = function.returnTypeNode.getBType(); functionSymbol.params = function.requiredParams.stream() .map(param -> param.symbol) - .collect(Collectors.toList()); + .toList(); functionSymbol.scope = env.scope; functionSymbol.type = new BInvokableType(Collections.singletonList(getStringAnyTupleType()), getRestType(functionSymbol), symTable.booleanType, null); @@ -2899,7 +2900,7 @@ private void createVarRefAssignmentStmts(BLangRecordVarRef parentRecordVarRef, B List keysToRemove = parentRecordVarRef.recordRefFields.stream() .map(field -> field.variableName.value) - .collect(Collectors.toList()); + .toList(); BLangSimpleVariable filteredDetail = generateRestFilter(variableReference, pos, keysToRemove, restParamType, parentBlockStmt); @@ -3717,26 +3718,24 @@ private BLangIf createIfElseStmtFromMatchPattern(BLangMatchPattern matchPattern, private BLangExpression createConditionForMatchPattern(BLangMatchPattern matchPattern, BLangSimpleVarRef matchExprVarRef) { NodeKind patternKind = matchPattern.getKind(); - switch (patternKind) { - case WILDCARD_MATCH_PATTERN: - return createConditionForWildCardMatchPattern((BLangWildCardMatchPattern) matchPattern, - matchExprVarRef); - case CONST_MATCH_PATTERN: - return createConditionForConstMatchPattern((BLangConstPattern) matchPattern, matchExprVarRef); - case VAR_BINDING_PATTERN_MATCH_PATTERN: - return createConditionForVarBindingPatternMatchPattern( - (BLangVarBindingPatternMatchPattern) matchPattern, matchExprVarRef); - case LIST_MATCH_PATTERN: - return createConditionForListMatchPattern((BLangListMatchPattern) matchPattern, matchExprVarRef); - case MAPPING_MATCH_PATTERN: - return createConditionForMappingMatchPattern((BLangMappingMatchPattern) matchPattern, matchExprVarRef); - case ERROR_MATCH_PATTERN: - return createConditionForErrorMatchPattern((BLangErrorMatchPattern) matchPattern, matchExprVarRef); - default: - // If some patterns are not implemented, those should be detected before this phase - // TODO : Remove this after all patterns are implemented - return null; - } + return switch (patternKind) { + case WILDCARD_MATCH_PATTERN -> + createConditionForWildCardMatchPattern((BLangWildCardMatchPattern) matchPattern, + matchExprVarRef); + case CONST_MATCH_PATTERN -> + createConditionForConstMatchPattern((BLangConstPattern) matchPattern, matchExprVarRef); + case VAR_BINDING_PATTERN_MATCH_PATTERN -> createConditionForVarBindingPatternMatchPattern( + (BLangVarBindingPatternMatchPattern) matchPattern, matchExprVarRef); + case LIST_MATCH_PATTERN -> + createConditionForListMatchPattern((BLangListMatchPattern) matchPattern, matchExprVarRef); + case MAPPING_MATCH_PATTERN -> + createConditionForMappingMatchPattern((BLangMappingMatchPattern) matchPattern, matchExprVarRef); + case ERROR_MATCH_PATTERN -> + createConditionForErrorMatchPattern((BLangErrorMatchPattern) matchPattern, matchExprVarRef); + // If some patterns are not implemented, those should be detected before this phase + // TODO : Remove this after all patterns are implemented + default -> null; + }; } private BLangExpression createConditionForWildCardMatchPattern(BLangWildCardMatchPattern wildCardMatchPattern, @@ -3864,23 +3863,22 @@ private BLangExpression createConditionForListMemberPattern(int index, BLangBind private BLangExpression createVarCheckCondition(BLangBindingPattern bindingPattern, BLangSimpleVarRef varRef) { NodeKind bindingPatternKind = bindingPattern.getKind(); - switch (bindingPatternKind) { - case WILDCARD_BINDING_PATTERN: - return createConditionForWildCardBindingPattern((BLangWildCardBindingPattern) bindingPattern, varRef); - case CAPTURE_BINDING_PATTERN: - return createConditionForCaptureBindingPattern((BLangCaptureBindingPattern) bindingPattern, varRef); - case LIST_BINDING_PATTERN: - return createVarCheckConditionForListBindingPattern((BLangListBindingPattern) bindingPattern, varRef); - case MAPPING_BINDING_PATTERN: - return createVarCheckConditionForMappingBindingPattern((BLangMappingBindingPattern) bindingPattern, - varRef); - case ERROR_BINDING_PATTERN: - return createConditionForErrorBindingPattern((BLangErrorBindingPattern) bindingPattern, varRef); - default: - // If some patterns are not implemented, those should be detected before this phase - // TODO : Remove this after all patterns are implemented - return null; - } + return switch (bindingPatternKind) { + case WILDCARD_BINDING_PATTERN -> + createConditionForWildCardBindingPattern((BLangWildCardBindingPattern) bindingPattern, varRef); + case CAPTURE_BINDING_PATTERN -> + createConditionForCaptureBindingPattern((BLangCaptureBindingPattern) bindingPattern, varRef); + case LIST_BINDING_PATTERN -> + createVarCheckConditionForListBindingPattern((BLangListBindingPattern) bindingPattern, varRef); + case MAPPING_BINDING_PATTERN -> + createVarCheckConditionForMappingBindingPattern((BLangMappingBindingPattern) bindingPattern, + varRef); + case ERROR_BINDING_PATTERN -> + createConditionForErrorBindingPattern((BLangErrorBindingPattern) bindingPattern, varRef); + // If some patterns are not implemented, those should be detected before this phase + // TODO : Remove this after all patterns are implemented + default -> null; + }; } private BLangExpression createVarCheckConditionForListBindingPattern(BLangListBindingPattern listBindingPattern, @@ -3955,26 +3953,25 @@ private BLangExpression createConditionForVarBindingPatternMatchPattern(BLangVar BLangBindingPattern bindingPattern = varBindingPatternMatchPattern.getBindingPattern(); Location pos = bindingPattern.pos; - switch (bindingPattern.getKind()) { - case WILDCARD_BINDING_PATTERN: - return createConditionForWildCardBindingPattern((BLangWildCardBindingPattern) bindingPattern, - matchExprVarRef); - case CAPTURE_BINDING_PATTERN: - return createConditionForCaptureBindingPattern((BLangCaptureBindingPattern) bindingPattern, - matchExprVarRef, pos); - case LIST_BINDING_PATTERN: - return createConditionForListBindingPattern((BLangListBindingPattern) bindingPattern, matchExprVarRef); - case MAPPING_BINDING_PATTERN: - return createConditionForMappingBindingPattern((BLangMappingBindingPattern) bindingPattern, - matchExprVarRef); - case ERROR_BINDING_PATTERN: - return createConditionForErrorBindingPattern((BLangErrorBindingPattern) bindingPattern, - matchExprVarRef); - default: - // If some patterns are not implemented, those should be detected before this phase - // TODO : Remove this after all patterns are implemented - return null; - } + return switch (bindingPattern.getKind()) { + case WILDCARD_BINDING_PATTERN -> + createConditionForWildCardBindingPattern((BLangWildCardBindingPattern) bindingPattern, + matchExprVarRef); + case CAPTURE_BINDING_PATTERN -> + createConditionForCaptureBindingPattern((BLangCaptureBindingPattern) bindingPattern, + matchExprVarRef, pos); + case LIST_BINDING_PATTERN -> + createConditionForListBindingPattern((BLangListBindingPattern) bindingPattern, matchExprVarRef); + case MAPPING_BINDING_PATTERN -> + createConditionForMappingBindingPattern((BLangMappingBindingPattern) bindingPattern, + matchExprVarRef); + case ERROR_BINDING_PATTERN -> + createConditionForErrorBindingPattern((BLangErrorBindingPattern) bindingPattern, + matchExprVarRef); + // If some patterns are not implemented, those should be detected before this phase + // TODO : Remove this after all patterns are implemented + default -> null; + }; } private BLangExpression createConditionForCaptureBindingPattern(BLangCaptureBindingPattern captureBindingPattern, @@ -4374,8 +4371,8 @@ private List getKeysToRemove(BLangMappingMatchPattern mappingMatchPatter private List getKeysToRemove(BLangMappingBindingPattern mappingBindingPattern) { List keysToRemove = new ArrayList<>(); List fieldBindingPatterns = mappingBindingPattern.fieldBindingPatterns; - for (int i = 0; i < fieldBindingPatterns.size(); i++) { - keysToRemove.add(fieldBindingPatterns.get(i).fieldName.value); + for (BLangFieldBindingPattern fieldBindingPattern : fieldBindingPatterns) { + keysToRemove.add(fieldBindingPattern.fieldName.value); } return keysToRemove; } @@ -4449,25 +4446,23 @@ private BLangExpression createConditionForFieldBindingPattern(int index, private BLangExpression createVarCheckCondition(BLangMatchPattern matchPattern, BLangSimpleVarRef varRef) { NodeKind patternKind = matchPattern.getKind(); - switch (patternKind) { - case WILDCARD_MATCH_PATTERN: - return createConditionForWildCardMatchPattern((BLangWildCardMatchPattern) matchPattern, varRef); - case CONST_MATCH_PATTERN: - return createConditionForConstMatchPattern((BLangConstPattern) matchPattern, varRef); - case VAR_BINDING_PATTERN_MATCH_PATTERN: - return createVarCheckCondition(((BLangVarBindingPatternMatchPattern) matchPattern).getBindingPattern(), - varRef); - case LIST_MATCH_PATTERN: - return createVarCheckConditionForListMatchPattern((BLangListMatchPattern) matchPattern, varRef); - case MAPPING_MATCH_PATTERN: - return createVarCheckConditionForMappingMatchPattern((BLangMappingMatchPattern) matchPattern, varRef); - case ERROR_MATCH_PATTERN: - return createConditionForErrorMatchPattern((BLangErrorMatchPattern) matchPattern, varRef); - default: - // If some patterns are not implemented, those should be detected before this phase - // TODO : Remove this after all patterns are implemented - return null; - } + return switch (patternKind) { + case WILDCARD_MATCH_PATTERN -> + createConditionForWildCardMatchPattern((BLangWildCardMatchPattern) matchPattern, varRef); + case CONST_MATCH_PATTERN -> createConditionForConstMatchPattern((BLangConstPattern) matchPattern, varRef); + case VAR_BINDING_PATTERN_MATCH_PATTERN -> + createVarCheckCondition(((BLangVarBindingPatternMatchPattern) matchPattern).getBindingPattern(), + varRef); + case LIST_MATCH_PATTERN -> + createVarCheckConditionForListMatchPattern((BLangListMatchPattern) matchPattern, varRef); + case MAPPING_MATCH_PATTERN -> + createVarCheckConditionForMappingMatchPattern((BLangMappingMatchPattern) matchPattern, varRef); + case ERROR_MATCH_PATTERN -> + createConditionForErrorMatchPattern((BLangErrorMatchPattern) matchPattern, varRef); + // If some patterns are not implemented, those should be detected before this phase + // TODO : Remove this after all patterns are implemented + default -> null; + }; } private BLangExpression createVarCheckConditionForMappingBindingPattern(BLangMappingBindingPattern @@ -6190,9 +6185,12 @@ private BLangRecordLiteral.BLangRecordKeyValueField createRecordKeyValueField(Lo } public void generateFieldsForUserUnspecifiedRecordFields(BLangRecordLiteral recordLiteral, - List userSpecifiedFields) { + List userSpecifiedFields) { BType type = Types.getImpliedType(recordLiteral.getBType()); - if (type.getKind() != TypeKind.RECORD) { + // If we are spreading an open record at compile time we can't determine which fields may be missing. Instead, + // {@code MapValueImpl.populateInitialValues} should fill in any missing fields by calling the default + // closures. + if (type.getKind() != TypeKind.RECORD || isSpreadingAnOpenRecord(userSpecifiedFields)) { return; } List fieldNames = getNamesOfUserSpecifiedRecordFields(userSpecifiedFields); @@ -6202,6 +6200,23 @@ public void generateFieldsForUserUnspecifiedRecordFields(BLangRecordLiteral reco generateFieldsForUserUnspecifiedRecordFields(recordType, userSpecifiedFields, fieldNames, pos, isReadonly); } + private boolean isSpreadingAnOpenRecord(List userSpecifiedFields) { + for (RecordLiteralNode.RecordField field : userSpecifiedFields) { + if (!(field instanceof BLangRecordLiteral.BLangRecordSpreadOperatorField spreadOperatorField)) { + continue; + } + BType type = Types.getReferredType(spreadOperatorField.expr.getBType()); + if (!(type instanceof BRecordType recordType)) { + return true; + } + if (recordType.restFieldType != null && + !types.isNeverTypeOrStructureTypeWithARequiredNeverMember(recordType.restFieldType)) { + return true; + } + } + return false; + } + private void generateFieldsForUserUnspecifiedRecordFields(BRecordType recordType, List fields, List fieldNames, Location pos, @@ -8134,13 +8149,13 @@ public void visit(BLangArrowFunction bLangArrowFunction) { varNode.symbol.kind = SymbolKind.FUNCTION; varNode.symbol.owner = invokableEnv.scope.owner; enclScope.define(varNode.symbol.name, varNode.symbol); - }).map(varNode -> varNode.symbol).collect(Collectors.toList()); + }).map(varNode -> varNode.symbol).toList(); funcSymbol.params = paramSymbols; funcSymbol.restParam = getRestSymbol(funcNode); funcSymbol.retType = funcNode.returnTypeNode.getBType(); // Create function type. - List paramTypes = paramSymbols.stream().map(paramSym -> paramSym.type).collect(Collectors.toList()); + List paramTypes = new ArrayList<>(paramSymbols.stream().map(paramSym -> paramSym.type).toList()); funcNode.setBType(new BInvokableType(paramTypes, getRestType(funcSymbol), funcNode.returnTypeNode.getBType(), funcSymbol.type.tsymbol)); @@ -8443,7 +8458,7 @@ public void visit(BLangWorkerReceive workerReceiveNode) { @Override public void visit(BLangWorkerFlushExpr workerFlushExpr) { workerFlushExpr.workerIdentifierList = workerFlushExpr.cachedWorkerSendStmts - .stream().map(send -> send.workerIdentifier).distinct().collect(Collectors.toList()); + .stream().map(send -> send.workerIdentifier).distinct().toList(); result = workerFlushExpr; } @@ -8825,7 +8840,7 @@ List getVisibleXMLNSStmts(SymbolEnv env) { return nameBXMLNSSymbolMap.keySet().stream() .map(key -> this.stmtsToBePropagatedToQuery.get(key)) .filter(Objects::nonNull) - .collect(Collectors.toList()); + .toList(); } @Override @@ -10055,13 +10070,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; @@ -10347,15 +10362,12 @@ BLangValueType createTypeNode(BType type) { } private BLangValueExpression cloneExpression(BLangExpression expr) { - switch (expr.getKind()) { - case SIMPLE_VARIABLE_REF: - return ASTBuilderUtil.createVariableRef(expr.pos, ((BLangSimpleVarRef) expr).symbol); - case FIELD_BASED_ACCESS_EXPR: - case INDEX_BASED_ACCESS_EXPR: - return cloneAccessExpr((BLangAccessExpression) expr); - default: - throw new IllegalStateException(); - } + return switch (expr.getKind()) { + case SIMPLE_VARIABLE_REF -> ASTBuilderUtil.createVariableRef(expr.pos, ((BLangSimpleVarRef) expr).symbol); + case FIELD_BASED_ACCESS_EXPR, + INDEX_BASED_ACCESS_EXPR -> cloneAccessExpr((BLangAccessExpression) expr); + default -> throw new IllegalStateException(); + }; } private BLangAccessExpression cloneAccessExpr(BLangAccessExpression originalAccessExpr) { @@ -10372,19 +10384,13 @@ private BLangAccessExpression cloneAccessExpr(BLangAccessExpression originalAcce } varRef.setBType(types.getSafeType(originalAccessExpr.expr.getBType(), true, false)); - BLangAccessExpression accessExpr; - switch (originalAccessExpr.getKind()) { - case FIELD_BASED_ACCESS_EXPR: - accessExpr = ASTBuilderUtil.createFieldAccessExpr(varRef, - ((BLangFieldBasedAccess) originalAccessExpr).field); - break; - case INDEX_BASED_ACCESS_EXPR: - accessExpr = ASTBuilderUtil.createIndexAccessExpr(varRef, - ((BLangIndexBasedAccess) originalAccessExpr).indexExpr); - break; - default: - throw new IllegalStateException(); - } + BLangAccessExpression accessExpr = switch (originalAccessExpr.getKind()) { + case FIELD_BASED_ACCESS_EXPR -> ASTBuilderUtil.createFieldAccessExpr(varRef, + ((BLangFieldBasedAccess) originalAccessExpr).field); + case INDEX_BASED_ACCESS_EXPR -> ASTBuilderUtil.createIndexAccessExpr(varRef, + ((BLangIndexBasedAccess) originalAccessExpr).indexExpr); + default -> throw new IllegalStateException(); + }; accessExpr.originalType = originalAccessExpr.originalType; accessExpr.pos = originalAccessExpr.pos; @@ -10509,18 +10515,15 @@ private void visitBinaryLogicalExpr(BLangBinaryExpr binaryExpr) { } protected boolean isMappingOrObjectConstructorOrObjInit(BLangExpression expression) { - switch (expression.getKind()) { - case TYPE_INIT_EXPR: - case RECORD_LITERAL_EXPR: - case OBJECT_CTOR_EXPRESSION: - return true; - case CHECK_EXPR: - return isMappingOrObjectConstructorOrObjInit(((BLangCheckedExpr) expression).expr); - case TYPE_CONVERSION_EXPR: - return isMappingOrObjectConstructorOrObjInit(((BLangTypeConversionExpr) expression).expr); - default: - return false; - } + return switch (expression.getKind()) { + case TYPE_INIT_EXPR, + RECORD_LITERAL_EXPR, + OBJECT_CTOR_EXPRESSION -> true; + case CHECK_EXPR -> isMappingOrObjectConstructorOrObjInit(((BLangCheckedExpr) expression).expr); + case TYPE_CONVERSION_EXPR -> + isMappingOrObjectConstructorOrObjInit(((BLangTypeConversionExpr) expression).expr); + default -> false; + }; } private BType getRestType(BInvokableSymbol invokableSymbol) { diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/QueryDesugar.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/QueryDesugar.java index ae4463de4fde..8c1e94878d25 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/QueryDesugar.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/QueryDesugar.java @@ -365,17 +365,17 @@ private boolean isXml(BType type) { if (TypeTags.isXMLTypeTag(refType.tag)) { return true; } - switch (refType.tag) { - case TypeTags.UNION: + return switch (refType.tag) { + case TypeTags.UNION -> { for (BType memberType : ((BUnionType) refType).getMemberTypes()) { if (!isXml(memberType)) { - return false; + yield false; } } - return true; - default: - return false; - } + yield true; + } + default -> false; + }; } /** @@ -1963,8 +1963,8 @@ public void visit(BLangSimpleVarRef bLangSimpleVarRef) { frameAccessExpr.expr = types.addConversionExprIfRequired(frameAccessExpr.expr, types.getSafeType(frameAccessExpr.expr.getBType(), true, false)); - if (symbol instanceof BVarSymbol) { - ((BVarSymbol) symbol).originalSymbol = null; + if (symbol instanceof BVarSymbol varSymbol) { + varSymbol.originalSymbol = null; if (withinLambdaOrArrowFunc || withinQuery) { if (!withinLambdaOrArrowFunc || symbol.closure) { // When there's a closure in a lambda inside a query lambda the symbol.closure is diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/ServiceDesugar.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/ServiceDesugar.java index 1a811140783b..f5a8a18e74e0 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/ServiceDesugar.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/ServiceDesugar.java @@ -56,7 +56,6 @@ import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; -import java.util.stream.Collectors; import static io.ballerina.runtime.api.constants.RuntimeConstants.UNDERSCORE; @@ -288,8 +287,7 @@ private void addMethodInvocation(Location pos, BLangSimpleVarRef varRef, BInvoka } void engageCustomServiceDesugar(BLangService service, SymbolEnv env) { - List expressionTypes = service.attachedExprs.stream().map(expression -> expression.getBType()) - .collect(Collectors.toList()); + List expressionTypes = service.attachedExprs.stream().map(expression -> expression.getBType()).toList(); service.serviceClass.functions.stream() .filter(fun -> Symbols.isResource(fun.symbol) || Symbols.isRemote(fun.symbol)) .forEach(func -> engageCustomResourceDesugar(func, env, expressionTypes)); diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/diagnostic/BLangDiagnostic.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/diagnostic/BLangDiagnostic.java index 49d72e414cdf..fc049e4a8877 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/diagnostic/BLangDiagnostic.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/diagnostic/BLangDiagnostic.java @@ -102,8 +102,7 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (obj instanceof BLangDiagnostic) { - BLangDiagnostic that = (BLangDiagnostic) obj; + if (obj instanceof BLangDiagnostic that) { if (this.diagnosticCode != null) { return this.location.equals(that.location) && this.msg.equals(that.message()) && this.diagnosticInfo.equals(that.diagnosticInfo) diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/diagnostic/BLangDiagnosticLocation.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/diagnostic/BLangDiagnosticLocation.java index 0071fc877d43..65de23902e81 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/diagnostic/BLangDiagnosticLocation.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/diagnostic/BLangDiagnosticLocation.java @@ -65,8 +65,7 @@ public TextRange textRange() { @Override public boolean equals(Object obj) { - if (obj instanceof BLangDiagnosticLocation) { - BLangDiagnosticLocation location = (BLangDiagnosticLocation) obj; + if (obj instanceof BLangDiagnosticLocation location) { return lineRange().equals(location.lineRange()) && textRange().equals(location.textRange()); } diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/diagnostic/BLangDiagnosticLog.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/diagnostic/BLangDiagnosticLog.java index 443b858d6053..6887ac80ed0d 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/diagnostic/BLangDiagnosticLog.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/diagnostic/BLangDiagnosticLog.java @@ -262,20 +262,19 @@ private List> convertDiagArgsToProps(Object[] args) { List> diagArgs = new ArrayList<>(); for (Object arg : args) { DiagnosticProperty dArg; - if (arg instanceof BType) { - TypeSymbol tsybol = typesFactory.getTypeDescriptor((BType) arg); + if (arg instanceof BType bType) { + TypeSymbol tsybol = typesFactory.getTypeDescriptor(bType); dArg = new BSymbolicProperty(tsybol); - } else if (arg instanceof BSymbol) { - BSymbol symbolArg = (BSymbol) arg; + } else if (arg instanceof BSymbol symbolArg) { Symbol symbol = symbolFactory.getBCompiledSymbol(symbolArg, symbolArg.getOriginalName().getValue()); dArg = new BSymbolicProperty(symbol); - } else if (arg instanceof String) { - dArg = new BStringProperty((String) arg); - } else if (arg instanceof Number) { - dArg = new BNumericProperty((Number) arg); - } else if (arg instanceof Collection) { + } else if (arg instanceof String s) { + dArg = new BStringProperty(s); + } else if (arg instanceof Number n) { + dArg = new BNumericProperty(n); + } else if (arg instanceof Collection collection) { Collection> diagProperties - = convertDiagArgsToProps(((Collection) arg).toArray()); + = convertDiagArgsToProps(collection.toArray()); dArg = new BCollectionProperty(diagProperties); } else { dArg = new NonCatProperty(arg); diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/diagnostic/properties/BCollectionProperty.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/diagnostic/properties/BCollectionProperty.java index 26b9627e29fa..dd569661a645 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/diagnostic/properties/BCollectionProperty.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/diagnostic/properties/BCollectionProperty.java @@ -28,7 +28,7 @@ * * @since Swan Lake */ -public class BCollectionProperty implements DiagnosticProperty { +public class BCollectionProperty implements DiagnosticProperty>> { private final DiagnosticPropertyKind kind; private final Collection> values; @@ -54,8 +54,7 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (obj instanceof BCollectionProperty) { - BCollectionProperty that = (BCollectionProperty) obj; + if (obj instanceof BCollectionProperty that) { return this.kind.equals(that.kind) && this.values.equals(that.values); } return false; diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/diagnostic/properties/BNumericProperty.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/diagnostic/properties/BNumericProperty.java index 516b8b1c1e96..fecba5975a4a 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/diagnostic/properties/BNumericProperty.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/diagnostic/properties/BNumericProperty.java @@ -53,8 +53,7 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (obj instanceof BNumericProperty) { - BNumericProperty that = (BNumericProperty) obj; + if (obj instanceof BNumericProperty that) { return this.kind.equals(that.kind) && this.value.equals(that.value); } return false; diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/diagnostic/properties/BStringProperty.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/diagnostic/properties/BStringProperty.java index de1b37524070..ba078e38cafa 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/diagnostic/properties/BStringProperty.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/diagnostic/properties/BStringProperty.java @@ -53,8 +53,7 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (obj instanceof BStringProperty) { - BStringProperty prop = (BStringProperty) obj; + if (obj instanceof BStringProperty prop) { return this.value.equals(prop.value) && this.kind.equals(prop.kind); } return false; diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/diagnostic/properties/NonCatProperty.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/diagnostic/properties/NonCatProperty.java index 2642d6a70a83..c02e26b0b065 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/diagnostic/properties/NonCatProperty.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/diagnostic/properties/NonCatProperty.java @@ -48,8 +48,7 @@ public Object value() { @Override public boolean equals(Object o) { - if (o instanceof NonCatProperty) { - NonCatProperty that = (NonCatProperty) o; + if (o instanceof NonCatProperty that) { if (kind != that.kind) { return false; } diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/packaging/Patten.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/packaging/Patten.java index a45f2829c983..fad11018d77c 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/packaging/Patten.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/packaging/Patten.java @@ -77,7 +77,7 @@ public Stream convert(Converter converter, PackageID packageID) { } @SuppressWarnings("unchecked") - public Stream convertToSources(Converter converter, PackageID id) { + public Stream convertToSources(Converter converter, PackageID id) { return convert(converter, id).flatMap(t -> converter.finalize(t, id)); } diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/packaging/converters/FilterSearch.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/packaging/converters/FilterSearch.java index a25c0cf4c20c..6ec39ce3a386 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/packaging/converters/FilterSearch.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/packaging/converters/FilterSearch.java @@ -11,8 +11,9 @@ /** * Filters directories. + * @param type of the file visitor */ -class FilterSearch extends SimpleFileVisitor { +class FilterSearch extends SimpleFileVisitor { private final List excludeDir; private List pathList = new ArrayList<>(); diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/packaging/converters/PathConverter.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/packaging/converters/PathConverter.java index c22a1a112574..75f58471bf57 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/packaging/converters/PathConverter.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/packaging/converters/PathConverter.java @@ -107,8 +107,8 @@ public Stream getLatestVersion(Path path, PackageID packageID) { @Override public Stream expandBalWithTest(Path path) { if (Files.isDirectory(path)) { - try { - return Files.find(path, Integer.MAX_VALUE, this::isBalWithTest).sorted(); + try (Stream paths = Files.find(path, Integer.MAX_VALUE, this::isBalWithTest)) { + return paths.sorted(); } catch (IOException ignore) { } } @@ -122,7 +122,7 @@ public Stream expandBal(Path path) { List excludePaths = new ArrayList<>(); excludePaths.add(Paths.get(ProjectDirConstants.TEST_DIR_NAME)); excludePaths.add(Paths.get(ProjectDirConstants.RESOURCE_DIR_NAME)); - FilterSearch filterSearch = new FilterSearch(excludePaths); + FilterSearch filterSearch = new FilterSearch<>(excludePaths); Files.walkFileTree(path, filterSearch); return filterSearch.getPathList().stream().sorted(); } catch (IOException ignore) { diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/packaging/converters/ZipConverter.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/packaging/converters/ZipConverter.java index d359ebc1fc47..cd1068652df9 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/packaging/converters/ZipConverter.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/packaging/converters/ZipConverter.java @@ -84,6 +84,7 @@ private static Path pathWithinZip(URI pathToZip) { return Paths.get(pathToZip); } + @SuppressWarnings("resource") private static void initFS(URI uri) { Map env = new HashMap<>(); env.put("create", "true"); @@ -188,13 +189,15 @@ public static void deleteFiles(Path dirPath) throws IOException { if (dirPath == null) { return; } - Files.walk(dirPath).sorted(Comparator.reverseOrder()).forEach(path -> { - try { - Files.delete(path); - } catch (IOException e) { - // - } - }); + try (Stream paths = Files.walk(dirPath)) { + paths.sorted(Comparator.reverseOrder()).forEach(path -> { + try { + Files.delete(path); + } catch (IOException e) { + // + } + }); + } } /** diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/packaging/repo/HomeBalaRepo.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/packaging/repo/HomeBalaRepo.java index ba7554ef3611..33bdded07ae9 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/packaging/repo/HomeBalaRepo.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/packaging/repo/HomeBalaRepo.java @@ -37,7 +37,6 @@ import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.stream.Collectors; import java.util.stream.Stream; import static org.wso2.ballerinalang.compiler.packaging.Patten.path; @@ -49,14 +48,14 @@ public class HomeBalaRepo implements Repo { private Path repoLocation; private ZipConverter zipConverter; - private List supportedPlatforms = Arrays.stream(SUPPORTED_PLATFORMS).collect(Collectors.toList()); + private List supportedPlatforms = Stream.concat( + Arrays.stream(SUPPORTED_PLATFORMS), Stream.of("any")).toList(); private Map dependencyManifests; public HomeBalaRepo(Map dependencyManifests) { this.repoLocation = RepoUtils.createAndGetHomeReposPath().resolve(ProjectDirConstants.BALA_CACHE_DIR_NAME); this.dependencyManifests = dependencyManifests; this.zipConverter = new ZipConverter(this.repoLocation); - supportedPlatforms.add("any"); } @Override @@ -156,13 +155,14 @@ private Path findBalaPath(Path repoLocation, String orgName, String pkgName, Str Path balaFilePath = this.repoLocation.resolve(orgName).resolve(pkgName).resolve(versionStr); // try to find a compatible bala file if (Files.exists(balaFilePath)) { - Stream list = Files.list(balaFilePath); - PathMatcher pathMatcher = balaFilePath.getFileSystem() - .getPathMatcher("glob:**/" + pkgName + "-*-" + - platform + "-" + versionStr + ".bala"); - for (Path file : (Iterable) list::iterator) { - if (pathMatcher.matches(file)) { - return file; + try (Stream list = Files.list(balaFilePath)) { + PathMatcher pathMatcher = balaFilePath.getFileSystem() + .getPathMatcher("glob:**/" + pkgName + "-*-" + + platform + "-" + versionStr + ".bala"); + for (Path file : (Iterable) list::iterator) { + if (pathMatcher.matches(file)) { + return file; + } } } } diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/parser/BLangAnonymousModelHelper.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/parser/BLangAnonymousModelHelper.java index 6d1830a9f340..59dae677cb68 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/parser/BLangAnonymousModelHelper.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/parser/BLangAnonymousModelHelper.java @@ -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; @@ -101,17 +101,17 @@ public String getNextAnonymousTypeKey(PackageID packageID) { return ANON_TYPE + UNDERSCORE + nextValue; } - public String getNextAnonymousTypeKey(PackageID packageID, Stack suffixes) { + public String getNextAnonymousTypeKey(PackageID packageID, Collection suffixes) { if (suffixes.isEmpty()) { return getNextAnonymousTypeKey(packageID); } return createAnonTypeName(suffixes, packageID); } - private String createAnonTypeName(Stack suffixes, PackageID pkgId) { + private String createAnonTypeName(Collection 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 anonTypesNames = anonTypesNamesPerPkg.computeIfAbsent(pkgId, key -> new HashMap<>()); String nameStr = name.toString(); diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/parser/BLangNodeBuilder.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/parser/BLangNodeBuilder.java index 58d576a52fb0..600a0e42ac1a 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/parser/BLangNodeBuilder.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/parser/BLangNodeBuilder.java @@ -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; @@ -539,8 +540,8 @@ public class BLangNodeBuilder extends NodeTransformer { private BLangMissingNodesHelper missingNodesHelper; /* To keep track of additional statements produced from multi-BLangNode resultant transformations */ - private Stack additionalStatements = new Stack<>(); - private final Stack anonTypeNameSuffixes = new Stack<>(); + private Deque additionalStatements = new ArrayDeque<>(); + private final Deque 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 */ @@ -566,7 +567,7 @@ public List accept(Node node) { BLangNode bLangNode = node.apply(this); List nodes = new ArrayList<>(); // if not already consumed, add left-over statements - while (!additionalStatements.empty()) { + while (!additionalStatements.isEmpty()) { nodes.add(additionalStatements.pop()); } nodes.add(bLangNode); @@ -1158,15 +1159,11 @@ public BLangNode transform(ParameterizedTypeDescriptorNode parameterizedTypeDesc } private TypeKind getParameterizedTypeKind(SyntaxKind syntaxKind) { - switch (syntaxKind) { - case TYPEDESC_TYPE_DESC: - return TypeKind.TYPEDESC; - case FUTURE_TYPE_DESC: - return TypeKind.FUTURE; - case XML_TYPE_DESC: - default: - return TypeKind.XML; - } + return switch (syntaxKind) { + case TYPEDESC_TYPE_DESC -> TypeKind.TYPEDESC; + case FUTURE_TYPE_DESC -> TypeKind.FUTURE; + default -> TypeKind.XML; + }; } private BLangNode transformErrorTypeDescriptor(ParameterizedTypeDescriptorNode parameterizedTypeDescNode) { @@ -1314,7 +1311,7 @@ public BLangClassDefinition transformObjectCtorExpressionBody(NodeList mem } else if (nodeKind == NodeKind.VARIABLE) { BLangSimpleVariable simpleVariable = (BLangSimpleVariable) bLangNode; simpleVariable.flagSet.add(Flag.OBJECT_CTOR); - classDefinition.addField((BLangSimpleVariable) bLangNode); + classDefinition.addField(simpleVariable); } else if (nodeKind == NodeKind.USER_DEFINED_TYPE) { dlog.error(bLangNode.pos, DiagnosticErrorCode.OBJECT_CTOR_DOES_NOT_SUPPORT_TYPE_REFERENCE_MEMBERS); } @@ -1681,7 +1678,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()); } } @@ -1963,18 +1960,13 @@ public BLangNode transform(AnnotationDeclarationNode annotationDeclarationNode) switch (firstIndent.kind()) { case OBJECT_KEYWORD: Token secondIndent = idents.get(1); - switch (secondIndent.kind()) { - case FUNCTION_KEYWORD: - bLAttachPoint = - AttachPoint.getAttachmentPoint(AttachPoint.Point.OBJECT_METHOD.getValue(), source); - break; - case FIELD_KEYWORD: - bLAttachPoint = - AttachPoint.getAttachmentPoint(AttachPoint.Point.OBJECT_FIELD.getValue(), source); - break; - default: - throw new RuntimeException("Syntax kind is not supported: " + secondIndent.kind()); - } + bLAttachPoint = switch (secondIndent.kind()) { + case FUNCTION_KEYWORD -> + AttachPoint.getAttachmentPoint(AttachPoint.Point.OBJECT_METHOD.getValue(), source); + case FIELD_KEYWORD -> + AttachPoint.getAttachmentPoint(AttachPoint.Point.OBJECT_FIELD.getValue(), source); + default -> throw new RuntimeException("Syntax kind is not supported: " + secondIndent.kind()); + }; break; case SERVICE_KEYWORD: String value; @@ -2429,54 +2421,50 @@ public BLangTypeConversionExpr transform(TypeCastExpressionNode typeCastExpressi @Override public BLangNode transform(Token token) { SyntaxKind kind = token.kind(); - switch (kind) { - case XML_TEXT_CONTENT: - case TEMPLATE_STRING: - case CLOSE_BRACE_TOKEN: - return createSimpleLiteral(token); - default: + return switch (kind) { + case XML_TEXT_CONTENT, TEMPLATE_STRING, CLOSE_BRACE_TOKEN -> createSimpleLiteral(token); + default -> { if (isTokenInRegExp(kind)) { - return createSimpleLiteral(token); + yield createSimpleLiteral(token); } throw new RuntimeException("Syntax kind is not supported: " + kind); - } + } + }; } private boolean isTokenInRegExp(SyntaxKind kind) { - switch (kind) { - case RE_LITERAL_CHAR: - case RE_CONTROL_ESCAPE: - case RE_NUMERIC_ESCAPE: - case RE_SIMPLE_CHAR_CLASS_CODE: - case RE_PROPERTY: - case RE_UNICODE_SCRIPT_START: - case RE_UNICODE_PROPERTY_VALUE: - case RE_UNICODE_GENERAL_CATEGORY_START: - case RE_UNICODE_GENERAL_CATEGORY_NAME: - case RE_FLAGS_VALUE: - case DIGIT: - case ASTERISK_TOKEN: - case PLUS_TOKEN: - case QUESTION_MARK_TOKEN: - case DOT_TOKEN: - case OPEN_BRACE_TOKEN: - case CLOSE_BRACE_TOKEN: - case OPEN_BRACKET_TOKEN: - case CLOSE_BRACKET_TOKEN: - case OPEN_PAREN_TOKEN: - case CLOSE_PAREN_TOKEN: - case DOLLAR_TOKEN: - case BITWISE_XOR_TOKEN: - case COLON_TOKEN: - case BACK_SLASH_TOKEN: - case MINUS_TOKEN: - case ESCAPED_MINUS_TOKEN: - case PIPE_TOKEN: - case COMMA_TOKEN: - return true; - default: - return false; - } + return switch (kind) { + case RE_LITERAL_CHAR, + RE_CONTROL_ESCAPE, + RE_NUMERIC_ESCAPE, + RE_SIMPLE_CHAR_CLASS_CODE, + RE_PROPERTY, + RE_UNICODE_SCRIPT_START, + RE_UNICODE_PROPERTY_VALUE, + RE_UNICODE_GENERAL_CATEGORY_START, + RE_UNICODE_GENERAL_CATEGORY_NAME, + RE_FLAGS_VALUE, + DIGIT, + ASTERISK_TOKEN, + PLUS_TOKEN, + QUESTION_MARK_TOKEN, + DOT_TOKEN, + OPEN_BRACE_TOKEN, + CLOSE_BRACE_TOKEN, + OPEN_BRACKET_TOKEN, + CLOSE_BRACKET_TOKEN, + OPEN_PAREN_TOKEN, + CLOSE_PAREN_TOKEN, + DOLLAR_TOKEN, + BITWISE_XOR_TOKEN, + COLON_TOKEN, + BACK_SLASH_TOKEN, + MINUS_TOKEN, + ESCAPED_MINUS_TOKEN, + PIPE_TOKEN, + COMMA_TOKEN -> true; + default -> false; + }; } @Override @@ -2698,8 +2686,7 @@ public BLangNode transform(MappingBindingPatternNode mappingBindingPatternNode) private BLangRecordVarRefKeyValue createRecordVarKeyValue(BindingPatternNode expr) { BLangRecordVarRefKeyValue keyValue = new BLangRecordVarRefKeyValue(); - if (expr instanceof FieldBindingPatternFullNode) { - FieldBindingPatternFullNode fullNode = (FieldBindingPatternFullNode) expr; + if (expr instanceof FieldBindingPatternFullNode fullNode) { keyValue.variableName = createIdentifier(fullNode.variableName().name()); keyValue.variableReference = createExpression(fullNode.bindingPattern()); } else { @@ -3912,8 +3899,7 @@ public BLangConstant transformEnumMember(EnumMemberNode member, Boolean publicQu typeNode.typeKind = TypeKind.STRING; bLangConstant.setTypeNode(typeNode); - if (deepLiteral instanceof BLangLiteral) { - BLangLiteral literal = (BLangLiteral) deepLiteral; + if (deepLiteral instanceof BLangLiteral literal) { if (!literal.originalValue.isEmpty()) { BLangFiniteTypeNode typeNodeAssociated = (BLangFiniteTypeNode) TreeBuilder.createFiniteTypeNode(); literal.originalValue = null; @@ -4446,14 +4432,11 @@ public BLangNode transform(XMLStepExpressionNode xmlStepExpressionNode) { for (Node node : xmlNamePatternChainingNode.xmlNamePattern()) { filters.add(createXMLElementFilter(node)); } - switch (xmlNamePatternChainingNode.startToken().kind()) { - case DOUBLE_SLASH_DOUBLE_ASTERISK_LT_TOKEN: - starCount = 2; - break; - case SLASH_ASTERISK_TOKEN: - starCount = 1; - break; - } + starCount = switch (xmlNamePatternChainingNode.startToken().kind()) { + case DOUBLE_SLASH_DOUBLE_ASTERISK_LT_TOKEN -> 2; + case SLASH_ASTERISK_TOKEN -> 1; + default -> starCount; + }; } BLangExpression expr = createExpression(xmlStepExpressionNode.expression()); @@ -4841,26 +4824,22 @@ private BLangFieldMatchPattern transformFieldMatchPattern(FieldMatchPatternNode private BLangBindingPattern transformBindingPattern(Node bindingPattern) { Location pos = getPosition(bindingPattern); SyntaxKind patternKind = bindingPattern.kind(); - switch (patternKind) { - case CAPTURE_BINDING_PATTERN: - return transformCaptureBindingPattern((CaptureBindingPatternNode) bindingPattern, pos); - case LIST_BINDING_PATTERN: - return transformListBindingPattern((ListBindingPatternNode) bindingPattern, pos); - case NAMED_ARG_BINDING_PATTERN: - return transformNamedArgBindingPattern((NamedArgBindingPatternNode) bindingPattern, pos); - case REST_BINDING_PATTERN: - return transformRestBindingPattern((RestBindingPatternNode) bindingPattern, pos); - case MAPPING_BINDING_PATTERN: - return transformMappingBindingPattern((MappingBindingPatternNode) bindingPattern, pos); - case FIELD_BINDING_PATTERN: - return transformFieldBindingPattern(bindingPattern, pos); - case ERROR_BINDING_PATTERN: - return transformErrorBindingPattern((ErrorBindingPatternNode) bindingPattern, pos); - case WILDCARD_BINDING_PATTERN: - default: + return switch (patternKind) { + case CAPTURE_BINDING_PATTERN -> + transformCaptureBindingPattern((CaptureBindingPatternNode) bindingPattern, pos); + case LIST_BINDING_PATTERN -> transformListBindingPattern((ListBindingPatternNode) bindingPattern, pos); + case NAMED_ARG_BINDING_PATTERN -> + transformNamedArgBindingPattern((NamedArgBindingPatternNode) bindingPattern, pos); + case REST_BINDING_PATTERN -> transformRestBindingPattern((RestBindingPatternNode) bindingPattern, pos); + case MAPPING_BINDING_PATTERN -> + transformMappingBindingPattern((MappingBindingPatternNode) bindingPattern, pos); + case FIELD_BINDING_PATTERN -> transformFieldBindingPattern(bindingPattern, pos); + case ERROR_BINDING_PATTERN -> transformErrorBindingPattern((ErrorBindingPatternNode) bindingPattern, pos); + default -> { assert patternKind == SyntaxKind.WILDCARD_BINDING_PATTERN; - return transformWildCardBindingPattern(pos); - } + yield transformWildCardBindingPattern(pos); + } + }; } private BLangWildCardBindingPattern transformWildCardBindingPattern(Location pos) { @@ -4929,9 +4908,7 @@ private BLangFieldBindingPattern transformFieldBindingPattern(Node bindingPatter BLangFieldBindingPattern bLangFieldBindingPattern = (BLangFieldBindingPattern) TreeBuilder.createFieldBindingPattern(); bLangFieldBindingPattern.pos = pos; - if (bindingPattern instanceof FieldBindingPatternVarnameNode) { - FieldBindingPatternVarnameNode fieldBindingPatternVarnameNode = - (FieldBindingPatternVarnameNode) bindingPattern; + if (bindingPattern instanceof FieldBindingPatternVarnameNode fieldBindingPatternVarnameNode) { BLangIdentifier fieldName = createIdentifier(fieldBindingPatternVarnameNode.variableName().name()); bLangFieldBindingPattern.fieldName = fieldName; BLangCaptureBindingPattern bLangCaptureBindingPatternInFieldBindingPattern = @@ -5219,13 +5196,11 @@ private BLangRecordVariable createBLangRecordVariable(MappingBindingPatternNode for (BindingPatternNode node : mappingBindingPatternNode.fieldBindingPatterns()) { BLangRecordVariableKeyValue recordKeyValue = new BLangRecordVariableKeyValue(); - if (node instanceof FieldBindingPatternFullNode) { - FieldBindingPatternFullNode fullNode = (FieldBindingPatternFullNode) node; + if (node instanceof FieldBindingPatternFullNode fullNode) { recordKeyValue.key = createIdentifier(fullNode.variableName().name()); recordKeyValue.valueBindingPattern = getBLangVariableNode(fullNode.bindingPattern(), getPosition(fullNode.bindingPattern())); - } else if (node instanceof FieldBindingPatternVarnameNode) { - FieldBindingPatternVarnameNode varnameNode = (FieldBindingPatternVarnameNode) node; + } else if (node instanceof FieldBindingPatternVarnameNode varnameNode) { recordKeyValue.key = createIdentifier(varnameNode.variableName().name()); BLangSimpleVariable value = (BLangSimpleVariable) TreeBuilder.createSimpleVariableNode(); value.pos = getPosition(varnameNode); @@ -5439,7 +5414,7 @@ private void generateForkStatements(List statements, ForkStateme function.anonForkName = nextAnonymousForkKey; statements.add(workerDef); - while (!this.additionalStatements.empty()) { + while (!this.additionalStatements.isEmpty()) { statements.add(additionalStatements.pop()); } forkJoin.addWorkers(workerDef); @@ -6124,10 +6099,10 @@ private BLangLiteral createSimpleLiteral(Node literal, boolean isFiniteType) { String originalValue = null; String textValue; - if (literal instanceof BasicLiteralNode) { - textValue = ((BasicLiteralNode) literal).literalToken().text(); - } else if (literal instanceof Token) { - textValue = ((Token) literal).text(); + if (literal instanceof BasicLiteralNode basicLiteralNode) { + textValue = basicLiteralNode.literalToken().text(); + } else if (literal instanceof Token token) { + textValue = token.text(); } else { textValue = ""; } @@ -6310,8 +6285,7 @@ private BLangType createBuiltInTypeNode(Node type) { String typeText; if (type.kind() == SyntaxKind.NIL_TYPE_DESC) { typeText = "()"; - } else if (type instanceof BuiltinSimpleNameReferenceNode) { - BuiltinSimpleNameReferenceNode simpleNameRef = (BuiltinSimpleNameReferenceNode) type; + } else if (type instanceof BuiltinSimpleNameReferenceNode simpleNameRef) { if (simpleNameRef.kind() == SyntaxKind.VAR_TYPE_DESC) { return null; } else if (simpleNameRef.name().isMissing()) { @@ -6665,28 +6639,18 @@ private void transformDocumentationBacktickContent(Node backtickContent, } private DocumentationReferenceType stringToRefType(String refTypeName) { - switch (refTypeName) { - case "type": - return DocumentationReferenceType.TYPE; - case "service": - return DocumentationReferenceType.SERVICE; - case "variable": - return DocumentationReferenceType.VARIABLE; - case "var": - return DocumentationReferenceType.VAR; - case "annotation": - return DocumentationReferenceType.ANNOTATION; - case "module": - return DocumentationReferenceType.MODULE; - case "function": - return DocumentationReferenceType.FUNCTION; - case "parameter": - return DocumentationReferenceType.PARAMETER; - case "const": - return DocumentationReferenceType.CONST; - default: - return DocumentationReferenceType.BACKTICK_CONTENT; - } + return switch (refTypeName) { + case "type" -> DocumentationReferenceType.TYPE; + case "service" -> DocumentationReferenceType.SERVICE; + case "variable" -> DocumentationReferenceType.VARIABLE; + case "var" -> DocumentationReferenceType.VAR; + case "annotation" -> DocumentationReferenceType.ANNOTATION; + case "module" -> DocumentationReferenceType.MODULE; + case "function" -> DocumentationReferenceType.FUNCTION; + case "parameter" -> DocumentationReferenceType.PARAMETER; + case "const" -> DocumentationReferenceType.CONST; + default -> DocumentationReferenceType.BACKTICK_CONTENT; + }; } private Object getIntegerLiteral(Node literal, String nodeValue) { @@ -6775,56 +6739,48 @@ private void markVariableWithFlag(BLangVariable variable, Flag flag) { } private boolean isSimpleLiteral(SyntaxKind syntaxKind) { - switch (syntaxKind) { - case STRING_LITERAL: - case NUMERIC_LITERAL: - case BOOLEAN_LITERAL: - case NIL_LITERAL: - case NULL_LITERAL: - return true; - default: - return false; - } + return switch (syntaxKind) { + case STRING_LITERAL, NUMERIC_LITERAL, BOOLEAN_LITERAL, NIL_LITERAL, NULL_LITERAL -> true; + default -> false; + }; } static boolean isType(SyntaxKind nodeKind) { - switch (nodeKind) { - case RECORD_TYPE_DESC: - case OBJECT_TYPE_DESC: - case NIL_TYPE_DESC: - case OPTIONAL_TYPE_DESC: - case ARRAY_TYPE_DESC: - case INT_TYPE_DESC: - case BYTE_TYPE_DESC: - case FLOAT_TYPE_DESC: - case DECIMAL_TYPE_DESC: - case STRING_TYPE_DESC: - case BOOLEAN_TYPE_DESC: - case XML_TYPE_DESC: - case JSON_TYPE_DESC: - case HANDLE_TYPE_DESC: - case ANY_TYPE_DESC: - case ANYDATA_TYPE_DESC: - case NEVER_TYPE_DESC: - case VAR_TYPE_DESC: - case SERVICE_TYPE_DESC: - case MAP_TYPE_DESC: - case UNION_TYPE_DESC: - case ERROR_TYPE_DESC: - case STREAM_TYPE_DESC: - case TABLE_TYPE_DESC: - case FUNCTION_TYPE_DESC: - case TUPLE_TYPE_DESC: - case PARENTHESISED_TYPE_DESC: - case READONLY_TYPE_DESC: - case DISTINCT_TYPE_DESC: - case INTERSECTION_TYPE_DESC: - case SINGLETON_TYPE_DESC: - case TYPE_REFERENCE_TYPE_DESC: - return true; - default: - return false; - } + return switch (nodeKind) { + case RECORD_TYPE_DESC, + OBJECT_TYPE_DESC, + NIL_TYPE_DESC, + OPTIONAL_TYPE_DESC, + ARRAY_TYPE_DESC, + INT_TYPE_DESC, + BYTE_TYPE_DESC, + FLOAT_TYPE_DESC, + DECIMAL_TYPE_DESC, + STRING_TYPE_DESC, + BOOLEAN_TYPE_DESC, + XML_TYPE_DESC, + JSON_TYPE_DESC, + HANDLE_TYPE_DESC, + ANY_TYPE_DESC, + ANYDATA_TYPE_DESC, + NEVER_TYPE_DESC, + VAR_TYPE_DESC, + SERVICE_TYPE_DESC, + MAP_TYPE_DESC, + UNION_TYPE_DESC, + ERROR_TYPE_DESC, + STREAM_TYPE_DESC, + TABLE_TYPE_DESC, + FUNCTION_TYPE_DESC, + TUPLE_TYPE_DESC, + PARENTHESISED_TYPE_DESC, + READONLY_TYPE_DESC, + DISTINCT_TYPE_DESC, + INTERSECTION_TYPE_DESC, + SINGLETON_TYPE_DESC, + TYPE_REFERENCE_TYPE_DESC -> true; + default -> false; + }; } private boolean isInTypeDefinitionContext(Node parent) { @@ -6838,12 +6794,10 @@ private boolean isInTypeDefinitionContext(Node parent) { } private boolean isNumericLiteral(SyntaxKind syntaxKind) { - switch (syntaxKind) { - case NUMERIC_LITERAL: - return true; - default: - return false; - } + return switch (syntaxKind) { + case NUMERIC_LITERAL -> true; + default -> false; + }; } private boolean isPresent(Node node) { @@ -6908,8 +6862,8 @@ private BLangListConstructorSpreadOpExpr createSpreadMemberExpr(Node expr, Locat } private boolean withinByteRange(Object num) { - if (num instanceof Long) { - return (Long) num <= 255 && (Long) num >= 0; + if (num instanceof Long l) { + return l <= 255 && l >= 0; } return false; } diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/parser/NodeCloner.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/parser/NodeCloner.java index c0abeca2c33f..3af5789cb94c 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/parser/NodeCloner.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/parser/NodeCloner.java @@ -1146,9 +1146,9 @@ public void visit(BLangSimpleVarRef source) { BLangSimpleVarRef clone; - if (source instanceof BLangRecordVarNameField) { + if (source instanceof BLangRecordVarNameField recordVarNameField) { BLangRecordVarNameField clonedVarNameField = new BLangRecordVarNameField(); - clonedVarNameField.readonly = ((BLangRecordVarNameField) source).readonly; + clonedVarNameField.readonly = recordVarNameField.readonly; clone = clonedVarNameField; } else { clone = new BLangSimpleVarRef(); diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/CodeAnalyzer.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/CodeAnalyzer.java index 65013f106aa7..4edbc78127c4 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/CodeAnalyzer.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/CodeAnalyzer.java @@ -252,8 +252,10 @@ import org.wso2.ballerinalang.compiler.util.TypeTags; import org.wso2.ballerinalang.util.Flags; +import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Comparator; +import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; @@ -263,9 +265,8 @@ import java.util.Map; import java.util.Objects; import java.util.Set; -import java.util.Stack; import java.util.function.Predicate; -import java.util.stream.Collectors; +import java.util.stream.Stream; import static org.ballerinalang.model.tree.NodeKind.LITERAL; import static org.ballerinalang.util.BLangCompilerConstants.RETRY_MANAGER_OBJECT_SHOULD_RETRY_FUNC; @@ -340,6 +341,9 @@ public void visit(BLangTestablePackage node, AnalyzerData data) { private void analyzeTopLevelNodes(BLangPackage pkgNode, AnalyzerData data) { List topLevelNodes = pkgNode.topLevelNodes; + + // topLevelNodes are modified while iterating over them + // noinspection ForLoopReplaceableByForEach for (int i = 0; i < topLevelNodes.size(); i++) { analyzeNode((BLangNode) topLevelNodes.get(i), data); } @@ -646,12 +650,12 @@ public void visit(BLangRollback rollbackNode, AnalyzerData data) { this.dlog.error(rollbackNode.pos, DiagnosticErrorCode.ROLLBACK_CANNOT_BE_OUTSIDE_TRANSACTION_BLOCK); return; } - if (!data.transactionalFuncCheckStack.empty() && data.transactionalFuncCheckStack.peek()) { + if (!data.transactionalFuncCheckStack.isEmpty() && data.transactionalFuncCheckStack.peek()) { this.dlog.error(rollbackNode.pos, DiagnosticErrorCode.ROLLBACK_CANNOT_BE_WITHIN_TRANSACTIONAL_FUNCTION); return; } if (!data.withinTransactionScope || !data.commitRollbackAllowed || - (!data.loopWithinTransactionCheckStack.empty() && data.loopWithinTransactionCheckStack.peek())) { + (!data.loopWithinTransactionCheckStack.isEmpty() && data.loopWithinTransactionCheckStack.peek())) { this.dlog.error(rollbackNode.pos, DiagnosticErrorCode.ROLLBACK_NOT_ALLOWED); return; } @@ -875,29 +879,22 @@ private boolean checkSimilarMatchPatterns(BLangMatchPattern firstPattern, BLangM return false; } - switch (firstPatternKind) { - case WILDCARD_MATCH_PATTERN: - case REST_MATCH_PATTERN: - return true; - case CONST_MATCH_PATTERN: - return checkSimilarConstMatchPattern((BLangConstPattern) firstPattern, - (BLangConstPattern) secondPattern); - case VAR_BINDING_PATTERN_MATCH_PATTERN: - return checkSimilarBindingPatterns( - ((BLangVarBindingPatternMatchPattern) firstPattern).getBindingPattern(), - ((BLangVarBindingPatternMatchPattern) secondPattern).getBindingPattern()); - case LIST_MATCH_PATTERN: - return checkSimilarListMatchPattern((BLangListMatchPattern) firstPattern, - (BLangListMatchPattern) secondPattern); - case MAPPING_MATCH_PATTERN: - return checkSimilarMappingMatchPattern((BLangMappingMatchPattern) firstPattern, - (BLangMappingMatchPattern) secondPattern); - case ERROR_MATCH_PATTERN: - return checkSimilarErrorMatchPattern((BLangErrorMatchPattern) firstPattern, - (BLangErrorMatchPattern) secondPattern); - default: - return false; - } + return switch (firstPatternKind) { + case WILDCARD_MATCH_PATTERN, + REST_MATCH_PATTERN -> true; + case CONST_MATCH_PATTERN -> checkSimilarConstMatchPattern((BLangConstPattern) firstPattern, + (BLangConstPattern) secondPattern); + case VAR_BINDING_PATTERN_MATCH_PATTERN -> checkSimilarBindingPatterns( + ((BLangVarBindingPatternMatchPattern) firstPattern).getBindingPattern(), + ((BLangVarBindingPatternMatchPattern) secondPattern).getBindingPattern()); + case LIST_MATCH_PATTERN -> checkSimilarListMatchPattern((BLangListMatchPattern) firstPattern, + (BLangListMatchPattern) secondPattern); + case MAPPING_MATCH_PATTERN -> checkSimilarMappingMatchPattern((BLangMappingMatchPattern) firstPattern, + (BLangMappingMatchPattern) secondPattern); + case ERROR_MATCH_PATTERN -> checkSimilarErrorMatchPattern((BLangErrorMatchPattern) firstPattern, + (BLangErrorMatchPattern) secondPattern); + default -> false; + }; } private boolean checkEmptyListOrMapMatchWithVarBindingPatternMatch(BLangMatchPattern firstPattern, @@ -1159,23 +1156,20 @@ private boolean checkSimilarBindingPatterns(BLangBindingPattern firstBidingPatte return false; } - switch (firstBindingPatternKind) { - case WILDCARD_BINDING_PATTERN: - case REST_BINDING_PATTERN: - case CAPTURE_BINDING_PATTERN: - return true; - case LIST_BINDING_PATTERN: - return checkSimilarListBindingPatterns((BLangListBindingPattern) firstBidingPattern, - (BLangListBindingPattern) secondBindingPattern); - case MAPPING_BINDING_PATTERN: - return checkSimilarMappingBindingPattern((BLangMappingBindingPattern) firstBidingPattern, - (BLangMappingBindingPattern) secondBindingPattern); - case ERROR_BINDING_PATTERN: - return checkSimilarErrorBindingPatterns((BLangErrorBindingPattern) firstBidingPattern, - (BLangErrorBindingPattern) secondBindingPattern); - default: - return false; - } + return switch (firstBindingPatternKind) { + case WILDCARD_BINDING_PATTERN, + REST_BINDING_PATTERN, + CAPTURE_BINDING_PATTERN -> true; + case LIST_BINDING_PATTERN -> checkSimilarListBindingPatterns((BLangListBindingPattern) firstBidingPattern, + (BLangListBindingPattern) secondBindingPattern); + case MAPPING_BINDING_PATTERN -> + checkSimilarMappingBindingPattern((BLangMappingBindingPattern) firstBidingPattern, + (BLangMappingBindingPattern) secondBindingPattern); + case ERROR_BINDING_PATTERN -> + checkSimilarErrorBindingPatterns((BLangErrorBindingPattern) firstBidingPattern, + (BLangErrorBindingPattern) secondBindingPattern); + default -> false; + }; } private boolean checkSimilarMappingBindingPattern(BLangMappingBindingPattern firstMappingBindingPattern, @@ -1432,27 +1426,27 @@ public void visit(BLangListMatchPattern listMatchPattern, AnalyzerData data) { } private boolean isConstMatchPatternExist(BLangMatchPattern matchPattern) { - switch (matchPattern.getKind()) { - case CONST_MATCH_PATTERN: - return true; - case LIST_MATCH_PATTERN: + return switch (matchPattern.getKind()) { + case CONST_MATCH_PATTERN -> true; + case LIST_MATCH_PATTERN -> { for (BLangMatchPattern memberMatchPattern : ((BLangListMatchPattern) matchPattern).matchPatterns) { if (isConstMatchPatternExist(memberMatchPattern)) { - return true; + yield true; } } - return false; - case MAPPING_MATCH_PATTERN: + yield false; + } + case MAPPING_MATCH_PATTERN -> { for (BLangFieldMatchPattern fieldMatchPattern : ((BLangMappingMatchPattern) matchPattern).fieldMatchPatterns) { if (isConstMatchPatternExist(fieldMatchPattern.matchPattern)) { - return true; + yield true; } } - return false; - default: - return false; - } + yield false; + } + default -> false; + }; } @Override @@ -1752,17 +1746,14 @@ private boolean isValidInferredArray(BLangNode node) { } private boolean isValidContextForInferredArray(BLangNode node) { - switch (node.getKind()) { - case PACKAGE: - case EXPR_FUNCTION_BODY: - case BLOCK_FUNCTION_BODY: - case BLOCK: - return true; - case VARIABLE_DEF: - return isValidContextForInferredArray(node.parent); - default: - return false; - } + return switch (node.getKind()) { + case PACKAGE, + EXPR_FUNCTION_BODY, + BLOCK_FUNCTION_BODY, + BLOCK -> true; + case VARIABLE_DEF -> isValidContextForInferredArray(node.parent); + default -> false; + }; } private boolean isValidVariableForInferredArray(BLangNode node) { @@ -1899,12 +1890,9 @@ private void checkDuplicateVarRefs(List varRefs, Set s } private List getVarRefs(BLangRecordVarRef varRef) { - List varRefs = varRef.recordRefFields.stream() - .map(e -> e.variableReference).collect(Collectors.toList()); - if (varRef.restParam != null) { - varRefs.add(varRef.restParam); - } - return varRefs; + return Stream.concat( + varRef.recordRefFields.stream().map(e -> e.variableReference), + Stream.ofNullable(varRef.restParam)).toList(); } private List getVarRefs(BLangErrorVarRef varRef) { @@ -2906,14 +2894,14 @@ public void visit(BLangWorkerFlushExpr workerFlushExpr, AnalyzerData data) { // 1) flush w1 -> Wait till all the asynchronous sends to worker w1 is completed // 2) flush -> Wait till all asynchronous sends to all workers are completed BLangIdentifier flushWrkIdentifier = workerFlushExpr.workerIdentifier; - Stack workerActionSystems = data.workerActionSystemStack; + Deque workerActionSystems = data.workerActionSystemStack; WorkerActionSystem currentWrkerAction = workerActionSystems.peek(); List sendStmts = getAsyncSendStmtsOfWorker(currentWrkerAction); if (flushWrkIdentifier != null) { List sendsToGivenWrkr = sendStmts.stream() .filter(bLangNode -> bLangNode.workerIdentifier.equals (flushWrkIdentifier)) - .collect(Collectors.toList()); + .toList(); if (sendsToGivenWrkr.isEmpty()) { this.dlog.error(workerFlushExpr.pos, DiagnosticErrorCode.INVALID_WORKER_FLUSH_FOR_WORKER, workerFlushExpr.workerSymbol, currentWrkerAction.currentWorkerId()); @@ -2937,7 +2925,7 @@ private List getAsyncSendStmtsOfWorker(WorkerActionSys return actions.stream() .filter(CodeAnalyzer::isWorkerSend) .map(bLangNode -> (BLangWorkerAsyncSendExpr) bLangNode) - .collect(Collectors.toList()); + .toList(); } @Override public void visit(BLangTrapExpr trapExpr, AnalyzerData data) { @@ -3684,8 +3672,8 @@ private void checkAccessSymbol(BSymbol symbol, PackageID pkgID, Location positio } private void analyzeExprs(List nodeList, AnalyzerData data) { - for (int i = 0; i < nodeList.size(); i++) { - analyzeExpr(nodeList.get(i), data); + for (E e : nodeList) { + analyzeExpr(e, data); } } @@ -3850,8 +3838,7 @@ private boolean validateWorkerInteractionsAfterWaitAction(WorkerActionSystem wor Set waitingOnWorkerSet = new HashSet<>(); for (BLangNode action : worker.actions) { if (isWaitAction(action)) { - if (action instanceof BLangWaitForAllExpr) { - BLangWaitForAllExpr waitForAllExpr = (BLangWaitForAllExpr) action; + if (action instanceof BLangWaitForAllExpr waitForAllExpr) { for (BLangWaitForAllExpr.BLangWaitKeyValue keyValuePair : waitForAllExpr.keyValuePairs) { BSymbol workerSymbol = getWorkerSymbol(keyValuePair); if (workerSymbol != null) { @@ -3891,9 +3878,8 @@ private boolean validateWorkerInteractionsAfterWaitAction(WorkerActionSystem wor private void handleWaitAction(WorkerActionSystem workerActionSystem, BLangNode currentAction, WorkerActionStateMachine worker, AnalyzerData data) { - if (currentAction instanceof BLangWaitForAllExpr) { + if (currentAction instanceof BLangWaitForAllExpr waitForAllExpr) { boolean allWorkersAreDone = true; - BLangWaitForAllExpr waitForAllExpr = (BLangWaitForAllExpr) currentAction; for (BLangWaitForAllExpr.BLangWaitKeyValue keyValuePair : waitForAllExpr.keyValuePairs) { BSymbol workerSymbol = getWorkerSymbol(keyValuePair); if (isWorkerSymbol(workerSymbol)) { @@ -4171,7 +4157,7 @@ private static class WorkerActionSystem { public final List alternateWorkerReceives = new ArrayList<>(); public List finshedWorkers = new ArrayList<>(); - private Stack workerActionStateMachines = new Stack<>(); + private Deque workerActionStateMachines = new ArrayDeque<>(); private Map workerInteractionEnvironments = new IdentityHashMap<>(); private Map workerEventIndexMap = new HashMap<>(); private boolean hasErrors = false; @@ -4426,7 +4412,7 @@ public static class AnalyzerData { // Fields related to worker system boolean inInternallyDefinedBlockStmt; int workerSystemMovementSequence; - Stack workerActionSystemStack = new Stack<>(); + Deque workerActionSystemStack = new ArrayDeque<>(); Map> workerReferences = new HashMap<>(); // Field related to transactions int transactionCount; @@ -4436,9 +4422,9 @@ public static class AnalyzerData { boolean commitRollbackAllowed; int commitCountWithinBlock; int rollbackCountWithinBlock; - Stack loopWithinTransactionCheckStack = new Stack<>(); - Stack returnWithinTransactionCheckStack = new Stack<>(); - Stack transactionalFuncCheckStack = new Stack<>(); + Deque loopWithinTransactionCheckStack = new ArrayDeque<>(); + Deque returnWithinTransactionCheckStack = new ArrayDeque<>(); + Deque transactionalFuncCheckStack = new ArrayDeque<>(); // Fields related to lock boolean withinLockBlock; // Common fields @@ -4447,7 +4433,7 @@ public static class AnalyzerData { boolean queryToTableWithKey; boolean withinQuery; Types.QueryConstructType queryConstructType; - Stack> returnTypes = new Stack<>(); + Deque> returnTypes = new ArrayDeque<>(); DefaultValueState defaultValueState = DefaultValueState.NOT_IN_DEFAULT_VALUE; } } diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/CompilerPluginRunner.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/CompilerPluginRunner.java index 2f9aa1cbc128..bcc47211e0fc 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/CompilerPluginRunner.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/CompilerPluginRunner.java @@ -71,7 +71,6 @@ import java.util.Set; import java.util.function.BiConsumer; import java.util.function.Consumer; -import java.util.stream.Collectors; /** * Invoke {@link CompilerPlugin} plugins. @@ -400,7 +399,7 @@ private void handleServiceTypeProcesses(CompilerPlugin plugin) { } List definitions = Arrays.stream(supportedTypes) - .map(type -> new DefinitionID(type.packageName(), type.name())).collect(Collectors.toList()); + .map(type -> new DefinitionID(type.packageName(), type.name())).toList(); resourceTypeProcessorMap.put(plugin, definitions); serviceListenerMap.put(plugin, listenerType); } diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/ConditionResolver.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/ConditionResolver.java index b94107f1ca03..7b667249be30 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/ConditionResolver.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/ConditionResolver.java @@ -37,7 +37,10 @@ * * @since 2.0.0 */ -public class ConditionResolver { +public final class ConditionResolver { + + private ConditionResolver() { + } static BType checkConstCondition(Types types, SymbolTable symTable, BLangExpression condition) { switch (condition.getKind()) { diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/ConstantAnalyzer.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/ConstantAnalyzer.java index b0d195ed68a7..b8ab21755152 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/ConstantAnalyzer.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/ConstantAnalyzer.java @@ -42,7 +42,8 @@ import org.wso2.ballerinalang.compiler.util.CompilerContext; import org.wso2.ballerinalang.compiler.util.Names; -import java.util.Stack; +import java.util.ArrayDeque; +import java.util.Deque; /** * Validate Given constant expressions. @@ -59,7 +60,7 @@ public class ConstantAnalyzer extends BLangNodeVisitor { private final SymbolTable symTable; private final SymbolResolver symResolver; private BLangDiagnosticLog dlog; - private Stack expressions = new Stack<>(); + private Deque expressions = new ArrayDeque<>(); private ConstantAnalyzer(CompilerContext context) { diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/ConstantTypeChecker.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/ConstantTypeChecker.java index 4e8a99c46bb6..1f1087921e10 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/ConstantTypeChecker.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/ConstantTypeChecker.java @@ -99,9 +99,11 @@ import java.math.BigDecimal; import java.math.MathContext; +import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; +import java.util.Deque; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; @@ -110,7 +112,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import java.util.Stack; import java.util.function.BiFunction; import static org.ballerinalang.model.symbols.SymbolOrigin.SOURCE; @@ -542,21 +543,21 @@ private BType checkMappingConstructorCompatibility(BType expType, BLangRecordLit BType possibleType = getMappingConstructorCompatibleNonUnionType(expType, data); - switch (possibleType.tag) { - case TypeTags.MAP: - return validateSpecifiedFieldsAndGetType(mappingConstructor, possibleType, data); - case TypeTags.RECORD: + return switch (possibleType.tag) { + case TypeTags.MAP -> validateSpecifiedFieldsAndGetType(mappingConstructor, possibleType, data); + case TypeTags.RECORD -> { boolean hasAllRequiredFields = validateRequiredFields((BRecordType) possibleType, mappingConstructor.fields, mappingConstructor.pos, data); - return hasAllRequiredFields ? validateSpecifiedFieldsAndGetType(mappingConstructor, possibleType, data) + yield hasAllRequiredFields ? validateSpecifiedFieldsAndGetType(mappingConstructor, possibleType, data) : symTable.semanticError; - case TypeTags.READONLY: - return checkConstExpr(mappingConstructor, possibleType, data); - default: + } + case TypeTags.READONLY -> checkConstExpr(mappingConstructor, possibleType, data); + default -> { reportIncompatibleMappingConstructorError(mappingConstructor, expType); - return symTable.semanticError; - } + yield symTable.semanticError; + } + }; } /** @@ -665,15 +666,12 @@ private BType getMappingConstructorCompatibleNonUnionType(BType type, AnalyzerDa private BType validateSpecifiedFieldsAndGetType(BLangRecordLiteral mappingConstructor, BType possibleType, AnalyzerData data) { - switch (possibleType.tag) { - case TypeTags.MAP: - BType expType = ((BMapType) possibleType).constraint; - return validateMapTypeAndInferredType(mappingConstructor, expType, possibleType, data); - case TypeTags.RECORD: - return validateRecordType(mappingConstructor, (BRecordType) possibleType, data); - default: - return symTable.semanticError; - } + return switch (possibleType.tag) { + case TypeTags.MAP -> validateMapTypeAndInferredType(mappingConstructor, + ((BMapType) possibleType).constraint, possibleType, data); + case TypeTags.RECORD -> validateRecordType(mappingConstructor, (BRecordType) possibleType, data); + default -> symTable.semanticError; + }; } private BType validateMapTypeAndInferredType(BLangRecordLiteral mappingConstructor, BType expType, @@ -1109,18 +1107,16 @@ private BType checkListConstructorCompatibility(BType expType, BLangListConstruc BType possibleType = getListConstructorCompatibleNonUnionType(expType, data); - switch (possibleType.tag) { - case TypeTags.ARRAY: - case TypeTags.BYTE_ARRAY: - return checkArrayType((BArrayType) possibleType, listConstructor, data); - case TypeTags.TUPLE: - return checkTupleType((BTupleType) possibleType, listConstructor, data); - case TypeTags.READONLY: - return checkConstExpr(listConstructor, possibleType, data); - default: + return switch (possibleType.tag) { + case TypeTags.ARRAY, + TypeTags.BYTE_ARRAY -> checkArrayType((BArrayType) possibleType, listConstructor, data); + case TypeTags.TUPLE -> checkTupleType((BTupleType) possibleType, listConstructor, data); + case TypeTags.READONLY -> checkConstExpr(listConstructor, possibleType, data); + default -> { dlog.error(listConstructor.pos, DiagnosticErrorCode.INCOMPATIBLE_TYPES, expType, listConstructor); - return symTable.semanticError; - } + yield symTable.semanticError; + } + }; } private BType checkArrayType(BArrayType arrayType, BLangListConstructorExpr listConstructor, AnalyzerData data) { @@ -1384,30 +1380,24 @@ private BType checkExprIncompatible(BType eType, BLangExpression expr, AnalyzerD } private BType getListConstructorCompatibleNonUnionType(BType type, AnalyzerData data) { - switch (type.tag) { - case TypeTags.ARRAY: - case TypeTags.BYTE_ARRAY: - case TypeTags.TUPLE: - case TypeTags.READONLY: - case TypeTags.TYPEDESC: - return type; - case TypeTags.JSON: - return !Symbols.isFlagOn(type.flags, Flags.READONLY) ? symTable.arrayJsonType : - ImmutableTypeCloner.getEffectiveImmutableType(null, types, symTable.arrayJsonType, - data.env, symTable, anonymousModelHelper, names); - case TypeTags.ANYDATA: - return !Symbols.isFlagOn(type.flags, Flags.READONLY) ? symTable.arrayAnydataType : - ImmutableTypeCloner.getEffectiveImmutableType(null, types, symTable.arrayAnydataType, - data.env, symTable, anonymousModelHelper, names); - case TypeTags.ANY: - return !Symbols.isFlagOn(type.flags, Flags.READONLY) ? symTable.arrayAllType : - ImmutableTypeCloner.getEffectiveImmutableType(null, types, symTable.arrayAllType, data.env, - symTable, anonymousModelHelper, names); - case TypeTags.INTERSECTION: - return ((BIntersectionType) type).effectiveType; - default: - return symTable.semanticError; - } + return switch (type.tag) { + case TypeTags.ARRAY, + TypeTags.BYTE_ARRAY, + TypeTags.TUPLE, + TypeTags.READONLY, + TypeTags.TYPEDESC -> type; + case TypeTags.JSON -> !Symbols.isFlagOn(type.flags, Flags.READONLY) ? symTable.arrayJsonType : + ImmutableTypeCloner.getEffectiveImmutableType(null, types, symTable.arrayJsonType, + data.env, symTable, anonymousModelHelper, names); + case TypeTags.ANYDATA -> !Symbols.isFlagOn(type.flags, Flags.READONLY) ? symTable.arrayAnydataType : + ImmutableTypeCloner.getEffectiveImmutableType(null, types, symTable.arrayAnydataType, + data.env, symTable, anonymousModelHelper, names); + case TypeTags.ANY -> !Symbols.isFlagOn(type.flags, Flags.READONLY) ? symTable.arrayAllType : + ImmutableTypeCloner.getEffectiveImmutableType(null, types, symTable.arrayAllType, data.env, + symTable, anonymousModelHelper, names); + case TypeTags.INTERSECTION -> ((BIntersectionType) type).effectiveType; + default -> symTable.semanticError; + }; } private BType getBroadType(BType type) { @@ -1500,8 +1490,8 @@ private Object calculateSingletonValue(BFiniteType lhs, BFiniteType rhs, Operato private Object getValue(BLangLiteral lhsLiteral) { Object value = lhsLiteral.value; - if (value instanceof BLangConstantValue) { - return ((BLangConstantValue) value).value; + if (value instanceof BLangConstantValue bLangConstantValue) { + return bLangConstantValue.value; } return value; } @@ -1681,16 +1671,12 @@ private Object calculateNegationForDecimal(Object value) { } private Object calculateNegation(Object value, BType type, AnalyzerData data) { - switch (type.tag) { - case TypeTags.INT: - return calculateNegationForInt(value, data); - case TypeTags.FLOAT: - return calculateNegationForFloat(value); - case TypeTags.DECIMAL: - return calculateNegationForDecimal(value); - default: - return null; - } + return switch (type.tag) { + case TypeTags.INT -> calculateNegationForInt(value, data); + case TypeTags.FLOAT -> calculateNegationForFloat(value); + case TypeTags.DECIMAL -> calculateNegationForDecimal(value); + default -> null; + }; } private Object calculateBitWiseComplement(Object value, BType type) { @@ -1936,42 +1922,37 @@ public BType getTypeOfHexFloatingPointLiteral(BLangLiteral literalExpr, Object l } private BType getFiniteType(Object value, BConstantSymbol constantSymbol, Location pos, BType type) { - switch (type.tag) { - case TypeTags.INT: - case TypeTags.FLOAT: - case TypeTags.DECIMAL: - case TypeTags.BYTE: + return switch (type.tag) { + case TypeTags.INT, + TypeTags.FLOAT, + TypeTags.DECIMAL, + TypeTags.BYTE -> { BLangNumericLiteral numericLiteral = (BLangNumericLiteral) TreeBuilder.createNumericLiteralExpression(); - return createFiniteType(constantSymbol, updateLiteral(numericLiteral, value, type, pos)); -// case TypeTags.BYTE: + yield createFiniteType(constantSymbol, updateLiteral(numericLiteral, value, type, pos)); + } +// case TypeTags.BYTE -> { // BLangNumericLiteral byteLiteral = (BLangNumericLiteral) TreeBuilder.createNumericLiteralExpression(); -// return createFiniteType(constantSymbol, updateLiteral(byteLiteral, value, symTable.intType, pos)); - case TypeTags.STRING: - case TypeTags.NIL: - case TypeTags.BOOLEAN: +// yield createFiniteType(constantSymbol, updateLiteral(byteLiteral, value, symTable.intType, pos)); +// } + case TypeTags.STRING, + TypeTags.NIL, + TypeTags.BOOLEAN -> { BLangLiteral literal = (BLangLiteral) TreeBuilder.createLiteralExpression(); - return createFiniteType(constantSymbol, updateLiteral(literal, value, type, pos)); - case TypeTags.UNION: - return createFiniteType(constantSymbol, value, (BUnionType) type, pos); - default: - return type; - } + yield createFiniteType(constantSymbol, updateLiteral(literal, value, type, pos)); + } + case TypeTags.UNION -> createFiniteType(constantSymbol, value, (BUnionType) type, pos); + default -> type; + }; } private BLangLiteral getLiteral(Object value, Location pos, BType type) { - switch (type.tag) { - case TypeTags.INT: - case TypeTags.FLOAT: - case TypeTags.DECIMAL: - BLangNumericLiteral numericLiteral = (BLangNumericLiteral) TreeBuilder.createNumericLiteralExpression(); - return updateLiteral(numericLiteral, value, type, pos); - case TypeTags.BYTE: - BLangNumericLiteral byteLiteral = (BLangNumericLiteral) TreeBuilder.createNumericLiteralExpression(); - return updateLiteral(byteLiteral, value, symTable.byteType, pos); - default: - BLangLiteral literal = (BLangLiteral) TreeBuilder.createLiteralExpression(); - return updateLiteral(literal, value, type, pos); - } + return switch (type.tag) { + case TypeTags.INT, TypeTags.FLOAT, TypeTags.DECIMAL -> + updateLiteral((BLangNumericLiteral) TreeBuilder.createNumericLiteralExpression(), value, type, pos); + case TypeTags.BYTE -> updateLiteral((BLangNumericLiteral) TreeBuilder.createNumericLiteralExpression(), + value, symTable.byteType, pos); + default -> updateLiteral((BLangLiteral) TreeBuilder.createLiteralExpression(), value, type, pos); + }; } private BLangLiteral updateLiteral(BLangLiteral literal, Object value, BType type, Location pos) { @@ -1998,18 +1979,12 @@ private BUnionType createFiniteType(BConstantSymbol constantSymbol, Object value BTypeSymbol finiteTypeSymbol = Symbols.createTypeSymbol(SymTag.FINITE_TYPE, constantSymbol.flags, Names.EMPTY, constantSymbol.pkgID, null, constantSymbol.owner, constantSymbol.pos, VIRTUAL); BFiniteType finiteType = new BFiniteType(finiteTypeSymbol); - Object memberValue; - switch (memberType.tag) { - case TypeTags.FLOAT: - memberValue = value instanceof String ? - Double.parseDouble((String) value) : ((Long) value).doubleValue(); - break; - case TypeTags.DECIMAL: - memberValue = new BigDecimal(String.valueOf(value)); - break; - default: - memberValue = value; - } + Object memberValue = switch (memberType.tag) { + case TypeTags.FLOAT -> value instanceof String ? + Double.parseDouble((String) value) : ((Long) value).doubleValue(); + case TypeTags.DECIMAL -> new BigDecimal(String.valueOf(value)); + default -> value; + }; finiteType.addValue(getLiteral(memberValue, pos, memberType)); finiteType.tsymbol.type = finiteType; memberTypes.add(finiteType); @@ -2788,7 +2763,7 @@ public static class AnalyzerData { Map modTable; BConstantSymbol constantSymbol; int compoundExprCount = 0; - Stack anonTypeNameSuffixes = new Stack<>(); + Deque anonTypeNameSuffixes = new ArrayDeque<>(); Location pos; } } diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/ConstantValueResolver.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/ConstantValueResolver.java index a98793bd9716..2b4567a63a47 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/ConstantValueResolver.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/ConstantValueResolver.java @@ -75,7 +75,9 @@ import java.math.BigDecimal; import java.math.MathContext; +import java.util.ArrayDeque; import java.util.ArrayList; +import java.util.Deque; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; @@ -83,7 +85,6 @@ import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.Stack; import java.util.function.BiFunction; import static org.ballerinalang.model.symbols.SymbolOrigin.SOURCE; @@ -111,7 +112,7 @@ public class ConstantValueResolver extends BLangNodeVisitor { private ArrayList resolvingConstants = new ArrayList<>(); private HashSet unresolvableConstants = new HashSet<>(); private HashMap createdTypeDefinitions = new HashMap<>(); - private Stack anonTypeNameSuffixes = new Stack<>(); + private Deque anonTypeNameSuffixes = new ArrayDeque<>(); private ConstantValueResolver(CompilerContext context) { context.put(CONSTANT_VALUE_RESOLVER_KEY, this); @@ -543,17 +544,12 @@ private BLangConstantValue calculateNegation(BLangConstantValue value) { BType constSymbolValType = value.type; int constSymbolValTypeTag = Types.getImpliedType(constSymbolValType).tag; - switch (constSymbolValTypeTag) { - case TypeTags.INT: - result = calculateNegationForInt(value); - break; - case TypeTags.FLOAT: - result = calculateNegationForFloat(value); - break; - case TypeTags.DECIMAL: - result = calculateNegationForDecimal(value); - break; - } + result = switch (constSymbolValTypeTag) { + case TypeTags.INT -> calculateNegationForInt(value); + case TypeTags.FLOAT -> calculateNegationForFloat(value); + case TypeTags.DECIMAL -> calculateNegationForDecimal(value); + default -> result; + }; return new BLangConstantValue(result, constSymbolValType); } @@ -576,12 +572,12 @@ private BLangConstantValue calculateBooleanComplement(BLangConstantValue value) BLangConstantValue constructBLangConstantValueWithExactType(BLangExpression expression, BConstantSymbol constantSymbol, SymbolEnv env) { - return constructBLangConstantValueWithExactType(expression, constantSymbol, env, new Stack<>(), false); + return constructBLangConstantValueWithExactType(expression, constantSymbol, env, new ArrayDeque<>(), false); } BLangConstantValue constructBLangConstantValueWithExactType(BLangExpression expression, BConstantSymbol constantSymbol, SymbolEnv env, - Stack anonTypeNameSuffixes, + Deque anonTypeNameSuffixes, boolean isSourceOnlyAnon) { this.currentConstSymbol = constantSymbol; BLangConstantValue value = constructBLangConstantValue(expression); @@ -696,14 +692,10 @@ private void updateConstantType(BConstantSymbol symbol, BLangExpression expr, Sy } private boolean isListOrMapping(int tag) { - switch (tag) { - case TypeTags.RECORD: - case TypeTags.MAP: - case TypeTags.ARRAY: - case TypeTags.TUPLE: - return true; - } - return false; + return switch (tag) { + case TypeTags.RECORD, TypeTags.MAP, TypeTags.ARRAY, TypeTags.TUPLE -> true; + default -> false; + }; } private BFiniteType createFiniteType(BConstantSymbol constantSymbol, BLangExpression expr) { @@ -725,35 +717,39 @@ private BType checkType(BLangExpression expr, BConstantSymbol constantSymbol, Ob type = Types.getImpliedType(type); - switch (type.tag) { - case TypeTags.INT: - case TypeTags.FLOAT: - case TypeTags.DECIMAL: + return switch (type.tag) { + case TypeTags.INT, + TypeTags.FLOAT, + TypeTags.DECIMAL -> { BLangNumericLiteral numericLiteral = (BLangNumericLiteral) TreeBuilder.createNumericLiteralExpression(); - return createFiniteType(constantSymbol, updateLiteral(numericLiteral, value, type, pos)); - case TypeTags.BYTE: + yield createFiniteType(constantSymbol, updateLiteral(numericLiteral, value, type, pos)); + } + case TypeTags.BYTE -> { BLangNumericLiteral byteLiteral = (BLangNumericLiteral) TreeBuilder.createNumericLiteralExpression(); - return createFiniteType(constantSymbol, updateLiteral(byteLiteral, value, symTable.intType, pos)); - case TypeTags.STRING: - case TypeTags.NIL: - case TypeTags.BOOLEAN: + yield createFiniteType(constantSymbol, updateLiteral(byteLiteral, value, symTable.intType, pos)); + } + case TypeTags.STRING, + TypeTags.NIL, + TypeTags.BOOLEAN -> { BLangLiteral literal = (BLangLiteral) TreeBuilder.createLiteralExpression(); - return createFiniteType(constantSymbol, updateLiteral(literal, value, type, pos)); - case TypeTags.MAP: - case TypeTags.RECORD: + yield createFiniteType(constantSymbol, updateLiteral(literal, value, type, pos)); + } + case TypeTags.MAP, + TypeTags.RECORD -> { if (value != null) { - return createRecordType(expr, constantSymbol, value, pos, env); + yield createRecordType(expr, constantSymbol, value, pos, env); } - return null; - case TypeTags.ARRAY: - case TypeTags.TUPLE: + yield null; + } + case TypeTags.ARRAY, + TypeTags.TUPLE -> { if (value != null) { - return createTupleType(expr, constantSymbol, pos, value, env); + yield createTupleType(expr, constantSymbol, pos, value, env); } - return null; - default: - return null; - } + yield null; + } + default -> null; + }; } private BLangLiteral updateLiteral(BLangLiteral literal, Object value, BType type, Location pos) { diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/DataflowAnalyzer.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/DataflowAnalyzer.java index 085e9ceb680a..4ff22f030b2f 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/DataflowAnalyzer.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/DataflowAnalyzer.java @@ -234,6 +234,7 @@ import java.util.Deque; import java.util.HashMap; import java.util.HashSet; +import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; @@ -241,7 +242,6 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; -import java.util.Stack; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -270,7 +270,7 @@ public class DataflowAnalyzer extends BLangNodeVisitor { private Map> globalNodeDependsOn; private Map> functionToDependency; private Map> possibleFailureUnInitVars; - private Stack enclosingOnFailClause; + private Deque enclosingOnFailClause; private boolean flowTerminated = false; private boolean possibleFailureReached = false; private boolean definiteFailureReached = false; @@ -310,7 +310,7 @@ public BLangPackage analyze(BLangPackage pkgNode) { this.globalNodeDependsOn = new LinkedHashMap<>(); this.functionToDependency = new HashMap<>(); this.possibleFailureUnInitVars = new LinkedHashMap<>(); - this.enclosingOnFailClause = new Stack<>(); + this.enclosingOnFailClause = new ArrayDeque<>(); this.dlog.setCurrentPackageId(pkgNode.packageID); SymbolEnv pkgEnv = this.symTable.pkgEnvMap.get(pkgNode.symbol); analyzeNode(pkgNode, pkgEnv); @@ -996,7 +996,10 @@ private void updateEnclosingOnFailUnInits(Map possibleUnini // Update the enclosing on-fail clause's possible failure uninitialized variables int enclosingOnFailSize = this.enclosingOnFailClause.size(); if (enclosingOnFailSize > 1) { - BLangOnFailClause enclosingOnFail = this.enclosingOnFailClause.get(enclosingOnFailSize - 2); + Iterator iterator = this.enclosingOnFailClause.iterator(); + // get second top element + iterator.next(); + BLangOnFailClause enclosingOnFail = iterator.next(); this.possibleFailureUnInitVars.put(enclosingOnFail, possibleUninitializedVars); } } @@ -1559,7 +1562,7 @@ private List createKeyArray(BLangRecordLiteral literal, List getFieldNames(BLangTableConstructorExpr constructorExpr) { @@ -1574,7 +1577,7 @@ private List getFieldNames(BLangTableConstructorExpr constructorExpr) { !constructorExpr.tableKeySpecifier.fieldNameIdentifierList.isEmpty()) { BLangTableKeySpecifier tableKeySpecifier = constructorExpr.tableKeySpecifier; return tableKeySpecifier.fieldNameIdentifierList.stream().map(identifier -> - ((BLangIdentifier) identifier).value).collect(Collectors.toList()); + ((BLangIdentifier) identifier).value).toList(); } else { return new ArrayList<>(); } @@ -2946,7 +2949,7 @@ private enum InitStatus { UN_INIT, PARTIAL_INIT } - private class BranchResult { + private static class BranchResult { Map uninitializedVars; Map possibleFailureUnInitVars; diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/IsAnydataUniqueVisitor.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/IsAnydataUniqueVisitor.java index c784af87b505..e4915183948f 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/IsAnydataUniqueVisitor.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/IsAnydataUniqueVisitor.java @@ -60,34 +60,32 @@ public IsAnydataUniqueVisitor(HashSet visited) { } private boolean isAnydata(BType type) { - switch (Types.getImpliedType(type).tag) { - case TypeTags.INT: - case TypeTags.BYTE: - case TypeTags.FLOAT: - case TypeTags.DECIMAL: - case TypeTags.STRING: - case TypeTags.CHAR_STRING: - case TypeTags.BOOLEAN: - case TypeTags.JSON: - case TypeTags.XML: - case TypeTags.XML_TEXT: - case TypeTags.XML_ELEMENT: - case TypeTags.XML_COMMENT: - case TypeTags.XML_PI: - case TypeTags.NIL: - case TypeTags.NEVER: - case TypeTags.ANYDATA: - case TypeTags.SIGNED8_INT: - case TypeTags.SIGNED16_INT: - case TypeTags.SIGNED32_INT: - case TypeTags.UNSIGNED8_INT: - case TypeTags.UNSIGNED16_INT: - case TypeTags.UNSIGNED32_INT: - case TypeTags.REGEXP: - return true; - default: - return false; - } + return switch (Types.getImpliedType(type).tag) { + case TypeTags.INT, + TypeTags.BYTE, + TypeTags.FLOAT, + TypeTags.DECIMAL, + TypeTags.STRING, + TypeTags.CHAR_STRING, + TypeTags.BOOLEAN, + TypeTags.JSON, + TypeTags.XML, + TypeTags.XML_TEXT, + TypeTags.XML_ELEMENT, + TypeTags.XML_COMMENT, + TypeTags.XML_PI, + TypeTags.NIL, + TypeTags.NEVER, + TypeTags.ANYDATA, + TypeTags.SIGNED8_INT, + TypeTags.SIGNED16_INT, + TypeTags.SIGNED32_INT, + TypeTags.UNSIGNED8_INT, + TypeTags.UNSIGNED16_INT, + TypeTags.UNSIGNED32_INT, + TypeTags.REGEXP -> true; + default -> false; + }; } @Override @@ -296,43 +294,30 @@ public Boolean visit(BRecordType type) { @Override public Boolean visit(BType type) { - switch (type.tag) { - case TypeTags.TABLE: - return visit((BTableType) type); - case TypeTags.ANYDATA: - return visit((BAnydataType) type); - case TypeTags.RECORD: - return visit((BRecordType) type); - case TypeTags.ARRAY: - return visit((BArrayType) type); - case TypeTags.UNION: - return visit((BUnionType) type); - case TypeTags.TYPEDESC: - return visit((BTypedescType) type); - case TypeTags.MAP: - return visit((BMapType) type); - case TypeTags.FINITE: - return visit((BFiniteType) type); - case TypeTags.TUPLE: - return visit((BTupleType) type); - case TypeTags.INTERSECTION: - return visit((BIntersectionType) type); - case TypeTags.TYPEREFDESC: - return visit((BTypeReferenceType) type); - case TypeTags.SIGNED8_INT: - case TypeTags.SIGNED16_INT: - case TypeTags.SIGNED32_INT: - case TypeTags.UNSIGNED8_INT: - case TypeTags.UNSIGNED16_INT: - case TypeTags.UNSIGNED32_INT: - return visit((BIntSubType) type); - case TypeTags.XML_ELEMENT: - case TypeTags.XML_PI: - case TypeTags.XML_COMMENT: - case TypeTags.XML_TEXT: - return visit((BXMLSubType) type); - } - return isAnydata(type); + return switch (type.tag) { + case TypeTags.TABLE -> visit((BTableType) type); + case TypeTags.ANYDATA -> visit((BAnydataType) type); + case TypeTags.RECORD -> visit((BRecordType) type); + case TypeTags.ARRAY -> visit((BArrayType) type); + case TypeTags.UNION -> visit((BUnionType) type); + case TypeTags.TYPEDESC -> visit((BTypedescType) type); + case TypeTags.MAP -> visit((BMapType) type); + case TypeTags.FINITE -> visit((BFiniteType) type); + case TypeTags.TUPLE -> visit((BTupleType) type); + case TypeTags.INTERSECTION -> visit((BIntersectionType) type); + case TypeTags.TYPEREFDESC -> visit((BTypeReferenceType) type); + case TypeTags.SIGNED8_INT, + TypeTags.SIGNED16_INT, + TypeTags.SIGNED32_INT, + TypeTags.UNSIGNED8_INT, + TypeTags.UNSIGNED16_INT, + TypeTags.UNSIGNED32_INT -> visit((BIntSubType) type); + case TypeTags.XML_ELEMENT, + TypeTags.XML_PI, + TypeTags.XML_COMMENT, + TypeTags.XML_TEXT -> visit((BXMLSubType) type); + default -> isAnydata(type); + }; } @Override diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/IsPureTypeUniqueVisitor.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/IsPureTypeUniqueVisitor.java index ede13dfbac28..b3b001f19f60 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/IsPureTypeUniqueVisitor.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/IsPureTypeUniqueVisitor.java @@ -58,31 +58,29 @@ public IsPureTypeUniqueVisitor(HashSet visited) { } private boolean isAnyData(BType type) { - switch (Types.getImpliedType(type).tag) { - case TypeTags.INT: - case TypeTags.BYTE: - case TypeTags.FLOAT: - case TypeTags.DECIMAL: - case TypeTags.STRING: - case TypeTags.BOOLEAN: - case TypeTags.JSON: - case TypeTags.XML: - case TypeTags.XML_TEXT: - case TypeTags.TABLE: - case TypeTags.NIL: - case TypeTags.NEVER: - case TypeTags.ANYDATA: - case TypeTags.SIGNED8_INT: - case TypeTags.SIGNED16_INT: - case TypeTags.SIGNED32_INT: - case TypeTags.UNSIGNED8_INT: - case TypeTags.UNSIGNED16_INT: - case TypeTags.UNSIGNED32_INT: - case TypeTags.CHAR_STRING: - return true; - default: - return false; - } + return switch (Types.getImpliedType(type).tag) { + case TypeTags.INT, + TypeTags.BYTE, + TypeTags.FLOAT, + TypeTags.DECIMAL, + TypeTags.STRING, + TypeTags.BOOLEAN, + TypeTags.JSON, + TypeTags.XML, + TypeTags.XML_TEXT, + TypeTags.TABLE, + TypeTags.NIL, + TypeTags.NEVER, + TypeTags.ANYDATA, + TypeTags.SIGNED8_INT, + TypeTags.SIGNED16_INT, + TypeTags.SIGNED32_INT, + TypeTags.UNSIGNED8_INT, + TypeTags.UNSIGNED16_INT, + TypeTags.UNSIGNED32_INT, + TypeTags.CHAR_STRING -> true; + default -> false; + }; } @Override @@ -253,38 +251,26 @@ public Boolean visit(BObjectType type) { @Override public Boolean visit(BType type) { - switch (type.tag) { - case TypeTags.TABLE: - return visit((BTableType) type); - case TypeTags.ANYDATA: - return visit((BAnydataType) type); - case TypeTags.RECORD: - return visit((BRecordType) type); - case TypeTags.ARRAY: - return visit((BArrayType) type); - case TypeTags.UNION: - return visit((BUnionType) type); - case TypeTags.TYPEDESC: - return visit((BTypedescType) type); - case TypeTags.MAP: - return visit((BMapType) type); - case TypeTags.FINITE: - return visit((BFiniteType) type); - case TypeTags.TUPLE: - return visit((BTupleType) type); - case TypeTags.INTERSECTION: - return visit((BIntersectionType) type); - case TypeTags.TYPEREFDESC: - return visit((BTypeReferenceType) type); - case TypeTags.SIGNED8_INT: - case TypeTags.SIGNED16_INT: - case TypeTags.SIGNED32_INT: - case TypeTags.UNSIGNED8_INT: - case TypeTags.UNSIGNED16_INT: - case TypeTags.UNSIGNED32_INT: - return visit((BIntSubType) type); - } - return isAnyData(type); + return switch (type.tag) { + case TypeTags.TABLE -> visit((BTableType) type); + case TypeTags.ANYDATA -> visit((BAnydataType) type); + case TypeTags.RECORD -> visit((BRecordType) type); + case TypeTags.ARRAY -> visit((BArrayType) type); + case TypeTags.UNION -> visit((BUnionType) type); + case TypeTags.TYPEDESC -> visit((BTypedescType) type); + case TypeTags.MAP -> visit((BMapType) type); + case TypeTags.FINITE -> visit((BFiniteType) type); + case TypeTags.TUPLE -> visit((BTupleType) type); + case TypeTags.INTERSECTION -> visit((BIntersectionType) type); + case TypeTags.TYPEREFDESC -> visit((BTypeReferenceType) type); + case TypeTags.SIGNED8_INT, + TypeTags.SIGNED16_INT, + TypeTags.SIGNED32_INT, + TypeTags.UNSIGNED8_INT, + TypeTags.UNSIGNED16_INT, + TypeTags.UNSIGNED32_INT -> visit((BIntSubType) type); + default -> isAnyData(type); + }; } @Override diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/IsolationAnalyzer.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/IsolationAnalyzer.java index c99a290731ca..5575a3bbdcf1 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/IsolationAnalyzer.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/IsolationAnalyzer.java @@ -264,13 +264,14 @@ import org.wso2.ballerinalang.compiler.util.TypeTags; import org.wso2.ballerinalang.util.Flags; +import java.util.ArrayDeque; import java.util.ArrayList; +import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.Stack; import static org.ballerinalang.model.symbols.SymbolOrigin.VIRTUAL; @@ -296,8 +297,8 @@ public class IsolationAnalyzer extends BLangNodeVisitor { private boolean inferredIsolated = true; private boolean inLockStatement = false; private boolean inIsolatedStartAction = false; - private final Stack copyInLockInfoStack = new Stack<>(); - private final Stack> isolatedLetVarStack = new Stack<>(); + private final Deque copyInLockInfoStack = new ArrayDeque<>(); + private final Deque> isolatedLetVarStack = new ArrayDeque<>(); private final Map isolationInferenceInfoMap = new HashMap<>(); private final Map arrowFunctionTempSymbolMap = new HashMap<>(); @@ -1014,15 +1015,13 @@ public void visit(BLangLock lockNode) { } } - if (copyInLockInfoStack.empty()) { + if (copyInLockInfoStack.isEmpty()) { return; } BLangLock lastCheckedLockNode = lockNode; - for (int i = copyInLockInfoStack.size() - 1; i >= 0; i--) { - LockInfo prevCopyInLockInfo = copyInLockInfoStack.get(i); - + for (LockInfo prevCopyInLockInfo : copyInLockInfoStack) { BLangLock outerLockNode = prevCopyInLockInfo.lockNode; if (!isEnclosedLockWithinSameFunction(lastCheckedLockNode, outerLockNode)) { @@ -3115,28 +3114,26 @@ private boolean isSubTypeOfReadOnlyOrIsolatedObjectUnionWithInference(Set } private boolean isDependentlyIsolatedExpressionKind(BLangExpression expression) { - switch (expression.getKind()) { - case LIST_CONSTRUCTOR_EXPR: - case TABLE_CONSTRUCTOR_EXPR: - case RECORD_LITERAL_EXPR: - case XML_COMMENT_LITERAL: - case XML_TEXT_LITERAL: - case XML_PI_LITERAL: - case XML_ELEMENT_LITERAL: - case XML_SEQUENCE_LITERAL: - case RAW_TEMPLATE_LITERAL: - case STRING_TEMPLATE_LITERAL: - case TYPE_CONVERSION_EXPR: - case CHECK_EXPR: - case CHECK_PANIC_EXPR: - case TRAP_EXPR: - case TERNARY_EXPR: - case ELVIS_EXPR: - return true; - case GROUP_EXPR: - return isDependentlyIsolatedExpressionKind(((BLangGroupExpr) expression).expression); - } - return false; + return switch (expression.getKind()) { + case LIST_CONSTRUCTOR_EXPR, + TABLE_CONSTRUCTOR_EXPR, + RECORD_LITERAL_EXPR, + XML_COMMENT_LITERAL, + XML_TEXT_LITERAL, + XML_PI_LITERAL, + XML_ELEMENT_LITERAL, + XML_SEQUENCE_LITERAL, + RAW_TEMPLATE_LITERAL, + STRING_TEMPLATE_LITERAL, + TYPE_CONVERSION_EXPR, + CHECK_EXPR, + CHECK_PANIC_EXPR, + TRAP_EXPR, + TERNARY_EXPR, + ELVIS_EXPR -> true; + case GROUP_EXPR -> isDependentlyIsolatedExpressionKind(((BLangGroupExpr) expression).expression); + default -> false; + }; } private boolean isCloneOrCloneReadOnlyInvocation(BLangInvocation invocation) { @@ -3158,12 +3155,10 @@ private boolean isInvalidTransferIn(BLangExpression expression, boolean invokedO BLangNode parent = expression.parent; NodeKind parentExprKind = parent.getKind(); - if (!(parent instanceof BLangExpression)) { + if (!(parent instanceof BLangExpression parentExpression)) { return !isIsolatedExpression(expression); } - BLangExpression parentExpression = (BLangExpression) parent; - if (parentExprKind != NodeKind.INVOCATION) { if (!isSelfReference(expression) && isIsolatedExpression(expression)) { return false; @@ -3374,7 +3369,7 @@ private boolean isInvalidCopyIn(BLangSimpleVarRef varRefExpr, SymbolEnv currentE private boolean isInvalidCopyIn(BLangSimpleVarRef varRefExpr, Name name, long symTag, SymbolEnv currentEnv) { BSymbol symbol = symResolver.lookupSymbolInGivenScope(currentEnv, name, symTag); if (symbol != symTable.notFoundSymbol && - (!(symbol instanceof BVarSymbol) || ((BVarSymbol) symbol).originalSymbol == null)) { + (!(symbol instanceof BVarSymbol bVarSymbol) || bVarSymbol.originalSymbol == null)) { return false; } @@ -3403,12 +3398,10 @@ private boolean isIsolatedModuleVariableSymbol(BSymbol symbol) { } private BSymbol getOriginalSymbol(BSymbol symbol) { - if (!(symbol instanceof BVarSymbol)) { + if (!(symbol instanceof BVarSymbol varSymbol)) { return symbol; } - BVarSymbol varSymbol = (BVarSymbol) symbol; - BVarSymbol originalSymbol = varSymbol.originalSymbol; return originalSymbol == null ? varSymbol : getOriginalSymbol(originalSymbol); } @@ -3450,8 +3443,8 @@ private boolean isReferenceOfLetVarInitializedWithAnIsolatedExpression(BLangSimp BSymbol originalSymbol = getOriginalSymbol(symbol); - for (int i = isolatedLetVarStack.size() - 1; i >= 0; i--) { - if (isolatedLetVarStack.get(i).contains(originalSymbol)) { + for (Set bSymbols : isolatedLetVarStack) { + if (bSymbols.contains(originalSymbol)) { return true; } } @@ -3493,11 +3486,10 @@ private boolean isIsolationInferableFunction(BLangFunction funcNode) { return true; } - if (!(owner instanceof BClassSymbol)) { + if (!(owner instanceof BClassSymbol ownerClassSymbol)) { return false; } - BClassSymbol ownerClassSymbol = (BClassSymbol) owner; return ownerClassSymbol.isServiceDecl || Symbols.isFlagOn(ownerClassSymbol.flags, Flags.OBJECT_CTOR); } diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/MainParameterVisitor.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/MainParameterVisitor.java index a1b3c21876ea..5593d51bc05a 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/MainParameterVisitor.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/MainParameterVisitor.java @@ -80,15 +80,10 @@ private boolean hasNil(LinkedHashSet memberTypes) { } public boolean isOperandType(BType type) { - switch (Types.getImpliedType(type).tag) { - case TypeTags.FLOAT: - case TypeTags.DECIMAL: - case TypeTags.BYTE: - return true; - case TypeTags.BOOLEAN: - return option; - default: - return TypeTags.isIntegerTypeTag(type.tag) || TypeTags.isStringTypeTag(type.tag); - } + return switch (Types.getImpliedType(type).tag) { + case TypeTags.FLOAT, TypeTags.DECIMAL, TypeTags.BYTE -> true; + case TypeTags.BOOLEAN -> option; + default -> TypeTags.isIntegerTypeTag(type.tag) || TypeTags.isStringTypeTag(type.tag); + }; } } diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/QueryTypeChecker.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/QueryTypeChecker.java index 0905aaafbd7e..dd92270be20c 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/QueryTypeChecker.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/QueryTypeChecker.java @@ -90,13 +90,13 @@ import org.wso2.ballerinalang.compiler.util.TypeTags; import org.wso2.ballerinalang.util.Flags; +import java.util.ArrayDeque; import java.util.ArrayList; +import java.util.Deque; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; -import java.util.Stack; -import java.util.stream.Collectors; import static org.ballerinalang.model.symbols.SymbolOrigin.VIRTUAL; import static org.ballerinalang.util.diagnostic.DiagnosticErrorCode.INVALID_QUERY_CONSTRUCT_INFERRED_MAP; @@ -159,8 +159,8 @@ public void checkQueryType(BLangQueryExpr queryExpr, TypeChecker.AnalyzerData da HashSet prevCheckedErrorList = commonAnalyzerData.checkedErrorList; commonAnalyzerData.checkedErrorList = new HashSet<>(); - Stack prevQueryFinalClauses = commonAnalyzerData.queryFinalClauses; - commonAnalyzerData.queryFinalClauses = new Stack<>(); + Deque prevQueryFinalClauses = commonAnalyzerData.queryFinalClauses; + commonAnalyzerData.queryFinalClauses = new ArrayDeque<>(); int prevLetCount = commonAnalyzerData.letCount; commonAnalyzerData.letCount = 0; @@ -239,8 +239,8 @@ public void checkQueryAction(BLangQueryAction queryAction, TypeChecker.AnalyzerD Types.CommonAnalyzerData commonAnalyzerData = data.commonAnalyzerData; //reset common analyzer data - Stack prevQueryFinalClauses = commonAnalyzerData.queryFinalClauses; - commonAnalyzerData.queryFinalClauses = new Stack<>(); + Deque prevQueryFinalClauses = commonAnalyzerData.queryFinalClauses; + commonAnalyzerData.queryFinalClauses = new ArrayDeque<>(); int prevLetCount = commonAnalyzerData.letCount; commonAnalyzerData.letCount = 0; @@ -282,10 +282,10 @@ public BType resolveQueryType(SymbolEnv env, BLangExpression selectExp, BType ta List safeResultTypes = types.getAllTypes(targetType, true).stream() .filter(t -> !types.isAssignable(t, symTable.errorType)) .filter(t -> !types.isAssignable(t, symTable.nilType)) - .collect(Collectors.toList()); + .toList(); // resultTypes will be empty if the targetType is `error?` if (safeResultTypes.isEmpty()) { - safeResultTypes.add(symTable.noType); + safeResultTypes = List.of(symTable.noType); } BType actualType = symTable.semanticError; List selectTypes = new ArrayList<>(); @@ -496,7 +496,7 @@ private BType getQueryTableType(BLangQueryExpr queryExpr, BType constraintType, validateKeySpecifier(queryExpr.fieldNameIdentifierList, constraintType); markReadOnlyForConstraintType(constraintType); tableType.fieldNameList = queryExpr.fieldNameIdentifierList.stream() - .map(identifier -> ((BLangIdentifier) identifier).value).collect(Collectors.toList()); + .map(identifier -> ((BLangIdentifier) identifier).value).toList(); } if (Symbols.isFlagOn(resolvedType.flags, Flags.READONLY)) { return ImmutableTypeCloner.getImmutableIntersectionType(null, types, @@ -642,7 +642,7 @@ private List getCollectionTypes(List clauses) { return clauses.stream() .filter(clause -> (clause.getKind() == NodeKind.FROM || clause.getKind() == NodeKind.JOIN)) .map(clause -> ((BLangInputClause) clause).collection.getBType()) - .collect(Collectors.toList()); + .toList(); } private BType getResolvedType(BType initType, BType expType, boolean isReadonly, SymbolEnv env) { diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/ReachabilityAnalyzer.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/ReachabilityAnalyzer.java index 1b180e6fd9e8..a169ec2ad9ff 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/ReachabilityAnalyzer.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/ReachabilityAnalyzer.java @@ -102,10 +102,11 @@ import org.wso2.ballerinalang.compiler.util.TypeTags; import org.wso2.ballerinalang.util.Flags; +import java.util.ArrayDeque; import java.util.ArrayList; +import java.util.Deque; import java.util.List; -import java.util.Stack; -import java.util.stream.Collectors; +import java.util.stream.Stream; import static org.wso2.ballerinalang.compiler.util.Constants.WORKER_LAMBDA_VAR_PREFIX; @@ -286,7 +287,7 @@ public void visit(BLangExpressionStmt exprStmtNode, AnalyzerData data) { public void visit(BLangIf ifStmt, AnalyzerData data) { checkStatementExecutionValidity(ifStmt, data); - data.potentiallyInvalidAssignmentInLoopsInfo.add(new PotentiallyInvalidAssignmentInfo(new ArrayList<>(), + data.potentiallyInvalidAssignmentInLoopsInfo.push(new PotentiallyInvalidAssignmentInfo(new ArrayList<>(), data.env.enclInvokable)); data.unreachableBlock = data.unreachableBlock || data.booleanConstCondition == symTable.falseType; analyzeReachability(ifStmt.body, data); @@ -310,7 +311,7 @@ public void visit(BLangIf ifStmt, AnalyzerData data) { } if (elseStmt != null) { - data.potentiallyInvalidAssignmentInLoopsInfo.add(new PotentiallyInvalidAssignmentInfo(new ArrayList<>(), + data.potentiallyInvalidAssignmentInLoopsInfo.push(new PotentiallyInvalidAssignmentInfo(new ArrayList<>(), data.env.enclInvokable)); data.unreachableBlock = data.unreachableBlock || (data.booleanConstCondition == symTable.trueType && @@ -387,9 +388,9 @@ public void visit(BLangFail failNode, AnalyzerData data) { @Override public void visit(BLangForeach foreach, AnalyzerData data) { SymbolEnv foreachEnv = SymbolEnv.createLoopEnv(foreach, data.env); - data.loopAndDoClauseEnvs.add(foreachEnv); + data.loopAndDoClauseEnvs.push(foreachEnv); - data.potentiallyInvalidAssignmentInLoopsInfo.add(new PotentiallyInvalidAssignmentInfo(new ArrayList<>(), + data.potentiallyInvalidAssignmentInLoopsInfo.push(new PotentiallyInvalidAssignmentInfo(new ArrayList<>(), data.env.enclInvokable)); boolean prevStatementReturnsPanicsOrFails = data.statementReturnsPanicsOrFails; @@ -445,7 +446,7 @@ public void visit(BLangMatchStatement matchStatement, AnalyzerData data) { List matchClauses = matchStatement.matchClauses; for (BLangMatchClause matchClause : matchClauses) { resetErrorThrown(data); - data.potentiallyInvalidAssignmentInLoopsInfo.add(new PotentiallyInvalidAssignmentInfo(new ArrayList<>(), + data.potentiallyInvalidAssignmentInLoopsInfo.push(new PotentiallyInvalidAssignmentInfo(new ArrayList<>(), data.env.enclInvokable)); analyzeReachability(matchClause, data); handlePotentiallyInvalidAssignmentsToTypeNarrowedVariablesInLoop( @@ -644,9 +645,9 @@ public void visit(BLangTupleVariableDef tupleVariableDef, AnalyzerData data) { @Override public void visit(BLangWhile whileNode, AnalyzerData data) { SymbolEnv whileEnv = SymbolEnv.createLoopEnv(whileNode, data.env); - data.loopAndDoClauseEnvs.add(whileEnv); + data.loopAndDoClauseEnvs.push(whileEnv); - data.potentiallyInvalidAssignmentInLoopsInfo.add(new PotentiallyInvalidAssignmentInfo(new ArrayList<>(), + data.potentiallyInvalidAssignmentInLoopsInfo.push(new PotentiallyInvalidAssignmentInfo(new ArrayList<>(), data.env.enclInvokable)); boolean prevStatementReturnsPanicsOrFails = data.statementReturnsPanicsOrFails; @@ -731,10 +732,10 @@ public void visit(BLangQueryAction queryAction, AnalyzerData data) { @Override public void visit(BLangDoClause doClause, AnalyzerData data) { SymbolEnv doEnv = doClause.env; - data.loopAndDoClauseEnvs.add(doEnv); + data.loopAndDoClauseEnvs.push(doEnv); data.loopAndDoClauseCount++; - data.potentiallyInvalidAssignmentInLoopsInfo.add(new PotentiallyInvalidAssignmentInfo(new ArrayList<>(), + data.potentiallyInvalidAssignmentInLoopsInfo.push(new PotentiallyInvalidAssignmentInfo(new ArrayList<>(), data.env.enclInvokable)); BLangBlockStmt body = doClause.body; @@ -922,7 +923,7 @@ private void handleInvalidAssignmentToTypeNarrowedVariableInLoop(List private void handlePotentiallyInvalidAssignmentsToTypeNarrowedVariablesInLoop( boolean branchTerminates, boolean isLoopBodyOrBranchWithContinueAsLastStmt, - Stack potentiallyInvalidAssignmentInLoopsInfo) { + Deque potentiallyInvalidAssignmentInLoopsInfo) { handlePotentiallyInvalidAssignmentsToTypeNarrowedVariablesInLoop( branchTerminates, isLoopBodyOrBranchWithContinueAsLastStmt, DiagnosticErrorCode.INVALID_ASSIGNMENT_TO_NARROWED_VAR_IN_LOOP, @@ -931,7 +932,7 @@ private void handlePotentiallyInvalidAssignmentsToTypeNarrowedVariablesInLoop( private void handlePotentiallyInvalidAssignmentsToTypeNarrowedVariablesInLoop( boolean branchTerminates, boolean isLoopBodyOrBranchWithContinueAsLastStmt, DiagnosticErrorCode errorCode, - Stack potentiallyInvalidAssignmentInLoopsInfo) { + Deque potentiallyInvalidAssignmentInLoopsInfo) { PotentiallyInvalidAssignmentInfo currentBranchInfo = potentiallyInvalidAssignmentInLoopsInfo.pop(); @@ -947,7 +948,7 @@ private void handlePotentiallyInvalidAssignmentsToTypeNarrowedVariablesInLoop( return; } - if (currentBranchLocations.isEmpty() || potentiallyInvalidAssignmentInLoopsInfo.empty()) { + if (currentBranchLocations.isEmpty() || potentiallyInvalidAssignmentInLoopsInfo.isEmpty()) { return; } @@ -961,10 +962,9 @@ private void handlePotentiallyInvalidAssignmentsToTypeNarrowedVariablesInLoop( } private List getVarRefs(BLangRecordVarRef varRef) { - List varRefs = varRef.recordRefFields.stream() - .map(e -> e.variableReference).collect(Collectors.toList()); - varRefs.add(varRef.restParam); - return varRefs; + return Stream.concat( + varRef.recordRefFields.stream().map(e -> e.variableReference), + Stream.of(varRef.restParam)).toList(); } private List getVarRefs(BLangErrorVarRef varRef) { @@ -1028,7 +1028,7 @@ public static class AnalyzerData { int loopAndDoClauseCount; BType booleanConstCondition; - Stack loopAndDoClauseEnvs = new Stack<>(); - Stack potentiallyInvalidAssignmentInLoopsInfo = new Stack<>(); + Deque loopAndDoClauseEnvs = new ArrayDeque<>(); + Deque potentiallyInvalidAssignmentInLoopsInfo = new ArrayDeque<>(); } } diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/SemanticAnalyzer.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/SemanticAnalyzer.java index d75255f64b92..84e687632a15 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/SemanticAnalyzer.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/SemanticAnalyzer.java @@ -222,9 +222,11 @@ import org.wso2.ballerinalang.util.AttachPoints; import org.wso2.ballerinalang.util.Flags; +import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; +import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; @@ -233,7 +235,6 @@ import java.util.Map; import java.util.Optional; import java.util.Set; -import java.util.Stack; import java.util.stream.Collectors; import static org.ballerinalang.model.symbols.SymbolOrigin.COMPILED_SOURCE; @@ -267,7 +268,7 @@ public class SemanticAnalyzer extends SimpleBLangNodeAnalyzer anonTypeNameSuffixes; + private final Deque anonTypeNameSuffixes; private final CompilerContext compilerContext; public static SemanticAnalyzer getInstance(CompilerContext context) { @@ -295,7 +296,7 @@ private SemanticAnalyzer(CompilerContext context) { this.constantValueResolver = ConstantValueResolver.getInstance(context); this.anonModelHelper = BLangAnonymousModelHelper.getInstance(context); this.unifier = new Unifier(); - this.anonTypeNameSuffixes = new Stack<>(); + this.anonTypeNameSuffixes = new ArrayDeque<>(); } public BLangPackage analyze(BLangPackage pkgNode) { @@ -321,6 +322,9 @@ public void visit(BLangPackage pkgNode, AnalyzerData data) { // Visit constants first. List topLevelNodes = pkgNode.topLevelNodes; + + // topLevelNodes are modified while iterating over them + // noinspection ForLoopReplaceableByForEach for (int i = 0; i < topLevelNodes.size(); i++) { TopLevelNode constant = topLevelNodes.get(i); if (constant.getKind() == NodeKind.CONSTANT) { @@ -331,9 +335,9 @@ public void visit(BLangPackage pkgNode, AnalyzerData data) { validateEnumMemberMetadata(pkgNode.constants); // Then resolve user defined types without analyzing type definitions that get added while analyzing other nodes - for (int i = 0; i < copyOfOriginalTopLevelNodes.size(); i++) { - if (copyOfOriginalTopLevelNodes.get(i).getKind() == NodeKind.TYPE_DEFINITION) { - analyzeNode((BLangNode) copyOfOriginalTopLevelNodes.get(i), data); + for (TopLevelNode copyOfOriginalTopLevelNode : copyOfOriginalTopLevelNodes) { + if (copyOfOriginalTopLevelNode.getKind() == NodeKind.TYPE_DEFINITION) { + analyzeNode((BLangNode) copyOfOriginalTopLevelNode, data); } } @@ -3860,7 +3864,7 @@ public void visit(BLangOnFailClause onFailClause, AnalyzerData data) { // Create a new block environment for the on-fail node. SymbolEnv onFailEnv = SymbolEnv.createBlockEnv(onFailClause.body, data.env); VariableDefinitionNode onFailVarDefNode = onFailClause.variableDefinitionNode; - Stack> onFailErrTypes = data.commonAnalyzerData.errorTypes; + Deque> onFailErrTypes = data.commonAnalyzerData.errorTypes; if (onFailVarDefNode != null) { BLangVariable variableNode = (BLangVariable) onFailVarDefNode.getVariable(); @@ -3978,7 +3982,7 @@ public void visit(BLangFail failNode, AnalyzerData data) { BLangExpression errorExpression = failNode.expr; BType errorExpressionType = typeChecker.checkExpr(errorExpression, data.env, data.prevEnvs, data.commonAnalyzerData); - if (!data.commonAnalyzerData.errorTypes.empty()) { + if (!data.commonAnalyzerData.errorTypes.isEmpty()) { BType failExprType = failNode.expr.getBType(); if (failExprType != symTable.semanticError) { BType errorTypes = types.getErrorTypes(failExprType); @@ -4308,13 +4312,13 @@ public void analyzeNode(BLangNode node, SymbolEnv env, QueryTypeChecker queryTyp analyzeNode(node, data); } - public void analyzeNode(BLangNode node, SymbolEnv env, Stack prevEnvs) { + public void analyzeNode(BLangNode node, SymbolEnv env, Deque prevEnvs) { AnalyzerData data = new AnalyzerData(env); data.prevEnvs = prevEnvs; analyzeNode(node, data); } - public void analyzeNode(BLangNode node, SymbolEnv env, Stack prevEnvs, + public void analyzeNode(BLangNode node, SymbolEnv env, Deque prevEnvs, Types.CommonAnalyzerData commonAnalyzerData) { AnalyzerData data = new AnalyzerData(env); data.prevEnvs = prevEnvs; @@ -4322,7 +4326,7 @@ public void analyzeNode(BLangNode node, SymbolEnv env, Stack prevEnvs analyzeNode(node, data); } - public void analyzeNode(BLangNode node, SymbolEnv env, Stack prevEnvs, + public void analyzeNode(BLangNode node, SymbolEnv env, Deque prevEnvs, QueryTypeChecker queryTypeChecker, Types.CommonAnalyzerData commonAnalyzerData) { AnalyzerData data = new AnalyzerData(env); data.prevEnvs = prevEnvs; @@ -5100,7 +5104,7 @@ public class AnalyzerData { boolean notCompletedNormally; boolean breakFound; Types.CommonAnalyzerData commonAnalyzerData = new Types.CommonAnalyzerData(); - Stack prevEnvs = new Stack<>(); + Deque prevEnvs = new ArrayDeque<>(); // The `typeChecker` field is used to set the correct typeChecker to call in query context. // TODO: Create new SemanticAnalyzer by extending current SemanticAnalyzer and use from QueryTypeChecker. TypeChecker typeChecker = TypeChecker.getInstance(compilerContext); diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/SymbolEnter.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/SymbolEnter.java index e4f2301ddb7a..943baf159e6b 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/SymbolEnter.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/SymbolEnter.java @@ -156,11 +156,13 @@ import org.wso2.ballerinalang.compiler.util.TypeTags; import org.wso2.ballerinalang.util.Flags; +import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; +import java.util.Deque; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; @@ -172,7 +174,6 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; -import java.util.Stack; import java.util.StringJoiner; import java.util.function.BinaryOperator; import java.util.function.Function; @@ -621,8 +622,8 @@ public void populateDistinctTypeIdsFromIncludedTypeReferences(BLangClassDefiniti private Comparator getTypePrecedenceComparator() { return (l, r) -> { - if (l instanceof OrderedNode && r instanceof OrderedNode) { - return ((OrderedNode) l).getPrecedence() - ((OrderedNode) r).getPrecedence(); + if (l instanceof OrderedNode lNode && r instanceof OrderedNode rNode) { + return lNode.getPrecedence() - rNode.getPrecedence(); } return 0; }; @@ -1266,7 +1267,7 @@ private void defineTypeNodes(List typeDefs, SymbolEnv env) { // dependencies or undefined types in type node. for (BLangNode unresolvedType : unresolvedTypes) { - Stack references = new Stack<>(); + Deque references = new ArrayDeque<>(); NodeKind unresolvedKind = unresolvedType.getKind(); if (unresolvedKind == NodeKind.TYPE_DEFINITION || unresolvedKind == NodeKind.CONSTANT) { TypeDefinition def = (TypeDefinition) unresolvedType; @@ -1344,7 +1345,7 @@ boolean isErrorIntersectionTypeCreatingNewType(BLangNode typeDef, SymbolEnv env) } private void checkErrors(SymbolEnv env, BLangNode unresolvedType, BLangNode currentTypeOrClassNode, - Stack visitedNodes, + Deque visitedNodes, boolean fromStructuredType) { // Check errors in the type definition. List memberTypeNodes; @@ -1438,25 +1439,23 @@ private void checkErrors(SymbolEnv env, BLangNode unresolvedType, BLangNode curr } private boolean isTypeConstructorAvailable(NodeKind unresolvedType) { - switch (unresolvedType) { - case OBJECT_TYPE: - case RECORD_TYPE: - case CONSTRAINED_TYPE: - case ARRAY_TYPE: - case TUPLE_TYPE_NODE: - case TABLE_TYPE: - case ERROR_TYPE: - case FUNCTION_TYPE: - case STREAM_TYPE: - return true; - default: - return false; - } + return switch (unresolvedType) { + case OBJECT_TYPE, + RECORD_TYPE, + CONSTRAINED_TYPE, + ARRAY_TYPE, + TUPLE_TYPE_NODE, + TABLE_TYPE, + ERROR_TYPE, + FUNCTION_TYPE, + STREAM_TYPE -> true; + default -> false; + }; } private void checkErrorsOfUserDefinedType(SymbolEnv env, BLangNode unresolvedType, BLangUserDefinedType currentTypeOrClassNode, - Stack visitedNodes, boolean fromStructuredType) { + Deque visitedNodes, boolean fromStructuredType) { String currentTypeNodeName = currentTypeOrClassNode.typeName.value; // Skip all types defined as anonymous types. if (currentTypeNodeName.startsWith("$")) { @@ -1490,10 +1489,13 @@ private void checkErrorsOfUserDefinedType(SymbolEnv env, BLangNode unresolvedTyp // Eg - A -> B -> C -> B // Last B is what we are currently checking // // In such case, we create a new list with relevant type names. - int i = visitedNodes.indexOf(currentTypeNodeName); - List dependencyList = new ArrayList<>(visitedNodes.size() - i); - for (; i < visitedNodes.size(); i++) { - dependencyList.add(visitedNodes.get(i)); + + List dependencyList = new ArrayList<>(); + for (String node : visitedNodes) { + dependencyList.add(0, node); + if (node.equals(currentTypeNodeName)) { + break; + } } if (!sameTypeNode && dependencyList.size() == 1 && dependencyList.get(0).equals(currentTypeNodeName)) { @@ -1882,19 +1884,20 @@ private BType defineSymbolForCyclicTypeDefinition(BLangTypeDefinition typeDef, S BTypeSymbol typeDefSymbol; BType newTypeNode; - switch (typeDef.typeNode.getKind()) { - case TUPLE_TYPE_NODE: + typeDefSymbol = switch (typeDef.typeNode.getKind()) { + case TUPLE_TYPE_NODE -> { newTypeNode = new BTupleType(null, new ArrayList<>(), true); - typeDefSymbol = Symbols.createTypeSymbol(SymTag.TUPLE_TYPE, Flags.asMask(typeDef.flagSet), + yield Symbols.createTypeSymbol(SymTag.TUPLE_TYPE, Flags.asMask(typeDef.flagSet), newTypeDefName, env.enclPkg.symbol.pkgID, newTypeNode, env.scope.owner, typeDef.name.pos, SOURCE); - break; - default: + } + default -> { newTypeNode = BUnionType.create(null, new LinkedHashSet<>(), true); - typeDefSymbol = Symbols.createTypeSymbol(SymTag.UNION_TYPE, Flags.asMask(typeDef.flagSet), + yield Symbols.createTypeSymbol(SymTag.UNION_TYPE, Flags.asMask(typeDef.flagSet), newTypeDefName, env.enclPkg.symbol.pkgID, newTypeNode, env.scope.owner, typeDef.name.pos, SOURCE); - } + } + }; typeDef.symbol = typeDefSymbol; defineTypeInMainScope(typeDefSymbol, typeDef, env); newTypeNode.tsymbol = typeDefSymbol; @@ -2401,8 +2404,7 @@ public void visit(BLangTupleVariable varNode) { if (varNode.restVariable != null) { memberVariables.add(varNode.restVariable); } - for (int i = 0; i < memberVariables.size(); i++) { - BLangVariable memberVar = memberVariables.get(i); + for (BLangVariable memberVar : memberVariables) { memberVar.isDeclaredWithVar = true; defineNode(memberVar, env); } @@ -2711,7 +2713,7 @@ boolean validateRecordVariable(BLangRecordVariable recordVar, SymbolEnv env) { Set bTypes = types.expandAndGetMemberTypesRecursive(unionType); List possibleTypes = bTypes.stream() .filter(rec -> doesRecordContainKeys(rec, recordVar.variableList, recordVar.restParam != null)) - .collect(Collectors.toList()); + .toList(); if (possibleTypes.isEmpty()) { dlog.error(recordVar.pos, DiagnosticErrorCode.INVALID_RECORD_BINDING_PATTERN, recordType); @@ -2762,7 +2764,7 @@ private BRecordType populatePossibleFields(BLangRecordVariable recordVar, List mappedFields = recordVar.variableList.stream().map(varKeyValue -> varKeyValue.getKey().value) - .collect(Collectors.toList()); + .toList(); LinkedHashMap fields = populateAndGetPossibleFieldsForRecVar(recordVar.pos, possibleTypes, mappedFields, recordSymbol, env); @@ -2991,7 +2993,7 @@ private boolean defineVariableList(BLangRecordVariable recordVar, BRecordType re if (recordVar.restParam != null) { BType restType = getRestParamType(recordVarType); List varList = recordVar.variableList.stream().map(t -> t.getKey().value) - .collect(Collectors.toList()); + .toList(); BRecordType restConstraint = createRecordTypeForRestField(recordVar.restParam.getPosition(), env, recordVarType, varList, restType); defineMemberNode(recordVar.restParam, env, restConstraint); @@ -4213,9 +4215,7 @@ private void defineUndefinedReadOnlyTypes(List typeDefNodes } private void populateImmutableTypeFieldsAndMembers(List typeDefNodes, SymbolEnv pkgEnv) { - int size = typeDefNodes.size(); - for (int i = 0; i < size; i++) { - BLangTypeDefinition typeDef = typeDefNodes.get(i); + for (BLangTypeDefinition typeDef : typeDefNodes) { NodeKind nodeKind = typeDef.typeNode.getKind(); if (nodeKind == NodeKind.OBJECT_TYPE) { if (((BObjectType) typeDef.symbol.type).mutableType == null) { @@ -4231,7 +4231,7 @@ private void populateImmutableTypeFieldsAndMembers(List typ SymbolEnv typeDefEnv = SymbolEnv.createTypeEnv(typeDef.typeNode, typeDef.symbol.scope, pkgEnv); ImmutableTypeCloner.defineUndefinedImmutableFields(typeDef, types, typeDefEnv, symTable, - anonymousModelHelper, names); + anonymousModelHelper, names); if (nodeKind != NodeKind.OBJECT_TYPE) { continue; @@ -4241,14 +4241,12 @@ private void populateImmutableTypeFieldsAndMembers(List typ BObjectType mutableObjectType = immutableObjectType.mutableType; ImmutableTypeCloner.defineObjectFunctions((BObjectTypeSymbol) immutableObjectType.tsymbol, - (BObjectTypeSymbol) mutableObjectType.tsymbol, names, symTable); + (BObjectTypeSymbol) mutableObjectType.tsymbol, names, symTable); } } private void validateFieldsAndSetReadOnlyType(List typeDefNodes, SymbolEnv pkgEnv) { - int origSize = typeDefNodes.size(); - for (int i = 0; i < origSize; i++) { - BLangNode typeDefOrClass = typeDefNodes.get(i); + for (BLangNode typeDefOrClass : typeDefNodes) { if (typeDefOrClass.getKind() == NodeKind.CLASS_DEFN) { BLangClassDefinition classDefinition = (BLangClassDefinition) typeDefOrClass; if (isObjectCtor(classDefinition)) { @@ -4606,9 +4604,9 @@ void defineInvokableSymbolParams(BLangInvokableNode invokableNode, BInvokableSym symResolver.validateInferTypedescParams(invokableNode.pos, invokableNode.getParameters(), retType); // Create function type - List paramTypes = paramSymbols.stream() + List paramTypes = new ArrayList<>(paramSymbols.stream() .map(paramSym -> paramSym.type) - .collect(Collectors.toList()); + .toList()); BInvokableTypeSymbol functionTypeSymbol = Symbols.createInvokableTypeSymbol(SymTag.FUNCTION_TYPE, invokableSymbol.flags, @@ -4671,7 +4669,7 @@ public void defineTypeNarrowedSymbol(Location location, SymbolEnv targetEnv, BVa if (type.tag == TypeTags.INVOKABLE && type.tsymbol != null) { BInvokableTypeSymbol tsymbol = (BInvokableTypeSymbol) type.tsymbol; BInvokableSymbol invokableSymbol = (BInvokableSymbol) varSymbol; - invokableSymbol.params = tsymbol.params == null ? null : new ArrayList(tsymbol.params); + invokableSymbol.params = tsymbol.params == null ? null : new ArrayList<>(tsymbol.params); invokableSymbol.restParam = tsymbol.restParam; invokableSymbol.retType = tsymbol.returnType; invokableSymbol.flags = tsymbol.flags; @@ -4867,7 +4865,7 @@ private BAttachedFunction createResourceFunction(BLangFunction funcNode, BInvoka p.symbol.kind = SymbolKind.PATH_PARAMETER; return p.symbol; }) - .collect(Collectors.toList()); + .toList(); BVarSymbol restPathParamSym = null; if (resourceFunction.restPathParam != null) { @@ -4882,8 +4880,7 @@ private BAttachedFunction createResourceFunction(BLangFunction funcNode, BInvoka int resourcePathCount = pathSegments.size(); List pathSegmentSymbols = new ArrayList<>(resourcePathCount); BResourcePathSegmentSymbol parentResource = null; - for (int i = 0; i < resourcePathCount; i++) { - BLangResourcePathSegment pathSegment = pathSegments.get(i); + for (BLangResourcePathSegment pathSegment : pathSegments) { Name resourcePathSymbolName = Names.fromString(pathSegment.name.value); BType resourcePathSegmentType = pathSegment.typeNode == null ? symTable.noType : symResolver.resolveTypeNode(pathSegment.typeNode, env); @@ -5158,7 +5155,7 @@ private void resolveIncludedFields(BLangStructureTypeNode structureTypeNode) { var.flagSet = field.symbol.getFlags(); return var; }); - }).collect(Collectors.toList()); + }).toList(); structureTypeNode.typeRefs.removeAll(invalidTypeRefs); } @@ -5219,8 +5216,7 @@ private void defineReferencedFunction(Location location, Set flagSet, Symb // Cache the function symbol. BAttachedFunction attachedFunc; - if (referencedFunc instanceof BResourceFunction) { - BResourceFunction resourceFunction = (BResourceFunction) referencedFunc; + if (referencedFunc instanceof BResourceFunction resourceFunction) { BResourceFunction cacheFunc = new BResourceFunction(referencedFunc.funcName, funcSymbol, (BInvokableType) funcSymbol.type, resourceFunction.accessor, resourceFunction.pathParams, resourceFunction.restPathParam, referencedFunc.pos); @@ -5249,7 +5245,8 @@ private boolean hasSameFunctionSignature(BInvokableSymbol attachedFuncSym, BInvo return false; } - return types.isAssignable(attachedFuncSym.type, referencedFuncSym.type); + return Symbols.isRemote(attachedFuncSym) == Symbols.isRemote(referencedFuncSym) && + types.isAssignable(attachedFuncSym.type, referencedFuncSym.type); } private boolean hasSameVisibilityModifier(long flags1, long flags2) { @@ -5261,14 +5258,15 @@ private String getCompleteFunctionSignature(BInvokableSymbol funcSymbol) { StringBuilder signatureBuilder = new StringBuilder(); StringJoiner paramListBuilder = new StringJoiner(", ", "(", ")"); - String visibilityModifier = ""; - if (Symbols.isPublic(funcSymbol)) { - visibilityModifier = "public "; + if (Symbols.isRemote(funcSymbol)) { + signatureBuilder.append("remote "); + } else if (Symbols.isPublic(funcSymbol)) { + signatureBuilder.append("public "); } else if (Symbols.isPrivate(funcSymbol)) { - visibilityModifier = "private "; + signatureBuilder.append("private "); } - signatureBuilder.append(visibilityModifier).append("function ") + signatureBuilder.append("function ") .append(funcSymbol.name.value.split("\\.")[1]); funcSymbol.params.forEach(param -> paramListBuilder.add(param.type.toString())); @@ -5445,7 +5443,7 @@ public ImportResolveHolder(BLangImportPackage resolved) { * * @since 0.985.0 */ - class LocationData { + private static class LocationData { private String name; private int row; diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/SymbolResolver.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/SymbolResolver.java index d4c568973ab1..e0d23ea3de8c 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/SymbolResolver.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/SymbolResolver.java @@ -121,8 +121,10 @@ import org.wso2.ballerinalang.util.Flags; import org.wso2.ballerinalang.util.Lists; +import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; +import java.util.Deque; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; @@ -1881,18 +1883,14 @@ public BSymbol getBinaryEqualityForTypeSets(OperatorKind opKind, BType lhsType, types.setImplicitCastExpr(binaryExpr.rhsExpr, rhsType, symTable.anyType); types.setImplicitCastExpr(binaryExpr.lhsExpr, lhsType, symTable.anyType); - switch (opKind) { - case REF_EQUAL: - // if one is a value type, consider === the same as == - return createEqualityOperator(OperatorKind.EQUAL, symTable.anyType, - symTable.anyType); - case REF_NOT_EQUAL: - // if one is a value type, consider !== the same as != - return createEqualityOperator(OperatorKind.NOT_EQUAL, symTable.anyType, - symTable.anyType); - default: - return createEqualityOperator(opKind, symTable.anyType, symTable.anyType); - } + return switch (opKind) { + // if one is a value type, consider === the same as == + case REF_EQUAL -> createEqualityOperator(OperatorKind.EQUAL, symTable.anyType, symTable.anyType); + // if one is a value type, consider !== the same as != + case REF_NOT_EQUAL -> createEqualityOperator(OperatorKind.NOT_EQUAL, symTable.anyType, + symTable.anyType); + default -> createEqualityOperator(opKind, symTable.anyType, symTable.anyType); + }; } } return symTable.notFoundSymbol; @@ -1916,15 +1914,13 @@ public BSymbol getBitwiseShiftOpsForTypeSets(OperatorKind opKind, BType lhsType, return createShiftOperator(opKind, lhsType, rhsType); case BITWISE_RIGHT_SHIFT: case BITWISE_UNSIGNED_RIGHT_SHIFT: - switch (Types.getImpliedType(lhsType).tag) { - case TypeTags.UNSIGNED32_INT: - case TypeTags.UNSIGNED16_INT: - case TypeTags.UNSIGNED8_INT: - case TypeTags.BYTE: - return createBinaryOperator(opKind, lhsType, rhsType, lhsType); - default: - return createShiftOperator(opKind, lhsType, rhsType); - } + return switch (Types.getImpliedType(lhsType).tag) { + case TypeTags.UNSIGNED32_INT, + TypeTags.UNSIGNED16_INT, + TypeTags.UNSIGNED8_INT, + TypeTags.BYTE -> createBinaryOperator(opKind, lhsType, rhsType, lhsType); + default -> createShiftOperator(opKind, lhsType, rhsType); + }; } } return symTable.notFoundSymbol; @@ -1990,16 +1986,13 @@ public BSymbol getArithmeticOpsForTypeSets(OperatorKind opKind, BType lhsType, B private boolean isIntFloatingPointMultiplication(OperatorKind opKind, BType lhsCompatibleType, BType rhsCompatibleType) { - switch (opKind) { - case MUL: - return lhsCompatibleType.tag == TypeTags.INT && isFloatingPointType(rhsCompatibleType) || - rhsCompatibleType.tag == TypeTags.INT && isFloatingPointType(lhsCompatibleType); - case DIV: - case MOD: - return isFloatingPointType(lhsCompatibleType) && rhsCompatibleType.tag == TypeTags.INT; - default: - return false; - } + return switch (opKind) { + case MUL -> lhsCompatibleType.tag == TypeTags.INT && isFloatingPointType(rhsCompatibleType) || + rhsCompatibleType.tag == TypeTags.INT && isFloatingPointType(lhsCompatibleType); + case DIV, + MOD -> isFloatingPointType(lhsCompatibleType) && rhsCompatibleType.tag == TypeTags.INT; + default -> false; + }; } private boolean isFloatingPointType(BType type) { @@ -2102,16 +2095,12 @@ public BSymbol getBinaryComparisonOpForTypeSets(OperatorKind opKind, BType lhsTy } if (validOrderedTypesExist) { - switch (opKind) { - case LESS_THAN: - return createBinaryComparisonOperator(OperatorKind.LESS_THAN, lhsType, rhsType); - case LESS_EQUAL: - return createBinaryComparisonOperator(OperatorKind.LESS_EQUAL, lhsType, rhsType); - case GREATER_THAN: - return createBinaryComparisonOperator(OperatorKind.GREATER_THAN, lhsType, rhsType); - default: - return createBinaryComparisonOperator(OperatorKind.GREATER_EQUAL, lhsType, rhsType); - } + return switch (opKind) { + case LESS_THAN -> createBinaryComparisonOperator(OperatorKind.LESS_THAN, lhsType, rhsType); + case LESS_EQUAL -> createBinaryComparisonOperator(OperatorKind.LESS_EQUAL, lhsType, rhsType); + case GREATER_THAN -> createBinaryComparisonOperator(OperatorKind.GREATER_THAN, lhsType, rhsType); + default -> createBinaryComparisonOperator(OperatorKind.GREATER_EQUAL, lhsType, rhsType); + }; } return symTable.notFoundSymbol; } @@ -2512,11 +2501,11 @@ private boolean isModuleLevelVar(BSymbol symbol) { public void populateAnnotationAttachmentSymbol(BLangAnnotationAttachment annotationAttachment, SymbolEnv env, ConstantValueResolver constantValueResolver) { - populateAnnotationAttachmentSymbol(annotationAttachment, env, constantValueResolver, new Stack<>()); + populateAnnotationAttachmentSymbol(annotationAttachment, env, constantValueResolver, new ArrayDeque<>()); } public void populateAnnotationAttachmentSymbol(BLangAnnotationAttachment annotationAttachment, SymbolEnv env, ConstantValueResolver constantValueResolver, - Stack anonTypeNameSuffixes) { + Deque anonTypeNameSuffixes) { BAnnotationSymbol annotationSymbol = annotationAttachment.annotationSymbol; if (annotationSymbol == null) { @@ -2648,14 +2637,10 @@ public List getListOfInterpolations(List seque } public boolean isReAtomNode(NodeKind kind) { - switch (kind) { - case REG_EXP_ATOM_CHAR_ESCAPE: - case REG_EXP_CHARACTER_CLASS: - case REG_EXP_CAPTURING_GROUP: - return true; - default: - return false; - } + return switch (kind) { + case REG_EXP_ATOM_CHAR_ESCAPE, REG_EXP_CHARACTER_CLASS, REG_EXP_CAPTURING_GROUP -> true; + default -> false; + }; } private boolean isDistinctXMLNSSymbol(BXMLNSSymbol symbol, BXMLNSSymbol foundSym) { diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/TypeChecker.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/TypeChecker.java index 38ae3cc9824d..709cc373a601 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/TypeChecker.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/TypeChecker.java @@ -187,8 +187,10 @@ import org.wso2.ballerinalang.util.Flags; import org.wso2.ballerinalang.util.Lists; +import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; +import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; @@ -199,7 +201,6 @@ import java.util.Map; import java.util.Optional; import java.util.Set; -import java.util.Stack; import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.stream.Collector; @@ -357,24 +358,24 @@ private BType checkExpr(BLangExpression expr, BType expType, AnalyzerData data) } public BType checkExpr(BLangExpression expr, SymbolEnv env) { - return checkExpr(expr, env, symTable.noType, new Stack<>()); + return checkExpr(expr, env, symTable.noType, new ArrayDeque<>()); } - public BType checkExpr(BLangExpression expr, SymbolEnv env, Stack prevEnvs, + public BType checkExpr(BLangExpression expr, SymbolEnv env, Deque prevEnvs, Types.CommonAnalyzerData commonAnalyzerData) { return checkExpr(expr, env, symTable.noType, prevEnvs, commonAnalyzerData); } - public BType checkExpr(BLangExpression expr, SymbolEnv env, BType expType, Stack prevEnvs) { + public BType checkExpr(BLangExpression expr, SymbolEnv env, BType expType, Deque prevEnvs) { final AnalyzerData data = new AnalyzerData(); data.env = env; data.prevEnvs = prevEnvs; - data.commonAnalyzerData.queryFinalClauses = new Stack<>(); - data.commonAnalyzerData.queryEnvs = new Stack<>(); + data.commonAnalyzerData.queryFinalClauses = new ArrayDeque<>(); + data.commonAnalyzerData.queryEnvs = new ArrayDeque<>(); return checkExpr(expr, env, expType, DiagnosticErrorCode.INCOMPATIBLE_TYPES, data); } - public BType checkExpr(BLangExpression expr, SymbolEnv env, BType expType, Stack prevEnvs, + public BType checkExpr(BLangExpression expr, SymbolEnv env, BType expType, Deque prevEnvs, Types.CommonAnalyzerData commonAnalyzerData) { final AnalyzerData data = new AnalyzerData(); data.env = env; @@ -639,8 +640,8 @@ public BType getIntegerLiteralType(BLangLiteral literalExpr, Object literalValue expectedType); return symTable.semanticError; } - if (literalValue instanceof Double) { - literalExpr.value = ((Double) literalValue).doubleValue(); + if (literalValue instanceof Double doubleValue) { + literalExpr.value = doubleValue.doubleValue(); } else { literalExpr.value = ((Long) literalValue).doubleValue(); } @@ -1033,7 +1034,7 @@ private BType getFiniteTypeWithValuesOfSingleType(BUnionType unionType, BType ma private BType getIntLiteralType(BType expType, Object literalValue, AnalyzerData data) { // The literalValue will be a string if it is not within the bounds of what is supported by Java Long, // indicating that it is an overflown Ballerina int - if (!(literalValue instanceof Long)) { + if (!(literalValue instanceof Long longValue)) { data.resultType = symTable.semanticError; return symTable.semanticError; } @@ -1041,37 +1042,37 @@ private BType getIntLiteralType(BType expType, Object literalValue, AnalyzerData case TypeTags.INT: return symTable.intType; case TypeTags.BYTE: - if (types.isByteLiteralValue((Long) literalValue)) { + if (types.isByteLiteralValue(longValue)) { return symTable.byteType; } break; case TypeTags.SIGNED32_INT: - if (types.isSigned32LiteralValue((Long) literalValue)) { + if (types.isSigned32LiteralValue(longValue)) { return symTable.signed32IntType; } break; case TypeTags.SIGNED16_INT: - if (types.isSigned16LiteralValue((Long) literalValue)) { + if (types.isSigned16LiteralValue(longValue)) { return symTable.signed16IntType; } break; case TypeTags.SIGNED8_INT: - if (types.isSigned8LiteralValue((Long) literalValue)) { + if (types.isSigned8LiteralValue(longValue)) { return symTable.signed8IntType; } break; case TypeTags.UNSIGNED32_INT: - if (types.isUnsigned32LiteralValue((Long) literalValue)) { + if (types.isUnsigned32LiteralValue(longValue)) { return symTable.unsigned32IntType; } break; case TypeTags.UNSIGNED16_INT: - if (types.isUnsigned16LiteralValue((Long) literalValue)) { + if (types.isUnsigned16LiteralValue(longValue)) { return symTable.unsigned16IntType; } break; case TypeTags.UNSIGNED8_INT: - if (types.isUnsigned8LiteralValue((Long) literalValue)) { + if (types.isUnsigned8LiteralValue(longValue)) { return symTable.unsigned8IntType; } break; @@ -1675,15 +1676,13 @@ private boolean validateTableConstructorExpr(BLangTableConstructorExpr tableCons switch (referredKeyTypeConstraint.tag) { case TypeTags.TUPLE: - for (BType type : ((BTupleType) referredKeyTypeConstraint).getTupleTypes()) { - memberTypes.add(type); - } + memberTypes.addAll(((BTupleType) referredKeyTypeConstraint).getTupleTypes()); break; case TypeTags.RECORD: Map fieldList = ((BRecordType) referredKeyTypeConstraint).getFields(); - memberTypes = fieldList.entrySet().stream() + memberTypes.addAll(fieldList.entrySet().stream() .filter(e -> fieldNameList.contains(e.getKey())).map(entry -> entry.getValue().type) - .collect(Collectors.toList()); + .toList()); if (memberTypes.isEmpty()) { memberTypes.add(keyTypeConstraint); } @@ -1951,26 +1950,22 @@ private void updateInferredTupleDetailsFromSpreadMember(Location spreadMemberPos private BType getListConstructorCompatibleNonUnionType(BType type, AnalyzerData data) { BType referredType = Types.getImpliedType(type); - switch (referredType.tag) { - case TypeTags.ARRAY: - case TypeTags.TUPLE: - case TypeTags.READONLY: - case TypeTags.TYPEDESC: - return type; - case TypeTags.JSON: - return !Symbols.isFlagOn(referredType.flags, Flags.READONLY) ? symTable.arrayJsonType : - ImmutableTypeCloner.getEffectiveImmutableType(null, types, symTable.arrayJsonType, - data.env, symTable, anonymousModelHelper, names); - case TypeTags.ANYDATA: - return !Symbols.isFlagOn(referredType.flags, Flags.READONLY) ? symTable.arrayAnydataType : - ImmutableTypeCloner.getEffectiveImmutableType(null, types, symTable.arrayAnydataType, - data.env, symTable, anonymousModelHelper, names); - case TypeTags.ANY: - return !Symbols.isFlagOn(referredType.flags, Flags.READONLY) ? symTable.arrayAllType : - ImmutableTypeCloner.getEffectiveImmutableType(null, types, symTable.arrayAllType, data.env, - symTable, anonymousModelHelper, names); - } - return symTable.semanticError; + return switch (referredType.tag) { + case TypeTags.ARRAY, + TypeTags.TUPLE, + TypeTags.READONLY, + TypeTags.TYPEDESC -> type; + case TypeTags.JSON -> !Symbols.isFlagOn(referredType.flags, Flags.READONLY) ? symTable.arrayJsonType : + ImmutableTypeCloner.getEffectiveImmutableType(null, types, symTable.arrayJsonType, + data.env, symTable, anonymousModelHelper, names); + case TypeTags.ANYDATA -> !Symbols.isFlagOn(referredType.flags, Flags.READONLY) ? symTable.arrayAnydataType : + ImmutableTypeCloner.getEffectiveImmutableType(null, types, symTable.arrayAnydataType, + data.env, symTable, anonymousModelHelper, names); + case TypeTags.ANY -> !Symbols.isFlagOn(referredType.flags, Flags.READONLY) ? symTable.arrayAllType : + ImmutableTypeCloner.getEffectiveImmutableType(null, types, symTable.arrayAllType, data.env, + symTable, anonymousModelHelper, names); + default -> symTable.semanticError; + }; } private BType checkArrayType(BLangListConstructorExpr listConstructor, BArrayType arrayType, AnalyzerData data) { @@ -3536,9 +3531,9 @@ private void checkFieldBasedAccess(BLangFieldBasedAccess fieldAccessExpr, boolea // First analyze the accessible expression. BLangExpression containerExpression = fieldAccessExpr.expr; - if (containerExpression instanceof BLangValueExpression) { - ((BLangValueExpression) containerExpression).isLValue = fieldAccessExpr.isLValue; - ((BLangValueExpression) containerExpression).isCompoundAssignmentLValue = + if (containerExpression instanceof BLangValueExpression valueExpression) { + valueExpression.isLValue = fieldAccessExpr.isLValue; + valueExpression.isCompoundAssignmentLValue = fieldAccessExpr.isCompoundAssignmentLValue; } @@ -3671,9 +3666,9 @@ public void visit(BLangIndexBasedAccess indexBasedAccessExpr, AnalyzerData data) return; } - if (containerExpression instanceof BLangValueExpression) { - ((BLangValueExpression) containerExpression).isLValue = indexBasedAccessExpr.isLValue; - ((BLangValueExpression) containerExpression).isCompoundAssignmentLValue = + if (containerExpression instanceof BLangValueExpression valueExpression) { + valueExpression.isLValue = indexBasedAccessExpr.isLValue; + valueExpression.isCompoundAssignmentLValue = indexBasedAccessExpr.isCompoundAssignmentLValue; } @@ -5705,7 +5700,7 @@ public BType checkCompatibilityWithConstructedNumericLiteral(BLangUnaryExpr unar return silentTypeCheckExpr(numericLiteral, referredType, data); } - public LinkedHashSet getIntSubtypesInUnionType(BUnionType expectedType) { + public LinkedHashSet getIntSubtypesInUnionType(BUnionType expectedType) { LinkedHashSet intTypesInUnion = new LinkedHashSet<>(expectedType.getMemberTypes().size()); for (BType type : expectedType.getMemberTypes()) { BType referredType = Types.getImpliedType(type); @@ -6101,17 +6096,13 @@ private boolean isXmlNamespaceAttribute(BLangXMLAttribute attribute) { } public BType getXMLSequenceType(BType xmlSubType) { - switch (Types.getImpliedType(xmlSubType).tag) { - case TypeTags.XML_ELEMENT: - return new BXMLType(symTable.xmlElementType, null); - case TypeTags.XML_COMMENT: - return new BXMLType(symTable.xmlCommentType, null); - case TypeTags.XML_PI: - return new BXMLType(symTable.xmlPIType, null); - default: - // Since 'xml:Text is same as xml<'xml:Text> - return symTable.xmlTextType; - } + return switch (Types.getImpliedType(xmlSubType).tag) { + case TypeTags.XML_ELEMENT -> new BXMLType(symTable.xmlElementType, null); + case TypeTags.XML_COMMENT -> new BXMLType(symTable.xmlCommentType, null); + case TypeTags.XML_PI -> new BXMLType(symTable.xmlPIType, null); + // Since 'xml:Text is same as xml<'xml:Text> + default -> symTable.xmlTextType; + }; } @Override @@ -6520,7 +6511,7 @@ protected void visitCheckAndCheckPanicExpr(BLangCheckedExpr checkedExpr, Analyze errorTypes.add(exprType); } - if (operatorKind == OperatorKind.CHECK && !data.commonAnalyzerData.errorTypes.empty()) { + if (operatorKind == OperatorKind.CHECK && !data.commonAnalyzerData.errorTypes.isEmpty()) { data.commonAnalyzerData.errorTypes.peek().add(types.getErrorTypes(checkedExpr.expr.getBType())); } @@ -6655,19 +6646,19 @@ public void visit(BLangAnnotAccessExpr annotAccessExpr, AnalyzerData data) { // Private methods private boolean isValidVariableReference(BLangExpression varRef) { - switch (varRef.getKind()) { - case SIMPLE_VARIABLE_REF: - case RECORD_VARIABLE_REF: - case TUPLE_VARIABLE_REF: - case ERROR_VARIABLE_REF: - case FIELD_BASED_ACCESS_EXPR: - case INDEX_BASED_ACCESS_EXPR: - case XML_ATTRIBUTE_ACCESS_EXPR: - return true; - default: + return switch (varRef.getKind()) { + case SIMPLE_VARIABLE_REF, + RECORD_VARIABLE_REF, + TUPLE_VARIABLE_REF, + ERROR_VARIABLE_REF, + FIELD_BASED_ACCESS_EXPR, + INDEX_BASED_ACCESS_EXPR, + XML_ATTRIBUTE_ACCESS_EXPR -> true; + default -> { dlog.error(varRef.pos, DiagnosticErrorCode.INVALID_RECORD_BINDING_PATTERN, varRef.getBType()); - return false; - } + yield false; + } + }; } private BType getEffectiveReadOnlyType(Location pos, BType type, AnalyzerData data) { @@ -7756,25 +7747,21 @@ private void checkTypeParamExpr(Location pos, BLangExpression arg, BType expecte private boolean requireTypeInference(BLangExpression expr, boolean inferTypeForNumericLiteral) { - switch (expr.getKind()) { - case GROUP_EXPR: - return requireTypeInference(((BLangGroupExpr) expr).expression, inferTypeForNumericLiteral); - case ARROW_EXPR: - case LIST_CONSTRUCTOR_EXPR: - case RECORD_LITERAL_EXPR: - case OBJECT_CTOR_EXPRESSION: - case RAW_TEMPLATE_LITERAL: - case TABLE_CONSTRUCTOR_EXPR: - case TYPE_INIT_EXPR: - case ERROR_CONSTRUCTOR_EXPRESSION: - return true; - case ELVIS_EXPR: - case TERNARY_EXPR: - case NUMERIC_LITERAL: - return inferTypeForNumericLiteral; - default: - return false; - } + return switch (expr.getKind()) { + case GROUP_EXPR -> requireTypeInference(((BLangGroupExpr) expr).expression, inferTypeForNumericLiteral); + case ARROW_EXPR, + LIST_CONSTRUCTOR_EXPR, + RECORD_LITERAL_EXPR, + OBJECT_CTOR_EXPRESSION, + RAW_TEMPLATE_LITERAL, + TABLE_CONSTRUCTOR_EXPR, + TYPE_INIT_EXPR, + ERROR_CONSTRUCTOR_EXPRESSION -> true; + case ELVIS_EXPR, + TERNARY_EXPR, + NUMERIC_LITERAL -> inferTypeForNumericLiteral; + default -> false; + }; } private boolean isNotObjectConstructorWithObjectSuperTypeInTypeCastExpr(BLangExpression expression, @@ -8943,31 +8930,30 @@ private BType checkIndexAccessExpr(BLangIndexBasedAccess indexBasedAccessExpr, A } private Long getConstIndex(BLangExpression indexExpr) { - switch (indexExpr.getKind()) { - case GROUP_EXPR: + return switch (indexExpr.getKind()) { + case GROUP_EXPR -> { BLangGroupExpr groupExpr = (BLangGroupExpr) indexExpr; - return getConstIndex(groupExpr.expression); - case NUMERIC_LITERAL: - return (Long) ((BLangLiteral) indexExpr).value; - case UNARY_EXPR: + yield getConstIndex(groupExpr.expression); + } + case NUMERIC_LITERAL -> (Long) ((BLangLiteral) indexExpr).value; + case UNARY_EXPR -> { BLangNumericLiteral numericLiteral = Types.constructNumericLiteralFromUnaryExpr((BLangUnaryExpr) indexExpr); - return (Long) numericLiteral.value; - default: - return (Long) ((BConstantSymbol) ((BLangSimpleVarRef) indexExpr).symbol).value.value; - } + yield (Long) numericLiteral.value; + } + default -> (Long) ((BConstantSymbol) ((BLangSimpleVarRef) indexExpr).symbol).value.value; + }; } private String getConstFieldName(BLangExpression indexExpr) { - switch (indexExpr.getKind()) { - case GROUP_EXPR: + return switch (indexExpr.getKind()) { + case GROUP_EXPR -> { BLangGroupExpr groupExpr = (BLangGroupExpr) indexExpr; - return getConstFieldName(groupExpr.expression); - case LITERAL: - return (String) ((BLangLiteral) indexExpr).value; - default: - return (String) ((BConstantSymbol) ((BLangSimpleVarRef) indexExpr).symbol).value.value; - } + yield getConstFieldName(groupExpr.expression); + } + case LITERAL -> (String) ((BLangLiteral) indexExpr).value; + default -> (String) ((BConstantSymbol) ((BLangSimpleVarRef) indexExpr).symbol).value.value; + }; } private BType checkArrayIndexBasedAccess(BLangIndexBasedAccess indexBasedAccess, BType indexExprType, @@ -9882,7 +9868,7 @@ String recordsToString(Set recordTypeSet) { public static class AnalyzerData { public SymbolEnv env; boolean isTypeChecked; - Stack prevEnvs; + Deque prevEnvs; Types.CommonAnalyzerData commonAnalyzerData = new Types.CommonAnalyzerData(); DiagnosticCode diagCode; BType expType; diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/TypeParamAnalyzer.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/TypeParamAnalyzer.java index 7eea5b686154..b985d97d8fce 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/TypeParamAnalyzer.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/TypeParamAnalyzer.java @@ -270,23 +270,19 @@ private BType createBuiltInType(BType type, Name name, long flags) { BType referredType = Types.getImpliedType(type); int tag = referredType.tag; // Handle built-in types. - switch (tag) { - case TypeTags.INT: - case TypeTags.BYTE: - case TypeTags.FLOAT: - case TypeTags.DECIMAL: - case TypeTags.STRING: - case TypeTags.BOOLEAN: - return new BType(tag, null, name, flags); - case TypeTags.ANY: - return new BAnyType(tag, null, name, flags); - case TypeTags.ANYDATA: - return createAnydataType((BUnionType) referredType, name, flags); - case TypeTags.READONLY: - return new BReadonlyType(tag, null, name, flags); - } - // For others, we will use TSymbol. - return type; + return switch (tag) { + case TypeTags.INT, + TypeTags.BYTE, + TypeTags.FLOAT, + TypeTags.DECIMAL, + TypeTags.STRING, + TypeTags.BOOLEAN -> new BType(tag, null, name, flags); + case TypeTags.ANY -> new BAnyType(tag, null, name, flags); + case TypeTags.ANYDATA -> createAnydataType((BUnionType) referredType, name, flags); + case TypeTags.READONLY -> new BReadonlyType(tag, null, name, flags); + // For others, we will use TSymbol. + default -> type; + }; } private BType createTypeParamType(BSymbol symbol, BType type, Name name, long flags) { @@ -1112,8 +1108,7 @@ private BType getMatchingObjectBoundType(BObjectType expType, SymbolEnv env, Has private BAttachedFunction duplicateAttachFunc(BAttachedFunction expFunc, BInvokableType matchType, BInvokableSymbol invokableSymbol) { - if (expFunc instanceof BResourceFunction) { - BResourceFunction resourceFunction = (BResourceFunction) expFunc; + if (expFunc instanceof BResourceFunction resourceFunction) { BResourceFunction newResourceFunc = new BResourceFunction(resourceFunction.funcName, invokableSymbol, matchType, resourceFunction.accessor, resourceFunction.pathParams, resourceFunction.restPathParam, expFunc.pos); diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/TypeResolver.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/TypeResolver.java index 60d046846775..2e4e4d944cdb 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/TypeResolver.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/TypeResolver.java @@ -112,7 +112,9 @@ import org.wso2.ballerinalang.compiler.util.TypeTags; import org.wso2.ballerinalang.util.Flags; +import java.util.ArrayDeque; import java.util.ArrayList; +import java.util.Deque; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; @@ -123,8 +125,6 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; -import java.util.Stack; -import java.util.stream.Collectors; import static org.ballerinalang.model.symbols.SymbolOrigin.BUILTIN; import static org.ballerinalang.model.symbols.SymbolOrigin.SOURCE; @@ -160,14 +160,14 @@ public class TypeResolver { private HashMap intersectionTypeList; public HashSet resolvedConstants = new HashSet<>(); private ArrayList resolvingConstants = new ArrayList<>(); - private Stack resolvingModuleDefs; + private Deque resolvingModuleDefs; private HashSet resolvedClassDef = new HashSet<>(); private Map modTable = new LinkedHashMap<>(); private Map constantMap = new HashMap<>(); private HashSet unknownTypeRefs; private SymbolEnv pkgEnv; private int currentDepth; - private Stack resolvingTypes; + private Deque resolvingTypes; public HashSet resolvingStructureTypes = new HashSet<>(); public TypeResolver(CompilerContext context) { @@ -225,8 +225,8 @@ public void defineBTypes(List moduleDefs, SymbolEnv pkgEnv) { } for (BLangNode def : moduleDefs) { - resolvingTypes = new Stack<>(); - resolvingModuleDefs = new Stack<>(); + resolvingTypes = new ArrayDeque<>(); + resolvingModuleDefs = new ArrayDeque<>(); switch (def.getKind()) { case CLASS_DEFN -> { intersectionTypeList = new HashMap<>(); @@ -593,15 +593,10 @@ private void logErrorForRestrictedCyclicTypes(BLangType typeNode, String name) { } private boolean isNotRestrictedCyclicTypeNode(BLangType typeNode) { - switch (typeNode.getKind()) { - case USER_DEFINED_TYPE: - case ARRAY_TYPE: - case CONSTRAINED_TYPE: - case INTERSECTION_TYPE_NODE: - return false; - default: - return true; - } + return switch (typeNode.getKind()) { + case USER_DEFINED_TYPE, ARRAY_TYPE, CONSTRAINED_TYPE, INTERSECTION_TYPE_NODE -> false; + default -> true; + }; } private void logInvalidCyclicReferenceError(String currentDefnName, Location pos) { @@ -610,12 +605,14 @@ private void logInvalidCyclicReferenceError(String currentDefnName, Location pos // Eg - A -> B -> C -> B // Last B is what we are currently checking // // In such case, we create a new list with relevant type names. - int i = resolvingModuleDefs.indexOf(currentDefnName); - List dependencyList = new ArrayList<>(resolvingModuleDefs.size() - i); - for (; i < resolvingModuleDefs.size(); i++) { - dependencyList.add(resolvingModuleDefs.get(i)); - } + List dependencyList = new ArrayList<>(); dependencyList.add(currentDefnName); + for (String resolvingModuleDef : resolvingModuleDefs) { + dependencyList.add(0, resolvingModuleDef); + if (resolvingModuleDef.equals(currentDefnName)) { + break; + } + } dlog.error(pos, DiagnosticErrorCode.CYCLIC_TYPE_REFERENCE, dependencyList); } @@ -699,56 +696,25 @@ private BType resolveTypeDesc(SymbolEnv symEnv, BLangTypeDefinition defn, int de data.typeDefinition = defn; data.depth = depth; - BType resultType; - switch (td.getKind()) { - case VALUE_TYPE: - resultType = resolveTypeDesc((BLangValueType) td, symEnv); - break; - case CONSTRAINED_TYPE: // map and typedesc - resultType = resolveTypeDesc((BLangConstrainedType) td, data); - break; - case ARRAY_TYPE: - resultType = resolveTypeDesc(((BLangArrayType) td), data); - break; - case TUPLE_TYPE_NODE: - resultType = resolveTypeDesc((BLangTupleTypeNode) td, data); - break; - case RECORD_TYPE: - resultType = resolveTypeDesc((BLangRecordTypeNode) td, data); - break; - case OBJECT_TYPE: - resultType = resolveTypeDesc((BLangObjectTypeNode) td, data); - break; - case FUNCTION_TYPE: - resultType = resolveTypeDesc((BLangFunctionTypeNode) td, data); - break; - case ERROR_TYPE: - resultType = resolveTypeDesc((BLangErrorType) td, data); - break; - case UNION_TYPE_NODE: - resultType = resolveTypeDesc((BLangUnionTypeNode) td, data); - break; - case INTERSECTION_TYPE_NODE: - resultType = resolveTypeDesc((BLangIntersectionTypeNode) td, data, anonymous); - break; - case USER_DEFINED_TYPE: - resultType = resolveTypeDesc((BLangUserDefinedType) td, data); - break; - case BUILT_IN_REF_TYPE: - resultType = resolveTypeDesc((BLangBuiltInRefTypeNode) td, symEnv); - break; - case FINITE_TYPE_NODE: - resultType = resolveSingletonType((BLangFiniteTypeNode) td, symEnv); - break; - case TABLE_TYPE: - resultType = resolveTypeDesc((BLangTableTypeNode) td, data); - break; - case STREAM_TYPE: - resultType = resolveTypeDesc((BLangStreamType) td, data); - break; - default: - throw new AssertionError("Invalid type"); - } + BType resultType = switch (td.getKind()) { + case VALUE_TYPE -> resolveTypeDesc((BLangValueType) td, symEnv); + // map and typedesc + case CONSTRAINED_TYPE -> resolveTypeDesc((BLangConstrainedType) td, data); + case ARRAY_TYPE -> resolveTypeDesc(((BLangArrayType) td), data); + case TUPLE_TYPE_NODE -> resolveTypeDesc((BLangTupleTypeNode) td, data); + case RECORD_TYPE -> resolveTypeDesc((BLangRecordTypeNode) td, data); + case OBJECT_TYPE -> resolveTypeDesc((BLangObjectTypeNode) td, data); + case FUNCTION_TYPE -> resolveTypeDesc((BLangFunctionTypeNode) td, data); + case ERROR_TYPE -> resolveTypeDesc((BLangErrorType) td, data); + case UNION_TYPE_NODE -> resolveTypeDesc((BLangUnionTypeNode) td, data); + case INTERSECTION_TYPE_NODE -> resolveTypeDesc((BLangIntersectionTypeNode) td, data, anonymous); + case USER_DEFINED_TYPE -> resolveTypeDesc((BLangUserDefinedType) td, data); + case BUILT_IN_REF_TYPE -> resolveTypeDesc((BLangBuiltInRefTypeNode) td, symEnv); + case FINITE_TYPE_NODE -> resolveSingletonType((BLangFiniteTypeNode) td, symEnv); + case TABLE_TYPE -> resolveTypeDesc((BLangTableTypeNode) td, data); + case STREAM_TYPE -> resolveTypeDesc((BLangStreamType) td, data); + default -> throw new AssertionError("Invalid type"); + }; BType refType = Types.getImpliedType(resultType); if (refType != symTable.noType) { @@ -779,17 +745,13 @@ private BType resolveTypeDesc(BLangConstrainedType td, ResolverData data) { currentDepth = data.depth; TypeKind typeKind = ((BLangBuiltInRefTypeNode) td.getType()).getTypeKind(); - switch (typeKind) { - case MAP: - return resolveMapTypeDesc(td, data); - case XML: - return resolveXmlTypeDesc(td, data); - case FUTURE: - return resolveFutureTypeDesc(td, data); - case TYPEDESC: - return resolveTypedescTypeDesc(td, data); - } - throw new IllegalStateException("unknown constrained type found: " + typeKind); + return switch (typeKind) { + case MAP -> resolveMapTypeDesc(td, data); + case XML -> resolveXmlTypeDesc(td, data); + case FUTURE -> resolveFutureTypeDesc(td, data); + case TYPEDESC -> resolveTypedescTypeDesc(td, data); + default -> throw new IllegalStateException("unknown constrained type found: " + typeKind); + }; } private BType resolveTypedescTypeDesc(BLangConstrainedType td, ResolverData data) { @@ -1973,7 +1935,7 @@ public void resolveConstant(SymbolEnv symEnv, Map modTable, B if (resolvingConstants.contains(constant)) { // To identify cycles. dlog.error(constant.pos, DiagnosticErrorCode.CONSTANT_CYCLIC_REFERENCE, (this.resolvingConstants).stream().map(constNode -> constNode.symbol) - .collect(Collectors.toList())); + .toList()); constant.setBType(symTable.semanticError); return; } @@ -2159,7 +2121,7 @@ private void addAssociatedTypeDefinition(BLangConstant constant, BType type, * * @since 2201.7.0 */ - class ResolverData { + private static class ResolverData { SymbolEnv env; Map modTable; int depth; @@ -2171,7 +2133,7 @@ class ResolverData { * * @since 2201.7.0 */ - class LocationData { + private static class LocationData { private String name; private int row; private int column; diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/Types.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/Types.java index 600e0ab8a79a..5d90b2db49d6 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/Types.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/Types.java @@ -115,8 +115,10 @@ import java.math.BigDecimal; import java.math.MathContext; import java.nio.charset.StandardCharsets; +import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Base64; +import java.util.Deque; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; @@ -129,7 +131,6 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; -import java.util.Stack; import static io.ballerina.runtime.api.constants.RuntimeConstants.UNDERSCORE; import static org.ballerinalang.model.symbols.SymbolOrigin.SOURCE; @@ -439,24 +440,22 @@ private boolean isSameType(BType source, BType target, Set unresolvedT } public boolean isValueType(BType type) { - switch (getImpliedType(type).tag) { - case TypeTags.BOOLEAN: - case TypeTags.BYTE: - case TypeTags.DECIMAL: - case TypeTags.FLOAT: - case TypeTags.INT: - case TypeTags.STRING: - case TypeTags.SIGNED32_INT: - case TypeTags.SIGNED16_INT: - case TypeTags.SIGNED8_INT: - case TypeTags.UNSIGNED32_INT: - case TypeTags.UNSIGNED16_INT: - case TypeTags.UNSIGNED8_INT: - case TypeTags.CHAR_STRING: - return true; - default: - return false; - } + return switch (getImpliedType(type).tag) { + case TypeTags.BOOLEAN, + TypeTags.BYTE, + TypeTags.DECIMAL, + TypeTags.FLOAT, + TypeTags.INT, + TypeTags.STRING, + TypeTags.SIGNED32_INT, + TypeTags.SIGNED16_INT, + TypeTags.SIGNED8_INT, + TypeTags.UNSIGNED32_INT, + TypeTags.UNSIGNED16_INT, + TypeTags.UNSIGNED8_INT, + TypeTags.CHAR_STRING -> true; + default -> false; + }; } boolean isBasicNumericType(BType bType) { @@ -1088,17 +1087,11 @@ private boolean isAssignableRecordType(BRecordType recordType, BType type, Set ((BMapType) type).constraint; + case TypeTags.JSON -> type; + default -> throw new IllegalArgumentException("Incompatible target type: " + type); + }; return recordFieldsAssignableToType(recordType, targetType, unresolvedTypes); } @@ -1487,22 +1480,20 @@ public boolean isInherentlyImmutableType(BType type) { return true; } - switch (type.tag) { - case TypeTags.XML_TEXT: - case TypeTags.FINITE: // Assuming a finite type will only have members from simple basic types. - case TypeTags.READONLY: - case TypeTags.NIL: - case TypeTags.NEVER: - case TypeTags.ERROR: - case TypeTags.INVOKABLE: - case TypeTags.TYPEDESC: - case TypeTags.HANDLE: - case TypeTags.REGEXP: - return true; - case TypeTags.XML: - return getImpliedType(((BXMLType) type).constraint).tag == TypeTags.NEVER; - } - return false; + return switch (type.tag) { + case TypeTags.XML_TEXT, + TypeTags.FINITE, // Assuming a finite type will only have members from simple basic types. + TypeTags.READONLY, + TypeTags.NIL, + TypeTags.NEVER, + TypeTags.ERROR, + TypeTags.INVOKABLE, + TypeTags.TYPEDESC, + TypeTags.HANDLE, + TypeTags.REGEXP -> true; + case TypeTags.XML -> getImpliedType(((BXMLType) type).constraint).tag == TypeTags.NEVER; + default -> false; + }; } /** @@ -2712,12 +2703,10 @@ public boolean checkListenerCompatibility(BType bType) { } public boolean isValidErrorDetailType(BType detailType) { - switch (getImpliedType(detailType).tag) { - case TypeTags.MAP: - case TypeTags.RECORD: - return isAssignable(detailType, symTable.detailType); - } - return false; + return switch (getImpliedType(detailType).tag) { + case TypeTags.MAP, TypeTags.RECORD -> isAssignable(detailType, symTable.detailType); + default -> false; + }; } // private methods @@ -2749,23 +2738,20 @@ public Boolean visit(BType target, BType source) { return true; } - switch (t.tag) { - case TypeTags.INT: - case TypeTags.BYTE: - case TypeTags.FLOAT: - case TypeTags.DECIMAL: - case TypeTags.STRING: - case TypeTags.BOOLEAN: - return t.tag == s.tag - && ((TypeParamAnalyzer.isTypeParam(t) || TypeParamAnalyzer.isTypeParam(s)) || - (t.tag == TypeTags.TYPEREFDESC || s.tag == TypeTags.TYPEREFDESC)); - case TypeTags.ANY: - case TypeTags.ANYDATA: - return t.tag == s.tag && hasSameReadonlyFlag(s, t) - && (TypeParamAnalyzer.isTypeParam(t) || TypeParamAnalyzer.isTypeParam(s)); - default: - return false; - } + return switch (t.tag) { + case TypeTags.INT, + TypeTags.BYTE, + TypeTags.FLOAT, + TypeTags.DECIMAL, + TypeTags.STRING, + TypeTags.BOOLEAN -> t.tag == s.tag && + ((TypeParamAnalyzer.isTypeParam(t) || TypeParamAnalyzer.isTypeParam(s)) || + (t.tag == TypeTags.TYPEREFDESC || s.tag == TypeTags.TYPEREFDESC)); + case TypeTags.ANY, + TypeTags.ANYDATA -> t.tag == s.tag && hasSameReadonlyFlag(s, t) && + (TypeParamAnalyzer.isTypeParam(t) || TypeParamAnalyzer.isTypeParam(s)); + default -> false; + }; } @Override @@ -3069,24 +3055,20 @@ public Boolean visit(BType target, BType source) { if (t == s) { return true; } - switch (t.tag) { - case TypeTags.INT: - case TypeTags.BYTE: - case TypeTags.FLOAT: - case TypeTags.DECIMAL: - case TypeTags.STRING: - case TypeTags.BOOLEAN: - return t.tag == s.tag - && ((TypeParamAnalyzer.isTypeParam(t) || TypeParamAnalyzer.isTypeParam(s)) || - (t.tag == TypeTags.TYPEREFDESC || s.tag == TypeTags.TYPEREFDESC)); - case TypeTags.ANY: - case TypeTags.ANYDATA: - return t.tag == s.tag && hasSameReadonlyFlag(s, t) - && (TypeParamAnalyzer.isTypeParam(t) || TypeParamAnalyzer.isTypeParam(s)); - default: - break; - } - return false; + return switch (t.tag) { + case TypeTags.INT, + TypeTags.BYTE, + TypeTags.FLOAT, + TypeTags.DECIMAL, + TypeTags.STRING, + TypeTags.BOOLEAN -> t.tag == s.tag && + ((TypeParamAnalyzer.isTypeParam(t) || TypeParamAnalyzer.isTypeParam(s)) || + (t.tag == TypeTags.TYPEREFDESC || s.tag == TypeTags.TYPEREFDESC)); + case TypeTags.ANY, + TypeTags.ANYDATA -> t.tag == s.tag && hasSameReadonlyFlag(s, t) && + (TypeParamAnalyzer.isTypeParam(t) || TypeParamAnalyzer.isTypeParam(s)); + default -> false; + }; } @@ -3570,19 +3552,18 @@ private boolean isInvalidNeverField(BField lhsField, BRecordType rhsType) { } BType restFieldType = rhsType.restFieldType; - switch (restFieldType.tag) { - case TypeTags.UNION: + return switch (restFieldType.tag) { + case TypeTags.UNION -> { for (BType member : ((BUnionType) restFieldType).getOriginalMemberTypes()) { if (getImpliedType(member).tag == NEVER) { - return false; + yield false; } } - return true; - case NEVER: - return false; - default: - return true; - } + yield true; + } + case NEVER -> false; + default -> true; + }; } private Optional getMatchingInvokableType(List rhsFuncList, @@ -3670,7 +3651,7 @@ private boolean isAssignableToUnionType(BType source, BType target, Set sourceIterator = sourceTypes.iterator(); while (sourceIterator.hasNext()) { BType sMember = sourceIterator.next(); if (sMember.tag == TypeTags.NEVER) { @@ -3693,8 +3674,7 @@ private boolean isAssignableToUnionType(BType source, BType target, Set targetIterator = targetTypes.iterator(); while (targetIterator.hasNext()) { BType t = targetIterator.next(); if (isAssignable(sMember, t, unresolvedTypes)) { @@ -3736,7 +3716,7 @@ private boolean isAssignableToUnionType(BType source, BType target, Set targetIterator = targetTypes.iterator(); boolean selfReferencedSource = (sourceMember != source) && isSelfReferencedStructuredType(source, sourceMember); @@ -3819,7 +3799,7 @@ public static void fixSelfReferencingSameUnion(BType originalMemberType, BUnionT LinkedHashSet readOnlyMemTypes) { boolean sameMember = originalMemberType == immutableMemberType; if (originalMemberType.tag == TypeTags.ARRAY) { - var arrayType = (BArrayType) originalMemberType; + BArrayType arrayType = (BArrayType) originalMemberType; if (origUnionType == arrayType.eType) { if (sameMember) { BArrayType newArrayType = new BArrayType(newImmutableUnion, arrayType.tsymbol, arrayType.size, @@ -3831,7 +3811,7 @@ public static void fixSelfReferencingSameUnion(BType originalMemberType, BUnionT } } } else if (originalMemberType.tag == TypeTags.MAP) { - var mapType = (BMapType) originalMemberType; + BMapType mapType = (BMapType) originalMemberType; if (origUnionType == mapType.constraint) { if (sameMember) { BMapType newMapType = new BMapType(mapType.tag, newImmutableUnion, mapType.tsymbol, mapType.flags); @@ -3842,7 +3822,7 @@ public static void fixSelfReferencingSameUnion(BType originalMemberType, BUnionT } } } else if (originalMemberType.tag == TypeTags.TABLE) { - var tableType = (BTableType) originalMemberType; + BTableType tableType = (BTableType) originalMemberType; if (origUnionType == tableType.constraint) { if (sameMember) { BTableType newTableType = new BTableType(tableType.tag, newImmutableUnion, tableType.tsymbol, @@ -3855,10 +3835,10 @@ public static void fixSelfReferencingSameUnion(BType originalMemberType, BUnionT return; } - var immutableConstraint = ((BTableType) immutableMemberType).constraint; + BType immutableConstraint = ((BTableType) immutableMemberType).constraint; if (tableType.constraint.tag == TypeTags.MAP) { sameMember = tableType.constraint == immutableConstraint; - var mapType = (BMapType) tableType.constraint; + BMapType mapType = (BMapType) tableType.constraint; if (origUnionType == mapType.constraint) { if (sameMember) { BMapType newMapType = new BMapType(mapType.tag, newImmutableUnion, mapType.tsymbol, @@ -4273,26 +4253,23 @@ public boolean isLiteralCompatibleWithBuiltinTypeWithSubTypes(BLangLiteral liter return true; } - switch (targetType.tag) { - case TypeTags.BYTE: - return literalType.tag == TypeTags.INT && isByteLiteralValue((Long) literal.value); - case TypeTags.SIGNED32_INT: - return literalType.tag == TypeTags.INT && isSigned32LiteralValue((Long) literal.value); - case TypeTags.SIGNED16_INT: - return literalType.tag == TypeTags.INT && isSigned16LiteralValue((Long) literal.value); - case TypeTags.SIGNED8_INT: - return literalType.tag == TypeTags.INT && isSigned8LiteralValue((Long) literal.value); - case TypeTags.UNSIGNED32_INT: - return literalType.tag == TypeTags.INT && isUnsigned32LiteralValue((Long) literal.value); - case TypeTags.UNSIGNED16_INT: - return literalType.tag == TypeTags.INT && isUnsigned16LiteralValue((Long) literal.value); - case TypeTags.UNSIGNED8_INT: - return literalType.tag == TypeTags.INT && isUnsigned8LiteralValue((Long) literal.value); - case TypeTags.CHAR_STRING: - return literalType.tag == TypeTags.STRING && isCharLiteralValue((String) literal.value); - default: - return false; - } + return switch (targetType.tag) { + case TypeTags.BYTE -> literalType.tag == TypeTags.INT && isByteLiteralValue((Long) literal.value); + case TypeTags.SIGNED32_INT -> + literalType.tag == TypeTags.INT && isSigned32LiteralValue((Long) literal.value); + case TypeTags.SIGNED16_INT -> + literalType.tag == TypeTags.INT && isSigned16LiteralValue((Long) literal.value); + case TypeTags.SIGNED8_INT -> literalType.tag == TypeTags.INT && isSigned8LiteralValue((Long) literal.value); + case TypeTags.UNSIGNED32_INT -> + literalType.tag == TypeTags.INT && isUnsigned32LiteralValue((Long) literal.value); + case TypeTags.UNSIGNED16_INT -> + literalType.tag == TypeTags.INT && isUnsigned16LiteralValue((Long) literal.value); + case TypeTags.UNSIGNED8_INT -> + literalType.tag == TypeTags.INT && isUnsigned8LiteralValue((Long) literal.value); + case TypeTags.CHAR_STRING -> + literalType.tag == TypeTags.STRING && isCharLiteralValue((String) literal.value); + default -> false; + }; } /** @@ -4825,28 +4802,21 @@ private boolean jsonEqualityIntersectionExists(Set typeSet) { public BType getRemainingMatchExprType(BType originalType, BType typeToRemove, SymbolEnv env) { originalType = getImpliedType(originalType); - switch (originalType.tag) { - case TypeTags.UNION: - return getRemainingType((BUnionType) originalType, getAllTypes(typeToRemove, true)); - case TypeTags.FINITE: - return getRemainingType((BFiniteType) originalType, getAllTypes(typeToRemove, true)); - case TypeTags.TUPLE: - return getRemainingType((BTupleType) originalType, typeToRemove, env); - default: - return originalType; - } + return switch (originalType.tag) { + case TypeTags.UNION -> getRemainingType((BUnionType) originalType, getAllTypes(typeToRemove, true)); + case TypeTags.FINITE -> getRemainingType((BFiniteType) originalType, getAllTypes(typeToRemove, true)); + case TypeTags.TUPLE -> getRemainingType((BTupleType) originalType, typeToRemove, env); + default -> originalType; + }; } private BType getRemainingType(BTupleType originalType, BType typeToRemove, SymbolEnv env) { typeToRemove = getImpliedType(typeToRemove); - switch (typeToRemove.tag) { - case TypeTags.TUPLE: - return getRemainingType(originalType, (BTupleType) typeToRemove, env); - case TypeTags.ARRAY: - return getRemainingType(originalType, (BArrayType) typeToRemove, env); - default: - return originalType; - } + return switch (typeToRemove.tag) { + case TypeTags.TUPLE -> getRemainingType(originalType, (BTupleType) typeToRemove, env); + case TypeTags.ARRAY -> getRemainingType(originalType, (BArrayType) typeToRemove, env); + default -> originalType; + }; } private BType getRemainingType(BTupleType originalType, BTupleType typeToRemove, SymbolEnv env) { @@ -4966,19 +4936,21 @@ public boolean isSubTypeOfReadOnly(BType type, SymbolEnv env) { private boolean isClosedRecordTypes(BType type) { type = getImpliedType(type); - switch (type.tag) { - case RECORD: + return switch (type.tag) { + case RECORD -> { BRecordType recordType = (BRecordType) type; - return recordType.sealed || recordType.restFieldType == symTable.neverType; - case UNION: + yield recordType.sealed || recordType.restFieldType == symTable.neverType; + } + case UNION -> { for (BType memberType : ((BUnionType) type).getMemberTypes()) { if (!isClosedRecordTypes(getImpliedType(memberType))) { - return false; + yield false; } } - return true; - } - return false; + yield true; + } + default -> false; + }; } private boolean removesDistinctRecords(BType typeToRemove, BType remainingType) { @@ -5324,12 +5296,10 @@ private BType getIntersection(IntersectionContext intersectionContext, BType lhs } private boolean isAnydataOrJson(BType type) { - switch (getImpliedType(type).tag) { - case TypeTags.ANYDATA: - case TypeTags.JSON: - return true; - } - return false; + return switch (getImpliedType(type).tag) { + case TypeTags.ANYDATA, TypeTags.JSON -> true; + default -> false; + }; } private BMapType getMapTypeForAnydataOrJson(BType type, SymbolEnv env) { @@ -5972,50 +5942,49 @@ public List getAllTypes(BType type, boolean getReferenced) { public boolean isAllowedConstantType(BType type) { type = getImpliedType(type); - switch (type.tag) { - case TypeTags.BOOLEAN: - case TypeTags.INT: - case TypeTags.SIGNED32_INT: - case TypeTags.SIGNED16_INT: - case TypeTags.SIGNED8_INT: - case TypeTags.UNSIGNED32_INT: - case TypeTags.UNSIGNED16_INT: - case TypeTags.UNSIGNED8_INT: - case TypeTags.BYTE: - case TypeTags.FLOAT: - case TypeTags.DECIMAL: - case TypeTags.STRING: - // TODO : Fix this, Issue : #21542 -// case TypeTags.CHAR_STRING: - case TypeTags.NIL: - case TypeTags.UNION: - case TypeTags.ANY: - case TypeTags.ANYDATA: - return true; - case TypeTags.MAP: - return isAllowedConstantType(((BMapType) type).constraint); - case TypeTags.RECORD: + return switch (type.tag) { + case TypeTags.BOOLEAN, + TypeTags.INT, + TypeTags.SIGNED32_INT, + TypeTags.SIGNED16_INT, + TypeTags.SIGNED8_INT, + TypeTags.UNSIGNED32_INT, + TypeTags.UNSIGNED16_INT, + TypeTags.UNSIGNED8_INT, + TypeTags.BYTE, + TypeTags.FLOAT, + TypeTags.DECIMAL, + TypeTags.STRING, + // TODO : Fix this, Issue : #21542 + //TypeTags.CHAR_STRING: + TypeTags.NIL, + TypeTags.UNION, + TypeTags.ANY, + TypeTags.ANYDATA -> true; + case TypeTags.MAP -> isAllowedConstantType(((BMapType) type).constraint); + case TypeTags.RECORD -> { for (BField field : ((BRecordType) type).fields.values()) { if (field.symbol.isDefaultable || !isAllowedConstantType(field.type)) { - return false; + yield false; } } - return true; - case TypeTags.ARRAY: - return isAllowedConstantType(((BArrayType) type).eType); - case TypeTags.TUPLE: + yield true; + } + case TypeTags.ARRAY -> isAllowedConstantType(((BArrayType) type).eType); + case TypeTags.TUPLE -> { for (BType memberType : ((BTupleType) type).getTupleTypes()) { if (!isAllowedConstantType(memberType)) { - return false; + yield false; } } - return true; - case TypeTags.FINITE: + yield true; + } + case TypeTags.FINITE -> { BLangExpression finiteValue = ((BFiniteType) type).getValueSpace().toArray(new BLangExpression[0])[0]; - return isAllowedConstantType(finiteValue.getBType()); - default: - return false; - } + yield isAllowedConstantType(finiteValue.getBType()); + } + default -> false; + }; } public boolean isValidLiteral(BLangLiteral literal, BType targetType) { @@ -6024,30 +5993,25 @@ public boolean isValidLiteral(BLangLiteral literal, BType targetType) { return true; } - switch (targetType.tag) { - case TypeTags.BYTE: - return literalType.tag == TypeTags.INT && isByteLiteralValue((Long) literal.value); - case TypeTags.DECIMAL: - return literalType.tag == TypeTags.FLOAT || literalType.tag == TypeTags.INT; - case TypeTags.FLOAT: - return literalType.tag == TypeTags.INT; - case TypeTags.SIGNED32_INT: - return literalType.tag == TypeTags.INT && isSigned32LiteralValue((Long) literal.value); - case TypeTags.SIGNED16_INT: - return literalType.tag == TypeTags.INT && isSigned16LiteralValue((Long) literal.value); - case TypeTags.SIGNED8_INT: - return literalType.tag == TypeTags.INT && isSigned8LiteralValue((Long) literal.value); - case TypeTags.UNSIGNED32_INT: - return literalType.tag == TypeTags.INT && isUnsigned32LiteralValue((Long) literal.value); - case TypeTags.UNSIGNED16_INT: - return literalType.tag == TypeTags.INT && isUnsigned16LiteralValue((Long) literal.value); - case TypeTags.UNSIGNED8_INT: - return literalType.tag == TypeTags.INT && isUnsigned8LiteralValue((Long) literal.value); - case TypeTags.CHAR_STRING: - return literalType.tag == TypeTags.STRING && isCharLiteralValue((String) literal.value); - default: - return false; - } + return switch (targetType.tag) { + case TypeTags.BYTE -> literalType.tag == TypeTags.INT && isByteLiteralValue((Long) literal.value); + case TypeTags.DECIMAL -> literalType.tag == TypeTags.FLOAT || literalType.tag == TypeTags.INT; + case TypeTags.FLOAT -> literalType.tag == TypeTags.INT; + case TypeTags.SIGNED32_INT -> + literalType.tag == TypeTags.INT && isSigned32LiteralValue((Long) literal.value); + case TypeTags.SIGNED16_INT -> + literalType.tag == TypeTags.INT && isSigned16LiteralValue((Long) literal.value); + case TypeTags.SIGNED8_INT -> literalType.tag == TypeTags.INT && isSigned8LiteralValue((Long) literal.value); + case TypeTags.UNSIGNED32_INT -> + literalType.tag == TypeTags.INT && isUnsigned32LiteralValue((Long) literal.value); + case TypeTags.UNSIGNED16_INT -> + literalType.tag == TypeTags.INT && isUnsigned16LiteralValue((Long) literal.value); + case TypeTags.UNSIGNED8_INT -> + literalType.tag == TypeTags.INT && isUnsigned8LiteralValue((Long) literal.value); + case TypeTags.CHAR_STRING -> + literalType.tag == TypeTags.STRING && isCharLiteralValue((String) literal.value); + default -> false; + }; } /** @@ -6098,11 +6062,10 @@ public TypePair(BType sourceType, BType targetType) { @Override public boolean equals(Object obj) { - if (!(obj instanceof TypePair)) { + if (!(obj instanceof TypePair other)) { return false; } - TypePair other = (TypePair) obj; return this.sourceType.equals(other.sourceType) && this.targetType.equals(other.targetType); } @@ -6208,12 +6171,12 @@ private boolean checkFillerValue(BFiniteType type) { if (type.getValueSpace().size() == 1) { // For singleton types, that value is the implicit initial value return true; } - Iterator iterator = type.getValueSpace().iterator(); - BLangExpression firstElement = (BLangExpression) iterator.next(); + Iterator iterator = type.getValueSpace().iterator(); + BLangExpression firstElement = iterator.next(); boolean defaultFillValuePresent = isImplicitDefaultValue(firstElement); while (iterator.hasNext()) { - BLangExpression value = (BLangExpression) iterator.next(); + BLangExpression value = iterator.next(); if (!isSameBasicType(value.getBType(), firstElement.getBType())) { return false; } @@ -6306,23 +6269,15 @@ private boolean isImplicitDefaultValue(BLangExpression expression) { BLangLiteral literalExpression = (BLangLiteral) expression; BType literalExprType = literalExpression.getBType(); Object value = literalExpression.getValue(); - switch (literalExprType.getKind()) { - case INT: - case BYTE: - return value.equals(0L); - case STRING: - return value == null || value.equals(""); - case DECIMAL: - return value.equals(String.valueOf(0)) || value.equals(0L); - case FLOAT: - return value.equals(String.valueOf(0.0)); - case BOOLEAN: - return value.equals(Boolean.FALSE); - case NIL: - return true; - default: - return false; - } + return switch (literalExprType.getKind()) { + case INT, BYTE -> value.equals(0L); + case STRING -> value == null || value.equals(""); + case DECIMAL -> value.equals(String.valueOf(0)) || value.equals(0L); + case FLOAT -> value.equals(String.valueOf(0.0)); + case BOOLEAN -> value.equals(Boolean.FALSE); + case NIL -> true; + default -> false; + }; } return false; } @@ -6477,34 +6432,33 @@ public boolean isSubTypeOfSimpleBasicTypeOrString(BType bType) { public BType findCompatibleType(BType type) { type = getImpliedType(type); - switch (type.tag) { - case TypeTags.DECIMAL: - case TypeTags.FLOAT: - case TypeTags.XML: - case TypeTags.XML_TEXT: - case TypeTags.XML_ELEMENT: - case TypeTags.XML_PI: - case TypeTags.XML_COMMENT: - return type; - case TypeTags.INT: - case TypeTags.BYTE: - case TypeTags.SIGNED32_INT: - case TypeTags.SIGNED16_INT: - case TypeTags.SIGNED8_INT: - case TypeTags.UNSIGNED32_INT: - case TypeTags.UNSIGNED16_INT: - case TypeTags.UNSIGNED8_INT: - return symTable.intType; - case TypeTags.STRING: - case TypeTags.CHAR_STRING: - return symTable.stringType; - case TypeTags.UNION: + return switch (type.tag) { + case TypeTags.DECIMAL, + TypeTags.FLOAT, + TypeTags.XML, + TypeTags.XML_TEXT, + TypeTags.XML_ELEMENT, + TypeTags.XML_PI, + TypeTags.XML_COMMENT -> type; + case TypeTags.INT, + TypeTags.BYTE, + TypeTags.SIGNED32_INT, + TypeTags.SIGNED16_INT, + TypeTags.SIGNED8_INT, + TypeTags.UNSIGNED32_INT, + TypeTags.UNSIGNED16_INT, + TypeTags.UNSIGNED8_INT -> symTable.intType; + case TypeTags.STRING, + TypeTags.CHAR_STRING -> symTable.stringType; + case TypeTags.UNION -> { LinkedHashSet memberTypes = ((BUnionType) type).getMemberTypes(); - return findCompatibleType(memberTypes.iterator().next()); - default: + yield findCompatibleType(memberTypes.iterator().next()); + } + default -> { Set valueSpace = ((BFiniteType) type).getValueSpace(); - return findCompatibleType(valueSpace.iterator().next().getBType()); - } + yield findCompatibleType(valueSpace.iterator().next().getBType()); + } + }; } public boolean isNonNilSimpleBasicTypeOrString(BType bType) { @@ -7158,14 +7112,14 @@ private enum BasicTypes { * Holds common analyzer data between {@link TypeChecker} and {@link SemanticAnalyzer}. */ public static class CommonAnalyzerData { - Stack queryEnvs = new Stack<>(); - Stack queryFinalClauses = new Stack<>(); + Deque queryEnvs = new ArrayDeque<>(); + Deque queryFinalClauses = new ArrayDeque<>(); HashSet checkedErrorList = new HashSet<>(); boolean breakToParallelQueryEnv = false; int letCount = 0; boolean nonErrorLoggingCheck = false; - Stack> errorTypes = new Stack<>(); + Deque> errorTypes = new ArrayDeque<>(); } /** @@ -7226,9 +7180,9 @@ public boolean isFunctionVarRef(BLangExpression expr) { public boolean isCloneableType(BUnionType type) { LinkedHashSet cloneableMemberTypes = symTable.cloneableType.getMemberTypes(); - Iterator memItr = type.getMemberTypes().iterator(); + Iterator memItr = type.getMemberTypes().iterator(); for (BType memberType : cloneableMemberTypes) { - if (!memItr.hasNext() || memberType.tag != ((BType) memItr.next()).tag) { + if (!memItr.hasNext() || memberType.tag != memItr.next().tag) { return false; } } @@ -7236,25 +7190,24 @@ public boolean isCloneableType(BUnionType type) { } public boolean isContainSubtypeOfInt(BType type) { - switch (type.tag) { - case TypeTags.BYTE: - case TypeTags.SIGNED32_INT: - case TypeTags.SIGNED16_INT: - case TypeTags.SIGNED8_INT: - case TypeTags.UNSIGNED32_INT: - case TypeTags.UNSIGNED16_INT: - case TypeTags.UNSIGNED8_INT: - return true; - case TypeTags.UNION: + return switch (type.tag) { + case TypeTags.BYTE, + TypeTags.SIGNED32_INT, + TypeTags.SIGNED16_INT, + TypeTags.SIGNED8_INT, + TypeTags.UNSIGNED32_INT, + TypeTags.UNSIGNED16_INT, + TypeTags.UNSIGNED8_INT -> true; + case TypeTags.UNION -> { for (BType memberType : ((BUnionType) type).getMemberTypes()) { if (isContainSubtypeOfInt(memberType)) { - return true; + yield true; } } - return false; - default: - return false; - } + yield false; + } + default -> false; + }; } public boolean isMappingConstructorCompatibleType(BType type) { diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/cyclefind/GlobalVariableRefAnalyzer.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/cyclefind/GlobalVariableRefAnalyzer.java index 185935e5bb5d..e91e441a25ae 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/cyclefind/GlobalVariableRefAnalyzer.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/cyclefind/GlobalVariableRefAnalyzer.java @@ -291,7 +291,7 @@ private List analyzeDependenciesStartingFrom(BSymbol symbol) { if (!dependencyOrder.isEmpty()) { List symbolsProvidersOrdered = this.dependencyOrder.stream() .map(nodeInfo -> nodeInfo.symbol) - .collect(Collectors.toList()); + .toList(); this.dependencyOrder.clear(); return symbolsProvidersOrdered; } @@ -382,7 +382,7 @@ private void projectSortToGlobalVarsList(Set sorted) { List sortedGlobalVars = sorted.stream() .filter(varMap::containsKey) .map(varMap::get) - .collect(Collectors.toList()); + .toList(); if (sortedGlobalVars.size() != this.pkgNode.globalVars.size()) { List symbolLessGlobalVars = this.pkgNode.globalVars.stream() @@ -401,7 +401,7 @@ private void sortConstants(Set sorted) { List sortedConstants = sorted.stream() .filter(varMap::containsKey) .map(varMap::get) - .collect(Collectors.toList()); + .toList(); if (sortedConstants.size() != this.pkgNode.constants.size()) { List symbolLessGlobalVars = this.pkgNode.constants.stream() @@ -487,7 +487,7 @@ private void handleCyclicReferenceError(NodeInfo node) { Collections.reverse(cycle); List symbolsOfCycle = cycle.stream() .map(n -> n.symbol) - .collect(Collectors.toList()); + .toList(); if (doesContainAGlobalVar(symbolsOfCycle)) { emitErrorMessage(symbolsOfCycle); @@ -520,7 +520,7 @@ private void emitErrorMessage(List symbolsOfCycle) { secondSubList.addAll(firstSubList); List names = secondSubList.stream() - .map(this::getNodeName).filter(Objects::nonNull).collect(Collectors.toList()); + .map(this::getNodeName).filter(Objects::nonNull).toList(); dlog.error(firstNode.get().getPosition(), DiagnosticErrorCode.GLOBAL_VARIABLE_CYCLIC_DEFINITION, names); } diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/SymbolTable.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/SymbolTable.java index 2700a855b958..a6c13bb63586 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/SymbolTable.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/SymbolTable.java @@ -335,93 +335,54 @@ private void defineReadonlyCompoundType() { } public BType getTypeFromTag(int tag) { - switch (tag) { - case TypeTags.INT: - return intType; - case TypeTags.BYTE: - return byteType; - case TypeTags.FLOAT: - return floatType; - case TypeTags.DECIMAL: - return decimalType; - case TypeTags.STRING: - return stringType; - case TypeTags.BOOLEAN: - return booleanType; - case TypeTags.JSON: - return jsonType; - case TypeTags.XML: - return xmlType; - case TypeTags.XML_COMMENT: - return xmlCommentType; - case TypeTags.XML_PI: - return xmlPIType; - case TypeTags.XML_ELEMENT: - return xmlElementType; - case TypeTags.XML_TEXT: - return xmlTextType; - case TypeTags.STREAM: - return streamType; - case TypeTags.TABLE: - return tableType; - case TypeTags.NIL: - return nilType; - case TypeTags.NEVER: - return neverType; - case TypeTags.ERROR: - return errorType; - case TypeTags.SIGNED32_INT: - return signed32IntType; - case TypeTags.SIGNED16_INT: - return signed16IntType; - case TypeTags.SIGNED8_INT: - return signed8IntType; - case TypeTags.UNSIGNED32_INT: - return unsigned32IntType; - case TypeTags.UNSIGNED16_INT: - return unsigned16IntType; - case TypeTags.UNSIGNED8_INT: - return unsigned8IntType; - case TypeTags.CHAR_STRING: - return charStringType; - case TypeTags.REGEXP: - return regExpType; - case TypeTags.BYTE_ARRAY: - return byteArrayType; - default: - return semanticError; - } + return switch (tag) { + case TypeTags.INT -> intType; + case TypeTags.BYTE -> byteType; + case TypeTags.FLOAT -> floatType; + case TypeTags.DECIMAL -> decimalType; + case TypeTags.STRING -> stringType; + case TypeTags.BOOLEAN -> booleanType; + case TypeTags.JSON -> jsonType; + case TypeTags.XML -> xmlType; + case TypeTags.XML_COMMENT -> xmlCommentType; + case TypeTags.XML_PI -> xmlPIType; + case TypeTags.XML_ELEMENT -> xmlElementType; + case TypeTags.XML_TEXT -> xmlTextType; + case TypeTags.STREAM -> streamType; + case TypeTags.TABLE -> tableType; + case TypeTags.NIL -> nilType; + case TypeTags.NEVER -> neverType; + case TypeTags.ERROR -> errorType; + case TypeTags.SIGNED32_INT -> signed32IntType; + case TypeTags.SIGNED16_INT -> signed16IntType; + case TypeTags.SIGNED8_INT -> signed8IntType; + case TypeTags.UNSIGNED32_INT -> unsigned32IntType; + case TypeTags.UNSIGNED16_INT -> unsigned16IntType; + case TypeTags.UNSIGNED8_INT -> unsigned8IntType; + case TypeTags.CHAR_STRING -> charStringType; + case TypeTags.REGEXP -> regExpType; + case TypeTags.BYTE_ARRAY -> byteArrayType; + default -> semanticError; + }; } public BType getLangLibSubType(String name) { // Assuming subtype names are unique across LangLib - switch (name) { - case Names.STRING_SIGNED32: - return this.signed32IntType; - case Names.STRING_SIGNED16: - return this.signed16IntType; - case Names.STRING_SIGNED8: - return this.signed8IntType; - case Names.STRING_UNSIGNED32: - return this.unsigned32IntType; - case Names.STRING_UNSIGNED16: - return this.unsigned16IntType; - case Names.STRING_UNSIGNED8: - return this.unsigned8IntType; - case Names.STRING_CHAR: - return this.charStringType; - case Names.STRING_XML_ELEMENT: - return this.xmlElementType; - case Names.STRING_XML_PI: - return this.xmlPIType; - case Names.STRING_XML_COMMENT: - return this.xmlCommentType; - case Names.STRING_XML_TEXT: - return this.xmlTextType; - case Names.STRING_REGEXP: - return this.regExpType; - } - throw new IllegalStateException("LangLib Subtype not found: " + name); + return switch (name) { + case Names.STRING_SIGNED32 -> this.signed32IntType; + case Names.STRING_SIGNED16 -> this.signed16IntType; + case Names.STRING_SIGNED8 -> this.signed8IntType; + case Names.STRING_UNSIGNED32 -> this.unsigned32IntType; + case Names.STRING_UNSIGNED16 -> this.unsigned16IntType; + case Names.STRING_UNSIGNED8 -> this.unsigned8IntType; + case Names.STRING_CHAR -> this.charStringType; + case Names.STRING_XML_ELEMENT -> this.xmlElementType; + case Names.STRING_XML_PI -> this.xmlPIType; + case Names.STRING_XML_COMMENT -> this.xmlCommentType; + case Names.STRING_XML_TEXT -> this.xmlTextType; + case Names.STRING_REGEXP -> this.regExpType; + default -> throw new IllegalStateException("LangLib Subtype not found: " + name); + }; } public void loadPredeclaredModules() { diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/symbols/BInvokableSymbol.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/symbols/BInvokableSymbol.java index cfdbef94aa68..b26f3014700e 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/symbols/BInvokableSymbol.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/symbols/BInvokableSymbol.java @@ -93,8 +93,8 @@ public List getParameters() { @Override public BInvokableType getType() { - if (type instanceof BInvokableType) { - return (BInvokableType) type; + if (type instanceof BInvokableType bInvokableType) { + return bInvokableType; } // Should never come here, this is to please the spotbugs throw new BLangCompilerException("Invokable symbol with non invokable type : " + type); diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/symbols/SymTag.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/symbols/SymTag.java index 95b246760243..dbfce11e531c 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/symbols/SymTag.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/symbols/SymTag.java @@ -20,7 +20,8 @@ /** * @since 0.94 */ -public class SymTag { +public final class SymTag { + public static final long NIL = 0; public static final long IMPORT = 1; public static final long ANNOTATION = 1 << 1; @@ -55,4 +56,7 @@ public class SymTag { public static final long ANNOTATION_ATTACHMENT = 1 << 30; public static final long RESOURCE_PATH_SEGMENT = 1 << 31; public static final long SEQUENCE = 1L << 32 | MAIN; + + private SymTag() { + } } diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/symbols/Symbols.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/symbols/Symbols.java index 4df3f8a51a75..650806f4204b 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/symbols/Symbols.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/symbols/Symbols.java @@ -37,7 +37,10 @@ /** * @since 0.94 */ -public class Symbols { +public final class Symbols { + + private Symbols() { + } public static BPackageSymbol createPackageSymbol(PackageID packageID, SymbolTable symTable, diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/types/BBuiltInRefType.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/types/BBuiltInRefType.java index 3dc5b104d4e1..cb8965ec71e1 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/types/BBuiltInRefType.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/types/BBuiltInRefType.java @@ -51,27 +51,17 @@ public R accept(BTypeVisitor visitor, T t) { @Override public TypeKind getKind() { - switch (tag) { - case JSON: - return TypeKind.JSON; - case XML: - return TypeKind.XML; - case STREAM: - return TypeKind.STREAM; - case TABLE: - return TypeKind.TABLE; - case ANY: - return TypeKind.ANY; - case ANYDATA: - return TypeKind.ANYDATA; - case MAP: - return TypeKind.MAP; - case FUTURE: - return TypeKind.FUTURE; - case TYPEDESC: - return TypeKind.TYPEDESC; - default: - return TypeKind.OTHER; - } + return switch (tag) { + case JSON -> TypeKind.JSON; + case XML -> TypeKind.XML; + case STREAM -> TypeKind.STREAM; + case TABLE -> TypeKind.TABLE; + case ANY -> TypeKind.ANY; + case ANYDATA -> TypeKind.ANYDATA; + case MAP -> TypeKind.MAP; + case FUTURE -> TypeKind.FUTURE; + case TYPEDESC -> TypeKind.TYPEDESC; + default -> TypeKind.OTHER; + }; } } diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/types/BInvokableType.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/types/BInvokableType.java index 79bde4b69a0b..3882ba40fde0 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/types/BInvokableType.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/types/BInvokableType.java @@ -93,10 +93,9 @@ public boolean equals(Object o) { if (this == o) { return true; } - if (!(o instanceof BInvokableType)) { + if (!(o instanceof BInvokableType that)) { return false; } - BInvokableType that = (BInvokableType) o; if (this.flags != that.flags) { return false; @@ -130,18 +129,18 @@ public String getTypeSignature() { retTypeWithParam = "(" + retType.toString() + ")"; } String restParam = ""; - if (restType != null && restType instanceof BArrayType) { + if (restType != null && restType instanceof BArrayType bArrayType) { if (!paramTypes.isEmpty()) { restParam += ", "; } - restParam += ((BArrayType) restType).eType + "..."; + restParam += bArrayType.eType + "..."; } return "(" + (!paramTypes.isEmpty() ? getBTypeListAsString(paramTypes) : "") + restParam + ")" + " returns " + retTypeWithParam; } private static String getBTypeListAsString(List typeNames) { - StringBuffer br = new StringBuffer(); + StringBuilder br = new StringBuilder(); int i = 0; for (BType type : typeNames) { br.append(type); diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/types/BTupleType.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/types/BTupleType.java index 8421e6c66ac8..6b647c1c2052 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/types/BTupleType.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/types/BTupleType.java @@ -181,28 +181,24 @@ private void setCyclicFlag(BType type) { return; } - if (type instanceof BArrayType) { - BArrayType arrayType = (BArrayType) type; + if (type instanceof BArrayType arrayType) { if (arrayType.eType == this) { isCyclic = true; } } - if (type instanceof BMapType) { - BMapType mapType = (BMapType) type; + if (type instanceof BMapType mapType) { if (mapType.constraint == this) { isCyclic = true; } } - if (type instanceof BTableType) { - BTableType tableType = (BTableType) type; + if (type instanceof BTableType tableType) { if (tableType.constraint == this) { isCyclic = true; } - if (tableType.constraint instanceof BMapType) { - BMapType mapType = (BMapType) tableType.constraint; + if (tableType.constraint instanceof BMapType mapType) { if (mapType.constraint == this) { isCyclic = true; } diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/types/BType.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/types/BType.java index 8bf4e35a8498..a60272975151 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/types/BType.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/types/BType.java @@ -88,34 +88,21 @@ public R accept(BTypeVisitor visitor, T t) { @Override public TypeKind getKind() { - switch (tag) { - case INT: - return TypeKind.INT; - case BYTE: - return TypeKind.BYTE; - case FLOAT: - return TypeKind.FLOAT; - case DECIMAL: - return TypeKind.DECIMAL; - case STRING: - return TypeKind.STRING; - case BOOLEAN: - return TypeKind.BOOLEAN; - case TYPEDESC: - return TypeKind.TYPEDESC; - case NIL: - return TypeKind.NIL; - case NEVER: - return TypeKind.NEVER; - case ERROR: - return TypeKind.ERROR; - case READONLY: - return TypeKind.READONLY; - case PARAMETERIZED_TYPE: - return TypeKind.PARAMETERIZED; - default: - return TypeKind.OTHER; - } + return switch (tag) { + case INT -> TypeKind.INT; + case BYTE -> TypeKind.BYTE; + case FLOAT -> TypeKind.FLOAT; + case DECIMAL -> TypeKind.DECIMAL; + case STRING -> TypeKind.STRING; + case BOOLEAN -> TypeKind.BOOLEAN; + case TYPEDESC -> TypeKind.TYPEDESC; + case NIL -> TypeKind.NIL; + case NEVER -> TypeKind.NEVER; + case ERROR -> TypeKind.ERROR; + case READONLY -> TypeKind.READONLY; + case PARAMETERIZED_TYPE -> TypeKind.PARAMETERIZED; + default -> TypeKind.OTHER; + }; } @Override diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/types/BTypeIdSet.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/types/BTypeIdSet.java index 89c13429e325..165982bd9438 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/types/BTypeIdSet.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/types/BTypeIdSet.java @@ -158,11 +158,10 @@ public boolean equals(Object obj) { if (this == obj) { return true; } - if (!(obj instanceof BTypeIdSet)) { + if (!(obj instanceof BTypeIdSet that)) { return false; } - BTypeIdSet that = (BTypeIdSet) obj; return this.primary.equals(that.primary) && this.secondary.equals(that.secondary); } @@ -219,8 +218,7 @@ public boolean equals(Object obj) { return true; } - if (obj instanceof BTypeId) { - BTypeId that = (BTypeId) obj; + if (obj instanceof BTypeId that) { return this.name.equals(that.name) && CompilerUtils.getPackageIDStringWithMajorVersion(this.packageID).equals( CompilerUtils.getPackageIDStringWithMajorVersion(that.packageID)); diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/types/BUnionType.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/types/BUnionType.java index bac229e3c946..b73167676809 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/types/BUnionType.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/types/BUnionType.java @@ -276,28 +276,24 @@ private void setCyclicFlag(BType type) { return; } - if (type instanceof BArrayType) { - BArrayType arrayType = (BArrayType) type; + if (type instanceof BArrayType arrayType) { if (arrayType.eType == this) { isCyclic = true; } } - if (type instanceof BMapType) { - BMapType mapType = (BMapType) type; + if (type instanceof BMapType mapType) { if (mapType.constraint == this) { isCyclic = true; } } - if (type instanceof BTableType) { - BTableType tableType = (BTableType) type; + if (type instanceof BTableType tableType) { if (tableType.constraint == this) { isCyclic = true; } - if (tableType.constraint instanceof BMapType) { - BMapType mapType = (BMapType) tableType.constraint; + if (tableType.constraint instanceof BMapType mapType) { if (mapType.constraint == this) { isCyclic = true; } @@ -353,30 +349,26 @@ public void mergeUnionType(BUnionType unionType) { } this.isCyclic = true; for (BType member : unionType.getMemberTypes()) { - if (member instanceof BArrayType) { - BArrayType arrayType = (BArrayType) member; + if (member instanceof BArrayType arrayType) { if (getImpliedType(arrayType.eType) == unionType) { BArrayType newArrayType = new BArrayType(this, arrayType.tsymbol, arrayType.size, arrayType.state, arrayType.flags); this.add(newArrayType); continue; } - } else if (member instanceof BMapType) { - BMapType mapType = (BMapType) member; + } else if (member instanceof BMapType mapType) { if (getImpliedType(mapType.constraint) == unionType) { BMapType newMapType = new BMapType(mapType.tag, this, mapType.tsymbol, mapType.flags); this.add(newMapType); continue; } - } else if (member instanceof BTableType) { - BTableType tableType = (BTableType) member; + } else if (member instanceof BTableType tableType) { if (getImpliedType(tableType.constraint) == unionType) { BTableType newTableType = new BTableType(tableType.tag, this, tableType.tsymbol, tableType.flags); this.add(newTableType); continue; - } else if (tableType.constraint instanceof BMapType) { - BMapType mapType = (BMapType) tableType.constraint; + } else if (tableType.constraint instanceof BMapType mapType) { if (getImpliedType(mapType.constraint) == unionType) { BMapType newMapType = new BMapType(mapType.tag, this, mapType.tsymbol, mapType.flags); BTableType newTableType = new BTableType(tableType.tag, newMapType, tableType.tsymbol, diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/types/TypeFlags.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/types/TypeFlags.java index c61b7bc82787..f7e6dcdfc481 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/types/TypeFlags.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/types/TypeFlags.java @@ -22,11 +22,15 @@ * * @since 1.1.0 */ -public class TypeFlags { +public final class TypeFlags { + public static final int NILABLE = 1; public static final int ANYDATA = NILABLE << 1; public static final int PURETYPE = ANYDATA << 1; + private TypeFlags() { + } + public static int asMask(boolean isNilable, boolean isAnydata, boolean isPureType) { int mask = 0; if (isNilable) { diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/tree/BLangConstantValue.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/tree/BLangConstantValue.java index fea425b354da..71ebb1d557d1 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/tree/BLangConstantValue.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/tree/BLangConstantValue.java @@ -49,8 +49,7 @@ public boolean equals(Object o) { return false; } - if (o instanceof BLangConstantValue) { - BLangConstantValue that = (BLangConstantValue) o; + if (o instanceof BLangConstantValue that) { if (this.type.tag != that.type.tag) { return false; diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/tree/BLangImportPackage.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/tree/BLangImportPackage.java index c5a925aaadb1..787a20f966f6 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/tree/BLangImportPackage.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/tree/BLangImportPackage.java @@ -24,7 +24,6 @@ import java.util.ArrayList; import java.util.List; -import java.util.stream.Collectors; /** * @since 0.94 @@ -136,7 +135,7 @@ public String getQualifiedPackageName() { String orgName = this.orgName.toString(); String pkgName = String.join(".", pkgNameComps.stream() .map(id -> id.value) - .collect(Collectors.toList())); + .toList()); String versionStr = (this.version.value != null) ? this.version.value : ""; if (!versionStr.isEmpty()) { diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/tree/BLangResourcePathSegment.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/tree/BLangResourcePathSegment.java index fc8b6fe469b4..17c38a3a355e 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/tree/BLangResourcePathSegment.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/tree/BLangResourcePathSegment.java @@ -54,14 +54,11 @@ public R apply(BLangNodeTransformer modifier, T props) { @Override public String toString() { - switch (this.kind) { - case RESOURCE_PATH_PARAM_SEGMENT: - return "[" + type + "]"; - case RESOURCE_PATH_REST_PARAM_SEGMENT: - return "[" + type + "...]"; - default: - return name.value; - } + return switch (this.kind) { + case RESOURCE_PATH_PARAM_SEGMENT -> "[" + type + "]"; + case RESOURCE_PATH_REST_PARAM_SEGMENT -> "[" + type + "...]"; + default -> name.value; + }; } @Override diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/tree/expressions/BLangCollectContextInvocation.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/tree/expressions/BLangCollectContextInvocation.java index 59cb4a80effc..382167b98a1b 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/tree/expressions/BLangCollectContextInvocation.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/tree/expressions/BLangCollectContextInvocation.java @@ -26,7 +26,7 @@ import java.util.Arrays; /** - * Implementation of {@link org.ballerinalang.model.tree.expressions.CollectContextInvocationNode}. + * Implementation of {@link CollectContextInvocationNode}. * * @since 2201.7.0 */ diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/tree/expressions/BLangElvisExpr.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/tree/expressions/BLangElvisExpr.java index 9790adf01c27..73a9dd125b62 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/tree/expressions/BLangElvisExpr.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/tree/expressions/BLangElvisExpr.java @@ -25,7 +25,7 @@ import org.wso2.ballerinalang.compiler.tree.BLangNodeVisitor; /** - * Implementation of {@link org.ballerinalang.model.tree.expressions.ElvisExpressionNode}. + * Implementation of {@link ElvisExpressionNode}. * * @since 0.964.1 */ diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/tree/expressions/BLangInvocation.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/tree/expressions/BLangInvocation.java index 4dee7bb1b183..d3b7ee0e88ac 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/tree/expressions/BLangInvocation.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/tree/expressions/BLangInvocation.java @@ -41,7 +41,7 @@ import java.util.StringJoiner; /** - * Implementation of {@link org.ballerinalang.model.tree.expressions.InvocationNode}. + * Implementation of {@link InvocationNode}. * * @since 0.94 */ diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/tree/expressions/BLangXMLQName.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/tree/expressions/BLangXMLQName.java index 68e952fbc425..a2ed20b01d6a 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/tree/expressions/BLangXMLQName.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/tree/expressions/BLangXMLQName.java @@ -118,11 +118,10 @@ public boolean equals(Object other) { return true; } - if (other == null || !(other instanceof BLangXMLQName)) { + if (other == null || !(other instanceof BLangXMLQName otherQname)) { return false; } - BLangXMLQName otherQname = (BLangXMLQName) other; return localname.equals(otherQname.localname) && prefix.equals(otherQname.prefix); } } diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/CompilerUtils.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/CompilerUtils.java index c78ed10ae522..6ac8ad830d89 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/CompilerUtils.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/CompilerUtils.java @@ -41,10 +41,13 @@ * * @since 0.965.0 */ -public class CompilerUtils { +public final class CompilerUtils { private static final String DISTRIBUTED_TRANSACTIONS = "distributed.transactions"; - + + private CompilerUtils() { + } + public static boolean isDistributedTransactionsEnabled() { boolean distributedTransactionEnabled = true; //TODO:Default will be true. Read from new VMOptions String distributedTxEnabledProp = System.getProperty(DISTRIBUTED_TRANSACTIONS); diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/Constants.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/Constants.java index 1c8ccc93164d..d3937ecd476b 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/Constants.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/Constants.java @@ -24,7 +24,7 @@ * * since 0.980.0 */ -public class Constants { +public final class Constants { private Constants() { } diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/FileUtils.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/FileUtils.java index a3266da93f36..f4d2cf32b227 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/FileUtils.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/FileUtils.java @@ -43,9 +43,13 @@ * * @since 0.970.0 */ -public class FileUtils { +public final class FileUtils { + private static final String SRC_DIR = "src"; + private FileUtils() { + } + public static void deleteFile(Path filePath) throws IOException { Files.deleteIfExists(filePath); } diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/ImmutableTypeCloner.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/ImmutableTypeCloner.java index d4b4d17d8789..544b2779d08b 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/ImmutableTypeCloner.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/ImmutableTypeCloner.java @@ -86,10 +86,13 @@ * * @since 1.3.0 */ -public class ImmutableTypeCloner { +public final class ImmutableTypeCloner { private static final String AND_READONLY_SUFFIX = " & readonly"; + private ImmutableTypeCloner() { + } + public static BType getEffectiveImmutableType(Location pos, Types types, BType type, SymbolEnv env, SymbolTable symTable, BLangAnonymousModelHelper anonymousModelHelper, diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/NodeUtils.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/NodeUtils.java index b668dd0fee5e..7d11bf155ef1 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/NodeUtils.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/NodeUtils.java @@ -21,12 +21,14 @@ import org.wso2.ballerinalang.compiler.tree.BLangIdentifier; import java.util.List; -import java.util.stream.Collectors; /** * @since 0.94 */ -public class NodeUtils { +public final class NodeUtils { + + private NodeUtils() { + } /** * Return the {@code Name} from the give package name components. @@ -50,7 +52,7 @@ public static Name getName(String localname, String namespaceURI) { public static PackageID getPackageID(Names names, BLangIdentifier orgNameNode, List pkgNameComps, BLangIdentifier versionNode) { - List nameList = pkgNameComps.stream().map(names::fromIdNode).collect(Collectors.toList()); + List nameList = pkgNameComps.stream().map(names::fromIdNode).toList(); Name orgName = null; if (orgNameNode != null) { orgName = names.fromIdNode(orgNameNode); diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/ProjectDirConstants.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/ProjectDirConstants.java index 8b98acd0e584..26e6480b26e8 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/ProjectDirConstants.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/ProjectDirConstants.java @@ -22,7 +22,7 @@ * * @since 0.964.0 */ -public class ProjectDirConstants { +public final class ProjectDirConstants { private ProjectDirConstants() { diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/ProjectDirs.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/ProjectDirs.java index ab6cacb226a7..1ca30d0af7f9 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/ProjectDirs.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/ProjectDirs.java @@ -28,8 +28,7 @@ import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.PathMatcher; -import java.util.ArrayList; -import java.util.List; +import java.util.stream.Stream; import static org.wso2.ballerinalang.compiler.util.ProjectDirConstants.BLANG_SOURCE_EXT; @@ -38,7 +37,7 @@ * * @since 0.965.0 */ -public class ProjectDirs { +public final class ProjectDirs { private static PathMatcher sourceFileMatcher = FileSystems.getDefault().getPathMatcher( "glob:*" + BLANG_SOURCE_EXT); @@ -49,6 +48,9 @@ public class ProjectDirs { private static PathMatcher testResourceFileMatcher = FileSystems.getDefault().getPathMatcher( "glob:../src/*/tests/resources/**" + BLANG_SOURCE_EXT); + private ProjectDirs() { + } + public static boolean isSourceFile(Path path) { return !Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS) && sourceFileMatcher.matches(path); } @@ -80,13 +82,13 @@ public static BLangCompilerException getPackageNotFoundError(String sourcePackag * @return true if source files exists else false */ public static boolean containsSourceFiles(Path pkgPath) throws BLangCompilerException { - List sourceFiles = new ArrayList<>(); - try { - sourceFiles = Files.find(pkgPath, Integer.MAX_VALUE, (path, attrs) -> - path.toString().endsWith(ProjectDirConstants.BLANG_SOURCE_EXT)).toList(); + try (Stream paths = Files.find(pkgPath, Integer.MAX_VALUE, (path, attrs) -> + path.toString().endsWith(ProjectDirConstants.BLANG_SOURCE_EXT))) { + return paths.findAny().isPresent(); } catch (IOException ignored) { // Here we are trying to check if there are source files inside the package to be compiled. If an error - // occurs when trying to visit the files inside the package then we simply return the empty list created. + // occurs when trying to visit the files inside the package then we simply return false. + return false; } catch (UncheckedIOException e) { // Files#find returns an UncheckedIOException instead of an AccessDeniedException when there is a file to // which user doesn't have required permission. @@ -97,7 +99,6 @@ public static boolean containsSourceFiles(Path pkgPath) throws BLangCompilerExce throw e; } } - return !sourceFiles.isEmpty(); } /** diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/TypeDefBuilderHelper.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/TypeDefBuilderHelper.java index a13f8f34bd71..c2fd5f5b7026 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/TypeDefBuilderHelper.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/TypeDefBuilderHelper.java @@ -79,10 +79,13 @@ * * @since 1.2.0 */ -public class TypeDefBuilderHelper { +public final class TypeDefBuilderHelper { public static final String INTERSECTED_ERROR_DETAIL = "$IntersectedErrorDetail$"; + private TypeDefBuilderHelper() { + } + public static BLangRecordTypeNode createRecordTypeNode(BRecordType recordType, PackageID packageID, SymbolTable symTable, Location pos) { List fieldList = new ArrayList<>(); diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/TypeTags.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/TypeTags.java index 2e24fccb8f9e..8858b5e58aea 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/TypeTags.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/TypeTags.java @@ -20,7 +20,7 @@ /** * @since 0.94 */ -public class TypeTags { +public final class TypeTags { public static final int INT = 1; public static final int BYTE = INT + 1; @@ -92,75 +92,57 @@ private TypeTags() { public static boolean isIntegerTypeTag(int tag) { // TODO : Fix byte type. Ideally, byte belongs to here. But we have modeled it differently. - switch (tag) { - case INT: - case SIGNED32_INT: - case SIGNED16_INT: - case SIGNED8_INT: - case UNSIGNED32_INT: - case UNSIGNED16_INT: - case UNSIGNED8_INT: - return true; - } - return false; + return switch (tag) { + case INT, + SIGNED32_INT, + SIGNED16_INT, + SIGNED8_INT, + UNSIGNED32_INT, + UNSIGNED16_INT, + UNSIGNED8_INT -> true; + default -> false; + }; } public static boolean isSignedIntegerTypeTag(int tag) { - switch (tag) { - case INT: - case SIGNED32_INT: - case SIGNED16_INT: - case SIGNED8_INT: - return true; - } - return false; + return switch (tag) { + case INT, SIGNED32_INT, SIGNED16_INT, SIGNED8_INT -> true; + default -> false; + }; } public static boolean isXMLTypeTag(int tag) { - switch (tag) { - case XML: - case XML_ELEMENT: - case XML_PI: - case XML_COMMENT: - case XML_TEXT: - return true; - } - return false; + return switch (tag) { + case XML, XML_ELEMENT, XML_PI, XML_COMMENT, XML_TEXT -> true; + default -> false; + }; } public static boolean isXMLNonSequenceType(int tag) { - switch (tag) { - case XML_ELEMENT: - case XML_PI: - case XML_COMMENT: - case XML_TEXT: - return true; - } - return false; + return switch (tag) { + case XML_ELEMENT, XML_PI, XML_COMMENT, XML_TEXT -> true; + default -> false; + }; } public static boolean isStringTypeTag(int tag) { - switch (tag) { - case STRING: - case CHAR_STRING: - return true; - } - return false; + return switch (tag) { + case STRING, CHAR_STRING -> true; + default -> false; + }; } public static boolean isSimpleBasicType(int tag) { - switch (tag) { - case TypeTags.BYTE: - case TypeTags.FLOAT: - case TypeTags.DECIMAL: - case TypeTags.BOOLEAN: - case TypeTags.NIL: - return true; - default: - return (TypeTags.isIntegerTypeTag(tag)) || (TypeTags.isStringTypeTag(tag)); - } + return switch (tag) { + case TypeTags.BYTE, + TypeTags.FLOAT, + TypeTags.DECIMAL, + TypeTags.BOOLEAN, + TypeTags.NIL -> true; + default -> (TypeTags.isIntegerTypeTag(tag)) || (TypeTags.isStringTypeTag(tag)); + }; } } diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/Unifier.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/Unifier.java index 512281b652e5..598d04640cae 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/Unifier.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/Unifier.java @@ -986,7 +986,8 @@ private BType getMatchingTypeForInferrableType(BType originalType, BType expType for (BType inferableType : inferableTypes) { for (BType expectedType : expectedTypes) { - if (Types.getImpliedType(inferableType).tag == Types.getImpliedType(expectedType).tag) { + expectedType = Types.getImpliedType(expectedType); + if (Types.getImpliedType(inferableType).tag == expectedType.tag) { matchedTypes.add(expectedType); } } diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/diagnotic/DiagnosticPos.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/diagnotic/DiagnosticPos.java index 8b015632e7ee..f4e3119ef870 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/diagnotic/DiagnosticPos.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/diagnotic/DiagnosticPos.java @@ -81,10 +81,9 @@ public boolean equals(Object obj) { if (this == obj) { return true; } - if (!(obj instanceof DiagnosticPos)) { + if (!(obj instanceof DiagnosticPos diagnosticPos)) { return false; } - DiagnosticPos diagnosticPos = (DiagnosticPos) obj; return packageID.equals(diagnosticPos.getPackageID()) && lineRange().fileName().equals(diagnosticPos.lineRange().fileName()) && (getStartLine() == diagnosticPos.getStartLine() && getEndLine() == diagnosticPos.getEndLine() && diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/programfile/PackageFileWriter.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/programfile/PackageFileWriter.java index 5b6059f7ab0a..22d6401e45cc 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/programfile/PackageFileWriter.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/programfile/PackageFileWriter.java @@ -30,7 +30,10 @@ * @since 0.963.0 */ @Deprecated -public class PackageFileWriter { +public final class PackageFileWriter { + + private PackageFileWriter() { + } public static byte[] writePackage(PackageFile packageFile) throws IOException { ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream(); diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/programfile/ProgramFileConstants.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/programfile/ProgramFileConstants.java index a8e81b4d5fde..deb7028985c4 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/programfile/ProgramFileConstants.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/programfile/ProgramFileConstants.java @@ -21,7 +21,7 @@ * @since 0.94 */ @Deprecated -public class ProgramFileConstants { +public final class ProgramFileConstants { public static final int MAGIC_NUMBER = 0xBA1DA4CE; public static final short VERSION_NUMBER = 50; @@ -32,4 +32,7 @@ public class ProgramFileConstants { // todo move this to a proper place public static final String[] SUPPORTED_PLATFORMS = {"java17", "java11"}; public static final String ANY_PLATFORM = "any"; + + private ProgramFileConstants() { + } } diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/util/AttachPoints.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/util/AttachPoints.java index 07ccac533675..4f96dbb96ab1 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/util/AttachPoints.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/util/AttachPoints.java @@ -26,7 +26,8 @@ * * @since 0.974.0 */ -public class AttachPoints { +public final class AttachPoints { + public static final int TYPE = 1; public static final int OBJECT = TYPE << 1; public static final int FUNCTION = OBJECT << 1; @@ -46,6 +47,9 @@ public class AttachPoints { public static final int WORKER = CONST << 1; public static final int CLASS = WORKER << 1; + private AttachPoints() { + } + public static int asMask(Set attachPoints) { int mask = 0; for (AttachPoint.Point point : attachPoints) { diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/util/Flags.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/util/Flags.java index 25fa804b1e70..4b6f1e0cb2cd 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/util/Flags.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/util/Flags.java @@ -25,7 +25,7 @@ /** * @since 0.94 */ -public class Flags { +public final class Flags { public static final long PUBLIC = 1; // 0 public static final long NATIVE = PUBLIC << 1; // 1 @@ -84,6 +84,9 @@ public class Flags { public static final long EFFECTIVE_TYPE_DEF = QUERY_LAMBDA << 1; // 43 public static final long SOURCE_ANNOTATION = EFFECTIVE_TYPE_DEF << 1; // 44 + private Flags() { + } + public static long asMask(Set flagSet) { long mask = 0; for (Flag flag : flagSet) { diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/util/LambdaExceptionUtils.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/util/LambdaExceptionUtils.java index 75f8144ec937..2677ff98d73a 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/util/LambdaExceptionUtils.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/util/LambdaExceptionUtils.java @@ -26,7 +26,10 @@ * * @since 0.970.0 */ -public class LambdaExceptionUtils { +public final class LambdaExceptionUtils { + + private LambdaExceptionUtils() { + } /** * Represents a {@code Consumer} interface which can throw exceptions. diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/util/Lists.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/util/Lists.java index b6c2b96b62a0..97fa97f99f8e 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/util/Lists.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/util/Lists.java @@ -25,7 +25,10 @@ /*** * @since 0.94 */ -public class Lists { +public final class Lists { + + private Lists() { + } @SafeVarargs public static List of(E... values) { diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/util/RepoUtils.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/util/RepoUtils.java index d59605eb2f59..b6bdde5c622b 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/util/RepoUtils.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/util/RepoUtils.java @@ -35,6 +35,7 @@ import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.Enumeration; import java.util.Map; import java.util.Properties; import java.util.jar.JarEntry; @@ -44,7 +45,7 @@ /** * Home repository util methods. */ -public class RepoUtils { +public final class RepoUtils { public static final String BALLERINA_INSTALL_DIR_PROP = "ballerina.home"; public static final String COMPILE_BALLERINA_ORG_PROP = "BALLERINA_DEV_COMPILE_BALLERINA_ORG"; @@ -70,7 +71,10 @@ public class RepoUtils { System.getenv(BALLERINA_DEV_CENTRAL)); private static final String UNKNOWN = "unknown"; - + + private RepoUtils() { + } + /** * Create and get the home repository path. * @@ -301,9 +305,9 @@ public static boolean isANightlyBuild() { */ public static Manifest getManifestFromBala(Path balaPath) { try (JarFile jar = new JarFile(balaPath.toString())) { - java.util.Enumeration enumEntries = jar.entries(); + Enumeration enumEntries = jar.entries(); while (enumEntries.hasMoreElements()) { - JarEntry file = (JarEntry) enumEntries.nextElement(); + JarEntry file = enumEntries.nextElement(); if (file.getName().contains(ProjectDirConstants.MANIFEST_FILE_NAME)) { if (file.isDirectory()) { // if its a directory, ignore continue; diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/util/TomlParserUtils.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/util/TomlParserUtils.java index 8f4a51cb4879..f7bd95ae113c 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/util/TomlParserUtils.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/util/TomlParserUtils.java @@ -35,7 +35,11 @@ * * @since 0.982.0 */ -public class TomlParserUtils { +public final class TomlParserUtils { + + private TomlParserUtils() { + } + /** * Read Settings.toml to populate the configurations. * diff --git a/compiler/ballerina-lang/src/test/java/io/ballerina/projects/BallerinaTomlTests.java b/compiler/ballerina-lang/src/test/java/io/ballerina/projects/BallerinaTomlTests.java index cbbc7c7898f4..91bae1a45de7 100644 --- a/compiler/ballerina-lang/src/test/java/io/ballerina/projects/BallerinaTomlTests.java +++ b/compiler/ballerina-lang/src/test/java/io/ballerina/projects/BallerinaTomlTests.java @@ -546,7 +546,8 @@ public void testOtherEntries() throws IOException { Assert.assertEquals(frequency.longValue(), 225); // other entry table array - List> userContacts = (ArrayList) packageManifest.getValue("userContact"); + ArrayList> userContacts = + (ArrayList>) packageManifest.getValue("userContact"); Assert.assertEquals(userContacts.size(), 2); Map firstContact = userContacts.get(0); Assert.assertEquals(firstContact.get("name"), "hevayo"); diff --git a/compiler/ballerina-lang/src/test/java/io/ballerina/projects/FileSystemRepositoryTests.java b/compiler/ballerina-lang/src/test/java/io/ballerina/projects/FileSystemRepositoryTests.java index 53beb3959031..d68450b701e8 100644 --- a/compiler/ballerina-lang/src/test/java/io/ballerina/projects/FileSystemRepositoryTests.java +++ b/compiler/ballerina-lang/src/test/java/io/ballerina/projects/FileSystemRepositoryTests.java @@ -39,7 +39,7 @@ */ public class FileSystemRepositoryTests { - class MockFileSystemRepository extends FileSystemRepository { + private static class MockFileSystemRepository extends FileSystemRepository { public MockFileSystemRepository(Environment environment, Path cacheDirectory) { super(environment, cacheDirectory); diff --git a/compiler/ballerina-lang/src/test/java/io/ballerina/projects/MavenPackageRepositoryTests.java b/compiler/ballerina-lang/src/test/java/io/ballerina/projects/MavenPackageRepositoryTests.java index b1e0fd6a445e..2c0a4511c862 100644 --- a/compiler/ballerina-lang/src/test/java/io/ballerina/projects/MavenPackageRepositoryTests.java +++ b/compiler/ballerina-lang/src/test/java/io/ballerina/projects/MavenPackageRepositoryTests.java @@ -38,6 +38,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.stream.Stream; /** * Test maven package repository. @@ -47,7 +48,7 @@ public class MavenPackageRepositoryTests { - class MockMavenPackageRepository extends MavenPackageRepository { + private static class MockMavenPackageRepository extends MavenPackageRepository { public MockMavenPackageRepository(Environment environment, Path cacheDirectory, String distributionVersion) { super(environment, cacheDirectory, distributionVersion, null, null); @@ -241,10 +242,11 @@ private static void deleteRemotePackage() throws IOException { resolve("local-custom-repo") .resolve("bala").resolve("luheerathan").resolve("pact"); if (Files.exists(destinationFolderPath)) { - Files.walk(destinationFolderPath) - .sorted(Comparator.reverseOrder()) + try (Stream paths = Files.walk(destinationFolderPath)) { + paths.sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(File::delete); + } } } } diff --git a/compiler/ballerina-lang/src/test/java/io/ballerina/projects/providers/SemverDataProvider.java b/compiler/ballerina-lang/src/test/java/io/ballerina/projects/providers/SemverDataProvider.java index f59e4012df56..b93a039e7ed7 100644 --- a/compiler/ballerina-lang/src/test/java/io/ballerina/projects/providers/SemverDataProvider.java +++ b/compiler/ballerina-lang/src/test/java/io/ballerina/projects/providers/SemverDataProvider.java @@ -5,7 +5,10 @@ /** * Data providers for semver versions tests. */ -public class SemverDataProvider { +public final class SemverDataProvider { + + private SemverDataProvider() { + } @DataProvider(name = "semverVersions") public static Object[][] provideSemverVersions() { diff --git a/compiler/ballerina-lang/src/test/java/io/ballerina/projects/test/resolution/packages/internal/Constants.java b/compiler/ballerina-lang/src/test/java/io/ballerina/projects/test/resolution/packages/internal/Constants.java index b33761be5565..e0b9f415cda9 100644 --- a/compiler/ballerina-lang/src/test/java/io/ballerina/projects/test/resolution/packages/internal/Constants.java +++ b/compiler/ballerina-lang/src/test/java/io/ballerina/projects/test/resolution/packages/internal/Constants.java @@ -22,7 +22,7 @@ * * @since 2.0.0 */ -public class Constants { +public final class Constants { public static final String APP_FILE_NAME = "app.dot"; public static final String REPO_DIR_NAME = "repositories"; diff --git a/compiler/ballerina-lang/src/test/java/io/ballerina/projects/test/resolution/packages/internal/DefaultPackageRepository.java b/compiler/ballerina-lang/src/test/java/io/ballerina/projects/test/resolution/packages/internal/DefaultPackageRepository.java index 2eb83679eb66..2eaaefc03c08 100644 --- a/compiler/ballerina-lang/src/test/java/io/ballerina/projects/test/resolution/packages/internal/DefaultPackageRepository.java +++ b/compiler/ballerina-lang/src/test/java/io/ballerina/projects/test/resolution/packages/internal/DefaultPackageRepository.java @@ -89,7 +89,7 @@ public Collection getModules(PackageOrg org, PackageName name, return pkgDescWrapper.modules().stream() .map(modNameStr -> Utils.getModuleName(name, modNameStr)) .map(moduleName -> ModuleDescriptor.from(moduleName, pkgDesc)) - .collect(Collectors.toList()); + .toList(); } @Override diff --git a/compiler/ballerina-lang/src/test/java/io/ballerina/projects/test/resolution/packages/internal/DotGraphUtils.java b/compiler/ballerina-lang/src/test/java/io/ballerina/projects/test/resolution/packages/internal/DotGraphUtils.java index 5ce88ca47b95..e06a2cf5cb78 100644 --- a/compiler/ballerina-lang/src/test/java/io/ballerina/projects/test/resolution/packages/internal/DotGraphUtils.java +++ b/compiler/ballerina-lang/src/test/java/io/ballerina/projects/test/resolution/packages/internal/DotGraphUtils.java @@ -46,7 +46,7 @@ * * @since 2.0.0 */ -public class DotGraphUtils { +public final class DotGraphUtils { private DotGraphUtils() { } diff --git a/compiler/ballerina-lang/src/test/java/io/ballerina/projects/test/resolution/packages/internal/GraphUtils.java b/compiler/ballerina-lang/src/test/java/io/ballerina/projects/test/resolution/packages/internal/GraphUtils.java index c1b72d494b9a..815a627cdc93 100644 --- a/compiler/ballerina-lang/src/test/java/io/ballerina/projects/test/resolution/packages/internal/GraphUtils.java +++ b/compiler/ballerina-lang/src/test/java/io/ballerina/projects/test/resolution/packages/internal/GraphUtils.java @@ -25,14 +25,13 @@ import java.util.Collection; import java.util.Comparator; import java.util.List; -import java.util.stream.Collectors; /** * Contains a list of utility methods to work with Ballerina dependency graphs. * * @since 2.0.0 */ -public class GraphUtils { +public final class GraphUtils { private GraphUtils() { } @@ -84,7 +83,7 @@ public static GraphComparisonResult compareGraph(DependencyGraph } private static List getSortedCollection(Collection nodes) { - return nodes.stream().sorted(pkgDescComparator).collect(Collectors.toList()); + return nodes.stream().sorted(pkgDescComparator).toList(); } private static GraphComparisonResult reportGraphsWithDifferentNumberOfNodes( diff --git a/compiler/ballerina-lang/src/test/java/io/ballerina/projects/test/resolution/packages/internal/PackageRepositoryBuilder.java b/compiler/ballerina-lang/src/test/java/io/ballerina/projects/test/resolution/packages/internal/PackageRepositoryBuilder.java index 070c33a13b8d..cad1d6aa8a1c 100644 --- a/compiler/ballerina-lang/src/test/java/io/ballerina/projects/test/resolution/packages/internal/PackageRepositoryBuilder.java +++ b/compiler/ballerina-lang/src/test/java/io/ballerina/projects/test/resolution/packages/internal/PackageRepositoryBuilder.java @@ -35,7 +35,7 @@ import java.util.Optional; import java.util.Set; import java.util.StringJoiner; -import java.util.stream.Collectors; +import java.util.stream.Stream; /** * Reads repository dot files and build test package repository instances. @@ -76,16 +76,11 @@ private PackageRepository buildInternal(TestCaseFilePaths filePaths, RepositoryK } private Optional getRepPath(TestCaseFilePaths filePaths, RepositoryKind repoKind) { - switch (repoKind) { - case DIST: - return filePaths.distRepoPath(); - case CENTRAL: - return filePaths.centralRepoPath(); - case LOCAL: - return filePaths.localRepoDirPath(); - default: - throw new IllegalStateException("Unsupported package repository kind " + repoKind); - } + return switch (repoKind) { + case DIST -> filePaths.distRepoPath(); + case CENTRAL -> filePaths.centralRepoPath(); + case LOCAL -> filePaths.localRepoDirPath(); + }; } private PackageRepository buildLocalRepo(Path localRepoDirPath) { @@ -93,8 +88,8 @@ private PackageRepository buildLocalRepo(Path localRepoDirPath) { return DefaultPackageRepository.EMPTY_REPO; } - try { - return buildLocalRepo(Files.list(localRepoDirPath).collect(Collectors.toList())); + try (Stream paths = Files.list(localRepoDirPath)) { + return buildLocalRepo(paths.toList()); } catch (IOException e) { throw new RuntimeException(e); } @@ -190,15 +185,10 @@ private void buildPkgDescGraph(PackageDescriptor pkgDesc, private PackageRepository buildInternal(PackageVersionContainer pkgContainer, Map> graphMap, RepositoryKind repoKind) { - switch (repoKind) { - case LOCAL: - return new LocalPackageRepository(pkgContainer, graphMap); - case CENTRAL: - case DIST: - return new DefaultPackageRepository(pkgContainer, graphMap); - default: - throw new IllegalStateException("Unsupported package repository kind " + repoKind); - } + return switch (repoKind) { + case LOCAL -> new LocalPackageRepository(pkgContainer, graphMap); + case CENTRAL, DIST -> new DefaultPackageRepository(pkgContainer, graphMap); + }; } private static class GraphNodeMarker { @@ -220,7 +210,7 @@ List getUnmarkedNodes() { return marker.entrySet().stream() .filter(entry -> entry.getValue() == Boolean.FALSE) .map(Map.Entry::getKey) - .collect(Collectors.toList()); + .toList(); } } } diff --git a/compiler/ballerina-lang/src/test/java/io/ballerina/projects/test/resolution/packages/internal/PackageResolutionTestCaseBuilder.java b/compiler/ballerina-lang/src/test/java/io/ballerina/projects/test/resolution/packages/internal/PackageResolutionTestCaseBuilder.java index 7d9c7ccd83dd..741c34aeb632 100644 --- a/compiler/ballerina-lang/src/test/java/io/ballerina/projects/test/resolution/packages/internal/PackageResolutionTestCaseBuilder.java +++ b/compiler/ballerina-lang/src/test/java/io/ballerina/projects/test/resolution/packages/internal/PackageResolutionTestCaseBuilder.java @@ -48,14 +48,13 @@ import java.util.List; import java.util.Objects; import java.util.Set; -import java.util.stream.Collectors; /** * Builds package resolution test cases. * * @since 2.0.0 */ -public class PackageResolutionTestCaseBuilder { +public final class PackageResolutionTestCaseBuilder { private PackageResolutionTestCaseBuilder() { } @@ -101,7 +100,7 @@ private static List getModulesInRootPackage(PackageDescWrapper rootP PackageDescriptor rootPkgDes) { return rootPkgDescWrapper.modules().stream() .map(modNameStr -> Utils.getModuleName(rootPkgDes.name(), modNameStr)) - .collect(Collectors.toList()); + .toList(); } private static DependencyGraph getPkgDescGraph(Path dotFilePath) { diff --git a/compiler/ballerina-lang/src/test/java/io/ballerina/projects/test/resolution/packages/internal/TestCaseFilePaths.java b/compiler/ballerina-lang/src/test/java/io/ballerina/projects/test/resolution/packages/internal/TestCaseFilePaths.java index ae065b61b8cb..b57002051ead 100644 --- a/compiler/ballerina-lang/src/test/java/io/ballerina/projects/test/resolution/packages/internal/TestCaseFilePaths.java +++ b/compiler/ballerina-lang/src/test/java/io/ballerina/projects/test/resolution/packages/internal/TestCaseFilePaths.java @@ -96,7 +96,10 @@ public Optional expectedGraphNoStickyPath() { * * @since 2.0.0 */ - public static class TestCaseFilePathsBuilder { + public static final class TestCaseFilePathsBuilder { + + private TestCaseFilePathsBuilder() { + } public static TestCaseFilePaths build(Path testSuitePath, Path testCasePath) { Path appPath = getFilePath(testSuitePath, testCasePath, Paths.get(Constants.APP_FILE_NAME)); diff --git a/compiler/ballerina-lang/src/test/java/io/ballerina/projects/test/resolution/packages/internal/Utils.java b/compiler/ballerina-lang/src/test/java/io/ballerina/projects/test/resolution/packages/internal/Utils.java index 35f450c2acda..70fc33cfc4f0 100644 --- a/compiler/ballerina-lang/src/test/java/io/ballerina/projects/test/resolution/packages/internal/Utils.java +++ b/compiler/ballerina-lang/src/test/java/io/ballerina/projects/test/resolution/packages/internal/Utils.java @@ -31,7 +31,8 @@ * * @since 2.0.0 */ -public class Utils { +public final class Utils { + private Utils() { } diff --git a/compiler/ballerina-lang/src/test/java/io/ballerina/projects/utils/FileUtil.java b/compiler/ballerina-lang/src/test/java/io/ballerina/projects/utils/FileUtil.java index 45c318fb2243..76a4bfcbc668 100644 --- a/compiler/ballerina-lang/src/test/java/io/ballerina/projects/utils/FileUtil.java +++ b/compiler/ballerina-lang/src/test/java/io/ballerina/projects/utils/FileUtil.java @@ -23,7 +23,10 @@ /** * Utilities required for test cases. */ -public class FileUtil { +public final class FileUtil { + + private FileUtil() { + } public static boolean deleteDirectory(Path directoryPath) { File directory = new File(String.valueOf(directoryPath)); diff --git a/compiler/ballerina-lang/src/test/java/org/ballerinalang/toml/SingletonStackTest.java b/compiler/ballerina-lang/src/test/java/org/ballerinalang/toml/SingletonStackTest.java index 631ab60d9e2b..859e81ecb4c9 100644 --- a/compiler/ballerina-lang/src/test/java/org/ballerinalang/toml/SingletonStackTest.java +++ b/compiler/ballerina-lang/src/test/java/org/ballerinalang/toml/SingletonStackTest.java @@ -27,7 +27,7 @@ public class SingletonStackTest { @Test(description = "The value in the stack should be retrieved/popped out if a value is present") public void testPopWithValue() { - SingletonStack singletonStackTest = new SingletonStack(); + SingletonStack singletonStackTest = new SingletonStack<>(); singletonStackTest.push("hello"); Assert.assertEquals(singletonStackTest.pop(), "hello"); } @@ -35,27 +35,27 @@ public void testPopWithValue() { @Test(description = "The value should not be pushed to the stack if the stack already contains a value it should " + "give an exception", expectedExceptions = IllegalStateException.class) public void testPopWithoutValue() { - SingletonStack singletonStackTest = new SingletonStack(); + SingletonStack singletonStackTest = new SingletonStack<>(); singletonStackTest.pop(); Assert.assertEquals(singletonStackTest.present(), true); } @Test(description = "Return true if the value exists") public void testWithValuePresent() { - SingletonStack singletonStackTest = new SingletonStack(); + SingletonStack singletonStackTest = new SingletonStack<>(); singletonStackTest.push("hello"); Assert.assertEquals(singletonStackTest.present(), true); } @Test(description = "Return false if a value does not exists") public void testWithValueAbsent() { - SingletonStack singletonStackTest = new SingletonStack(); + SingletonStack singletonStackTest = new SingletonStack<>(); Assert.assertEquals(singletonStackTest.present(), false); } @Test(description = "The value should be pushed to the stack if the stack is not null") public void testPushToStackWithValue() { - SingletonStack singletonStackTest = new SingletonStack(); + SingletonStack singletonStackTest = new SingletonStack<>(); singletonStackTest.push("hello"); Assert.assertEquals(singletonStackTest.present(), true); Assert.assertEquals(singletonStackTest.pop(), "hello"); @@ -64,7 +64,7 @@ public void testPushToStackWithValue() { @Test(description = "The value should not be pushed to the stack if the stack already contains a value it should " + "give an exception", expectedExceptions = IllegalStateException.class) public void testPushMultipleValuesToStack() { - SingletonStack singletonStackTest = new SingletonStack(); + SingletonStack singletonStackTest = new SingletonStack<>(); singletonStackTest.push("hello"); singletonStackTest.push("world"); Assert.assertEquals(singletonStackTest.present(), true); diff --git a/compiler/ballerina-lang/src/test/java/org/ballerinalang/util/DiagnosticCodeTest.java b/compiler/ballerina-lang/src/test/java/org/ballerinalang/util/DiagnosticCodeTest.java index dad028d0504e..bdc87cee7285 100644 --- a/compiler/ballerina-lang/src/test/java/org/ballerinalang/util/DiagnosticCodeTest.java +++ b/compiler/ballerina-lang/src/test/java/org/ballerinalang/util/DiagnosticCodeTest.java @@ -80,7 +80,7 @@ private void validateDiagnosticUniqueness(DiagnosticCode[] codes) { } } - private String arrayToString(List listOfStrings) { + private String arrayToString(List listOfStrings) { return String.join(", ", listOfStrings); } } diff --git a/compiler/ballerina-lang/src/test/java/org/wso2/ballerinalang/compiler/BLangNodeTransformerTest.java b/compiler/ballerina-lang/src/test/java/org/wso2/ballerinalang/compiler/BLangNodeTransformerTest.java index 09bcdff89652..a5ab3766832a 100644 --- a/compiler/ballerina-lang/src/test/java/org/wso2/ballerinalang/compiler/BLangNodeTransformerTest.java +++ b/compiler/ballerina-lang/src/test/java/org/wso2/ballerinalang/compiler/BLangNodeTransformerTest.java @@ -50,11 +50,8 @@ */ public class BLangNodeTransformerTest { private static final Logger LOGGER = LoggerFactory.getLogger(BLangNodeTransformerTest.class); - private static final JsonParser JSON_PARSER = new JsonParser(); public static final Path RES_DIR = Paths.get("src/test/resources/node-tree/").toAbsolutePath(); - private final JsonParser jsonParser = new JsonParser(); - @Test(dataProvider = "testTransformationTestProvider", enabled = false) public void testTransformation(String configName, String sourcePackage) throws IOException, IllegalAccessException { @@ -67,7 +64,7 @@ public void testTransformation(String configName, String sourcePackage) BLangPackage bLangPackage = pkg.getCompilation().defaultModuleBLangPackage(); Set> skipList = new HashSet<>(); String jsonStr = generateFieldJson(bLangPackage.getClass(), bLangPackage, skipList, bLangPackage); - JsonObject actualJsonObj = jsonParser.parse(jsonStr).getAsJsonObject(); + JsonObject actualJsonObj = JsonParser.parseString(jsonStr).getAsJsonObject(); // Fix test cases replacing expected using responses // if (!expJsonObj.equals(actualJsonObj)) { @@ -174,10 +171,10 @@ private boolean handleCollections(Class type, Object objVal, Set> sk int[] level) throws IllegalAccessException { if (objVal instanceof Map) { builder.append("{"); - Iterator entries = ((Map) objVal).entrySet().iterator(); + Iterator> entries = ((Map) objVal).entrySet().iterator(); StringJoiner joiner = new StringJoiner(","); while (entries.hasNext()) { - Map.Entry entry = entries.next(); + Map.Entry entry = entries.next(); StringBuilder sBuilder = new StringBuilder("\"" + entry.getKey() + "\": "); joiner.add(generateFieldValueJson(entry.getValue().getClass(), entry.getValue(), skipList, visitedList, sBuilder, referenceNode, level)); @@ -189,7 +186,7 @@ private boolean handleCollections(Class type, Object objVal, Set> sk // Lists, Sets builder.append("["); StringJoiner joiner = new StringJoiner(","); - for (Object item : (Collection) objVal) { + for (Object item : (Collection) objVal) { joiner.add(generateFieldValueJson(item.getClass(), item, skipList, visitedList, new StringBuilder(""), referenceNode, level)); } @@ -242,7 +239,7 @@ private static JsonObject fileContentAsObject(String filePath) { } catch (IOException ex) { LOGGER.error(ex.getMessage()); } - return JSON_PARSER.parse(contentAsString).getAsJsonObject(); + return JsonParser.parseString(contentAsString).getAsJsonObject(); } private static Project loadProject(String sourceFilePath) { diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/diagnostics/DiagnosticMessageHelper.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/diagnostics/DiagnosticMessageHelper.java index 32a6d106d011..703e43031916 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/diagnostics/DiagnosticMessageHelper.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/diagnostics/DiagnosticMessageHelper.java @@ -28,7 +28,8 @@ * * @since 2.0.0 */ -public class DiagnosticMessageHelper { +public final class DiagnosticMessageHelper { + private static ResourceBundle messages = ResourceBundle.getBundle( "syntax_diagnostic_message", Locale.getDefault()); diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/BallerinaLexer.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/BallerinaLexer.java index cfddd0d51c37..a00d39fee324 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/BallerinaLexer.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/BallerinaLexer.java @@ -45,28 +45,22 @@ public BallerinaLexer(CharReader charReader) { */ @Override public STToken nextToken() { - STToken token; - switch (this.mode) { - case TEMPLATE: - token = readTemplateToken(); - break; - case REGEXP: - token = readRegExpTemplateToken(); - break; - case INTERPOLATION: + STToken token = switch (this.mode) { + case TEMPLATE -> readTemplateToken(); + case REGEXP -> readRegExpTemplateToken(); + case INTERPOLATION -> { processLeadingTrivia(); - token = readTokenInInterpolation(); - break; - case INTERPOLATION_BRACED_CONTENT: + yield readTokenInInterpolation(); + } + case INTERPOLATION_BRACED_CONTENT -> { processLeadingTrivia(); - token = readTokenInBracedContentInInterpolation(); - break; - case DEFAULT: - case IMPORT: - default: + yield readTokenInBracedContentInInterpolation(); + } + default -> { processLeadingTrivia(); - token = readToken(); - } + yield readToken(); + } + }; // Can we improve this logic by creating the token with diagnostics then and there? return cloneWithDiagnostics(token); @@ -574,18 +568,11 @@ private STToken processDecimalFloatLiteral() { nextChar = peek(); } - switch (nextChar) { - case 'e': - case 'E': - return processExponent(false); - case 'f': - case 'F': - case 'd': - case 'D': - return parseFloatingPointTypeSuffix(); - } - - return getLiteral(SyntaxKind.DECIMAL_FLOATING_POINT_LITERAL_TOKEN); + return switch (nextChar) { + case 'e', 'E' -> processExponent(false); + case 'f', 'F', 'd', 'D' -> parseFloatingPointTypeSuffix(); + default -> getLiteral(SyntaxKind.DECIMAL_FLOATING_POINT_LITERAL_TOKEN); + }; } /** @@ -636,15 +623,11 @@ private STToken processExponent(boolean isHex) { return getLiteral(SyntaxKind.HEX_FLOATING_POINT_LITERAL_TOKEN); } - switch (nextChar) { - case 'f': - case 'F': - case 'd': - case 'D': - return parseFloatingPointTypeSuffix(); - } + return switch (nextChar) { + case 'f', 'F', 'd', 'D' -> parseFloatingPointTypeSuffix(); + default -> getLiteral(SyntaxKind.DECIMAL_FLOATING_POINT_LITERAL_TOKEN); + }; - return getLiteral(SyntaxKind.DECIMAL_FLOATING_POINT_LITERAL_TOKEN); } /** @@ -842,213 +825,118 @@ private boolean isHexIntFollowedIdentifier() { private STToken processIdentifierOrKeyword() { processUnquotedIdentifier(); String tokenText = getLexeme(); - switch (tokenText) { + return switch (tokenText) { // built-in named-types - case LexerTerminals.INT: - return getSyntaxToken(SyntaxKind.INT_KEYWORD); - case LexerTerminals.FLOAT: - return getSyntaxToken(SyntaxKind.FLOAT_KEYWORD); - case LexerTerminals.STRING: - return getSyntaxToken(SyntaxKind.STRING_KEYWORD); - case LexerTerminals.BOOLEAN: - return getSyntaxToken(SyntaxKind.BOOLEAN_KEYWORD); - case LexerTerminals.DECIMAL: - return getSyntaxToken(SyntaxKind.DECIMAL_KEYWORD); - case LexerTerminals.XML: - return getSyntaxToken(SyntaxKind.XML_KEYWORD); - case LexerTerminals.JSON: - return getSyntaxToken(SyntaxKind.JSON_KEYWORD); - case LexerTerminals.HANDLE: - return getSyntaxToken(SyntaxKind.HANDLE_KEYWORD); - case LexerTerminals.ANY: - return getSyntaxToken(SyntaxKind.ANY_KEYWORD); - case LexerTerminals.ANYDATA: - return getSyntaxToken(SyntaxKind.ANYDATA_KEYWORD); - case LexerTerminals.NEVER: - return getSyntaxToken(SyntaxKind.NEVER_KEYWORD); - case LexerTerminals.BYTE: - return getSyntaxToken(SyntaxKind.BYTE_KEYWORD); + case LexerTerminals.INT -> getSyntaxToken(SyntaxKind.INT_KEYWORD); + case LexerTerminals.FLOAT -> getSyntaxToken(SyntaxKind.FLOAT_KEYWORD); + case LexerTerminals.STRING -> getSyntaxToken(SyntaxKind.STRING_KEYWORD); + case LexerTerminals.BOOLEAN -> getSyntaxToken(SyntaxKind.BOOLEAN_KEYWORD); + case LexerTerminals.DECIMAL -> getSyntaxToken(SyntaxKind.DECIMAL_KEYWORD); + case LexerTerminals.XML -> getSyntaxToken(SyntaxKind.XML_KEYWORD); + case LexerTerminals.JSON -> getSyntaxToken(SyntaxKind.JSON_KEYWORD); + case LexerTerminals.HANDLE -> getSyntaxToken(SyntaxKind.HANDLE_KEYWORD); + case LexerTerminals.ANY -> getSyntaxToken(SyntaxKind.ANY_KEYWORD); + case LexerTerminals.ANYDATA -> getSyntaxToken(SyntaxKind.ANYDATA_KEYWORD); + case LexerTerminals.NEVER -> getSyntaxToken(SyntaxKind.NEVER_KEYWORD); + case LexerTerminals.BYTE -> getSyntaxToken(SyntaxKind.BYTE_KEYWORD); // Keywords - case LexerTerminals.PUBLIC: - return getSyntaxToken(SyntaxKind.PUBLIC_KEYWORD); - case LexerTerminals.PRIVATE: - return getSyntaxToken(SyntaxKind.PRIVATE_KEYWORD); - case LexerTerminals.FUNCTION: - return getSyntaxToken(SyntaxKind.FUNCTION_KEYWORD); - case LexerTerminals.RETURN: - return getSyntaxToken(SyntaxKind.RETURN_KEYWORD); - case LexerTerminals.RETURNS: - return getSyntaxToken(SyntaxKind.RETURNS_KEYWORD); - case LexerTerminals.EXTERNAL: - return getSyntaxToken(SyntaxKind.EXTERNAL_KEYWORD); - case LexerTerminals.TYPE: - return getSyntaxToken(SyntaxKind.TYPE_KEYWORD); - case LexerTerminals.RECORD: - return getSyntaxToken(SyntaxKind.RECORD_KEYWORD); - case LexerTerminals.OBJECT: - return getSyntaxToken(SyntaxKind.OBJECT_KEYWORD); - case LexerTerminals.REMOTE: - return getSyntaxToken(SyntaxKind.REMOTE_KEYWORD); - case LexerTerminals.ABSTRACT: - return getSyntaxToken(SyntaxKind.ABSTRACT_KEYWORD); - case LexerTerminals.CLIENT: - return getSyntaxToken(SyntaxKind.CLIENT_KEYWORD); - case LexerTerminals.IF: - return getSyntaxToken(SyntaxKind.IF_KEYWORD); - case LexerTerminals.ELSE: - return getSyntaxToken(SyntaxKind.ELSE_KEYWORD); - case LexerTerminals.WHILE: - return getSyntaxToken(SyntaxKind.WHILE_KEYWORD); - case LexerTerminals.TRUE: - return getSyntaxToken(SyntaxKind.TRUE_KEYWORD); - case LexerTerminals.FALSE: - return getSyntaxToken(SyntaxKind.FALSE_KEYWORD); - case LexerTerminals.CHECK: - return getSyntaxToken(SyntaxKind.CHECK_KEYWORD); - case LexerTerminals.FAIL: - return getSyntaxToken(SyntaxKind.FAIL_KEYWORD); - case LexerTerminals.CHECKPANIC: - return getSyntaxToken(SyntaxKind.CHECKPANIC_KEYWORD); - case LexerTerminals.CONTINUE: - return getSyntaxToken(SyntaxKind.CONTINUE_KEYWORD); - case LexerTerminals.BREAK: - return getSyntaxToken(SyntaxKind.BREAK_KEYWORD); - case LexerTerminals.PANIC: - return getSyntaxToken(SyntaxKind.PANIC_KEYWORD); - case LexerTerminals.IMPORT: - return getSyntaxToken(SyntaxKind.IMPORT_KEYWORD); - case LexerTerminals.AS: - return getSyntaxToken(SyntaxKind.AS_KEYWORD); - case LexerTerminals.SERVICE: - return getSyntaxToken(SyntaxKind.SERVICE_KEYWORD); - case LexerTerminals.ON: - return getSyntaxToken(SyntaxKind.ON_KEYWORD); - case LexerTerminals.RESOURCE: - return getSyntaxToken(SyntaxKind.RESOURCE_KEYWORD); - case LexerTerminals.LISTENER: - return getSyntaxToken(SyntaxKind.LISTENER_KEYWORD); - case LexerTerminals.CONST: - return getSyntaxToken(SyntaxKind.CONST_KEYWORD); - case LexerTerminals.FINAL: - return getSyntaxToken(SyntaxKind.FINAL_KEYWORD); - case LexerTerminals.TYPEOF: - return getSyntaxToken(SyntaxKind.TYPEOF_KEYWORD); - case LexerTerminals.IS: - return getSyntaxToken(SyntaxKind.IS_KEYWORD); - case LexerTerminals.NULL: - return getSyntaxToken(SyntaxKind.NULL_KEYWORD); - case LexerTerminals.LOCK: - return getSyntaxToken(SyntaxKind.LOCK_KEYWORD); - case LexerTerminals.ANNOTATION: - return getSyntaxToken(SyntaxKind.ANNOTATION_KEYWORD); - case LexerTerminals.SOURCE: - return getSyntaxToken(SyntaxKind.SOURCE_KEYWORD); - case LexerTerminals.VAR: - return getSyntaxToken(SyntaxKind.VAR_KEYWORD); - case LexerTerminals.WORKER: - return getSyntaxToken(SyntaxKind.WORKER_KEYWORD); - case LexerTerminals.PARAMETER: - return getSyntaxToken(SyntaxKind.PARAMETER_KEYWORD); - case LexerTerminals.FIELD: - return getSyntaxToken(SyntaxKind.FIELD_KEYWORD); - case LexerTerminals.ISOLATED: - return getSyntaxToken(SyntaxKind.ISOLATED_KEYWORD); - case LexerTerminals.XMLNS: - return getSyntaxToken(SyntaxKind.XMLNS_KEYWORD); - case LexerTerminals.FORK: - return getSyntaxToken(SyntaxKind.FORK_KEYWORD); - case LexerTerminals.MAP: - return getSyntaxToken(SyntaxKind.MAP_KEYWORD); - case LexerTerminals.FUTURE: - return getSyntaxToken(SyntaxKind.FUTURE_KEYWORD); - case LexerTerminals.TYPEDESC: - return getSyntaxToken(SyntaxKind.TYPEDESC_KEYWORD); - case LexerTerminals.TRAP: - return getSyntaxToken(SyntaxKind.TRAP_KEYWORD); - case LexerTerminals.IN: - return getSyntaxToken(SyntaxKind.IN_KEYWORD); - case LexerTerminals.FOREACH: - return getSyntaxToken(SyntaxKind.FOREACH_KEYWORD); - case LexerTerminals.TABLE: - return getSyntaxToken(SyntaxKind.TABLE_KEYWORD); - case LexerTerminals.ERROR: - return getSyntaxToken(SyntaxKind.ERROR_KEYWORD); - case LexerTerminals.LET: - return getSyntaxToken(SyntaxKind.LET_KEYWORD); - case LexerTerminals.STREAM: - return getSyntaxToken(SyntaxKind.STREAM_KEYWORD); - case LexerTerminals.NEW: - return getSyntaxToken(SyntaxKind.NEW_KEYWORD); - case LexerTerminals.READONLY: - return getSyntaxToken(SyntaxKind.READONLY_KEYWORD); - case LexerTerminals.DISTINCT: - return getSyntaxToken(SyntaxKind.DISTINCT_KEYWORD); - case LexerTerminals.FROM: - return getSyntaxToken(SyntaxKind.FROM_KEYWORD); - case LexerTerminals.START: - return getSyntaxToken(SyntaxKind.START_KEYWORD); - case LexerTerminals.FLUSH: - return getSyntaxToken(SyntaxKind.FLUSH_KEYWORD); - case LexerTerminals.WAIT: - return getSyntaxToken(SyntaxKind.WAIT_KEYWORD); - case LexerTerminals.DO: - return getSyntaxToken(SyntaxKind.DO_KEYWORD); - case LexerTerminals.TRANSACTION: - return getSyntaxToken(SyntaxKind.TRANSACTION_KEYWORD); - case LexerTerminals.COMMIT: - return getSyntaxToken(SyntaxKind.COMMIT_KEYWORD); - case LexerTerminals.RETRY: - return getSyntaxToken(SyntaxKind.RETRY_KEYWORD); - case LexerTerminals.ROLLBACK: - return getSyntaxToken(SyntaxKind.ROLLBACK_KEYWORD); - case LexerTerminals.TRANSACTIONAL: - return getSyntaxToken(SyntaxKind.TRANSACTIONAL_KEYWORD); - case LexerTerminals.ENUM: - return getSyntaxToken(SyntaxKind.ENUM_KEYWORD); - case LexerTerminals.BASE16: - return getSyntaxToken(SyntaxKind.BASE16_KEYWORD); - case LexerTerminals.BASE64: - return getSyntaxToken(SyntaxKind.BASE64_KEYWORD); - case LexerTerminals.MATCH: - return getSyntaxToken(SyntaxKind.MATCH_KEYWORD); - case LexerTerminals.CONFLICT: - return getSyntaxToken(SyntaxKind.CONFLICT_KEYWORD); - case LexerTerminals.CLASS: - return getSyntaxToken(SyntaxKind.CLASS_KEYWORD); - case LexerTerminals.CONFIGURABLE: - return getSyntaxToken(SyntaxKind.CONFIGURABLE_KEYWORD); - case LexerTerminals.WHERE: - return getSyntaxToken(SyntaxKind.WHERE_KEYWORD); - case LexerTerminals.SELECT: - return getSyntaxToken(SyntaxKind.SELECT_KEYWORD); - case LexerTerminals.LIMIT: - return getSyntaxToken(SyntaxKind.LIMIT_KEYWORD); - case LexerTerminals.OUTER: - return getSyntaxToken(SyntaxKind.OUTER_KEYWORD); - case LexerTerminals.EQUALS: - return getSyntaxToken(SyntaxKind.EQUALS_KEYWORD); - case LexerTerminals.ORDER: - return getSyntaxToken(SyntaxKind.ORDER_KEYWORD); - case LexerTerminals.BY: - return getSyntaxToken(SyntaxKind.BY_KEYWORD); - case LexerTerminals.ASCENDING: - return getSyntaxToken(SyntaxKind.ASCENDING_KEYWORD); - case LexerTerminals.DESCENDING: - return getSyntaxToken(SyntaxKind.DESCENDING_KEYWORD); - case LexerTerminals.JOIN: - return getSyntaxToken(SyntaxKind.JOIN_KEYWORD); - case LexerTerminals.RE: + case LexerTerminals.PUBLIC -> getSyntaxToken(SyntaxKind.PUBLIC_KEYWORD); + case LexerTerminals.PRIVATE -> getSyntaxToken(SyntaxKind.PRIVATE_KEYWORD); + case LexerTerminals.FUNCTION -> getSyntaxToken(SyntaxKind.FUNCTION_KEYWORD); + case LexerTerminals.RETURN -> getSyntaxToken(SyntaxKind.RETURN_KEYWORD); + case LexerTerminals.RETURNS -> getSyntaxToken(SyntaxKind.RETURNS_KEYWORD); + case LexerTerminals.EXTERNAL -> getSyntaxToken(SyntaxKind.EXTERNAL_KEYWORD); + case LexerTerminals.TYPE -> getSyntaxToken(SyntaxKind.TYPE_KEYWORD); + case LexerTerminals.RECORD -> getSyntaxToken(SyntaxKind.RECORD_KEYWORD); + case LexerTerminals.OBJECT -> getSyntaxToken(SyntaxKind.OBJECT_KEYWORD); + case LexerTerminals.REMOTE -> getSyntaxToken(SyntaxKind.REMOTE_KEYWORD); + case LexerTerminals.ABSTRACT -> getSyntaxToken(SyntaxKind.ABSTRACT_KEYWORD); + case LexerTerminals.CLIENT -> getSyntaxToken(SyntaxKind.CLIENT_KEYWORD); + case LexerTerminals.IF -> getSyntaxToken(SyntaxKind.IF_KEYWORD); + case LexerTerminals.ELSE -> getSyntaxToken(SyntaxKind.ELSE_KEYWORD); + case LexerTerminals.WHILE -> getSyntaxToken(SyntaxKind.WHILE_KEYWORD); + case LexerTerminals.TRUE -> getSyntaxToken(SyntaxKind.TRUE_KEYWORD); + case LexerTerminals.FALSE -> getSyntaxToken(SyntaxKind.FALSE_KEYWORD); + case LexerTerminals.CHECK -> getSyntaxToken(SyntaxKind.CHECK_KEYWORD); + case LexerTerminals.FAIL -> getSyntaxToken(SyntaxKind.FAIL_KEYWORD); + case LexerTerminals.CHECKPANIC -> getSyntaxToken(SyntaxKind.CHECKPANIC_KEYWORD); + case LexerTerminals.CONTINUE -> getSyntaxToken(SyntaxKind.CONTINUE_KEYWORD); + case LexerTerminals.BREAK -> getSyntaxToken(SyntaxKind.BREAK_KEYWORD); + case LexerTerminals.PANIC -> getSyntaxToken(SyntaxKind.PANIC_KEYWORD); + case LexerTerminals.IMPORT -> getSyntaxToken(SyntaxKind.IMPORT_KEYWORD); + case LexerTerminals.AS -> getSyntaxToken(SyntaxKind.AS_KEYWORD); + case LexerTerminals.SERVICE -> getSyntaxToken(SyntaxKind.SERVICE_KEYWORD); + case LexerTerminals.ON -> getSyntaxToken(SyntaxKind.ON_KEYWORD); + case LexerTerminals.RESOURCE -> getSyntaxToken(SyntaxKind.RESOURCE_KEYWORD); + case LexerTerminals.LISTENER -> getSyntaxToken(SyntaxKind.LISTENER_KEYWORD); + case LexerTerminals.CONST -> getSyntaxToken(SyntaxKind.CONST_KEYWORD); + case LexerTerminals.FINAL -> getSyntaxToken(SyntaxKind.FINAL_KEYWORD); + case LexerTerminals.TYPEOF -> getSyntaxToken(SyntaxKind.TYPEOF_KEYWORD); + case LexerTerminals.IS -> getSyntaxToken(SyntaxKind.IS_KEYWORD); + case LexerTerminals.NULL -> getSyntaxToken(SyntaxKind.NULL_KEYWORD); + case LexerTerminals.LOCK -> getSyntaxToken(SyntaxKind.LOCK_KEYWORD); + case LexerTerminals.ANNOTATION -> getSyntaxToken(SyntaxKind.ANNOTATION_KEYWORD); + case LexerTerminals.SOURCE -> getSyntaxToken(SyntaxKind.SOURCE_KEYWORD); + case LexerTerminals.VAR -> getSyntaxToken(SyntaxKind.VAR_KEYWORD); + case LexerTerminals.WORKER -> getSyntaxToken(SyntaxKind.WORKER_KEYWORD); + case LexerTerminals.PARAMETER -> getSyntaxToken(SyntaxKind.PARAMETER_KEYWORD); + case LexerTerminals.FIELD -> getSyntaxToken(SyntaxKind.FIELD_KEYWORD); + case LexerTerminals.ISOLATED -> getSyntaxToken(SyntaxKind.ISOLATED_KEYWORD); + case LexerTerminals.XMLNS -> getSyntaxToken(SyntaxKind.XMLNS_KEYWORD); + case LexerTerminals.FORK -> getSyntaxToken(SyntaxKind.FORK_KEYWORD); + case LexerTerminals.MAP -> getSyntaxToken(SyntaxKind.MAP_KEYWORD); + case LexerTerminals.FUTURE -> getSyntaxToken(SyntaxKind.FUTURE_KEYWORD); + case LexerTerminals.TYPEDESC -> getSyntaxToken(SyntaxKind.TYPEDESC_KEYWORD); + case LexerTerminals.TRAP -> getSyntaxToken(SyntaxKind.TRAP_KEYWORD); + case LexerTerminals.IN -> getSyntaxToken(SyntaxKind.IN_KEYWORD); + case LexerTerminals.FOREACH -> getSyntaxToken(SyntaxKind.FOREACH_KEYWORD); + case LexerTerminals.TABLE -> getSyntaxToken(SyntaxKind.TABLE_KEYWORD); + case LexerTerminals.ERROR -> getSyntaxToken(SyntaxKind.ERROR_KEYWORD); + case LexerTerminals.LET -> getSyntaxToken(SyntaxKind.LET_KEYWORD); + case LexerTerminals.STREAM -> getSyntaxToken(SyntaxKind.STREAM_KEYWORD); + case LexerTerminals.NEW -> getSyntaxToken(SyntaxKind.NEW_KEYWORD); + case LexerTerminals.READONLY -> getSyntaxToken(SyntaxKind.READONLY_KEYWORD); + case LexerTerminals.DISTINCT -> getSyntaxToken(SyntaxKind.DISTINCT_KEYWORD); + case LexerTerminals.FROM -> getSyntaxToken(SyntaxKind.FROM_KEYWORD); + case LexerTerminals.START -> getSyntaxToken(SyntaxKind.START_KEYWORD); + case LexerTerminals.FLUSH -> getSyntaxToken(SyntaxKind.FLUSH_KEYWORD); + case LexerTerminals.WAIT -> getSyntaxToken(SyntaxKind.WAIT_KEYWORD); + case LexerTerminals.DO -> getSyntaxToken(SyntaxKind.DO_KEYWORD); + case LexerTerminals.TRANSACTION -> getSyntaxToken(SyntaxKind.TRANSACTION_KEYWORD); + case LexerTerminals.COMMIT -> getSyntaxToken(SyntaxKind.COMMIT_KEYWORD); + case LexerTerminals.RETRY -> getSyntaxToken(SyntaxKind.RETRY_KEYWORD); + case LexerTerminals.ROLLBACK -> getSyntaxToken(SyntaxKind.ROLLBACK_KEYWORD); + case LexerTerminals.TRANSACTIONAL -> getSyntaxToken(SyntaxKind.TRANSACTIONAL_KEYWORD); + case LexerTerminals.ENUM -> getSyntaxToken(SyntaxKind.ENUM_KEYWORD); + case LexerTerminals.BASE16 -> getSyntaxToken(SyntaxKind.BASE16_KEYWORD); + case LexerTerminals.BASE64 -> getSyntaxToken(SyntaxKind.BASE64_KEYWORD); + case LexerTerminals.MATCH -> getSyntaxToken(SyntaxKind.MATCH_KEYWORD); + case LexerTerminals.CONFLICT -> getSyntaxToken(SyntaxKind.CONFLICT_KEYWORD); + case LexerTerminals.CLASS -> getSyntaxToken(SyntaxKind.CLASS_KEYWORD); + case LexerTerminals.CONFIGURABLE -> getSyntaxToken(SyntaxKind.CONFIGURABLE_KEYWORD); + case LexerTerminals.WHERE -> getSyntaxToken(SyntaxKind.WHERE_KEYWORD); + case LexerTerminals.SELECT -> getSyntaxToken(SyntaxKind.SELECT_KEYWORD); + case LexerTerminals.LIMIT -> getSyntaxToken(SyntaxKind.LIMIT_KEYWORD); + case LexerTerminals.OUTER -> getSyntaxToken(SyntaxKind.OUTER_KEYWORD); + case LexerTerminals.EQUALS -> getSyntaxToken(SyntaxKind.EQUALS_KEYWORD); + case LexerTerminals.ORDER -> getSyntaxToken(SyntaxKind.ORDER_KEYWORD); + case LexerTerminals.BY -> getSyntaxToken(SyntaxKind.BY_KEYWORD); + case LexerTerminals.ASCENDING -> getSyntaxToken(SyntaxKind.ASCENDING_KEYWORD); + case LexerTerminals.DESCENDING -> getSyntaxToken(SyntaxKind.DESCENDING_KEYWORD); + case LexerTerminals.JOIN -> getSyntaxToken(SyntaxKind.JOIN_KEYWORD); + case LexerTerminals.RE -> { if (getNextNonWSOrNonCommentChar() == LexerTerminals.BACKTICK) { - return getSyntaxToken(SyntaxKind.RE_KEYWORD); + yield getSyntaxToken(SyntaxKind.RE_KEYWORD); } - return getIdentifierToken(); - default: + yield getIdentifierToken(); + } + default -> // if (this.keywordModes.contains(KeywordMode.QUERY)) { // return getQueryCtxKeywordOrIdentifier(tokenText); // } - return getIdentifierToken(); - } + getIdentifierToken(); + }; } private int getNextNonWSOrNonCommentChar() { @@ -1155,50 +1043,46 @@ private boolean isEndOfInvalidToken() { } int currentChar = peek(); - switch (currentChar) { - case LexerTerminals.NEWLINE: - case LexerTerminals.CARRIAGE_RETURN: - case LexerTerminals.SPACE: - case LexerTerminals.TAB: - - // Separators - case LexerTerminals.SEMICOLON: - case LexerTerminals.COLON: - case LexerTerminals.DOT: - case LexerTerminals.COMMA: - case LexerTerminals.OPEN_PARANTHESIS: - case LexerTerminals.CLOSE_PARANTHESIS: - case LexerTerminals.OPEN_BRACE: - case LexerTerminals.CLOSE_BRACE: - case LexerTerminals.OPEN_BRACKET: - case LexerTerminals.CLOSE_BRACKET: - case LexerTerminals.PIPE: - case LexerTerminals.QUESTION_MARK: - case LexerTerminals.DOUBLE_QUOTE: - case LexerTerminals.SINGLE_QUOTE: - case LexerTerminals.HASH: - case LexerTerminals.AT: - case LexerTerminals.BACKTICK: - case LexerTerminals.DOLLAR: - - // Arithmetic operators - case LexerTerminals.EQUAL: - case LexerTerminals.PLUS: - case LexerTerminals.MINUS: - case LexerTerminals.ASTERISK: - case LexerTerminals.SLASH: - case LexerTerminals.PERCENT: - case LexerTerminals.GT: - case LexerTerminals.LT: - case LexerTerminals.BACKSLASH: - case LexerTerminals.EXCLAMATION_MARK: - case LexerTerminals.BITWISE_AND: - case LexerTerminals.BITWISE_XOR: - case LexerTerminals.NEGATION: - return true; - default: - return isIdentifierFollowingChar(currentChar); - } + return switch (currentChar) { + case LexerTerminals.NEWLINE, + LexerTerminals.CARRIAGE_RETURN, + LexerTerminals.SPACE, + LexerTerminals.TAB, + // Separators + LexerTerminals.SEMICOLON, + LexerTerminals.COLON, + LexerTerminals.DOT, + LexerTerminals.COMMA, + LexerTerminals.OPEN_PARANTHESIS, + LexerTerminals.CLOSE_PARANTHESIS, + LexerTerminals.OPEN_BRACE, + LexerTerminals.CLOSE_BRACE, + LexerTerminals.OPEN_BRACKET, + LexerTerminals.CLOSE_BRACKET, + LexerTerminals.PIPE, + LexerTerminals.QUESTION_MARK, + LexerTerminals.DOUBLE_QUOTE, + LexerTerminals.SINGLE_QUOTE, + LexerTerminals.HASH, + LexerTerminals.AT, + LexerTerminals.BACKTICK, + LexerTerminals.DOLLAR, + // Arithmetic operators + LexerTerminals.EQUAL, + LexerTerminals.PLUS, + LexerTerminals.MINUS, + LexerTerminals.ASTERISK, + LexerTerminals.SLASH, + LexerTerminals.PERCENT, + LexerTerminals.GT, + LexerTerminals.LT, + LexerTerminals.BACKSLASH, + LexerTerminals.EXCLAMATION_MARK, + LexerTerminals.BITWISE_AND, + LexerTerminals.BITWISE_XOR, + LexerTerminals.NEGATION -> true; + default -> isIdentifierFollowingChar(currentChar); + }; } /** @@ -1337,16 +1221,17 @@ private boolean isNotIsToken() { * @return One of the tokens: '|', '|}', '||' */ private STToken processPipeOperator() { - switch (peek()) { // check for the second char - case LexerTerminals.CLOSE_BRACE: + return switch (peek()) { // check for the second char + case LexerTerminals.CLOSE_BRACE -> { reader.advance(); - return getSyntaxToken(SyntaxKind.CLOSE_BRACE_PIPE_TOKEN); - case LexerTerminals.PIPE: + yield getSyntaxToken(SyntaxKind.CLOSE_BRACE_PIPE_TOKEN); + } + case LexerTerminals.PIPE -> { reader.advance(); - return getSyntaxToken(SyntaxKind.LOGICAL_OR_TOKEN); - default: - return getSyntaxToken(SyntaxKind.PIPE_TOKEN); - } + yield getSyntaxToken(SyntaxKind.LOGICAL_OR_TOKEN); + } + default -> getSyntaxToken(SyntaxKind.PIPE_TOKEN); + }; } /** @@ -1691,21 +1576,22 @@ private STToken processTokenStartWithGt() { } char nextChar = reader.peek(1); - switch (nextChar) { - case LexerTerminals.GT: + return switch (nextChar) { + case LexerTerminals.GT -> { if (reader.peek(2) == LexerTerminals.EQUAL) { // ">>>=" reader.advance(2); - return getSyntaxToken(SyntaxKind.TRIPPLE_GT_TOKEN); + yield getSyntaxToken(SyntaxKind.TRIPPLE_GT_TOKEN); } - return getSyntaxToken(SyntaxKind.GT_TOKEN); - case LexerTerminals.EQUAL: + yield getSyntaxToken(SyntaxKind.GT_TOKEN); + } + case LexerTerminals.EQUAL -> { // ">>=" reader.advance(1); - return getSyntaxToken(SyntaxKind.DOUBLE_GT_TOKEN); - default: - return getSyntaxToken(SyntaxKind.GT_TOKEN); - } + yield getSyntaxToken(SyntaxKind.DOUBLE_GT_TOKEN); + } + default -> getSyntaxToken(SyntaxKind.GT_TOKEN); + }; } /* diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/BallerinaParser.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/BallerinaParser.java index db0812e4ec85..5134953eda5b 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/BallerinaParser.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/BallerinaParser.java @@ -633,44 +633,41 @@ private STNode addAnnotNotAttachedDiagnostic(STNodeList annotList) { private boolean isModuleVarDeclStart(int lookahead) { // Assumes that we reach here after a peek() STToken nextToken = peek(lookahead + 1); - switch (nextToken.kind) { - case EQUAL_TOKEN: // Scenario: foo = . Even though this is not valid, consider this as a var-decl and - // continue; - case OPEN_BRACKET_TOKEN: // Scenario foo[] (Array type descriptor with custom type) - case QUESTION_MARK_TOKEN: // Scenario foo? (Optional type descriptor with custom type) - case PIPE_TOKEN: // Scenario foo | (Union type descriptor with custom type) - case BITWISE_AND_TOKEN: // Scenario foo & (Intersection type descriptor with custom type) - case OPEN_BRACE_TOKEN: // Scenario foo{} (mapping-binding-pattern) - case ERROR_KEYWORD: // Scenario foo error (error-binding-pattern) - case EOF_TOKEN: - return true; - case IDENTIFIER_TOKEN: - switch (peek(lookahead + 2).kind) { - case EQUAL_TOKEN: // Scenario: foo bar = - case SEMICOLON_TOKEN: // Scenario: foo bar; - case EOF_TOKEN: - return true; - default: - return false; - } - case COLON_TOKEN: + return switch (nextToken.kind) { + case EQUAL_TOKEN, // Scenario: foo = . Even though this is not valid, consider this as a var-decl and + // continue; + OPEN_BRACKET_TOKEN, // Scenario foo[] (Array type descriptor with custom type) + QUESTION_MARK_TOKEN, // Scenario foo? (Optional type descriptor with custom type) + PIPE_TOKEN, // Scenario foo | (Union type descriptor with custom type) + BITWISE_AND_TOKEN, // Scenario foo & (Intersection type descriptor with custom type) + OPEN_BRACE_TOKEN, // Scenario foo{} (mapping-binding-pattern) + ERROR_KEYWORD, // Scenario foo error (error-binding-pattern) + EOF_TOKEN -> true; + case IDENTIFIER_TOKEN -> switch (peek(lookahead + 2).kind) { + case EQUAL_TOKEN, + // Scenario: foo bar = + SEMICOLON_TOKEN, + // Scenario: foo bar; + EOF_TOKEN -> true; + default -> false; + }; + case COLON_TOKEN -> { if (lookahead > 1) { // This means there's a colon somewhere after the type name. // This is not a valid var-decl. - return false; + yield false; } - switch (peek(lookahead + 2).kind) { - case IDENTIFIER_TOKEN: // Scenario: foo:bar baz ... - return isModuleVarDeclStart(lookahead + 2); - case EOF_TOKEN: // Scenario: foo: recovery - return true; - default: - return false; - } - default: - return false; - } + yield switch (peek(lookahead + 2).kind) { + // Scenario: foo:bar baz ... + case IDENTIFIER_TOKEN -> isModuleVarDeclStart(lookahead + 2); + // Scenario: foo: recovery + case EOF_TOKEN -> true; + default -> false; + }; + } + default -> false; + }; } /** @@ -831,36 +828,32 @@ private STNode parseModuleName(STNode moduleNameStart) { } private STNode parseModuleNameRhs() { - switch(peek().kind) { - case DOT_TOKEN: - return consume(); - case AS_KEYWORD: - case SEMICOLON_TOKEN: - return null; - default: + return switch (peek().kind) { + case DOT_TOKEN -> consume(); + case AS_KEYWORD, SEMICOLON_TOKEN -> null; + default -> { recover(peek(), ParserRuleContext.AFTER_IMPORT_MODULE_NAME); - return parseModuleNameRhs(); - } + yield parseModuleNameRhs(); + } + }; } private boolean isEndOfImportDecl(STToken nextToken) { - switch (nextToken.kind) { - case SEMICOLON_TOKEN: - case PUBLIC_KEYWORD: - case FUNCTION_KEYWORD: - case TYPE_KEYWORD: - case ABSTRACT_KEYWORD: - case CONST_KEYWORD: - case EOF_TOKEN: - case SERVICE_KEYWORD: - case IMPORT_KEYWORD: - case FINAL_KEYWORD: - case TRANSACTIONAL_KEYWORD: - case ISOLATED_KEYWORD: - return true; - default: - return false; - } + return switch (nextToken.kind) { + case SEMICOLON_TOKEN, + PUBLIC_KEYWORD, + FUNCTION_KEYWORD, + TYPE_KEYWORD, + ABSTRACT_KEYWORD, + CONST_KEYWORD, + EOF_TOKEN, + SERVICE_KEYWORD, + IMPORT_KEYWORD, + FINAL_KEYWORD, + TRANSACTIONAL_KEYWORD, + ISOLATED_KEYWORD -> true; + default -> false; + }; } /** @@ -1105,14 +1098,10 @@ private DiagnosticErrorCode getInvalidQualifierError(SyntaxKind qualifierKind) { } boolean isModuleVarDeclQualifier(SyntaxKind tokenKind) { - switch (tokenKind) { - case FINAL_KEYWORD: - case ISOLATED_KEYWORD: - case CONFIGURABLE_KEYWORD: - return true; - default: - return false; - } + return switch (tokenKind) { + case FINAL_KEYWORD, ISOLATED_KEYWORD, CONFIGURABLE_KEYWORD -> true; + default -> false; + }; } private void reportInvalidQualifier(STNode qualifier) { @@ -1158,85 +1147,81 @@ private void reportInvalidAnnotations(STNode annots, List qualifiers, Di private boolean isTopLevelQualifier(SyntaxKind tokenKind) { STToken nextNextToken; - switch (tokenKind) { - case FINAL_KEYWORD: // final-qualifier - case CONFIGURABLE_KEYWORD: // configurable-qualifier - return true; - case READONLY_KEYWORD: // readonly-type-desc, class-def + return switch (tokenKind) { + case FINAL_KEYWORD, // final-qualifier + CONFIGURABLE_KEYWORD // configurable-qualifier + -> true; + // readonly-type-desc, class-def + case READONLY_KEYWORD -> { nextNextToken = getNextNextToken(); // Treat readonly as a top level qualifier only with class definition. - switch (nextNextToken.kind) { - case CLIENT_KEYWORD: - case SERVICE_KEYWORD: - case DISTINCT_KEYWORD: - case ISOLATED_KEYWORD: - case CLASS_KEYWORD: - return true; - default: - return false; - } - case DISTINCT_KEYWORD: // class-def, distinct-type-desc + yield switch (nextNextToken.kind) { + case CLIENT_KEYWORD, + SERVICE_KEYWORD, + DISTINCT_KEYWORD, + ISOLATED_KEYWORD, + CLASS_KEYWORD -> true; + default -> false; + }; + } + // class-def, distinct-type-desc + case DISTINCT_KEYWORD -> { nextNextToken = getNextNextToken(); // distinct-type-desc can occur recursively. // e.g. `distinct distinct student` is a valid type descriptor // Treat distinct as a top level qualifier only with class definition. - switch (nextNextToken.kind) { - case CLIENT_KEYWORD: - case SERVICE_KEYWORD: - case READONLY_KEYWORD: - case ISOLATED_KEYWORD: - case CLASS_KEYWORD: - return true; - default: - return false; - } - default: - return isTypeDescQualifier(tokenKind); - } + yield switch (nextNextToken.kind) { + case CLIENT_KEYWORD, + SERVICE_KEYWORD, + READONLY_KEYWORD, + ISOLATED_KEYWORD, + CLASS_KEYWORD -> true; + default -> false; + }; + } + default -> isTypeDescQualifier(tokenKind); + }; } private boolean isTypeDescQualifier(SyntaxKind tokenKind) { - switch (tokenKind) { - case TRANSACTIONAL_KEYWORD: // func-type-dec, func-def - case ISOLATED_KEYWORD: // func-type-dec, object-type-desc, func-def, class-def, isolated-final-qual - case CLIENT_KEYWORD: // object-type-desc, class-def - case ABSTRACT_KEYWORD: // object-type-desc(outdated) - case SERVICE_KEYWORD: // object-type-desc, object-constructor, class-def, service-decl - return true; - default: - return false; - } + return switch (tokenKind) { + case TRANSACTIONAL_KEYWORD, // func-type-dec, func-def + ISOLATED_KEYWORD, // func-type-dec, object-type-desc, func-def, class-def, isolated-final-qual + CLIENT_KEYWORD, // object-type-desc, class-def + ABSTRACT_KEYWORD, // object-type-desc(outdated) + SERVICE_KEYWORD // object-type-desc, object-constructor, class-def, service-decl + -> true; + default -> false; + }; } private boolean isObjectMemberQualifier(SyntaxKind tokenKind) { - switch (tokenKind) { - case REMOTE_KEYWORD: // method-def, method-decl - case RESOURCE_KEYWORD: // resource-method-def - case FINAL_KEYWORD: // final-qualifier - return true; - default: - return isTypeDescQualifier(tokenKind); - } + return switch (tokenKind) { + case REMOTE_KEYWORD, // method-def, method-decl + RESOURCE_KEYWORD, // resource-method-def + FINAL_KEYWORD // final-qualifier + -> true; + default -> isTypeDescQualifier(tokenKind); + }; } private boolean isExprQualifier(SyntaxKind tokenKind) { - switch (tokenKind) { - case TRANSACTIONAL_KEYWORD: // transactional-expr, object-type, func-type + return switch (tokenKind) { + // transactional-expr, object-type, func-type + case TRANSACTIONAL_KEYWORD -> { STToken nextNextToken = getNextNextToken(); // Treat transactional as a expr level qualifier only with object-type and func-type. - switch (nextNextToken.kind) { - case CLIENT_KEYWORD: - case ABSTRACT_KEYWORD: - case ISOLATED_KEYWORD: - case OBJECT_KEYWORD: - case FUNCTION_KEYWORD: - return true; - default: - return false; - } - default: - return isTypeDescQualifier(tokenKind); - } + yield switch (nextNextToken.kind) { + case CLIENT_KEYWORD, + ABSTRACT_KEYWORD, + ISOLATED_KEYWORD, + OBJECT_KEYWORD, + FUNCTION_KEYWORD -> true; + default -> false; + }; + } + default -> isTypeDescQualifier(tokenKind); + }; } private void parseTopLevelQualifiers(List qualifiers) { @@ -1412,15 +1397,13 @@ private STNode parseFunctionKeywordRhs(STNode metadata, STNode visibilityQualifi } private boolean isBindingPatternsStartToken(SyntaxKind tokenKind) { - switch (tokenKind) { - case IDENTIFIER_TOKEN: - case OPEN_BRACKET_TOKEN: - case OPEN_BRACE_TOKEN: - case ERROR_KEYWORD: - return true; - default: - return false; - } + return switch (tokenKind) { + case IDENTIFIER_TOKEN, + OPEN_BRACKET_TOKEN, + OPEN_BRACE_TOKEN, + ERROR_KEYWORD -> true; + default -> false; + }; } /** @@ -2184,14 +2167,11 @@ private boolean isPossibleServiceDecl(List nodeList) { // Check for [isolated] service match STNode firstElement = nodeList.get(0); - switch (firstElement.kind) { - case SERVICE_KEYWORD: - return true; - case ISOLATED_KEYWORD: - return nodeList.size() > 1 && nodeList.get(1).kind == SyntaxKind.SERVICE_KEYWORD; - default: - return false; - } + return switch (firstElement.kind) { + case SERVICE_KEYWORD -> true; + case ISOLATED_KEYWORD -> nodeList.size() > 1 && nodeList.get(1).kind == SyntaxKind.SERVICE_KEYWORD; + default -> false; + }; } private STNode parseParameterRhs() { @@ -2199,15 +2179,14 @@ private STNode parseParameterRhs() { } private STNode parseParameterRhs(SyntaxKind tokenKind) { - switch (tokenKind) { - case COMMA_TOKEN: - return consume(); - case CLOSE_PAREN_TOKEN: - return null; - default: + return switch (tokenKind) { + case COMMA_TOKEN -> consume(); + case CLOSE_PAREN_TOKEN -> null; + default -> { recover(peek(), ParserRuleContext.PARAM_END); - return parseParameterRhs(); - } + yield parseParameterRhs(); + } + }; } @@ -2452,21 +2431,19 @@ private boolean isSafeMissingReturnsParse() { } private boolean isSafeMissingReturnsParseCtx(ParserRuleContext ctx) { - switch (ctx) { - case TYPE_DESC_IN_ANNOTATION_DECL: - case TYPE_DESC_BEFORE_IDENTIFIER: - case TYPE_DESC_BEFORE_IDENTIFIER_IN_GROUPING_KEY: - case TYPE_DESC_IN_RECORD_FIELD: - case TYPE_DESC_IN_PARAM: - case TYPE_DESC_IN_TYPE_BINDING_PATTERN: - case VAR_DECL_STARTED_WITH_DENTIFIER: - case TYPE_DESC_IN_PATH_PARAM: - case AMBIGUOUS_STMT: - // Contexts that expect an identifier after function type are not safe to parse as a missing return type - return false; - default: - return true; - } + return switch (ctx) { + // Contexts that expect an identifier after function type are not safe to parse as a missing return type + case TYPE_DESC_IN_ANNOTATION_DECL, + TYPE_DESC_BEFORE_IDENTIFIER, + TYPE_DESC_BEFORE_IDENTIFIER_IN_GROUPING_KEY, + TYPE_DESC_IN_RECORD_FIELD, + TYPE_DESC_IN_PARAM, + TYPE_DESC_IN_TYPE_BINDING_PATTERN, + VAR_DECL_STARTED_WITH_DENTIFIER, + TYPE_DESC_IN_PATH_PARAM, + AMBIGUOUS_STMT -> false; + default -> true; + }; } /** @@ -2640,15 +2617,10 @@ private STNode parseComplexTypeDescriptorInternal(STNode typeDesc, ParserRuleCon } private boolean isValidTypeContinuationToken(STToken token) { - switch (token.kind) { - case QUESTION_MARK_TOKEN: - case OPEN_BRACKET_TOKEN: - case PIPE_TOKEN: - case BITWISE_AND_TOKEN: - return true; - default: - return false; - } + return switch (token.kind) { + case QUESTION_MARK_TOKEN, OPEN_BRACKET_TOKEN, PIPE_TOKEN, BITWISE_AND_TOKEN -> true; + default -> false; + }; } private STNode validateForUsageOfVar(STNode typeDesc) { @@ -2761,17 +2733,12 @@ private ParserRuleContext getTypeDescRecoveryCtx(List qualifiers) { } STNode lastQualifier = getLastNodeInList(qualifiers); - switch (lastQualifier.kind) { - case ISOLATED_KEYWORD: - return ParserRuleContext.TYPE_DESC_WITHOUT_ISOLATED; - case TRANSACTIONAL_KEYWORD: - return ParserRuleContext.FUNC_TYPE_DESC; - case SERVICE_KEYWORD: - case CLIENT_KEYWORD: - default: - // We reach here for service and client only. - return ParserRuleContext.OBJECT_TYPE_DESCRIPTOR; - } + return switch (lastQualifier.kind) { + case ISOLATED_KEYWORD -> ParserRuleContext.TYPE_DESC_WITHOUT_ISOLATED; + case TRANSACTIONAL_KEYWORD -> ParserRuleContext.FUNC_TYPE_DESC; + // We reach here for service and client only. + default -> ParserRuleContext.OBJECT_TYPE_DESCRIPTOR; + }; } /** @@ -2781,15 +2748,10 @@ private ParserRuleContext getTypeDescRecoveryCtx(List qualifiers) { * @return true if the given token is a parameterized type keyword. false otherwise */ static boolean isParameterizedTypeToken(SyntaxKind tokenKind) { - switch (tokenKind) { - case TYPEDESC_KEYWORD: - case FUTURE_KEYWORD: - case XML_KEYWORD: - case ERROR_KEYWORD: - return true; - default: - return false; - } + return switch (tokenKind) { + case TYPEDESC_KEYWORD, FUTURE_KEYWORD, XML_KEYWORD, ERROR_KEYWORD -> true; + default -> false; + }; } private STNode parseQualifiedIdentWithTransactionPrefix(ParserRuleContext context) { @@ -2843,27 +2805,31 @@ private STNode parseQualifiedTypeRefOrTypeDesc(List qualifiers, boolean } private STNode parseTypeDescStartWithPredeclPrefix(STToken preDeclaredPrefix, List qualifiers) { - switch (preDeclaredPrefix.kind) { - case MAP_KEYWORD: + return switch (preDeclaredPrefix.kind) { + case MAP_KEYWORD -> { reportInvalidQualifierList(qualifiers); - return parseMapTypeDescriptor(preDeclaredPrefix); - case OBJECT_KEYWORD: + yield parseMapTypeDescriptor(preDeclaredPrefix); + } + case OBJECT_KEYWORD -> { STNode objectTypeQualifiers = createObjectTypeQualNodeList(qualifiers); - return parseObjectTypeDescriptor(preDeclaredPrefix, objectTypeQualifiers); - case STREAM_KEYWORD: + yield parseObjectTypeDescriptor(preDeclaredPrefix, objectTypeQualifiers); + } + case STREAM_KEYWORD -> { reportInvalidQualifierList(qualifiers); - return parseStreamTypeDescriptor(preDeclaredPrefix); - case TABLE_KEYWORD: + yield parseStreamTypeDescriptor(preDeclaredPrefix); + } + case TABLE_KEYWORD -> { reportInvalidQualifierList(qualifiers); - return parseTableTypeDescriptor(preDeclaredPrefix); - default: + yield parseTableTypeDescriptor(preDeclaredPrefix); + } + default -> { if (isParameterizedTypeToken(preDeclaredPrefix.kind)) { reportInvalidQualifierList(qualifiers); - return parseParameterizedTypeDescriptor(preDeclaredPrefix); + yield parseParameterizedTypeDescriptor(preDeclaredPrefix); } - - return createBuiltinSimpleNameReference(preDeclaredPrefix); - } + yield createBuiltinSimpleNameReference(preDeclaredPrefix); + } + }; } private STNode parseQualifiedIdentifierWithPredeclPrefix(STToken preDeclaredPrefix, boolean isInConditionalExpr) { @@ -2959,17 +2925,15 @@ public static STNode createBuiltinSimpleNameReference(STNode token) { */ protected STNode parseFunctionBody() { STToken token = peek(); - switch (token.kind) { - case EQUAL_TOKEN: - return parseExternalFunctionBody(); - case OPEN_BRACE_TOKEN: - return parseFunctionBodyBlock(false); - case RIGHT_DOUBLE_ARROW_TOKEN: - return parseExpressionFuncBody(false, false); - default: + return switch (token.kind) { + case EQUAL_TOKEN -> parseExternalFunctionBody(); + case OPEN_BRACE_TOKEN -> parseFunctionBodyBlock(false); + case RIGHT_DOUBLE_ARROW_TOKEN -> parseExpressionFuncBody(false, false); + default -> { recover(token, ParserRuleContext.FUNC_BODY); - return parseFunctionBody(); - } + yield parseFunctionBody(); + } + }; } /** @@ -3083,12 +3047,7 @@ private boolean isEndOfFuncBodyBlock(SyntaxKind nextTokenKind, boolean isAnonFun } private boolean isEndOfRecordTypeNode(SyntaxKind nextTokenKind) { - switch (nextTokenKind) { - case TYPE_KEYWORD: - case PUBLIC_KEYWORD: - default: - return isEndOfModuleLevelNode(1); - } + return isEndOfModuleLevelNode(1); } private boolean isEndOfObjectTypeNode() { @@ -3096,12 +3055,10 @@ private boolean isEndOfObjectTypeNode() { } private boolean isEndOfStatements() { - switch (peek().kind) { - case RESOURCE_KEYWORD: - return true; - default: - return isEndOfModuleLevelNode(1); - } + return switch (peek().kind) { + case RESOURCE_KEYWORD -> true; + default -> isEndOfModuleLevelNode(1); + }; } private boolean isEndOfModuleLevelNode(int peekIndex) { @@ -3109,31 +3066,28 @@ private boolean isEndOfModuleLevelNode(int peekIndex) { } private boolean isEndOfModuleLevelNode(int peekIndex, boolean isObject) { - switch (peek(peekIndex).kind) { - case EOF_TOKEN: - case CLOSE_BRACE_TOKEN: - case CLOSE_BRACE_PIPE_TOKEN: - case IMPORT_KEYWORD: - case ANNOTATION_KEYWORD: - case LISTENER_KEYWORD: - case CLASS_KEYWORD: - return true; - case SERVICE_KEYWORD: - return isServiceDeclStart(ParserRuleContext.OBJECT_CONSTRUCTOR_MEMBER, 1); - case PUBLIC_KEYWORD: - return !isObject && isEndOfModuleLevelNode(peekIndex + 1, false); - case FUNCTION_KEYWORD: + return switch (peek(peekIndex).kind) { + case EOF_TOKEN, + CLOSE_BRACE_TOKEN, + CLOSE_BRACE_PIPE_TOKEN, + IMPORT_KEYWORD, + ANNOTATION_KEYWORD, + LISTENER_KEYWORD, + CLASS_KEYWORD -> true; + case SERVICE_KEYWORD -> isServiceDeclStart(ParserRuleContext.OBJECT_CONSTRUCTOR_MEMBER, 1); + case PUBLIC_KEYWORD -> !isObject && isEndOfModuleLevelNode(peekIndex + 1, false); + case FUNCTION_KEYWORD -> { if (isObject) { - return false; + yield false; } // if function keyword follows by a identifier treat is as // the function name. Only function def can have func-name - return peek(peekIndex + 1).kind == SyntaxKind.IDENTIFIER_TOKEN && + yield peek(peekIndex + 1).kind == SyntaxKind.IDENTIFIER_TOKEN && peek(peekIndex + 2).kind == SyntaxKind.OPEN_PAREN_TOKEN; - default: - return false; - } + } + default -> false; + }; } /** @@ -3143,21 +3097,19 @@ private boolean isEndOfModuleLevelNode(int peekIndex, boolean isObject) { * @return true if the token represents an end of a parameter. false otherwise */ private boolean isEndOfParameter(SyntaxKind tokenKind) { - switch (tokenKind) { - case CLOSE_PAREN_TOKEN: - case CLOSE_BRACKET_TOKEN: - case SEMICOLON_TOKEN: - case COMMA_TOKEN: - case RETURNS_KEYWORD: - case TYPE_KEYWORD: - case IF_KEYWORD: - case WHILE_KEYWORD: - case DO_KEYWORD: - case AT_TOKEN: - return true; - default: - return isEndOfModuleLevelNode(1); - } + return switch (tokenKind) { + case CLOSE_PAREN_TOKEN, + CLOSE_BRACKET_TOKEN, + SEMICOLON_TOKEN, + COMMA_TOKEN, + RETURNS_KEYWORD, + TYPE_KEYWORD, + IF_KEYWORD, + WHILE_KEYWORD, + DO_KEYWORD, + AT_TOKEN -> true; + default -> isEndOfModuleLevelNode(1); + }; } /** @@ -3167,19 +3119,17 @@ private boolean isEndOfParameter(SyntaxKind tokenKind) { * @return true if the token represents an end of a parameter-list. false otherwise */ private boolean isEndOfParametersList(SyntaxKind tokenKind) { - switch (tokenKind) { - case CLOSE_PAREN_TOKEN: - case SEMICOLON_TOKEN: - case RETURNS_KEYWORD: - case TYPE_KEYWORD: - case IF_KEYWORD: - case WHILE_KEYWORD: - case DO_KEYWORD: - case RIGHT_DOUBLE_ARROW_TOKEN: - return true; - default: - return isEndOfModuleLevelNode(1); - } + return switch (tokenKind) { + case CLOSE_PAREN_TOKEN, + SEMICOLON_TOKEN, + RETURNS_KEYWORD, + TYPE_KEYWORD, + IF_KEYWORD, + WHILE_KEYWORD, + DO_KEYWORD, + RIGHT_DOUBLE_ARROW_TOKEN -> true; + default -> isEndOfModuleLevelNode(1); + }; } /** @@ -3357,35 +3307,33 @@ private STNode parseBinaryOperator() { * @return true if the token kind refers to a binary operator. false otherwise */ private boolean isBinaryOperator(SyntaxKind kind) { - switch (kind) { - case PLUS_TOKEN: - case MINUS_TOKEN: - case SLASH_TOKEN: - case ASTERISK_TOKEN: - case GT_TOKEN: - case LT_TOKEN: - case DOUBLE_EQUAL_TOKEN: - case TRIPPLE_EQUAL_TOKEN: - case LT_EQUAL_TOKEN: - case GT_EQUAL_TOKEN: - case NOT_EQUAL_TOKEN: - case NOT_DOUBLE_EQUAL_TOKEN: - case BITWISE_AND_TOKEN: - case BITWISE_XOR_TOKEN: - case PIPE_TOKEN: - case LOGICAL_AND_TOKEN: - case LOGICAL_OR_TOKEN: - case PERCENT_TOKEN: - case DOUBLE_LT_TOKEN: - case DOUBLE_GT_TOKEN: - case TRIPPLE_GT_TOKEN: - case ELLIPSIS_TOKEN: - case DOUBLE_DOT_LT_TOKEN: - case ELVIS_TOKEN: - return true; - default: - return false; - } + return switch (kind) { + case PLUS_TOKEN, + MINUS_TOKEN, + SLASH_TOKEN, + ASTERISK_TOKEN, + GT_TOKEN, + LT_TOKEN, + DOUBLE_EQUAL_TOKEN, + TRIPPLE_EQUAL_TOKEN, + LT_EQUAL_TOKEN, + GT_EQUAL_TOKEN, + NOT_EQUAL_TOKEN, + NOT_DOUBLE_EQUAL_TOKEN, + BITWISE_AND_TOKEN, + BITWISE_XOR_TOKEN, + PIPE_TOKEN, + LOGICAL_AND_TOKEN, + LOGICAL_OR_TOKEN, + PERCENT_TOKEN, + DOUBLE_LT_TOKEN, + DOUBLE_GT_TOKEN, + TRIPPLE_GT_TOKEN, + ELLIPSIS_TOKEN, + DOUBLE_DOT_LT_TOKEN, + ELVIS_TOKEN -> true; + default -> false; + }; } /** @@ -3395,67 +3343,50 @@ private boolean isBinaryOperator(SyntaxKind kind) { * @return Precedence of the given operator */ private OperatorPrecedence getOpPrecedence(SyntaxKind binaryOpKind) { - switch (binaryOpKind) { - case ASTERISK_TOKEN: // multiplication - case SLASH_TOKEN: // division - case PERCENT_TOKEN: // remainder - return OperatorPrecedence.MULTIPLICATIVE; - case PLUS_TOKEN: - case MINUS_TOKEN: - return OperatorPrecedence.ADDITIVE; - case GT_TOKEN: - case LT_TOKEN: - case GT_EQUAL_TOKEN: - case LT_EQUAL_TOKEN: - case IS_KEYWORD: - case NOT_IS_KEYWORD: - return OperatorPrecedence.BINARY_COMPARE; - case DOT_TOKEN: - case OPEN_BRACKET_TOKEN: - case OPEN_PAREN_TOKEN: - case ANNOT_CHAINING_TOKEN: - case OPTIONAL_CHAINING_TOKEN: - case DOT_LT_TOKEN: - case SLASH_LT_TOKEN: - case DOUBLE_SLASH_DOUBLE_ASTERISK_LT_TOKEN: - case SLASH_ASTERISK_TOKEN: - return OperatorPrecedence.MEMBER_ACCESS; - case DOUBLE_EQUAL_TOKEN: - case TRIPPLE_EQUAL_TOKEN: - case NOT_EQUAL_TOKEN: - case NOT_DOUBLE_EQUAL_TOKEN: - return OperatorPrecedence.EQUALITY; - case BITWISE_AND_TOKEN: - return OperatorPrecedence.BITWISE_AND; - case BITWISE_XOR_TOKEN: - return OperatorPrecedence.BITWISE_XOR; - case PIPE_TOKEN: - return OperatorPrecedence.BITWISE_OR; - case LOGICAL_AND_TOKEN: - return OperatorPrecedence.LOGICAL_AND; - case LOGICAL_OR_TOKEN: - return OperatorPrecedence.LOGICAL_OR; - case RIGHT_ARROW_TOKEN: - return OperatorPrecedence.REMOTE_CALL_ACTION; - case RIGHT_DOUBLE_ARROW_TOKEN: - return OperatorPrecedence.ANON_FUNC_OR_LET; - case SYNC_SEND_TOKEN: - return OperatorPrecedence.ACTION; - case DOUBLE_LT_TOKEN: - case DOUBLE_GT_TOKEN: - case TRIPPLE_GT_TOKEN: - return OperatorPrecedence.SHIFT; - case ELLIPSIS_TOKEN: - case DOUBLE_DOT_LT_TOKEN: - return OperatorPrecedence.RANGE; - case ELVIS_TOKEN: - return OperatorPrecedence.ELVIS_CONDITIONAL; - case QUESTION_MARK_TOKEN: - case COLON_TOKEN: - return OperatorPrecedence.CONDITIONAL; - default: - throw new UnsupportedOperationException("Unsupported binary operator '" + binaryOpKind + "'"); - } + return switch (binaryOpKind) { + case ASTERISK_TOKEN, // multiplication + SLASH_TOKEN, // division + PERCENT_TOKEN // remainder + -> OperatorPrecedence.MULTIPLICATIVE; + case PLUS_TOKEN, + MINUS_TOKEN -> OperatorPrecedence.ADDITIVE; + case GT_TOKEN, + LT_TOKEN, + GT_EQUAL_TOKEN, + LT_EQUAL_TOKEN, + IS_KEYWORD, + NOT_IS_KEYWORD -> OperatorPrecedence.BINARY_COMPARE; + case DOT_TOKEN, + OPEN_BRACKET_TOKEN, + OPEN_PAREN_TOKEN, + ANNOT_CHAINING_TOKEN, + OPTIONAL_CHAINING_TOKEN, + DOT_LT_TOKEN, + SLASH_LT_TOKEN, + DOUBLE_SLASH_DOUBLE_ASTERISK_LT_TOKEN, + SLASH_ASTERISK_TOKEN -> OperatorPrecedence.MEMBER_ACCESS; + case DOUBLE_EQUAL_TOKEN, + TRIPPLE_EQUAL_TOKEN, + NOT_EQUAL_TOKEN, + NOT_DOUBLE_EQUAL_TOKEN -> OperatorPrecedence.EQUALITY; + case BITWISE_AND_TOKEN -> OperatorPrecedence.BITWISE_AND; + case BITWISE_XOR_TOKEN -> OperatorPrecedence.BITWISE_XOR; + case PIPE_TOKEN -> OperatorPrecedence.BITWISE_OR; + case LOGICAL_AND_TOKEN -> OperatorPrecedence.LOGICAL_AND; + case LOGICAL_OR_TOKEN -> OperatorPrecedence.LOGICAL_OR; + case RIGHT_ARROW_TOKEN -> OperatorPrecedence.REMOTE_CALL_ACTION; + case RIGHT_DOUBLE_ARROW_TOKEN -> OperatorPrecedence.ANON_FUNC_OR_LET; + case SYNC_SEND_TOKEN -> OperatorPrecedence.ACTION; + case DOUBLE_LT_TOKEN, + DOUBLE_GT_TOKEN, + TRIPPLE_GT_TOKEN -> OperatorPrecedence.SHIFT; + case ELLIPSIS_TOKEN, + DOUBLE_DOT_LT_TOKEN -> OperatorPrecedence.RANGE; + case ELVIS_TOKEN -> OperatorPrecedence.ELVIS_CONDITIONAL; + case QUESTION_MARK_TOKEN, + COLON_TOKEN -> OperatorPrecedence.CONDITIONAL; + default -> throw new UnsupportedOperationException("Unsupported binary operator '" + binaryOpKind + "'"); + }; } /** @@ -3467,43 +3398,30 @@ private OperatorPrecedence getOpPrecedence(SyntaxKind binaryOpKind) { * @return Kind of the operator to insert */ private SyntaxKind getBinaryOperatorKindToInsert(OperatorPrecedence opPrecedenceLevel) { - switch (opPrecedenceLevel) { - case MULTIPLICATIVE: - return SyntaxKind.ASTERISK_TOKEN; - case DEFAULT: - case UNARY: - case ACTION: - case EXPRESSION_ACTION: - case REMOTE_CALL_ACTION: - case ANON_FUNC_OR_LET: - case QUERY: - case TRAP: - case ADDITIVE: - return SyntaxKind.PLUS_TOKEN; - case SHIFT: - return SyntaxKind.DOUBLE_LT_TOKEN; - case RANGE: - return SyntaxKind.ELLIPSIS_TOKEN; - case BINARY_COMPARE: - return SyntaxKind.LT_TOKEN; - case EQUALITY: - return SyntaxKind.DOUBLE_EQUAL_TOKEN; - case BITWISE_AND: - return SyntaxKind.BITWISE_AND_TOKEN; - case BITWISE_XOR: - return SyntaxKind.BITWISE_XOR_TOKEN; - case BITWISE_OR: - return SyntaxKind.PIPE_TOKEN; - case LOGICAL_AND: - return SyntaxKind.LOGICAL_AND_TOKEN; - case LOGICAL_OR: - return SyntaxKind.LOGICAL_OR_TOKEN; - case ELVIS_CONDITIONAL: - return SyntaxKind.ELVIS_TOKEN; - default: - throw new UnsupportedOperationException( - "Unsupported operator precedence level'" + opPrecedenceLevel + "'"); - } + return switch (opPrecedenceLevel) { + case MULTIPLICATIVE -> SyntaxKind.ASTERISK_TOKEN; + case DEFAULT, + UNARY, + ACTION, + EXPRESSION_ACTION, + REMOTE_CALL_ACTION, + ANON_FUNC_OR_LET, + QUERY, + TRAP, + ADDITIVE -> SyntaxKind.PLUS_TOKEN; + case SHIFT -> SyntaxKind.DOUBLE_LT_TOKEN; + case RANGE -> SyntaxKind.ELLIPSIS_TOKEN; + case BINARY_COMPARE -> SyntaxKind.LT_TOKEN; + case EQUALITY -> SyntaxKind.DOUBLE_EQUAL_TOKEN; + case BITWISE_AND -> SyntaxKind.BITWISE_AND_TOKEN; + case BITWISE_XOR -> SyntaxKind.BITWISE_XOR_TOKEN; + case BITWISE_OR -> SyntaxKind.PIPE_TOKEN; + case LOGICAL_AND -> SyntaxKind.LOGICAL_AND_TOKEN; + case LOGICAL_OR -> SyntaxKind.LOGICAL_OR_TOKEN; + case ELVIS_CONDITIONAL -> SyntaxKind.ELVIS_TOKEN; + default -> throw new UnsupportedOperationException( + "Unsupported operator precedence level'" + opPrecedenceLevel + "'"); + }; } /** *

@@ -3514,43 +3432,30 @@ private SyntaxKind getBinaryOperatorKindToInsert(OperatorPrecedence opPrecedence * @return Context of the missing operator */ private ParserRuleContext getMissingBinaryOperatorContext(OperatorPrecedence opPrecedenceLevel) { - switch (opPrecedenceLevel) { - case MULTIPLICATIVE: - return ParserRuleContext.ASTERISK; - case DEFAULT: - case UNARY: - case ACTION: - case EXPRESSION_ACTION: - case REMOTE_CALL_ACTION: - case ANON_FUNC_OR_LET: - case QUERY: - case TRAP: - case ADDITIVE: - return ParserRuleContext.PLUS_TOKEN; - case SHIFT: - return ParserRuleContext.DOUBLE_LT; - case RANGE: - return ParserRuleContext.ELLIPSIS; - case BINARY_COMPARE: - return ParserRuleContext.LT_TOKEN; - case EQUALITY: - return ParserRuleContext.DOUBLE_EQUAL; - case BITWISE_AND: - return ParserRuleContext.BITWISE_AND_OPERATOR; - case BITWISE_XOR: - return ParserRuleContext.BITWISE_XOR; - case BITWISE_OR: - return ParserRuleContext.PIPE; - case LOGICAL_AND: - return ParserRuleContext.LOGICAL_AND; - case LOGICAL_OR: - return ParserRuleContext.LOGICAL_OR; - case ELVIS_CONDITIONAL: - return ParserRuleContext.ELVIS; - default: - throw new UnsupportedOperationException( - "Unsupported operator precedence level'" + opPrecedenceLevel + "'"); - } + return switch (opPrecedenceLevel) { + case MULTIPLICATIVE -> ParserRuleContext.ASTERISK; + case DEFAULT, + UNARY, + ACTION, + EXPRESSION_ACTION, + REMOTE_CALL_ACTION, + ANON_FUNC_OR_LET, + QUERY, + TRAP, + ADDITIVE -> ParserRuleContext.PLUS_TOKEN; + case SHIFT -> ParserRuleContext.DOUBLE_LT; + case RANGE -> ParserRuleContext.ELLIPSIS; + case BINARY_COMPARE -> ParserRuleContext.LT_TOKEN; + case EQUALITY -> ParserRuleContext.DOUBLE_EQUAL; + case BITWISE_AND -> ParserRuleContext.BITWISE_AND_OPERATOR; + case BITWISE_XOR -> ParserRuleContext.BITWISE_XOR; + case BITWISE_OR -> ParserRuleContext.PIPE; + case LOGICAL_AND -> ParserRuleContext.LOGICAL_AND; + case LOGICAL_OR -> ParserRuleContext.LOGICAL_OR; + case ELVIS_CONDITIONAL -> ParserRuleContext.ELVIS; + default -> throw new UnsupportedOperationException( + "Unsupported operator precedence level'" + opPrecedenceLevel + "'"); + }; } /** @@ -3604,33 +3509,24 @@ private STNode parseClassDefinition(STNode metadata, STNode qualifier, List true; + default -> isObjectNetworkQual(tokenKind); + }; } private boolean isObjectTypeQual(SyntaxKind tokenKind) { - switch (tokenKind) { - case ISOLATED_KEYWORD: - return true; - default: - return isObjectNetworkQual(tokenKind); - } + return switch (tokenKind) { + case ISOLATED_KEYWORD -> true; + default -> isObjectNetworkQual(tokenKind); + }; } private boolean isObjectNetworkQual(SyntaxKind tokenKind) { - switch (tokenKind) { - case SERVICE_KEYWORD: - case CLIENT_KEYWORD: - return true; - default: - return false; - } + return switch (tokenKind) { + case SERVICE_KEYWORD, CLIENT_KEYWORD -> true; + default -> false; + }; } /** @@ -3868,15 +3764,14 @@ private STNode parseRecordTypeDescriptor() { */ private STNode parseRecordBodyStartDelimiter() { STToken nextToken = peek(); - switch (nextToken.kind) { - case OPEN_BRACE_PIPE_TOKEN: - return parseClosedRecordBodyStart(); - case OPEN_BRACE_TOKEN: - return parseOpenBrace(); - default: + return switch (nextToken.kind) { + case OPEN_BRACE_PIPE_TOKEN -> parseClosedRecordBodyStart(); + case OPEN_BRACE_TOKEN -> parseOpenBrace(); + default -> { recover(nextToken, ParserRuleContext.RECORD_BODY_START); - return parseRecordBodyStartDelimiter(); - } + yield parseRecordBodyStartDelimiter(); + } + }; } /** @@ -4337,16 +4232,17 @@ protected STNode parseStatement() { * @return true if the statement is not valid false otherwise */ boolean validateStatement(STNode statement) { - switch (statement.kind) { - case LOCAL_TYPE_DEFINITION_STATEMENT: + return switch (statement.kind) { + case LOCAL_TYPE_DEFINITION_STATEMENT -> { addInvalidNodeToNextToken(statement, DiagnosticErrorCode.ERROR_LOCAL_TYPE_DEFINITION_NOT_ALLOWED); - return true; - case CONST_DECLARATION: + yield true; + } + case CONST_DECLARATION -> { addInvalidNodeToNextToken(statement, DiagnosticErrorCode.ERROR_LOCAL_CONST_DECL_NOT_ALLOWED); - return true; - default: - return false; - } + yield true; + } + default -> false; + }; } private STNode getAnnotations(STNode nullbaleAnnot) { @@ -4850,17 +4746,12 @@ private STNode modifyTypedBindingPatternWithIsolatedQualifier(STNode typedBindin STTypedBindingPatternNode typedBindingPatternNode = (STTypedBindingPatternNode) typedBindingPattern; STNode typeDescriptor = typedBindingPatternNode.typeDescriptor; STNode bindingPattern = typedBindingPatternNode.bindingPattern; - switch (typeDescriptor.kind) { - case OBJECT_TYPE_DESC: - typeDescriptor = modifyObjectTypeDescWithALeadingQualifier(typeDescriptor, isolatedQualifier); - break; - case FUNCTION_TYPE_DESC: - typeDescriptor = modifyFuncTypeDescWithALeadingQualifier(typeDescriptor, isolatedQualifier); - break; - default: - typeDescriptor = SyntaxErrors.cloneWithLeadingInvalidNodeMinutiae(typeDescriptor, isolatedQualifier, - DiagnosticErrorCode.ERROR_QUALIFIER_NOT_ALLOWED, ((STToken) isolatedQualifier).text()); - } + typeDescriptor = switch (typeDescriptor.kind) { + case OBJECT_TYPE_DESC -> modifyObjectTypeDescWithALeadingQualifier(typeDescriptor, isolatedQualifier); + case FUNCTION_TYPE_DESC -> modifyFuncTypeDescWithALeadingQualifier(typeDescriptor, isolatedQualifier); + default -> SyntaxErrors.cloneWithLeadingInvalidNodeMinutiae(typeDescriptor, isolatedQualifier, + DiagnosticErrorCode.ERROR_QUALIFIER_NOT_ALLOWED, ((STToken) isolatedQualifier).text()); + }; return STNodeFactory.createTypedBindingPatternNode(typeDescriptor, bindingPattern); } @@ -4994,37 +4885,28 @@ private STNode parseExpression(boolean isRhsExpr) { } private boolean isValidLVExpr(STNode expression) { - switch (expression.kind) { - case SIMPLE_NAME_REFERENCE: - case QUALIFIED_NAME_REFERENCE: - case LIST_BINDING_PATTERN: - case MAPPING_BINDING_PATTERN: - case ERROR_BINDING_PATTERN: - case WILDCARD_BINDING_PATTERN: - return true; - case FIELD_ACCESS: - return isValidLVMemberExpr(((STFieldAccessExpressionNode) expression).expression); - case INDEXED_EXPRESSION: - return isValidLVMemberExpr(((STIndexedExpressionNode) expression).containerExpression); - default: - return (expression instanceof STMissingToken); - } + return switch (expression.kind) { + case SIMPLE_NAME_REFERENCE, + QUALIFIED_NAME_REFERENCE, + LIST_BINDING_PATTERN, + MAPPING_BINDING_PATTERN, + ERROR_BINDING_PATTERN, + WILDCARD_BINDING_PATTERN -> true; + case FIELD_ACCESS -> isValidLVMemberExpr(((STFieldAccessExpressionNode) expression).expression); + case INDEXED_EXPRESSION -> isValidLVMemberExpr(((STIndexedExpressionNode) expression).containerExpression); + default -> (expression instanceof STMissingToken); + }; } private boolean isValidLVMemberExpr(STNode expression) { - switch (expression.kind) { - case SIMPLE_NAME_REFERENCE: - case QUALIFIED_NAME_REFERENCE: - return true; - case FIELD_ACCESS: - return isValidLVMemberExpr(((STFieldAccessExpressionNode) expression).expression); - case INDEXED_EXPRESSION: - return isValidLVMemberExpr(((STIndexedExpressionNode) expression).containerExpression); - case BRACED_EXPRESSION: - return isValidLVMemberExpr(((STBracedExpressionNode) expression).expression); - default: - return (expression instanceof STMissingToken); - } + return switch (expression.kind) { + case SIMPLE_NAME_REFERENCE, + QUALIFIED_NAME_REFERENCE -> true; + case FIELD_ACCESS -> isValidLVMemberExpr(((STFieldAccessExpressionNode) expression).expression); + case INDEXED_EXPRESSION -> isValidLVMemberExpr(((STIndexedExpressionNode) expression).containerExpression); + case BRACED_EXPRESSION -> isValidLVMemberExpr(((STBracedExpressionNode) expression).expression); + default -> (expression instanceof STMissingToken); + }; } /** @@ -5266,70 +5148,66 @@ private void validateExprAnnotsAndQualifiers(STToken nextToken, STNode annots, L } private boolean isAnnotAllowedExprStart(STToken nextToken) { - switch (nextToken.kind) { - case START_KEYWORD: - case FUNCTION_KEYWORD: - case OBJECT_KEYWORD: - return true; - default: - return false; - } + return switch (nextToken.kind) { + case START_KEYWORD, FUNCTION_KEYWORD, OBJECT_KEYWORD -> true; + default -> false; + }; } private boolean isValidExprStart(SyntaxKind tokenKind) { - switch (tokenKind) { - case DECIMAL_INTEGER_LITERAL_TOKEN: - case HEX_INTEGER_LITERAL_TOKEN: - case STRING_LITERAL_TOKEN: - case NULL_KEYWORD: - case TRUE_KEYWORD: - case FALSE_KEYWORD: - case DECIMAL_FLOATING_POINT_LITERAL_TOKEN: - case HEX_FLOATING_POINT_LITERAL_TOKEN: - case IDENTIFIER_TOKEN: - case OPEN_PAREN_TOKEN: - case CHECK_KEYWORD: - case CHECKPANIC_KEYWORD: - case OPEN_BRACE_TOKEN: - case TYPEOF_KEYWORD: - case PLUS_TOKEN: - case MINUS_TOKEN: - case NEGATION_TOKEN: - case EXCLAMATION_MARK_TOKEN: - case TRAP_KEYWORD: - case OPEN_BRACKET_TOKEN: - case LT_TOKEN: - case TABLE_KEYWORD: - case STREAM_KEYWORD: - case FROM_KEYWORD: - case ERROR_KEYWORD: - case LET_KEYWORD: - case BACKTICK_TOKEN: - case XML_KEYWORD: - case RE_KEYWORD: - case STRING_KEYWORD: - case FUNCTION_KEYWORD: - case AT_TOKEN: - case NEW_KEYWORD: - case START_KEYWORD: - case FLUSH_KEYWORD: - case LEFT_ARROW_TOKEN: - case WAIT_KEYWORD: - case COMMIT_KEYWORD: - case SERVICE_KEYWORD: - case BASE16_KEYWORD: - case BASE64_KEYWORD: - case ISOLATED_KEYWORD: - case TRANSACTIONAL_KEYWORD: - case CLIENT_KEYWORD: - case OBJECT_KEYWORD: - return true; - default: + return switch (tokenKind) { + case DECIMAL_INTEGER_LITERAL_TOKEN, + HEX_INTEGER_LITERAL_TOKEN, + STRING_LITERAL_TOKEN, + NULL_KEYWORD, + TRUE_KEYWORD, + FALSE_KEYWORD, + DECIMAL_FLOATING_POINT_LITERAL_TOKEN, + HEX_FLOATING_POINT_LITERAL_TOKEN, + IDENTIFIER_TOKEN, + OPEN_PAREN_TOKEN, + CHECK_KEYWORD, + CHECKPANIC_KEYWORD, + OPEN_BRACE_TOKEN, + TYPEOF_KEYWORD, + PLUS_TOKEN, + MINUS_TOKEN, + NEGATION_TOKEN, + EXCLAMATION_MARK_TOKEN, + TRAP_KEYWORD, + OPEN_BRACKET_TOKEN, + LT_TOKEN, + TABLE_KEYWORD, + STREAM_KEYWORD, + FROM_KEYWORD, + ERROR_KEYWORD, + LET_KEYWORD, + BACKTICK_TOKEN, + XML_KEYWORD, + RE_KEYWORD, + STRING_KEYWORD, + FUNCTION_KEYWORD, + AT_TOKEN, + NEW_KEYWORD, + START_KEYWORD, + FLUSH_KEYWORD, + LEFT_ARROW_TOKEN, + WAIT_KEYWORD, + COMMIT_KEYWORD, + SERVICE_KEYWORD, + BASE16_KEYWORD, + BASE64_KEYWORD, + ISOLATED_KEYWORD, + TRANSACTIONAL_KEYWORD, + CLIENT_KEYWORD, + OBJECT_KEYWORD -> true; + default -> { if (isPredeclaredPrefix(tokenKind)) { - return true; + yield true; } - return isSimpleTypeInExpression(tokenKind); - } + yield isSimpleTypeInExpression(tokenKind); + } + }; } /** @@ -5762,32 +5640,29 @@ private boolean hasLeadingMinutiae(STNode node) { } private boolean isValidExprRhsStart(SyntaxKind tokenKind, SyntaxKind precedingNodeKind) { - switch (tokenKind) { - case OPEN_PAREN_TOKEN: - // Only an identifier or a qualified identifier is followed by a function call. - return precedingNodeKind == SyntaxKind.QUALIFIED_NAME_REFERENCE || - precedingNodeKind == SyntaxKind.SIMPLE_NAME_REFERENCE; - case DOT_TOKEN: - case OPEN_BRACKET_TOKEN: - case IS_KEYWORD: - case RIGHT_ARROW_TOKEN: - case RIGHT_DOUBLE_ARROW_TOKEN: - case SYNC_SEND_TOKEN: - case ANNOT_CHAINING_TOKEN: - case OPTIONAL_CHAINING_TOKEN: - case COLON_TOKEN: - case DOT_LT_TOKEN: - case SLASH_LT_TOKEN: - case DOUBLE_SLASH_DOUBLE_ASTERISK_LT_TOKEN: - case SLASH_ASTERISK_TOKEN: - case NOT_IS_KEYWORD: - return true; - case QUESTION_MARK_TOKEN: - // TODO : Should fix properly #33259 - return getNextNextToken().kind != SyntaxKind.EQUAL_TOKEN && peek(3).kind != SyntaxKind.EQUAL_TOKEN; - default: - return isBinaryOperator(tokenKind); - } + return switch (tokenKind) { + // Only an identifier or a qualified identifier is followed by a function call. + case OPEN_PAREN_TOKEN -> precedingNodeKind == SyntaxKind.QUALIFIED_NAME_REFERENCE || + precedingNodeKind == SyntaxKind.SIMPLE_NAME_REFERENCE; + case DOT_TOKEN, + OPEN_BRACKET_TOKEN, + IS_KEYWORD, + RIGHT_ARROW_TOKEN, + RIGHT_DOUBLE_ARROW_TOKEN, + SYNC_SEND_TOKEN, + ANNOT_CHAINING_TOKEN, + OPTIONAL_CHAINING_TOKEN, + COLON_TOKEN, + DOT_LT_TOKEN, + SLASH_LT_TOKEN, + DOUBLE_SLASH_DOUBLE_ASTERISK_LT_TOKEN, + SLASH_ASTERISK_TOKEN, + NOT_IS_KEYWORD -> true; + // TODO : Should fix properly #33259 + case QUESTION_MARK_TOKEN -> + getNextNextToken().kind != SyntaxKind.EQUAL_TOKEN && peek(3).kind != SyntaxKind.EQUAL_TOKEN; + default -> isBinaryOperator(tokenKind); + }; } /** @@ -5854,15 +5729,14 @@ private STNode parseKeyExpr(boolean isRhsExpr) { } private STNode parseMemberAccessKeyExprEnd() { - switch (peek().kind) { - case COMMA_TOKEN: - return parseComma(); - case CLOSE_BRACKET_TOKEN: - return null; - default: + return switch (peek().kind) { + case COMMA_TOKEN -> parseComma(); + case CLOSE_BRACKET_TOKEN -> null; + default -> { recover(peek(), ParserRuleContext.MEMBER_ACCESS_KEY_EXPR_END); - return parseMemberAccessKeyExprEnd(); - } + yield parseMemberAccessKeyExprEnd(); + } + }; } /** @@ -5995,24 +5869,22 @@ private STNode parseBracedExprOrAnonFuncParamRhs(STNode openParen, STNode expr, * @return true if the node is an action node. false otherwise */ private boolean isAction(STNode node) { - switch (node.kind) { - case REMOTE_METHOD_CALL_ACTION: - case BRACED_ACTION: - case CHECK_ACTION: - case START_ACTION: - case TRAP_ACTION: - case FLUSH_ACTION: - case ASYNC_SEND_ACTION: - case SYNC_SEND_ACTION: - case RECEIVE_ACTION: - case WAIT_ACTION: - case QUERY_ACTION: - case COMMIT_ACTION: - case CLIENT_RESOURCE_ACCESS_ACTION: - return true; - default: - return false; - } + return switch (node.kind) { + case REMOTE_METHOD_CALL_ACTION, + BRACED_ACTION, + CHECK_ACTION, + START_ACTION, + TRAP_ACTION, + FLUSH_ACTION, + ASYNC_SEND_ACTION, + SYNC_SEND_ACTION, + RECEIVE_ACTION, + WAIT_ACTION, + QUERY_ACTION, + COMMIT_ACTION, + CLIENT_RESOURCE_ACCESS_ACTION -> true; + default -> false; + }; } /** @@ -6034,48 +5906,44 @@ private boolean isEndOfActionOrExpression(STToken nextToken, boolean isRhsExpr, } } - switch (tokenKind) { - case EOF_TOKEN: - case CLOSE_BRACE_TOKEN: - case OPEN_BRACE_TOKEN: - case CLOSE_PAREN_TOKEN: - case CLOSE_BRACKET_TOKEN: - case SEMICOLON_TOKEN: - case COMMA_TOKEN: - case PUBLIC_KEYWORD: - case CONST_KEYWORD: - case LISTENER_KEYWORD: - case RESOURCE_KEYWORD: - case EQUAL_TOKEN: - case DOCUMENTATION_STRING: - case AT_TOKEN: - case AS_KEYWORD: - case IN_KEYWORD: - case FROM_KEYWORD: - case WHERE_KEYWORD: - case LET_KEYWORD: - case SELECT_KEYWORD: - case DO_KEYWORD: - case COLON_TOKEN: - case ON_KEYWORD: - case CONFLICT_KEYWORD: - case LIMIT_KEYWORD: - case JOIN_KEYWORD: - case OUTER_KEYWORD: - case ORDER_KEYWORD: - case BY_KEYWORD: - case ASCENDING_KEYWORD: - case DESCENDING_KEYWORD: - case EQUALS_KEYWORD: - case TYPE_KEYWORD: - return true; - case RIGHT_DOUBLE_ARROW_TOKEN: - return isInMatchGuard; - case IDENTIFIER_TOKEN: - return isGroupOrCollectKeyword(nextToken); - default: - return isSimpleType(tokenKind); - } + return switch (tokenKind) { + case EOF_TOKEN, + CLOSE_BRACE_TOKEN, + OPEN_BRACE_TOKEN, + CLOSE_PAREN_TOKEN, + CLOSE_BRACKET_TOKEN, + SEMICOLON_TOKEN, + COMMA_TOKEN, + PUBLIC_KEYWORD, + CONST_KEYWORD, + LISTENER_KEYWORD, + RESOURCE_KEYWORD, + EQUAL_TOKEN, + DOCUMENTATION_STRING, + AT_TOKEN, + AS_KEYWORD, + IN_KEYWORD, + FROM_KEYWORD, + WHERE_KEYWORD, + LET_KEYWORD, + SELECT_KEYWORD, + DO_KEYWORD, + COLON_TOKEN, + ON_KEYWORD, + CONFLICT_KEYWORD, + LIMIT_KEYWORD, + JOIN_KEYWORD, + OUTER_KEYWORD, + ORDER_KEYWORD, + BY_KEYWORD, + ASCENDING_KEYWORD, + DESCENDING_KEYWORD, + EQUALS_KEYWORD, + TYPE_KEYWORD -> true; + case RIGHT_DOUBLE_ARROW_TOKEN -> isInMatchGuard; + case IDENTIFIER_TOKEN -> isGroupOrCollectKeyword(nextToken); + default -> isSimpleType(tokenKind); + }; } /** @@ -6090,30 +5958,18 @@ private STNode parseBasicLiteral() { } private STNode parseBasicLiteral(STNode literalToken) { - SyntaxKind nodeKind; - switch (literalToken.kind) { - case NULL_KEYWORD: - nodeKind = SyntaxKind.NULL_LITERAL; - break; - case TRUE_KEYWORD: - case FALSE_KEYWORD: - nodeKind = SyntaxKind.BOOLEAN_LITERAL; - break; - case DECIMAL_INTEGER_LITERAL_TOKEN: - case DECIMAL_FLOATING_POINT_LITERAL_TOKEN: - case HEX_INTEGER_LITERAL_TOKEN: - case HEX_FLOATING_POINT_LITERAL_TOKEN: - nodeKind = SyntaxKind.NUMERIC_LITERAL; - break; - case STRING_LITERAL_TOKEN: - nodeKind = SyntaxKind.STRING_LITERAL; - break; - case ASTERISK_TOKEN: - nodeKind = SyntaxKind.ASTERISK_LITERAL; - break; - default: - nodeKind = literalToken.kind; - } + SyntaxKind nodeKind = switch (literalToken.kind) { + case NULL_KEYWORD -> SyntaxKind.NULL_LITERAL; + case TRUE_KEYWORD, + FALSE_KEYWORD -> SyntaxKind.BOOLEAN_LITERAL; + case DECIMAL_INTEGER_LITERAL_TOKEN, + DECIMAL_FLOATING_POINT_LITERAL_TOKEN, + HEX_INTEGER_LITERAL_TOKEN, + HEX_FLOATING_POINT_LITERAL_TOKEN -> SyntaxKind.NUMERIC_LITERAL; + case STRING_LITERAL_TOKEN -> SyntaxKind.STRING_LITERAL; + case ASTERISK_TOKEN -> SyntaxKind.ASTERISK_LITERAL; + default -> literalToken.kind; + }; return STNodeFactory.createBasicLiteralNode(nodeKind, literalToken); } @@ -6347,16 +6203,15 @@ private DiagnosticErrorCode validateArgumentOrder(SyntaxKind prevArgKind, Syntax } private STNode parseArgEnd() { - switch (peek().kind) { - case COMMA_TOKEN: - return parseComma(); - case CLOSE_PAREN_TOKEN: - // null marks the end of args - return null; - default: + return switch (peek().kind) { + case COMMA_TOKEN -> parseComma(); + // null marks the end of args + case CLOSE_PAREN_TOKEN -> null; + default -> { recover(peek(), ParserRuleContext.ARG_END); - return parseArgEnd(); - } + yield parseArgEnd(); + } + }; } /** @@ -6683,28 +6538,24 @@ private STNode parseObjectMemberWithoutMeta(STNode metadata, List qualif */ private boolean isObjectFieldStart() { STToken nextNextToken = getNextNextToken(); - switch (nextNextToken.kind) { - case ERROR_KEYWORD: // error-binding-pattern not allowed in fields - case OPEN_BRACE_TOKEN: // mapping-binding-pattern not allowed in fields - return false; - case CLOSE_BRACE_TOKEN: - return true; - default: - return isModuleVarDeclStart(1); - } + return switch (nextNextToken.kind) { + case ERROR_KEYWORD, // error-binding-pattern not allowed in fields + OPEN_BRACE_TOKEN // mapping-binding-pattern not allowed in fields + -> false; + case CLOSE_BRACE_TOKEN -> true; + default -> isModuleVarDeclStart(1); + }; } private boolean isObjectMethodStart(STToken token) { - switch (token.kind) { - case FUNCTION_KEYWORD: - case REMOTE_KEYWORD: - case RESOURCE_KEYWORD: - case ISOLATED_KEYWORD: - case TRANSACTIONAL_KEYWORD: - return true; - default: - return false; - } + return switch (token.kind) { + case FUNCTION_KEYWORD, + REMOTE_KEYWORD, + RESOURCE_KEYWORD, + ISOLATED_KEYWORD, + TRANSACTIONAL_KEYWORD -> true; + default -> false; + }; } /** @@ -6893,13 +6744,10 @@ private STNode parseRelativeResourcePath() { } private boolean isEndRelativeResourcePath(SyntaxKind tokenKind) { - switch (tokenKind) { - case EOF_TOKEN: - case OPEN_PAREN_TOKEN: - return true; - default: - return false; - } + return switch (tokenKind) { + case EOF_TOKEN, OPEN_PAREN_TOKEN -> true; + default -> false; + }; } private STNode createResourcePathNodeList(List pathElementList) { @@ -6942,22 +6790,25 @@ private STNode createResourcePathNodeList(List pathElementList) { */ private STNode parseResourcePathSegment(boolean isFirstSegment) { STToken nextToken = peek(); - switch (nextToken.kind) { - case IDENTIFIER_TOKEN: + return switch (nextToken.kind) { + case IDENTIFIER_TOKEN -> { if (isFirstSegment && nextToken.isMissing() && isInvalidNodeStackEmpty() && getNextNextToken().kind == SyntaxKind.SLASH_TOKEN) { // special case `[MISSING]/` to improve the error message for `/hello` removeInsertedToken(); // to ignore current missing identifier diagnostic - return SyntaxErrors.createMissingTokenWithDiagnostics(SyntaxKind.IDENTIFIER_TOKEN, + yield SyntaxErrors.createMissingTokenWithDiagnostics(SyntaxKind.IDENTIFIER_TOKEN, DiagnosticErrorCode.ERROR_RESOURCE_PATH_CANNOT_BEGIN_WITH_SLASH); } - return consume(); - case OPEN_BRACKET_TOKEN: - return parseResourcePathParameter(); - default: + // special case `[MISSING]/` to improve the error message for `/hello` + // to ignore current missing identifier diagnostic + yield consume(); + } + case OPEN_BRACKET_TOKEN -> parseResourcePathParameter(); + default -> { recover(nextToken, ParserRuleContext.RESOURCE_PATH_SEGMENT); - return parseResourcePathSegment(isFirstSegment); - } + yield parseResourcePathSegment(isFirstSegment); + } + }; } /** @@ -6983,29 +6834,26 @@ private STNode parseResourcePathParameter() { private STNode parseOptionalPathParamName() { STToken nextToken = peek(); - switch (nextToken.kind) { - case IDENTIFIER_TOKEN: - return consume(); - case CLOSE_BRACKET_TOKEN: - return STNodeFactory.createEmptyNode(); - default: + return switch (nextToken.kind) { + case IDENTIFIER_TOKEN -> consume(); + case CLOSE_BRACKET_TOKEN -> STNodeFactory.createEmptyNode(); + default -> { recover(nextToken, ParserRuleContext.OPTIONAL_PATH_PARAM_NAME); - return parseOptionalPathParamName(); - } + yield parseOptionalPathParamName(); + } + }; } private STNode parseOptionalEllipsis() { STToken nextToken = peek(); - switch (nextToken.kind) { - case ELLIPSIS_TOKEN: - return consume(); - case IDENTIFIER_TOKEN: - case CLOSE_BRACKET_TOKEN: - return STNodeFactory.createEmptyNode(); - default: + return switch (nextToken.kind) { + case ELLIPSIS_TOKEN -> consume(); + case IDENTIFIER_TOKEN, CLOSE_BRACKET_TOKEN -> STNodeFactory.createEmptyNode(); + default -> { recover(nextToken, ParserRuleContext.PATH_PARAM_ELLIPSIS); - return parseOptionalEllipsis(); - } + yield parseOptionalEllipsis(); + } + }; } /** @@ -7015,17 +6863,15 @@ private STNode parseOptionalEllipsis() { */ private STNode parseRelativeResourcePathEnd() { STToken nextToken = peek(); - switch (nextToken.kind) { - case OPEN_PAREN_TOKEN: - case EOF_TOKEN: - // null represents the end of resource path. - return null; - case SLASH_TOKEN: - return consume(); - default: + return switch (nextToken.kind) { + // null represents the end of resource path. + case OPEN_PAREN_TOKEN, EOF_TOKEN -> null; + case SLASH_TOKEN -> consume(); + default -> { recover(nextToken, ParserRuleContext.RELATIVE_RESOURCE_PATH_END); - return parseRelativeResourcePathEnd(); - } + yield parseRelativeResourcePathEnd(); + } + }; } /** @@ -7120,15 +6966,14 @@ private STNode parseElseBlock() { */ private STNode parseElseBody() { STToken nextToken = peek(); - switch (nextToken.kind) { - case IF_KEYWORD: - return parseIfElseBlock(); - case OPEN_BRACE_TOKEN: - return parseBlockNode(); - default: + return switch (nextToken.kind) { + case IF_KEYWORD -> parseIfElseBlock(); + case OPEN_BRACE_TOKEN -> parseBlockNode(); + default -> { recover(peek(), ParserRuleContext.ELSE_BODY); - return parseElseBody(); - } + yield parseElseBody(); + } + }; } /** @@ -7385,14 +7230,10 @@ private STNode parseBreakKeyword() { private STNode parseReturnStatementRhs(STNode returnKeyword) { STNode expr; STToken token = peek(); - switch (token.kind) { - case SEMICOLON_TOKEN: - expr = STNodeFactory.createEmptyNode(); - break; - default: - expr = parseActionOrExpression(); - break; - } + expr = switch (token.kind) { + case SEMICOLON_TOKEN -> STNodeFactory.createEmptyNode(); + default -> parseActionOrExpression(); + }; STNode semicolon = parseSemicolon(); return STNodeFactory.createReturnStatementNode(returnKeyword, expr, semicolon); @@ -7457,41 +7298,37 @@ private STNode parseMappingConstructorFields(List fields) { } private STNode parseMappingFieldEnd() { - switch (peek().kind) { - case COMMA_TOKEN: - return parseComma(); - case CLOSE_BRACE_TOKEN: - return null; - default: + return switch (peek().kind) { + case COMMA_TOKEN -> parseComma(); + case CLOSE_BRACE_TOKEN -> null; + default -> { recover(peek(), ParserRuleContext.MAPPING_FIELD_END); - return parseMappingFieldEnd(); - } + yield parseMappingFieldEnd(); + } + }; } private boolean isEndOfMappingConstructor(SyntaxKind tokenKind) { - switch (tokenKind) { - case IDENTIFIER_TOKEN: - case READONLY_KEYWORD: - return false; - case EOF_TOKEN: - case DOCUMENTATION_STRING: - case AT_TOKEN: - case CLOSE_BRACE_TOKEN: - case SEMICOLON_TOKEN: - case PUBLIC_KEYWORD: - case PRIVATE_KEYWORD: - case FUNCTION_KEYWORD: - case RETURNS_KEYWORD: - case SERVICE_KEYWORD: - case TYPE_KEYWORD: - case LISTENER_KEYWORD: - case CONST_KEYWORD: - case FINAL_KEYWORD: - case RESOURCE_KEYWORD: - return true; - default: - return isSimpleType(tokenKind); - } + return switch (tokenKind) { + case IDENTIFIER_TOKEN, + READONLY_KEYWORD -> false; + case EOF_TOKEN, + DOCUMENTATION_STRING, + AT_TOKEN, + CLOSE_BRACE_TOKEN, + SEMICOLON_TOKEN, + PUBLIC_KEYWORD, + PRIVATE_KEYWORD, + FUNCTION_KEYWORD, + RETURNS_KEYWORD, + SERVICE_KEYWORD, + TYPE_KEYWORD, + LISTENER_KEYWORD, + CONST_KEYWORD, + FINAL_KEYWORD, + RESOURCE_KEYWORD -> true; + default -> isSimpleType(tokenKind); + }; } /** @@ -7533,15 +7370,14 @@ private STNode parseMappingField(ParserRuleContext fieldContext) { private STNode parseSpecificField(STNode readonlyKeyword) { STToken nextToken = peek(); - switch (nextToken.kind) { - case STRING_LITERAL_TOKEN: - return parseQualifiedSpecificField(readonlyKeyword); - case IDENTIFIER_TOKEN: - return parseSpecificFieldWithOptionalValue(readonlyKeyword); - default: + return switch (nextToken.kind) { + case STRING_LITERAL_TOKEN -> parseQualifiedSpecificField(readonlyKeyword); + case IDENTIFIER_TOKEN -> parseSpecificFieldWithOptionalValue(readonlyKeyword); + default -> { recover(peek(), ParserRuleContext.SPECIFIC_FIELD); - return parseSpecificField(readonlyKeyword); - } + yield parseSpecificField(readonlyKeyword); + } + }; } private STNode parseQualifiedSpecificField(STNode readonlyKeyword) { @@ -7950,13 +7786,10 @@ private STNode parseAbsoluteResourcePath() { } private boolean isEndAbsoluteResourcePath(SyntaxKind tokenKind) { - switch (tokenKind) { - case EOF_TOKEN: - case ON_KEYWORD: - return true; - default: - return false; - } + return switch (tokenKind) { + case EOF_TOKEN, ON_KEYWORD -> true; + default -> false; + }; } /** @@ -8010,21 +7843,19 @@ private STNode parseServiceKeyword() { * @return true if the token kind refers to a binary operator. false otherwise */ static boolean isCompoundBinaryOperator(SyntaxKind tokenKind) { - switch (tokenKind) { - case PLUS_TOKEN: - case MINUS_TOKEN: - case SLASH_TOKEN: - case ASTERISK_TOKEN: - case BITWISE_AND_TOKEN: - case BITWISE_XOR_TOKEN: - case PIPE_TOKEN: - case DOUBLE_LT_TOKEN: - case DOUBLE_GT_TOKEN: - case TRIPPLE_GT_TOKEN: - return true; - default: - return false; - } + return switch (tokenKind) { + case PLUS_TOKEN, + MINUS_TOKEN, + SLASH_TOKEN, + ASTERISK_TOKEN, + BITWISE_AND_TOKEN, + BITWISE_XOR_TOKEN, + PIPE_TOKEN, + DOUBLE_LT_TOKEN, + DOUBLE_GT_TOKEN, + TRIPPLE_GT_TOKEN -> true; + default -> false; + }; } private boolean isCompoundAssignment(SyntaxKind tokenKind) { @@ -8084,26 +7915,23 @@ private STNode parseListeners() { } private boolean isEndOfListeners(SyntaxKind tokenKind) { - switch (tokenKind) { - case OPEN_BRACE_TOKEN: - case EOF_TOKEN: - return true; - default: - return false; - } + return switch (tokenKind) { + case OPEN_BRACE_TOKEN, + EOF_TOKEN -> true; + default -> false; + }; } private STNode parseListenersMemberEnd() { STToken nextToken = peek(); - switch (nextToken.kind) { - case COMMA_TOKEN: - return parseComma(); - case OPEN_BRACE_TOKEN: - return null; - default: + return switch (nextToken.kind) { + case COMMA_TOKEN -> parseComma(); + case OPEN_BRACE_TOKEN -> null; + default -> { recover(nextToken, ParserRuleContext.LISTENERS_LIST_END); - return parseListenersMemberEnd(); - } + yield parseListenersMemberEnd(); + } + }; } /** @@ -8118,28 +7946,29 @@ private STNode parseListenersMemberEnd() { */ private boolean isServiceDeclStart(ParserRuleContext currentContext, int lookahead) { // Assume we always reach here after a peek() - switch (peek(lookahead + 1).kind) { - case IDENTIFIER_TOKEN: + return switch (peek(lookahead + 1).kind) { + case IDENTIFIER_TOKEN -> { SyntaxKind tokenAfterIdentifier = peek(lookahead + 2).kind; - switch (tokenAfterIdentifier) { - case ON_KEYWORD: // service foo on ... - case OPEN_BRACE_TOKEN: // missing listeners--> service foo { - return true; - case EQUAL_TOKEN: // service foo = ... - case SEMICOLON_TOKEN: // service foo; - case QUESTION_MARK_TOKEN: // service foo?; - return false; - default: - // If not any of above, this is not a valid syntax. - return false; - } - case ON_KEYWORD: - // Next token sequence is similar to: `service on ...`. - // Then this is a service decl. - return true; - default: - return false; - } + yield switch (tokenAfterIdentifier) { + case ON_KEYWORD, + // service foo on ... + OPEN_BRACE_TOKEN // missing listeners--> service foo { + -> true; + case EQUAL_TOKEN, + // service foo = ... + SEMICOLON_TOKEN, + // service foo; + QUESTION_MARK_TOKEN // service foo?; + -> false; + // If not any of above, this is not a valid syntax. + default -> false; + }; + } + // Next token sequence is similar to: `service on ...`. + // Then this is a service decl. + case ON_KEYWORD -> true; + default -> false; + }; } /** @@ -8426,15 +8255,10 @@ private STNode parseUnaryOperator() { * @return true if the token kind refers to a unary operator. false otherwise */ private boolean isUnaryOperator(SyntaxKind kind) { - switch (kind) { - case PLUS_TOKEN: - case MINUS_TOKEN: - case NEGATION_TOKEN: - case EXCLAMATION_MARK_TOKEN: - return true; - default: - return false; - } + return switch (kind) { + case PLUS_TOKEN, MINUS_TOKEN, NEGATION_TOKEN, EXCLAMATION_MARK_TOKEN -> true; + default -> false; + }; } /** @@ -8487,7 +8311,7 @@ private STNode createArrayTypeDesc(STNode memberTypeDesc, STNode openBracketToke } // If the member type desc is an array type desc flatten the dimensions - List arrayDimensions = new ArrayList(); + List arrayDimensions = new ArrayList<>(); if (memberTypeDesc.kind == SyntaxKind.ARRAY_TYPE_DESC) { STArrayTypeDescriptorNode innerArrayType = (STArrayTypeDescriptorNode) memberTypeDesc; STNode innerArrayDimensions = innerArrayType.dimensions; @@ -8523,20 +8347,18 @@ private STNode createArrayTypeDesc(STNode memberTypeDesc, STNode openBracketToke */ private STNode parseArrayLength() { STToken token = peek(); - switch (token.kind) { - case DECIMAL_INTEGER_LITERAL_TOKEN: - case HEX_INTEGER_LITERAL_TOKEN: - case ASTERISK_TOKEN: - return parseBasicLiteral(); - case CLOSE_BRACKET_TOKEN: - return STNodeFactory.createEmptyNode(); + return switch (token.kind) { + case DECIMAL_INTEGER_LITERAL_TOKEN, + HEX_INTEGER_LITERAL_TOKEN, + ASTERISK_TOKEN -> parseBasicLiteral(); + case CLOSE_BRACKET_TOKEN -> STNodeFactory.createEmptyNode(); // Parsing variable-reference-expr is same as parsing qualified identifier - case IDENTIFIER_TOKEN: - return parseQualifiedIdentifier(ParserRuleContext.ARRAY_LENGTH); - default: + case IDENTIFIER_TOKEN -> parseQualifiedIdentifier(ParserRuleContext.ARRAY_LENGTH); + default -> { recover(token, ParserRuleContext.ARRAY_LENGTH); - return parseArrayLength(); - } + yield parseArrayLength(); + } + }; } /** @@ -8769,26 +8591,24 @@ private STNode parseStatementStartWithExprRhs(STNode expression) { } private boolean isPossibleExpressionStatement(STNode expression) { - switch (expression.kind) { - case METHOD_CALL: - case FUNCTION_CALL: - case CHECK_EXPRESSION: - case REMOTE_METHOD_CALL_ACTION: - case CHECK_ACTION: - case BRACED_ACTION: - case START_ACTION: - case TRAP_ACTION: - case FLUSH_ACTION: - case ASYNC_SEND_ACTION: - case SYNC_SEND_ACTION: - case RECEIVE_ACTION: - case WAIT_ACTION: - case QUERY_ACTION: - case COMMIT_ACTION: - return true; - default: - return false; - } + return switch (expression.kind) { + case METHOD_CALL, + FUNCTION_CALL, + CHECK_EXPRESSION, + REMOTE_METHOD_CALL_ACTION, + CHECK_ACTION, + BRACED_ACTION, + START_ACTION, + TRAP_ACTION, + FLUSH_ACTION, + ASYNC_SEND_ACTION, + SYNC_SEND_ACTION, + RECEIVE_ACTION, + WAIT_ACTION, + QUERY_ACTION, + COMMIT_ACTION -> true; + default -> false; + }; } private STNode getExpressionAsStatement(STNode expression) { @@ -9048,15 +8868,14 @@ private STNode parseResourceAccessPath(boolean isRhsExpr, boolean isInMatchGuard private STNode parseResourceAccessSegment() { STToken nextToken = peek(); - switch (nextToken.kind) { - case IDENTIFIER_TOKEN: - return consume(); - case OPEN_BRACKET_TOKEN: - return parseComputedOrResourceAccessRestSegment(consume()); - default: + return switch (nextToken.kind) { + case IDENTIFIER_TOKEN -> consume(); + case OPEN_BRACKET_TOKEN -> parseComputedOrResourceAccessRestSegment(consume()); + default -> { recover(nextToken, ParserRuleContext.RESOURCE_ACCESS_PATH_SEGMENT); - return parseResourceAccessSegment(); - } + yield parseResourceAccessSegment(); + } + }; } /** @@ -9113,13 +8932,11 @@ private STNode parseResourceAccessSegmentRhs(boolean isRhsExpr, boolean isInMatc } private boolean isEndOfResourceAccessPathSegments(STToken nextToken, boolean isRhsExpr, boolean isInMatchGuard) { - switch (nextToken.kind) { - case DOT_TOKEN: - case OPEN_PAREN_TOKEN: - return true; - default: - return isEndOfActionOrExpression(nextToken, isRhsExpr, isInMatchGuard); - } + return switch (nextToken.kind) { + case DOT_TOKEN, + OPEN_PAREN_TOKEN -> true; + default -> isEndOfActionOrExpression(nextToken, isRhsExpr, isInMatchGuard); + }; } private STNode parseRemoteMethodCallOrClientResourceAccessOrAsyncSendAction(STNode expression, boolean isRhsExpr, @@ -9276,17 +9093,12 @@ private STNode parseParameterizedTypeDescriptor(STNode keywordToken) { } private SyntaxKind getParameterizedTypeDescKind(STNode keywordToken) { - switch (keywordToken.kind) { - case TYPEDESC_KEYWORD: - return SyntaxKind.TYPEDESC_TYPE_DESC; - case FUTURE_KEYWORD: - return SyntaxKind.FUTURE_TYPE_DESC; - case XML_KEYWORD: - return SyntaxKind.XML_TYPE_DESC; - case ERROR_KEYWORD: - default: - return SyntaxKind.ERROR_TYPE_DESC; - } + return switch (keywordToken.kind) { + case TYPEDESC_KEYWORD -> SyntaxKind.TYPEDESC_TYPE_DESC; + case FUTURE_KEYWORD -> SyntaxKind.FUTURE_TYPE_DESC; + case XML_KEYWORD -> SyntaxKind.XML_TYPE_DESC; + default -> SyntaxKind.ERROR_TYPE_DESC; + }; } /** @@ -9589,26 +9401,22 @@ private STNode parseAnnotationAttachPoints() { * @return Parsed node */ private STNode parseAttachPointEnd() { - switch (peek().kind) { - case SEMICOLON_TOKEN: - // null represents the end of attach points. - return null; - case COMMA_TOKEN: - return consume(); - default: + return switch (peek().kind) { + // null represents the end of attach points. + case SEMICOLON_TOKEN -> null; + case COMMA_TOKEN -> consume(); + default -> { recover(peek(), ParserRuleContext.ATTACH_POINT_END); - return parseAttachPointEnd(); - } + yield parseAttachPointEnd(); + } + }; } private boolean isEndAnnotAttachPointList(SyntaxKind tokenKind) { - switch (tokenKind) { - case EOF_TOKEN: - case SEMICOLON_TOKEN: - return true; - default: - return false; - } + return switch (tokenKind) { + case EOF_TOKEN, SEMICOLON_TOKEN -> true; + default -> false; + }; } /** @@ -9793,14 +9601,13 @@ private STNode parseServiceAttachPoint(STNode sourceKeyword, STNode firstIdent) */ private STNode parseIdentAfterObjectIdent() { STToken token = peek(); - switch (token.kind) { - case FUNCTION_KEYWORD: - case FIELD_KEYWORD: - return consume(); - default: + return switch (token.kind) { + case FUNCTION_KEYWORD, FIELD_KEYWORD -> consume(); + default -> { recover(token, ParserRuleContext.IDENT_AFTER_OBJECT_IDENT); - return parseIdentAfterObjectIdent(); - } + yield parseIdentAfterObjectIdent(); + } + }; } /** @@ -9877,15 +9684,10 @@ private STNode parseXMLNSKeyword() { } private boolean isValidXMLNameSpaceURI(STNode expr) { - switch (expr.kind) { - case STRING_LITERAL: - case QUALIFIED_NAME_REFERENCE: - case SIMPLE_NAME_REFERENCE: - return true; - case IDENTIFIER_TOKEN: - default: - return false; - } + return switch (expr.kind) { + case STRING_LITERAL, QUALIFIED_NAME_REFERENCE, SIMPLE_NAME_REFERENCE -> true; + default -> false; + }; } private STNode parseSimpleConstExpr() { @@ -10199,57 +10001,50 @@ private static boolean isTypeStartingToken(SyntaxKind nextTokenKind, STToken nex * @return true for simple type token in expression. false otherwise. */ private boolean isSimpleTypeInExpression(SyntaxKind nodeKind) { - switch (nodeKind) { - case VAR_KEYWORD: - case READONLY_KEYWORD: - return false; - default: - return isSimpleType(nodeKind); - } + return switch (nodeKind) { + case VAR_KEYWORD, READONLY_KEYWORD -> false; + default -> isSimpleType(nodeKind); + }; } static boolean isSimpleType(SyntaxKind nodeKind) { - switch (nodeKind) { - case INT_KEYWORD: - case FLOAT_KEYWORD: - case DECIMAL_KEYWORD: - case BOOLEAN_KEYWORD: - case STRING_KEYWORD: - case BYTE_KEYWORD: - case JSON_KEYWORD: - case HANDLE_KEYWORD: - case ANY_KEYWORD: - case ANYDATA_KEYWORD: - case NEVER_KEYWORD: - case VAR_KEYWORD: - case READONLY_KEYWORD: - return true; - default: - return false; - } + return switch (nodeKind) { + case INT_KEYWORD, + FLOAT_KEYWORD, + DECIMAL_KEYWORD, + BOOLEAN_KEYWORD, + STRING_KEYWORD, + BYTE_KEYWORD, + JSON_KEYWORD, + HANDLE_KEYWORD, + ANY_KEYWORD, + ANYDATA_KEYWORD, + NEVER_KEYWORD, + VAR_KEYWORD, + READONLY_KEYWORD -> true; + default -> false; + }; } static boolean isPredeclaredPrefix(SyntaxKind nodeKind) { - switch (nodeKind) { - case BOOLEAN_KEYWORD: - case DECIMAL_KEYWORD: - case ERROR_KEYWORD: - case FLOAT_KEYWORD: - case FUNCTION_KEYWORD: - case FUTURE_KEYWORD: - case INT_KEYWORD: - case MAP_KEYWORD: - case OBJECT_KEYWORD: - case STREAM_KEYWORD: - case STRING_KEYWORD: - case TABLE_KEYWORD: - case TRANSACTION_KEYWORD: - case TYPEDESC_KEYWORD: - case XML_KEYWORD: - return true; - default: - return false; - } + return switch (nodeKind) { + case BOOLEAN_KEYWORD, + DECIMAL_KEYWORD, + ERROR_KEYWORD, + FLOAT_KEYWORD, + FUNCTION_KEYWORD, + FUTURE_KEYWORD, + INT_KEYWORD, + MAP_KEYWORD, + OBJECT_KEYWORD, + STREAM_KEYWORD, + STRING_KEYWORD, + TABLE_KEYWORD, + TRANSACTION_KEYWORD, + TYPEDESC_KEYWORD, + XML_KEYWORD -> true; + default -> false; + }; } private boolean isQualifiedIdentifierPredeclaredPrefix(SyntaxKind nodeKind) { @@ -10257,37 +10052,25 @@ private boolean isQualifiedIdentifierPredeclaredPrefix(SyntaxKind nodeKind) { } private static SyntaxKind getBuiltinTypeSyntaxKind(SyntaxKind typeKeyword) { - switch (typeKeyword) { - case INT_KEYWORD: - return SyntaxKind.INT_TYPE_DESC; - case FLOAT_KEYWORD: - return SyntaxKind.FLOAT_TYPE_DESC; - case DECIMAL_KEYWORD: - return SyntaxKind.DECIMAL_TYPE_DESC; - case BOOLEAN_KEYWORD: - return SyntaxKind.BOOLEAN_TYPE_DESC; - case STRING_KEYWORD: - return SyntaxKind.STRING_TYPE_DESC; - case BYTE_KEYWORD: - return SyntaxKind.BYTE_TYPE_DESC; - case JSON_KEYWORD: - return SyntaxKind.JSON_TYPE_DESC; - case HANDLE_KEYWORD: - return SyntaxKind.HANDLE_TYPE_DESC; - case ANY_KEYWORD: - return SyntaxKind.ANY_TYPE_DESC; - case ANYDATA_KEYWORD: - return SyntaxKind.ANYDATA_TYPE_DESC; - case NEVER_KEYWORD: - return SyntaxKind.NEVER_TYPE_DESC; - case VAR_KEYWORD: - return SyntaxKind.VAR_TYPE_DESC; - case READONLY_KEYWORD: - return SyntaxKind.READONLY_TYPE_DESC; - default: + return switch (typeKeyword) { + case INT_KEYWORD -> SyntaxKind.INT_TYPE_DESC; + case FLOAT_KEYWORD -> SyntaxKind.FLOAT_TYPE_DESC; + case DECIMAL_KEYWORD -> SyntaxKind.DECIMAL_TYPE_DESC; + case BOOLEAN_KEYWORD -> SyntaxKind.BOOLEAN_TYPE_DESC; + case STRING_KEYWORD -> SyntaxKind.STRING_TYPE_DESC; + case BYTE_KEYWORD -> SyntaxKind.BYTE_TYPE_DESC; + case JSON_KEYWORD -> SyntaxKind.JSON_TYPE_DESC; + case HANDLE_KEYWORD -> SyntaxKind.HANDLE_TYPE_DESC; + case ANY_KEYWORD -> SyntaxKind.ANY_TYPE_DESC; + case ANYDATA_KEYWORD -> SyntaxKind.ANYDATA_TYPE_DESC; + case NEVER_KEYWORD -> SyntaxKind.NEVER_TYPE_DESC; + case VAR_KEYWORD -> SyntaxKind.VAR_TYPE_DESC; + case READONLY_KEYWORD -> SyntaxKind.READONLY_TYPE_DESC; + default -> { assert false : typeKeyword + " is not a built-in type"; - return SyntaxKind.TYPE_REFERENCE; - } + yield SyntaxKind.TYPE_REFERENCE; + } + }; } /** @@ -10487,26 +10270,22 @@ private STNode parseSpreadMember() { } private boolean isEndOfListConstructor(SyntaxKind tokenKind) { - switch (tokenKind) { - case EOF_TOKEN: - case CLOSE_BRACKET_TOKEN: - return true; - default: - return false; - } + return switch (tokenKind) { + case EOF_TOKEN, CLOSE_BRACKET_TOKEN -> true; + default -> false; + }; } private STNode parseListConstructorMemberEnd() { STToken nextToken = peek(); - switch (nextToken.kind) { - case COMMA_TOKEN: - return consume(); - case CLOSE_BRACKET_TOKEN: - return null; - default: + return switch (nextToken.kind) { + case COMMA_TOKEN -> consume(); + case CLOSE_BRACKET_TOKEN -> null; + default -> { recover(nextToken, ParserRuleContext.LIST_CONSTRUCTOR_MEMBER_END); - return parseListConstructorMemberEnd(); - } + yield parseListConstructorMemberEnd(); + } + }; } /** @@ -10685,29 +10464,22 @@ private STNode parseRowList() { } private boolean isEndOfTableRowList(SyntaxKind tokenKind) { - switch (tokenKind) { - case EOF_TOKEN: - case CLOSE_BRACKET_TOKEN: - return true; - case COMMA_TOKEN: - case OPEN_BRACE_TOKEN: - return false; - default: - return isEndOfMappingConstructor(tokenKind); - } + return switch (tokenKind) { + case EOF_TOKEN, CLOSE_BRACKET_TOKEN -> true; + case COMMA_TOKEN, OPEN_BRACE_TOKEN -> false; + default -> isEndOfMappingConstructor(tokenKind); + }; } private STNode parseTableRowEnd() { - switch (peek().kind) { - case COMMA_TOKEN: - return parseComma(); - case CLOSE_BRACKET_TOKEN: - case EOF_TOKEN: - return null; - default: + return switch (peek().kind) { + case COMMA_TOKEN -> parseComma(); + case CLOSE_BRACKET_TOKEN, EOF_TOKEN -> null; + default -> { recover(peek(), ParserRuleContext.TABLE_ROW_END); - return parseTableRowEnd(); - } + yield parseTableRowEnd(); + } + }; } /** @@ -10795,13 +10567,10 @@ private STNode parseFieldNames() { } private boolean isEndOfFieldNamesList(SyntaxKind tokenKind) { - switch (tokenKind) { - case COMMA_TOKEN: - case IDENTIFIER_TOKEN: - return false; - default: - return true; - } + return switch (tokenKind) { + case COMMA_TOKEN, IDENTIFIER_TOKEN -> false; + default -> true; + }; } /** @@ -10956,15 +10725,11 @@ private STNode parseLetVarDeclarations(ParserRuleContext context, boolean isRhsE static boolean isEndOfLetVarDeclarations(STToken nextToken, STToken nextNextToken) { SyntaxKind tokenKind = nextToken.kind; - switch (tokenKind) { - case COMMA_TOKEN: - case AT_TOKEN: - return false; - case IN_KEYWORD: - return true; - default: - return isGroupOrCollectKeyword(nextToken) || !isTypeStartingToken(tokenKind, nextNextToken); - } + return switch (tokenKind) { + case COMMA_TOKEN, AT_TOKEN -> false; + case IN_KEYWORD -> true; + default -> isGroupOrCollectKeyword(nextToken) || !isTypeStartingToken(tokenKind, nextNextToken); + }; } /** @@ -11013,13 +10778,10 @@ private STNode parseTemplateContent() { } private boolean isEndOfBacktickContent(SyntaxKind kind) { - switch (kind) { - case EOF_TOKEN: - case BACKTICK_TOKEN: - return true; - default: - return false; - } + return switch (kind) { + case EOF_TOKEN, BACKTICK_TOKEN -> true; + default -> false; + }; } private STNode parseTemplateItem() { @@ -11222,16 +10984,15 @@ private STNode parseInterpolation() { private boolean isEndOfInterpolation() { SyntaxKind nextTokenKind = peek().kind; - switch (nextTokenKind) { - case EOF_TOKEN: - case BACKTICK_TOKEN: - return true; - default: - // Validate if the close brace is the end close brace of interpolation + return switch (nextTokenKind) { + case EOF_TOKEN, BACKTICK_TOKEN -> true; + default -> { ParserMode currentLexerMode = this.tokenReader.getCurrentMode(); - return nextTokenKind == SyntaxKind.CLOSE_BRACE_TOKEN && currentLexerMode != ParserMode.INTERPOLATION && + // Validate if the close brace is the end close brace of interpolation + yield nextTokenKind == SyntaxKind.CLOSE_BRACE_TOKEN && currentLexerMode != ParserMode.INTERPOLATION && currentLexerMode != ParserMode.INTERPOLATION_BRACED_CONTENT; - } + } + }; } /** @@ -11330,15 +11091,14 @@ private STNode parseTypeParameter() { * @return Parsed node. */ private STNode parseKeyConstraint(STNode keyKeywordToken) { - switch (peek().kind) { - case OPEN_PAREN_TOKEN: - return parseKeySpecifier(keyKeywordToken); - case LT_TOKEN: - return parseKeyTypeConstraint(keyKeywordToken); - default: + return switch (peek().kind) { + case OPEN_PAREN_TOKEN -> parseKeySpecifier(keyKeywordToken); + case LT_TOKEN -> parseKeyTypeConstraint(keyKeywordToken); + default -> { recover(peek(), ParserRuleContext.KEY_CONSTRAINTS_RHS); - return parseKeyConstraint(keyKeywordToken); - } + yield parseKeyConstraint(keyKeywordToken); + } + }; } /** @@ -11438,13 +11198,10 @@ private STNode[] createFuncTypeQualNodeList(List qualifierList, STNode f } private boolean isRegularFuncQual(SyntaxKind tokenKind) { - switch (tokenKind) { - case ISOLATED_KEYWORD: - case TRANSACTIONAL_KEYWORD: - return true; - default: - return false; - } + return switch (tokenKind) { + case ISOLATED_KEYWORD, TRANSACTIONAL_KEYWORD -> true; + default -> false; + }; } /** @@ -11625,36 +11382,33 @@ private STNode parseImplicitAnonFunc(STNode openParen, STNode firstParam, boolea } private STNode parseImplicitAnonFuncParamEnd() { - switch (peek().kind) { - case COMMA_TOKEN: - return parseComma(); - case CLOSE_PAREN_TOKEN: - return null; - default: + return switch (peek().kind) { + case COMMA_TOKEN -> parseComma(); + case CLOSE_PAREN_TOKEN -> null; + default -> { recover(peek(), ParserRuleContext.ANON_FUNC_PARAM_RHS); - return parseImplicitAnonFuncParamEnd(); - } + yield parseImplicitAnonFuncParamEnd(); + } + }; } private boolean isEndOfAnonFuncParametersList(SyntaxKind tokenKind) { - switch (tokenKind) { - case EOF_TOKEN: - case CLOSE_BRACE_TOKEN: - case CLOSE_PAREN_TOKEN: - case CLOSE_BRACKET_TOKEN: - case SEMICOLON_TOKEN: - case RETURNS_KEYWORD: - case TYPE_KEYWORD: - case LISTENER_KEYWORD: - case IF_KEYWORD: - case WHILE_KEYWORD: - case DO_KEYWORD: - case OPEN_BRACE_TOKEN: - case RIGHT_DOUBLE_ARROW_TOKEN: - return true; - default: - return false; - } + return switch (tokenKind) { + case EOF_TOKEN, + CLOSE_BRACE_TOKEN, + CLOSE_PAREN_TOKEN, + CLOSE_BRACKET_TOKEN, + SEMICOLON_TOKEN, + RETURNS_KEYWORD, + TYPE_KEYWORD, + LISTENER_KEYWORD, + IF_KEYWORD, + WHILE_KEYWORD, + DO_KEYWORD, + OPEN_BRACE_TOKEN, + RIGHT_DOUBLE_ARROW_TOKEN -> true; + default -> false; + }; } /** @@ -11762,43 +11516,38 @@ private STNode invalidateTypeDescAfterRestDesc(STNode restDescriptor) { private STNode parseTupleMemberRhs() { STToken nextToken = peek(); - switch (nextToken.kind) { - case COMMA_TOKEN: - return parseComma(); - case CLOSE_BRACKET_TOKEN: - return null; - default: + return switch (nextToken.kind) { + case COMMA_TOKEN -> parseComma(); + case CLOSE_BRACKET_TOKEN -> null; + default -> { recover(nextToken, ParserRuleContext.TUPLE_TYPE_MEMBER_RHS); - return parseTupleMemberRhs(); - } + yield parseTupleMemberRhs(); + } + }; } private STNode parseTypeDescInTupleRhs() { STToken nextToken = peek(); - switch (nextToken.kind) { - case COMMA_TOKEN: - case CLOSE_BRACKET_TOKEN: - return null; - case ELLIPSIS_TOKEN: - return parseEllipsis(); - default: + return switch (nextToken.kind) { + case COMMA_TOKEN, CLOSE_BRACKET_TOKEN -> null; + case ELLIPSIS_TOKEN -> parseEllipsis(); + default -> { recover(nextToken, ParserRuleContext.TYPE_DESC_IN_TUPLE_RHS); - return parseTypeDescInTupleRhs(); - } + yield parseTypeDescInTupleRhs(); + } + }; } private boolean isEndOfTypeList(SyntaxKind nextTokenKind) { - switch (nextTokenKind) { - case CLOSE_BRACKET_TOKEN: - case CLOSE_BRACE_TOKEN: - case CLOSE_PAREN_TOKEN: - case EOF_TOKEN: - case EQUAL_TOKEN: - case SEMICOLON_TOKEN: - return true; - default: - return false; - } + return switch (nextTokenKind) { + case CLOSE_BRACKET_TOKEN, + CLOSE_BRACE_TOKEN, + CLOSE_PAREN_TOKEN, + EOF_TOKEN, + EQUAL_TOKEN, + SEMICOLON_TOKEN -> true; + default -> false; + }; } /** @@ -11872,15 +11621,15 @@ private STNode parseTableConstructorOrQuery(STNode tableKeyword, boolean isRhsEx private STNode parseTableConstructorOrQueryRhs(STNode tableKeyword, STNode keySpecifier, boolean isRhsExpr, boolean allowActions) { - switch (peek().kind) { - case FROM_KEYWORD: - return parseQueryExprRhs(parseQueryConstructType(tableKeyword, keySpecifier), isRhsExpr, allowActions); - case OPEN_BRACKET_TOKEN: - return parseTableConstructorExprRhs(tableKeyword, keySpecifier); - default: + return switch (peek().kind) { + case FROM_KEYWORD -> + parseQueryExprRhs(parseQueryConstructType(tableKeyword, keySpecifier), isRhsExpr, allowActions); + case OPEN_BRACKET_TOKEN -> parseTableConstructorExprRhs(tableKeyword, keySpecifier); + default -> { recover(peek(), ParserRuleContext.TABLE_CONSTRUCTOR_OR_QUERY_RHS); - return parseTableConstructorOrQueryRhs(tableKeyword, keySpecifier, isRhsExpr, allowActions); - } + yield parseTableConstructorOrQueryRhs(tableKeyword, keySpecifier, isRhsExpr, allowActions); + } + }; } /** @@ -11994,24 +11743,21 @@ private boolean isNestedQueryExpr() { } private boolean isValidIntermediateQueryStart(STToken token) { - switch (token.kind) { - case FROM_KEYWORD: - case WHERE_KEYWORD: - case LET_KEYWORD: - case SELECT_KEYWORD: - case JOIN_KEYWORD: - case OUTER_KEYWORD: - case ORDER_KEYWORD: - case BY_KEYWORD: - case ASCENDING_KEYWORD: - case DESCENDING_KEYWORD: - case LIMIT_KEYWORD: - return true; - case IDENTIFIER_TOKEN: - return isGroupOrCollectKeyword(token); - default: - return false; - } + return switch (token.kind) { + case FROM_KEYWORD, + WHERE_KEYWORD, + LET_KEYWORD, + SELECT_KEYWORD, + JOIN_KEYWORD, + OUTER_KEYWORD, + ORDER_KEYWORD, + BY_KEYWORD, + ASCENDING_KEYWORD, + DESCENDING_KEYWORD, + LIMIT_KEYWORD -> true; + case IDENTIFIER_TOKEN -> isGroupOrCollectKeyword(token); + default -> false; + }; } private static boolean isGroupOrCollectKeyword(STToken nextToken) { @@ -12135,31 +11881,29 @@ private STNode parseEqualsKeyword() { } private boolean isEndOfIntermediateClause(SyntaxKind tokenKind) { - switch (tokenKind) { - case CLOSE_BRACE_TOKEN: - case CLOSE_PAREN_TOKEN: - case CLOSE_BRACKET_TOKEN: - case OPEN_BRACE_TOKEN: - case SEMICOLON_TOKEN: - case PUBLIC_KEYWORD: - case FUNCTION_KEYWORD: - case EOF_TOKEN: - case RESOURCE_KEYWORD: - case LISTENER_KEYWORD: - case DOCUMENTATION_STRING: - case PRIVATE_KEYWORD: - case RETURNS_KEYWORD: - case SERVICE_KEYWORD: - case TYPE_KEYWORD: - case CONST_KEYWORD: - case FINAL_KEYWORD: - case DO_KEYWORD: - case ON_KEYWORD: - case CONFLICT_KEYWORD: - return true; - default: - return isValidExprRhsStart(tokenKind, SyntaxKind.NONE); - } + return switch (tokenKind) { + case CLOSE_BRACE_TOKEN, + CLOSE_PAREN_TOKEN, + CLOSE_BRACKET_TOKEN, + OPEN_BRACE_TOKEN, + SEMICOLON_TOKEN, + PUBLIC_KEYWORD, + FUNCTION_KEYWORD, + EOF_TOKEN, + RESOURCE_KEYWORD, + LISTENER_KEYWORD, + DOCUMENTATION_STRING, + PRIVATE_KEYWORD, + RETURNS_KEYWORD, + SERVICE_KEYWORD, + TYPE_KEYWORD, + CONST_KEYWORD, + FINAL_KEYWORD, + DO_KEYWORD, + ON_KEYWORD, + CONFLICT_KEYWORD -> true; + default -> isValidExprRhsStart(tokenKind, SyntaxKind.NONE); + }; } /** @@ -12421,47 +12165,38 @@ private STNode parseOrderKeyList(boolean isRhsExpr) { } private boolean isEndOfGroupByKeyListElement(STToken nextToken) { - switch (nextToken.kind) { - case COMMA_TOKEN: - return false; - case EOF_TOKEN: - return true; - default: - return isQueryClauseStartToken(nextToken); - } + return switch (nextToken.kind) { + case COMMA_TOKEN -> false; + case EOF_TOKEN -> true; + default -> isQueryClauseStartToken(nextToken); + }; } private boolean isEndOfOrderKeys(STToken nextToken) { - switch (nextToken.kind) { - case COMMA_TOKEN: - case ASCENDING_KEYWORD: - case DESCENDING_KEYWORD: - return false; - case SEMICOLON_TOKEN: - case EOF_TOKEN: - return true; - default: - return isQueryClauseStartToken(nextToken); - } + return switch (nextToken.kind) { + case COMMA_TOKEN, + ASCENDING_KEYWORD, + DESCENDING_KEYWORD -> false; + case SEMICOLON_TOKEN, + EOF_TOKEN -> true; + default -> isQueryClauseStartToken(nextToken); + }; } private boolean isQueryClauseStartToken(STToken nextToken) { - switch (nextToken.kind) { - case SELECT_KEYWORD: - case LET_KEYWORD: - case WHERE_KEYWORD: - case OUTER_KEYWORD: - case JOIN_KEYWORD: - case ORDER_KEYWORD: - case DO_KEYWORD: - case FROM_KEYWORD: - case LIMIT_KEYWORD: - return true; - case IDENTIFIER_TOKEN: - return isGroupOrCollectKeyword(nextToken); - default: - return false; - } + return switch (nextToken.kind) { + case SELECT_KEYWORD, + LET_KEYWORD, + WHERE_KEYWORD, + OUTER_KEYWORD, + JOIN_KEYWORD, + ORDER_KEYWORD, + DO_KEYWORD, + FROM_KEYWORD, + LIMIT_KEYWORD -> true; + case IDENTIFIER_TOKEN -> isGroupOrCollectKeyword(nextToken); + default -> false; + }; } private STNode parseGroupingKeyListMemberEnd() { @@ -12548,14 +12283,10 @@ private STNode parseOrderKey(boolean isRhsExpr) { STNode orderDirection; STToken nextToken = peek(); - switch (nextToken.kind) { - case ASCENDING_KEYWORD: - case DESCENDING_KEYWORD: - orderDirection = consume(); - break; - default: - orderDirection = STNodeFactory.createEmptyNode(); - } + orderDirection = switch (nextToken.kind) { + case ASCENDING_KEYWORD, DESCENDING_KEYWORD -> consume(); + default -> STNodeFactory.createEmptyNode(); + }; return STNodeFactory.createOrderKeyNode(expression, orderDirection); } @@ -12758,20 +12489,22 @@ private STNode generateValidExprForStartAction(STNode expr) { STNode closeParenToken = SyntaxErrors.createMissingTokenWithDiagnostics(SyntaxKind.CLOSE_PAREN_TOKEN, DiagnosticErrorCode.ERROR_MISSING_CLOSE_PAREN_TOKEN); - switch (expr.kind) { - case FIELD_ACCESS: + return switch (expr.kind) { + case FIELD_ACCESS -> { STFieldAccessExpressionNode fieldAccessExpr = (STFieldAccessExpressionNode) expr; - return STNodeFactory.createMethodCallExpressionNode(fieldAccessExpr.expression, + yield STNodeFactory.createMethodCallExpressionNode(fieldAccessExpr.expression, fieldAccessExpr.dotToken, fieldAccessExpr.fieldName, openParenToken, arguments, closeParenToken); - case ASYNC_SEND_ACTION: + } + case ASYNC_SEND_ACTION -> { STAsyncSendActionNode asyncSendAction = (STAsyncSendActionNode) expr; - return STNodeFactory.createRemoteMethodCallActionNode(asyncSendAction.expression, + yield STNodeFactory.createRemoteMethodCallActionNode(asyncSendAction.expression, asyncSendAction.rightArrowToken, asyncSendAction.peerWorker, openParenToken, arguments, closeParenToken); - default: // QualifiedNameRef or SimpleNameRef - return STNodeFactory.createFunctionCallExpressionNode(expr, openParenToken, arguments, closeParenToken); - } + } + // QualifiedNameRef or SimpleNameRef + default -> STNodeFactory.createFunctionCallExpressionNode(expr, openParenToken, arguments, closeParenToken); + }; } /** @@ -12826,13 +12559,10 @@ private STNode parseFlushKeyword() { */ private STNode parseOptionalPeerWorkerName() { STToken token = peek(); - switch (token.kind) { - case IDENTIFIER_TOKEN: - case FUNCTION_KEYWORD: - return STNodeFactory.createSimpleNameReferenceNode(consume()); - default: - return STNodeFactory.createEmptyNode(); - } + return switch (token.kind) { + case IDENTIFIER_TOKEN, FUNCTION_KEYWORD -> STNodeFactory.createSimpleNameReferenceNode(consume()); + default -> STNodeFactory.createEmptyNode(); + }; } /** @@ -12894,48 +12624,41 @@ private STNode parseSignedIntOrFloat() { STNode operator = parseUnaryOperator(); STNode literal; STToken nextToken = peek(); - switch (nextToken.kind) { - case HEX_INTEGER_LITERAL_TOKEN: - case DECIMAL_FLOATING_POINT_LITERAL_TOKEN: - case HEX_FLOATING_POINT_LITERAL_TOKEN: - literal = parseBasicLiteral(); - break; - default: // decimal integer literal - literal = parseDecimalIntLiteral(ParserRuleContext.DECIMAL_INTEGER_LITERAL_TOKEN); - literal = STNodeFactory.createBasicLiteralNode(SyntaxKind.NUMERIC_LITERAL, literal); - } + literal = switch (nextToken.kind) { + case HEX_INTEGER_LITERAL_TOKEN, + DECIMAL_FLOATING_POINT_LITERAL_TOKEN, + HEX_FLOATING_POINT_LITERAL_TOKEN -> parseBasicLiteral(); + // decimal integer literal + default -> STNodeFactory.createBasicLiteralNode(SyntaxKind.NUMERIC_LITERAL, + parseDecimalIntLiteral(ParserRuleContext.DECIMAL_INTEGER_LITERAL_TOKEN)); + }; return STNodeFactory.createUnaryExpressionNode(operator, literal); } private static boolean isSingletonTypeDescStart(SyntaxKind tokenKind, STToken nextNextToken) { - switch (tokenKind) { - case STRING_LITERAL_TOKEN: - case DECIMAL_INTEGER_LITERAL_TOKEN: - case HEX_INTEGER_LITERAL_TOKEN: - case DECIMAL_FLOATING_POINT_LITERAL_TOKEN: - case HEX_FLOATING_POINT_LITERAL_TOKEN: - case TRUE_KEYWORD: - case FALSE_KEYWORD: - case NULL_KEYWORD: - return true; - case PLUS_TOKEN: - case MINUS_TOKEN: - return isIntOrFloat(nextNextToken); - default: - return false; - } + return switch (tokenKind) { + case STRING_LITERAL_TOKEN, + DECIMAL_INTEGER_LITERAL_TOKEN, + HEX_INTEGER_LITERAL_TOKEN, + DECIMAL_FLOATING_POINT_LITERAL_TOKEN, + HEX_FLOATING_POINT_LITERAL_TOKEN, + TRUE_KEYWORD, + FALSE_KEYWORD, + NULL_KEYWORD -> true; + case PLUS_TOKEN, + MINUS_TOKEN -> isIntOrFloat(nextNextToken); + default -> false; + }; } static boolean isIntOrFloat(STToken token) { - switch (token.kind) { - case DECIMAL_INTEGER_LITERAL_TOKEN: - case HEX_INTEGER_LITERAL_TOKEN: - case DECIMAL_FLOATING_POINT_LITERAL_TOKEN: - case HEX_FLOATING_POINT_LITERAL_TOKEN: - return true; - default: - return false; - } + return switch (token.kind) { + case DECIMAL_INTEGER_LITERAL_TOKEN, + HEX_INTEGER_LITERAL_TOKEN, + DECIMAL_FLOATING_POINT_LITERAL_TOKEN, + HEX_FLOATING_POINT_LITERAL_TOKEN -> true; + default -> false; + }; } /** @@ -13040,14 +12763,14 @@ private STNode parseSyncSendAction(STNode expression) { */ private STNode parsePeerWorkerName() { STToken token = peek(); - switch (token.kind) { - case IDENTIFIER_TOKEN: - case FUNCTION_KEYWORD: - return STNodeFactory.createSimpleNameReferenceNode(consume()); - default: + return switch (token.kind) { + case IDENTIFIER_TOKEN, + FUNCTION_KEYWORD -> STNodeFactory.createSimpleNameReferenceNode(consume()); + default -> { recover(token, ParserRuleContext.PEER_WORKER_NAME); - return parsePeerWorkerName(); - } + yield parsePeerWorkerName(); + } + }; } /** @@ -13088,16 +12811,14 @@ private STNode parseReceiveAction() { } private STNode parseReceiveWorkers() { - switch (peek().kind) { - case FUNCTION_KEYWORD: - case IDENTIFIER_TOKEN: - return parseSingleOrAlternateReceiveWorkers(); - case OPEN_BRACE_TOKEN: - return parseMultipleReceiveWorkers(); - default: + return switch (peek().kind) { + case FUNCTION_KEYWORD, IDENTIFIER_TOKEN -> parseSingleOrAlternateReceiveWorkers(); + case OPEN_BRACE_TOKEN -> parseMultipleReceiveWorkers(); + default -> { recover(peek(), ParserRuleContext.RECEIVE_WORKERS); - return parseReceiveWorkers(); - } + yield parseReceiveWorkers(); + } + }; } private STNode parseSingleOrAlternateReceiveWorkers() { @@ -13177,25 +12898,21 @@ private STNode parseReceiveFields() { } private boolean isEndOfReceiveFields(SyntaxKind nextTokenKind) { - switch (nextTokenKind) { - case EOF_TOKEN: - case CLOSE_BRACE_TOKEN: - return true; - default: - return false; - } + return switch (nextTokenKind) { + case EOF_TOKEN, CLOSE_BRACE_TOKEN -> true; + default -> false; + }; } private STNode parseReceiveFieldEnd() { - switch (peek().kind) { - case COMMA_TOKEN: - return parseComma(); - case CLOSE_BRACE_TOKEN: - return null; - default: + return switch (peek().kind) { + case COMMA_TOKEN -> parseComma(); + case CLOSE_BRACE_TOKEN -> null; + default -> { recover(peek(), ParserRuleContext.RECEIVE_FIELD_END); - return parseReceiveFieldEnd(); - } + yield parseReceiveFieldEnd(); + } + }; } /** @@ -13206,17 +12923,20 @@ private STNode parseReceiveFieldEnd() { * @return Receiver field node */ private STNode parseReceiveField() { - switch (peek().kind) { - case FUNCTION_KEYWORD: + return switch (peek().kind) { + case FUNCTION_KEYWORD -> { STNode functionKeyword = consume(); - return STNodeFactory.createSimpleNameReferenceNode(functionKeyword); - case IDENTIFIER_TOKEN: + yield STNodeFactory.createSimpleNameReferenceNode(functionKeyword); + } + case IDENTIFIER_TOKEN -> { STNode identifier = parseIdentifier(ParserRuleContext.RECEIVE_FIELD_NAME); - return createReceiveField(identifier); - default: + yield createReceiveField(identifier); + } + default -> { recover(peek(), ParserRuleContext.RECEIVE_FIELD); - return parseReceiveField(); - } + yield parseReceiveField(); + } + }; } private STNode createReceiveField(STNode identifier) { @@ -13382,16 +13102,10 @@ private STNode parseSingleOrAlternateWaitAction(STNode waitKeyword) { } private boolean isEndOfWaitFutureExprList(SyntaxKind nextTokenKind) { - switch (nextTokenKind) { - case EOF_TOKEN: - case CLOSE_BRACE_TOKEN: - case SEMICOLON_TOKEN: - case OPEN_BRACE_TOKEN: - return true; - case PIPE_TOKEN: - default: - return false; - } + return switch (nextTokenKind) { + case EOF_TOKEN, CLOSE_BRACE_TOKEN, SEMICOLON_TOKEN, OPEN_BRACE_TOKEN -> true; + default -> false; + }; } private STNode parseWaitFutureExpr() { @@ -13474,25 +13188,21 @@ private STNode parseWaitFields() { } private boolean isEndOfWaitFields(SyntaxKind nextTokenKind) { - switch (nextTokenKind) { - case EOF_TOKEN: - case CLOSE_BRACE_TOKEN: - return true; - default: - return false; - } + return switch (nextTokenKind) { + case EOF_TOKEN, CLOSE_BRACE_TOKEN -> true; + default -> false; + }; } private STNode parseWaitFieldEnd() { - switch (peek().kind) { - case COMMA_TOKEN: - return parseComma(); - case CLOSE_BRACE_TOKEN: - return null; - default: + return switch (peek().kind) { + case COMMA_TOKEN -> parseComma(); + case CLOSE_BRACE_TOKEN -> null; + default -> { recover(peek(), ParserRuleContext.WAIT_FIELD_END); - return parseWaitFieldEnd(); - } + yield parseWaitFieldEnd(); + } + }; } /** @@ -13855,15 +13565,10 @@ private STNode parseEnumMemberList() { * @return Parsed enum member node. */ private STNode parseEnumMember() { - STNode metadata; - switch (peek().kind) { - case DOCUMENTATION_STRING: - case AT_TOKEN: - metadata = parseMetaData(); - break; - default: - metadata = STNodeFactory.createEmptyNode(); - } + STNode metadata = switch (peek().kind) { + case DOCUMENTATION_STRING, AT_TOKEN -> parseMetaData(); + default -> STNodeFactory.createEmptyNode(); + }; STNode identifierNode = parseIdentifier(ParserRuleContext.ENUM_MEMBER_NAME); return parseEnumMemberRhs(metadata, identifierNode); @@ -13890,15 +13595,14 @@ private STNode parseEnumMemberRhs(STNode metadata, STNode identifierNode) { } private STNode parseEnumMemberEnd() { - switch (peek().kind) { - case COMMA_TOKEN: - return parseComma(); - case CLOSE_BRACE_TOKEN: - return null; - default: + return switch (peek().kind) { + case COMMA_TOKEN -> parseComma(); + case CLOSE_BRACE_TOKEN -> null; + default -> { recover(peek(), ParserRuleContext.ENUM_MEMBER_END); - return parseEnumMemberEnd(); - } + yield parseEnumMemberEnd(); + } + }; } private STNode parseTransactionStmtOrVarDecl(STNode annots, List qualifiers, STToken transactionKeyword) { @@ -13990,19 +13694,16 @@ private STNode parseRetryStatement() { private STNode parseRetryKeywordRhs(STNode retryKeyword) { STToken nextToken = peek(); - switch (nextToken.kind) { - case LT_TOKEN: - STNode typeParam = parseTypeParameter(); - return parseRetryTypeParamRhs(retryKeyword, typeParam); - case OPEN_PAREN_TOKEN: - case OPEN_BRACE_TOKEN: - case TRANSACTION_KEYWORD: - typeParam = STNodeFactory.createEmptyNode(); - return parseRetryTypeParamRhs(retryKeyword, typeParam); - default: + return switch (nextToken.kind) { + case LT_TOKEN -> parseRetryTypeParamRhs(retryKeyword, parseTypeParameter()); + case OPEN_PAREN_TOKEN, + OPEN_BRACE_TOKEN, + TRANSACTION_KEYWORD -> parseRetryTypeParamRhs(retryKeyword, STNodeFactory.createEmptyNode()); + default -> { recover(peek(), ParserRuleContext.RETRY_KEYWORD_RHS); - return parseRetryKeywordRhs(retryKeyword); - } + yield parseRetryKeywordRhs(retryKeyword); + } + }; } private STNode parseRetryTypeParamRhs(STNode retryKeyword, STNode typeParam) { @@ -14027,15 +13728,14 @@ private STNode parseRetryTypeParamRhs(STNode retryKeyword, STNode typeParam) { } private STNode parseRetryBody() { - switch (peek().kind) { - case OPEN_BRACE_TOKEN: - return parseBlockNode(); - case TRANSACTION_KEYWORD: - return parseTransactionStatement(consume()); - default: + return switch (peek().kind) { + case OPEN_BRACE_TOKEN -> parseBlockNode(); + case TRANSACTION_KEYWORD -> parseTransactionStatement(consume()); + default -> { recover(peek(), ParserRuleContext.RETRY_BODY); - return parseRetryBody(); - } + yield parseRetryBody(); + } + }; } /** @@ -14058,15 +13758,10 @@ private STNode parseOptionalOnFailClause() { } private boolean isEndOfRegularCompoundStmt(SyntaxKind nodeKind) { - switch (nodeKind) { - case CLOSE_BRACE_TOKEN: - case SEMICOLON_TOKEN: - case AT_TOKEN: - case EOF_TOKEN: - return true; - default: - return isStatementStartingToken(nodeKind); - } + return switch (nodeKind) { + case CLOSE_BRACE_TOKEN, SEMICOLON_TOKEN, AT_TOKEN, EOF_TOKEN -> true; + default -> isStatementStartingToken(nodeKind); + }; } private boolean isStatementStartingToken(SyntaxKind nodeKind) { @@ -14624,30 +14319,22 @@ private STNode parseXMLNamePattern() { } private boolean isEndOfXMLNamePattern(SyntaxKind tokenKind) { - switch (tokenKind) { - case GT_TOKEN: - case EOF_TOKEN: - return true; - case IDENTIFIER_TOKEN: - case ASTERISK_TOKEN: - case COLON_TOKEN: - default: - return false; - } + return switch (tokenKind) { + case GT_TOKEN, EOF_TOKEN -> true; + default -> false; + }; } private STNode parseXMLNamePatternSeparator() { STToken token = peek(); - switch (token.kind) { - case PIPE_TOKEN: - return consume(); - case GT_TOKEN: - case EOF_TOKEN: - return null; - default: + return switch (token.kind) { + case PIPE_TOKEN -> consume(); + case GT_TOKEN, EOF_TOKEN -> null; + default -> { recover(token, ParserRuleContext.XML_NAME_PATTERN_RHS); - return parseXMLNamePatternSeparator(); - } + yield parseXMLNamePatternSeparator(); + } + }; } /** @@ -14825,14 +14512,10 @@ private STNode parseMatchKeyword() { } private boolean isEndOfMatchClauses(SyntaxKind nextTokenKind) { - switch (nextTokenKind) { - case EOF_TOKEN: - case CLOSE_BRACE_TOKEN: - case TYPE_KEYWORD: - return true; - default: - return isEndOfStatements(); - } + return switch (nextTokenKind) { + case EOF_TOKEN, CLOSE_BRACE_TOKEN, TYPE_KEYWORD -> true; + default -> isEndOfStatements(); + }; } /** @@ -14919,14 +14602,10 @@ private STNode parseMatchPatternList() { } private boolean isEndOfMatchPattern(SyntaxKind nextTokenKind) { - switch (nextTokenKind) { - case PIPE_TOKEN: - case IF_KEYWORD: - case RIGHT_DOUBLE_ARROW_TOKEN: - return true; - default: - return false; - } + return switch (nextTokenKind) { + case PIPE_TOKEN, IF_KEYWORD, RIGHT_DOUBLE_ARROW_TOKEN -> true; + default -> false; + }; } /** @@ -14951,46 +14630,41 @@ private STNode parseMatchPattern() { return parseErrorMatchPatternOrConsPattern(typeRefOrConstExpr); } - switch (nextToken.kind) { - case OPEN_PAREN_TOKEN: - case NULL_KEYWORD: - case TRUE_KEYWORD: - case FALSE_KEYWORD: - case PLUS_TOKEN: - case MINUS_TOKEN: - case DECIMAL_INTEGER_LITERAL_TOKEN: - case HEX_INTEGER_LITERAL_TOKEN: - case DECIMAL_FLOATING_POINT_LITERAL_TOKEN: - case HEX_FLOATING_POINT_LITERAL_TOKEN: - case STRING_LITERAL_TOKEN: - return parseSimpleConstExpr(); - case VAR_KEYWORD: - return parseVarTypedBindingPattern(); - case OPEN_BRACKET_TOKEN: - return parseListMatchPattern(); - case OPEN_BRACE_TOKEN: - return parseMappingMatchPattern(); - case ERROR_KEYWORD: - return parseErrorMatchPattern(); - default: + return switch (nextToken.kind) { + case OPEN_PAREN_TOKEN, + NULL_KEYWORD, + TRUE_KEYWORD, + FALSE_KEYWORD, + PLUS_TOKEN, + MINUS_TOKEN, + DECIMAL_INTEGER_LITERAL_TOKEN, + HEX_INTEGER_LITERAL_TOKEN, + DECIMAL_FLOATING_POINT_LITERAL_TOKEN, + HEX_FLOATING_POINT_LITERAL_TOKEN, + STRING_LITERAL_TOKEN -> parseSimpleConstExpr(); + case VAR_KEYWORD -> parseVarTypedBindingPattern(); + case OPEN_BRACKET_TOKEN -> parseListMatchPattern(); + case OPEN_BRACE_TOKEN -> parseMappingMatchPattern(); + case ERROR_KEYWORD -> parseErrorMatchPattern(); + default -> { recover(nextToken, ParserRuleContext.MATCH_PATTERN_START); - return parseMatchPattern(); - } + yield parseMatchPattern(); + } + }; } private STNode parseMatchPatternListMemberRhs() { STToken nextToken = peek(); - switch (nextToken.kind) { - case PIPE_TOKEN: - return parsePipeToken(); - case IF_KEYWORD: - case RIGHT_DOUBLE_ARROW_TOKEN: - // Returning null indicates the end of the match-patterns list - return null; - default: + return switch (nextToken.kind) { + case PIPE_TOKEN -> parsePipeToken(); + // Returning null indicates the end of the match-patterns list + case IF_KEYWORD, + RIGHT_DOUBLE_ARROW_TOKEN -> null; + default -> { recover(nextToken, ParserRuleContext.MATCH_PATTERN_LIST_MEMBER_RHS); - return parseMatchPatternListMemberRhs(); - } + yield parseMatchPatternListMemberRhs(); + } + }; } /** @@ -15083,24 +14757,19 @@ private STNode parseListMatchPattern() { } public boolean isEndOfListMatchPattern() { - switch (peek().kind) { - case CLOSE_BRACKET_TOKEN: - case EOF_TOKEN: - return true; - default: - return false; - } + return switch (peek().kind) { + case CLOSE_BRACKET_TOKEN, EOF_TOKEN -> true; + default -> false; + }; } private STNode parseListMatchPatternMember() { STNode nextToken = peek(); - switch (nextToken.kind) { - case ELLIPSIS_TOKEN: - return parseRestMatchPattern(); - default: - // No need of recovery here - return parseMatchPattern(); - } + return switch (nextToken.kind) { + case ELLIPSIS_TOKEN -> parseRestMatchPattern(); + // No need of recovery here + default -> parseMatchPattern(); + }; } /** @@ -15126,16 +14795,14 @@ private STNode parseRestMatchPattern() { } private STNode parseListMatchPatternMemberRhs() { - switch (peek().kind) { - case COMMA_TOKEN: - return parseComma(); - case CLOSE_BRACKET_TOKEN: - case EOF_TOKEN: - return null; - default: + return switch (peek().kind) { + case COMMA_TOKEN -> parseComma(); + case CLOSE_BRACKET_TOKEN, EOF_TOKEN -> null; + default -> { recover(peek(), ParserRuleContext.LIST_MATCH_PATTERN_MEMBER_RHS); - return parseListMatchPatternMemberRhs(); - } + yield parseListMatchPatternMemberRhs(); + } + }; } /** @@ -15239,19 +14906,16 @@ private void invalidateExtraFieldMatchPatterns(List fieldMatchPatterns) private STNode parseFieldMatchPatternMember() { STToken nextToken = peek(); - switch (nextToken.kind) { - case IDENTIFIER_TOKEN: - return parseFieldMatchPattern(); - case ELLIPSIS_TOKEN: - return parseRestMatchPattern(); - case CLOSE_BRACE_TOKEN: - case EOF_TOKEN: - // null marks the end of field-match-patterns - return null; - default: + return switch (nextToken.kind) { + case IDENTIFIER_TOKEN -> parseFieldMatchPattern(); + case ELLIPSIS_TOKEN -> parseRestMatchPattern(); + // null marks the end of field-match-patterns + case CLOSE_BRACE_TOKEN, EOF_TOKEN -> null; + default -> { recover(nextToken, ParserRuleContext.FIELD_MATCH_PATTERNS_START); - return parseFieldMatchPatternMember(); - } + yield parseFieldMatchPatternMember(); + } + }; } /** @@ -15270,26 +14934,21 @@ public STNode parseFieldMatchPattern() { } public boolean isEndOfMappingMatchPattern() { - switch (peek().kind) { - case CLOSE_BRACE_TOKEN: - case EOF_TOKEN: - return true; - default: - return false; - } + return switch (peek().kind) { + case CLOSE_BRACE_TOKEN, EOF_TOKEN -> true; + default -> false; + }; } - - private STNode parseFieldMatchPatternRhs() { - switch (peek().kind) { - case COMMA_TOKEN: - return parseComma(); - case CLOSE_BRACE_TOKEN: - case EOF_TOKEN: - return null; - default: + + private STNode parseFieldMatchPatternRhs() { + return switch (peek().kind) { + case COMMA_TOKEN -> parseComma(); + case CLOSE_BRACE_TOKEN, EOF_TOKEN -> null; + default -> { recover(peek(), ParserRuleContext.FIELD_MATCH_PATTERN_MEMBER_RHS); - return parseFieldMatchPatternRhs(); - } + yield parseFieldMatchPatternRhs(); + } + }; } private STNode parseErrorMatchPatternOrConsPattern(STNode typeRefOrConstExpr) { @@ -15310,19 +14969,17 @@ private STNode parseErrorMatchPatternOrConsPattern(STNode typeRefOrConstExpr) { } private boolean isMatchPatternEnd(SyntaxKind tokenKind) { - switch (tokenKind) { - case RIGHT_DOUBLE_ARROW_TOKEN: - case COMMA_TOKEN: - case CLOSE_BRACE_TOKEN: - case CLOSE_BRACKET_TOKEN: - case CLOSE_PAREN_TOKEN: - case PIPE_TOKEN: - case IF_KEYWORD: - case EOF_TOKEN: - return true; - default: - return false; - } + return switch (tokenKind) { + case RIGHT_DOUBLE_ARROW_TOKEN, + COMMA_TOKEN, + CLOSE_BRACE_TOKEN, + CLOSE_BRACKET_TOKEN, + CLOSE_PAREN_TOKEN, + PIPE_TOKEN, + IF_KEYWORD, + EOF_TOKEN -> true; + default -> false; + }; } /** @@ -15419,35 +15076,28 @@ private STNode parseErrorArgListMatchPatterns() { } private boolean isSimpleMatchPattern(SyntaxKind matchPatternKind) { - switch (matchPatternKind) { - case IDENTIFIER_TOKEN: - case SIMPLE_NAME_REFERENCE: - case QUALIFIED_NAME_REFERENCE: - case NUMERIC_LITERAL: - case STRING_LITERAL: - case NULL_LITERAL: - case NIL_LITERAL: - case BOOLEAN_LITERAL: - case TYPED_BINDING_PATTERN: - case UNARY_EXPRESSION: - return true; - default: - return false; - } + return switch (matchPatternKind) { + case IDENTIFIER_TOKEN, + SIMPLE_NAME_REFERENCE, + QUALIFIED_NAME_REFERENCE, + NUMERIC_LITERAL, + STRING_LITERAL, + NULL_LITERAL, + NIL_LITERAL, + BOOLEAN_LITERAL, + TYPED_BINDING_PATTERN, + UNARY_EXPRESSION -> true; + default -> false; + }; } private boolean isValidSecondArgMatchPattern(SyntaxKind syntaxKind) { - switch (syntaxKind) { - case ERROR_MATCH_PATTERN: - case NAMED_ARG_MATCH_PATTERN: - case REST_MATCH_PATTERN: - return true; - default: - if (isSimpleMatchPattern(syntaxKind)) { - return true; - } - return false; - } + return switch (syntaxKind) { + case ERROR_MATCH_PATTERN, + NAMED_ARG_MATCH_PATTERN, + REST_MATCH_PATTERN -> true; + default -> isSimpleMatchPattern(syntaxKind); + }; } /** @@ -15488,15 +15138,14 @@ private boolean isEndOfErrorFieldMatchPatterns() { } private STNode parseErrorArgListMatchPatternEnd(ParserRuleContext currentCtx) { - switch (peek().kind) { - case COMMA_TOKEN: - return consume(); - case CLOSE_PAREN_TOKEN: - return null; - default: + return switch (peek().kind) { + case COMMA_TOKEN -> consume(); + case CLOSE_PAREN_TOKEN -> null; + default -> { recover(peek(), currentCtx); - return parseErrorArgListMatchPatternEnd(currentCtx); - } + yield parseErrorArgListMatchPatternEnd(currentCtx); + } + }; } private STNode parseErrorArgListMatchPattern(ParserRuleContext context) { @@ -15564,17 +15213,17 @@ private STNode parseNamedArgMatchPattern(STNode identifier) { } private DiagnosticErrorCode validateErrorFieldMatchPatternOrder(SyntaxKind prevArgKind, SyntaxKind currentArgKind) { - switch (currentArgKind) { - case NAMED_ARG_MATCH_PATTERN: - case REST_MATCH_PATTERN: + return switch (currentArgKind) { + case NAMED_ARG_MATCH_PATTERN, + REST_MATCH_PATTERN -> { // Nothing is allowed after a rest arg if (prevArgKind == SyntaxKind.REST_MATCH_PATTERN) { - return DiagnosticErrorCode.ERROR_REST_ARG_FOLLOWED_BY_ANOTHER_ARG; + yield DiagnosticErrorCode.ERROR_REST_ARG_FOLLOWED_BY_ANOTHER_ARG; } - return null; - default: - return DiagnosticErrorCode.ERROR_MATCH_PATTERN_NOT_ALLOWED; - } + yield null; + } + default -> DiagnosticErrorCode.ERROR_MATCH_PATTERN_NOT_ALLOWED; + }; } /** @@ -15946,17 +15595,15 @@ private STNode parseTypeDescOrExpr(List qualifiers) { } private boolean isExpression(SyntaxKind kind) { - switch (kind) { - case NUMERIC_LITERAL: - case STRING_LITERAL_TOKEN: - case NIL_LITERAL: - case NULL_LITERAL: - case BOOLEAN_LITERAL: - return true; - default: - return kind.compareTo(SyntaxKind.BINARY_EXPRESSION) >= 0 && - kind.compareTo(SyntaxKind.ERROR_CONSTRUCTOR) <= 0; - } + return switch (kind) { + case NUMERIC_LITERAL, + STRING_LITERAL_TOKEN, + NIL_LITERAL, + NULL_LITERAL, + BOOLEAN_LITERAL -> true; + default -> kind.compareTo(SyntaxKind.BINARY_EXPRESSION) >= 0 && + kind.compareTo(SyntaxKind.ERROR_CONSTRUCTOR) <= 0; + }; } /** @@ -16210,12 +15857,10 @@ private boolean isAllBasicLiterals(STNode node) { } private boolean isNumericLiteral(STNode node) { - switch (node.kind) { - case NUMERIC_LITERAL: - return true; - default: - return false; - } + return switch (node.kind) { + case NUMERIC_LITERAL -> true; + default -> false; + }; } // ------------------------ Typed binding patterns --------------------------- @@ -16271,19 +15916,16 @@ private boolean isNumericLiteral(STNode node) { * @return binding-pattern node */ private STNode parseBindingPattern() { - switch (peek().kind) { - case OPEN_BRACKET_TOKEN: - return parseListBindingPattern(); - case IDENTIFIER_TOKEN: - return parseBindingPatternStartsWithIdentifier(); - case OPEN_BRACE_TOKEN: - return parseMappingBindingPattern(); - case ERROR_KEYWORD: - return parseErrorBindingPattern(); - default: + return switch (peek().kind) { + case OPEN_BRACKET_TOKEN -> parseListBindingPattern(); + case IDENTIFIER_TOKEN -> parseBindingPatternStartsWithIdentifier(); + case OPEN_BRACE_TOKEN -> parseMappingBindingPattern(); + case ERROR_KEYWORD -> parseErrorBindingPattern(); + default -> { recover(peek(), ParserRuleContext.BINDING_PATTERN); - return parseBindingPattern(); - } + yield parseBindingPattern(); + } + }; } private STNode parseBindingPatternStartsWithIdentifier() { @@ -16374,25 +16016,21 @@ private STNode parseListBindingPattern(STNode openBracket, STNode firstMember, L } private STNode parseListBindingPatternMemberRhs() { - switch (peek().kind) { - case COMMA_TOKEN: - return parseComma(); - case CLOSE_BRACKET_TOKEN: - return null; - default: + return switch (peek().kind) { + case COMMA_TOKEN -> parseComma(); + case CLOSE_BRACKET_TOKEN -> null; + default -> { recover(peek(), ParserRuleContext.LIST_BINDING_PATTERN_MEMBER_END); - return parseListBindingPatternMemberRhs(); - } + yield parseListBindingPatternMemberRhs(); + } + }; } private boolean isEndOfListBindingPattern(SyntaxKind nextTokenKind) { - switch (nextTokenKind) { - case CLOSE_BRACKET_TOKEN: - case EOF_TOKEN: - return true; - default: - return false; - } + return switch (nextTokenKind) { + case CLOSE_BRACKET_TOKEN, EOF_TOKEN -> true; + default -> false; + }; } /** @@ -16408,18 +16046,17 @@ private boolean isEndOfListBindingPattern(SyntaxKind nextTokenKind) { * @return List binding pattern member */ private STNode parseListBindingPatternMember() { - switch (peek().kind) { - case ELLIPSIS_TOKEN: - return parseRestBindingPattern(); - case OPEN_BRACKET_TOKEN: - case IDENTIFIER_TOKEN: - case OPEN_BRACE_TOKEN: - case ERROR_KEYWORD: - return parseBindingPattern(); - default: + return switch (peek().kind) { + case ELLIPSIS_TOKEN -> parseRestBindingPattern(); + case OPEN_BRACKET_TOKEN, + IDENTIFIER_TOKEN, + OPEN_BRACE_TOKEN, + ERROR_KEYWORD -> parseBindingPattern(); + default -> { recover(peek(), ParserRuleContext.LIST_BINDING_PATTERN_MEMBER); - return parseListBindingPatternMember(); - } + yield parseListBindingPatternMember(); + } + }; } /** @@ -16544,25 +16181,22 @@ private STNode parseMappingBindingPattern(STNode openBrace, List binding */ private STNode parseMappingBindingPatternMember() { STToken token = peek(); - switch (token.kind) { - case ELLIPSIS_TOKEN: - return parseRestBindingPattern(); - default: - return parseFieldBindingPattern(); - } + return switch (token.kind) { + case ELLIPSIS_TOKEN -> parseRestBindingPattern(); + default -> parseFieldBindingPattern(); + }; } private STNode parseMappingBindingPatternEnd() { STToken nextToken = peek(); - switch (nextToken.kind) { - case COMMA_TOKEN: - return parseComma(); - case CLOSE_BRACE_TOKEN: - return null; - default: + return switch (nextToken.kind) { + case COMMA_TOKEN -> parseComma(); + case CLOSE_BRACE_TOKEN -> null; + default -> { recover(nextToken, ParserRuleContext.MAPPING_BINDING_PATTERN_END); - return parseMappingBindingPatternEnd(); - } + yield parseMappingBindingPatternEnd(); + } + }; } /** @@ -16818,25 +16452,22 @@ private STNode parseErrorArgListBPWithoutErrorMsgAndCause(List argListBi private boolean isEndOfErrorFieldBindingPatterns() { SyntaxKind nextTokenKind = peek().kind; - switch (nextTokenKind) { - case CLOSE_PAREN_TOKEN: - case EOF_TOKEN: - return true; - default: - return false; - } + return switch (nextTokenKind) { + case CLOSE_PAREN_TOKEN, + EOF_TOKEN -> true; + default -> false; + }; } private STNode parseErrorArgsBindingPatternEnd(ParserRuleContext currentCtx) { - switch (peek().kind) { - case COMMA_TOKEN: - return consume(); - case CLOSE_PAREN_TOKEN: - return null; - default: + return switch (peek().kind) { + case COMMA_TOKEN -> consume(); + case CLOSE_PAREN_TOKEN -> null; + default -> { recover(peek(), currentCtx); - return parseErrorArgsBindingPatternEnd(currentCtx); - } + yield parseErrorArgsBindingPatternEnd(currentCtx); + } + }; } private STNode parseErrorArgListBindingPattern(ParserRuleContext context, boolean isFirstArg) { @@ -16880,22 +16511,17 @@ private STNode parseNamedOrSimpleArgBindingPattern(STNode argNameOrSimpleBinding private DiagnosticErrorCode validateErrorFieldBindingPatternOrder(SyntaxKind prevArgKind, SyntaxKind currentArgKind) { - switch (currentArgKind) { - case NAMED_ARG_BINDING_PATTERN: - case REST_BINDING_PATTERN: + return switch (currentArgKind) { + case NAMED_ARG_BINDING_PATTERN, + REST_BINDING_PATTERN -> { // Nothing is allowed after a rest arg if (prevArgKind == SyntaxKind.REST_BINDING_PATTERN) { - return DiagnosticErrorCode.ERROR_REST_ARG_FOLLOWED_BY_ANOTHER_ARG; + yield DiagnosticErrorCode.ERROR_REST_ARG_FOLLOWED_BY_ANOTHER_ARG; } - return null; - case CAPTURE_BINDING_PATTERN: - case WILDCARD_BINDING_PATTERN: - case ERROR_BINDING_PATTERN: - case LIST_BINDING_PATTERN: - case MAPPING_BINDING_PATTERN: - default: - return DiagnosticErrorCode.ERROR_BINDING_PATTERN_NOT_ALLOWED; - } + yield null; + } + default -> DiagnosticErrorCode.ERROR_BINDING_PATTERN_NOT_ALLOWED; + }; } // ------------------------ Typed binding patterns --------------------------- @@ -17020,13 +16646,10 @@ private STNode parseAsMemberAccessExpr(STNode typeNameOrExpr, STNode openBracket } private boolean isBracketedListEnd(SyntaxKind nextTokenKind) { - switch (nextTokenKind) { - case EOF_TOKEN: - case CLOSE_BRACKET_TOKEN: - return true; - default: - return false; - } + return switch (nextTokenKind) { + case EOF_TOKEN, CLOSE_BRACKET_TOKEN -> true; + default -> false; + }; } /** @@ -17102,15 +16725,14 @@ private STNode parseAsArrayTypeDesc(STNode typeDesc, STNode openBracket, STNode } private STNode parseBracketedListMemberEnd() { - switch (peek().kind) { - case COMMA_TOKEN: - return parseComma(); - case CLOSE_BRACKET_TOKEN: - return null; - default: + return switch (peek().kind) { + case COMMA_TOKEN -> parseComma(); + case CLOSE_BRACKET_TOKEN -> null; + default -> { recover(peek(), ParserRuleContext.BRACKETED_LIST_MEMBER_END); - return parseBracketedListMemberEnd(); - } + yield parseBracketedListMemberEnd(); + } + }; } /** @@ -17995,45 +17617,42 @@ private SyntaxKind getStmtStartBracketedListType(STNode memberNode) { return SyntaxKind.TUPLE_TYPE_DESC; } - switch (memberNode.kind) { - case WILDCARD_BINDING_PATTERN: - case CAPTURE_BINDING_PATTERN: - case LIST_BINDING_PATTERN: - case MAPPING_BINDING_PATTERN: - case ERROR_BINDING_PATTERN: - return SyntaxKind.LIST_BINDING_PATTERN; - case QUALIFIED_NAME_REFERENCE: // a qualified-name-ref can only be a type-ref - return SyntaxKind.TUPLE_TYPE_DESC; - case LIST_CONSTRUCTOR: - case MAPPING_CONSTRUCTOR: - case SPREAD_MEMBER: - return SyntaxKind.LIST_CONSTRUCTOR; - case MAPPING_BP_OR_MAPPING_CONSTRUCTOR: - case REST_BINDING_PATTERN: + return switch (memberNode.kind) { + case WILDCARD_BINDING_PATTERN, + CAPTURE_BINDING_PATTERN, + LIST_BINDING_PATTERN, + MAPPING_BINDING_PATTERN, + ERROR_BINDING_PATTERN -> SyntaxKind.LIST_BINDING_PATTERN; + // a qualified-name-ref can only be a type-ref + case QUALIFIED_NAME_REFERENCE -> SyntaxKind.TUPLE_TYPE_DESC; + case LIST_CONSTRUCTOR, + MAPPING_CONSTRUCTOR, + SPREAD_MEMBER -> SyntaxKind.LIST_CONSTRUCTOR; + case MAPPING_BP_OR_MAPPING_CONSTRUCTOR, + REST_BINDING_PATTERN -> // can be either list-bp or list-constructor. Cannot be a tuple-type-desc - return SyntaxKind.LIST_BP_OR_LIST_CONSTRUCTOR; - case SIMPLE_NAME_REFERENCE: // member is a simple type-ref/var-ref - case BRACKETED_LIST: // member is again ambiguous - return SyntaxKind.NONE; - case ERROR_CONSTRUCTOR: + SyntaxKind.LIST_BP_OR_LIST_CONSTRUCTOR; + case SIMPLE_NAME_REFERENCE, // member is a simple type-ref/var-ref + BRACKETED_LIST // member is again ambiguous + -> SyntaxKind.NONE; + case ERROR_CONSTRUCTOR -> { if (isPossibleErrorBindingPattern((STErrorConstructorExpressionNode) memberNode)) { - return SyntaxKind.NONE; + yield SyntaxKind.NONE; } - return SyntaxKind.LIST_CONSTRUCTOR; - case INDEXED_EXPRESSION: - return SyntaxKind.TUPLE_TYPE_DESC_OR_LIST_CONST; - case MEMBER_TYPE_DESC: - return SyntaxKind.MEMBER_TYPE_DESC; - case REST_TYPE: - return SyntaxKind.REST_TYPE; - default: + yield SyntaxKind.LIST_CONSTRUCTOR; + } + case INDEXED_EXPRESSION -> SyntaxKind.TUPLE_TYPE_DESC_OR_LIST_CONST; + case MEMBER_TYPE_DESC -> SyntaxKind.MEMBER_TYPE_DESC; + case REST_TYPE -> SyntaxKind.REST_TYPE; + default -> { if (isExpression(memberNode.kind) && !isAllBasicLiterals(memberNode) && !isAmbiguous(memberNode)) { - return SyntaxKind.LIST_CONSTRUCTOR; + yield SyntaxKind.LIST_CONSTRUCTOR; } + yield SyntaxKind.NONE; // can be any of the three. - return SyntaxKind.NONE; - } + } + }; } private boolean isPossibleErrorBindingPattern(STErrorConstructorExpressionNode errorConstructor) { @@ -18056,19 +17675,12 @@ private boolean isPossibleErrorBindingPattern(STErrorConstructorExpressionNode e } private boolean isPosibleArgBindingPattern(STFunctionArgumentNode arg) { - switch (arg.kind) { - case POSITIONAL_ARG: - STNode expr = ((STPositionalArgumentNode) arg).expression; - return isPosibleBindingPattern(expr); - case NAMED_ARG: - expr = ((STNamedArgumentNode) arg).expression; - return isPosibleBindingPattern(expr); - case REST_ARG: - expr = ((STRestArgumentNode) arg).expression; - return expr.kind == SyntaxKind.SIMPLE_NAME_REFERENCE; - default: - return false; - } + return switch (arg.kind) { + case POSITIONAL_ARG -> isPosibleBindingPattern(((STPositionalArgumentNode) arg).expression); + case NAMED_ARG -> isPosibleBindingPattern(((STNamedArgumentNode) arg).expression); + case REST_ARG -> ((STRestArgumentNode) arg).expression.kind == SyntaxKind.SIMPLE_NAME_REFERENCE; + default -> false; + }; } private boolean isPosibleBindingPattern(STNode node) { @@ -18194,16 +17806,14 @@ private STNode parseStatementStartBracketedListRhs(STNode annots, STNode openBra } private boolean isWildcardBP(STNode node) { - switch (node.kind) { - case SIMPLE_NAME_REFERENCE: + return switch (node.kind) { + case SIMPLE_NAME_REFERENCE -> { STToken nameToken = (STToken) ((STSimpleNameReferenceNode) node).name; - return isUnderscoreToken(nameToken); - case IDENTIFIER_TOKEN: - return isUnderscoreToken((STToken) node); - default: - return false; - - } + yield isUnderscoreToken(nameToken); + } + case IDENTIFIER_TOKEN -> isUnderscoreToken((STToken) node); + default -> false; + }; } private boolean isUnderscoreToken(STToken token) { @@ -18495,22 +18105,29 @@ private STNode parseIdentifierRhsInStmtStartingBrace(STNode readonlyKeyword) { return STNodeFactory.createSpecificFieldNode(readonlyKeyword, identifier, colon, value); } - switch (peek().kind) { - case OPEN_BRACKET_TOKEN: // { foo:[ + return switch (peek().kind) { + // { foo:[ + case OPEN_BRACKET_TOKEN -> { STNode bindingPatternOrExpr = parseListBindingPatternOrListConstructor(); - return getMappingField(identifier, colon, bindingPatternOrExpr); - case OPEN_BRACE_TOKEN: // { foo:{ - bindingPatternOrExpr = parseMappingBindingPatterOrMappingConstructor(); - return getMappingField(identifier, colon, bindingPatternOrExpr); - case ERROR_KEYWORD: // { foo: error - bindingPatternOrExpr = parseErrorBindingPatternOrErrorConstructor(); - return getMappingField(identifier, colon, bindingPatternOrExpr); - case IDENTIFIER_TOKEN: // { foo:bar - return parseQualifiedIdentifierRhsInStmtStartBrace(identifier, colon); - default: + yield getMappingField(identifier, colon, bindingPatternOrExpr); + } + // { foo:{ + case OPEN_BRACE_TOKEN -> { + STNode bindingPatternOrExpr = parseMappingBindingPatterOrMappingConstructor(); + yield getMappingField(identifier, colon, bindingPatternOrExpr); + } + // { foo: error + case ERROR_KEYWORD -> { + STNode bindingPatternOrExpr = parseErrorBindingPatternOrErrorConstructor(); + yield getMappingField(identifier, colon, bindingPatternOrExpr); + } + // { foo:bar + case IDENTIFIER_TOKEN -> parseQualifiedIdentifierRhsInStmtStartBrace(identifier, colon); + default -> { STNode expr = parseExpression(); - return getMappingField(identifier, colon, expr); - } + yield getMappingField(identifier, colon, expr); + } + }; default: switchContext(ParserRuleContext.BLOCK_STMT); if (!isEmpty(readonlyKeyword)) { @@ -18603,21 +18220,19 @@ private SyntaxKind getBracedListType(STNode member) { } // "{foo," and "{foo:bar," is ambiguous - switch (expr.kind) { - case SIMPLE_NAME_REFERENCE: - case LIST_BP_OR_LIST_CONSTRUCTOR: - case MAPPING_BP_OR_MAPPING_CONSTRUCTOR: - return SyntaxKind.MAPPING_BP_OR_MAPPING_CONSTRUCTOR; - case ERROR_BINDING_PATTERN: - return SyntaxKind.MAPPING_BINDING_PATTERN; - case ERROR_CONSTRUCTOR: + return switch (expr.kind) { + case SIMPLE_NAME_REFERENCE, + LIST_BP_OR_LIST_CONSTRUCTOR, + MAPPING_BP_OR_MAPPING_CONSTRUCTOR -> SyntaxKind.MAPPING_BP_OR_MAPPING_CONSTRUCTOR; + case ERROR_BINDING_PATTERN -> SyntaxKind.MAPPING_BINDING_PATTERN; + case ERROR_CONSTRUCTOR -> { if (isPossibleErrorBindingPattern((STErrorConstructorExpressionNode) expr)) { - return SyntaxKind.MAPPING_BP_OR_MAPPING_CONSTRUCTOR; + yield SyntaxKind.MAPPING_BP_OR_MAPPING_CONSTRUCTOR; } - return SyntaxKind.MAPPING_CONSTRUCTOR; - default: - return SyntaxKind.MAPPING_CONSTRUCTOR; - } + yield SyntaxKind.MAPPING_CONSTRUCTOR; + } + default -> SyntaxKind.MAPPING_CONSTRUCTOR; + }; case SPREAD_FIELD: case COMPUTED_NAME_FIELD: return SyntaxKind.MAPPING_CONSTRUCTOR; @@ -18647,13 +18262,10 @@ private STNode parseMappingBindingPatterOrMappingConstructor() { } private boolean isBracedListEnd(SyntaxKind nextTokenKind) { - switch (nextTokenKind) { - case EOF_TOKEN: - case CLOSE_BRACE_TOKEN: - return true; - default: - return false; - } + return switch (nextTokenKind) { + case EOF_TOKEN, CLOSE_BRACE_TOKEN -> true; + default -> false; + }; } private STNode parseMappingBindingPatternOrMappingConstructor(STNode openBrace, List memberList) { @@ -18741,21 +18353,14 @@ private STNode parseMappingFieldRhs(STNode key) { private STNode parseMappingFieldValue(STNode key, STNode colon) { // {foo: ... - STNode expr; - switch (peek().kind) { - case IDENTIFIER_TOKEN: - expr = parseExpression(); - break; - case OPEN_BRACKET_TOKEN: // { foo:[ - expr = parseListBindingPatternOrListConstructor(); - break; - case OPEN_BRACE_TOKEN: // { foo:{ - expr = parseMappingBindingPatterOrMappingConstructor(); - break; - default: - expr = parseExpression(); - break; - } + STNode expr = switch (peek().kind) { + case IDENTIFIER_TOKEN -> parseExpression(); + // { foo:[ + case OPEN_BRACKET_TOKEN -> parseListBindingPatternOrListConstructor(); + // { foo:{ + case OPEN_BRACE_TOKEN -> parseMappingBindingPatterOrMappingConstructor(); + default -> parseExpression(); + }; if (isBindingPattern(expr.kind)) { key = STNodeFactory.createSimpleNameReferenceNode(key); @@ -18767,16 +18372,14 @@ private STNode parseMappingFieldValue(STNode key, STNode colon) { } private boolean isBindingPattern(SyntaxKind kind) { - switch (kind) { - case FIELD_BINDING_PATTERN: - case MAPPING_BINDING_PATTERN: - case CAPTURE_BINDING_PATTERN: - case LIST_BINDING_PATTERN: - case WILDCARD_BINDING_PATTERN: - return true; - default: - return false; - } + return switch (kind) { + case FIELD_BINDING_PATTERN, + MAPPING_BINDING_PATTERN, + CAPTURE_BINDING_PATTERN, + LIST_BINDING_PATTERN, + WILDCARD_BINDING_PATTERN -> true; + default -> false; + }; } private SyntaxKind getTypeOfMappingBPOrMappingCons(STNode memberNode) { @@ -18901,21 +18504,17 @@ private STNode parseListBindingPatternOrListConstructorMember() { } private SyntaxKind getParsingNodeTypeOfListBPOrListCons(STNode memberNode) { - switch (memberNode.kind) { - case CAPTURE_BINDING_PATTERN: - case LIST_BINDING_PATTERN: - case MAPPING_BINDING_PATTERN: - case WILDCARD_BINDING_PATTERN: - return SyntaxKind.LIST_BINDING_PATTERN; - case SIMPLE_NAME_REFERENCE: // member is a simple type-ref/var-ref - case LIST_BP_OR_LIST_CONSTRUCTOR: // member is again ambiguous - case MAPPING_BP_OR_MAPPING_CONSTRUCTOR: - case REST_BINDING_PATTERN: - return SyntaxKind.LIST_BP_OR_LIST_CONSTRUCTOR; - case SPREAD_MEMBER: - default: - return SyntaxKind.LIST_CONSTRUCTOR; - } + return switch (memberNode.kind) { + case CAPTURE_BINDING_PATTERN, + LIST_BINDING_PATTERN, + MAPPING_BINDING_PATTERN, + WILDCARD_BINDING_PATTERN -> SyntaxKind.LIST_BINDING_PATTERN; + case SIMPLE_NAME_REFERENCE, // member is a simple type-ref/var-ref + LIST_BP_OR_LIST_CONSTRUCTOR, // member is again ambiguous + MAPPING_BP_OR_MAPPING_CONSTRUCTOR, + REST_BINDING_PATTERN -> SyntaxKind.LIST_BP_OR_LIST_CONSTRUCTOR; + default -> SyntaxKind.LIST_CONSTRUCTOR; + }; } private STNode parseAsListConstructor(STNode openBracket, List memberList, STNode member, boolean isRoot) { @@ -19447,23 +19046,22 @@ private STNode getExpression(STNode ambiguousNode, boolean isInMappingConstructo private STNode getMappingField(STNode identifier, STNode colon, STNode bindingPatternOrExpr) { STNode simpleNameRef = STNodeFactory.createSimpleNameReferenceNode(identifier); - switch (bindingPatternOrExpr.kind) { - case LIST_BINDING_PATTERN: - case MAPPING_BINDING_PATTERN: - return STNodeFactory.createFieldBindingPatternFullNode(simpleNameRef, colon, bindingPatternOrExpr); - case LIST_CONSTRUCTOR: - case MAPPING_CONSTRUCTOR: + return switch (bindingPatternOrExpr.kind) { + case LIST_BINDING_PATTERN, + MAPPING_BINDING_PATTERN -> + STNodeFactory.createFieldBindingPatternFullNode(simpleNameRef, colon, bindingPatternOrExpr); + case LIST_CONSTRUCTOR, + MAPPING_CONSTRUCTOR -> { STNode readonlyKeyword = STNodeFactory.createEmptyNode(); - return STNodeFactory + yield STNodeFactory .createSpecificFieldNode(readonlyKeyword, identifier, colon, bindingPatternOrExpr); - case LIST_BP_OR_LIST_CONSTRUCTOR: - case MAPPING_BP_OR_MAPPING_CONSTRUCTOR: - default: - // If ambiguous, return an specific node, since it is used to represent any - // ambiguous mapping field - readonlyKeyword = STNodeFactory.createEmptyNode(); - return STNodeFactory.createSpecificFieldNode(readonlyKeyword, identifier, colon, bindingPatternOrExpr); - } + } + // If ambiguous, return an specific node, since it is used to represent any ambiguous mapping field + default -> { + STNode readonlyKeyword = STNodeFactory.createEmptyNode(); + yield STNodeFactory.createSpecificFieldNode(readonlyKeyword, identifier, colon, bindingPatternOrExpr); + } + }; } // ----------------------------------------- Error Recovery ---------------------------------------- @@ -19493,24 +19091,22 @@ private boolean isInsideABlock(STToken nextToken) { } private boolean isBlockContext(ParserRuleContext ctx) { - switch (ctx) { - case FUNC_BODY_BLOCK: - case CLASS_MEMBER: - case OBJECT_CONSTRUCTOR_MEMBER: - case OBJECT_TYPE_MEMBER: - case BLOCK_STMT: - case MATCH_BODY: - case MAPPING_MATCH_PATTERN: - case MAPPING_BINDING_PATTERN: - case MAPPING_CONSTRUCTOR: - case FORK_STMT: - case MULTI_RECEIVE_WORKERS: - case MULTI_WAIT_FIELDS: - case MODULE_ENUM_DECLARATION: - return true; - default: - return false; - } + return switch (ctx) { + case FUNC_BODY_BLOCK, + CLASS_MEMBER, + OBJECT_CONSTRUCTOR_MEMBER, + OBJECT_TYPE_MEMBER, + BLOCK_STMT, + MATCH_BODY, + MAPPING_MATCH_PATTERN, + MAPPING_BINDING_PATTERN, + MAPPING_CONSTRUCTOR, + FORK_STMT, + MULTI_RECEIVE_WORKERS, + MULTI_WAIT_FIELDS, + MODULE_ENUM_DECLARATION -> true; + default -> false; + }; } // ----------------------------------------- ~ End of Parser ~ ---------------------------------------- diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/BallerinaParserErrorHandler.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/BallerinaParserErrorHandler.java index 20b922cfe6bf..cddfaec7223e 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/BallerinaParserErrorHandler.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/BallerinaParserErrorHandler.java @@ -856,26 +856,24 @@ public BallerinaParserErrorHandler(AbstractTokenReader tokenReader) { private boolean isEndOfObjectTypeNode(int nextLookahead) { STToken nextToken = this.tokenReader.peek(nextLookahead); - switch (nextToken.kind) { - case CLOSE_BRACE_TOKEN: - case EOF_TOKEN: - case CLOSE_BRACE_PIPE_TOKEN: - case TYPE_KEYWORD: - case SERVICE_KEYWORD: - return true; - default: + return switch (nextToken.kind) { + case CLOSE_BRACE_TOKEN, + EOF_TOKEN, + CLOSE_BRACE_PIPE_TOKEN, + TYPE_KEYWORD, + SERVICE_KEYWORD -> true; + default -> { STToken nextNextToken = this.tokenReader.peek(nextLookahead + 1); - switch (nextNextToken.kind) { - case CLOSE_BRACE_TOKEN: - case EOF_TOKEN: - case CLOSE_BRACE_PIPE_TOKEN: - case TYPE_KEYWORD: - case SERVICE_KEYWORD: - return true; - default: - return false; - } - } + yield switch (nextNextToken.kind) { + case CLOSE_BRACE_TOKEN, + EOF_TOKEN, + CLOSE_BRACE_PIPE_TOKEN, + TYPE_KEYWORD, + SERVICE_KEYWORD -> true; + default -> false; + }; + } + }; } /** @@ -1278,1581 +1276,1367 @@ private int getNextLookahead(int lookahead) { * @return */ private boolean isKeyword(ParserRuleContext currentCtx) { - switch (currentCtx) { - case EOF: - case PUBLIC_KEYWORD: - case PRIVATE_KEYWORD: - case FUNCTION_KEYWORD: - case NEW_KEYWORD: - case SELECT_KEYWORD: - case WHERE_KEYWORD: - case FROM_KEYWORD: - case ORDER_KEYWORD: - case GROUP_KEYWORD: - case BY_KEYWORD: - case START_KEYWORD: - case FLUSH_KEYWORD: - case DEFAULT_WORKER_NAME_IN_ASYNC_SEND: - case WAIT_KEYWORD: - case CHECKING_KEYWORD: - case FAIL_KEYWORD: - case DO_KEYWORD: - case TRANSACTION_KEYWORD: - case TRANSACTIONAL_KEYWORD: - case COMMIT_KEYWORD: - case RETRY_KEYWORD: - case ROLLBACK_KEYWORD: - case ENUM_KEYWORD: - case MATCH_KEYWORD: - case RETURNS_KEYWORD: - case EXTERNAL_KEYWORD: - case RECORD_KEYWORD: - case TYPE_KEYWORD: - case OBJECT_KEYWORD: - case ABSTRACT_KEYWORD: - case CLIENT_KEYWORD: - case IF_KEYWORD: - case ELSE_KEYWORD: - case WHILE_KEYWORD: - case PANIC_KEYWORD: - case AS_KEYWORD: - case LOCK_KEYWORD: - case IMPORT_KEYWORD: - case CONTINUE_KEYWORD: - case BREAK_KEYWORD: - case RETURN_KEYWORD: - case SERVICE_KEYWORD: - case ON_KEYWORD: - case LISTENER_KEYWORD: - case CONST_KEYWORD: - case FINAL_KEYWORD: - case TYPEOF_KEYWORD: - case IS_KEYWORD: - case NOT_IS_KEYWORD: - case NULL_KEYWORD: - case ANNOTATION_KEYWORD: - case SOURCE_KEYWORD: - case XMLNS_KEYWORD: - case WORKER_KEYWORD: - case FORK_KEYWORD: - case TRAP_KEYWORD: - case FOREACH_KEYWORD: - case IN_KEYWORD: - case TABLE_KEYWORD: - case KEY_KEYWORD: - case ERROR_KEYWORD: - case LET_KEYWORD: - case STREAM_KEYWORD: - case XML_KEYWORD: - case RE_KEYWORD: - case STRING_KEYWORD: - case BASE16_KEYWORD: - case BASE64_KEYWORD: - case DISTINCT_KEYWORD: - case CONFLICT_KEYWORD: - case LIMIT_KEYWORD: - case EQUALS_KEYWORD: - case JOIN_KEYWORD: - case OUTER_KEYWORD: - case CLASS_KEYWORD: - case MAP_KEYWORD: - case COLLECT_KEYWORD: - return true; - default: - return false; - } + return switch (currentCtx) { + case EOF, + PUBLIC_KEYWORD, + PRIVATE_KEYWORD, + FUNCTION_KEYWORD, + NEW_KEYWORD, + SELECT_KEYWORD, + WHERE_KEYWORD, + FROM_KEYWORD, + ORDER_KEYWORD, + GROUP_KEYWORD, + BY_KEYWORD, + START_KEYWORD, + FLUSH_KEYWORD, + DEFAULT_WORKER_NAME_IN_ASYNC_SEND, + WAIT_KEYWORD, + CHECKING_KEYWORD, + FAIL_KEYWORD, + DO_KEYWORD, + TRANSACTION_KEYWORD, + TRANSACTIONAL_KEYWORD, + COMMIT_KEYWORD, + RETRY_KEYWORD, + ROLLBACK_KEYWORD, + ENUM_KEYWORD, + MATCH_KEYWORD, + RETURNS_KEYWORD, + EXTERNAL_KEYWORD, + RECORD_KEYWORD, + TYPE_KEYWORD, + OBJECT_KEYWORD, + ABSTRACT_KEYWORD, + CLIENT_KEYWORD, + IF_KEYWORD, + ELSE_KEYWORD, + WHILE_KEYWORD, + PANIC_KEYWORD, + AS_KEYWORD, + LOCK_KEYWORD, + IMPORT_KEYWORD, + CONTINUE_KEYWORD, + BREAK_KEYWORD, + RETURN_KEYWORD, + SERVICE_KEYWORD, + ON_KEYWORD, + LISTENER_KEYWORD, + CONST_KEYWORD, + FINAL_KEYWORD, + TYPEOF_KEYWORD, + IS_KEYWORD, + NOT_IS_KEYWORD, + NULL_KEYWORD, + ANNOTATION_KEYWORD, + SOURCE_KEYWORD, + XMLNS_KEYWORD, + WORKER_KEYWORD, + FORK_KEYWORD, + TRAP_KEYWORD, + FOREACH_KEYWORD, + IN_KEYWORD, + TABLE_KEYWORD, + KEY_KEYWORD, + ERROR_KEYWORD, + LET_KEYWORD, + STREAM_KEYWORD, + XML_KEYWORD, + RE_KEYWORD, + STRING_KEYWORD, + BASE16_KEYWORD, + BASE64_KEYWORD, + DISTINCT_KEYWORD, + CONFLICT_KEYWORD, + LIMIT_KEYWORD, + EQUALS_KEYWORD, + JOIN_KEYWORD, + OUTER_KEYWORD, + CLASS_KEYWORD, + MAP_KEYWORD, + COLLECT_KEYWORD -> true; + default -> false; + }; } @Override protected boolean hasAlternativePaths(ParserRuleContext currentCtx) { + return switch (currentCtx) { + case TOP_LEVEL_NODE, + TOP_LEVEL_NODE_WITHOUT_MODIFIER, + TOP_LEVEL_NODE_WITHOUT_METADATA, + FUNC_OPTIONAL_RETURNS, + FUNC_BODY_OR_TYPE_DESC_RHS, + ANON_FUNC_BODY, + FUNC_BODY, + EXPRESSION, + TERMINAL_EXPRESSION, + VAR_DECL_STMT_RHS, + EXPRESSION_RHS, + VARIABLE_REF_RHS, + STATEMENT, + STATEMENT_WITHOUT_ANNOTS, + PARAM_LIST, + REQUIRED_PARAM_NAME_RHS, + TYPE_NAME_OR_VAR_NAME, + FIELD_DESCRIPTOR_RHS, + FIELD_OR_REST_DESCIPTOR_RHS, + RECORD_BODY_END, + RECORD_BODY_START, + TYPE_DESCRIPTOR, + TYPE_DESC_WITHOUT_ISOLATED, + RECORD_FIELD_OR_RECORD_END, + RECORD_FIELD_START, + RECORD_FIELD_WITHOUT_METADATA, + ARG_START, + ARG_START_OR_ARG_LIST_END, + NAMED_OR_POSITIONAL_ARG_RHS, + ARG_END, + CLASS_MEMBER_OR_OBJECT_MEMBER_START, + OBJECT_CONSTRUCTOR_MEMBER_START, + CLASS_MEMBER_OR_OBJECT_MEMBER_WITHOUT_META, + OBJECT_CONS_MEMBER_WITHOUT_META, + OPTIONAL_FIELD_INITIALIZER, + OBJECT_METHOD_START, + OBJECT_FUNC_OR_FIELD, + OBJECT_FUNC_OR_FIELD_WITHOUT_VISIBILITY, + OBJECT_TYPE_START, + OBJECT_CONSTRUCTOR_START, + ELSE_BLOCK, + ELSE_BODY, + CALL_STMT_START, + IMPORT_PREFIX_DECL, + IMPORT_DECL_ORG_OR_MODULE_NAME_RHS, + AFTER_IMPORT_MODULE_NAME, + RETURN_STMT_RHS, + ACCESS_EXPRESSION, + FIRST_MAPPING_FIELD, + MAPPING_FIELD, + SPECIFIC_FIELD, + SPECIFIC_FIELD_RHS, + MAPPING_FIELD_END, + OPTIONAL_ABSOLUTE_PATH, + CONST_DECL_TYPE, + CONST_DECL_RHS, + ARRAY_LENGTH, + PARAMETER_START, + PARAMETER_START_WITHOUT_ANNOTATION, + STMT_START_WITH_EXPR_RHS, + EXPR_STMT_RHS, + EXPRESSION_STATEMENT_START, + ANNOT_DECL_OPTIONAL_TYPE, + ANNOT_DECL_RHS, + ANNOT_OPTIONAL_ATTACH_POINTS, + ATTACH_POINT, + ATTACH_POINT_IDENT, + ATTACH_POINT_END, + XML_NAMESPACE_PREFIX_DECL, + CONSTANT_EXPRESSION_START, + TYPE_DESC_RHS, + LIST_CONSTRUCTOR_FIRST_MEMBER, + LIST_CONSTRUCTOR_MEMBER, + TYPE_CAST_PARAM, + TYPE_CAST_PARAM_RHS, + TABLE_KEYWORD_RHS, + ROW_LIST_RHS, + TABLE_ROW_END, + KEY_SPECIFIER_RHS, + TABLE_KEY_RHS, + LET_VAR_DECL_START, + ORDER_KEY_LIST_END, + STREAM_TYPE_FIRST_PARAM_RHS, + TEMPLATE_MEMBER, + TEMPLATE_STRING_RHS, + FUNCTION_KEYWORD_RHS, + FUNC_TYPE_FUNC_KEYWORD_RHS_START, + WORKER_NAME_RHS, + BINDING_PATTERN, + LIST_BINDING_PATTERNS_START, + LIST_BINDING_PATTERN_MEMBER_END, + FIELD_BINDING_PATTERN_END, + LIST_BINDING_PATTERN_MEMBER, + MAPPING_BINDING_PATTERN_END, + MAPPING_BINDING_PATTERN_MEMBER, + KEY_CONSTRAINTS_RHS, + TABLE_TYPE_DESC_RHS, + NEW_KEYWORD_RHS, + TABLE_CONSTRUCTOR_OR_QUERY_START, + TABLE_CONSTRUCTOR_OR_QUERY_RHS, + QUERY_PIPELINE_RHS, + BRACED_EXPR_OR_ANON_FUNC_PARAM_RHS, + ANON_FUNC_PARAM_RHS, + PARAM_END, + ANNOTATION_REF_RHS, + INFER_PARAM_END_OR_PARENTHESIS_END, + TYPE_DESC_IN_TUPLE_RHS, + TUPLE_TYPE_MEMBER_RHS, + LIST_CONSTRUCTOR_MEMBER_END, + NIL_OR_PARENTHESISED_TYPE_DESC_RHS, + REMOTE_OR_RESOURCE_CALL_OR_ASYNC_SEND_RHS, + REMOTE_CALL_OR_ASYNC_SEND_END, + RECEIVE_WORKERS, + RECEIVE_FIELD, + RECEIVE_FIELD_END, + WAIT_KEYWORD_RHS, + WAIT_FIELD_NAME_RHS, + WAIT_FIELD_END, + WAIT_FUTURE_EXPR_END, + OPTIONAL_PEER_WORKER, + ENUM_MEMBER_START, + ENUM_MEMBER_RHS, + ENUM_MEMBER_END, + MEMBER_ACCESS_KEY_EXPR_END, + ROLLBACK_RHS, + RETRY_KEYWORD_RHS, + RETRY_TYPE_PARAM_RHS, + RETRY_BODY, + STMT_START_BRACKETED_LIST_MEMBER, + STMT_START_BRACKETED_LIST_RHS, + BINDING_PATTERN_OR_EXPR_RHS, + BINDING_PATTERN_OR_VAR_REF_RHS, + BRACKETED_LIST_RHS, + BRACKETED_LIST_MEMBER, + BRACKETED_LIST_MEMBER_END, + TYPE_DESC_RHS_OR_BP_RHS, + LIST_BINDING_MEMBER_OR_ARRAY_LENGTH, + XML_NAVIGATE_EXPR, + XML_NAME_PATTERN_RHS, + XML_ATOMIC_NAME_PATTERN_START, + XML_ATOMIC_NAME_IDENTIFIER_RHS, + XML_STEP_START, + FUNC_TYPE_DESC_RHS_OR_ANON_FUNC_BODY, + OPTIONAL_MATCH_GUARD, + MATCH_PATTERN_LIST_MEMBER_RHS, + MATCH_PATTERN_START, + LIST_MATCH_PATTERNS_START, + LIST_MATCH_PATTERN_MEMBER, + LIST_MATCH_PATTERN_MEMBER_RHS, + ERROR_BINDING_PATTERN_ERROR_KEYWORD_RHS, + ERROR_ARG_LIST_BINDING_PATTERN_START, + ERROR_MESSAGE_BINDING_PATTERN_END, + ERROR_MESSAGE_BINDING_PATTERN_RHS, + ERROR_FIELD_BINDING_PATTERN, + ERROR_FIELD_BINDING_PATTERN_END, + FIELD_MATCH_PATTERNS_START, + FIELD_MATCH_PATTERN_MEMBER, + FIELD_MATCH_PATTERN_MEMBER_RHS, + ERROR_MATCH_PATTERN_OR_CONST_PATTERN, + ERROR_MATCH_PATTERN_ERROR_KEYWORD_RHS, + ERROR_ARG_LIST_MATCH_PATTERN_START, + ERROR_MESSAGE_MATCH_PATTERN_END, + ERROR_MESSAGE_MATCH_PATTERN_RHS, + ERROR_FIELD_MATCH_PATTERN, + ERROR_FIELD_MATCH_PATTERN_RHS, + NAMED_ARG_MATCH_PATTERN_RHS, + EXTERNAL_FUNC_BODY_OPTIONAL_ANNOTS, + LIST_BP_OR_LIST_CONSTRUCTOR_MEMBER, + TUPLE_TYPE_DESC_OR_LIST_CONST_MEMBER, + OBJECT_METHOD_WITHOUT_FIRST_QUALIFIER, + OBJECT_METHOD_WITHOUT_SECOND_QUALIFIER, + OBJECT_METHOD_WITHOUT_THIRD_QUALIFIER, + JOIN_CLAUSE_START, + INTERMEDIATE_CLAUSE_START, + MAPPING_BP_OR_MAPPING_CONSTRUCTOR_MEMBER, + TYPE_DESC_OR_EXPR_RHS, + LISTENERS_LIST_END, + REGULAR_COMPOUND_STMT_RHS, + NAMED_WORKER_DECL_START, + FUNC_TYPE_DESC_START, + ANON_FUNC_EXPRESSION_START, + MODULE_CLASS_DEFINITION_START, + OBJECT_CONSTRUCTOR_TYPE_REF, + OBJECT_FIELD_QUALIFIER, + OPTIONAL_SERVICE_DECL_TYPE, + SERVICE_IDENT_RHS, + ABSOLUTE_RESOURCE_PATH_START, + ABSOLUTE_RESOURCE_PATH_END, + SERVICE_DECL_OR_VAR_DECL, + OPTIONAL_RELATIVE_PATH, + RELATIVE_RESOURCE_PATH_START, + RELATIVE_RESOURCE_PATH_END, + RESOURCE_PATH_SEGMENT, + PATH_PARAM_OPTIONAL_ANNOTS, + PATH_PARAM_ELLIPSIS, + OPTIONAL_PATH_PARAM_NAME, + OBJECT_CONS_WITHOUT_FIRST_QUALIFIER, + OBJECT_TYPE_WITHOUT_FIRST_QUALIFIER, + CONFIG_VAR_DECL_RHS, + SERVICE_DECL_START, + ERROR_CONSTRUCTOR_RHS, + OPTIONAL_TYPE_PARAMETER, + MAP_TYPE_OR_TYPE_REF, + OBJECT_TYPE_OR_TYPE_REF, + STREAM_TYPE_OR_TYPE_REF, + TABLE_TYPE_OR_TYPE_REF, + PARAMETERIZED_TYPE_OR_TYPE_REF, + TYPE_DESC_RHS_OR_TYPE_REF, + TRANSACTION_STMT_RHS_OR_TYPE_REF, + TABLE_CONS_OR_QUERY_EXPR_OR_VAR_REF, + QUERY_EXPR_OR_VAR_REF, + ERROR_CONS_EXPR_OR_VAR_REF, + QUALIFIED_IDENTIFIER, + CLASS_DEF_WITHOUT_FIRST_QUALIFIER, + CLASS_DEF_WITHOUT_SECOND_QUALIFIER, + CLASS_DEF_WITHOUT_THIRD_QUALIFIER, + FUNC_DEF_START, + FUNC_DEF_WITHOUT_FIRST_QUALIFIER, + FUNC_TYPE_DESC_START_WITHOUT_FIRST_QUAL, + MODULE_VAR_DECL_START, + MODULE_VAR_WITHOUT_FIRST_QUAL, + MODULE_VAR_WITHOUT_SECOND_QUAL, + FUNC_DEF_OR_TYPE_DESC_RHS, + CLASS_DESCRIPTOR, + EXPR_START_OR_INFERRED_TYPEDESC_DEFAULT_START, + TYPE_CAST_PARAM_START_OR_INFERRED_TYPEDESC_DEFAULT_END, + END_OF_PARAMS_OR_NEXT_PARAM_START, + ASSIGNMENT_STMT_RHS, + PARAM_START, + PARAM_RHS, + FUNC_TYPE_PARAM_RHS, + ANNOTATION_DECL_START, + ON_FAIL_OPTIONAL_BINDING_PATTERN, + OPTIONAL_RESOURCE_ACCESS_PATH, + RESOURCE_ACCESS_PATH_SEGMENT, + COMPUTED_SEGMENT_OR_REST_SEGMENT, + RESOURCE_ACCESS_SEGMENT_RHS, + OPTIONAL_RESOURCE_ACCESS_METHOD, + OPTIONAL_RESOURCE_ACCESS_ACTION_ARG_LIST, + OPTIONAL_TOP_LEVEL_SEMICOLON, + TUPLE_MEMBER, + GROUPING_KEY_LIST_ELEMENT, + GROUPING_KEY_LIST_ELEMENT_END, + RESULT_CLAUSE, + SINGLE_OR_ALTERNATE_WORKER_SEPARATOR -> true; + default -> false; + }; + } + + /** + * Returns the shortest alternative path for a parser rule with alternatives. + * + * @param currentCtx Parser rule with alternatives + * @return shortest alternative path + */ + protected ParserRuleContext getShortestAlternative(ParserRuleContext currentCtx) { + return switch (currentCtx) { + case TOP_LEVEL_NODE, + TOP_LEVEL_NODE_WITHOUT_MODIFIER, + TOP_LEVEL_NODE_WITHOUT_METADATA -> ParserRuleContext.EOF; + case FUNC_OPTIONAL_RETURNS -> ParserRuleContext.RETURNS_KEYWORD; + case FUNC_BODY_OR_TYPE_DESC_RHS -> ParserRuleContext.FUNC_BODY; + case ANON_FUNC_BODY -> ParserRuleContext.EXPLICIT_ANON_FUNC_EXPR_BODY_START; + case FUNC_BODY -> ParserRuleContext.FUNC_BODY_BLOCK; + case EXPRESSION, + TERMINAL_EXPRESSION -> ParserRuleContext.VARIABLE_REF; + case VAR_DECL_STMT_RHS -> ParserRuleContext.SEMICOLON; + case EXPRESSION_RHS, + VARIABLE_REF_RHS -> ParserRuleContext.BINARY_OPERATOR; + case STATEMENT, + STATEMENT_WITHOUT_ANNOTS -> ParserRuleContext.VAR_DECL_STMT; + case PARAM_LIST -> ParserRuleContext.CLOSE_PARENTHESIS; + case REQUIRED_PARAM_NAME_RHS -> ParserRuleContext.PARAM_END; + case TYPE_NAME_OR_VAR_NAME -> ParserRuleContext.VARIABLE_NAME; + case FIELD_DESCRIPTOR_RHS -> ParserRuleContext.SEMICOLON; + case FIELD_OR_REST_DESCIPTOR_RHS -> ParserRuleContext.VARIABLE_NAME; + case RECORD_BODY_END -> ParserRuleContext.CLOSE_BRACE; + case RECORD_BODY_START -> ParserRuleContext.OPEN_BRACE; + case TYPE_DESCRIPTOR -> ParserRuleContext.SIMPLE_TYPE_DESC_IDENTIFIER; + case TYPE_DESC_WITHOUT_ISOLATED -> ParserRuleContext.FUNC_TYPE_DESC; + case RECORD_FIELD_OR_RECORD_END -> ParserRuleContext.RECORD_BODY_END; + case RECORD_FIELD_START, + RECORD_FIELD_WITHOUT_METADATA -> ParserRuleContext.TYPE_DESC_IN_RECORD_FIELD; + case ARG_START -> ParserRuleContext.EXPRESSION; + case ARG_START_OR_ARG_LIST_END -> ParserRuleContext.ARG_LIST_END; + case NAMED_OR_POSITIONAL_ARG_RHS -> ParserRuleContext.ARG_END; + case ARG_END -> ParserRuleContext.ARG_LIST_END; + case CLASS_MEMBER_OR_OBJECT_MEMBER_START, + OBJECT_CONSTRUCTOR_MEMBER_START, + CLASS_MEMBER_OR_OBJECT_MEMBER_WITHOUT_META, + OBJECT_CONS_MEMBER_WITHOUT_META -> ParserRuleContext.CLOSE_BRACE; + case OPTIONAL_FIELD_INITIALIZER -> ParserRuleContext.SEMICOLON; + case ON_FAIL_OPTIONAL_BINDING_PATTERN -> ParserRuleContext.BLOCK_STMT; + case OBJECT_METHOD_START -> ParserRuleContext.FUNC_DEF_OR_FUNC_TYPE; + case OBJECT_FUNC_OR_FIELD -> ParserRuleContext.OBJECT_FUNC_OR_FIELD_WITHOUT_VISIBILITY; + case OBJECT_FUNC_OR_FIELD_WITHOUT_VISIBILITY -> ParserRuleContext.OBJECT_FIELD_START; + case OBJECT_TYPE_START, + OBJECT_CONSTRUCTOR_START -> ParserRuleContext.OBJECT_KEYWORD; + case ELSE_BLOCK -> ParserRuleContext.STATEMENT; + case ELSE_BODY -> ParserRuleContext.OPEN_BRACE; + case CALL_STMT_START -> ParserRuleContext.VARIABLE_REF; + case IMPORT_PREFIX_DECL -> ParserRuleContext.SEMICOLON; + case IMPORT_DECL_ORG_OR_MODULE_NAME_RHS -> ParserRuleContext.AFTER_IMPORT_MODULE_NAME; + case AFTER_IMPORT_MODULE_NAME, + RETURN_STMT_RHS -> ParserRuleContext.SEMICOLON; + case ACCESS_EXPRESSION -> ParserRuleContext.VARIABLE_REF; + case FIRST_MAPPING_FIELD -> ParserRuleContext.CLOSE_BRACE; + case MAPPING_FIELD -> ParserRuleContext.SPECIFIC_FIELD; + case SPECIFIC_FIELD -> ParserRuleContext.MAPPING_FIELD_NAME; + case SPECIFIC_FIELD_RHS -> ParserRuleContext.MAPPING_FIELD_END; + case MAPPING_FIELD_END -> ParserRuleContext.CLOSE_BRACE; + case OPTIONAL_ABSOLUTE_PATH -> ParserRuleContext.ON_KEYWORD; + case CONST_DECL_TYPE -> ParserRuleContext.VARIABLE_NAME; + case CONST_DECL_RHS -> ParserRuleContext.ASSIGN_OP; + case ARRAY_LENGTH -> ParserRuleContext.CLOSE_BRACKET; + case PARAMETER_START -> ParserRuleContext.PARAMETER_START_WITHOUT_ANNOTATION; + case PARAMETER_START_WITHOUT_ANNOTATION -> ParserRuleContext.TYPE_DESC_IN_PARAM; + case STMT_START_WITH_EXPR_RHS, + EXPR_STMT_RHS -> ParserRuleContext.SEMICOLON; + case EXPRESSION_STATEMENT_START -> ParserRuleContext.VARIABLE_REF; + case ANNOT_DECL_OPTIONAL_TYPE -> ParserRuleContext.ANNOTATION_TAG; + case ANNOT_DECL_RHS, + ANNOT_OPTIONAL_ATTACH_POINTS -> ParserRuleContext.SEMICOLON; + case ATTACH_POINT -> ParserRuleContext.ATTACH_POINT_IDENT; + case ATTACH_POINT_IDENT -> ParserRuleContext.SINGLE_KEYWORD_ATTACH_POINT_IDENT; + case ATTACH_POINT_END, + BINDING_PATTERN_OR_VAR_REF_RHS -> ParserRuleContext.SEMICOLON; + case XML_NAMESPACE_PREFIX_DECL -> ParserRuleContext.SEMICOLON; + case CONSTANT_EXPRESSION_START -> ParserRuleContext.VARIABLE_REF; + case TYPE_DESC_RHS -> ParserRuleContext.END_OF_TYPE_DESC; + case LIST_CONSTRUCTOR_FIRST_MEMBER -> ParserRuleContext.CLOSE_BRACKET; + case LIST_CONSTRUCTOR_MEMBER -> ParserRuleContext.EXPRESSION; + case TYPE_CAST_PARAM, + TYPE_CAST_PARAM_RHS -> ParserRuleContext.TYPE_DESC_IN_ANGLE_BRACKETS; + case TABLE_KEYWORD_RHS -> ParserRuleContext.TABLE_CONSTRUCTOR; + case ROW_LIST_RHS, + TABLE_ROW_END -> ParserRuleContext.CLOSE_BRACKET; + case KEY_SPECIFIER_RHS, + TABLE_KEY_RHS -> ParserRuleContext.CLOSE_PARENTHESIS; + case LET_VAR_DECL_START -> ParserRuleContext.TYPE_DESC_IN_TYPE_BINDING_PATTERN; + case ORDER_KEY_LIST_END -> ParserRuleContext.ORDER_CLAUSE_END; + case GROUPING_KEY_LIST_ELEMENT_END -> ParserRuleContext.GROUP_BY_CLAUSE_END; + case GROUPING_KEY_LIST_ELEMENT -> ParserRuleContext.VARIABLE_NAME; + case STREAM_TYPE_FIRST_PARAM_RHS -> ParserRuleContext.GT; + case TEMPLATE_MEMBER, + TEMPLATE_STRING_RHS -> ParserRuleContext.TEMPLATE_END; + case FUNCTION_KEYWORD_RHS -> ParserRuleContext.FUNC_TYPE_FUNC_KEYWORD_RHS; + case FUNC_TYPE_FUNC_KEYWORD_RHS_START -> ParserRuleContext.FUNC_TYPE_DESC_END; + case WORKER_NAME_RHS -> ParserRuleContext.BLOCK_STMT; + case BINDING_PATTERN -> ParserRuleContext.BINDING_PATTERN_STARTING_IDENTIFIER; + case LIST_BINDING_PATTERNS_START, + LIST_BINDING_PATTERN_MEMBER_END -> ParserRuleContext.CLOSE_BRACKET; + case FIELD_BINDING_PATTERN_END -> ParserRuleContext.CLOSE_BRACE; + case LIST_BINDING_PATTERN_MEMBER -> ParserRuleContext.BINDING_PATTERN; + case MAPPING_BINDING_PATTERN_END -> ParserRuleContext.CLOSE_BRACE; + case MAPPING_BINDING_PATTERN_MEMBER -> ParserRuleContext.FIELD_BINDING_PATTERN; + case KEY_CONSTRAINTS_RHS -> ParserRuleContext.OPEN_PARENTHESIS; + case TABLE_TYPE_DESC_RHS -> ParserRuleContext.TYPE_DESC_RHS; + case NEW_KEYWORD_RHS -> ParserRuleContext.EXPRESSION_RHS; + case TABLE_CONSTRUCTOR_OR_QUERY_START -> ParserRuleContext.TABLE_KEYWORD; + case TABLE_CONSTRUCTOR_OR_QUERY_RHS -> ParserRuleContext.TABLE_CONSTRUCTOR; + case QUERY_PIPELINE_RHS -> ParserRuleContext.QUERY_EXPRESSION_RHS; + case BRACED_EXPR_OR_ANON_FUNC_PARAM_RHS, + ANON_FUNC_PARAM_RHS -> ParserRuleContext.CLOSE_PARENTHESIS; + case PARAM_END -> ParserRuleContext.CLOSE_PARENTHESIS; + case ANNOTATION_REF_RHS -> ParserRuleContext.ANNOTATION_END; + case INFER_PARAM_END_OR_PARENTHESIS_END -> ParserRuleContext.CLOSE_PARENTHESIS; + case TYPE_DESC_IN_TUPLE_RHS -> ParserRuleContext.CLOSE_BRACKET; + case TUPLE_TYPE_MEMBER_RHS -> ParserRuleContext.CLOSE_BRACKET; + case LIST_CONSTRUCTOR_MEMBER_END -> ParserRuleContext.CLOSE_BRACKET; + case NIL_OR_PARENTHESISED_TYPE_DESC_RHS -> ParserRuleContext.CLOSE_PARENTHESIS; + case REMOTE_OR_RESOURCE_CALL_OR_ASYNC_SEND_RHS -> ParserRuleContext.PEER_WORKER_NAME; + case REMOTE_CALL_OR_ASYNC_SEND_END -> ParserRuleContext.SEMICOLON; + case RECEIVE_WORKERS, + RECEIVE_FIELD -> ParserRuleContext.PEER_WORKER_NAME; + case RECEIVE_FIELD_END -> ParserRuleContext.CLOSE_BRACE; + case WAIT_KEYWORD_RHS -> ParserRuleContext.MULTI_WAIT_FIELDS; + case WAIT_FIELD_NAME_RHS -> ParserRuleContext.WAIT_FIELD_END; + case WAIT_FIELD_END -> ParserRuleContext.CLOSE_BRACE; + case WAIT_FUTURE_EXPR_END -> ParserRuleContext.ALTERNATE_WAIT_EXPR_LIST_END; + case OPTIONAL_PEER_WORKER -> ParserRuleContext.EXPRESSION_RHS; + case ENUM_MEMBER_START -> ParserRuleContext.ENUM_MEMBER_NAME; + case ENUM_MEMBER_RHS -> ParserRuleContext.ENUM_MEMBER_END; + case ENUM_MEMBER_END -> ParserRuleContext.CLOSE_BRACE; + case MEMBER_ACCESS_KEY_EXPR_END -> ParserRuleContext.CLOSE_BRACKET; + case ROLLBACK_RHS -> ParserRuleContext.SEMICOLON; + case RETRY_KEYWORD_RHS -> ParserRuleContext.RETRY_TYPE_PARAM_RHS; + case RETRY_TYPE_PARAM_RHS -> ParserRuleContext.RETRY_BODY; + case RETRY_BODY -> ParserRuleContext.BLOCK_STMT; + case STMT_START_BRACKETED_LIST_MEMBER -> ParserRuleContext.TYPE_DESCRIPTOR; + case STMT_START_BRACKETED_LIST_RHS -> ParserRuleContext.VARIABLE_NAME; + case BINDING_PATTERN_OR_EXPR_RHS, + BRACKETED_LIST_RHS -> ParserRuleContext.TYPE_DESC_RHS_OR_BP_RHS; + case BRACKETED_LIST_MEMBER -> ParserRuleContext.EXPRESSION; + case BRACKETED_LIST_MEMBER_END -> ParserRuleContext.CLOSE_BRACKET; + case TYPE_DESC_RHS_OR_BP_RHS -> ParserRuleContext.TYPE_DESC_RHS_IN_TYPED_BP; + case LIST_BINDING_MEMBER_OR_ARRAY_LENGTH -> ParserRuleContext.BINDING_PATTERN; + case XML_NAVIGATE_EXPR -> ParserRuleContext.XML_FILTER_EXPR; + case XML_NAME_PATTERN_RHS -> ParserRuleContext.GT; + case XML_ATOMIC_NAME_PATTERN_START -> ParserRuleContext.XML_ATOMIC_NAME_IDENTIFIER; + case XML_ATOMIC_NAME_IDENTIFIER_RHS -> ParserRuleContext.IDENTIFIER; + case XML_STEP_START -> ParserRuleContext.SLASH_ASTERISK_TOKEN; + case FUNC_TYPE_DESC_RHS_OR_ANON_FUNC_BODY -> ParserRuleContext.ANON_FUNC_BODY; + case OPTIONAL_MATCH_GUARD -> ParserRuleContext.RIGHT_DOUBLE_ARROW; + case MATCH_PATTERN_LIST_MEMBER_RHS -> ParserRuleContext.MATCH_PATTERN_END; + case MATCH_PATTERN_START -> ParserRuleContext.CONSTANT_EXPRESSION; + case LIST_MATCH_PATTERNS_START -> ParserRuleContext.CLOSE_BRACKET; + case LIST_MATCH_PATTERN_MEMBER -> ParserRuleContext.MATCH_PATTERN_START; + case LIST_MATCH_PATTERN_MEMBER_RHS -> ParserRuleContext.CLOSE_BRACKET; + case ERROR_BINDING_PATTERN_ERROR_KEYWORD_RHS -> ParserRuleContext.OPEN_PARENTHESIS; + case ERROR_ARG_LIST_BINDING_PATTERN_START, + ERROR_MESSAGE_BINDING_PATTERN_END -> ParserRuleContext.CLOSE_PARENTHESIS; + case ERROR_MESSAGE_BINDING_PATTERN_RHS -> ParserRuleContext.ERROR_CAUSE_SIMPLE_BINDING_PATTERN; + case ERROR_FIELD_BINDING_PATTERN -> ParserRuleContext.NAMED_ARG_BINDING_PATTERN; + case ERROR_FIELD_BINDING_PATTERN_END -> ParserRuleContext.CLOSE_PARENTHESIS; + case FIELD_MATCH_PATTERNS_START -> ParserRuleContext.CLOSE_BRACE; + case FIELD_MATCH_PATTERN_MEMBER -> ParserRuleContext.VARIABLE_NAME; + case FIELD_MATCH_PATTERN_MEMBER_RHS -> ParserRuleContext.CLOSE_BRACE; + case ERROR_MATCH_PATTERN_OR_CONST_PATTERN -> ParserRuleContext.MATCH_PATTERN_RHS; + case ERROR_MATCH_PATTERN_ERROR_KEYWORD_RHS -> ParserRuleContext.OPEN_PARENTHESIS; + case ERROR_ARG_LIST_MATCH_PATTERN_START, + ERROR_MESSAGE_MATCH_PATTERN_END -> ParserRuleContext.CLOSE_PARENTHESIS; + case ERROR_MESSAGE_MATCH_PATTERN_RHS -> ParserRuleContext.ERROR_CAUSE_MATCH_PATTERN; + case ERROR_FIELD_MATCH_PATTERN -> ParserRuleContext.NAMED_ARG_MATCH_PATTERN; + case ERROR_FIELD_MATCH_PATTERN_RHS -> ParserRuleContext.CLOSE_PARENTHESIS; + case NAMED_ARG_MATCH_PATTERN_RHS -> ParserRuleContext.NAMED_ARG_MATCH_PATTERN; + case EXTERNAL_FUNC_BODY_OPTIONAL_ANNOTS -> ParserRuleContext.EXTERNAL_KEYWORD; + case LIST_BP_OR_LIST_CONSTRUCTOR_MEMBER -> ParserRuleContext.LIST_BINDING_PATTERN_MEMBER; + case TUPLE_TYPE_DESC_OR_LIST_CONST_MEMBER -> ParserRuleContext.TYPE_DESCRIPTOR; + case OBJECT_METHOD_WITHOUT_FIRST_QUALIFIER, + OBJECT_METHOD_WITHOUT_SECOND_QUALIFIER, + OBJECT_METHOD_WITHOUT_THIRD_QUALIFIER, + FUNC_DEF -> ParserRuleContext.FUNC_DEF_OR_FUNC_TYPE; + case JOIN_CLAUSE_START -> ParserRuleContext.JOIN_KEYWORD; + case INTERMEDIATE_CLAUSE_START -> ParserRuleContext.WHERE_CLAUSE; + case MAPPING_BP_OR_MAPPING_CONSTRUCTOR_MEMBER -> ParserRuleContext.MAPPING_BINDING_PATTERN_MEMBER; + case TYPE_DESC_OR_EXPR_RHS -> ParserRuleContext.TYPE_DESC_RHS_OR_BP_RHS; + case LISTENERS_LIST_END -> ParserRuleContext.OBJECT_CONSTRUCTOR_BLOCK; + case REGULAR_COMPOUND_STMT_RHS -> ParserRuleContext.STATEMENT; + case NAMED_WORKER_DECL_START -> ParserRuleContext.WORKER_KEYWORD; + case FUNC_TYPE_DESC_START, + FUNC_DEF_START, + ANON_FUNC_EXPRESSION_START -> ParserRuleContext.FUNCTION_KEYWORD; + case MODULE_CLASS_DEFINITION_START -> ParserRuleContext.CLASS_KEYWORD; + case OBJECT_CONSTRUCTOR_TYPE_REF -> ParserRuleContext.OPEN_BRACE; + case OBJECT_FIELD_QUALIFIER -> ParserRuleContext.TYPE_DESC_BEFORE_IDENTIFIER; + case OPTIONAL_SERVICE_DECL_TYPE -> ParserRuleContext.OPTIONAL_ABSOLUTE_PATH; + case SERVICE_IDENT_RHS -> ParserRuleContext.ATTACH_POINT_END; + case ABSOLUTE_RESOURCE_PATH_START -> ParserRuleContext.ABSOLUTE_PATH_SINGLE_SLASH; + case ABSOLUTE_RESOURCE_PATH_END -> ParserRuleContext.SERVICE_DECL_RHS; + case SERVICE_DECL_OR_VAR_DECL -> ParserRuleContext.SERVICE_VAR_DECL_RHS; + case OPTIONAL_RELATIVE_PATH -> ParserRuleContext.OPEN_PARENTHESIS; + case RELATIVE_RESOURCE_PATH_START -> ParserRuleContext.DOT; + case RELATIVE_RESOURCE_PATH_END -> ParserRuleContext.RESOURCE_ACCESSOR_DEF_OR_DECL_RHS; + case RESOURCE_PATH_SEGMENT -> ParserRuleContext.PATH_SEGMENT_IDENT; + case PATH_PARAM_OPTIONAL_ANNOTS -> ParserRuleContext.TYPE_DESC_IN_PATH_PARAM; + case PATH_PARAM_ELLIPSIS, + OPTIONAL_PATH_PARAM_NAME -> ParserRuleContext.CLOSE_BRACKET; + case OBJECT_CONS_WITHOUT_FIRST_QUALIFIER, + OBJECT_TYPE_WITHOUT_FIRST_QUALIFIER -> ParserRuleContext.OBJECT_KEYWORD; + case CONFIG_VAR_DECL_RHS -> ParserRuleContext.EXPRESSION; + case SERVICE_DECL_START -> ParserRuleContext.SERVICE_KEYWORD; + case ERROR_CONSTRUCTOR_RHS -> ParserRuleContext.ARG_LIST_OPEN_PAREN; + case OPTIONAL_TYPE_PARAMETER -> ParserRuleContext.TYPE_DESC_RHS; + case MAP_TYPE_OR_TYPE_REF -> ParserRuleContext.LT; + case OBJECT_TYPE_OR_TYPE_REF -> ParserRuleContext.OBJECT_TYPE_OBJECT_KEYWORD_RHS; + case STREAM_TYPE_OR_TYPE_REF -> ParserRuleContext.LT; + case TABLE_TYPE_OR_TYPE_REF -> ParserRuleContext.ROW_TYPE_PARAM; + case PARAMETERIZED_TYPE_OR_TYPE_REF -> ParserRuleContext.OPTIONAL_TYPE_PARAMETER; + case TYPE_DESC_RHS_OR_TYPE_REF -> ParserRuleContext.TYPE_DESC_RHS; + case TRANSACTION_STMT_RHS_OR_TYPE_REF -> ParserRuleContext.TRANSACTION_STMT_TRANSACTION_KEYWORD_RHS; + case TABLE_CONS_OR_QUERY_EXPR_OR_VAR_REF -> ParserRuleContext.EXPRESSION_START_TABLE_KEYWORD_RHS; + case QUERY_EXPR_OR_VAR_REF -> ParserRuleContext.QUERY_CONSTRUCT_TYPE_RHS; + case ERROR_CONS_EXPR_OR_VAR_REF -> ParserRuleContext.ERROR_CONS_ERROR_KEYWORD_RHS; + case QUALIFIED_IDENTIFIER -> ParserRuleContext.QUALIFIED_IDENTIFIER_START_IDENTIFIER; + case CLASS_DEF_WITHOUT_FIRST_QUALIFIER, + CLASS_DEF_WITHOUT_SECOND_QUALIFIER, + CLASS_DEF_WITHOUT_THIRD_QUALIFIER -> ParserRuleContext.CLASS_KEYWORD; + case FUNC_DEF_WITHOUT_FIRST_QUALIFIER -> ParserRuleContext.FUNC_DEF_OR_FUNC_TYPE; + case FUNC_TYPE_DESC_START_WITHOUT_FIRST_QUAL -> ParserRuleContext.FUNCTION_KEYWORD; + case MODULE_VAR_DECL_START, + MODULE_VAR_WITHOUT_FIRST_QUAL, + MODULE_VAR_WITHOUT_SECOND_QUAL -> ParserRuleContext.VAR_DECL_STMT; + case FUNC_DEF_OR_TYPE_DESC_RHS -> ParserRuleContext.SEMICOLON; + case CLASS_DESCRIPTOR -> ParserRuleContext.TYPE_REFERENCE; + case EXPR_START_OR_INFERRED_TYPEDESC_DEFAULT_START -> ParserRuleContext.EXPRESSION; + case TYPE_CAST_PARAM_START_OR_INFERRED_TYPEDESC_DEFAULT_END -> + ParserRuleContext.INFERRED_TYPEDESC_DEFAULT_END_GT; + case END_OF_PARAMS_OR_NEXT_PARAM_START -> ParserRuleContext.CLOSE_PARENTHESIS; + case ASSIGNMENT_STMT_RHS -> ParserRuleContext.ASSIGN_OP; + case PARAM_START -> ParserRuleContext.TYPE_DESC_IN_PARAM; + case PARAM_RHS -> ParserRuleContext.VARIABLE_NAME; + case FUNC_TYPE_PARAM_RHS -> ParserRuleContext.PARAM_END; + case ANNOTATION_DECL_START -> ParserRuleContext.ANNOTATION_KEYWORD; + case OPTIONAL_RESOURCE_ACCESS_PATH, + RESOURCE_ACCESS_SEGMENT_RHS -> ParserRuleContext.OPTIONAL_RESOURCE_ACCESS_METHOD; + case RESOURCE_ACCESS_PATH_SEGMENT -> ParserRuleContext.IDENTIFIER; + case COMPUTED_SEGMENT_OR_REST_SEGMENT -> ParserRuleContext.EXPRESSION; + case OPTIONAL_RESOURCE_ACCESS_METHOD -> ParserRuleContext.OPTIONAL_RESOURCE_ACCESS_ACTION_ARG_LIST; + case OPTIONAL_RESOURCE_ACCESS_ACTION_ARG_LIST -> ParserRuleContext.ACTION_END; + case OPTIONAL_TOP_LEVEL_SEMICOLON -> ParserRuleContext.TOP_LEVEL_NODE; + case TUPLE_MEMBER -> ParserRuleContext.TYPE_DESC_IN_TUPLE; + case RESULT_CLAUSE -> ParserRuleContext.SELECT_CLAUSE; + case SINGLE_OR_ALTERNATE_WORKER_SEPARATOR -> ParserRuleContext.SINGLE_OR_ALTERNATE_WORKER_END; + default -> throw new IllegalStateException("Alternative path entry not found"); + }; + } + + private Result seekMatchInAlternativePaths(ParserRuleContext currentCtx, int lookahead, int currentDepth, + int matchingRulesCount, boolean isEntryPoint) { + ParserRuleContext[] alternativeRules; switch (currentCtx) { case TOP_LEVEL_NODE: + alternativeRules = TOP_LEVEL_NODE; + break; case TOP_LEVEL_NODE_WITHOUT_MODIFIER: + alternativeRules = TOP_LEVEL_NODE_WITHOUT_MODIFIER; + break; case TOP_LEVEL_NODE_WITHOUT_METADATA: + alternativeRules = TOP_LEVEL_NODE_WITHOUT_METADATA; + break; + case FUNC_DEF_START: + alternativeRules = FUNC_DEF_START; + break; + case FUNC_DEF_WITHOUT_FIRST_QUALIFIER: + alternativeRules = FUNC_DEF_WITHOUT_FIRST_QUALIFIER; + break; + case FUNC_TYPE_DESC_START_WITHOUT_FIRST_QUAL: + alternativeRules = FUNC_TYPE_DESC_START_WITHOUT_FIRST_QUAL; + break; case FUNC_OPTIONAL_RETURNS: + ParserRuleContext parentCtx = getParentContext(); + ParserRuleContext[] alternatives; + if (parentCtx == ParserRuleContext.FUNC_DEF) { + ParserRuleContext grandParentCtx = getGrandParentContext(); + if (grandParentCtx == ParserRuleContext.OBJECT_TYPE_MEMBER) { + alternatives = METHOD_DECL_OPTIONAL_RETURNS; + } else { + alternatives = FUNC_DEF_OPTIONAL_RETURNS; + } + } else if (parentCtx == ParserRuleContext.ANON_FUNC_EXPRESSION) { + alternatives = ANNON_FUNC_OPTIONAL_RETURNS; + } else if (parentCtx == ParserRuleContext.FUNC_TYPE_DESC) { + alternatives = FUNC_TYPE_OPTIONAL_RETURNS; + } else if (parentCtx == ParserRuleContext.FUNC_TYPE_DESC_OR_ANON_FUNC) { + alternatives = FUNC_TYPE_OR_ANON_FUNC_OPTIONAL_RETURNS; + } else { + alternatives = FUNC_TYPE_OR_DEF_OPTIONAL_RETURNS; + } + + alternativeRules = alternatives; + break; case FUNC_BODY_OR_TYPE_DESC_RHS: + alternativeRules = FUNC_BODY_OR_TYPE_DESC_RHS; + break; + case FUNC_TYPE_DESC_RHS_OR_ANON_FUNC_BODY: + alternativeRules = FUNC_TYPE_DESC_RHS_OR_ANON_FUNC_BODY; + break; case ANON_FUNC_BODY: + alternativeRules = ANON_FUNC_BODY; + break; case FUNC_BODY: - case EXPRESSION: - case TERMINAL_EXPRESSION: - case VAR_DECL_STMT_RHS: - case EXPRESSION_RHS: - case VARIABLE_REF_RHS: - case STATEMENT: - case STATEMENT_WITHOUT_ANNOTS: + alternativeRules = FUNC_BODY; + break; case PARAM_LIST: + alternativeRules = PARAM_LIST; + break; case REQUIRED_PARAM_NAME_RHS: - case TYPE_NAME_OR_VAR_NAME: + alternativeRules = REQUIRED_PARAM_NAME_RHS; + break; case FIELD_DESCRIPTOR_RHS: + alternativeRules = FIELD_DESCRIPTOR_RHS; + break; case FIELD_OR_REST_DESCIPTOR_RHS: + alternativeRules = FIELD_OR_REST_DESCIPTOR_RHS; + break; case RECORD_BODY_END: + alternativeRules = RECORD_BODY_END; + break; case RECORD_BODY_START: + alternativeRules = RECORD_BODY_START; + break; case TYPE_DESCRIPTOR: + assert isInTypeDescContext(); + alternativeRules = TYPE_DESCRIPTORS; + break; case TYPE_DESC_WITHOUT_ISOLATED: + alternativeRules = TYPE_DESCRIPTOR_WITHOUT_ISOLATED; + break; + case CLASS_DESCRIPTOR: + alternativeRules = CLASS_DESCRIPTOR; + break; case RECORD_FIELD_OR_RECORD_END: + alternativeRules = RECORD_FIELD_OR_RECORD_END; + break; case RECORD_FIELD_START: + alternativeRules = RECORD_FIELD_START; + break; case RECORD_FIELD_WITHOUT_METADATA: - case ARG_START: - case ARG_START_OR_ARG_LIST_END: - case NAMED_OR_POSITIONAL_ARG_RHS: - case ARG_END: + alternativeRules = RECORD_FIELD_WITHOUT_METADATA; + break; case CLASS_MEMBER_OR_OBJECT_MEMBER_START: + alternativeRules = CLASS_MEMBER_OR_OBJECT_MEMBER_START; + break; case OBJECT_CONSTRUCTOR_MEMBER_START: + alternativeRules = OBJECT_CONSTRUCTOR_MEMBER_START; + break; case CLASS_MEMBER_OR_OBJECT_MEMBER_WITHOUT_META: + alternativeRules = CLASS_MEMBER_OR_OBJECT_MEMBER_WITHOUT_META; + break; case OBJECT_CONS_MEMBER_WITHOUT_META: + alternativeRules = OBJECT_CONS_MEMBER_WITHOUT_META; + break; case OPTIONAL_FIELD_INITIALIZER: + alternativeRules = OPTIONAL_FIELD_INITIALIZER; + break; + case ON_FAIL_OPTIONAL_BINDING_PATTERN: + alternativeRules = ON_FAIL_OPTIONAL_BINDING_PATTERN; + break; case OBJECT_METHOD_START: + alternativeRules = OBJECT_METHOD_START; + break; + case OBJECT_METHOD_WITHOUT_FIRST_QUALIFIER: + alternativeRules = OBJECT_METHOD_WITHOUT_FIRST_QUALIFIER; + break; + case OBJECT_METHOD_WITHOUT_SECOND_QUALIFIER: + alternativeRules = OBJECT_METHOD_WITHOUT_SECOND_QUALIFIER; + break; + case OBJECT_METHOD_WITHOUT_THIRD_QUALIFIER: + alternativeRules = OBJECT_METHOD_WITHOUT_THIRD_QUALIFIER; + break; case OBJECT_FUNC_OR_FIELD: + alternativeRules = OBJECT_FUNC_OR_FIELD; + break; case OBJECT_FUNC_OR_FIELD_WITHOUT_VISIBILITY: + alternativeRules = OBJECT_FUNC_OR_FIELD_WITHOUT_VISIBILITY; + break; case OBJECT_TYPE_START: + alternativeRules = OBJECT_TYPE_START; + break; case OBJECT_CONSTRUCTOR_START: - case ELSE_BLOCK: - case ELSE_BODY: - case CALL_STMT_START: + alternativeRules = OBJECT_CONSTRUCTOR_START; + break; case IMPORT_PREFIX_DECL: + alternativeRules = IMPORT_PREFIX_DECL; + break; case IMPORT_DECL_ORG_OR_MODULE_NAME_RHS: + alternativeRules = IMPORT_DECL_ORG_OR_MODULE_NAME_RHS; + break; case AFTER_IMPORT_MODULE_NAME: - case RETURN_STMT_RHS: - case ACCESS_EXPRESSION: - case FIRST_MAPPING_FIELD: - case MAPPING_FIELD: - case SPECIFIC_FIELD: - case SPECIFIC_FIELD_RHS: - case MAPPING_FIELD_END: + alternativeRules = AFTER_IMPORT_MODULE_NAME; + break; case OPTIONAL_ABSOLUTE_PATH: + alternativeRules = OPTIONAL_ABSOLUTE_PATH; + break; case CONST_DECL_TYPE: + alternativeRules = CONST_DECL_TYPE; + break; case CONST_DECL_RHS: - case ARRAY_LENGTH: + alternativeRules = CONST_DECL_RHS; + break; case PARAMETER_START: + alternativeRules = PARAMETER_START; + break; case PARAMETER_START_WITHOUT_ANNOTATION: - case STMT_START_WITH_EXPR_RHS: - case EXPR_STMT_RHS: - case EXPRESSION_STATEMENT_START: + alternativeRules = PARAMETER_START_WITHOUT_ANNOTATION; + break; case ANNOT_DECL_OPTIONAL_TYPE: + alternativeRules = ANNOT_DECL_OPTIONAL_TYPE; + break; case ANNOT_DECL_RHS: + alternativeRules = ANNOT_DECL_RHS; + break; case ANNOT_OPTIONAL_ATTACH_POINTS: + alternativeRules = ANNOT_OPTIONAL_ATTACH_POINTS; + break; case ATTACH_POINT: + alternativeRules = ATTACH_POINT; + break; case ATTACH_POINT_IDENT: + alternativeRules = ATTACH_POINT_IDENT; + break; case ATTACH_POINT_END: + alternativeRules = ATTACH_POINT_END; + break; case XML_NAMESPACE_PREFIX_DECL: - case CONSTANT_EXPRESSION_START: - case TYPE_DESC_RHS: - case LIST_CONSTRUCTOR_FIRST_MEMBER: - case LIST_CONSTRUCTOR_MEMBER: - case TYPE_CAST_PARAM: - case TYPE_CAST_PARAM_RHS: - case TABLE_KEYWORD_RHS: - case ROW_LIST_RHS: - case TABLE_ROW_END: - case KEY_SPECIFIER_RHS: - case TABLE_KEY_RHS: - case LET_VAR_DECL_START: - case ORDER_KEY_LIST_END: - case STREAM_TYPE_FIRST_PARAM_RHS: - case TEMPLATE_MEMBER: - case TEMPLATE_STRING_RHS: - case FUNCTION_KEYWORD_RHS: - case FUNC_TYPE_FUNC_KEYWORD_RHS_START: - case WORKER_NAME_RHS: - case BINDING_PATTERN: - case LIST_BINDING_PATTERNS_START: - case LIST_BINDING_PATTERN_MEMBER_END: - case FIELD_BINDING_PATTERN_END: - case LIST_BINDING_PATTERN_MEMBER: - case MAPPING_BINDING_PATTERN_END: - case MAPPING_BINDING_PATTERN_MEMBER: - case KEY_CONSTRAINTS_RHS: - case TABLE_TYPE_DESC_RHS: - case NEW_KEYWORD_RHS: - case TABLE_CONSTRUCTOR_OR_QUERY_START: - case TABLE_CONSTRUCTOR_OR_QUERY_RHS: - case QUERY_PIPELINE_RHS: - case BRACED_EXPR_OR_ANON_FUNC_PARAM_RHS: - case ANON_FUNC_PARAM_RHS: - case PARAM_END: - case ANNOTATION_REF_RHS: - case INFER_PARAM_END_OR_PARENTHESIS_END: - case TYPE_DESC_IN_TUPLE_RHS: - case TUPLE_TYPE_MEMBER_RHS: - case LIST_CONSTRUCTOR_MEMBER_END: - case NIL_OR_PARENTHESISED_TYPE_DESC_RHS: - case REMOTE_OR_RESOURCE_CALL_OR_ASYNC_SEND_RHS: - case REMOTE_CALL_OR_ASYNC_SEND_END: - case RECEIVE_WORKERS: - case RECEIVE_FIELD: - case RECEIVE_FIELD_END: - case WAIT_KEYWORD_RHS: - case WAIT_FIELD_NAME_RHS: - case WAIT_FIELD_END: - case WAIT_FUTURE_EXPR_END: - case OPTIONAL_PEER_WORKER: + alternativeRules = XML_NAMESPACE_PREFIX_DECL; + break; case ENUM_MEMBER_START: + alternativeRules = ENUM_MEMBER_START; + break; case ENUM_MEMBER_RHS: + alternativeRules = ENUM_MEMBER_RHS; + break; case ENUM_MEMBER_END: - case MEMBER_ACCESS_KEY_EXPR_END: - case ROLLBACK_RHS: - case RETRY_KEYWORD_RHS: - case RETRY_TYPE_PARAM_RHS: - case RETRY_BODY: - case STMT_START_BRACKETED_LIST_MEMBER: - case STMT_START_BRACKETED_LIST_RHS: - case BINDING_PATTERN_OR_EXPR_RHS: - case BINDING_PATTERN_OR_VAR_REF_RHS: - case BRACKETED_LIST_RHS: - case BRACKETED_LIST_MEMBER: - case BRACKETED_LIST_MEMBER_END: - case TYPE_DESC_RHS_OR_BP_RHS: - case LIST_BINDING_MEMBER_OR_ARRAY_LENGTH: - case XML_NAVIGATE_EXPR: - case XML_NAME_PATTERN_RHS: - case XML_ATOMIC_NAME_PATTERN_START: - case XML_ATOMIC_NAME_IDENTIFIER_RHS: - case XML_STEP_START: - case FUNC_TYPE_DESC_RHS_OR_ANON_FUNC_BODY: - case OPTIONAL_MATCH_GUARD: - case MATCH_PATTERN_LIST_MEMBER_RHS: - case MATCH_PATTERN_START: - case LIST_MATCH_PATTERNS_START: - case LIST_MATCH_PATTERN_MEMBER: - case LIST_MATCH_PATTERN_MEMBER_RHS: - case ERROR_BINDING_PATTERN_ERROR_KEYWORD_RHS: - case ERROR_ARG_LIST_BINDING_PATTERN_START: - case ERROR_MESSAGE_BINDING_PATTERN_END: - case ERROR_MESSAGE_BINDING_PATTERN_RHS: - case ERROR_FIELD_BINDING_PATTERN: - case ERROR_FIELD_BINDING_PATTERN_END: - case FIELD_MATCH_PATTERNS_START: - case FIELD_MATCH_PATTERN_MEMBER: - case FIELD_MATCH_PATTERN_MEMBER_RHS: - case ERROR_MATCH_PATTERN_OR_CONST_PATTERN: - case ERROR_MATCH_PATTERN_ERROR_KEYWORD_RHS: - case ERROR_ARG_LIST_MATCH_PATTERN_START: - case ERROR_MESSAGE_MATCH_PATTERN_END: - case ERROR_MESSAGE_MATCH_PATTERN_RHS: - case ERROR_FIELD_MATCH_PATTERN: - case ERROR_FIELD_MATCH_PATTERN_RHS: - case NAMED_ARG_MATCH_PATTERN_RHS: + alternativeRules = ENUM_MEMBER_END; + break; case EXTERNAL_FUNC_BODY_OPTIONAL_ANNOTS: + alternativeRules = EXTERNAL_FUNC_BODY_OPTIONAL_ANNOTS; + break; case LIST_BP_OR_LIST_CONSTRUCTOR_MEMBER: + alternativeRules = LIST_BP_OR_LIST_CONSTRUCTOR_MEMBER; + break; case TUPLE_TYPE_DESC_OR_LIST_CONST_MEMBER: - case OBJECT_METHOD_WITHOUT_FIRST_QUALIFIER: - case OBJECT_METHOD_WITHOUT_SECOND_QUALIFIER: - case OBJECT_METHOD_WITHOUT_THIRD_QUALIFIER: - case JOIN_CLAUSE_START: - case INTERMEDIATE_CLAUSE_START: + alternativeRules = TUPLE_TYPE_DESC_OR_LIST_CONST_MEMBER; + break; case MAPPING_BP_OR_MAPPING_CONSTRUCTOR_MEMBER: - case TYPE_DESC_OR_EXPR_RHS: - case LISTENERS_LIST_END: - case REGULAR_COMPOUND_STMT_RHS: - case NAMED_WORKER_DECL_START: + alternativeRules = MAPPING_BP_OR_MAPPING_CONSTRUCTOR_MEMBER; + break; case FUNC_TYPE_DESC_START: case ANON_FUNC_EXPRESSION_START: + alternativeRules = FUNC_TYPE_DESC_START; + break; case MODULE_CLASS_DEFINITION_START: + alternativeRules = MODULE_CLASS_DEFINITION_START; + break; + case CLASS_DEF_WITHOUT_FIRST_QUALIFIER: + alternativeRules = CLASS_DEF_WITHOUT_FIRST_QUALIFIER; + break; + case CLASS_DEF_WITHOUT_SECOND_QUALIFIER: + alternativeRules = CLASS_DEF_WITHOUT_SECOND_QUALIFIER; + break; + case CLASS_DEF_WITHOUT_THIRD_QUALIFIER: + alternativeRules = CLASS_DEF_WITHOUT_THIRD_QUALIFIER; + break; case OBJECT_CONSTRUCTOR_TYPE_REF: + alternativeRules = OBJECT_CONSTRUCTOR_RHS; + break; case OBJECT_FIELD_QUALIFIER: + alternativeRules = OBJECT_FIELD_QUALIFIER; + break; + case CONFIG_VAR_DECL_RHS: + alternativeRules = CONFIG_VAR_DECL_RHS; + break; case OPTIONAL_SERVICE_DECL_TYPE: + alternativeRules = OPTIONAL_SERVICE_DECL_TYPE; + break; case SERVICE_IDENT_RHS: + alternativeRules = SERVICE_IDENT_RHS; + break; case ABSOLUTE_RESOURCE_PATH_START: + alternativeRules = ABSOLUTE_RESOURCE_PATH_START; + break; case ABSOLUTE_RESOURCE_PATH_END: + alternativeRules = ABSOLUTE_RESOURCE_PATH_END; + break; case SERVICE_DECL_OR_VAR_DECL: + alternativeRules = SERVICE_DECL_OR_VAR_DECL; + break; case OPTIONAL_RELATIVE_PATH: + alternativeRules = OPTIONAL_RELATIVE_PATH; + break; case RELATIVE_RESOURCE_PATH_START: - case RELATIVE_RESOURCE_PATH_END: + alternativeRules = RELATIVE_RESOURCE_PATH_START; + break; case RESOURCE_PATH_SEGMENT: + alternativeRules = RESOURCE_PATH_SEGMENT; + break; case PATH_PARAM_OPTIONAL_ANNOTS: + alternativeRules = PATH_PARAM_OPTIONAL_ANNOTS; + break; case PATH_PARAM_ELLIPSIS: + alternativeRules = PATH_PARAM_ELLIPSIS; + break; case OPTIONAL_PATH_PARAM_NAME: - case OBJECT_CONS_WITHOUT_FIRST_QUALIFIER: - case OBJECT_TYPE_WITHOUT_FIRST_QUALIFIER: - case CONFIG_VAR_DECL_RHS: + alternativeRules = OPTIONAL_PATH_PARAM_NAME; + break; + case RELATIVE_RESOURCE_PATH_END: + alternativeRules = RELATIVE_RESOURCE_PATH_END; + break; case SERVICE_DECL_START: - case ERROR_CONSTRUCTOR_RHS: + alternativeRules = SERVICE_DECL_START; + break; case OPTIONAL_TYPE_PARAMETER: + alternativeRules = OPTIONAL_TYPE_PARAMETER; + break; case MAP_TYPE_OR_TYPE_REF: + alternativeRules = MAP_TYPE_OR_TYPE_REF; + break; case OBJECT_TYPE_OR_TYPE_REF: + alternativeRules = OBJECT_TYPE_OR_TYPE_REF; + break; case STREAM_TYPE_OR_TYPE_REF: + alternativeRules = STREAM_TYPE_OR_TYPE_REF; + break; case TABLE_TYPE_OR_TYPE_REF: + alternativeRules = TABLE_TYPE_OR_TYPE_REF; + break; case PARAMETERIZED_TYPE_OR_TYPE_REF: + alternativeRules = PARAMETERIZED_TYPE_OR_TYPE_REF; + break; case TYPE_DESC_RHS_OR_TYPE_REF: + alternativeRules = TYPE_DESC_RHS_OR_TYPE_REF; + break; case TRANSACTION_STMT_RHS_OR_TYPE_REF: + alternativeRules = TRANSACTION_STMT_RHS_OR_TYPE_REF; + break; case TABLE_CONS_OR_QUERY_EXPR_OR_VAR_REF: + alternativeRules = TABLE_CONS_OR_QUERY_EXPR_OR_VAR_REF; + break; case QUERY_EXPR_OR_VAR_REF: + alternativeRules = QUERY_EXPR_OR_VAR_REF; + break; case ERROR_CONS_EXPR_OR_VAR_REF: + alternativeRules = ERROR_CONS_EXPR_OR_VAR_REF; + break; case QUALIFIED_IDENTIFIER: - case CLASS_DEF_WITHOUT_FIRST_QUALIFIER: - case CLASS_DEF_WITHOUT_SECOND_QUALIFIER: - case CLASS_DEF_WITHOUT_THIRD_QUALIFIER: - case FUNC_DEF_START: - case FUNC_DEF_WITHOUT_FIRST_QUALIFIER: - case FUNC_TYPE_DESC_START_WITHOUT_FIRST_QUAL: + alternativeRules = QUALIFIED_IDENTIFIER; + break; case MODULE_VAR_DECL_START: + alternativeRules = MODULE_VAR_DECL_START; + break; case MODULE_VAR_WITHOUT_FIRST_QUAL: + alternativeRules = MODULE_VAR_WITHOUT_FIRST_QUAL; + break; case MODULE_VAR_WITHOUT_SECOND_QUAL: + alternativeRules = MODULE_VAR_WITHOUT_SECOND_QUAL; + break; + case OBJECT_TYPE_WITHOUT_FIRST_QUALIFIER: + alternativeRules = OBJECT_TYPE_WITHOUT_FIRST_QUALIFIER; + break; case FUNC_DEF_OR_TYPE_DESC_RHS: - case CLASS_DESCRIPTOR: + alternativeRules = FUNC_DEF_OR_TYPE_DESC_RHS; + break; case EXPR_START_OR_INFERRED_TYPEDESC_DEFAULT_START: + alternativeRules = EXPR_START_OR_INFERRED_TYPEDESC_DEFAULT_START; + break; case TYPE_CAST_PARAM_START_OR_INFERRED_TYPEDESC_DEFAULT_END: + alternativeRules = TYPE_CAST_PARAM_START_OR_INFERRED_TYPEDESC_DEFAULT_END; + break; case END_OF_PARAMS_OR_NEXT_PARAM_START: - case ASSIGNMENT_STMT_RHS: + alternativeRules = END_OF_PARAMS_OR_NEXT_PARAM_START; + break; case PARAM_START: + alternativeRules = PARAM_START; + break; case PARAM_RHS: + alternativeRules = PARAM_RHS; + break; case FUNC_TYPE_PARAM_RHS: + alternativeRules = FUNC_TYPE_PARAM_RHS; + break; case ANNOTATION_DECL_START: - case ON_FAIL_OPTIONAL_BINDING_PATTERN: - case OPTIONAL_RESOURCE_ACCESS_PATH: - case RESOURCE_ACCESS_PATH_SEGMENT: - case COMPUTED_SEGMENT_OR_REST_SEGMENT: - case RESOURCE_ACCESS_SEGMENT_RHS: - case OPTIONAL_RESOURCE_ACCESS_METHOD: - case OPTIONAL_RESOURCE_ACCESS_ACTION_ARG_LIST: + alternativeRules = ANNOTATION_DECL_START; + break; case OPTIONAL_TOP_LEVEL_SEMICOLON: + alternativeRules = OPTIONAL_TOP_LEVEL_SEMICOLON; + break; case TUPLE_MEMBER: - case GROUPING_KEY_LIST_ELEMENT: - case GROUPING_KEY_LIST_ELEMENT_END: - case RESULT_CLAUSE: - case SINGLE_OR_ALTERNATE_WORKER_SEPARATOR: - return true; + alternativeRules = TUPLE_MEMBER; + break; default: - return false; + return seekMatchInStmtRelatedAlternativePaths(currentCtx, lookahead, currentDepth, matchingRulesCount, + isEntryPoint); } + + return seekInAlternativesPaths(lookahead, currentDepth, matchingRulesCount, alternativeRules, isEntryPoint); } - /** - * Returns the shortest alternative path for a parser rule with alternatives. - * - * @param currentCtx Parser rule with alternatives - * @return shortest alternative path - */ - protected ParserRuleContext getShortestAlternative(ParserRuleContext currentCtx) { + private Result seekMatchInStmtRelatedAlternativePaths(ParserRuleContext currentCtx, int lookahead, int currentDepth, + int matchingRulesCount, boolean isEntryPoint) { + ParserRuleContext[] alternativeRules; switch (currentCtx) { - case TOP_LEVEL_NODE: - case TOP_LEVEL_NODE_WITHOUT_MODIFIER: - case TOP_LEVEL_NODE_WITHOUT_METADATA: - return ParserRuleContext.EOF; - case FUNC_OPTIONAL_RETURNS: - return ParserRuleContext.RETURNS_KEYWORD; - case FUNC_BODY_OR_TYPE_DESC_RHS: - return ParserRuleContext.FUNC_BODY; - case ANON_FUNC_BODY: - return ParserRuleContext.EXPLICIT_ANON_FUNC_EXPR_BODY_START; - case FUNC_BODY: - return ParserRuleContext.FUNC_BODY_BLOCK; - case EXPRESSION: - case TERMINAL_EXPRESSION: - return ParserRuleContext.VARIABLE_REF; case VAR_DECL_STMT_RHS: - return ParserRuleContext.SEMICOLON; - case EXPRESSION_RHS: - case VARIABLE_REF_RHS: - return ParserRuleContext.BINARY_OPERATOR; + alternativeRules = VAR_DECL_RHS; + break; case STATEMENT: case STATEMENT_WITHOUT_ANNOTS: - return ParserRuleContext.VAR_DECL_STMT; - case PARAM_LIST: - return ParserRuleContext.CLOSE_PARENTHESIS; - case REQUIRED_PARAM_NAME_RHS: - return ParserRuleContext.PARAM_END; + return seekInStatements(currentCtx, lookahead, currentDepth, matchingRulesCount, isEntryPoint); case TYPE_NAME_OR_VAR_NAME: - return ParserRuleContext.VARIABLE_NAME; - case FIELD_DESCRIPTOR_RHS: - return ParserRuleContext.SEMICOLON; - case FIELD_OR_REST_DESCIPTOR_RHS: - return ParserRuleContext.VARIABLE_NAME; - case RECORD_BODY_END: - return ParserRuleContext.CLOSE_BRACE; - case RECORD_BODY_START: - return ParserRuleContext.OPEN_BRACE; - case TYPE_DESCRIPTOR: - return ParserRuleContext.SIMPLE_TYPE_DESC_IDENTIFIER; - case TYPE_DESC_WITHOUT_ISOLATED: - return ParserRuleContext.FUNC_TYPE_DESC; - case RECORD_FIELD_OR_RECORD_END: - return ParserRuleContext.RECORD_BODY_END; - case RECORD_FIELD_START: - case RECORD_FIELD_WITHOUT_METADATA: - return ParserRuleContext.TYPE_DESC_IN_RECORD_FIELD; - case ARG_START: - return ParserRuleContext.EXPRESSION; - case ARG_START_OR_ARG_LIST_END: - return ParserRuleContext.ARG_LIST_END; - case NAMED_OR_POSITIONAL_ARG_RHS: - return ParserRuleContext.ARG_END; - case ARG_END: - return ParserRuleContext.ARG_LIST_END; - case CLASS_MEMBER_OR_OBJECT_MEMBER_START: - case OBJECT_CONSTRUCTOR_MEMBER_START: - case CLASS_MEMBER_OR_OBJECT_MEMBER_WITHOUT_META: - case OBJECT_CONS_MEMBER_WITHOUT_META: - return ParserRuleContext.CLOSE_BRACE; - case OPTIONAL_FIELD_INITIALIZER: - return ParserRuleContext.SEMICOLON; - case ON_FAIL_OPTIONAL_BINDING_PATTERN: - return ParserRuleContext.BLOCK_STMT; - case OBJECT_METHOD_START: - return ParserRuleContext.FUNC_DEF_OR_FUNC_TYPE; - case OBJECT_FUNC_OR_FIELD: - return ParserRuleContext.OBJECT_FUNC_OR_FIELD_WITHOUT_VISIBILITY; - case OBJECT_FUNC_OR_FIELD_WITHOUT_VISIBILITY: - return ParserRuleContext.OBJECT_FIELD_START; - case OBJECT_TYPE_START: - case OBJECT_CONSTRUCTOR_START: - return ParserRuleContext.OBJECT_KEYWORD; + alternativeRules = TYPE_OR_VAR_NAME; + break; case ELSE_BLOCK: - return ParserRuleContext.STATEMENT; + alternativeRules = ELSE_BLOCK; + break; case ELSE_BODY: - return ParserRuleContext.OPEN_BRACE; + alternativeRules = ELSE_BODY; + break; case CALL_STMT_START: - return ParserRuleContext.VARIABLE_REF; - case IMPORT_PREFIX_DECL: - return ParserRuleContext.SEMICOLON; - case IMPORT_DECL_ORG_OR_MODULE_NAME_RHS: - return ParserRuleContext.AFTER_IMPORT_MODULE_NAME; - case AFTER_IMPORT_MODULE_NAME: + alternativeRules = CALL_STATEMENT; + break; case RETURN_STMT_RHS: - return ParserRuleContext.SEMICOLON; - case ACCESS_EXPRESSION: - return ParserRuleContext.VARIABLE_REF; - case FIRST_MAPPING_FIELD: - return ParserRuleContext.CLOSE_BRACE; - case MAPPING_FIELD: - return ParserRuleContext.SPECIFIC_FIELD; - case SPECIFIC_FIELD: - return ParserRuleContext.MAPPING_FIELD_NAME; - case SPECIFIC_FIELD_RHS: - return ParserRuleContext.MAPPING_FIELD_END; - case MAPPING_FIELD_END: - return ParserRuleContext.CLOSE_BRACE; - case OPTIONAL_ABSOLUTE_PATH: - return ParserRuleContext.ON_KEYWORD; - case CONST_DECL_TYPE: - return ParserRuleContext.VARIABLE_NAME; - case CONST_DECL_RHS: - return ParserRuleContext.ASSIGN_OP; + alternativeRules = RETURN_RHS; + break; case ARRAY_LENGTH: - return ParserRuleContext.CLOSE_BRACKET; - case PARAMETER_START: - return ParserRuleContext.PARAMETER_START_WITHOUT_ANNOTATION; - case PARAMETER_START_WITHOUT_ANNOTATION: - return ParserRuleContext.TYPE_DESC_IN_PARAM; + alternativeRules = ARRAY_LENGTH; + break; case STMT_START_WITH_EXPR_RHS: + alternativeRules = STMT_START_WITH_EXPR_RHS; + break; case EXPR_STMT_RHS: - return ParserRuleContext.SEMICOLON; + alternativeRules = EXPR_STMT_RHS; + break; case EXPRESSION_STATEMENT_START: - return ParserRuleContext.VARIABLE_REF; - case ANNOT_DECL_OPTIONAL_TYPE: - return ParserRuleContext.ANNOTATION_TAG; - case ANNOT_DECL_RHS: - case ANNOT_OPTIONAL_ATTACH_POINTS: - return ParserRuleContext.SEMICOLON; - case ATTACH_POINT: - return ParserRuleContext.ATTACH_POINT_IDENT; - case ATTACH_POINT_IDENT: - return ParserRuleContext.SINGLE_KEYWORD_ATTACH_POINT_IDENT; - case ATTACH_POINT_END: - case BINDING_PATTERN_OR_VAR_REF_RHS: - return ParserRuleContext.SEMICOLON; - case XML_NAMESPACE_PREFIX_DECL: - return ParserRuleContext.SEMICOLON; - case CONSTANT_EXPRESSION_START: - return ParserRuleContext.VARIABLE_REF; + alternativeRules = EXPRESSION_STATEMENT_START; + break; case TYPE_DESC_RHS: - return ParserRuleContext.END_OF_TYPE_DESC; - case LIST_CONSTRUCTOR_FIRST_MEMBER: - return ParserRuleContext.CLOSE_BRACKET; - case LIST_CONSTRUCTOR_MEMBER: - return ParserRuleContext.EXPRESSION; - case TYPE_CAST_PARAM: - case TYPE_CAST_PARAM_RHS: - return ParserRuleContext.TYPE_DESC_IN_ANGLE_BRACKETS; - case TABLE_KEYWORD_RHS: - return ParserRuleContext.TABLE_CONSTRUCTOR; - case ROW_LIST_RHS: - case TABLE_ROW_END: - return ParserRuleContext.CLOSE_BRACKET; - case KEY_SPECIFIER_RHS: - case TABLE_KEY_RHS: - return ParserRuleContext.CLOSE_PARENTHESIS; - case LET_VAR_DECL_START: - return ParserRuleContext.TYPE_DESC_IN_TYPE_BINDING_PATTERN; - case ORDER_KEY_LIST_END: - return ParserRuleContext.ORDER_CLAUSE_END; - case GROUPING_KEY_LIST_ELEMENT_END: - return ParserRuleContext.GROUP_BY_CLAUSE_END; - case GROUPING_KEY_LIST_ELEMENT: - return ParserRuleContext.VARIABLE_NAME; + assert isInTypeDescContext(); + alternativeRules = TYPE_DESC_RHS; + break; case STREAM_TYPE_FIRST_PARAM_RHS: - return ParserRuleContext.GT; - case TEMPLATE_MEMBER: - case TEMPLATE_STRING_RHS: - return ParserRuleContext.TEMPLATE_END; + alternativeRules = STREAM_TYPE_FIRST_PARAM_RHS; + break; case FUNCTION_KEYWORD_RHS: - return ParserRuleContext.FUNC_TYPE_FUNC_KEYWORD_RHS; + alternativeRules = FUNCTION_KEYWORD_RHS; + break; case FUNC_TYPE_FUNC_KEYWORD_RHS_START: - return ParserRuleContext.FUNC_TYPE_DESC_END; + alternativeRules = FUNC_TYPE_FUNC_KEYWORD_RHS_START; + break; case WORKER_NAME_RHS: - return ParserRuleContext.BLOCK_STMT; + alternativeRules = WORKER_NAME_RHS; + break; case BINDING_PATTERN: - return ParserRuleContext.BINDING_PATTERN_STARTING_IDENTIFIER; + alternativeRules = BINDING_PATTERN; + break; case LIST_BINDING_PATTERNS_START: + alternativeRules = LIST_BINDING_PATTERNS_START; + break; case LIST_BINDING_PATTERN_MEMBER_END: - return ParserRuleContext.CLOSE_BRACKET; - case FIELD_BINDING_PATTERN_END: - return ParserRuleContext.CLOSE_BRACE; + alternativeRules = LIST_BINDING_PATTERN_MEMBER_END; + break; case LIST_BINDING_PATTERN_MEMBER: - return ParserRuleContext.BINDING_PATTERN; + alternativeRules = LIST_BINDING_PATTERN_CONTENTS; + break; case MAPPING_BINDING_PATTERN_END: - return ParserRuleContext.CLOSE_BRACE; + alternativeRules = MAPPING_BINDING_PATTERN_END; + break; + case FIELD_BINDING_PATTERN_END: + alternativeRules = FIELD_BINDING_PATTERN_END; + break; case MAPPING_BINDING_PATTERN_MEMBER: - return ParserRuleContext.FIELD_BINDING_PATTERN; + alternativeRules = MAPPING_BINDING_PATTERN_MEMBER; + break; + case ERROR_BINDING_PATTERN_ERROR_KEYWORD_RHS: + alternativeRules = ERROR_BINDING_PATTERN_ERROR_KEYWORD_RHS; + break; + case ERROR_ARG_LIST_BINDING_PATTERN_START: + alternativeRules = ERROR_ARG_LIST_BINDING_PATTERN_START; + break; + case ERROR_MESSAGE_BINDING_PATTERN_END: + alternativeRules = ERROR_MESSAGE_BINDING_PATTERN_END; + break; + case ERROR_MESSAGE_BINDING_PATTERN_RHS: + alternativeRules = ERROR_MESSAGE_BINDING_PATTERN_RHS; + break; + case ERROR_FIELD_BINDING_PATTERN: + alternativeRules = ERROR_FIELD_BINDING_PATTERN; + break; + case ERROR_FIELD_BINDING_PATTERN_END: + alternativeRules = ERROR_FIELD_BINDING_PATTERN_END; + break; case KEY_CONSTRAINTS_RHS: - return ParserRuleContext.OPEN_PARENTHESIS; + alternativeRules = KEY_CONSTRAINTS_RHS; + break; case TABLE_TYPE_DESC_RHS: - return ParserRuleContext.TYPE_DESC_RHS; - case NEW_KEYWORD_RHS: - return ParserRuleContext.EXPRESSION_RHS; - case TABLE_CONSTRUCTOR_OR_QUERY_START: - return ParserRuleContext.TABLE_KEYWORD; - case TABLE_CONSTRUCTOR_OR_QUERY_RHS: - return ParserRuleContext.TABLE_CONSTRUCTOR; - case QUERY_PIPELINE_RHS: - return ParserRuleContext.QUERY_EXPRESSION_RHS; - case BRACED_EXPR_OR_ANON_FUNC_PARAM_RHS: - case ANON_FUNC_PARAM_RHS: - return ParserRuleContext.CLOSE_PARENTHESIS; - case PARAM_END: - return ParserRuleContext.CLOSE_PARENTHESIS; - case ANNOTATION_REF_RHS: - return ParserRuleContext.ANNOTATION_END; - case INFER_PARAM_END_OR_PARENTHESIS_END: - return ParserRuleContext.CLOSE_PARENTHESIS; + alternativeRules = TABLE_TYPE_DESC_RHS; + break; case TYPE_DESC_IN_TUPLE_RHS: - return ParserRuleContext.CLOSE_BRACKET; + alternativeRules = TYPE_DESC_IN_TUPLE_RHS; + break; case TUPLE_TYPE_MEMBER_RHS: - return ParserRuleContext.CLOSE_BRACKET; + alternativeRules = TUPLE_TYPE_MEMBER_RHS; + break; case LIST_CONSTRUCTOR_MEMBER_END: - return ParserRuleContext.CLOSE_BRACKET; + alternativeRules = LIST_CONSTRUCTOR_MEMBER_END; + break; case NIL_OR_PARENTHESISED_TYPE_DESC_RHS: - return ParserRuleContext.CLOSE_PARENTHESIS; + alternativeRules = NIL_OR_PARENTHESISED_TYPE_DESC_RHS; + break; case REMOTE_OR_RESOURCE_CALL_OR_ASYNC_SEND_RHS: - return ParserRuleContext.PEER_WORKER_NAME; + alternativeRules = REMOTE_OR_RESOURCE_CALL_OR_ASYNC_SEND_RHS; + break; case REMOTE_CALL_OR_ASYNC_SEND_END: - return ParserRuleContext.SEMICOLON; + alternativeRules = REMOTE_CALL_OR_ASYNC_SEND_END; + break; + case OPTIONAL_RESOURCE_ACCESS_PATH: + alternativeRules = OPTIONAL_RESOURCE_ACCESS_PATH; + break; + case RESOURCE_ACCESS_PATH_SEGMENT: + alternativeRules = RESOURCE_ACCESS_PATH_SEGMENT; + break; + case COMPUTED_SEGMENT_OR_REST_SEGMENT: + alternativeRules = COMPUTED_SEGMENT_OR_REST_SEGMENT; + break; + case RESOURCE_ACCESS_SEGMENT_RHS: + alternativeRules = RESOURCE_ACCESS_SEGMENT_RHS; + break; + case OPTIONAL_RESOURCE_ACCESS_METHOD: + alternativeRules = OPTIONAL_RESOURCE_ACCESS_METHOD; + break; + case OPTIONAL_RESOURCE_ACCESS_ACTION_ARG_LIST: + alternativeRules = OPTIONAL_RESOURCE_ACCESS_ACTION_ARG_LIST; + break; case RECEIVE_WORKERS: + alternativeRules = RECEIVE_WORKERS; + break; case RECEIVE_FIELD: - return ParserRuleContext.PEER_WORKER_NAME; + alternativeRules = RECEIVE_FIELD; + break; case RECEIVE_FIELD_END: - return ParserRuleContext.CLOSE_BRACE; + alternativeRules = RECEIVE_FIELD_END; + break; case WAIT_KEYWORD_RHS: - return ParserRuleContext.MULTI_WAIT_FIELDS; + alternativeRules = WAIT_KEYWORD_RHS; + break; case WAIT_FIELD_NAME_RHS: - return ParserRuleContext.WAIT_FIELD_END; + alternativeRules = WAIT_FIELD_NAME_RHS; + break; case WAIT_FIELD_END: - return ParserRuleContext.CLOSE_BRACE; + alternativeRules = WAIT_FIELD_END; + break; case WAIT_FUTURE_EXPR_END: - return ParserRuleContext.ALTERNATE_WAIT_EXPR_LIST_END; + alternativeRules = WAIT_FUTURE_EXPR_END; + break; case OPTIONAL_PEER_WORKER: - return ParserRuleContext.EXPRESSION_RHS; - case ENUM_MEMBER_START: - return ParserRuleContext.ENUM_MEMBER_NAME; - case ENUM_MEMBER_RHS: - return ParserRuleContext.ENUM_MEMBER_END; - case ENUM_MEMBER_END: - return ParserRuleContext.CLOSE_BRACE; - case MEMBER_ACCESS_KEY_EXPR_END: - return ParserRuleContext.CLOSE_BRACKET; + alternativeRules = OPTIONAL_PEER_WORKER; + break; case ROLLBACK_RHS: - return ParserRuleContext.SEMICOLON; + alternativeRules = ROLLBACK_RHS; + break; case RETRY_KEYWORD_RHS: - return ParserRuleContext.RETRY_TYPE_PARAM_RHS; + alternativeRules = RETRY_KEYWORD_RHS; + break; case RETRY_TYPE_PARAM_RHS: - return ParserRuleContext.RETRY_BODY; + alternativeRules = RETRY_TYPE_PARAM_RHS; + break; case RETRY_BODY: - return ParserRuleContext.BLOCK_STMT; + alternativeRules = RETRY_BODY; + break; case STMT_START_BRACKETED_LIST_MEMBER: - return ParserRuleContext.TYPE_DESCRIPTOR; + alternativeRules = LIST_BP_OR_TUPLE_TYPE_MEMBER; + break; case STMT_START_BRACKETED_LIST_RHS: - return ParserRuleContext.VARIABLE_NAME; - case BINDING_PATTERN_OR_EXPR_RHS: - case BRACKETED_LIST_RHS: - return ParserRuleContext.TYPE_DESC_RHS_OR_BP_RHS; - case BRACKETED_LIST_MEMBER: - return ParserRuleContext.EXPRESSION; + alternativeRules = LIST_BP_OR_TUPLE_TYPE_DESC_RHS; + break; case BRACKETED_LIST_MEMBER_END: - return ParserRuleContext.CLOSE_BRACKET; + alternativeRules = BRACKETED_LIST_MEMBER_END; + break; + case BRACKETED_LIST_MEMBER: + alternativeRules = BRACKETED_LIST_MEMBER; + break; + case BRACKETED_LIST_RHS: + case BINDING_PATTERN_OR_EXPR_RHS: + case TYPE_DESC_OR_EXPR_RHS: + alternativeRules = BRACKETED_LIST_RHS; + break; + case BINDING_PATTERN_OR_VAR_REF_RHS: + alternativeRules = BINDING_PATTERN_OR_VAR_REF_RHS; + break; case TYPE_DESC_RHS_OR_BP_RHS: - return ParserRuleContext.TYPE_DESC_RHS_IN_TYPED_BP; + alternativeRules = TYPE_DESC_RHS_OR_BP_RHS; + break; case LIST_BINDING_MEMBER_OR_ARRAY_LENGTH: - return ParserRuleContext.BINDING_PATTERN; - case XML_NAVIGATE_EXPR: - return ParserRuleContext.XML_FILTER_EXPR; - case XML_NAME_PATTERN_RHS: - return ParserRuleContext.GT; - case XML_ATOMIC_NAME_PATTERN_START: - return ParserRuleContext.XML_ATOMIC_NAME_IDENTIFIER; - case XML_ATOMIC_NAME_IDENTIFIER_RHS: - return ParserRuleContext.IDENTIFIER; - case XML_STEP_START: - return ParserRuleContext.SLASH_ASTERISK_TOKEN; - case FUNC_TYPE_DESC_RHS_OR_ANON_FUNC_BODY: - return ParserRuleContext.ANON_FUNC_BODY; - case OPTIONAL_MATCH_GUARD: - return ParserRuleContext.RIGHT_DOUBLE_ARROW; + alternativeRules = LIST_BINDING_MEMBER_OR_ARRAY_LENGTH; + break; case MATCH_PATTERN_LIST_MEMBER_RHS: - return ParserRuleContext.MATCH_PATTERN_END; + alternativeRules = MATCH_PATTERN_LIST_MEMBER_RHS; + break; case MATCH_PATTERN_START: - return ParserRuleContext.CONSTANT_EXPRESSION; + alternativeRules = MATCH_PATTERN_START; + break; case LIST_MATCH_PATTERNS_START: - return ParserRuleContext.CLOSE_BRACKET; + alternativeRules = LIST_MATCH_PATTERNS_START; + break; case LIST_MATCH_PATTERN_MEMBER: - return ParserRuleContext.MATCH_PATTERN_START; + alternativeRules = LIST_MATCH_PATTERN_MEMBER; + break; case LIST_MATCH_PATTERN_MEMBER_RHS: - return ParserRuleContext.CLOSE_BRACKET; - case ERROR_BINDING_PATTERN_ERROR_KEYWORD_RHS: - return ParserRuleContext.OPEN_PARENTHESIS; - case ERROR_ARG_LIST_BINDING_PATTERN_START: - case ERROR_MESSAGE_BINDING_PATTERN_END: - return ParserRuleContext.CLOSE_PARENTHESIS; - case ERROR_MESSAGE_BINDING_PATTERN_RHS: - return ParserRuleContext.ERROR_CAUSE_SIMPLE_BINDING_PATTERN; - case ERROR_FIELD_BINDING_PATTERN: - return ParserRuleContext.NAMED_ARG_BINDING_PATTERN; - case ERROR_FIELD_BINDING_PATTERN_END: - return ParserRuleContext.CLOSE_PARENTHESIS; + alternativeRules = LIST_MATCH_PATTERN_MEMBER_RHS; + break; case FIELD_MATCH_PATTERNS_START: - return ParserRuleContext.CLOSE_BRACE; + alternativeRules = FIELD_MATCH_PATTERNS_START; + break; case FIELD_MATCH_PATTERN_MEMBER: - return ParserRuleContext.VARIABLE_NAME; + alternativeRules = FIELD_MATCH_PATTERN_MEMBER; + break; case FIELD_MATCH_PATTERN_MEMBER_RHS: - return ParserRuleContext.CLOSE_BRACE; + alternativeRules = FIELD_MATCH_PATTERN_MEMBER_RHS; + break; case ERROR_MATCH_PATTERN_OR_CONST_PATTERN: - return ParserRuleContext.MATCH_PATTERN_RHS; + alternativeRules = ERROR_MATCH_PATTERN_OR_CONST_PATTERN; + break; case ERROR_MATCH_PATTERN_ERROR_KEYWORD_RHS: - return ParserRuleContext.OPEN_PARENTHESIS; + alternativeRules = ERROR_MATCH_PATTERN_ERROR_KEYWORD_RHS; + break; case ERROR_ARG_LIST_MATCH_PATTERN_START: + alternativeRules = ERROR_ARG_LIST_MATCH_PATTERN_START; + break; case ERROR_MESSAGE_MATCH_PATTERN_END: - return ParserRuleContext.CLOSE_PARENTHESIS; + alternativeRules = ERROR_MESSAGE_MATCH_PATTERN_END; + break; case ERROR_MESSAGE_MATCH_PATTERN_RHS: - return ParserRuleContext.ERROR_CAUSE_MATCH_PATTERN; + alternativeRules = ERROR_MESSAGE_MATCH_PATTERN_RHS; + break; case ERROR_FIELD_MATCH_PATTERN: - return ParserRuleContext.NAMED_ARG_MATCH_PATTERN; + alternativeRules = ERROR_FIELD_MATCH_PATTERN; + break; case ERROR_FIELD_MATCH_PATTERN_RHS: - return ParserRuleContext.CLOSE_PARENTHESIS; + alternativeRules = ERROR_FIELD_MATCH_PATTERN_RHS; + break; case NAMED_ARG_MATCH_PATTERN_RHS: - return ParserRuleContext.NAMED_ARG_MATCH_PATTERN; - case EXTERNAL_FUNC_BODY_OPTIONAL_ANNOTS: - return ParserRuleContext.EXTERNAL_KEYWORD; - case LIST_BP_OR_LIST_CONSTRUCTOR_MEMBER: - return ParserRuleContext.LIST_BINDING_PATTERN_MEMBER; - case TUPLE_TYPE_DESC_OR_LIST_CONST_MEMBER: - return ParserRuleContext.TYPE_DESCRIPTOR; - case OBJECT_METHOD_WITHOUT_FIRST_QUALIFIER: - case OBJECT_METHOD_WITHOUT_SECOND_QUALIFIER: - case OBJECT_METHOD_WITHOUT_THIRD_QUALIFIER: - case FUNC_DEF: - return ParserRuleContext.FUNC_DEF_OR_FUNC_TYPE; + alternativeRules = NAMED_ARG_MATCH_PATTERN_RHS; + break; case JOIN_CLAUSE_START: - return ParserRuleContext.JOIN_KEYWORD; + alternativeRules = JOIN_CLAUSE_START; + break; case INTERMEDIATE_CLAUSE_START: - return ParserRuleContext.WHERE_CLAUSE; - case MAPPING_BP_OR_MAPPING_CONSTRUCTOR_MEMBER: - return ParserRuleContext.MAPPING_BINDING_PATTERN_MEMBER; - case TYPE_DESC_OR_EXPR_RHS: - return ParserRuleContext.TYPE_DESC_RHS_OR_BP_RHS; - case LISTENERS_LIST_END: - return ParserRuleContext.OBJECT_CONSTRUCTOR_BLOCK; + alternativeRules = INTERMEDIATE_CLAUSE_START; + break; case REGULAR_COMPOUND_STMT_RHS: - return ParserRuleContext.STATEMENT; + alternativeRules = REGULAR_COMPOUND_STMT_RHS; + break; case NAMED_WORKER_DECL_START: - return ParserRuleContext.WORKER_KEYWORD; - case FUNC_TYPE_DESC_START: - case FUNC_DEF_START: - case ANON_FUNC_EXPRESSION_START: - return ParserRuleContext.FUNCTION_KEYWORD; - case MODULE_CLASS_DEFINITION_START: - return ParserRuleContext.CLASS_KEYWORD; - case OBJECT_CONSTRUCTOR_TYPE_REF: - return ParserRuleContext.OPEN_BRACE; - case OBJECT_FIELD_QUALIFIER: - return ParserRuleContext.TYPE_DESC_BEFORE_IDENTIFIER; - case OPTIONAL_SERVICE_DECL_TYPE: - return ParserRuleContext.OPTIONAL_ABSOLUTE_PATH; - case SERVICE_IDENT_RHS: - return ParserRuleContext.ATTACH_POINT_END; - case ABSOLUTE_RESOURCE_PATH_START: - return ParserRuleContext.ABSOLUTE_PATH_SINGLE_SLASH; - case ABSOLUTE_RESOURCE_PATH_END: - return ParserRuleContext.SERVICE_DECL_RHS; - case SERVICE_DECL_OR_VAR_DECL: - return ParserRuleContext.SERVICE_VAR_DECL_RHS; - case OPTIONAL_RELATIVE_PATH: - return ParserRuleContext.OPEN_PARENTHESIS; - case RELATIVE_RESOURCE_PATH_START: - return ParserRuleContext.DOT; - case RELATIVE_RESOURCE_PATH_END: - return ParserRuleContext.RESOURCE_ACCESSOR_DEF_OR_DECL_RHS; - case RESOURCE_PATH_SEGMENT: - return ParserRuleContext.PATH_SEGMENT_IDENT; - case PATH_PARAM_OPTIONAL_ANNOTS: - return ParserRuleContext.TYPE_DESC_IN_PATH_PARAM; - case PATH_PARAM_ELLIPSIS: - case OPTIONAL_PATH_PARAM_NAME: - return ParserRuleContext.CLOSE_BRACKET; - case OBJECT_CONS_WITHOUT_FIRST_QUALIFIER: - case OBJECT_TYPE_WITHOUT_FIRST_QUALIFIER: - return ParserRuleContext.OBJECT_KEYWORD; - case CONFIG_VAR_DECL_RHS: - return ParserRuleContext.EXPRESSION; - case SERVICE_DECL_START: - return ParserRuleContext.SERVICE_KEYWORD; - case ERROR_CONSTRUCTOR_RHS: - return ParserRuleContext.ARG_LIST_OPEN_PAREN; - case OPTIONAL_TYPE_PARAMETER: - return ParserRuleContext.TYPE_DESC_RHS; - case MAP_TYPE_OR_TYPE_REF: - return ParserRuleContext.LT; - case OBJECT_TYPE_OR_TYPE_REF: - return ParserRuleContext.OBJECT_TYPE_OBJECT_KEYWORD_RHS; - case STREAM_TYPE_OR_TYPE_REF: - return ParserRuleContext.LT; - case TABLE_TYPE_OR_TYPE_REF: - return ParserRuleContext.ROW_TYPE_PARAM; - case PARAMETERIZED_TYPE_OR_TYPE_REF: - return ParserRuleContext.OPTIONAL_TYPE_PARAMETER; - case TYPE_DESC_RHS_OR_TYPE_REF: - return ParserRuleContext.TYPE_DESC_RHS; - case TRANSACTION_STMT_RHS_OR_TYPE_REF: - return ParserRuleContext.TRANSACTION_STMT_TRANSACTION_KEYWORD_RHS; - case TABLE_CONS_OR_QUERY_EXPR_OR_VAR_REF: - return ParserRuleContext.EXPRESSION_START_TABLE_KEYWORD_RHS; - case QUERY_EXPR_OR_VAR_REF: - return ParserRuleContext.QUERY_CONSTRUCT_TYPE_RHS; - case ERROR_CONS_EXPR_OR_VAR_REF: - return ParserRuleContext.ERROR_CONS_ERROR_KEYWORD_RHS; - case QUALIFIED_IDENTIFIER: - return ParserRuleContext.QUALIFIED_IDENTIFIER_START_IDENTIFIER; - case CLASS_DEF_WITHOUT_FIRST_QUALIFIER: - case CLASS_DEF_WITHOUT_SECOND_QUALIFIER: - case CLASS_DEF_WITHOUT_THIRD_QUALIFIER: - return ParserRuleContext.CLASS_KEYWORD; - case FUNC_DEF_WITHOUT_FIRST_QUALIFIER: - return ParserRuleContext.FUNC_DEF_OR_FUNC_TYPE; - case FUNC_TYPE_DESC_START_WITHOUT_FIRST_QUAL: - return ParserRuleContext.FUNCTION_KEYWORD; - case MODULE_VAR_DECL_START: - case MODULE_VAR_WITHOUT_FIRST_QUAL: - case MODULE_VAR_WITHOUT_SECOND_QUAL: - return ParserRuleContext.VAR_DECL_STMT; - case FUNC_DEF_OR_TYPE_DESC_RHS: - return ParserRuleContext.SEMICOLON; - case CLASS_DESCRIPTOR: - return ParserRuleContext.TYPE_REFERENCE; - case EXPR_START_OR_INFERRED_TYPEDESC_DEFAULT_START: - return ParserRuleContext.EXPRESSION; - case TYPE_CAST_PARAM_START_OR_INFERRED_TYPEDESC_DEFAULT_END: - return ParserRuleContext.INFERRED_TYPEDESC_DEFAULT_END_GT; - case END_OF_PARAMS_OR_NEXT_PARAM_START: - return ParserRuleContext.CLOSE_PARENTHESIS; + alternativeRules = NAMED_WORKER_DECL_START; + break; case ASSIGNMENT_STMT_RHS: - return ParserRuleContext.ASSIGN_OP; - case PARAM_START: - return ParserRuleContext.TYPE_DESC_IN_PARAM; - case PARAM_RHS: - return ParserRuleContext.VARIABLE_NAME; - case FUNC_TYPE_PARAM_RHS: - return ParserRuleContext.PARAM_END; - case ANNOTATION_DECL_START: - return ParserRuleContext.ANNOTATION_KEYWORD; - case OPTIONAL_RESOURCE_ACCESS_PATH: - case RESOURCE_ACCESS_SEGMENT_RHS: - return ParserRuleContext.OPTIONAL_RESOURCE_ACCESS_METHOD; - case RESOURCE_ACCESS_PATH_SEGMENT: - return ParserRuleContext.IDENTIFIER; - case COMPUTED_SEGMENT_OR_REST_SEGMENT: - return ParserRuleContext.EXPRESSION; - case OPTIONAL_RESOURCE_ACCESS_METHOD: - return ParserRuleContext.OPTIONAL_RESOURCE_ACCESS_ACTION_ARG_LIST; - case OPTIONAL_RESOURCE_ACCESS_ACTION_ARG_LIST: - return ParserRuleContext.ACTION_END; - case OPTIONAL_TOP_LEVEL_SEMICOLON: - return ParserRuleContext.TOP_LEVEL_NODE; - case TUPLE_MEMBER: - return ParserRuleContext.TYPE_DESC_IN_TUPLE; - case RESULT_CLAUSE: - return ParserRuleContext.SELECT_CLAUSE; - case SINGLE_OR_ALTERNATE_WORKER_SEPARATOR: - return ParserRuleContext.SINGLE_OR_ALTERNATE_WORKER_END; + alternativeRules = ASSIGNMENT_STMT_RHS; + break; default: - throw new IllegalStateException("Alternative path entry not found"); + return seekMatchInExprRelatedAlternativePaths(currentCtx, lookahead, currentDepth, matchingRulesCount, + isEntryPoint); } + + return seekInAlternativesPaths(lookahead, currentDepth, matchingRulesCount, alternativeRules, isEntryPoint); } - private Result seekMatchInAlternativePaths(ParserRuleContext currentCtx, int lookahead, int currentDepth, - int matchingRulesCount, boolean isEntryPoint) { + private Result seekMatchInExprRelatedAlternativePaths(ParserRuleContext currentCtx, int lookahead, int currentDepth, + int matchingRulesCount, boolean isEntryPoint) { ParserRuleContext[] alternativeRules; switch (currentCtx) { - case TOP_LEVEL_NODE: - alternativeRules = TOP_LEVEL_NODE; + case EXPRESSION: + case TERMINAL_EXPRESSION: + alternativeRules = EXPRESSION_START; break; - case TOP_LEVEL_NODE_WITHOUT_MODIFIER: - alternativeRules = TOP_LEVEL_NODE_WITHOUT_MODIFIER; + case ARG_START: + alternativeRules = ARG_START; break; - case TOP_LEVEL_NODE_WITHOUT_METADATA: - alternativeRules = TOP_LEVEL_NODE_WITHOUT_METADATA; - break; - case FUNC_DEF_START: - alternativeRules = FUNC_DEF_START; - break; - case FUNC_DEF_WITHOUT_FIRST_QUALIFIER: - alternativeRules = FUNC_DEF_WITHOUT_FIRST_QUALIFIER; - break; - case FUNC_TYPE_DESC_START_WITHOUT_FIRST_QUAL: - alternativeRules = FUNC_TYPE_DESC_START_WITHOUT_FIRST_QUAL; - break; - case FUNC_OPTIONAL_RETURNS: - ParserRuleContext parentCtx = getParentContext(); - ParserRuleContext[] alternatives; - if (parentCtx == ParserRuleContext.FUNC_DEF) { - ParserRuleContext grandParentCtx = getGrandParentContext(); - if (grandParentCtx == ParserRuleContext.OBJECT_TYPE_MEMBER) { - alternatives = METHOD_DECL_OPTIONAL_RETURNS; - } else { - alternatives = FUNC_DEF_OPTIONAL_RETURNS; - } - } else if (parentCtx == ParserRuleContext.ANON_FUNC_EXPRESSION) { - alternatives = ANNON_FUNC_OPTIONAL_RETURNS; - } else if (parentCtx == ParserRuleContext.FUNC_TYPE_DESC) { - alternatives = FUNC_TYPE_OPTIONAL_RETURNS; - } else if (parentCtx == ParserRuleContext.FUNC_TYPE_DESC_OR_ANON_FUNC) { - alternatives = FUNC_TYPE_OR_ANON_FUNC_OPTIONAL_RETURNS; - } else { - alternatives = FUNC_TYPE_OR_DEF_OPTIONAL_RETURNS; - } - - alternativeRules = alternatives; - break; - case FUNC_BODY_OR_TYPE_DESC_RHS: - alternativeRules = FUNC_BODY_OR_TYPE_DESC_RHS; - break; - case FUNC_TYPE_DESC_RHS_OR_ANON_FUNC_BODY: - alternativeRules = FUNC_TYPE_DESC_RHS_OR_ANON_FUNC_BODY; - break; - case ANON_FUNC_BODY: - alternativeRules = ANON_FUNC_BODY; - break; - case FUNC_BODY: - alternativeRules = FUNC_BODY; - break; - case PARAM_LIST: - alternativeRules = PARAM_LIST; - break; - case REQUIRED_PARAM_NAME_RHS: - alternativeRules = REQUIRED_PARAM_NAME_RHS; - break; - case FIELD_DESCRIPTOR_RHS: - alternativeRules = FIELD_DESCRIPTOR_RHS; - break; - case FIELD_OR_REST_DESCIPTOR_RHS: - alternativeRules = FIELD_OR_REST_DESCIPTOR_RHS; - break; - case RECORD_BODY_END: - alternativeRules = RECORD_BODY_END; - break; - case RECORD_BODY_START: - alternativeRules = RECORD_BODY_START; - break; - case TYPE_DESCRIPTOR: - assert isInTypeDescContext(); - alternativeRules = TYPE_DESCRIPTORS; - break; - case TYPE_DESC_WITHOUT_ISOLATED: - alternativeRules = TYPE_DESCRIPTOR_WITHOUT_ISOLATED; - break; - case CLASS_DESCRIPTOR: - alternativeRules = CLASS_DESCRIPTOR; + case ARG_START_OR_ARG_LIST_END: + alternativeRules = ARG_START_OR_ARG_LIST_END; break; - case RECORD_FIELD_OR_RECORD_END: - alternativeRules = RECORD_FIELD_OR_RECORD_END; + case NAMED_OR_POSITIONAL_ARG_RHS: + alternativeRules = NAMED_OR_POSITIONAL_ARG_RHS; break; - case RECORD_FIELD_START: - alternativeRules = RECORD_FIELD_START; + case ARG_END: + alternativeRules = ARG_END; break; - case RECORD_FIELD_WITHOUT_METADATA: - alternativeRules = RECORD_FIELD_WITHOUT_METADATA; + case ACCESS_EXPRESSION: + return seekInAccessExpression(currentCtx, lookahead, currentDepth, matchingRulesCount, isEntryPoint); + case FIRST_MAPPING_FIELD: + alternativeRules = FIRST_MAPPING_FIELD_START; break; - case CLASS_MEMBER_OR_OBJECT_MEMBER_START: - alternativeRules = CLASS_MEMBER_OR_OBJECT_MEMBER_START; + case MAPPING_FIELD: + alternativeRules = MAPPING_FIELD_START; break; - case OBJECT_CONSTRUCTOR_MEMBER_START: - alternativeRules = OBJECT_CONSTRUCTOR_MEMBER_START; + case SPECIFIC_FIELD: + alternativeRules = SPECIFIC_FIELD; break; - case CLASS_MEMBER_OR_OBJECT_MEMBER_WITHOUT_META: - alternativeRules = CLASS_MEMBER_OR_OBJECT_MEMBER_WITHOUT_META; + case SPECIFIC_FIELD_RHS: + alternativeRules = SPECIFIC_FIELD_RHS; break; - case OBJECT_CONS_MEMBER_WITHOUT_META: - alternativeRules = OBJECT_CONS_MEMBER_WITHOUT_META; + case MAPPING_FIELD_END: + alternativeRules = MAPPING_FIELD_END; break; - case OPTIONAL_FIELD_INITIALIZER: - alternativeRules = OPTIONAL_FIELD_INITIALIZER; + case LET_VAR_DECL_START: + alternativeRules = LET_VAR_DECL_START; break; - case ON_FAIL_OPTIONAL_BINDING_PATTERN: - alternativeRules = ON_FAIL_OPTIONAL_BINDING_PATTERN; + case ORDER_KEY_LIST_END: + alternativeRules = ORDER_KEY_LIST_END; break; - case OBJECT_METHOD_START: - alternativeRules = OBJECT_METHOD_START; + case GROUPING_KEY_LIST_ELEMENT: + alternativeRules = GROUPING_KEY_LIST_ELEMENT; break; - case OBJECT_METHOD_WITHOUT_FIRST_QUALIFIER: - alternativeRules = OBJECT_METHOD_WITHOUT_FIRST_QUALIFIER; + case GROUPING_KEY_LIST_ELEMENT_END: + alternativeRules = GROUPING_KEY_LIST_ELEMENT_END; break; - case OBJECT_METHOD_WITHOUT_SECOND_QUALIFIER: - alternativeRules = OBJECT_METHOD_WITHOUT_SECOND_QUALIFIER; + case TEMPLATE_MEMBER: + alternativeRules = TEMPLATE_MEMBER; break; - case OBJECT_METHOD_WITHOUT_THIRD_QUALIFIER: - alternativeRules = OBJECT_METHOD_WITHOUT_THIRD_QUALIFIER; + case TEMPLATE_STRING_RHS: + alternativeRules = TEMPLATE_STRING_RHS; break; - case OBJECT_FUNC_OR_FIELD: - alternativeRules = OBJECT_FUNC_OR_FIELD; + case CONSTANT_EXPRESSION_START: + alternativeRules = CONSTANT_EXPRESSION; break; - case OBJECT_FUNC_OR_FIELD_WITHOUT_VISIBILITY: - alternativeRules = OBJECT_FUNC_OR_FIELD_WITHOUT_VISIBILITY; + case LIST_CONSTRUCTOR_FIRST_MEMBER: + alternativeRules = LIST_CONSTRUCTOR_FIRST_MEMBER; break; - case OBJECT_TYPE_START: - alternativeRules = OBJECT_TYPE_START; + case LIST_CONSTRUCTOR_MEMBER: + alternativeRules = LIST_CONSTRUCTOR_MEMBER; break; - case OBJECT_CONSTRUCTOR_START: - alternativeRules = OBJECT_CONSTRUCTOR_START; + case TYPE_CAST_PARAM: + alternativeRules = TYPE_CAST_PARAM; break; - case IMPORT_PREFIX_DECL: - alternativeRules = IMPORT_PREFIX_DECL; + case TYPE_CAST_PARAM_RHS: + alternativeRules = TYPE_CAST_PARAM_RHS; break; - case IMPORT_DECL_ORG_OR_MODULE_NAME_RHS: - alternativeRules = IMPORT_DECL_ORG_OR_MODULE_NAME_RHS; + case TABLE_KEYWORD_RHS: + alternativeRules = TABLE_KEYWORD_RHS; break; - case AFTER_IMPORT_MODULE_NAME: - alternativeRules = AFTER_IMPORT_MODULE_NAME; + case ROW_LIST_RHS: + alternativeRules = ROW_LIST_RHS; break; - case OPTIONAL_ABSOLUTE_PATH: - alternativeRules = OPTIONAL_ABSOLUTE_PATH; + case TABLE_ROW_END: + alternativeRules = TABLE_ROW_END; break; - case CONST_DECL_TYPE: - alternativeRules = CONST_DECL_TYPE; + case KEY_SPECIFIER_RHS: + alternativeRules = KEY_SPECIFIER_RHS; break; - case CONST_DECL_RHS: - alternativeRules = CONST_DECL_RHS; + case TABLE_KEY_RHS: + alternativeRules = TABLE_KEY_RHS; break; - case PARAMETER_START: - alternativeRules = PARAMETER_START; + case NEW_KEYWORD_RHS: + alternativeRules = NEW_KEYWORD_RHS; break; - case PARAMETER_START_WITHOUT_ANNOTATION: - alternativeRules = PARAMETER_START_WITHOUT_ANNOTATION; + case TABLE_CONSTRUCTOR_OR_QUERY_START: + alternativeRules = TABLE_CONSTRUCTOR_OR_QUERY_START; break; - case ANNOT_DECL_OPTIONAL_TYPE: - alternativeRules = ANNOT_DECL_OPTIONAL_TYPE; + case TABLE_CONSTRUCTOR_OR_QUERY_RHS: + alternativeRules = TABLE_CONSTRUCTOR_OR_QUERY_RHS; break; - case ANNOT_DECL_RHS: - alternativeRules = ANNOT_DECL_RHS; + case QUERY_PIPELINE_RHS: + alternativeRules = QUERY_PIPELINE_RHS; break; - case ANNOT_OPTIONAL_ATTACH_POINTS: - alternativeRules = ANNOT_OPTIONAL_ATTACH_POINTS; + case BRACED_EXPR_OR_ANON_FUNC_PARAM_RHS: + case ANON_FUNC_PARAM_RHS: + alternativeRules = BRACED_EXPR_OR_ANON_FUNC_PARAM_RHS; break; - case ATTACH_POINT: - alternativeRules = ATTACH_POINT; + case PARAM_END: + alternativeRules = PARAM_END; break; - case ATTACH_POINT_IDENT: - alternativeRules = ATTACH_POINT_IDENT; + case ANNOTATION_REF_RHS: + alternativeRules = ANNOTATION_REF_RHS; break; - case ATTACH_POINT_END: - alternativeRules = ATTACH_POINT_END; + case INFER_PARAM_END_OR_PARENTHESIS_END: + alternativeRules = INFER_PARAM_END_OR_PARENTHESIS_END; break; - case XML_NAMESPACE_PREFIX_DECL: - alternativeRules = XML_NAMESPACE_PREFIX_DECL; + case XML_NAVIGATE_EXPR: + alternativeRules = XML_NAVIGATE_EXPR; break; - case ENUM_MEMBER_START: - alternativeRules = ENUM_MEMBER_START; + case XML_NAME_PATTERN_RHS: + alternativeRules = XML_NAME_PATTERN_RHS; break; - case ENUM_MEMBER_RHS: - alternativeRules = ENUM_MEMBER_RHS; + case XML_ATOMIC_NAME_PATTERN_START: + alternativeRules = XML_ATOMIC_NAME_PATTERN_START; break; - case ENUM_MEMBER_END: - alternativeRules = ENUM_MEMBER_END; + case XML_ATOMIC_NAME_IDENTIFIER_RHS: + alternativeRules = XML_ATOMIC_NAME_IDENTIFIER_RHS; break; - case EXTERNAL_FUNC_BODY_OPTIONAL_ANNOTS: - alternativeRules = EXTERNAL_FUNC_BODY_OPTIONAL_ANNOTS; + case XML_STEP_START: + alternativeRules = XML_STEP_START; break; - case LIST_BP_OR_LIST_CONSTRUCTOR_MEMBER: - alternativeRules = LIST_BP_OR_LIST_CONSTRUCTOR_MEMBER; + case OPTIONAL_MATCH_GUARD: + alternativeRules = OPTIONAL_MATCH_GUARD; break; - case TUPLE_TYPE_DESC_OR_LIST_CONST_MEMBER: - alternativeRules = TUPLE_TYPE_DESC_OR_LIST_CONST_MEMBER; + case MEMBER_ACCESS_KEY_EXPR_END: + alternativeRules = MEMBER_ACCESS_KEY_EXPR_END; break; - case MAPPING_BP_OR_MAPPING_CONSTRUCTOR_MEMBER: - alternativeRules = MAPPING_BP_OR_MAPPING_CONSTRUCTOR_MEMBER; + case LISTENERS_LIST_END: + alternativeRules = LISTENERS_LIST_END; break; - case FUNC_TYPE_DESC_START: - case ANON_FUNC_EXPRESSION_START: - alternativeRules = FUNC_TYPE_DESC_START; + case OBJECT_CONS_WITHOUT_FIRST_QUALIFIER: + alternativeRules = OBJECT_CONS_WITHOUT_FIRST_QUALIFIER; break; - case MODULE_CLASS_DEFINITION_START: - alternativeRules = MODULE_CLASS_DEFINITION_START; + case RESULT_CLAUSE: + alternativeRules = RESULT_CLAUSE; break; - case CLASS_DEF_WITHOUT_FIRST_QUALIFIER: - alternativeRules = CLASS_DEF_WITHOUT_FIRST_QUALIFIER; + case EXPRESSION_RHS: + return seekMatchInExpressionRhs(lookahead, currentDepth, matchingRulesCount, isEntryPoint, false); + case VARIABLE_REF_RHS: + return seekMatchInExpressionRhs(lookahead, currentDepth, matchingRulesCount, isEntryPoint, true); + case ERROR_CONSTRUCTOR_RHS: + alternativeRules = ERROR_CONSTRUCTOR_RHS; break; - case CLASS_DEF_WITHOUT_SECOND_QUALIFIER: - alternativeRules = CLASS_DEF_WITHOUT_SECOND_QUALIFIER; - break; - case CLASS_DEF_WITHOUT_THIRD_QUALIFIER: - alternativeRules = CLASS_DEF_WITHOUT_THIRD_QUALIFIER; - break; - case OBJECT_CONSTRUCTOR_TYPE_REF: - alternativeRules = OBJECT_CONSTRUCTOR_RHS; - break; - case OBJECT_FIELD_QUALIFIER: - alternativeRules = OBJECT_FIELD_QUALIFIER; - break; - case CONFIG_VAR_DECL_RHS: - alternativeRules = CONFIG_VAR_DECL_RHS; - break; - case OPTIONAL_SERVICE_DECL_TYPE: - alternativeRules = OPTIONAL_SERVICE_DECL_TYPE; - break; - case SERVICE_IDENT_RHS: - alternativeRules = SERVICE_IDENT_RHS; - break; - case ABSOLUTE_RESOURCE_PATH_START: - alternativeRules = ABSOLUTE_RESOURCE_PATH_START; - break; - case ABSOLUTE_RESOURCE_PATH_END: - alternativeRules = ABSOLUTE_RESOURCE_PATH_END; - break; - case SERVICE_DECL_OR_VAR_DECL: - alternativeRules = SERVICE_DECL_OR_VAR_DECL; - break; - case OPTIONAL_RELATIVE_PATH: - alternativeRules = OPTIONAL_RELATIVE_PATH; - break; - case RELATIVE_RESOURCE_PATH_START: - alternativeRules = RELATIVE_RESOURCE_PATH_START; - break; - case RESOURCE_PATH_SEGMENT: - alternativeRules = RESOURCE_PATH_SEGMENT; - break; - case PATH_PARAM_OPTIONAL_ANNOTS: - alternativeRules = PATH_PARAM_OPTIONAL_ANNOTS; - break; - case PATH_PARAM_ELLIPSIS: - alternativeRules = PATH_PARAM_ELLIPSIS; - break; - case OPTIONAL_PATH_PARAM_NAME: - alternativeRules = OPTIONAL_PATH_PARAM_NAME; - break; - case RELATIVE_RESOURCE_PATH_END: - alternativeRules = RELATIVE_RESOURCE_PATH_END; - break; - case SERVICE_DECL_START: - alternativeRules = SERVICE_DECL_START; - break; - case OPTIONAL_TYPE_PARAMETER: - alternativeRules = OPTIONAL_TYPE_PARAMETER; - break; - case MAP_TYPE_OR_TYPE_REF: - alternativeRules = MAP_TYPE_OR_TYPE_REF; - break; - case OBJECT_TYPE_OR_TYPE_REF: - alternativeRules = OBJECT_TYPE_OR_TYPE_REF; - break; - case STREAM_TYPE_OR_TYPE_REF: - alternativeRules = STREAM_TYPE_OR_TYPE_REF; - break; - case TABLE_TYPE_OR_TYPE_REF: - alternativeRules = TABLE_TYPE_OR_TYPE_REF; - break; - case PARAMETERIZED_TYPE_OR_TYPE_REF: - alternativeRules = PARAMETERIZED_TYPE_OR_TYPE_REF; - break; - case TYPE_DESC_RHS_OR_TYPE_REF: - alternativeRules = TYPE_DESC_RHS_OR_TYPE_REF; - break; - case TRANSACTION_STMT_RHS_OR_TYPE_REF: - alternativeRules = TRANSACTION_STMT_RHS_OR_TYPE_REF; - break; - case TABLE_CONS_OR_QUERY_EXPR_OR_VAR_REF: - alternativeRules = TABLE_CONS_OR_QUERY_EXPR_OR_VAR_REF; - break; - case QUERY_EXPR_OR_VAR_REF: - alternativeRules = QUERY_EXPR_OR_VAR_REF; - break; - case ERROR_CONS_EXPR_OR_VAR_REF: - alternativeRules = ERROR_CONS_EXPR_OR_VAR_REF; - break; - case QUALIFIED_IDENTIFIER: - alternativeRules = QUALIFIED_IDENTIFIER; - break; - case MODULE_VAR_DECL_START: - alternativeRules = MODULE_VAR_DECL_START; - break; - case MODULE_VAR_WITHOUT_FIRST_QUAL: - alternativeRules = MODULE_VAR_WITHOUT_FIRST_QUAL; - break; - case MODULE_VAR_WITHOUT_SECOND_QUAL: - alternativeRules = MODULE_VAR_WITHOUT_SECOND_QUAL; - break; - case OBJECT_TYPE_WITHOUT_FIRST_QUALIFIER: - alternativeRules = OBJECT_TYPE_WITHOUT_FIRST_QUALIFIER; - break; - case FUNC_DEF_OR_TYPE_DESC_RHS: - alternativeRules = FUNC_DEF_OR_TYPE_DESC_RHS; - break; - case EXPR_START_OR_INFERRED_TYPEDESC_DEFAULT_START: - alternativeRules = EXPR_START_OR_INFERRED_TYPEDESC_DEFAULT_START; - break; - case TYPE_CAST_PARAM_START_OR_INFERRED_TYPEDESC_DEFAULT_END: - alternativeRules = TYPE_CAST_PARAM_START_OR_INFERRED_TYPEDESC_DEFAULT_END; - break; - case END_OF_PARAMS_OR_NEXT_PARAM_START: - alternativeRules = END_OF_PARAMS_OR_NEXT_PARAM_START; - break; - case PARAM_START: - alternativeRules = PARAM_START; - break; - case PARAM_RHS: - alternativeRules = PARAM_RHS; - break; - case FUNC_TYPE_PARAM_RHS: - alternativeRules = FUNC_TYPE_PARAM_RHS; - break; - case ANNOTATION_DECL_START: - alternativeRules = ANNOTATION_DECL_START; - break; - case OPTIONAL_TOP_LEVEL_SEMICOLON: - alternativeRules = OPTIONAL_TOP_LEVEL_SEMICOLON; - break; - case TUPLE_MEMBER: - alternativeRules = TUPLE_MEMBER; - break; - default: - return seekMatchInStmtRelatedAlternativePaths(currentCtx, lookahead, currentDepth, matchingRulesCount, - isEntryPoint); - } - - return seekInAlternativesPaths(lookahead, currentDepth, matchingRulesCount, alternativeRules, isEntryPoint); - } - - private Result seekMatchInStmtRelatedAlternativePaths(ParserRuleContext currentCtx, int lookahead, int currentDepth, - int matchingRulesCount, boolean isEntryPoint) { - ParserRuleContext[] alternativeRules; - switch (currentCtx) { - case VAR_DECL_STMT_RHS: - alternativeRules = VAR_DECL_RHS; - break; - case STATEMENT: - case STATEMENT_WITHOUT_ANNOTS: - return seekInStatements(currentCtx, lookahead, currentDepth, matchingRulesCount, isEntryPoint); - case TYPE_NAME_OR_VAR_NAME: - alternativeRules = TYPE_OR_VAR_NAME; - break; - case ELSE_BLOCK: - alternativeRules = ELSE_BLOCK; - break; - case ELSE_BODY: - alternativeRules = ELSE_BODY; - break; - case CALL_STMT_START: - alternativeRules = CALL_STATEMENT; - break; - case RETURN_STMT_RHS: - alternativeRules = RETURN_RHS; - break; - case ARRAY_LENGTH: - alternativeRules = ARRAY_LENGTH; - break; - case STMT_START_WITH_EXPR_RHS: - alternativeRules = STMT_START_WITH_EXPR_RHS; - break; - case EXPR_STMT_RHS: - alternativeRules = EXPR_STMT_RHS; - break; - case EXPRESSION_STATEMENT_START: - alternativeRules = EXPRESSION_STATEMENT_START; - break; - case TYPE_DESC_RHS: - assert isInTypeDescContext(); - alternativeRules = TYPE_DESC_RHS; - break; - case STREAM_TYPE_FIRST_PARAM_RHS: - alternativeRules = STREAM_TYPE_FIRST_PARAM_RHS; - break; - case FUNCTION_KEYWORD_RHS: - alternativeRules = FUNCTION_KEYWORD_RHS; - break; - case FUNC_TYPE_FUNC_KEYWORD_RHS_START: - alternativeRules = FUNC_TYPE_FUNC_KEYWORD_RHS_START; - break; - case WORKER_NAME_RHS: - alternativeRules = WORKER_NAME_RHS; - break; - case BINDING_PATTERN: - alternativeRules = BINDING_PATTERN; - break; - case LIST_BINDING_PATTERNS_START: - alternativeRules = LIST_BINDING_PATTERNS_START; - break; - case LIST_BINDING_PATTERN_MEMBER_END: - alternativeRules = LIST_BINDING_PATTERN_MEMBER_END; - break; - case LIST_BINDING_PATTERN_MEMBER: - alternativeRules = LIST_BINDING_PATTERN_CONTENTS; - break; - case MAPPING_BINDING_PATTERN_END: - alternativeRules = MAPPING_BINDING_PATTERN_END; - break; - case FIELD_BINDING_PATTERN_END: - alternativeRules = FIELD_BINDING_PATTERN_END; - break; - case MAPPING_BINDING_PATTERN_MEMBER: - alternativeRules = MAPPING_BINDING_PATTERN_MEMBER; - break; - case ERROR_BINDING_PATTERN_ERROR_KEYWORD_RHS: - alternativeRules = ERROR_BINDING_PATTERN_ERROR_KEYWORD_RHS; - break; - case ERROR_ARG_LIST_BINDING_PATTERN_START: - alternativeRules = ERROR_ARG_LIST_BINDING_PATTERN_START; - break; - case ERROR_MESSAGE_BINDING_PATTERN_END: - alternativeRules = ERROR_MESSAGE_BINDING_PATTERN_END; - break; - case ERROR_MESSAGE_BINDING_PATTERN_RHS: - alternativeRules = ERROR_MESSAGE_BINDING_PATTERN_RHS; - break; - case ERROR_FIELD_BINDING_PATTERN: - alternativeRules = ERROR_FIELD_BINDING_PATTERN; - break; - case ERROR_FIELD_BINDING_PATTERN_END: - alternativeRules = ERROR_FIELD_BINDING_PATTERN_END; - break; - case KEY_CONSTRAINTS_RHS: - alternativeRules = KEY_CONSTRAINTS_RHS; - break; - case TABLE_TYPE_DESC_RHS: - alternativeRules = TABLE_TYPE_DESC_RHS; - break; - case TYPE_DESC_IN_TUPLE_RHS: - alternativeRules = TYPE_DESC_IN_TUPLE_RHS; - break; - case TUPLE_TYPE_MEMBER_RHS: - alternativeRules = TUPLE_TYPE_MEMBER_RHS; - break; - case LIST_CONSTRUCTOR_MEMBER_END: - alternativeRules = LIST_CONSTRUCTOR_MEMBER_END; - break; - case NIL_OR_PARENTHESISED_TYPE_DESC_RHS: - alternativeRules = NIL_OR_PARENTHESISED_TYPE_DESC_RHS; - break; - case REMOTE_OR_RESOURCE_CALL_OR_ASYNC_SEND_RHS: - alternativeRules = REMOTE_OR_RESOURCE_CALL_OR_ASYNC_SEND_RHS; - break; - case REMOTE_CALL_OR_ASYNC_SEND_END: - alternativeRules = REMOTE_CALL_OR_ASYNC_SEND_END; - break; - case OPTIONAL_RESOURCE_ACCESS_PATH: - alternativeRules = OPTIONAL_RESOURCE_ACCESS_PATH; - break; - case RESOURCE_ACCESS_PATH_SEGMENT: - alternativeRules = RESOURCE_ACCESS_PATH_SEGMENT; - break; - case COMPUTED_SEGMENT_OR_REST_SEGMENT: - alternativeRules = COMPUTED_SEGMENT_OR_REST_SEGMENT; - break; - case RESOURCE_ACCESS_SEGMENT_RHS: - alternativeRules = RESOURCE_ACCESS_SEGMENT_RHS; - break; - case OPTIONAL_RESOURCE_ACCESS_METHOD: - alternativeRules = OPTIONAL_RESOURCE_ACCESS_METHOD; - break; - case OPTIONAL_RESOURCE_ACCESS_ACTION_ARG_LIST: - alternativeRules = OPTIONAL_RESOURCE_ACCESS_ACTION_ARG_LIST; - break; - case RECEIVE_WORKERS: - alternativeRules = RECEIVE_WORKERS; - break; - case RECEIVE_FIELD: - alternativeRules = RECEIVE_FIELD; - break; - case RECEIVE_FIELD_END: - alternativeRules = RECEIVE_FIELD_END; - break; - case WAIT_KEYWORD_RHS: - alternativeRules = WAIT_KEYWORD_RHS; - break; - case WAIT_FIELD_NAME_RHS: - alternativeRules = WAIT_FIELD_NAME_RHS; - break; - case WAIT_FIELD_END: - alternativeRules = WAIT_FIELD_END; - break; - case WAIT_FUTURE_EXPR_END: - alternativeRules = WAIT_FUTURE_EXPR_END; - break; - case OPTIONAL_PEER_WORKER: - alternativeRules = OPTIONAL_PEER_WORKER; - break; - case ROLLBACK_RHS: - alternativeRules = ROLLBACK_RHS; - break; - case RETRY_KEYWORD_RHS: - alternativeRules = RETRY_KEYWORD_RHS; - break; - case RETRY_TYPE_PARAM_RHS: - alternativeRules = RETRY_TYPE_PARAM_RHS; - break; - case RETRY_BODY: - alternativeRules = RETRY_BODY; - break; - case STMT_START_BRACKETED_LIST_MEMBER: - alternativeRules = LIST_BP_OR_TUPLE_TYPE_MEMBER; - break; - case STMT_START_BRACKETED_LIST_RHS: - alternativeRules = LIST_BP_OR_TUPLE_TYPE_DESC_RHS; - break; - case BRACKETED_LIST_MEMBER_END: - alternativeRules = BRACKETED_LIST_MEMBER_END; - break; - case BRACKETED_LIST_MEMBER: - alternativeRules = BRACKETED_LIST_MEMBER; - break; - case BRACKETED_LIST_RHS: - case BINDING_PATTERN_OR_EXPR_RHS: - case TYPE_DESC_OR_EXPR_RHS: - alternativeRules = BRACKETED_LIST_RHS; - break; - case BINDING_PATTERN_OR_VAR_REF_RHS: - alternativeRules = BINDING_PATTERN_OR_VAR_REF_RHS; - break; - case TYPE_DESC_RHS_OR_BP_RHS: - alternativeRules = TYPE_DESC_RHS_OR_BP_RHS; - break; - case LIST_BINDING_MEMBER_OR_ARRAY_LENGTH: - alternativeRules = LIST_BINDING_MEMBER_OR_ARRAY_LENGTH; - break; - case MATCH_PATTERN_LIST_MEMBER_RHS: - alternativeRules = MATCH_PATTERN_LIST_MEMBER_RHS; - break; - case MATCH_PATTERN_START: - alternativeRules = MATCH_PATTERN_START; - break; - case LIST_MATCH_PATTERNS_START: - alternativeRules = LIST_MATCH_PATTERNS_START; - break; - case LIST_MATCH_PATTERN_MEMBER: - alternativeRules = LIST_MATCH_PATTERN_MEMBER; - break; - case LIST_MATCH_PATTERN_MEMBER_RHS: - alternativeRules = LIST_MATCH_PATTERN_MEMBER_RHS; - break; - case FIELD_MATCH_PATTERNS_START: - alternativeRules = FIELD_MATCH_PATTERNS_START; - break; - case FIELD_MATCH_PATTERN_MEMBER: - alternativeRules = FIELD_MATCH_PATTERN_MEMBER; - break; - case FIELD_MATCH_PATTERN_MEMBER_RHS: - alternativeRules = FIELD_MATCH_PATTERN_MEMBER_RHS; - break; - case ERROR_MATCH_PATTERN_OR_CONST_PATTERN: - alternativeRules = ERROR_MATCH_PATTERN_OR_CONST_PATTERN; - break; - case ERROR_MATCH_PATTERN_ERROR_KEYWORD_RHS: - alternativeRules = ERROR_MATCH_PATTERN_ERROR_KEYWORD_RHS; - break; - case ERROR_ARG_LIST_MATCH_PATTERN_START: - alternativeRules = ERROR_ARG_LIST_MATCH_PATTERN_START; - break; - case ERROR_MESSAGE_MATCH_PATTERN_END: - alternativeRules = ERROR_MESSAGE_MATCH_PATTERN_END; - break; - case ERROR_MESSAGE_MATCH_PATTERN_RHS: - alternativeRules = ERROR_MESSAGE_MATCH_PATTERN_RHS; - break; - case ERROR_FIELD_MATCH_PATTERN: - alternativeRules = ERROR_FIELD_MATCH_PATTERN; - break; - case ERROR_FIELD_MATCH_PATTERN_RHS: - alternativeRules = ERROR_FIELD_MATCH_PATTERN_RHS; - break; - case NAMED_ARG_MATCH_PATTERN_RHS: - alternativeRules = NAMED_ARG_MATCH_PATTERN_RHS; - break; - case JOIN_CLAUSE_START: - alternativeRules = JOIN_CLAUSE_START; - break; - case INTERMEDIATE_CLAUSE_START: - alternativeRules = INTERMEDIATE_CLAUSE_START; - break; - case REGULAR_COMPOUND_STMT_RHS: - alternativeRules = REGULAR_COMPOUND_STMT_RHS; - break; - case NAMED_WORKER_DECL_START: - alternativeRules = NAMED_WORKER_DECL_START; - break; - case ASSIGNMENT_STMT_RHS: - alternativeRules = ASSIGNMENT_STMT_RHS; - break; - default: - return seekMatchInExprRelatedAlternativePaths(currentCtx, lookahead, currentDepth, matchingRulesCount, - isEntryPoint); - } - - return seekInAlternativesPaths(lookahead, currentDepth, matchingRulesCount, alternativeRules, isEntryPoint); - } - - private Result seekMatchInExprRelatedAlternativePaths(ParserRuleContext currentCtx, int lookahead, int currentDepth, - int matchingRulesCount, boolean isEntryPoint) { - ParserRuleContext[] alternativeRules; - switch (currentCtx) { - case EXPRESSION: - case TERMINAL_EXPRESSION: - alternativeRules = EXPRESSION_START; - break; - case ARG_START: - alternativeRules = ARG_START; - break; - case ARG_START_OR_ARG_LIST_END: - alternativeRules = ARG_START_OR_ARG_LIST_END; - break; - case NAMED_OR_POSITIONAL_ARG_RHS: - alternativeRules = NAMED_OR_POSITIONAL_ARG_RHS; - break; - case ARG_END: - alternativeRules = ARG_END; - break; - case ACCESS_EXPRESSION: - return seekInAccessExpression(currentCtx, lookahead, currentDepth, matchingRulesCount, isEntryPoint); - case FIRST_MAPPING_FIELD: - alternativeRules = FIRST_MAPPING_FIELD_START; - break; - case MAPPING_FIELD: - alternativeRules = MAPPING_FIELD_START; - break; - case SPECIFIC_FIELD: - alternativeRules = SPECIFIC_FIELD; - break; - case SPECIFIC_FIELD_RHS: - alternativeRules = SPECIFIC_FIELD_RHS; - break; - case MAPPING_FIELD_END: - alternativeRules = MAPPING_FIELD_END; - break; - case LET_VAR_DECL_START: - alternativeRules = LET_VAR_DECL_START; - break; - case ORDER_KEY_LIST_END: - alternativeRules = ORDER_KEY_LIST_END; - break; - case GROUPING_KEY_LIST_ELEMENT: - alternativeRules = GROUPING_KEY_LIST_ELEMENT; - break; - case GROUPING_KEY_LIST_ELEMENT_END: - alternativeRules = GROUPING_KEY_LIST_ELEMENT_END; - break; - case TEMPLATE_MEMBER: - alternativeRules = TEMPLATE_MEMBER; - break; - case TEMPLATE_STRING_RHS: - alternativeRules = TEMPLATE_STRING_RHS; - break; - case CONSTANT_EXPRESSION_START: - alternativeRules = CONSTANT_EXPRESSION; - break; - case LIST_CONSTRUCTOR_FIRST_MEMBER: - alternativeRules = LIST_CONSTRUCTOR_FIRST_MEMBER; - break; - case LIST_CONSTRUCTOR_MEMBER: - alternativeRules = LIST_CONSTRUCTOR_MEMBER; - break; - case TYPE_CAST_PARAM: - alternativeRules = TYPE_CAST_PARAM; - break; - case TYPE_CAST_PARAM_RHS: - alternativeRules = TYPE_CAST_PARAM_RHS; - break; - case TABLE_KEYWORD_RHS: - alternativeRules = TABLE_KEYWORD_RHS; - break; - case ROW_LIST_RHS: - alternativeRules = ROW_LIST_RHS; - break; - case TABLE_ROW_END: - alternativeRules = TABLE_ROW_END; - break; - case KEY_SPECIFIER_RHS: - alternativeRules = KEY_SPECIFIER_RHS; - break; - case TABLE_KEY_RHS: - alternativeRules = TABLE_KEY_RHS; - break; - case NEW_KEYWORD_RHS: - alternativeRules = NEW_KEYWORD_RHS; - break; - case TABLE_CONSTRUCTOR_OR_QUERY_START: - alternativeRules = TABLE_CONSTRUCTOR_OR_QUERY_START; - break; - case TABLE_CONSTRUCTOR_OR_QUERY_RHS: - alternativeRules = TABLE_CONSTRUCTOR_OR_QUERY_RHS; - break; - case QUERY_PIPELINE_RHS: - alternativeRules = QUERY_PIPELINE_RHS; - break; - case BRACED_EXPR_OR_ANON_FUNC_PARAM_RHS: - case ANON_FUNC_PARAM_RHS: - alternativeRules = BRACED_EXPR_OR_ANON_FUNC_PARAM_RHS; - break; - case PARAM_END: - alternativeRules = PARAM_END; - break; - case ANNOTATION_REF_RHS: - alternativeRules = ANNOTATION_REF_RHS; - break; - case INFER_PARAM_END_OR_PARENTHESIS_END: - alternativeRules = INFER_PARAM_END_OR_PARENTHESIS_END; - break; - case XML_NAVIGATE_EXPR: - alternativeRules = XML_NAVIGATE_EXPR; - break; - case XML_NAME_PATTERN_RHS: - alternativeRules = XML_NAME_PATTERN_RHS; - break; - case XML_ATOMIC_NAME_PATTERN_START: - alternativeRules = XML_ATOMIC_NAME_PATTERN_START; - break; - case XML_ATOMIC_NAME_IDENTIFIER_RHS: - alternativeRules = XML_ATOMIC_NAME_IDENTIFIER_RHS; - break; - case XML_STEP_START: - alternativeRules = XML_STEP_START; - break; - case OPTIONAL_MATCH_GUARD: - alternativeRules = OPTIONAL_MATCH_GUARD; - break; - case MEMBER_ACCESS_KEY_EXPR_END: - alternativeRules = MEMBER_ACCESS_KEY_EXPR_END; - break; - case LISTENERS_LIST_END: - alternativeRules = LISTENERS_LIST_END; - break; - case OBJECT_CONS_WITHOUT_FIRST_QUALIFIER: - alternativeRules = OBJECT_CONS_WITHOUT_FIRST_QUALIFIER; - break; - case RESULT_CLAUSE: - alternativeRules = RESULT_CLAUSE; - break; - case EXPRESSION_RHS: - return seekMatchInExpressionRhs(lookahead, currentDepth, matchingRulesCount, isEntryPoint, false); - case VARIABLE_REF_RHS: - return seekMatchInExpressionRhs(lookahead, currentDepth, matchingRulesCount, isEntryPoint, true); - case ERROR_CONSTRUCTOR_RHS: - alternativeRules = ERROR_CONSTRUCTOR_RHS; - break; - case SINGLE_OR_ALTERNATE_WORKER_SEPARATOR: - alternativeRules = SINGLE_OR_ALTERNATE_WORKER_SEPARATOR; + case SINGLE_OR_ALTERNATE_WORKER_SEPARATOR: + alternativeRules = SINGLE_OR_ALTERNATE_WORKER_SEPARATOR; break; default: throw new IllegalStateException("seekMatchInExprRelatedAlternativePaths found: " + currentCtx); @@ -2908,20 +2692,12 @@ private Result seekInAccessExpression(ParserRuleContext currentCtx, int lookahea ParserRuleContext nextContext; STToken nextNextToken = this.tokenReader.peek(lookahead + 1); - switch (nextNextToken.kind) { - case OPEN_PAREN_TOKEN: - nextContext = ParserRuleContext.OPEN_PARENTHESIS; - break; - case DOT_TOKEN: - nextContext = ParserRuleContext.DOT; - break; - case OPEN_BRACKET_TOKEN: - nextContext = ParserRuleContext.MEMBER_ACCESS_KEY_EXPR; - break; - default: - nextContext = getNextRuleForExpr(); - break; - } + nextContext = switch (nextNextToken.kind) { + case OPEN_PAREN_TOKEN -> ParserRuleContext.OPEN_PARENTHESIS; + case DOT_TOKEN -> ParserRuleContext.DOT; + case OPEN_BRACKET_TOKEN -> ParserRuleContext.MEMBER_ACCESS_KEY_EXPR; + default -> getNextRuleForExpr(); + }; currentMatches++; lookahead++; @@ -3075,14 +2851,10 @@ private Result seekMatchInExpressionRhs(int lookahead, int currentDepth, int cur } else if (parentCtx == ParserRuleContext.SELECT_CLAUSE || parentCtx == ParserRuleContext.COLLECT_CLAUSE) { STToken nextToken = this.tokenReader.peek(lookahead); - switch (nextToken.kind) { - case ON_KEYWORD: - case CONFLICT_KEYWORD: - nextContext = ParserRuleContext.ON_CONFLICT_CLAUSE; - break; - default: - nextContext = ParserRuleContext.QUERY_EXPRESSION_END; - } + nextContext = switch (nextToken.kind) { + case ON_KEYWORD, CONFLICT_KEYWORD -> ParserRuleContext.ON_CONFLICT_CLAUSE; + default -> ParserRuleContext.QUERY_EXPRESSION_END; + }; } else if (parentCtx == ParserRuleContext.JOIN_CLAUSE) { nextContext = ParserRuleContext.ON_CLAUSE; } else if (parentCtx == ParserRuleContext.ON_CLAUSE) { @@ -3231,42 +3003,34 @@ protected ParserRuleContext getNextRule(ParserRuleContext currentCtx, int nextLo return ParserRuleContext.RECORD_FIELD_OR_RECORD_END; case ELLIPSIS: parentCtx = getParentContext(); - switch (parentCtx) { - case MAPPING_CONSTRUCTOR: - case LIST_CONSTRUCTOR: - case ARG_LIST: - return ParserRuleContext.EXPRESSION; - case STMT_START_BRACKETED_LIST: - case BRACKETED_LIST: - case TUPLE_MEMBERS: - return ParserRuleContext.CLOSE_BRACKET; - case REST_MATCH_PATTERN: - return ParserRuleContext.VAR_KEYWORD; - case RELATIVE_RESOURCE_PATH: - return ParserRuleContext.OPTIONAL_PATH_PARAM_NAME; - case CLIENT_RESOURCE_ACCESS_ACTION: - return ParserRuleContext.EXPRESSION; - default: - return ParserRuleContext.VARIABLE_NAME; - } + return switch (parentCtx) { + case MAPPING_CONSTRUCTOR, + LIST_CONSTRUCTOR, + ARG_LIST -> ParserRuleContext.EXPRESSION; + case STMT_START_BRACKETED_LIST, + BRACKETED_LIST, + TUPLE_MEMBERS -> ParserRuleContext.CLOSE_BRACKET; + case REST_MATCH_PATTERN -> ParserRuleContext.VAR_KEYWORD; + case RELATIVE_RESOURCE_PATH -> ParserRuleContext.OPTIONAL_PATH_PARAM_NAME; + case CLIENT_RESOURCE_ACCESS_ACTION -> ParserRuleContext.EXPRESSION; + default -> ParserRuleContext.VARIABLE_NAME; + }; case QUESTION_MARK: return getNextRuleForQuestionMark(); case RECORD_TYPE_DESCRIPTOR: return ParserRuleContext.RECORD_KEYWORD; case ASTERISK: parentCtx = getParentContext(); - switch (parentCtx) { - case ARRAY_TYPE_DESCRIPTOR: - return ParserRuleContext.CLOSE_BRACKET; - case XML_ATOMIC_NAME_PATTERN: + return switch (parentCtx) { + case ARRAY_TYPE_DESCRIPTOR -> ParserRuleContext.CLOSE_BRACKET; + case XML_ATOMIC_NAME_PATTERN -> { endContext(); - return ParserRuleContext.XML_NAME_PATTERN_RHS; - case REQUIRED_PARAM: - case DEFAULTABLE_PARAM: - return ParserRuleContext.TYPE_DESC_IN_PARAM; - default: - return ParserRuleContext.TYPE_REFERENCE_IN_TYPE_INCLUSION; - } + yield ParserRuleContext.XML_NAME_PATTERN_RHS; + } + case REQUIRED_PARAM, + DEFAULTABLE_PARAM -> ParserRuleContext.TYPE_DESC_IN_PARAM; + default -> ParserRuleContext.TYPE_REFERENCE_IN_TYPE_INCLUSION; + }; case TYPE_NAME: return ParserRuleContext.TYPE_DESC_IN_TYPE_DEF; case OBJECT_TYPE_DESCRIPTOR: @@ -4412,74 +4176,57 @@ private ParserRuleContext getNextRuleForOpenParenthesis() { } private boolean isInMatchPatternCtx(ParserRuleContext context) { - switch (context) { - case MATCH_PATTERN: - case LIST_MATCH_PATTERN: - case MAPPING_MATCH_PATTERN: - case ERROR_MATCH_PATTERN: - case NAMED_ARG_MATCH_PATTERN: - return true; - default: - return false; - } + return switch (context) { + case MATCH_PATTERN, + LIST_MATCH_PATTERN, + MAPPING_MATCH_PATTERN, + ERROR_MATCH_PATTERN, + NAMED_ARG_MATCH_PATTERN -> true; + default -> false; + }; } private ParserRuleContext getNextRuleForOpenBrace() { ParserRuleContext parentCtx = getParentContext(); - switch (parentCtx) { - case OBJECT_TYPE_DESCRIPTOR: - return ParserRuleContext.OBJECT_TYPE_MEMBER; - case MODULE_CLASS_DEFINITION: - return ParserRuleContext.CLASS_MEMBER; - case OBJECT_CONSTRUCTOR: - case SERVICE_DECL: - return ParserRuleContext.OBJECT_CONSTRUCTOR_MEMBER; - case RECORD_TYPE_DESCRIPTOR: - return ParserRuleContext.RECORD_FIELD; - case MAPPING_CONSTRUCTOR: - return ParserRuleContext.FIRST_MAPPING_FIELD; - case FORK_STMT: - return ParserRuleContext.NAMED_WORKER_DECL; - case MULTI_RECEIVE_WORKERS: - return ParserRuleContext.RECEIVE_FIELD; - case MULTI_WAIT_FIELDS: - return ParserRuleContext.WAIT_FIELD_NAME; - case MODULE_ENUM_DECLARATION: - return ParserRuleContext.ENUM_MEMBER_LIST; - case MAPPING_BINDING_PATTERN: - return ParserRuleContext.MAPPING_BINDING_PATTERN_MEMBER; - case MAPPING_MATCH_PATTERN: - return ParserRuleContext.FIELD_MATCH_PATTERNS_START; - case MATCH_BODY: - return ParserRuleContext.MATCH_PATTERN; - default: - return ParserRuleContext.STATEMENT; - } + return switch (parentCtx) { + case OBJECT_TYPE_DESCRIPTOR -> ParserRuleContext.OBJECT_TYPE_MEMBER; + case MODULE_CLASS_DEFINITION -> ParserRuleContext.CLASS_MEMBER; + case OBJECT_CONSTRUCTOR, + SERVICE_DECL -> ParserRuleContext.OBJECT_CONSTRUCTOR_MEMBER; + case RECORD_TYPE_DESCRIPTOR -> ParserRuleContext.RECORD_FIELD; + case MAPPING_CONSTRUCTOR -> ParserRuleContext.FIRST_MAPPING_FIELD; + case FORK_STMT -> ParserRuleContext.NAMED_WORKER_DECL; + case MULTI_RECEIVE_WORKERS -> ParserRuleContext.RECEIVE_FIELD; + case MULTI_WAIT_FIELDS -> ParserRuleContext.WAIT_FIELD_NAME; + case MODULE_ENUM_DECLARATION -> ParserRuleContext.ENUM_MEMBER_LIST; + case MAPPING_BINDING_PATTERN -> ParserRuleContext.MAPPING_BINDING_PATTERN_MEMBER; + case MAPPING_MATCH_PATTERN -> ParserRuleContext.FIELD_MATCH_PATTERNS_START; + case MATCH_BODY -> ParserRuleContext.MATCH_PATTERN; + default -> ParserRuleContext.STATEMENT; + }; } private boolean isExpressionContext(ParserRuleContext ctx) { - switch (ctx) { - case LISTENERS_LIST: - case MAPPING_CONSTRUCTOR: - case COMPUTED_FIELD_NAME: - case LIST_CONSTRUCTOR: - case INTERPOLATION: - case ARG_LIST: - case LET_EXPR_LET_VAR_DECL: - case LET_CLAUSE_LET_VAR_DECL: - case TABLE_CONSTRUCTOR: - case QUERY_EXPRESSION: - case TABLE_CONSTRUCTOR_OR_QUERY_EXPRESSION: - case ORDER_KEY_LIST: - case GROUP_BY_CLAUSE: - case SELECT_CLAUSE: - case COLLECT_CLAUSE: - case JOIN_CLAUSE: - case ON_CONFLICT_CLAUSE: - return true; - default: - return false; - } + return switch (ctx) { + case LISTENERS_LIST, + MAPPING_CONSTRUCTOR, + COMPUTED_FIELD_NAME, + LIST_CONSTRUCTOR, + INTERPOLATION, + ARG_LIST, + LET_EXPR_LET_VAR_DECL, + LET_CLAUSE_LET_VAR_DECL, + TABLE_CONSTRUCTOR, + QUERY_EXPRESSION, + TABLE_CONSTRUCTOR_OR_QUERY_EXPRESSION, + ORDER_KEY_LIST, + GROUP_BY_CLAUSE, + SELECT_CLAUSE, + COLLECT_CLAUSE, + JOIN_CLAUSE, + ON_CONFLICT_CLAUSE -> true; + default -> false; + }; } /** @@ -4511,70 +4258,47 @@ private ParserRuleContext getNextRuleForParamType() { */ private ParserRuleContext getNextRuleForComma() { ParserRuleContext parentCtx = getParentContext(); - switch (parentCtx) { - case PARAM_LIST: - case REQUIRED_PARAM: - case DEFAULTABLE_PARAM: - case REST_PARAM: + return switch (parentCtx) { + case PARAM_LIST, + REQUIRED_PARAM, + DEFAULTABLE_PARAM, + REST_PARAM -> { endContext(); - return parentCtx; - case ARG_LIST: - return ParserRuleContext.ARG_START; - case MAPPING_CONSTRUCTOR: - return ParserRuleContext.MAPPING_FIELD; - case LIST_CONSTRUCTOR: - return ParserRuleContext.LIST_CONSTRUCTOR_MEMBER; - case LISTENERS_LIST: - case ORDER_KEY_LIST: - return ParserRuleContext.EXPRESSION; - case GROUP_BY_CLAUSE: - return ParserRuleContext.GROUPING_KEY_LIST_ELEMENT; - case ANNOT_ATTACH_POINTS_LIST: - return ParserRuleContext.ATTACH_POINT; - case TABLE_CONSTRUCTOR: - return ParserRuleContext.MAPPING_CONSTRUCTOR; - case KEY_SPECIFIER: - return ParserRuleContext.VARIABLE_NAME; - case LET_EXPR_LET_VAR_DECL: - case LET_CLAUSE_LET_VAR_DECL: - return ParserRuleContext.LET_VAR_DECL_START; - case TYPE_DESC_IN_STREAM_TYPE_DESC: - return ParserRuleContext.TYPE_DESCRIPTOR; - case BRACED_EXPR_OR_ANON_FUNC_PARAMS: - return ParserRuleContext.IMPLICIT_ANON_FUNC_PARAM; - case TUPLE_MEMBERS: - return ParserRuleContext.TUPLE_MEMBER; - case LIST_BINDING_PATTERN: - return ParserRuleContext.LIST_BINDING_PATTERN_MEMBER; - case MAPPING_BINDING_PATTERN: - case MAPPING_BP_OR_MAPPING_CONSTRUCTOR: - return ParserRuleContext.MAPPING_BINDING_PATTERN_MEMBER; - case MULTI_RECEIVE_WORKERS: - return ParserRuleContext.RECEIVE_FIELD; - case MULTI_WAIT_FIELDS: - return ParserRuleContext.WAIT_FIELD_NAME; - case ENUM_MEMBER_LIST: - return ParserRuleContext.ENUM_MEMBER_START; - case MEMBER_ACCESS_KEY_EXPR: - return ParserRuleContext.MEMBER_ACCESS_KEY_EXPR_END; - case STMT_START_BRACKETED_LIST: - return ParserRuleContext.STMT_START_BRACKETED_LIST_MEMBER; - case BRACKETED_LIST: - return ParserRuleContext.BRACKETED_LIST_MEMBER; - case LIST_MATCH_PATTERN: - return ParserRuleContext.LIST_MATCH_PATTERN_MEMBER; - case ERROR_BINDING_PATTERN: - return ParserRuleContext.ERROR_FIELD_BINDING_PATTERN; - case MAPPING_MATCH_PATTERN: - return ParserRuleContext.FIELD_MATCH_PATTERN_MEMBER; - case ERROR_MATCH_PATTERN: - return ParserRuleContext.ERROR_FIELD_MATCH_PATTERN; - case NAMED_ARG_MATCH_PATTERN: + yield parentCtx; + } + case ARG_LIST -> ParserRuleContext.ARG_START; + case MAPPING_CONSTRUCTOR -> ParserRuleContext.MAPPING_FIELD; + case LIST_CONSTRUCTOR -> ParserRuleContext.LIST_CONSTRUCTOR_MEMBER; + case LISTENERS_LIST, + ORDER_KEY_LIST -> ParserRuleContext.EXPRESSION; + case GROUP_BY_CLAUSE -> ParserRuleContext.GROUPING_KEY_LIST_ELEMENT; + case ANNOT_ATTACH_POINTS_LIST -> ParserRuleContext.ATTACH_POINT; + case TABLE_CONSTRUCTOR -> ParserRuleContext.MAPPING_CONSTRUCTOR; + case KEY_SPECIFIER -> ParserRuleContext.VARIABLE_NAME; + case LET_EXPR_LET_VAR_DECL, + LET_CLAUSE_LET_VAR_DECL -> ParserRuleContext.LET_VAR_DECL_START; + case TYPE_DESC_IN_STREAM_TYPE_DESC -> ParserRuleContext.TYPE_DESCRIPTOR; + case BRACED_EXPR_OR_ANON_FUNC_PARAMS -> ParserRuleContext.IMPLICIT_ANON_FUNC_PARAM; + case TUPLE_MEMBERS -> ParserRuleContext.TUPLE_MEMBER; + case LIST_BINDING_PATTERN -> ParserRuleContext.LIST_BINDING_PATTERN_MEMBER; + case MAPPING_BINDING_PATTERN, + MAPPING_BP_OR_MAPPING_CONSTRUCTOR -> ParserRuleContext.MAPPING_BINDING_PATTERN_MEMBER; + case MULTI_RECEIVE_WORKERS -> ParserRuleContext.RECEIVE_FIELD; + case MULTI_WAIT_FIELDS -> ParserRuleContext.WAIT_FIELD_NAME; + case ENUM_MEMBER_LIST -> ParserRuleContext.ENUM_MEMBER_START; + case MEMBER_ACCESS_KEY_EXPR -> ParserRuleContext.MEMBER_ACCESS_KEY_EXPR_END; + case STMT_START_BRACKETED_LIST -> ParserRuleContext.STMT_START_BRACKETED_LIST_MEMBER; + case BRACKETED_LIST -> ParserRuleContext.BRACKETED_LIST_MEMBER; + case LIST_MATCH_PATTERN -> ParserRuleContext.LIST_MATCH_PATTERN_MEMBER; + case ERROR_BINDING_PATTERN -> ParserRuleContext.ERROR_FIELD_BINDING_PATTERN; + case MAPPING_MATCH_PATTERN -> ParserRuleContext.FIELD_MATCH_PATTERN_MEMBER; + case ERROR_MATCH_PATTERN -> ParserRuleContext.ERROR_FIELD_MATCH_PATTERN; + case NAMED_ARG_MATCH_PATTERN -> { endContext(); - return ParserRuleContext.NAMED_ARG_MATCH_PATTERN_RHS; - default: - throw new IllegalStateException("getNextRuleForComma found: " + parentCtx); - } + yield ParserRuleContext.NAMED_ARG_MATCH_PATTERN_RHS; + } + default -> throw new IllegalStateException("getNextRuleForComma found: " + parentCtx); + }; } /** @@ -4706,29 +4430,27 @@ private ParserRuleContext getNextRuleForTypeDescriptor() { } private boolean isInTypeDescContext() { - switch (getParentContext()) { - case TYPE_DESC_IN_ANNOTATION_DECL: - case TYPE_DESC_BEFORE_IDENTIFIER: - case TYPE_DESC_BEFORE_IDENTIFIER_IN_GROUPING_KEY: - case TYPE_DESC_IN_RECORD_FIELD: - case TYPE_DESC_IN_PARAM: - case TYPE_DESC_IN_TYPE_BINDING_PATTERN: - case TYPE_DESC_IN_TYPE_DEF: - case TYPE_DESC_IN_ANGLE_BRACKETS: - case TYPE_DESC_IN_RETURN_TYPE_DESC: - case TYPE_DESC_IN_EXPRESSION: - case TYPE_DESC_IN_STREAM_TYPE_DESC: - case TYPE_DESC_IN_PARENTHESIS: - case TYPE_DESC_IN_TUPLE: - case TYPE_DESC_IN_SERVICE: - case TYPE_DESC_IN_PATH_PARAM: - case STMT_START_BRACKETED_LIST: - case BRACKETED_LIST: - case TYPE_REFERENCE_IN_TYPE_INCLUSION: - return true; - default: - return false; - } + return switch (getParentContext()) { + case TYPE_DESC_IN_ANNOTATION_DECL, + TYPE_DESC_BEFORE_IDENTIFIER, + TYPE_DESC_BEFORE_IDENTIFIER_IN_GROUPING_KEY, + TYPE_DESC_IN_RECORD_FIELD, + TYPE_DESC_IN_PARAM, + TYPE_DESC_IN_TYPE_BINDING_PATTERN, + TYPE_DESC_IN_TYPE_DEF, + TYPE_DESC_IN_ANGLE_BRACKETS, + TYPE_DESC_IN_RETURN_TYPE_DESC, + TYPE_DESC_IN_EXPRESSION, + TYPE_DESC_IN_STREAM_TYPE_DESC, + TYPE_DESC_IN_PARENTHESIS, + TYPE_DESC_IN_TUPLE, + TYPE_DESC_IN_SERVICE, + TYPE_DESC_IN_PATH_PARAM, + STMT_START_BRACKETED_LIST, + BRACKETED_LIST, + TYPE_REFERENCE_IN_TYPE_INCLUSION -> true; + default -> false; + }; } /** @@ -4738,37 +4460,34 @@ private boolean isInTypeDescContext() { */ private ParserRuleContext getNextRuleForEqualOp() { ParserRuleContext parentCtx = getParentContext(); - switch (parentCtx) { - case EXTERNAL_FUNC_BODY: - return ParserRuleContext.EXTERNAL_FUNC_BODY_OPTIONAL_ANNOTS; - case REQUIRED_PARAM: - case DEFAULTABLE_PARAM: - return ParserRuleContext.EXPR_START_OR_INFERRED_TYPEDESC_DEFAULT_START; - case RECORD_FIELD: - case ARG_LIST: - case OBJECT_CONSTRUCTOR_MEMBER: - case CLASS_MEMBER: - case OBJECT_TYPE_MEMBER: - case LISTENER_DECL: - case CONSTANT_DECL: - case LET_EXPR_LET_VAR_DECL: - case LET_CLAUSE_LET_VAR_DECL: - case ENUM_MEMBER_LIST: - case GROUP_BY_CLAUSE: - return ParserRuleContext.EXPRESSION; - case FUNC_DEF_OR_FUNC_TYPE: + return switch (parentCtx) { + case EXTERNAL_FUNC_BODY -> ParserRuleContext.EXTERNAL_FUNC_BODY_OPTIONAL_ANNOTS; + case REQUIRED_PARAM, + DEFAULTABLE_PARAM -> ParserRuleContext.EXPR_START_OR_INFERRED_TYPEDESC_DEFAULT_START; + case RECORD_FIELD, + ARG_LIST, + OBJECT_CONSTRUCTOR_MEMBER, + CLASS_MEMBER, + OBJECT_TYPE_MEMBER, + LISTENER_DECL, + CONSTANT_DECL, + LET_EXPR_LET_VAR_DECL, + LET_CLAUSE_LET_VAR_DECL, + ENUM_MEMBER_LIST, + GROUP_BY_CLAUSE -> ParserRuleContext.EXPRESSION; + case FUNC_DEF_OR_FUNC_TYPE -> { switchContext(ParserRuleContext.VAR_DECL_STMT); - return ParserRuleContext.EXPRESSION; - case NAMED_ARG_MATCH_PATTERN: - return ParserRuleContext.MATCH_PATTERN; - case ERROR_BINDING_PATTERN: - return ParserRuleContext.BINDING_PATTERN; - default: + yield ParserRuleContext.EXPRESSION; + } + case NAMED_ARG_MATCH_PATTERN -> ParserRuleContext.MATCH_PATTERN; + case ERROR_BINDING_PATTERN -> ParserRuleContext.BINDING_PATTERN; + default -> { if (isStatement(parentCtx)) { - return ParserRuleContext.EXPRESSION; + yield ParserRuleContext.EXPRESSION; } throw new IllegalStateException("getNextRuleForEqualOp found: " + parentCtx); - } + } + }; } /** @@ -4840,12 +4559,10 @@ private ParserRuleContext getNextRuleForCloseBrace(int nextLookahead) { parentCtx = getParentContext(); if (parentCtx == ParserRuleContext.FORK_STMT) { nextToken = this.tokenReader.peek(nextLookahead); - switch (nextToken.kind) { - case CLOSE_BRACE_TOKEN: - return ParserRuleContext.CLOSE_BRACE; - default: - return ParserRuleContext.REGULAR_COMPOUND_STMT_RHS; - } + return switch (nextToken.kind) { + case CLOSE_BRACE_TOKEN -> ParserRuleContext.CLOSE_BRACE; + default -> ParserRuleContext.REGULAR_COMPOUND_STMT_RHS; + }; } else { return ParserRuleContext.REGULAR_COMPOUND_STMT_RHS; } @@ -4907,24 +4624,22 @@ private ParserRuleContext getNextRuleForCloseBrace(int nextLookahead) { private ParserRuleContext getNextRuleForCloseBraceInFuncBody() { ParserRuleContext parentCtx; parentCtx = getParentContext(); - switch (parentCtx) { - case OBJECT_CONSTRUCTOR_MEMBER: - return ParserRuleContext.OBJECT_CONSTRUCTOR_MEMBER_START; - case CLASS_MEMBER: - case OBJECT_TYPE_MEMBER: - return ParserRuleContext.CLASS_MEMBER_OR_OBJECT_MEMBER_START; - case COMP_UNIT: - return ParserRuleContext.OPTIONAL_TOP_LEVEL_SEMICOLON; - case FUNC_DEF: - case FUNC_DEF_OR_FUNC_TYPE: + return switch (parentCtx) { + case OBJECT_CONSTRUCTOR_MEMBER -> ParserRuleContext.OBJECT_CONSTRUCTOR_MEMBER_START; + case CLASS_MEMBER, + OBJECT_TYPE_MEMBER -> ParserRuleContext.CLASS_MEMBER_OR_OBJECT_MEMBER_START; + case COMP_UNIT -> ParserRuleContext.OPTIONAL_TOP_LEVEL_SEMICOLON; + case FUNC_DEF, + FUNC_DEF_OR_FUNC_TYPE -> { endContext(); // end func-def - return getNextRuleForCloseBraceInFuncBody(); - case ANON_FUNC_EXPRESSION: - default: + yield getNextRuleForCloseBraceInFuncBody(); + } + default -> { // Anonynous func endContext(); // end anon-func - return ParserRuleContext.EXPRESSION_RHS; - } + yield ParserRuleContext.EXPRESSION_RHS; + } + }; } private ParserRuleContext getNextRuleForAnnotationEnd(int nextLookahead) { @@ -4937,45 +4652,34 @@ private ParserRuleContext getNextRuleForAnnotationEnd(int nextLookahead) { endContext(); // end annotations parentCtx = getParentContext(); - switch (parentCtx) { - case COMP_UNIT: - return ParserRuleContext.TOP_LEVEL_NODE_WITHOUT_METADATA; - case FUNC_DEF: - case FUNC_TYPE_DESC: - case FUNC_DEF_OR_FUNC_TYPE: - case ANON_FUNC_EXPRESSION: - case FUNC_TYPE_DESC_OR_ANON_FUNC: - return ParserRuleContext.TYPE_DESC_IN_RETURN_TYPE_DESC; - case LET_EXPR_LET_VAR_DECL: - case LET_CLAUSE_LET_VAR_DECL: - return ParserRuleContext.TYPE_DESC_IN_TYPE_BINDING_PATTERN; - case RECORD_FIELD: - return ParserRuleContext.RECORD_FIELD_WITHOUT_METADATA; - case OBJECT_CONSTRUCTOR_MEMBER: - return ParserRuleContext.OBJECT_CONS_MEMBER_WITHOUT_META; - case CLASS_MEMBER: - case OBJECT_TYPE_MEMBER: - return ParserRuleContext.CLASS_MEMBER_OR_OBJECT_MEMBER_WITHOUT_META; - case FUNC_BODY_BLOCK: - return ParserRuleContext.STATEMENT_WITHOUT_ANNOTS; - case EXTERNAL_FUNC_BODY: - return ParserRuleContext.EXTERNAL_KEYWORD; - case TYPE_CAST: - return ParserRuleContext.TYPE_CAST_PARAM_RHS; - case ENUM_MEMBER_LIST: - return ParserRuleContext.ENUM_MEMBER_NAME; - case RELATIVE_RESOURCE_PATH: - return ParserRuleContext.TYPE_DESC_IN_PATH_PARAM; - case TUPLE_MEMBERS: - return ParserRuleContext.TUPLE_MEMBER; - default: + return switch (parentCtx) { + case COMP_UNIT -> ParserRuleContext.TOP_LEVEL_NODE_WITHOUT_METADATA; + case FUNC_DEF, + FUNC_TYPE_DESC, + FUNC_DEF_OR_FUNC_TYPE, + ANON_FUNC_EXPRESSION, + FUNC_TYPE_DESC_OR_ANON_FUNC -> ParserRuleContext.TYPE_DESC_IN_RETURN_TYPE_DESC; + case LET_EXPR_LET_VAR_DECL, + LET_CLAUSE_LET_VAR_DECL -> ParserRuleContext.TYPE_DESC_IN_TYPE_BINDING_PATTERN; + case RECORD_FIELD -> ParserRuleContext.RECORD_FIELD_WITHOUT_METADATA; + case OBJECT_CONSTRUCTOR_MEMBER -> ParserRuleContext.OBJECT_CONS_MEMBER_WITHOUT_META; + case CLASS_MEMBER, + OBJECT_TYPE_MEMBER -> ParserRuleContext.CLASS_MEMBER_OR_OBJECT_MEMBER_WITHOUT_META; + case FUNC_BODY_BLOCK -> ParserRuleContext.STATEMENT_WITHOUT_ANNOTS; + case EXTERNAL_FUNC_BODY -> ParserRuleContext.EXTERNAL_KEYWORD; + case TYPE_CAST -> ParserRuleContext.TYPE_CAST_PARAM_RHS; + case ENUM_MEMBER_LIST -> ParserRuleContext.ENUM_MEMBER_NAME; + case RELATIVE_RESOURCE_PATH -> ParserRuleContext.TYPE_DESC_IN_PATH_PARAM; + case TUPLE_MEMBERS -> ParserRuleContext.TUPLE_MEMBER; + default -> { if (isParameter(parentCtx)) { - return ParserRuleContext.TYPE_DESC_IN_PARAM; + yield ParserRuleContext.TYPE_DESC_IN_PARAM; } // everything else, treat as an annotation in an expression - return ParserRuleContext.EXPRESSION; - } + yield ParserRuleContext.EXPRESSION; + } + }; } /** @@ -5163,16 +4867,12 @@ private ParserRuleContext getNextRuleForSemicolon(int nextLookahead) { private ParserRuleContext getNextRuleForDot() { ParserRuleContext parentCtx = getParentContext(); - switch (parentCtx) { - case IMPORT_DECL: - return ParserRuleContext.IMPORT_MODULE_NAME; - case RELATIVE_RESOURCE_PATH: - return ParserRuleContext.RESOURCE_ACCESSOR_DEF_OR_DECL_RHS; - case CLIENT_RESOURCE_ACCESS_ACTION: - return ParserRuleContext.METHOD_NAME; - default: - return ParserRuleContext.FIELD_ACCESS_IDENTIFIER; - } + return switch (parentCtx) { + case IMPORT_DECL -> ParserRuleContext.IMPORT_MODULE_NAME; + case RELATIVE_RESOURCE_PATH -> ParserRuleContext.RESOURCE_ACCESSOR_DEF_OR_DECL_RHS; + case CLIENT_RESOURCE_ACCESS_ACTION -> ParserRuleContext.METHOD_NAME; + default -> ParserRuleContext.FIELD_ACCESS_IDENTIFIER; + }; } /** @@ -5181,16 +4881,15 @@ private ParserRuleContext getNextRuleForDot() { * @return Next parser context */ private ParserRuleContext getNextRuleForQuestionMark() { - ParserRuleContext parentCtx = getParentContext(); - switch (parentCtx) { - case OPTIONAL_TYPE_DESCRIPTOR: - endContext(); - return ParserRuleContext.TYPE_DESC_RHS; - case CONDITIONAL_EXPRESSION: - return ParserRuleContext.EXPRESSION; - default: - return ParserRuleContext.SEMICOLON; - } + ParserRuleContext parentCtx = getParentContext(); + return switch (parentCtx) { + case OPTIONAL_TYPE_DESCRIPTOR -> { + endContext(); + yield ParserRuleContext.TYPE_DESC_RHS; + } + case CONDITIONAL_EXPRESSION -> ParserRuleContext.EXPRESSION; + default -> ParserRuleContext.SEMICOLON; + }; } /** @@ -5200,27 +4899,21 @@ private ParserRuleContext getNextRuleForQuestionMark() { */ private ParserRuleContext getNextRuleForOpenBracket() { ParserRuleContext parentCtx = getParentContext(); - switch (parentCtx) { - case ARRAY_TYPE_DESCRIPTOR: - return ParserRuleContext.ARRAY_LENGTH; - case LIST_CONSTRUCTOR: - return ParserRuleContext.LIST_CONSTRUCTOR_FIRST_MEMBER; - case TABLE_CONSTRUCTOR: - return ParserRuleContext.ROW_LIST_RHS; - case LIST_BINDING_PATTERN: - return ParserRuleContext.LIST_BINDING_PATTERNS_START; - case LIST_MATCH_PATTERN: - return ParserRuleContext.LIST_MATCH_PATTERNS_START; - case RELATIVE_RESOURCE_PATH: - return ParserRuleContext.PATH_PARAM_OPTIONAL_ANNOTS; - case CLIENT_RESOURCE_ACCESS_ACTION: - return ParserRuleContext.COMPUTED_SEGMENT_OR_REST_SEGMENT; - default: + return switch (parentCtx) { + case ARRAY_TYPE_DESCRIPTOR -> ParserRuleContext.ARRAY_LENGTH; + case LIST_CONSTRUCTOR -> ParserRuleContext.LIST_CONSTRUCTOR_FIRST_MEMBER; + case TABLE_CONSTRUCTOR -> ParserRuleContext.ROW_LIST_RHS; + case LIST_BINDING_PATTERN -> ParserRuleContext.LIST_BINDING_PATTERNS_START; + case LIST_MATCH_PATTERN -> ParserRuleContext.LIST_MATCH_PATTERNS_START; + case RELATIVE_RESOURCE_PATH -> ParserRuleContext.PATH_PARAM_OPTIONAL_ANNOTS; + case CLIENT_RESOURCE_ACCESS_ACTION -> ParserRuleContext.COMPUTED_SEGMENT_OR_REST_SEGMENT; + default -> { if (isInTypeDescContext()) { - return ParserRuleContext.TUPLE_MEMBERS; + yield ParserRuleContext.TUPLE_MEMBERS; } - return ParserRuleContext.EXPRESSION; - } + yield ParserRuleContext.EXPRESSION; + } + }; } /** @@ -5280,14 +4973,13 @@ private ParserRuleContext getNextRuleForCloseBracket() { */ private ParserRuleContext getNextRuleForDecimalIntegerLiteral() { ParserRuleContext parentCtx = getParentContext(); - switch (parentCtx) { - case CONSTANT_EXPRESSION: + return switch (parentCtx) { + case CONSTANT_EXPRESSION -> { endContext(); - return getNextRuleForConstExpr(); - case ARRAY_TYPE_DESCRIPTOR: - default: - return ParserRuleContext.CLOSE_BRACKET; - } + yield getNextRuleForConstExpr(); + } + default -> ParserRuleContext.CLOSE_BRACKET; + }; } private ParserRuleContext getNextRuleForExpr() { @@ -5316,25 +5008,23 @@ private ParserRuleContext getNextRuleForExprStartsWithVarRef() { private ParserRuleContext getNextRuleForConstExpr() { ParserRuleContext parentCtx = getParentContext(); - switch (parentCtx) { - case XML_NAMESPACE_DECLARATION: - return ParserRuleContext.XML_NAMESPACE_PREFIX_DECL; - default: + return switch (parentCtx) { + case XML_NAMESPACE_DECLARATION -> ParserRuleContext.XML_NAMESPACE_PREFIX_DECL; + default -> { if (isInTypeDescContext()) { - return ParserRuleContext.TYPE_DESC_RHS; + yield ParserRuleContext.TYPE_DESC_RHS; } - return getNextRuleForMatchPattern(); - } + yield getNextRuleForMatchPattern(); + } + }; } private ParserRuleContext getNextRuleForLt() { ParserRuleContext parentCtx = getParentContext(); - switch (parentCtx) { - case TYPE_CAST: - return ParserRuleContext.TYPE_CAST_PARAM; - default: - return ParserRuleContext.TYPE_DESC_IN_ANGLE_BRACKETS; - } + return switch (parentCtx) { + case TYPE_CAST -> ParserRuleContext.TYPE_CAST_PARAM; + default -> ParserRuleContext.TYPE_DESC_IN_ANGLE_BRACKETS; + }; } private ParserRuleContext getNextRuleForGt() { @@ -5504,49 +5194,40 @@ private ParserRuleContext getNextRuleForIdentifier() { private ParserRuleContext getNextRuleForColon() { ParserRuleContext parentCtx; parentCtx = getParentContext(); - switch (parentCtx) { - case MAPPING_CONSTRUCTOR: - return ParserRuleContext.EXPRESSION; - case MULTI_RECEIVE_WORKERS: - return ParserRuleContext.PEER_WORKER_NAME; - case MULTI_WAIT_FIELDS: - return ParserRuleContext.EXPRESSION; - case CONDITIONAL_EXPRESSION: + return switch (parentCtx) { + case MAPPING_CONSTRUCTOR -> ParserRuleContext.EXPRESSION; + case MULTI_RECEIVE_WORKERS -> ParserRuleContext.PEER_WORKER_NAME; + case MULTI_WAIT_FIELDS -> ParserRuleContext.EXPRESSION; + case CONDITIONAL_EXPRESSION -> { endContext(); // end conditional-expr - return ParserRuleContext.EXPRESSION; - case MAPPING_BINDING_PATTERN: - case MAPPING_BP_OR_MAPPING_CONSTRUCTOR: - return ParserRuleContext.VARIABLE_NAME; - case FIELD_BINDING_PATTERN: + yield ParserRuleContext.EXPRESSION; + } + case MAPPING_BINDING_PATTERN, + MAPPING_BP_OR_MAPPING_CONSTRUCTOR -> ParserRuleContext.VARIABLE_NAME; + case FIELD_BINDING_PATTERN -> { endContext(); - return ParserRuleContext.VARIABLE_NAME; - case XML_ATOMIC_NAME_PATTERN: - return ParserRuleContext.XML_ATOMIC_NAME_IDENTIFIER_RHS; - case MAPPING_MATCH_PATTERN: - return ParserRuleContext.MATCH_PATTERN; - default: - return ParserRuleContext.IDENTIFIER; - } + yield ParserRuleContext.VARIABLE_NAME; + } + case XML_ATOMIC_NAME_PATTERN -> ParserRuleContext.XML_ATOMIC_NAME_IDENTIFIER_RHS; + case MAPPING_MATCH_PATTERN -> ParserRuleContext.MATCH_PATTERN; + default -> ParserRuleContext.IDENTIFIER; + }; } private ParserRuleContext getNextRuleForMatchPattern() { ParserRuleContext parentCtx = getParentContext(); - switch (parentCtx) { - case LIST_MATCH_PATTERN: - return ParserRuleContext.LIST_MATCH_PATTERN_MEMBER_RHS; - case MAPPING_MATCH_PATTERN: - return ParserRuleContext.FIELD_MATCH_PATTERN_MEMBER_RHS; - case MATCH_PATTERN: - return ParserRuleContext.MATCH_PATTERN_LIST_MEMBER_RHS; - case ERROR_MATCH_PATTERN: - case NAMED_ARG_MATCH_PATTERN: - return ParserRuleContext.ERROR_FIELD_MATCH_PATTERN_RHS; - case ERROR_ARG_LIST_MATCH_PATTERN_FIRST_ARG: + return switch (parentCtx) { + case LIST_MATCH_PATTERN -> ParserRuleContext.LIST_MATCH_PATTERN_MEMBER_RHS; + case MAPPING_MATCH_PATTERN -> ParserRuleContext.FIELD_MATCH_PATTERN_MEMBER_RHS; + case MATCH_PATTERN -> ParserRuleContext.MATCH_PATTERN_LIST_MEMBER_RHS; + case ERROR_MATCH_PATTERN, + NAMED_ARG_MATCH_PATTERN -> ParserRuleContext.ERROR_FIELD_MATCH_PATTERN_RHS; + case ERROR_ARG_LIST_MATCH_PATTERN_FIRST_ARG -> { endContext(); - return ParserRuleContext.ERROR_MESSAGE_MATCH_PATTERN_END; - default: - return ParserRuleContext.OPTIONAL_MATCH_GUARD; - } + yield ParserRuleContext.ERROR_MESSAGE_MATCH_PATTERN_END; + } + default -> ParserRuleContext.OPTIONAL_MATCH_GUARD; + }; } /** @@ -5556,24 +5237,22 @@ private ParserRuleContext getNextRuleForMatchPattern() { */ private ParserRuleContext getNextRuleForTypeReference() { ParserRuleContext parentCtx = getParentContext(); - switch (parentCtx) { - case ERROR_CONSTRUCTOR: - return ParserRuleContext.ARG_LIST_OPEN_PAREN; - case OBJECT_CONSTRUCTOR: - return ParserRuleContext.OPEN_BRACE; - case ERROR_MATCH_PATTERN: - case ERROR_BINDING_PATTERN: - return ParserRuleContext.OPEN_PARENTHESIS; - case CLASS_DESCRIPTOR_IN_NEW_EXPR: + return switch (parentCtx) { + case ERROR_CONSTRUCTOR -> ParserRuleContext.ARG_LIST_OPEN_PAREN; + case OBJECT_CONSTRUCTOR -> ParserRuleContext.OPEN_BRACE; + case ERROR_MATCH_PATTERN, + ERROR_BINDING_PATTERN -> ParserRuleContext.OPEN_PARENTHESIS; + case CLASS_DESCRIPTOR_IN_NEW_EXPR -> { endContext(); - return ParserRuleContext.ARG_LIST_OPEN_PAREN; - default: + yield ParserRuleContext.ARG_LIST_OPEN_PAREN; + } + default -> { if (isInTypeDescContext()) { - return ParserRuleContext.TYPE_DESC_RHS; + yield ParserRuleContext.TYPE_DESC_RHS; } - throw new IllegalStateException("getNextRuleForTypeReference found: " + parentCtx); - } + } + }; } /** @@ -5587,16 +5266,13 @@ private ParserRuleContext getNextRuleForErrorKeyword() { } ParserRuleContext parentCtx = getParentContext(); - switch (parentCtx) { - case ERROR_MATCH_PATTERN: - return ParserRuleContext.ERROR_MATCH_PATTERN_ERROR_KEYWORD_RHS; - case ERROR_BINDING_PATTERN: - return ParserRuleContext.ERROR_BINDING_PATTERN_ERROR_KEYWORD_RHS; - case ERROR_CONSTRUCTOR: - return ParserRuleContext.ERROR_CONSTRUCTOR_RHS; - } + return switch (parentCtx) { + case ERROR_MATCH_PATTERN -> ParserRuleContext.ERROR_MATCH_PATTERN_ERROR_KEYWORD_RHS; + case ERROR_BINDING_PATTERN -> ParserRuleContext.ERROR_BINDING_PATTERN_ERROR_KEYWORD_RHS; + case ERROR_CONSTRUCTOR -> ParserRuleContext.ERROR_CONSTRUCTOR_RHS; + default -> ParserRuleContext.ARG_LIST_OPEN_PAREN; + }; - return ParserRuleContext.ARG_LIST_OPEN_PAREN; } /** @@ -5632,565 +5308,400 @@ private ParserRuleContext getNextRuleForFuncTypeFuncKeywordRhs() { private ParserRuleContext getNextRuleForAction() { ParserRuleContext parentCtx = getParentContext(); - switch (parentCtx) { - case MATCH_STMT: - return ParserRuleContext.MATCH_BODY; - case FOREACH_STMT: - return ParserRuleContext.BLOCK_STMT; - default: - return ParserRuleContext.SEMICOLON; - } + return switch (parentCtx) { + case MATCH_STMT -> ParserRuleContext.MATCH_BODY; + case FOREACH_STMT -> ParserRuleContext.BLOCK_STMT; + default -> ParserRuleContext.SEMICOLON; + }; } /** * Check whether the given context is a statement. - * - * @param parentCtx Parser context to check - * @return true if the given context is a statement. false otherwise - */ - private boolean isStatement(ParserRuleContext parentCtx) { - switch (parentCtx) { - case STATEMENT: - case STATEMENT_WITHOUT_ANNOTS: - case VAR_DECL_STMT: - case ASSIGNMENT_STMT: - case ASSIGNMENT_OR_VAR_DECL_STMT: - case IF_BLOCK: - case BLOCK_STMT: - case WHILE_BLOCK: - case DO_BLOCK: - case CALL_STMT: - case PANIC_STMT: - case CONTINUE_STATEMENT: - case BREAK_STATEMENT: - case RETURN_STMT: - case FAIL_STATEMENT: - case LOCAL_TYPE_DEFINITION_STMT: - case EXPRESSION_STATEMENT: - case LOCK_STMT: - case FORK_STMT: - case FOREACH_STMT: - case TRANSACTION_STMT: - case RETRY_STMT: - case ROLLBACK_STMT: - case AMBIGUOUS_STMT: - case MATCH_STMT: - return true; - default: - return false; - } - } - - /** - * Check whether the given token refers to a binary operator. - * - * @param token Token to check - * @return true if the given token refers to a binary operator. false otherwise - */ - private boolean isBinaryOperator(STToken token) { - switch (token.kind) { - case PLUS_TOKEN: - case MINUS_TOKEN: - case SLASH_TOKEN: - case ASTERISK_TOKEN: - case GT_TOKEN: - case LT_TOKEN: - case DOUBLE_EQUAL_TOKEN: - case TRIPPLE_EQUAL_TOKEN: - case LT_EQUAL_TOKEN: - case GT_EQUAL_TOKEN: - case NOT_EQUAL_TOKEN: - case NOT_DOUBLE_EQUAL_TOKEN: - case BITWISE_AND_TOKEN: - case BITWISE_XOR_TOKEN: - case PIPE_TOKEN: - case LOGICAL_AND_TOKEN: - case LOGICAL_OR_TOKEN: - case DOUBLE_LT_TOKEN: - case DOUBLE_GT_TOKEN: - case TRIPPLE_GT_TOKEN: - case ELLIPSIS_TOKEN: - case DOUBLE_DOT_LT_TOKEN: - case ELVIS_TOKEN: - return true; - - // Treat these also as binary operators. - case RIGHT_ARROW_TOKEN: - case RIGHT_DOUBLE_ARROW_TOKEN: - return true; - default: - return false; - } - } - - private boolean isParameter(ParserRuleContext ctx) { - switch (ctx) { - case REQUIRED_PARAM: - case DEFAULTABLE_PARAM: - case REST_PARAM: - case PARAM_LIST: - return true; - default: - return false; - } - } - - /** - * Get the shortest insert solution at the given parser rule context. If the parser rule is a terminal, - * then return the corresponding terminal token kind as the fix. If the parser rule is a production, - * then navigate the shortest path and get next available terminal token kind as the fix. - * - * @param ctx Parser rule context - * @return Shortest insert solution at the given parser rule - */ - @Override - protected Solution getInsertSolution(ParserRuleContext ctx) { - SyntaxKind kind = getExpectedTokenKind(ctx); - if (kind != SyntaxKind.NONE) { - return new Solution(Action.INSERT, ctx, kind, ctx.toString()); - } - - if (hasAlternativePaths(ctx)) { - ctx = getShortestAlternative(ctx); - return getInsertSolution(ctx); - } - - ctx = getNextRule(ctx, 1); - return getInsertSolution(ctx); - } - - /** - * Get the expected token kind at the given parser rule context. If the parser rule is a terminal, - * then the corresponding terminal token kind is returned. If the parser rule is a production, - * then {@link SyntaxKind#NONE} is returned. - * - * @param ctx Parser rule context - * @return Token kind expected at the given parser rule - */ - @Override - protected SyntaxKind getExpectedTokenKind(ParserRuleContext ctx) { - switch (ctx) { - case EXTERNAL_FUNC_BODY: - return SyntaxKind.EQUAL_TOKEN; - case FUNC_BODY_BLOCK: - return SyntaxKind.OPEN_BRACE_TOKEN; - case FUNC_DEF: - case FUNC_DEF_OR_FUNC_TYPE: - case FUNC_TYPE_DESC: - case FUNC_TYPE_DESC_OR_ANON_FUNC: - return SyntaxKind.FUNCTION_KEYWORD; - case SIMPLE_TYPE_DESCRIPTOR: - return SyntaxKind.ANY_KEYWORD; - case REQUIRED_PARAM: - case VAR_DECL_STMT: - case ASSIGNMENT_OR_VAR_DECL_STMT: - case DEFAULTABLE_PARAM: - case REST_PARAM: - case TYPE_NAME: - case TYPE_REFERENCE_IN_TYPE_INCLUSION: - case TYPE_REFERENCE: - case SIMPLE_TYPE_DESC_IDENTIFIER: - case FIELD_ACCESS_IDENTIFIER: - case FUNC_NAME: - case CLASS_NAME: - case VARIABLE_NAME: - case IMPORT_MODULE_NAME: - case IMPORT_ORG_OR_MODULE_NAME: - case IMPORT_PREFIX: - case VARIABLE_REF: - case BASIC_LITERAL: // return var-ref for any kind of terminal expression - case IDENTIFIER: - case QUALIFIED_IDENTIFIER_START_IDENTIFIER: - case NAMESPACE_PREFIX: - case IMPLICIT_ANON_FUNC_PARAM: - case METHOD_NAME: - case PEER_WORKER_NAME: - case RECEIVE_FIELD_NAME: - case WAIT_FIELD_NAME: - case FIELD_BINDING_PATTERN_NAME: - case XML_ATOMIC_NAME_IDENTIFIER: - case MAPPING_FIELD_NAME: - case WORKER_NAME: - case NAMED_WORKERS: - case ANNOTATION_TAG: - case AFTER_PARAMETER_TYPE: - case MODULE_ENUM_NAME: - case ENUM_MEMBER_NAME: - case TYPED_BINDING_PATTERN_TYPE_RHS: - case ASSIGNMENT_STMT: - case EXPRESSION: - case TERMINAL_EXPRESSION: - case XML_NAME: - case ACCESS_EXPRESSION: - case BINDING_PATTERN_STARTING_IDENTIFIER: - case COMPUTED_FIELD_NAME: - case SIMPLE_BINDING_PATTERN: - case ERROR_FIELD_BINDING_PATTERN: - case ERROR_CAUSE_SIMPLE_BINDING_PATTERN: - case PATH_SEGMENT_IDENT: - case TYPE_DESCRIPTOR: - case NAMED_ARG_BINDING_PATTERN: - return SyntaxKind.IDENTIFIER_TOKEN; - case DECIMAL_INTEGER_LITERAL_TOKEN: - case SIGNED_INT_OR_FLOAT_RHS: - return SyntaxKind.DECIMAL_INTEGER_LITERAL_TOKEN; - case STRING_LITERAL_TOKEN: - return SyntaxKind.STRING_LITERAL_TOKEN; - case OPTIONAL_TYPE_DESCRIPTOR: - return SyntaxKind.OPTIONAL_TYPE_DESC; - case ARRAY_TYPE_DESCRIPTOR: - return SyntaxKind.ARRAY_TYPE_DESC; - case HEX_INTEGER_LITERAL_TOKEN: - return SyntaxKind.HEX_INTEGER_LITERAL_TOKEN; - case OBJECT_FIELD_RHS: - return SyntaxKind.SEMICOLON_TOKEN; - case DECIMAL_FLOATING_POINT_LITERAL_TOKEN: - return SyntaxKind.DECIMAL_FLOATING_POINT_LITERAL_TOKEN; - case HEX_FLOATING_POINT_LITERAL_TOKEN: - return SyntaxKind.HEX_FLOATING_POINT_LITERAL_TOKEN; - case STATEMENT: - case STATEMENT_WITHOUT_ANNOTS: - return SyntaxKind.CLOSE_BRACE_TOKEN; - case ERROR_MATCH_PATTERN: - case NIL_LITERAL: - return SyntaxKind.OPEN_PAREN_TOKEN; - default: - return getExpectedSeperatorTokenKind(ctx); + * + * @param parentCtx Parser context to check + * @return true if the given context is a statement. false otherwise + */ + private boolean isStatement(ParserRuleContext parentCtx) { + return switch (parentCtx) { + case STATEMENT, + STATEMENT_WITHOUT_ANNOTS, + VAR_DECL_STMT, + ASSIGNMENT_STMT, + ASSIGNMENT_OR_VAR_DECL_STMT, + IF_BLOCK, + BLOCK_STMT, + WHILE_BLOCK, + DO_BLOCK, + CALL_STMT, + PANIC_STMT, + CONTINUE_STATEMENT, + BREAK_STATEMENT, + RETURN_STMT, + FAIL_STATEMENT, + LOCAL_TYPE_DEFINITION_STMT, + EXPRESSION_STATEMENT, + LOCK_STMT, + FORK_STMT, + FOREACH_STMT, + TRANSACTION_STMT, + RETRY_STMT, + ROLLBACK_STMT, + AMBIGUOUS_STMT, + MATCH_STMT -> true; + default -> false; + }; + } + + /** + * Check whether the given token refers to a binary operator. + * + * @param token Token to check + * @return true if the given token refers to a binary operator. false otherwise + */ + private boolean isBinaryOperator(STToken token) { + return switch (token.kind) { + case PLUS_TOKEN, + MINUS_TOKEN, + SLASH_TOKEN, + ASTERISK_TOKEN, + GT_TOKEN, + LT_TOKEN, + DOUBLE_EQUAL_TOKEN, + TRIPPLE_EQUAL_TOKEN, + LT_EQUAL_TOKEN, + GT_EQUAL_TOKEN, + NOT_EQUAL_TOKEN, + NOT_DOUBLE_EQUAL_TOKEN, + BITWISE_AND_TOKEN, + BITWISE_XOR_TOKEN, + PIPE_TOKEN, + LOGICAL_AND_TOKEN, + LOGICAL_OR_TOKEN, + DOUBLE_LT_TOKEN, + DOUBLE_GT_TOKEN, + TRIPPLE_GT_TOKEN, + ELLIPSIS_TOKEN, + DOUBLE_DOT_LT_TOKEN, + ELVIS_TOKEN -> true; + + // Treat these also as binary operators. + case RIGHT_ARROW_TOKEN, + RIGHT_DOUBLE_ARROW_TOKEN -> true; + default -> false; + }; + } + + private boolean isParameter(ParserRuleContext ctx) { + return switch (ctx) { + case REQUIRED_PARAM, DEFAULTABLE_PARAM, REST_PARAM, PARAM_LIST -> true; + default -> false; + }; + } + + /** + * Get the shortest insert solution at the given parser rule context. If the parser rule is a terminal, + * then return the corresponding terminal token kind as the fix. If the parser rule is a production, + * then navigate the shortest path and get next available terminal token kind as the fix. + * + * @param ctx Parser rule context + * @return Shortest insert solution at the given parser rule + */ + @Override + protected Solution getInsertSolution(ParserRuleContext ctx) { + SyntaxKind kind = getExpectedTokenKind(ctx); + if (kind != SyntaxKind.NONE) { + return new Solution(Action.INSERT, ctx, kind, ctx.toString()); + } + + if (hasAlternativePaths(ctx)) { + ctx = getShortestAlternative(ctx); + return getInsertSolution(ctx); } + + ctx = getNextRule(ctx, 1); + return getInsertSolution(ctx); + } + + /** + * Get the expected token kind at the given parser rule context. If the parser rule is a terminal, + * then the corresponding terminal token kind is returned. If the parser rule is a production, + * then {@link SyntaxKind#NONE} is returned. + * + * @param ctx Parser rule context + * @return Token kind expected at the given parser rule + */ + @Override + protected SyntaxKind getExpectedTokenKind(ParserRuleContext ctx) { + return switch (ctx) { + case EXTERNAL_FUNC_BODY -> SyntaxKind.EQUAL_TOKEN; + case FUNC_BODY_BLOCK -> SyntaxKind.OPEN_BRACE_TOKEN; + case FUNC_DEF, + FUNC_DEF_OR_FUNC_TYPE, + FUNC_TYPE_DESC, + FUNC_TYPE_DESC_OR_ANON_FUNC -> SyntaxKind.FUNCTION_KEYWORD; + case SIMPLE_TYPE_DESCRIPTOR -> SyntaxKind.ANY_KEYWORD; + case REQUIRED_PARAM, + VAR_DECL_STMT, + ASSIGNMENT_OR_VAR_DECL_STMT, + DEFAULTABLE_PARAM, + REST_PARAM, + TYPE_NAME, + TYPE_REFERENCE_IN_TYPE_INCLUSION, + TYPE_REFERENCE, + SIMPLE_TYPE_DESC_IDENTIFIER, + FIELD_ACCESS_IDENTIFIER, + FUNC_NAME, + CLASS_NAME, + VARIABLE_NAME, + IMPORT_MODULE_NAME, + IMPORT_ORG_OR_MODULE_NAME, + IMPORT_PREFIX, + VARIABLE_REF, + BASIC_LITERAL, // return var-ref for any kind of terminal expression + IDENTIFIER, + QUALIFIED_IDENTIFIER_START_IDENTIFIER, + NAMESPACE_PREFIX, + IMPLICIT_ANON_FUNC_PARAM, + METHOD_NAME, + PEER_WORKER_NAME, + RECEIVE_FIELD_NAME, + WAIT_FIELD_NAME, + FIELD_BINDING_PATTERN_NAME, + XML_ATOMIC_NAME_IDENTIFIER, + MAPPING_FIELD_NAME, + WORKER_NAME, + NAMED_WORKERS, + ANNOTATION_TAG, + AFTER_PARAMETER_TYPE, + MODULE_ENUM_NAME, + ENUM_MEMBER_NAME, + TYPED_BINDING_PATTERN_TYPE_RHS, + ASSIGNMENT_STMT, + EXPRESSION, + TERMINAL_EXPRESSION, + XML_NAME, + ACCESS_EXPRESSION, + BINDING_PATTERN_STARTING_IDENTIFIER, + COMPUTED_FIELD_NAME, + SIMPLE_BINDING_PATTERN, + ERROR_FIELD_BINDING_PATTERN, + ERROR_CAUSE_SIMPLE_BINDING_PATTERN, + PATH_SEGMENT_IDENT, + TYPE_DESCRIPTOR, + NAMED_ARG_BINDING_PATTERN -> SyntaxKind.IDENTIFIER_TOKEN; + case DECIMAL_INTEGER_LITERAL_TOKEN, + SIGNED_INT_OR_FLOAT_RHS -> SyntaxKind.DECIMAL_INTEGER_LITERAL_TOKEN; + case STRING_LITERAL_TOKEN -> SyntaxKind.STRING_LITERAL_TOKEN; + case OPTIONAL_TYPE_DESCRIPTOR -> SyntaxKind.OPTIONAL_TYPE_DESC; + case ARRAY_TYPE_DESCRIPTOR -> SyntaxKind.ARRAY_TYPE_DESC; + case HEX_INTEGER_LITERAL_TOKEN -> SyntaxKind.HEX_INTEGER_LITERAL_TOKEN; + case OBJECT_FIELD_RHS -> SyntaxKind.SEMICOLON_TOKEN; + case DECIMAL_FLOATING_POINT_LITERAL_TOKEN -> SyntaxKind.DECIMAL_FLOATING_POINT_LITERAL_TOKEN; + case HEX_FLOATING_POINT_LITERAL_TOKEN -> SyntaxKind.HEX_FLOATING_POINT_LITERAL_TOKEN; + case STATEMENT, + STATEMENT_WITHOUT_ANNOTS -> SyntaxKind.CLOSE_BRACE_TOKEN; + case ERROR_MATCH_PATTERN, + NIL_LITERAL -> SyntaxKind.OPEN_PAREN_TOKEN; + default -> getExpectedSeperatorTokenKind(ctx); + }; } protected SyntaxKind getExpectedSeperatorTokenKind(ParserRuleContext ctx) { - switch (ctx) { - case BITWISE_AND_OPERATOR: - return SyntaxKind.BITWISE_AND_TOKEN; - case EQUAL_OR_RIGHT_ARROW: - return SyntaxKind.EQUAL_TOKEN; - case EOF: - return SyntaxKind.EOF_TOKEN; - case ASSIGN_OP: - return SyntaxKind.EQUAL_TOKEN; - case BINARY_OPERATOR: - return SyntaxKind.PLUS_TOKEN; - case CLOSE_BRACE: - return SyntaxKind.CLOSE_BRACE_TOKEN; - case CLOSE_PARENTHESIS: - case ARG_LIST_CLOSE_PAREN: - return SyntaxKind.CLOSE_PAREN_TOKEN; - case COMMA: - case ERROR_MESSAGE_BINDING_PATTERN_END_COMMA: - case ERROR_MESSAGE_MATCH_PATTERN_END_COMMA: - return SyntaxKind.COMMA_TOKEN; - case OPEN_BRACE: - return SyntaxKind.OPEN_BRACE_TOKEN; - case OPEN_PARENTHESIS: - case ARG_LIST_OPEN_PAREN: - case PARENTHESISED_TYPE_DESC_START: - return SyntaxKind.OPEN_PAREN_TOKEN; - case SEMICOLON: - return SyntaxKind.SEMICOLON_TOKEN; - case ASTERISK: - return SyntaxKind.ASTERISK_TOKEN; - case CLOSED_RECORD_BODY_END: - return SyntaxKind.CLOSE_BRACE_PIPE_TOKEN; - case CLOSED_RECORD_BODY_START: - return SyntaxKind.OPEN_BRACE_PIPE_TOKEN; - case ELLIPSIS: - return SyntaxKind.ELLIPSIS_TOKEN; - case QUESTION_MARK: - return SyntaxKind.QUESTION_MARK_TOKEN; - case CLOSE_BRACKET: - return SyntaxKind.CLOSE_BRACKET_TOKEN; - case DOT: - case METHOD_CALL_DOT: - return SyntaxKind.DOT_TOKEN; - case OPEN_BRACKET: - case TUPLE_TYPE_DESC_START: - return SyntaxKind.OPEN_BRACKET_TOKEN; - case SLASH: - case ABSOLUTE_PATH_SINGLE_SLASH: - case RESOURCE_METHOD_CALL_SLASH_TOKEN: - return SyntaxKind.SLASH_TOKEN; - case COLON: - case TYPE_REF_COLON: - case VAR_REF_COLON: - return SyntaxKind.COLON_TOKEN; - case UNARY_OPERATOR: - case COMPOUND_BINARY_OPERATOR: - case UNARY_EXPRESSION: - case EXPRESSION_RHS: - return SyntaxKind.PLUS_TOKEN; - case AT: - return SyntaxKind.AT_TOKEN; - case RIGHT_ARROW: - return SyntaxKind.RIGHT_ARROW_TOKEN; - case GT: - case INFERRED_TYPEDESC_DEFAULT_END_GT: - return SyntaxKind.GT_TOKEN; - case LT: - case STREAM_TYPE_PARAM_START_TOKEN: - case INFERRED_TYPEDESC_DEFAULT_START_LT: - return SyntaxKind.LT_TOKEN; - case SYNC_SEND_TOKEN: - return SyntaxKind.SYNC_SEND_TOKEN; - case ANNOT_CHAINING_TOKEN: - return SyntaxKind.ANNOT_CHAINING_TOKEN; - case OPTIONAL_CHAINING_TOKEN: - return SyntaxKind.OPTIONAL_CHAINING_TOKEN; - case DOT_LT_TOKEN: - return SyntaxKind.DOT_LT_TOKEN; - case SLASH_LT_TOKEN: - return SyntaxKind.SLASH_LT_TOKEN; - case DOUBLE_SLASH_DOUBLE_ASTERISK_LT_TOKEN: - return SyntaxKind.DOUBLE_SLASH_DOUBLE_ASTERISK_LT_TOKEN; - case SLASH_ASTERISK_TOKEN: - return SyntaxKind.SLASH_ASTERISK_TOKEN; - case PLUS_TOKEN: - return SyntaxKind.PLUS_TOKEN; - case MINUS_TOKEN: - return SyntaxKind.MINUS_TOKEN; - case LEFT_ARROW_TOKEN: - return SyntaxKind.LEFT_ARROW_TOKEN; - case TEMPLATE_END: - case TEMPLATE_START: - return SyntaxKind.BACKTICK_TOKEN; - case LT_TOKEN: - return SyntaxKind.LT_TOKEN; - case GT_TOKEN: - return SyntaxKind.GT_TOKEN; - case INTERPOLATION_START_TOKEN: - return SyntaxKind.INTERPOLATION_START_TOKEN; - case EXPR_FUNC_BODY_START: - case RIGHT_DOUBLE_ARROW: - return SyntaxKind.RIGHT_DOUBLE_ARROW_TOKEN; - default: - return getExpectedKeywordKind(ctx); - } + return switch (ctx) { + case BITWISE_AND_OPERATOR -> SyntaxKind.BITWISE_AND_TOKEN; + case EQUAL_OR_RIGHT_ARROW, + ASSIGN_OP -> SyntaxKind.EQUAL_TOKEN; + case EOF -> SyntaxKind.EOF_TOKEN; + case BINARY_OPERATOR -> SyntaxKind.PLUS_TOKEN; + case CLOSE_BRACE -> SyntaxKind.CLOSE_BRACE_TOKEN; + case CLOSE_PARENTHESIS, + ARG_LIST_CLOSE_PAREN -> SyntaxKind.CLOSE_PAREN_TOKEN; + case COMMA, + ERROR_MESSAGE_BINDING_PATTERN_END_COMMA, + ERROR_MESSAGE_MATCH_PATTERN_END_COMMA -> SyntaxKind.COMMA_TOKEN; + case OPEN_BRACE -> SyntaxKind.OPEN_BRACE_TOKEN; + case OPEN_PARENTHESIS, + ARG_LIST_OPEN_PAREN, + PARENTHESISED_TYPE_DESC_START -> SyntaxKind.OPEN_PAREN_TOKEN; + case SEMICOLON -> SyntaxKind.SEMICOLON_TOKEN; + case ASTERISK -> SyntaxKind.ASTERISK_TOKEN; + case CLOSED_RECORD_BODY_END -> SyntaxKind.CLOSE_BRACE_PIPE_TOKEN; + case CLOSED_RECORD_BODY_START -> SyntaxKind.OPEN_BRACE_PIPE_TOKEN; + case ELLIPSIS -> SyntaxKind.ELLIPSIS_TOKEN; + case QUESTION_MARK -> SyntaxKind.QUESTION_MARK_TOKEN; + case CLOSE_BRACKET -> SyntaxKind.CLOSE_BRACKET_TOKEN; + case DOT, + METHOD_CALL_DOT -> SyntaxKind.DOT_TOKEN; + case OPEN_BRACKET, + TUPLE_TYPE_DESC_START -> SyntaxKind.OPEN_BRACKET_TOKEN; + case SLASH, + ABSOLUTE_PATH_SINGLE_SLASH, + RESOURCE_METHOD_CALL_SLASH_TOKEN -> SyntaxKind.SLASH_TOKEN; + case COLON, + TYPE_REF_COLON, + VAR_REF_COLON -> SyntaxKind.COLON_TOKEN; + case UNARY_OPERATOR, + COMPOUND_BINARY_OPERATOR, + UNARY_EXPRESSION, + EXPRESSION_RHS -> SyntaxKind.PLUS_TOKEN; + case AT -> SyntaxKind.AT_TOKEN; + case RIGHT_ARROW -> SyntaxKind.RIGHT_ARROW_TOKEN; + case GT, + INFERRED_TYPEDESC_DEFAULT_END_GT -> SyntaxKind.GT_TOKEN; + case LT, + STREAM_TYPE_PARAM_START_TOKEN, + INFERRED_TYPEDESC_DEFAULT_START_LT -> SyntaxKind.LT_TOKEN; + case SYNC_SEND_TOKEN -> SyntaxKind.SYNC_SEND_TOKEN; + case ANNOT_CHAINING_TOKEN -> SyntaxKind.ANNOT_CHAINING_TOKEN; + case OPTIONAL_CHAINING_TOKEN -> SyntaxKind.OPTIONAL_CHAINING_TOKEN; + case DOT_LT_TOKEN -> SyntaxKind.DOT_LT_TOKEN; + case SLASH_LT_TOKEN -> SyntaxKind.SLASH_LT_TOKEN; + case DOUBLE_SLASH_DOUBLE_ASTERISK_LT_TOKEN -> SyntaxKind.DOUBLE_SLASH_DOUBLE_ASTERISK_LT_TOKEN; + case SLASH_ASTERISK_TOKEN -> SyntaxKind.SLASH_ASTERISK_TOKEN; + case PLUS_TOKEN -> SyntaxKind.PLUS_TOKEN; + case MINUS_TOKEN -> SyntaxKind.MINUS_TOKEN; + case LEFT_ARROW_TOKEN -> SyntaxKind.LEFT_ARROW_TOKEN; + case TEMPLATE_END, + TEMPLATE_START -> SyntaxKind.BACKTICK_TOKEN; + case LT_TOKEN -> SyntaxKind.LT_TOKEN; + case GT_TOKEN -> SyntaxKind.GT_TOKEN; + case INTERPOLATION_START_TOKEN -> SyntaxKind.INTERPOLATION_START_TOKEN; + case EXPR_FUNC_BODY_START, + RIGHT_DOUBLE_ARROW -> SyntaxKind.RIGHT_DOUBLE_ARROW_TOKEN; + default -> getExpectedKeywordKind(ctx); + }; } protected SyntaxKind getExpectedKeywordKind(ParserRuleContext ctx) { - switch (ctx) { - case EXTERNAL_KEYWORD: - return SyntaxKind.EXTERNAL_KEYWORD; - case FUNCTION_KEYWORD: - return SyntaxKind.FUNCTION_KEYWORD; - case RETURNS_KEYWORD: - return SyntaxKind.RETURNS_KEYWORD; - case PUBLIC_KEYWORD: - return SyntaxKind.PUBLIC_KEYWORD; - case RECORD_FIELD: - case RECORD_KEYWORD: - return SyntaxKind.RECORD_KEYWORD; - case TYPE_KEYWORD: - return SyntaxKind.TYPE_KEYWORD; - case OBJECT_KEYWORD: - case OBJECT_IDENT: - case OBJECT_TYPE_DESCRIPTOR: - return SyntaxKind.OBJECT_KEYWORD; - case PRIVATE_KEYWORD: - return SyntaxKind.PRIVATE_KEYWORD; - case REMOTE_IDENT: - return SyntaxKind.REMOTE_KEYWORD; - case ABSTRACT_KEYWORD: - return SyntaxKind.ABSTRACT_KEYWORD; - case CLIENT_KEYWORD: - return SyntaxKind.CLIENT_KEYWORD; - case IF_KEYWORD: - return SyntaxKind.IF_KEYWORD; - case ELSE_KEYWORD: - return SyntaxKind.ELSE_KEYWORD; - case WHILE_KEYWORD: - return SyntaxKind.WHILE_KEYWORD; - case CHECKING_KEYWORD: - return SyntaxKind.CHECK_KEYWORD; - case FAIL_KEYWORD: - return SyntaxKind.FAIL_KEYWORD; - case AS_KEYWORD: - return SyntaxKind.AS_KEYWORD; - case BOOLEAN_LITERAL: - return SyntaxKind.TRUE_KEYWORD; - case IMPORT_KEYWORD: - return SyntaxKind.IMPORT_KEYWORD; - case ON_KEYWORD: - return SyntaxKind.ON_KEYWORD; - case PANIC_KEYWORD: - return SyntaxKind.PANIC_KEYWORD; - case RETURN_KEYWORD: - return SyntaxKind.RETURN_KEYWORD; - case SERVICE_KEYWORD: - case SERVICE_IDENT: - return SyntaxKind.SERVICE_KEYWORD; - case BREAK_KEYWORD: - return SyntaxKind.BREAK_KEYWORD; - case LISTENER_KEYWORD: - return SyntaxKind.LISTENER_KEYWORD; - case CONTINUE_KEYWORD: - return SyntaxKind.CONTINUE_KEYWORD; - case CONST_KEYWORD: - return SyntaxKind.CONST_KEYWORD; - case FINAL_KEYWORD: - return SyntaxKind.FINAL_KEYWORD; - case IS_KEYWORD: - return SyntaxKind.IS_KEYWORD; - case TYPEOF_KEYWORD: - return SyntaxKind.TYPEOF_KEYWORD; - case MAP_KEYWORD: - case MAP_TYPE_DESCRIPTOR: - return SyntaxKind.MAP_KEYWORD; - case PARAMETERIZED_TYPE: - return SyntaxKind.ERROR_KEYWORD; - case NULL_KEYWORD: - return SyntaxKind.NULL_KEYWORD; - case LOCK_KEYWORD: - return SyntaxKind.LOCK_KEYWORD; - case ANNOTATION_KEYWORD: - return SyntaxKind.ANNOTATION_KEYWORD; - case SINGLE_KEYWORD_ATTACH_POINT_IDENT: - return SyntaxKind.TYPE_KEYWORD; - case IDENT_AFTER_OBJECT_IDENT: - return SyntaxKind.FUNCTION_KEYWORD; - case FIELD_IDENT: - return SyntaxKind.FIELD_KEYWORD; - case FUNCTION_IDENT: - return SyntaxKind.FUNCTION_KEYWORD; - case RECORD_IDENT: - return SyntaxKind.RECORD_KEYWORD; - case XMLNS_KEYWORD: - case XML_NAMESPACE_DECLARATION: - return SyntaxKind.XMLNS_KEYWORD; - case SOURCE_KEYWORD: - return SyntaxKind.SOURCE_KEYWORD; - case START_KEYWORD: - return SyntaxKind.START_KEYWORD; - case FLUSH_KEYWORD: - return SyntaxKind.FLUSH_KEYWORD; - case OPTIONAL_PEER_WORKER: - case DEFAULT_WORKER_NAME_IN_ASYNC_SEND: - return SyntaxKind.FUNCTION_KEYWORD; - case WAIT_KEYWORD: - return SyntaxKind.WAIT_KEYWORD; - case TRANSACTION_KEYWORD: - return SyntaxKind.TRANSACTION_KEYWORD; - case TRANSACTIONAL_KEYWORD: - return SyntaxKind.TRANSACTIONAL_KEYWORD; - case COMMIT_KEYWORD: - return SyntaxKind.COMMIT_KEYWORD; - case RETRY_KEYWORD: - return SyntaxKind.RETRY_KEYWORD; - case ROLLBACK_KEYWORD: - return SyntaxKind.ROLLBACK_KEYWORD; - case ENUM_KEYWORD: - return SyntaxKind.ENUM_KEYWORD; - case MATCH_KEYWORD: - return SyntaxKind.MATCH_KEYWORD; - case NEW_KEYWORD: - return SyntaxKind.NEW_KEYWORD; - case FORK_KEYWORD: - return SyntaxKind.FORK_KEYWORD; - case NAMED_WORKER_DECL: - case WORKER_KEYWORD: - return SyntaxKind.WORKER_KEYWORD; - case TRAP_KEYWORD: - return SyntaxKind.TRAP_KEYWORD; - case FOREACH_KEYWORD: - return SyntaxKind.FOREACH_KEYWORD; - case IN_KEYWORD: - return SyntaxKind.IN_KEYWORD; - case PIPE: - case UNION_OR_INTERSECTION_TOKEN: - return SyntaxKind.PIPE_TOKEN; - case TABLE_KEYWORD: - return SyntaxKind.TABLE_KEYWORD; - case KEY_KEYWORD: - return SyntaxKind.KEY_KEYWORD; - case ERROR_KEYWORD: - case ERROR_BINDING_PATTERN: - return SyntaxKind.ERROR_KEYWORD; - case STREAM_KEYWORD: - return SyntaxKind.STREAM_KEYWORD; - case LET_KEYWORD: - return SyntaxKind.LET_KEYWORD; - case XML_KEYWORD: - return SyntaxKind.XML_KEYWORD; - case RE_KEYWORD: - return SyntaxKind.RE_KEYWORD; - case STRING_KEYWORD: - return SyntaxKind.STRING_KEYWORD; - case BASE16_KEYWORD: - return SyntaxKind.BASE16_KEYWORD; - case BASE64_KEYWORD: - return SyntaxKind.BASE64_KEYWORD; - case SELECT_KEYWORD: - return SyntaxKind.SELECT_KEYWORD; - case WHERE_KEYWORD: - return SyntaxKind.WHERE_KEYWORD; - case FROM_KEYWORD: - return SyntaxKind.FROM_KEYWORD; - case ORDER_KEYWORD: - return SyntaxKind.ORDER_KEYWORD; - case GROUP_KEYWORD: - return SyntaxKind.GROUP_KEYWORD; - case BY_KEYWORD: - return SyntaxKind.BY_KEYWORD; - case ORDER_DIRECTION: - return SyntaxKind.ASCENDING_KEYWORD; - case DO_KEYWORD: - return SyntaxKind.DO_KEYWORD; - case DISTINCT_KEYWORD: - return SyntaxKind.DISTINCT_KEYWORD; - case VAR_KEYWORD: - return SyntaxKind.VAR_KEYWORD; - case CONFLICT_KEYWORD: - return SyntaxKind.CONFLICT_KEYWORD; - case LIMIT_KEYWORD: - return SyntaxKind.LIMIT_KEYWORD; - case EQUALS_KEYWORD: - return SyntaxKind.EQUALS_KEYWORD; - case JOIN_KEYWORD: - return SyntaxKind.JOIN_KEYWORD; - case OUTER_KEYWORD: - return SyntaxKind.OUTER_KEYWORD; - case CLASS_KEYWORD: - return SyntaxKind.CLASS_KEYWORD; - case COLLECT_KEYWORD: - return SyntaxKind.COLLECT_KEYWORD; - default: - return getExpectedQualifierKind(ctx); - } + return switch (ctx) { + case EXTERNAL_KEYWORD -> SyntaxKind.EXTERNAL_KEYWORD; + case FUNCTION_KEYWORD, + IDENT_AFTER_OBJECT_IDENT, + FUNCTION_IDENT, + OPTIONAL_PEER_WORKER, + DEFAULT_WORKER_NAME_IN_ASYNC_SEND -> SyntaxKind.FUNCTION_KEYWORD; + case RETURNS_KEYWORD -> SyntaxKind.RETURNS_KEYWORD; + case PUBLIC_KEYWORD -> SyntaxKind.PUBLIC_KEYWORD; + case RECORD_FIELD, + RECORD_KEYWORD, + RECORD_IDENT -> SyntaxKind.RECORD_KEYWORD; + case TYPE_KEYWORD, + SINGLE_KEYWORD_ATTACH_POINT_IDENT -> SyntaxKind.TYPE_KEYWORD; + case OBJECT_KEYWORD, + OBJECT_IDENT, + OBJECT_TYPE_DESCRIPTOR -> SyntaxKind.OBJECT_KEYWORD; + case PRIVATE_KEYWORD -> SyntaxKind.PRIVATE_KEYWORD; + case REMOTE_IDENT -> SyntaxKind.REMOTE_KEYWORD; + case ABSTRACT_KEYWORD -> SyntaxKind.ABSTRACT_KEYWORD; + case CLIENT_KEYWORD -> SyntaxKind.CLIENT_KEYWORD; + case IF_KEYWORD -> SyntaxKind.IF_KEYWORD; + case ELSE_KEYWORD -> SyntaxKind.ELSE_KEYWORD; + case WHILE_KEYWORD -> SyntaxKind.WHILE_KEYWORD; + case CHECKING_KEYWORD -> SyntaxKind.CHECK_KEYWORD; + case FAIL_KEYWORD -> SyntaxKind.FAIL_KEYWORD; + case AS_KEYWORD -> SyntaxKind.AS_KEYWORD; + case BOOLEAN_LITERAL -> SyntaxKind.TRUE_KEYWORD; + case IMPORT_KEYWORD -> SyntaxKind.IMPORT_KEYWORD; + case ON_KEYWORD -> SyntaxKind.ON_KEYWORD; + case PANIC_KEYWORD -> SyntaxKind.PANIC_KEYWORD; + case RETURN_KEYWORD -> SyntaxKind.RETURN_KEYWORD; + case SERVICE_KEYWORD, + SERVICE_IDENT -> SyntaxKind.SERVICE_KEYWORD; + case BREAK_KEYWORD -> SyntaxKind.BREAK_KEYWORD; + case LISTENER_KEYWORD -> SyntaxKind.LISTENER_KEYWORD; + case CONTINUE_KEYWORD -> SyntaxKind.CONTINUE_KEYWORD; + case CONST_KEYWORD -> SyntaxKind.CONST_KEYWORD; + case FINAL_KEYWORD -> SyntaxKind.FINAL_KEYWORD; + case IS_KEYWORD -> SyntaxKind.IS_KEYWORD; + case TYPEOF_KEYWORD -> SyntaxKind.TYPEOF_KEYWORD; + case MAP_KEYWORD, + MAP_TYPE_DESCRIPTOR -> SyntaxKind.MAP_KEYWORD; + case PARAMETERIZED_TYPE, + ERROR_KEYWORD, + ERROR_BINDING_PATTERN -> SyntaxKind.ERROR_KEYWORD; + case NULL_KEYWORD -> SyntaxKind.NULL_KEYWORD; + case LOCK_KEYWORD -> SyntaxKind.LOCK_KEYWORD; + case ANNOTATION_KEYWORD -> SyntaxKind.ANNOTATION_KEYWORD; + case FIELD_IDENT -> SyntaxKind.FIELD_KEYWORD; + case XMLNS_KEYWORD, + XML_NAMESPACE_DECLARATION -> SyntaxKind.XMLNS_KEYWORD; + case SOURCE_KEYWORD -> SyntaxKind.SOURCE_KEYWORD; + case START_KEYWORD -> SyntaxKind.START_KEYWORD; + case FLUSH_KEYWORD -> SyntaxKind.FLUSH_KEYWORD; + case WAIT_KEYWORD -> SyntaxKind.WAIT_KEYWORD; + case TRANSACTION_KEYWORD -> SyntaxKind.TRANSACTION_KEYWORD; + case TRANSACTIONAL_KEYWORD -> SyntaxKind.TRANSACTIONAL_KEYWORD; + case COMMIT_KEYWORD -> SyntaxKind.COMMIT_KEYWORD; + case RETRY_KEYWORD -> SyntaxKind.RETRY_KEYWORD; + case ROLLBACK_KEYWORD -> SyntaxKind.ROLLBACK_KEYWORD; + case ENUM_KEYWORD -> SyntaxKind.ENUM_KEYWORD; + case MATCH_KEYWORD -> SyntaxKind.MATCH_KEYWORD; + case NEW_KEYWORD -> SyntaxKind.NEW_KEYWORD; + case FORK_KEYWORD -> SyntaxKind.FORK_KEYWORD; + case NAMED_WORKER_DECL, + WORKER_KEYWORD -> SyntaxKind.WORKER_KEYWORD; + case TRAP_KEYWORD -> SyntaxKind.TRAP_KEYWORD; + case FOREACH_KEYWORD -> SyntaxKind.FOREACH_KEYWORD; + case IN_KEYWORD -> SyntaxKind.IN_KEYWORD; + case PIPE, + UNION_OR_INTERSECTION_TOKEN -> SyntaxKind.PIPE_TOKEN; + case TABLE_KEYWORD -> SyntaxKind.TABLE_KEYWORD; + case KEY_KEYWORD -> SyntaxKind.KEY_KEYWORD; + case STREAM_KEYWORD -> SyntaxKind.STREAM_KEYWORD; + case LET_KEYWORD -> SyntaxKind.LET_KEYWORD; + case XML_KEYWORD -> SyntaxKind.XML_KEYWORD; + case RE_KEYWORD -> SyntaxKind.RE_KEYWORD; + case STRING_KEYWORD -> SyntaxKind.STRING_KEYWORD; + case BASE16_KEYWORD -> SyntaxKind.BASE16_KEYWORD; + case BASE64_KEYWORD -> SyntaxKind.BASE64_KEYWORD; + case SELECT_KEYWORD -> SyntaxKind.SELECT_KEYWORD; + case WHERE_KEYWORD -> SyntaxKind.WHERE_KEYWORD; + case FROM_KEYWORD -> SyntaxKind.FROM_KEYWORD; + case ORDER_KEYWORD -> SyntaxKind.ORDER_KEYWORD; + case GROUP_KEYWORD -> SyntaxKind.GROUP_KEYWORD; + case BY_KEYWORD -> SyntaxKind.BY_KEYWORD; + case ORDER_DIRECTION -> SyntaxKind.ASCENDING_KEYWORD; + case DO_KEYWORD -> SyntaxKind.DO_KEYWORD; + case DISTINCT_KEYWORD -> SyntaxKind.DISTINCT_KEYWORD; + case VAR_KEYWORD -> SyntaxKind.VAR_KEYWORD; + case CONFLICT_KEYWORD -> SyntaxKind.CONFLICT_KEYWORD; + case LIMIT_KEYWORD -> SyntaxKind.LIMIT_KEYWORD; + case EQUALS_KEYWORD -> SyntaxKind.EQUALS_KEYWORD; + case JOIN_KEYWORD -> SyntaxKind.JOIN_KEYWORD; + case OUTER_KEYWORD -> SyntaxKind.OUTER_KEYWORD; + case CLASS_KEYWORD -> SyntaxKind.CLASS_KEYWORD; + case COLLECT_KEYWORD -> SyntaxKind.COLLECT_KEYWORD; + default -> getExpectedQualifierKind(ctx); + }; } protected SyntaxKind getExpectedQualifierKind(ParserRuleContext ctx) { // Ideally, optimal solution should not be an INSERT action on qualifiers. // Therefore, qualifier ctxs are pointed to the end of qualifier parsing token to exit early. - switch (ctx) { - case FIRST_OBJECT_CONS_QUALIFIER: - case SECOND_OBJECT_CONS_QUALIFIER: - case FIRST_OBJECT_TYPE_QUALIFIER: - case SECOND_OBJECT_TYPE_QUALIFIER: - return SyntaxKind.OBJECT_KEYWORD; - case FIRST_CLASS_TYPE_QUALIFIER: - case SECOND_CLASS_TYPE_QUALIFIER: - case THIRD_CLASS_TYPE_QUALIFIER: - case FOURTH_CLASS_TYPE_QUALIFIER: - return SyntaxKind.CLASS_KEYWORD; - case FUNC_DEF_FIRST_QUALIFIER: - case FUNC_DEF_SECOND_QUALIFIER: - case FUNC_TYPE_FIRST_QUALIFIER: - case FUNC_TYPE_SECOND_QUALIFIER: - case OBJECT_METHOD_FIRST_QUALIFIER: - case OBJECT_METHOD_SECOND_QUALIFIER: - case OBJECT_METHOD_THIRD_QUALIFIER: - case OBJECT_METHOD_FOURTH_QUALIFIER: - return SyntaxKind.FUNCTION_KEYWORD; - case MODULE_VAR_FIRST_QUAL: - case MODULE_VAR_SECOND_QUAL: - case MODULE_VAR_THIRD_QUAL: - case OBJECT_MEMBER_VISIBILITY_QUAL: - return SyntaxKind.IDENTIFIER_TOKEN; - case SERVICE_DECL_QUALIFIER: - return SyntaxKind.SERVICE_KEYWORD; - default: - return SyntaxKind.NONE; - } + return switch (ctx) { + case FIRST_OBJECT_CONS_QUALIFIER, + SECOND_OBJECT_CONS_QUALIFIER, + FIRST_OBJECT_TYPE_QUALIFIER, + SECOND_OBJECT_TYPE_QUALIFIER -> SyntaxKind.OBJECT_KEYWORD; + case FIRST_CLASS_TYPE_QUALIFIER, + SECOND_CLASS_TYPE_QUALIFIER, + THIRD_CLASS_TYPE_QUALIFIER, + FOURTH_CLASS_TYPE_QUALIFIER -> SyntaxKind.CLASS_KEYWORD; + case FUNC_DEF_FIRST_QUALIFIER, + FUNC_DEF_SECOND_QUALIFIER, + FUNC_TYPE_FIRST_QUALIFIER, + FUNC_TYPE_SECOND_QUALIFIER, + OBJECT_METHOD_FIRST_QUALIFIER, + OBJECT_METHOD_SECOND_QUALIFIER, + OBJECT_METHOD_THIRD_QUALIFIER, + OBJECT_METHOD_FOURTH_QUALIFIER -> SyntaxKind.FUNCTION_KEYWORD; + case MODULE_VAR_FIRST_QUAL, + MODULE_VAR_SECOND_QUAL, + MODULE_VAR_THIRD_QUAL, + OBJECT_MEMBER_VISIBILITY_QUAL -> SyntaxKind.IDENTIFIER_TOKEN; + case SERVICE_DECL_QUALIFIER -> SyntaxKind.SERVICE_KEYWORD; + default -> SyntaxKind.NONE; + }; } /** @@ -6200,19 +5711,17 @@ protected SyntaxKind getExpectedQualifierKind(ParserRuleContext ctx) { * @return true if the given token kind belongs to a basic literal.false otherwise */ private boolean isBasicLiteral(SyntaxKind kind) { - switch (kind) { - case DECIMAL_INTEGER_LITERAL_TOKEN: - case HEX_INTEGER_LITERAL_TOKEN: - case STRING_LITERAL_TOKEN: - case TRUE_KEYWORD: - case FALSE_KEYWORD: - case NULL_KEYWORD: - case DECIMAL_FLOATING_POINT_LITERAL_TOKEN: - case HEX_FLOATING_POINT_LITERAL_TOKEN: - return true; - default: - return false; - } + return switch (kind) { + case DECIMAL_INTEGER_LITERAL_TOKEN, + HEX_INTEGER_LITERAL_TOKEN, + STRING_LITERAL_TOKEN, + TRUE_KEYWORD, + FALSE_KEYWORD, + NULL_KEYWORD, + DECIMAL_FLOATING_POINT_LITERAL_TOKEN, + HEX_FLOATING_POINT_LITERAL_TOKEN -> true; + default -> false; + }; } /** @@ -6222,34 +5731,30 @@ private boolean isBasicLiteral(SyntaxKind kind) { * @return true if the given token refers to a unary operator. false otherwise */ private boolean isUnaryOperator(STToken token) { - switch (token.kind) { - case PLUS_TOKEN: - case MINUS_TOKEN: - case NEGATION_TOKEN: - case EXCLAMATION_MARK_TOKEN: - return true; - default: - return false; - } + return switch (token.kind) { + case PLUS_TOKEN, + MINUS_TOKEN, + NEGATION_TOKEN, + EXCLAMATION_MARK_TOKEN -> true; + default -> false; + }; } private boolean isSingleKeywordAttachPointIdent(SyntaxKind tokenKind) { - switch (tokenKind) { - case ANNOTATION_KEYWORD: - case EXTERNAL_KEYWORD: - case VAR_KEYWORD: - case CONST_KEYWORD: - case LISTENER_KEYWORD: - case WORKER_KEYWORD: - case TYPE_KEYWORD: - case FUNCTION_KEYWORD: - case PARAMETER_KEYWORD: - case RETURN_KEYWORD: - case FIELD_KEYWORD: - case CLASS_KEYWORD: - return true; - default: - return false; - } + return switch (tokenKind) { + case ANNOTATION_KEYWORD, + EXTERNAL_KEYWORD, + VAR_KEYWORD, + CONST_KEYWORD, + LISTENER_KEYWORD, + WORKER_KEYWORD, + TYPE_KEYWORD, + FUNCTION_KEYWORD, + PARAMETER_KEYWORD, + RETURN_KEYWORD, + FIELD_KEYWORD, + CLASS_KEYWORD -> true; + default -> false; + }; } } diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/DocumentationLexer.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/DocumentationLexer.java index 3fa92bf2f267..739330972b23 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/DocumentationLexer.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/DocumentationLexer.java @@ -63,46 +63,34 @@ public DocumentationLexer(CharReader charReader, */ @Override public STToken nextToken() { - STToken token; - switch (this.mode) { - case DOC_LINE_START_HASH: + STToken token = switch (this.mode) { + case DOC_LINE_START_HASH -> { processLeadingTrivia(); - token = readDocLineStartHashToken(); - break; - case DOC_LINE_DIFFERENTIATOR: + yield readDocLineStartHashToken(); + } + case DOC_LINE_DIFFERENTIATOR -> { processLeadingTrivia(); - token = readDocLineDifferentiatorToken(); - break; - case DOC_INTERNAL: - token = readDocInternalToken(); - break; - case DOC_PARAMETER: + yield readDocLineDifferentiatorToken(); + } + case DOC_INTERNAL -> readDocInternalToken(); + case DOC_PARAMETER -> { processLeadingTrivia(); - token = readDocParameterToken(); - break; - case DOC_REFERENCE_TYPE: + yield readDocParameterToken(); + } + case DOC_REFERENCE_TYPE -> { processLeadingTrivia(); - token = readDocReferenceTypeToken(); - break; - case DOC_SINGLE_BACKTICK_CONTENT: - token = readSingleBacktickContentToken(); - break; - case DOC_DOUBLE_BACKTICK_CONTENT: - token = readCodeContent(2); - break; - case DOC_TRIPLE_BACKTICK_CONTENT: - token = readCodeContent(3); - break; - case DOC_CODE_REF_END: - token = readCodeReferenceEndToken(); - break; - case DOC_CODE_LINE_START_HASH: + yield readDocReferenceTypeToken(); + } + case DOC_SINGLE_BACKTICK_CONTENT -> readSingleBacktickContentToken(); + case DOC_DOUBLE_BACKTICK_CONTENT -> readCodeContent(2); + case DOC_TRIPLE_BACKTICK_CONTENT -> readCodeContent(3); + case DOC_CODE_REF_END -> readCodeReferenceEndToken(); + case DOC_CODE_LINE_START_HASH -> { processLeadingTrivia(); - token = readCodeLineStartHashToken(); - break; - default: - token = null; - } + yield readCodeLineStartHashToken(); + } + default -> null; + }; // Can we improve this logic by creating the token with diagnostics then and there? return cloneWithDiagnostics(token); @@ -134,13 +122,10 @@ private String getLexeme() { * Check whether a given char is a possible identifier start. */ private boolean isPossibleIdentifierStart(int startChar) { - switch (startChar) { - case LexerTerminals.SINGLE_QUOTE: - case LexerTerminals.BACKSLASH: - return true; - default: - return isIdentifierInitialChar(startChar); - } + return switch (startChar) { + case LexerTerminals.SINGLE_QUOTE, LexerTerminals.BACKSLASH -> true; + default -> isIdentifierInitialChar(startChar); + }; } /** @@ -753,29 +738,21 @@ private STToken readDocReferenceTypeToken() { private STToken processReferenceType() { String tokenText = getLexeme(); - switch (tokenText) { - case LexerTerminals.TYPE: - return getDocSyntaxToken(SyntaxKind.TYPE_DOC_REFERENCE_TOKEN); - case LexerTerminals.SERVICE: - return getDocSyntaxToken(SyntaxKind.SERVICE_DOC_REFERENCE_TOKEN); - case LexerTerminals.VARIABLE: - return getDocSyntaxToken(SyntaxKind.VARIABLE_DOC_REFERENCE_TOKEN); - case LexerTerminals.VAR: - return getDocSyntaxToken(SyntaxKind.VAR_DOC_REFERENCE_TOKEN); - case LexerTerminals.ANNOTATION: - return getDocSyntaxToken(SyntaxKind.ANNOTATION_DOC_REFERENCE_TOKEN); - case LexerTerminals.MODULE: - return getDocSyntaxToken(SyntaxKind.MODULE_DOC_REFERENCE_TOKEN); - case LexerTerminals.FUNCTION: - return getDocSyntaxToken(SyntaxKind.FUNCTION_DOC_REFERENCE_TOKEN); - case LexerTerminals.PARAMETER: - return getDocSyntaxToken(SyntaxKind.PARAMETER_DOC_REFERENCE_TOKEN); - case LexerTerminals.CONST: - return getDocSyntaxToken(SyntaxKind.CONST_DOC_REFERENCE_TOKEN); - default: + return switch (tokenText) { + case LexerTerminals.TYPE -> getDocSyntaxToken(SyntaxKind.TYPE_DOC_REFERENCE_TOKEN); + case LexerTerminals.SERVICE -> getDocSyntaxToken(SyntaxKind.SERVICE_DOC_REFERENCE_TOKEN); + case LexerTerminals.VARIABLE -> getDocSyntaxToken(SyntaxKind.VARIABLE_DOC_REFERENCE_TOKEN); + case LexerTerminals.VAR -> getDocSyntaxToken(SyntaxKind.VAR_DOC_REFERENCE_TOKEN); + case LexerTerminals.ANNOTATION -> getDocSyntaxToken(SyntaxKind.ANNOTATION_DOC_REFERENCE_TOKEN); + case LexerTerminals.MODULE -> getDocSyntaxToken(SyntaxKind.MODULE_DOC_REFERENCE_TOKEN); + case LexerTerminals.FUNCTION -> getDocSyntaxToken(SyntaxKind.FUNCTION_DOC_REFERENCE_TOKEN); + case LexerTerminals.PARAMETER -> getDocSyntaxToken(SyntaxKind.PARAMETER_DOC_REFERENCE_TOKEN); + case LexerTerminals.CONST -> getDocSyntaxToken(SyntaxKind.CONST_DOC_REFERENCE_TOKEN); + default -> { assert false : "Invalid reference type"; - return getDocSyntaxToken(SyntaxKind.EOF_TOKEN); - } + yield getDocSyntaxToken(SyntaxKind.EOF_TOKEN); + } + }; } /* diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/DocumentationParser.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/DocumentationParser.java index b000e44c872e..4be4e8881505 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/DocumentationParser.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/DocumentationParser.java @@ -91,17 +91,12 @@ private STNode parseDocumentationLines() { private STNode parseSingleDocumentationLine() { STNode hashToken = consume(); STToken nextToken = peek(); - switch (nextToken.kind) { - case PLUS_TOKEN: - return parseParameterDocumentationLine(hashToken); - case DEPRECATION_LITERAL: - return parseDeprecationDocumentationLine(hashToken); - case TRIPLE_BACKTICK_TOKEN: - case DOUBLE_BACKTICK_TOKEN: - return parseCodeBlockOrInlineCodeRef(hashToken); - default: - return parseDocumentationLine(hashToken); - } + return switch (nextToken.kind) { + case PLUS_TOKEN -> parseParameterDocumentationLine(hashToken); + case DEPRECATION_LITERAL -> parseDeprecationDocumentationLine(hashToken); + case TRIPLE_BACKTICK_TOKEN, DOUBLE_BACKTICK_TOKEN -> parseCodeBlockOrInlineCodeRef(hashToken); + default -> parseDocumentationLine(hashToken); + }; } /** @@ -128,16 +123,11 @@ private STNode parseCodeBlockOrInlineCodeRef(STNode startLineHash) { } private boolean isInlineCodeRef(SyntaxKind nextTokenKind) { - switch (nextTokenKind) { - case HASH_TOKEN: - return getNextNextToken().kind == SyntaxKind.DOCUMENTATION_DESCRIPTION; - case CODE_CONTENT: - return getNextNextToken().kind != SyntaxKind.HASH_TOKEN; - case DOUBLE_BACKTICK_TOKEN: - case TRIPLE_BACKTICK_TOKEN: - default: - return true; - } + return switch (nextTokenKind) { + case HASH_TOKEN -> getNextNextToken().kind == SyntaxKind.DOCUMENTATION_DESCRIPTION; + case CODE_CONTENT -> getNextNextToken().kind != SyntaxKind.HASH_TOKEN; + default -> true; + }; } /** @@ -408,13 +398,12 @@ private boolean isEndOfCodeLines() { STNode nextToken = peek(); if (nextToken.kind == SyntaxKind.HASH_TOKEN) { STNode nextNextToken = getNextNextToken(); - switch (nextNextToken.kind) { - case CODE_CONTENT: - case HASH_TOKEN: // case where code line description is empty - return false; - default: - return true; - } + return switch (nextNextToken.kind) { + case CODE_CONTENT, + // case where code line description is empty + HASH_TOKEN -> false; + default -> true; + }; } return true; @@ -478,22 +467,14 @@ private enum ReferenceGenre { private boolean isBallerinaNameRefTokenSequence(ReferenceGenre refGenre) { boolean hasMatch; Lookahead lookahead = new Lookahead(); - switch (refGenre) { - case SPECIAL_KEY: - // Look for x, m:x match - hasMatch = hasQualifiedIdentifier(lookahead); - break; - case FUNCTION_KEY: - // Look for x, m:x, x(), m:x(), T.y(), m:T.y() match - hasMatch = hasBacktickExpr(lookahead, true); - break; - case NO_KEY: - // Look for x(), m:x(), T.y(), m:T.y() match - hasMatch = hasBacktickExpr(lookahead, false); - break; - default: - throw new IllegalStateException("Unsupported backtick reference genre"); - } + hasMatch = switch (refGenre) { + // Look for x, m:x match + case SPECIAL_KEY -> hasQualifiedIdentifier(lookahead); + // Look for x, m:x, x(), m:x(), T.y(), m:T.y() match + case FUNCTION_KEY -> hasBacktickExpr(lookahead, true); + // Look for x(), m:x(), T.y(), m:T.y() match + case NO_KEY -> hasBacktickExpr(lookahead, false); + }; return hasMatch && peek(lookahead.offset).kind == SyntaxKind.BACKTICK_TOKEN; } @@ -568,20 +549,18 @@ private boolean hasIdentifier(Lookahead lookahead) { } private boolean isDocumentReferenceType(SyntaxKind kind) { - switch (kind) { - case TYPE_DOC_REFERENCE_TOKEN: - case SERVICE_DOC_REFERENCE_TOKEN: - case VARIABLE_DOC_REFERENCE_TOKEN: - case VAR_DOC_REFERENCE_TOKEN: - case ANNOTATION_DOC_REFERENCE_TOKEN: - case MODULE_DOC_REFERENCE_TOKEN: - case FUNCTION_DOC_REFERENCE_TOKEN: - case PARAMETER_DOC_REFERENCE_TOKEN: - case CONST_DOC_REFERENCE_TOKEN: - return true; - default: - return false; - } + return switch (kind) { + case TYPE_DOC_REFERENCE_TOKEN, + SERVICE_DOC_REFERENCE_TOKEN, + VARIABLE_DOC_REFERENCE_TOKEN, + VAR_DOC_REFERENCE_TOKEN, + ANNOTATION_DOC_REFERENCE_TOKEN, + MODULE_DOC_REFERENCE_TOKEN, + FUNCTION_DOC_REFERENCE_TOKEN, + PARAMETER_DOC_REFERENCE_TOKEN, + CONST_DOC_REFERENCE_TOKEN -> true; + default -> false; + }; } /** @@ -610,21 +589,19 @@ private STNode parseParameterDocumentationLine(STNode hashToken) { } private boolean isEndOfIntermediateDocumentation(SyntaxKind kind) { - switch (kind) { - case DOCUMENTATION_DESCRIPTION: - case PLUS_TOKEN: - case PARAMETER_NAME: - case MINUS_TOKEN: - case BACKTICK_TOKEN: - case DOUBLE_BACKTICK_TOKEN: - case TRIPLE_BACKTICK_TOKEN: - case CODE_CONTENT: - case RETURN_KEYWORD: - case DEPRECATION_LITERAL: - return false; - default: - return !isDocumentReferenceType(kind); - } + return switch (kind) { + case DOCUMENTATION_DESCRIPTION, + PLUS_TOKEN, + PARAMETER_NAME, + MINUS_TOKEN, + BACKTICK_TOKEN, + DOUBLE_BACKTICK_TOKEN, + TRIPLE_BACKTICK_TOKEN, + CODE_CONTENT, + RETURN_KEYWORD, + DEPRECATION_LITERAL -> false; + default -> !isDocumentReferenceType(kind); + }; } /** @@ -710,17 +687,15 @@ private STNode combineAndCreateCodeContentToken() { } private boolean isBacktickExprToken(SyntaxKind kind) { - switch (kind) { - case DOT_TOKEN: - case COLON_TOKEN: - case OPEN_PAREN_TOKEN: - case CLOSE_PAREN_TOKEN: - case IDENTIFIER_TOKEN: - case CODE_CONTENT: - return true; - default: - return false; - } + return switch (kind) { + case DOT_TOKEN, + COLON_TOKEN, + OPEN_PAREN_TOKEN, + CLOSE_PAREN_TOKEN, + IDENTIFIER_TOKEN, + CODE_CONTENT -> true; + default -> false; + }; } private STNode parseNameReferenceContent() { @@ -742,18 +717,16 @@ private STNode parseBacktickExpr(STNode identifier) { STNode referenceName = parseQualifiedIdentifier(identifier); STToken nextToken = peek(); - switch (nextToken.kind) { - case BACKTICK_TOKEN: - return referenceName; - case DOT_TOKEN: + return switch (nextToken.kind) { + case BACKTICK_TOKEN -> referenceName; + case DOT_TOKEN -> { STNode dotToken = consume(); - return parseMethodCall(referenceName, dotToken); - case OPEN_PAREN_TOKEN: - return parseFuncCall(referenceName); - default: - // Since we have validated the token sequence beforehand, code should not reach here. - throw new IllegalStateException("Unsupported token kind"); - } + yield parseMethodCall(referenceName, dotToken); + } + case OPEN_PAREN_TOKEN -> parseFuncCall(referenceName); + // Since we have validated the token sequence beforehand, code should not reach here. + default -> throw new IllegalStateException("Unsupported token kind"); + }; } /** diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/LexerTerminals.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/LexerTerminals.java index 34c7c7aff43a..36f5c0b0041f 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/LexerTerminals.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/LexerTerminals.java @@ -22,7 +22,7 @@ * * @since 1.2.0 */ -public class LexerTerminals { +public final class LexerTerminals { // Keywords public static final String PUBLIC = "public"; @@ -173,4 +173,7 @@ public class LexerTerminals { public static final char FORM_FEED = 0xC; public static final String RE = "re"; + + private LexerTerminals() { + } } diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/ParserFactory.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/ParserFactory.java index 645780822f93..f14ef661f223 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/ParserFactory.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/ParserFactory.java @@ -34,7 +34,7 @@ * * @since 1.3.0 */ -public class ParserFactory { +public final class ParserFactory { private ParserFactory() { } diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/RegExpLexer.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/RegExpLexer.java index 99b6037888f7..b51cc5b3f5ab 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/RegExpLexer.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/RegExpLexer.java @@ -101,56 +101,49 @@ private STToken readTokenInReDisjunction() { // ReSequence has zero or more ReTerm. this.reader.advance(); - switch (nextChar) { - case LexerTerminals.BITWISE_XOR: - return getRegExpSyntaxToken(SyntaxKind.BITWISE_XOR_TOKEN); - case LexerTerminals.DOLLAR: + return switch (nextChar) { + case LexerTerminals.BITWISE_XOR -> getRegExpSyntaxToken(SyntaxKind.BITWISE_XOR_TOKEN); + case LexerTerminals.DOLLAR -> { if (this.mode != ParserMode.RE_CHAR_CLASS && peek() == LexerTerminals.OPEN_BRACE) { // Start interpolation mode. startMode(ParserMode.INTERPOLATION); this.reader.advance(); - return getRegExpSyntaxToken(SyntaxKind.INTERPOLATION_START_TOKEN); + yield getRegExpSyntaxToken(SyntaxKind.INTERPOLATION_START_TOKEN); } - return getRegExpSyntaxToken(SyntaxKind.DOLLAR_TOKEN); - case LexerTerminals.DOT: - return getRegExpSyntaxToken(SyntaxKind.DOT_TOKEN); - case LexerTerminals.ASTERISK: - return getRegExpSyntaxToken(SyntaxKind.ASTERISK_TOKEN); - case LexerTerminals.PLUS: - return getRegExpSyntaxToken(SyntaxKind.PLUS_TOKEN); - case LexerTerminals.QUESTION_MARK: - return getRegExpSyntaxToken(SyntaxKind.QUESTION_MARK_TOKEN); - case LexerTerminals.BACKSLASH: - return processReEscape(); + yield getRegExpSyntaxToken(SyntaxKind.DOLLAR_TOKEN); + // Start interpolation mode. + } + case LexerTerminals.DOT -> getRegExpSyntaxToken(SyntaxKind.DOT_TOKEN); + case LexerTerminals.ASTERISK -> getRegExpSyntaxToken(SyntaxKind.ASTERISK_TOKEN); + case LexerTerminals.PLUS -> getRegExpSyntaxToken(SyntaxKind.PLUS_TOKEN); + case LexerTerminals.QUESTION_MARK -> getRegExpSyntaxToken(SyntaxKind.QUESTION_MARK_TOKEN); + case LexerTerminals.BACKSLASH -> processReEscape(); // Start parsing ReSyntaxChar character class [[^] [ReCharSet]]. - case LexerTerminals.OPEN_BRACKET: + case LexerTerminals.OPEN_BRACKET -> { if (this.mode != ParserMode.RE_QUOTE_ESCAPE) { startMode(ParserMode.RE_CHAR_CLASS); } - - return getRegExpSyntaxToken(SyntaxKind.OPEN_BRACKET_TOKEN); - case LexerTerminals.CLOSE_BRACKET: + yield getRegExpSyntaxToken(SyntaxKind.OPEN_BRACKET_TOKEN); + } + case LexerTerminals.CLOSE_BRACKET -> { if (this.mode == ParserMode.RE_CHAR_CLASS) { endMode(); } - return getRegExpSyntaxToken(SyntaxKind.CLOSE_BRACKET_TOKEN); - case LexerTerminals.OPEN_BRACE: - return getRegExpSyntaxToken(SyntaxKind.OPEN_BRACE_TOKEN); - case LexerTerminals.CLOSE_BRACE: - return getRegExpSyntaxToken(SyntaxKind.CLOSE_BRACE_TOKEN); + yield getRegExpSyntaxToken(SyntaxKind.CLOSE_BRACKET_TOKEN); + } + case LexerTerminals.OPEN_BRACE -> getRegExpSyntaxToken(SyntaxKind.OPEN_BRACE_TOKEN); + case LexerTerminals.CLOSE_BRACE -> getRegExpSyntaxToken(SyntaxKind.CLOSE_BRACE_TOKEN); // Start parsing capturing group ([? ReFlagsOnOff :] ReDisjunction). - case LexerTerminals.OPEN_PARANTHESIS: - return getRegExpSyntaxToken(SyntaxKind.OPEN_PAREN_TOKEN); - case LexerTerminals.CLOSE_PARANTHESIS: - return getRegExpSyntaxToken(SyntaxKind.CLOSE_PAREN_TOKEN); - case LexerTerminals.COMMA: - return getRegExpSyntaxToken(SyntaxKind.COMMA_TOKEN); - default: + case LexerTerminals.OPEN_PARANTHESIS -> getRegExpSyntaxToken(SyntaxKind.OPEN_PAREN_TOKEN); + case LexerTerminals.CLOSE_PARANTHESIS -> getRegExpSyntaxToken(SyntaxKind.CLOSE_PAREN_TOKEN); + case LexerTerminals.COMMA -> getRegExpSyntaxToken(SyntaxKind.COMMA_TOKEN); + default -> { if (isDigit(nextChar)) { - return getRegExpText(SyntaxKind.DIGIT); + yield getRegExpText(SyntaxKind.DIGIT); } - return getRegExpText(SyntaxKind.RE_LITERAL_CHAR); - } + yield getRegExpText(SyntaxKind.RE_LITERAL_CHAR); + } + }; } private STToken processReEscape() { @@ -482,17 +475,10 @@ private String getLexeme() { * @return true, if the character is ReSimpleCharClassCode. false otherwise. */ protected static boolean isReSimpleCharClassCode(int c) { - switch (c) { - case 'd': - case 'D': - case 's': - case 'S': - case 'w': - case 'W': - return true; - default: - return false; - } + return switch (c) { + case 'd', 'D', 's', 'S', 'w', 'W' -> true; + default -> false; + }; } /** @@ -506,14 +492,10 @@ protected static boolean isReSimpleCharClassCode(int c) { * @return true, if the character is ReCharSetLiteralChar. false otherwise. */ protected static boolean isReCharSetLiteralChar(int c) { - switch (c) { - case '\\': - case ']': - case '-': - return false; - default: - return true; - } + return switch (c) { + case '\\', ']', '-' -> false; + default -> true; + }; } /** @@ -531,14 +513,9 @@ protected static boolean isReCharSetLiteralChar(int c) { * @return true, if the character is ReFlag. false otherwise. */ protected static boolean isReFlag(int c) { - switch (c) { - case 'm': - case 's': - case 'i': - case 'x': - return true; - default: - return false; - } + return switch (c) { + case 'm', 's', 'i', 'x' -> true; + default -> false; + }; } } diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/RegExpParser.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/RegExpParser.java index 1e489cd72b43..160f8596a6d5 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/RegExpParser.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/RegExpParser.java @@ -96,36 +96,25 @@ private STNode parseReTerm() { return parseReAssertion(); } - STNode reAtom; - switch (nextToken.kind) { - case RE_LITERAL_CHAR: - case RE_NUMERIC_ESCAPE: - case RE_CONTROL_ESCAPE: - case COMMA_TOKEN: - case DOT_TOKEN: - case DIGIT: - reAtom = parseChars(); - break; - case BACK_SLASH_TOKEN: - reAtom = parseReEscape(); - break; - case OPEN_BRACKET_TOKEN: - reAtom = parseCharacterClass(); - break; - case OPEN_PAREN_TOKEN: - reAtom = parseCapturingGroup(); - break; - case INTERPOLATION_START_TOKEN: - reAtom = parseInterpolation(); - break; - default: + STNode reAtom = switch (nextToken.kind) { + case RE_LITERAL_CHAR, + RE_NUMERIC_ESCAPE, + RE_CONTROL_ESCAPE, + COMMA_TOKEN, + DOT_TOKEN, + DIGIT -> parseChars(); + case BACK_SLASH_TOKEN -> parseReEscape(); + case OPEN_BRACKET_TOKEN -> parseCharacterClass(); + case OPEN_PAREN_TOKEN -> parseCapturingGroup(); + case INTERPOLATION_START_TOKEN -> parseInterpolation(); + default -> { // Here the token is a syntax char, which is invalid. A syntax char should have a backslash prior // to the token. STNode missingBackSlash = SyntaxErrors.createMissingRegExpTokenWithDiagnostics(SyntaxKind.BACK_SLASH_TOKEN); - reAtom = SyntaxErrors.cloneWithTrailingInvalidNodeMinutiae(missingBackSlash, consume()); - break; - } + yield SyntaxErrors.cloneWithTrailingInvalidNodeMinutiae(missingBackSlash, consume()); + } + }; nextToken = peek(); STNode quantifier = parseOptionalQuantifier(nextToken.kind); @@ -138,15 +127,10 @@ private STNode parseReTerm() { } private STNode parseOptionalQuantifier(SyntaxKind tokenKind) { - switch (tokenKind) { - case PLUS_TOKEN: - case ASTERISK_TOKEN: - case QUESTION_MARK_TOKEN: - case OPEN_BRACE_TOKEN: - return parseReQuantifier(); - default: - return null; - } + return switch (tokenKind) { + case PLUS_TOKEN, ASTERISK_TOKEN, QUESTION_MARK_TOKEN, OPEN_BRACE_TOKEN -> parseReQuantifier(); + default -> null; + }; } /** @@ -304,17 +288,10 @@ static boolean isReSimpleCharClassCode(STToken token) { if (token.kind != SyntaxKind.RE_LITERAL_CHAR) { return false; } - switch (token.text()) { - case "d": - case "D": - case "s": - case "S": - case "w": - case "W": - return true; - default: - return false; - } + return switch (token.text()) { + case "d", "D", "s", "S", "w", "W" -> true; + default -> false; + }; } /** @@ -445,24 +422,17 @@ private STNode parseCharSetAtom(STToken nextToken, STNode prevNode) { } private boolean isReCharSetLiteralChar(String tokenText) { - switch (tokenText) { - case "\\": - case "-": - case "]": - return false; - default: - return true; - } + return switch (tokenText) { + case "\\", "-", "]" -> false; + default -> true; + }; } private boolean isCharacterClassEnd(SyntaxKind kind) { - switch (kind) { - case EOF_TOKEN: - case CLOSE_BRACKET_TOKEN: - return true; - default: - return false; - } + return switch (kind) { + case EOF_TOKEN, CLOSE_BRACKET_TOKEN -> true; + default -> false; + }; } /** @@ -550,15 +520,11 @@ private boolean isInvalidDigit(STToken nextToken, boolean isLeastDigits) { } private boolean isEndOfDigits(SyntaxKind kind, boolean isLeastDigits) { - switch (kind) { - case CLOSE_BRACE_TOKEN: - case EOF_TOKEN: - return true; - case COMMA_TOKEN: - return isLeastDigits; - default: - return false; - } + return switch (kind) { + case CLOSE_BRACE_TOKEN, EOF_TOKEN -> true; + case COMMA_TOKEN -> isLeastDigits; + default -> false; + }; } /** @@ -637,15 +603,10 @@ static boolean isReFlag(STToken nextToken) { if (nextToken.kind != SyntaxKind.RE_LITERAL_CHAR) { return false; } - switch (nextToken.text()) { - case "m": - case "s": - case "i": - case "x": - return true; - default: - return false; - } + return switch (nextToken.text()) { + case "m", "s", "i", "x" -> true; + default -> false; + }; } /** @@ -749,24 +710,17 @@ private STNode parseInterpolation() { } private boolean isEndOfReDisjunction(SyntaxKind kind, boolean inCapturingGroup) { - switch (kind) { - case EOF_TOKEN: - case BACKTICK_TOKEN: - return true; - default: - return kind == SyntaxKind.CLOSE_PAREN_TOKEN && inCapturingGroup; - } + return switch (kind) { + case EOF_TOKEN, BACKTICK_TOKEN -> true; + default -> kind == SyntaxKind.CLOSE_PAREN_TOKEN && inCapturingGroup; + }; } private boolean isEndOfReSequence(SyntaxKind kind, boolean inCapturingGroup) { - switch (kind) { - case EOF_TOKEN: - case BACKTICK_TOKEN: - case PIPE_TOKEN: - return true; - default: - return kind == SyntaxKind.CLOSE_PAREN_TOKEN && inCapturingGroup; - } + return switch (kind) { + case EOF_TOKEN, BACKTICK_TOKEN, PIPE_TOKEN -> true; + default -> kind == SyntaxKind.CLOSE_PAREN_TOKEN && inCapturingGroup; + }; } private STNode getToken(STToken token, SyntaxKind syntaxKind) { diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/SyntaxErrors.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/SyntaxErrors.java index 16bea2db962f..22d23ca87b6a 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/SyntaxErrors.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/SyntaxErrors.java @@ -39,7 +39,7 @@ * * @since 2.0.0 */ -public class SyntaxErrors { +public final class SyntaxErrors { private SyntaxErrors() { } @@ -98,484 +98,322 @@ public static STToken createMissingTokenWithDiagnostics(SyntaxKind expectedKind, } private static DiagnosticCode getErrorCode(ParserRuleContext currentCtx) { - switch (currentCtx) { - case EXTERNAL_FUNC_BODY: - return DiagnosticErrorCode.ERROR_MISSING_EQUAL_TOKEN; - case FUNC_BODY_BLOCK: - return DiagnosticErrorCode.ERROR_MISSING_OPEN_BRACE_TOKEN; - case FUNC_DEF: - case FUNC_DEF_OR_FUNC_TYPE: - case FUNC_TYPE_DESC: - case FUNC_TYPE_DESC_OR_ANON_FUNC: - case IDENT_AFTER_OBJECT_IDENT: - case FUNC_DEF_FIRST_QUALIFIER: - case FUNC_DEF_SECOND_QUALIFIER: - case FUNC_TYPE_FIRST_QUALIFIER: - case FUNC_TYPE_SECOND_QUALIFIER: - case OBJECT_METHOD_FIRST_QUALIFIER: - case OBJECT_METHOD_SECOND_QUALIFIER: - case OBJECT_METHOD_THIRD_QUALIFIER: - case OBJECT_METHOD_FOURTH_QUALIFIER: - return DiagnosticErrorCode.ERROR_MISSING_FUNCTION_KEYWORD; - case SINGLE_KEYWORD_ATTACH_POINT_IDENT: - return DiagnosticErrorCode.ERROR_MISSING_ATTACH_POINT_NAME; - case SIMPLE_TYPE_DESCRIPTOR: - return DiagnosticErrorCode.ERROR_MISSING_BUILTIN_TYPE; - case REQUIRED_PARAM: - case VAR_DECL_STMT: - case ASSIGNMENT_OR_VAR_DECL_STMT: - case DEFAULTABLE_PARAM: - case REST_PARAM: - case TYPE_DESCRIPTOR: - case OPTIONAL_TYPE_DESCRIPTOR: - case ARRAY_TYPE_DESCRIPTOR: - case SIMPLE_TYPE_DESC_IDENTIFIER: - return DiagnosticErrorCode.ERROR_MISSING_TYPE_DESC; - case TYPE_REFERENCE: - return DiagnosticErrorCode.ERROR_MISSING_TYPE_REFERENCE; - case TYPE_NAME: - case TYPE_REFERENCE_IN_TYPE_INCLUSION: - case FIELD_ACCESS_IDENTIFIER: - case CLASS_NAME: - case FUNC_NAME: - case VARIABLE_NAME: - case IMPORT_MODULE_NAME: - case IMPORT_ORG_OR_MODULE_NAME: - case IMPORT_PREFIX: - case VARIABLE_REF: - case BASIC_LITERAL: // return var-ref for any kind of terminal expression - case IDENTIFIER: - case QUALIFIED_IDENTIFIER_START_IDENTIFIER: - case NAMESPACE_PREFIX: - case IMPLICIT_ANON_FUNC_PARAM: - case METHOD_NAME: - case PEER_WORKER_NAME: - case RECEIVE_FIELD_NAME: - case WAIT_FIELD_NAME: - case FIELD_BINDING_PATTERN_NAME: - case XML_ATOMIC_NAME_IDENTIFIER: - case MAPPING_FIELD_NAME: - case WORKER_NAME: - case NAMED_WORKERS: - case ANNOTATION_TAG: - case AFTER_PARAMETER_TYPE: - case MODULE_ENUM_NAME: - case ENUM_MEMBER_NAME: - case TYPED_BINDING_PATTERN_TYPE_RHS: - case ASSIGNMENT_STMT: - case XML_NAME: - case ACCESS_EXPRESSION: - case BINDING_PATTERN_STARTING_IDENTIFIER: - case COMPUTED_FIELD_NAME: - case SIMPLE_BINDING_PATTERN: - case ERROR_FIELD_BINDING_PATTERN: - case ERROR_CAUSE_SIMPLE_BINDING_PATTERN: - case PATH_SEGMENT_IDENT: - case NAMED_ARG_BINDING_PATTERN: - case MODULE_VAR_FIRST_QUAL: - case MODULE_VAR_SECOND_QUAL: - case MODULE_VAR_THIRD_QUAL: - case OBJECT_MEMBER_VISIBILITY_QUAL: - return DiagnosticErrorCode.ERROR_MISSING_IDENTIFIER; - case EXPRESSION: - case TERMINAL_EXPRESSION: - return DiagnosticErrorCode.ERROR_MISSING_EXPRESSION; - case STRING_LITERAL_TOKEN: - return DiagnosticErrorCode.ERROR_MISSING_STRING_LITERAL; - case DECIMAL_INTEGER_LITERAL_TOKEN: - case SIGNED_INT_OR_FLOAT_RHS: - return DiagnosticErrorCode.ERROR_MISSING_DECIMAL_INTEGER_LITERAL; - case HEX_INTEGER_LITERAL_TOKEN: - return DiagnosticErrorCode.ERROR_MISSING_HEX_INTEGER_LITERAL; - case OBJECT_FIELD_RHS: - case BINDING_PATTERN_OR_VAR_REF_RHS: - return DiagnosticErrorCode.ERROR_MISSING_SEMICOLON_TOKEN; - case NIL_LITERAL: - case ERROR_MATCH_PATTERN: - return DiagnosticErrorCode.ERROR_MISSING_ERROR_KEYWORD; - case DECIMAL_FLOATING_POINT_LITERAL_TOKEN: - return DiagnosticErrorCode.ERROR_MISSING_DECIMAL_FLOATING_POINT_LITERAL; - case HEX_FLOATING_POINT_LITERAL_TOKEN: - return DiagnosticErrorCode.ERROR_MISSING_HEX_FLOATING_POINT_LITERAL; - case STATEMENT: - case STATEMENT_WITHOUT_ANNOTS: - return DiagnosticErrorCode.ERROR_MISSING_CLOSE_BRACE_TOKEN; - case XML_COMMENT_CONTENT: - case XML_PI_DATA: - return DiagnosticErrorCode.ERROR_MISSING_XML_TEXT_CONTENT; - default: - return getSeperatorTokenErrorCode(currentCtx); - } + return switch (currentCtx) { + case EXTERNAL_FUNC_BODY -> DiagnosticErrorCode.ERROR_MISSING_EQUAL_TOKEN; + case FUNC_BODY_BLOCK -> DiagnosticErrorCode.ERROR_MISSING_OPEN_BRACE_TOKEN; + case FUNC_DEF, + FUNC_DEF_OR_FUNC_TYPE, + FUNC_TYPE_DESC, + FUNC_TYPE_DESC_OR_ANON_FUNC, + IDENT_AFTER_OBJECT_IDENT, + FUNC_DEF_FIRST_QUALIFIER, + FUNC_DEF_SECOND_QUALIFIER, + FUNC_TYPE_FIRST_QUALIFIER, + FUNC_TYPE_SECOND_QUALIFIER, + OBJECT_METHOD_FIRST_QUALIFIER, + OBJECT_METHOD_SECOND_QUALIFIER, + OBJECT_METHOD_THIRD_QUALIFIER, + OBJECT_METHOD_FOURTH_QUALIFIER -> DiagnosticErrorCode.ERROR_MISSING_FUNCTION_KEYWORD; + case SINGLE_KEYWORD_ATTACH_POINT_IDENT -> DiagnosticErrorCode.ERROR_MISSING_ATTACH_POINT_NAME; + case SIMPLE_TYPE_DESCRIPTOR -> DiagnosticErrorCode.ERROR_MISSING_BUILTIN_TYPE; + case REQUIRED_PARAM, + VAR_DECL_STMT, + ASSIGNMENT_OR_VAR_DECL_STMT, + DEFAULTABLE_PARAM, + REST_PARAM, + TYPE_DESCRIPTOR, + OPTIONAL_TYPE_DESCRIPTOR, + ARRAY_TYPE_DESCRIPTOR, + SIMPLE_TYPE_DESC_IDENTIFIER -> DiagnosticErrorCode.ERROR_MISSING_TYPE_DESC; + // return var-ref for any kind of terminal expression + case TYPE_REFERENCE -> DiagnosticErrorCode.ERROR_MISSING_TYPE_REFERENCE; + case TYPE_NAME, + TYPE_REFERENCE_IN_TYPE_INCLUSION, + FIELD_ACCESS_IDENTIFIER, + CLASS_NAME, + FUNC_NAME, + VARIABLE_NAME, + IMPORT_MODULE_NAME, + IMPORT_ORG_OR_MODULE_NAME, + IMPORT_PREFIX, + VARIABLE_REF, + BASIC_LITERAL, + IDENTIFIER, + QUALIFIED_IDENTIFIER_START_IDENTIFIER, + NAMESPACE_PREFIX, + IMPLICIT_ANON_FUNC_PARAM, + METHOD_NAME, + PEER_WORKER_NAME, + RECEIVE_FIELD_NAME, + WAIT_FIELD_NAME, + FIELD_BINDING_PATTERN_NAME, + XML_ATOMIC_NAME_IDENTIFIER, + MAPPING_FIELD_NAME, + WORKER_NAME, + NAMED_WORKERS, + ANNOTATION_TAG, + AFTER_PARAMETER_TYPE, + MODULE_ENUM_NAME, + ENUM_MEMBER_NAME, + TYPED_BINDING_PATTERN_TYPE_RHS, + ASSIGNMENT_STMT, + XML_NAME, + ACCESS_EXPRESSION, + BINDING_PATTERN_STARTING_IDENTIFIER, + COMPUTED_FIELD_NAME, + SIMPLE_BINDING_PATTERN, + ERROR_FIELD_BINDING_PATTERN, + ERROR_CAUSE_SIMPLE_BINDING_PATTERN, + PATH_SEGMENT_IDENT, + NAMED_ARG_BINDING_PATTERN, + MODULE_VAR_FIRST_QUAL, + MODULE_VAR_SECOND_QUAL, + MODULE_VAR_THIRD_QUAL, + OBJECT_MEMBER_VISIBILITY_QUAL -> DiagnosticErrorCode.ERROR_MISSING_IDENTIFIER; + case EXPRESSION, + TERMINAL_EXPRESSION -> DiagnosticErrorCode.ERROR_MISSING_EXPRESSION; + case STRING_LITERAL_TOKEN -> DiagnosticErrorCode.ERROR_MISSING_STRING_LITERAL; + case DECIMAL_INTEGER_LITERAL_TOKEN, + SIGNED_INT_OR_FLOAT_RHS -> DiagnosticErrorCode.ERROR_MISSING_DECIMAL_INTEGER_LITERAL; + case HEX_INTEGER_LITERAL_TOKEN -> DiagnosticErrorCode.ERROR_MISSING_HEX_INTEGER_LITERAL; + case OBJECT_FIELD_RHS, + BINDING_PATTERN_OR_VAR_REF_RHS -> DiagnosticErrorCode.ERROR_MISSING_SEMICOLON_TOKEN; + case NIL_LITERAL, + ERROR_MATCH_PATTERN -> DiagnosticErrorCode.ERROR_MISSING_ERROR_KEYWORD; + case DECIMAL_FLOATING_POINT_LITERAL_TOKEN -> + DiagnosticErrorCode.ERROR_MISSING_DECIMAL_FLOATING_POINT_LITERAL; + case HEX_FLOATING_POINT_LITERAL_TOKEN -> DiagnosticErrorCode.ERROR_MISSING_HEX_FLOATING_POINT_LITERAL; + case STATEMENT, + STATEMENT_WITHOUT_ANNOTS -> DiagnosticErrorCode.ERROR_MISSING_CLOSE_BRACE_TOKEN; + case XML_COMMENT_CONTENT, + XML_PI_DATA -> DiagnosticErrorCode.ERROR_MISSING_XML_TEXT_CONTENT; + default -> getSeperatorTokenErrorCode(currentCtx); + }; } private static DiagnosticCode getSeperatorTokenErrorCode(ParserRuleContext ctx) { - switch (ctx) { - case BITWISE_AND_OPERATOR: - return DiagnosticErrorCode.ERROR_MISSING_BITWISE_AND_TOKEN; - case EQUAL_OR_RIGHT_ARROW: - case ASSIGN_OP: - return DiagnosticErrorCode.ERROR_MISSING_EQUAL_TOKEN; - case BINARY_OPERATOR: - case UNARY_OPERATOR: - case COMPOUND_BINARY_OPERATOR: - case UNARY_EXPRESSION: - case EXPRESSION_RHS: - case PLUS_TOKEN: - return DiagnosticErrorCode.ERROR_MISSING_BINARY_OPERATOR; - case CLOSE_BRACE: - return DiagnosticErrorCode.ERROR_MISSING_CLOSE_BRACE_TOKEN; - case CLOSE_PARENTHESIS: - case ARG_LIST_CLOSE_PAREN: - return DiagnosticErrorCode.ERROR_MISSING_CLOSE_PAREN_TOKEN; - case COMMA: - case ERROR_MESSAGE_BINDING_PATTERN_END_COMMA: - case ERROR_MESSAGE_MATCH_PATTERN_END_COMMA: - return DiagnosticErrorCode.ERROR_MISSING_COMMA_TOKEN; - case OPEN_BRACE: - return DiagnosticErrorCode.ERROR_MISSING_OPEN_BRACE_TOKEN; - case OPEN_PARENTHESIS: - case ARG_LIST_OPEN_PAREN: - case PARENTHESISED_TYPE_DESC_START: - return DiagnosticErrorCode.ERROR_MISSING_OPEN_PAREN_TOKEN; - case SEMICOLON: - case OBJECT_FIELD_RHS: - return DiagnosticErrorCode.ERROR_MISSING_SEMICOLON_TOKEN; - case ASTERISK: - return DiagnosticErrorCode.ERROR_MISSING_ASTERISK_TOKEN; - case CLOSED_RECORD_BODY_END: - return DiagnosticErrorCode.ERROR_MISSING_CLOSE_BRACE_PIPE_TOKEN; - case CLOSED_RECORD_BODY_START: - return DiagnosticErrorCode.ERROR_MISSING_OPEN_BRACE_PIPE_TOKEN; - case ELLIPSIS: - return DiagnosticErrorCode.ERROR_MISSING_ELLIPSIS_TOKEN; - case QUESTION_MARK: - return DiagnosticErrorCode.ERROR_MISSING_QUESTION_MARK_TOKEN; - case CLOSE_BRACKET: - return DiagnosticErrorCode.ERROR_MISSING_CLOSE_BRACKET_TOKEN; - case DOT: - case METHOD_CALL_DOT: - return DiagnosticErrorCode.ERROR_MISSING_DOT_TOKEN; - case OPEN_BRACKET: - case TUPLE_TYPE_DESC_START: - return DiagnosticErrorCode.ERROR_MISSING_OPEN_BRACKET_TOKEN; - case SLASH: - case ABSOLUTE_PATH_SINGLE_SLASH: - case RESOURCE_METHOD_CALL_SLASH_TOKEN: - return DiagnosticErrorCode.ERROR_MISSING_SLASH_TOKEN; - case COLON: - case VAR_REF_COLON: - case TYPE_REF_COLON: - return DiagnosticErrorCode.ERROR_MISSING_COLON_TOKEN; - case AT: - return DiagnosticErrorCode.ERROR_MISSING_AT_TOKEN; - case RIGHT_ARROW: - return DiagnosticErrorCode.ERROR_MISSING_RIGHT_ARROW_TOKEN; - case GT: - case GT_TOKEN: - case XML_START_OR_EMPTY_TAG_END: - case XML_ATTRIBUTES: - case INFERRED_TYPEDESC_DEFAULT_END_GT: - return DiagnosticErrorCode.ERROR_MISSING_GT_TOKEN; - case LT: - case LT_TOKEN: - case XML_START_OR_EMPTY_TAG: - case XML_END_TAG: - case INFERRED_TYPEDESC_DEFAULT_START_LT: - case STREAM_TYPE_PARAM_START_TOKEN: - return DiagnosticErrorCode.ERROR_MISSING_LT_TOKEN; - case SYNC_SEND_TOKEN: - return DiagnosticErrorCode.ERROR_MISSING_SYNC_SEND_TOKEN; - case ANNOT_CHAINING_TOKEN: - return DiagnosticErrorCode.ERROR_MISSING_ANNOT_CHAINING_TOKEN; - case OPTIONAL_CHAINING_TOKEN: - return DiagnosticErrorCode.ERROR_MISSING_OPTIONAL_CHAINING_TOKEN; - case DOT_LT_TOKEN: - return DiagnosticErrorCode.ERROR_MISSING_DOT_LT_TOKEN; - case SLASH_LT_TOKEN: - return DiagnosticErrorCode.ERROR_MISSING_SLASH_LT_TOKEN; - case DOUBLE_SLASH_DOUBLE_ASTERISK_LT_TOKEN: - return DiagnosticErrorCode.ERROR_MISSING_DOUBLE_SLASH_DOUBLE_ASTERISK_LT_TOKEN; - case SLASH_ASTERISK_TOKEN: - return DiagnosticErrorCode.ERROR_MISSING_SLASH_ASTERISK_TOKEN; - case MINUS_TOKEN: - return DiagnosticErrorCode.ERROR_MISSING_MINUS_TOKEN; - case LEFT_ARROW_TOKEN: - return DiagnosticErrorCode.ERROR_MISSING_LEFT_ARROW_TOKEN; - case TEMPLATE_END: - case TEMPLATE_START: - case XML_CONTENT: - case XML_TEXT: - return DiagnosticErrorCode.ERROR_MISSING_BACKTICK_TOKEN; - case XML_COMMENT_START: - return DiagnosticErrorCode.ERROR_MISSING_XML_COMMENT_START_TOKEN; - case XML_COMMENT_END: - return DiagnosticErrorCode.ERROR_MISSING_XML_COMMENT_END_TOKEN; - case XML_PI: - case XML_PI_START: - return DiagnosticErrorCode.ERROR_MISSING_XML_PI_START_TOKEN; - case XML_PI_END: - return DiagnosticErrorCode.ERROR_MISSING_XML_PI_END_TOKEN; - case XML_QUOTE_END: - case XML_QUOTE_START: - return DiagnosticErrorCode.ERROR_MISSING_DOUBLE_QUOTE_TOKEN; - case INTERPOLATION_START_TOKEN: - return DiagnosticErrorCode.ERROR_MISSING_INTERPOLATION_START_TOKEN; - case EXPR_FUNC_BODY_START: - case RIGHT_DOUBLE_ARROW: - return DiagnosticErrorCode.ERROR_MISSING_RIGHT_DOUBLE_ARROW_TOKEN; - case XML_CDATA_END: - return DiagnosticErrorCode.ERROR_MISSING_XML_CDATA_END_TOKEN; - default: - return getKeywordErrorCode(ctx); - } + return switch (ctx) { + case BITWISE_AND_OPERATOR -> DiagnosticErrorCode.ERROR_MISSING_BITWISE_AND_TOKEN; + case EQUAL_OR_RIGHT_ARROW, + ASSIGN_OP -> DiagnosticErrorCode.ERROR_MISSING_EQUAL_TOKEN; + case BINARY_OPERATOR, + UNARY_OPERATOR, + COMPOUND_BINARY_OPERATOR, + UNARY_EXPRESSION, + EXPRESSION_RHS, + PLUS_TOKEN -> DiagnosticErrorCode.ERROR_MISSING_BINARY_OPERATOR; + case CLOSE_BRACE -> DiagnosticErrorCode.ERROR_MISSING_CLOSE_BRACE_TOKEN; + case CLOSE_PARENTHESIS, + ARG_LIST_CLOSE_PAREN -> DiagnosticErrorCode.ERROR_MISSING_CLOSE_PAREN_TOKEN; + case COMMA, + ERROR_MESSAGE_BINDING_PATTERN_END_COMMA, + ERROR_MESSAGE_MATCH_PATTERN_END_COMMA -> DiagnosticErrorCode.ERROR_MISSING_COMMA_TOKEN; + case OPEN_BRACE -> DiagnosticErrorCode.ERROR_MISSING_OPEN_BRACE_TOKEN; + case OPEN_PARENTHESIS, + ARG_LIST_OPEN_PAREN, + PARENTHESISED_TYPE_DESC_START -> DiagnosticErrorCode.ERROR_MISSING_OPEN_PAREN_TOKEN; + case SEMICOLON, + OBJECT_FIELD_RHS -> DiagnosticErrorCode.ERROR_MISSING_SEMICOLON_TOKEN; + case ASTERISK -> DiagnosticErrorCode.ERROR_MISSING_ASTERISK_TOKEN; + case CLOSED_RECORD_BODY_END -> DiagnosticErrorCode.ERROR_MISSING_CLOSE_BRACE_PIPE_TOKEN; + case CLOSED_RECORD_BODY_START -> DiagnosticErrorCode.ERROR_MISSING_OPEN_BRACE_PIPE_TOKEN; + case ELLIPSIS -> DiagnosticErrorCode.ERROR_MISSING_ELLIPSIS_TOKEN; + case QUESTION_MARK -> DiagnosticErrorCode.ERROR_MISSING_QUESTION_MARK_TOKEN; + case CLOSE_BRACKET -> DiagnosticErrorCode.ERROR_MISSING_CLOSE_BRACKET_TOKEN; + case DOT, + METHOD_CALL_DOT -> DiagnosticErrorCode.ERROR_MISSING_DOT_TOKEN; + case OPEN_BRACKET, + TUPLE_TYPE_DESC_START -> DiagnosticErrorCode.ERROR_MISSING_OPEN_BRACKET_TOKEN; + case SLASH, + ABSOLUTE_PATH_SINGLE_SLASH, + RESOURCE_METHOD_CALL_SLASH_TOKEN -> DiagnosticErrorCode.ERROR_MISSING_SLASH_TOKEN; + case COLON, + VAR_REF_COLON, + TYPE_REF_COLON -> DiagnosticErrorCode.ERROR_MISSING_COLON_TOKEN; + case AT -> DiagnosticErrorCode.ERROR_MISSING_AT_TOKEN; + case RIGHT_ARROW -> DiagnosticErrorCode.ERROR_MISSING_RIGHT_ARROW_TOKEN; + case GT, + GT_TOKEN, + XML_START_OR_EMPTY_TAG_END, + XML_ATTRIBUTES, + INFERRED_TYPEDESC_DEFAULT_END_GT -> DiagnosticErrorCode.ERROR_MISSING_GT_TOKEN; + case LT, + LT_TOKEN, + XML_START_OR_EMPTY_TAG, + XML_END_TAG, + INFERRED_TYPEDESC_DEFAULT_START_LT, + STREAM_TYPE_PARAM_START_TOKEN -> DiagnosticErrorCode.ERROR_MISSING_LT_TOKEN; + case SYNC_SEND_TOKEN -> DiagnosticErrorCode.ERROR_MISSING_SYNC_SEND_TOKEN; + case ANNOT_CHAINING_TOKEN -> DiagnosticErrorCode.ERROR_MISSING_ANNOT_CHAINING_TOKEN; + case OPTIONAL_CHAINING_TOKEN -> DiagnosticErrorCode.ERROR_MISSING_OPTIONAL_CHAINING_TOKEN; + case DOT_LT_TOKEN -> DiagnosticErrorCode.ERROR_MISSING_DOT_LT_TOKEN; + case SLASH_LT_TOKEN -> DiagnosticErrorCode.ERROR_MISSING_SLASH_LT_TOKEN; + case DOUBLE_SLASH_DOUBLE_ASTERISK_LT_TOKEN -> + DiagnosticErrorCode.ERROR_MISSING_DOUBLE_SLASH_DOUBLE_ASTERISK_LT_TOKEN; + case SLASH_ASTERISK_TOKEN -> DiagnosticErrorCode.ERROR_MISSING_SLASH_ASTERISK_TOKEN; + case MINUS_TOKEN -> DiagnosticErrorCode.ERROR_MISSING_MINUS_TOKEN; + case LEFT_ARROW_TOKEN -> DiagnosticErrorCode.ERROR_MISSING_LEFT_ARROW_TOKEN; + case TEMPLATE_END, + TEMPLATE_START, + XML_CONTENT, + XML_TEXT -> DiagnosticErrorCode.ERROR_MISSING_BACKTICK_TOKEN; + case XML_COMMENT_START -> DiagnosticErrorCode.ERROR_MISSING_XML_COMMENT_START_TOKEN; + case XML_COMMENT_END -> DiagnosticErrorCode.ERROR_MISSING_XML_COMMENT_END_TOKEN; + case XML_PI, + XML_PI_START -> DiagnosticErrorCode.ERROR_MISSING_XML_PI_START_TOKEN; + case XML_PI_END -> DiagnosticErrorCode.ERROR_MISSING_XML_PI_END_TOKEN; + case XML_QUOTE_END, + XML_QUOTE_START -> DiagnosticErrorCode.ERROR_MISSING_DOUBLE_QUOTE_TOKEN; + case INTERPOLATION_START_TOKEN -> DiagnosticErrorCode.ERROR_MISSING_INTERPOLATION_START_TOKEN; + case EXPR_FUNC_BODY_START, + RIGHT_DOUBLE_ARROW -> DiagnosticErrorCode.ERROR_MISSING_RIGHT_DOUBLE_ARROW_TOKEN; + case XML_CDATA_END -> DiagnosticErrorCode.ERROR_MISSING_XML_CDATA_END_TOKEN; + default -> getKeywordErrorCode(ctx); + }; } private static DiagnosticCode getKeywordErrorCode(ParserRuleContext ctx) { - switch (ctx) { - case PUBLIC_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_PUBLIC_KEYWORD; - case PRIVATE_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_PRIVATE_KEYWORD; - case ABSTRACT_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_ABSTRACT_KEYWORD; - case CLIENT_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_CLIENT_KEYWORD; - case IMPORT_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_IMPORT_KEYWORD; - case FUNCTION_KEYWORD: - case FUNCTION_IDENT: - case OPTIONAL_PEER_WORKER: - case DEFAULT_WORKER_NAME_IN_ASYNC_SEND: - return DiagnosticErrorCode.ERROR_MISSING_FUNCTION_KEYWORD; - case CONST_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_CONST_KEYWORD; - case LISTENER_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_LISTENER_KEYWORD; - case SERVICE_KEYWORD: - case SERVICE_IDENT: - case SERVICE_DECL_QUALIFIER: - return DiagnosticErrorCode.ERROR_MISSING_SERVICE_KEYWORD; - case XMLNS_KEYWORD: - case XML_NAMESPACE_DECLARATION: - return DiagnosticErrorCode.ERROR_MISSING_XMLNS_KEYWORD; - case ANNOTATION_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_ANNOTATION_KEYWORD; - case TYPE_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_TYPE_KEYWORD; - case RECORD_KEYWORD: - case RECORD_FIELD: - case RECORD_IDENT: - return DiagnosticErrorCode.ERROR_MISSING_RECORD_KEYWORD; - case OBJECT_KEYWORD: - case OBJECT_IDENT: - case OBJECT_TYPE_DESCRIPTOR: - case FIRST_OBJECT_CONS_QUALIFIER: - case SECOND_OBJECT_CONS_QUALIFIER: - case FIRST_OBJECT_TYPE_QUALIFIER: - case SECOND_OBJECT_TYPE_QUALIFIER: - return DiagnosticErrorCode.ERROR_MISSING_OBJECT_KEYWORD; - case AS_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_AS_KEYWORD; - case ON_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_ON_KEYWORD; - case FINAL_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_FINAL_KEYWORD; - case SOURCE_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_SOURCE_KEYWORD; - case WORKER_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_WORKER_KEYWORD; - case FIELD_IDENT: - return DiagnosticErrorCode.ERROR_MISSING_FIELD_KEYWORD; - case RETURNS_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_RETURNS_KEYWORD; - case RETURN_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_RETURN_KEYWORD; - case EXTERNAL_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_EXTERNAL_KEYWORD; - case BOOLEAN_LITERAL: - return DiagnosticErrorCode.ERROR_MISSING_TRUE_KEYWORD; - case IF_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_IF_KEYWORD; - case ELSE_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_ELSE_KEYWORD; - case WHILE_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_WHILE_KEYWORD; - case CHECKING_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_CHECK_KEYWORD; - case PANIC_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_PANIC_KEYWORD; - case CONTINUE_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_CONTINUE_KEYWORD; - case BREAK_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_BREAK_KEYWORD; - case TYPEOF_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_TYPEOF_KEYWORD; - case IS_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_IS_KEYWORD; - case NULL_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_NULL_KEYWORD; - case LOCK_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_LOCK_KEYWORD; - case FORK_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_FORK_KEYWORD; - case TRAP_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_TRAP_KEYWORD; - case IN_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_IN_KEYWORD; - case FOREACH_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_FOREACH_KEYWORD; - case TABLE_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_TABLE_KEYWORD; - case KEY_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_KEY_KEYWORD; - case LET_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_LET_KEYWORD; - case NEW_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_NEW_KEYWORD; - case FROM_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_FROM_KEYWORD; - case WHERE_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_WHERE_KEYWORD; - case SELECT_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_SELECT_KEYWORD; - case START_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_START_KEYWORD; - case FLUSH_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_FLUSH_KEYWORD; - case WAIT_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_WAIT_KEYWORD; - case DO_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_DO_KEYWORD; - case TRANSACTION_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_TRANSACTION_KEYWORD; - case TRANSACTIONAL_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_TRANSACTIONAL_KEYWORD; - case COMMIT_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_COMMIT_KEYWORD; - case ROLLBACK_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_ROLLBACK_KEYWORD; - case RETRY_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_RETRY_KEYWORD; - case ENUM_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_ENUM_KEYWORD; - case BASE16_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_BASE16_KEYWORD; - case BASE64_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_BASE64_KEYWORD; - case MATCH_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_MATCH_KEYWORD; - case CONFLICT_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_CONFLICT_KEYWORD; - case LIMIT_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_LIMIT_KEYWORD; - case ORDER_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_ORDER_KEYWORD; - case BY_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_BY_KEYWORD; - case GROUP_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_GROUP_KEYWORD; - case ORDER_DIRECTION: - return DiagnosticErrorCode.ERROR_MISSING_ASCENDING_KEYWORD; - case JOIN_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_JOIN_KEYWORD; - case OUTER_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_OUTER_KEYWORD; - case FAIL_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_FAIL_KEYWORD; - case PIPE: - case UNION_OR_INTERSECTION_TOKEN: - return DiagnosticErrorCode.ERROR_MISSING_PIPE_TOKEN; - case EQUALS_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_EQUALS_KEYWORD; - case REMOTE_IDENT: - return DiagnosticErrorCode.ERROR_MISSING_REMOTE_KEYWORD; + return switch (ctx) { + case PUBLIC_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_PUBLIC_KEYWORD; + case PRIVATE_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_PRIVATE_KEYWORD; + case ABSTRACT_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_ABSTRACT_KEYWORD; + case CLIENT_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_CLIENT_KEYWORD; + case IMPORT_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_IMPORT_KEYWORD; + case FUNCTION_KEYWORD, + FUNCTION_IDENT, + OPTIONAL_PEER_WORKER, + DEFAULT_WORKER_NAME_IN_ASYNC_SEND -> DiagnosticErrorCode.ERROR_MISSING_FUNCTION_KEYWORD; + case CONST_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_CONST_KEYWORD; + case LISTENER_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_LISTENER_KEYWORD; + case SERVICE_KEYWORD, + SERVICE_IDENT, + SERVICE_DECL_QUALIFIER -> DiagnosticErrorCode.ERROR_MISSING_SERVICE_KEYWORD; + case XMLNS_KEYWORD, + XML_NAMESPACE_DECLARATION -> DiagnosticErrorCode.ERROR_MISSING_XMLNS_KEYWORD; + case ANNOTATION_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_ANNOTATION_KEYWORD; + case TYPE_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_TYPE_KEYWORD; + case RECORD_KEYWORD, + RECORD_FIELD, + RECORD_IDENT -> DiagnosticErrorCode.ERROR_MISSING_RECORD_KEYWORD; + case OBJECT_KEYWORD, + OBJECT_IDENT, + OBJECT_TYPE_DESCRIPTOR, + FIRST_OBJECT_CONS_QUALIFIER, + SECOND_OBJECT_CONS_QUALIFIER, + FIRST_OBJECT_TYPE_QUALIFIER, + SECOND_OBJECT_TYPE_QUALIFIER -> DiagnosticErrorCode.ERROR_MISSING_OBJECT_KEYWORD; + case AS_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_AS_KEYWORD; + case ON_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_ON_KEYWORD; + case FINAL_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_FINAL_KEYWORD; + case SOURCE_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_SOURCE_KEYWORD; + case WORKER_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_WORKER_KEYWORD; + case FIELD_IDENT -> DiagnosticErrorCode.ERROR_MISSING_FIELD_KEYWORD; + case RETURNS_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_RETURNS_KEYWORD; + case RETURN_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_RETURN_KEYWORD; + case EXTERNAL_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_EXTERNAL_KEYWORD; + case BOOLEAN_LITERAL -> DiagnosticErrorCode.ERROR_MISSING_TRUE_KEYWORD; + case IF_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_IF_KEYWORD; + case ELSE_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_ELSE_KEYWORD; + case WHILE_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_WHILE_KEYWORD; + case CHECKING_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_CHECK_KEYWORD; + case PANIC_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_PANIC_KEYWORD; + case CONTINUE_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_CONTINUE_KEYWORD; + case BREAK_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_BREAK_KEYWORD; + case TYPEOF_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_TYPEOF_KEYWORD; + case IS_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_IS_KEYWORD; + case NULL_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_NULL_KEYWORD; + case LOCK_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_LOCK_KEYWORD; + case FORK_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_FORK_KEYWORD; + case TRAP_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_TRAP_KEYWORD; + case IN_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_IN_KEYWORD; + case FOREACH_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_FOREACH_KEYWORD; + case TABLE_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_TABLE_KEYWORD; + case KEY_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_KEY_KEYWORD; + case LET_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_LET_KEYWORD; + case NEW_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_NEW_KEYWORD; + case FROM_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_FROM_KEYWORD; + case WHERE_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_WHERE_KEYWORD; + case SELECT_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_SELECT_KEYWORD; + case START_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_START_KEYWORD; + case FLUSH_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_FLUSH_KEYWORD; + case WAIT_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_WAIT_KEYWORD; + case DO_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_DO_KEYWORD; + case TRANSACTION_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_TRANSACTION_KEYWORD; + case TRANSACTIONAL_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_TRANSACTIONAL_KEYWORD; + case COMMIT_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_COMMIT_KEYWORD; + case ROLLBACK_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_ROLLBACK_KEYWORD; + case RETRY_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_RETRY_KEYWORD; + case ENUM_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_ENUM_KEYWORD; + case BASE16_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_BASE16_KEYWORD; + case BASE64_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_BASE64_KEYWORD; + case MATCH_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_MATCH_KEYWORD; + case CONFLICT_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_CONFLICT_KEYWORD; + case LIMIT_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_LIMIT_KEYWORD; + case ORDER_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_ORDER_KEYWORD; + case BY_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_BY_KEYWORD; + case GROUP_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_GROUP_KEYWORD; + case ORDER_DIRECTION -> DiagnosticErrorCode.ERROR_MISSING_ASCENDING_KEYWORD; + case JOIN_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_JOIN_KEYWORD; + case OUTER_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_OUTER_KEYWORD; + case FAIL_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_FAIL_KEYWORD; + case PIPE, + UNION_OR_INTERSECTION_TOKEN -> DiagnosticErrorCode.ERROR_MISSING_PIPE_TOKEN; + case EQUALS_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_EQUALS_KEYWORD; + case REMOTE_IDENT -> DiagnosticErrorCode.ERROR_MISSING_REMOTE_KEYWORD; // Type keywords - case STRING_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_STRING_KEYWORD; - case XML_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_XML_KEYWORD; - case RE_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_RE_KEYWORD; - case VAR_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_VAR_KEYWORD; - case MAP_KEYWORD: - case NAMED_WORKER_DECL: - case MAP_TYPE_DESCRIPTOR: - return DiagnosticErrorCode.ERROR_MISSING_MAP_KEYWORD; - case ERROR_KEYWORD: - case ERROR_BINDING_PATTERN: - case PARAMETERIZED_TYPE: - return DiagnosticErrorCode.ERROR_MISSING_ERROR_KEYWORD; - case STREAM_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_STREAM_KEYWORD; - case READONLY_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_READONLY_KEYWORD; - case DISTINCT_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_DISTINCT_KEYWORD; - case CLASS_KEYWORD: - case FIRST_CLASS_TYPE_QUALIFIER: - case SECOND_CLASS_TYPE_QUALIFIER: - case THIRD_CLASS_TYPE_QUALIFIER: - case FOURTH_CLASS_TYPE_QUALIFIER: - return DiagnosticErrorCode.ERROR_MISSING_CLASS_KEYWORD; - case COLLECT_KEYWORD: - return DiagnosticErrorCode.ERROR_MISSING_COLLECT_KEYWORD; - default: - return DiagnosticErrorCode.ERROR_SYNTAX_ERROR; - } + case STRING_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_STRING_KEYWORD; + case XML_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_XML_KEYWORD; + case RE_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_RE_KEYWORD; + case VAR_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_VAR_KEYWORD; + case MAP_KEYWORD, + NAMED_WORKER_DECL, + MAP_TYPE_DESCRIPTOR -> DiagnosticErrorCode.ERROR_MISSING_MAP_KEYWORD; + case ERROR_KEYWORD, + ERROR_BINDING_PATTERN, + PARAMETERIZED_TYPE -> DiagnosticErrorCode.ERROR_MISSING_ERROR_KEYWORD; + case STREAM_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_STREAM_KEYWORD; + case READONLY_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_READONLY_KEYWORD; + case DISTINCT_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_DISTINCT_KEYWORD; + case CLASS_KEYWORD, + FIRST_CLASS_TYPE_QUALIFIER, + SECOND_CLASS_TYPE_QUALIFIER, + THIRD_CLASS_TYPE_QUALIFIER, + FOURTH_CLASS_TYPE_QUALIFIER -> DiagnosticErrorCode.ERROR_MISSING_CLASS_KEYWORD; + case COLLECT_KEYWORD -> DiagnosticErrorCode.ERROR_MISSING_COLLECT_KEYWORD; + default -> DiagnosticErrorCode.ERROR_SYNTAX_ERROR; + }; } private static DiagnosticCode getDocWarningCode(SyntaxKind expectedKind) { - switch (expectedKind) { - case HASH_TOKEN: - return DiagnosticWarningCode.WARNING_MISSING_HASH_TOKEN; - case BACKTICK_TOKEN: - return DiagnosticWarningCode.WARNING_MISSING_SINGLE_BACKTICK_TOKEN; - case DOUBLE_BACKTICK_TOKEN: - return DiagnosticWarningCode.WARNING_MISSING_DOUBLE_BACKTICK_TOKEN; - case TRIPLE_BACKTICK_TOKEN: - return DiagnosticWarningCode.WARNING_MISSING_TRIPLE_BACKTICK_TOKEN; - case IDENTIFIER_TOKEN: - return DiagnosticWarningCode.WARNING_MISSING_IDENTIFIER_TOKEN; - case OPEN_PAREN_TOKEN: - return DiagnosticWarningCode.WARNING_MISSING_OPEN_PAREN_TOKEN; - case CLOSE_PAREN_TOKEN: - return DiagnosticWarningCode.WARNING_MISSING_CLOSE_PAREN_TOKEN; - case MINUS_TOKEN: - return DiagnosticWarningCode.WARNING_MISSING_HYPHEN_TOKEN; - case PARAMETER_NAME: - return DiagnosticWarningCode.WARNING_MISSING_PARAMETER_NAME; - case CODE_CONTENT: - return DiagnosticWarningCode.WARNING_MISSING_CODE_REFERENCE; - default: - return DiagnosticWarningCode.WARNING_SYNTAX_WARNING; - } + return switch (expectedKind) { + case HASH_TOKEN -> DiagnosticWarningCode.WARNING_MISSING_HASH_TOKEN; + case BACKTICK_TOKEN -> DiagnosticWarningCode.WARNING_MISSING_SINGLE_BACKTICK_TOKEN; + case DOUBLE_BACKTICK_TOKEN -> DiagnosticWarningCode.WARNING_MISSING_DOUBLE_BACKTICK_TOKEN; + case TRIPLE_BACKTICK_TOKEN -> DiagnosticWarningCode.WARNING_MISSING_TRIPLE_BACKTICK_TOKEN; + case IDENTIFIER_TOKEN -> DiagnosticWarningCode.WARNING_MISSING_IDENTIFIER_TOKEN; + case OPEN_PAREN_TOKEN -> DiagnosticWarningCode.WARNING_MISSING_OPEN_PAREN_TOKEN; + case CLOSE_PAREN_TOKEN -> DiagnosticWarningCode.WARNING_MISSING_CLOSE_PAREN_TOKEN; + case MINUS_TOKEN -> DiagnosticWarningCode.WARNING_MISSING_HYPHEN_TOKEN; + case PARAMETER_NAME -> DiagnosticWarningCode.WARNING_MISSING_PARAMETER_NAME; + case CODE_CONTENT -> DiagnosticWarningCode.WARNING_MISSING_CODE_REFERENCE; + default -> DiagnosticWarningCode.WARNING_SYNTAX_WARNING; + }; } private static DiagnosticCode getRegExpErrorCode(SyntaxKind expectedKind) { - switch (expectedKind) { - case CLOSE_PAREN_TOKEN: - return DiagnosticErrorCode.ERROR_MISSING_CLOSE_PAREN_TOKEN; - case CLOSE_BRACKET_TOKEN: - return DiagnosticErrorCode.ERROR_MISSING_CLOSE_BRACKET_TOKEN; - case OPEN_BRACE_TOKEN: - return DiagnosticErrorCode.ERROR_MISSING_OPEN_BRACE_TOKEN; - case CLOSE_BRACE_TOKEN: - return DiagnosticErrorCode.ERROR_MISSING_CLOSE_BRACE_TOKEN; - case COLON_TOKEN: - return DiagnosticErrorCode.ERROR_MISSING_COLON_TOKEN; - case RE_UNICODE_PROPERTY_VALUE: - return DiagnosticErrorCode.ERROR_MISSING_RE_UNICODE_PROPERTY_VALUE; - case DIGIT: - return DiagnosticErrorCode.ERROR_MISSING_RE_QUANTIFIER_DIGIT; - case BITWISE_XOR_TOKEN: - return DiagnosticErrorCode.ERROR_INVALID_RE_SYNTAX_CHAR; - case BACK_SLASH_TOKEN: - return DiagnosticErrorCode.ERROR_MISSING_BACKSLASH; - default: - return DiagnosticErrorCode.ERROR_SYNTAX_ERROR; - } + return switch (expectedKind) { + case CLOSE_PAREN_TOKEN -> DiagnosticErrorCode.ERROR_MISSING_CLOSE_PAREN_TOKEN; + case CLOSE_BRACKET_TOKEN -> DiagnosticErrorCode.ERROR_MISSING_CLOSE_BRACKET_TOKEN; + case OPEN_BRACE_TOKEN -> DiagnosticErrorCode.ERROR_MISSING_OPEN_BRACE_TOKEN; + case CLOSE_BRACE_TOKEN -> DiagnosticErrorCode.ERROR_MISSING_CLOSE_BRACE_TOKEN; + case COLON_TOKEN -> DiagnosticErrorCode.ERROR_MISSING_COLON_TOKEN; + case RE_UNICODE_PROPERTY_VALUE -> DiagnosticErrorCode.ERROR_MISSING_RE_UNICODE_PROPERTY_VALUE; + case DIGIT -> DiagnosticErrorCode.ERROR_MISSING_RE_QUANTIFIER_DIGIT; + case BITWISE_XOR_TOKEN -> DiagnosticErrorCode.ERROR_INVALID_RE_SYNTAX_CHAR; + case BACK_SLASH_TOKEN -> DiagnosticErrorCode.ERROR_MISSING_BACKSLASH; + default -> DiagnosticErrorCode.ERROR_SYNTAX_ERROR; + }; } /** diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/XMLLexer.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/XMLLexer.java index 1a15e11d5d72..cce1fffacf19 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/XMLLexer.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/XMLLexer.java @@ -45,53 +45,37 @@ public XMLLexer(CharReader charReader) { */ @Override public STToken nextToken() { - STToken token; - switch (this.mode) { - case XML_CONTENT: - token = readTokenInXMLContent(); - break; - case XML_ELEMENT_START_TAG: + STToken token = switch (this.mode) { + case XML_CONTENT -> readTokenInXMLContent(); + case XML_ELEMENT_START_TAG -> { processLeadingXMLTrivia(); - token = readTokenInXMLElement(true); - break; - case XML_ELEMENT_END_TAG: + yield readTokenInXMLElement(true); + } + case XML_ELEMENT_END_TAG -> { processLeadingXMLTrivia(); - token = readTokenInXMLElement(false); - break; - case XML_TEXT: - // XML text have no trivia. Whitespace is part of the text. - token = readTokenInXMLText(); - break; - case INTERPOLATION: - token = readTokenInInterpolation(); - break; - case XML_ATTRIBUTES: + yield readTokenInXMLElement(false); + } + // XML text have no trivia. Whitespace is part of the text. + case XML_TEXT -> readTokenInXMLText(); + case INTERPOLATION -> readTokenInInterpolation(); + case XML_ATTRIBUTES -> { processLeadingXMLTrivia(); - token = readTokenInXMLAttributes(true); - break; - case XML_COMMENT: - token = readTokenInXMLCommentOrCDATA(false); - break; - case XML_PI: + yield readTokenInXMLAttributes(true); + } + case XML_COMMENT -> readTokenInXMLCommentOrCDATA(false); + case XML_PI -> { processLeadingXMLTrivia(); - token = readTokenInXMLPI(); - break; - case XML_PI_DATA: + yield readTokenInXMLPI(); + } + case XML_PI_DATA -> { processLeadingXMLTrivia(); - token = readTokenInXMLPIData(); - break; - case XML_SINGLE_QUOTED_STRING: - token = processXMLSingleQuotedString(); - break; - case XML_DOUBLE_QUOTED_STRING: - token = processXMLDoubleQuotedString(); - break; - case XML_CDATA_SECTION: - token = readTokenInXMLCommentOrCDATA(true); - break; - default: - token = null; - } + yield readTokenInXMLPIData(); + } + case XML_SINGLE_QUOTED_STRING -> processXMLSingleQuotedString(); + case XML_DOUBLE_QUOTED_STRING -> processXMLDoubleQuotedString(); + case XML_CDATA_SECTION -> readTokenInXMLCommentOrCDATA(true); + default -> null; + }; // Can we improve this logic by creating the token with diagnostics then and there? return cloneWithDiagnostics(token); diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/XMLParser.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/XMLParser.java index 456fa126af8e..20161bb133d3 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/XMLParser.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/XMLParser.java @@ -76,17 +76,16 @@ private STNode parseXMLContent(boolean isInXMLElement) { * @return true if this is the end of the back-tick literal. false otherwise */ private boolean isEndOfXMLContent(SyntaxKind kind, boolean isInXMLElement) { - switch (kind) { - case EOF_TOKEN: - case BACKTICK_TOKEN: - return true; - case LT_TOKEN: + return switch (kind) { + case EOF_TOKEN, + BACKTICK_TOKEN -> true; + case LT_TOKEN -> { STToken nextNextToken = getNextNextToken(); - return isInXMLElement && + yield isInXMLElement && (nextNextToken.kind == SyntaxKind.SLASH_TOKEN || nextNextToken.kind == SyntaxKind.LT_TOKEN); - default: - return false; - } + } + default -> false; + }; } /** @@ -104,20 +103,14 @@ private boolean isEndOfXMLContent(SyntaxKind kind, boolean isInXMLElement) { */ private STNode parseXMLContentItem() { STToken nextToken = peek(); - switch (nextToken.kind) { - case LT_TOKEN: - return parseXMLElement(); - case XML_COMMENT_START_TOKEN: - return parseXMLComment(); - case XML_PI_START_TOKEN: - return parseXMLPI(); - case INTERPOLATION_START_TOKEN: - return parseInterpolation(); - case XML_CDATA_START_TOKEN: - return parseXMLCdataSection(); - default: - return parseXMLText(); - } + return switch (nextToken.kind) { + case LT_TOKEN -> parseXMLElement(); + case XML_COMMENT_START_TOKEN -> parseXMLComment(); + case XML_PI_START_TOKEN -> parseXMLPI(); + case INTERPOLATION_START_TOKEN -> parseInterpolation(); + case XML_CDATA_START_TOKEN -> parseXMLCdataSection(); + default -> parseXMLText(); + }; } /** @@ -338,19 +331,17 @@ protected STNode parseQualifiedIdentifier(STNode identifier) { * @return true if this is the end of the XML attributes. false otherwise */ private boolean isEndOfXMLAttributes(SyntaxKind kind) { - switch (kind) { - case EOF_TOKEN: - case BACKTICK_TOKEN: - case GT_TOKEN: - case LT_TOKEN: - case SLASH_TOKEN: - case XML_COMMENT_START_TOKEN: - case XML_PI_START_TOKEN: - case XML_CDATA_START_TOKEN: - return true; - default: - return false; - } + return switch (kind) { + case EOF_TOKEN, + BACKTICK_TOKEN, + GT_TOKEN, + LT_TOKEN, + SLASH_TOKEN, + XML_COMMENT_START_TOKEN, + XML_PI_START_TOKEN, + XML_CDATA_START_TOKEN -> true; + default -> false; + }; } /** @@ -432,18 +423,17 @@ private STNode parseStartQuote(ParserRuleContext ctx) { } private boolean isEndOfXMLAttributeValue(SyntaxKind nextTokenKind) { - switch (nextTokenKind) { - case EOF_TOKEN: - case BACKTICK_TOKEN: - case LT_TOKEN: - case GT_TOKEN: - case DOUBLE_QUOTE_TOKEN: - case SINGLE_QUOTE_TOKEN: - case IDENTIFIER_TOKEN: // Lexer will return identifier if the start quote is missing - return true; - default: - return false; - } + return switch (nextTokenKind) { + case EOF_TOKEN, + BACKTICK_TOKEN, + LT_TOKEN, + GT_TOKEN, + DOUBLE_QUOTE_TOKEN, + SINGLE_QUOTE_TOKEN, + IDENTIFIER_TOKEN -> // Lexer will return identifier if the start quote is missing + true; + default -> false; + }; } /** @@ -459,16 +449,16 @@ private boolean isEndOfXMLAttributeValue(SyntaxKind nextTokenKind) { */ private STNode parseXMLText() { STToken nextToken = peek(); - switch (nextToken.kind) { - case INTERPOLATION_START_TOKEN: - case EOF_TOKEN: - case BACKTICK_TOKEN: - case LT_TOKEN: - return null; - default: + return switch (nextToken.kind) { + case INTERPOLATION_START_TOKEN, + EOF_TOKEN, + BACKTICK_TOKEN, + LT_TOKEN -> null; + default -> { STNode content = parseCharData(); - return STNodeFactory.createXMLTextNode(content); - } + yield STNodeFactory.createXMLTextNode(content); + } + }; } /** @@ -540,16 +530,14 @@ private STNode parseXMLCommentEnd() { } private boolean isEndOfXMLComment(SyntaxKind nextTokenKind) { - switch (nextTokenKind) { - case EOF_TOKEN: - case BACKTICK_TOKEN: - case LT_TOKEN: - case GT_TOKEN: - case XML_COMMENT_END_TOKEN: - return true; - default: - return false; - } + return switch (nextTokenKind) { + case EOF_TOKEN, + BACKTICK_TOKEN, + LT_TOKEN, + GT_TOKEN, + XML_COMMENT_END_TOKEN -> true; + default -> false; + }; } /** @@ -583,14 +571,12 @@ private STNode parseXMLCdataSection() { } private boolean isEndOfXMLCdata(SyntaxKind nextTokenKind) { - switch (nextTokenKind) { - case EOF_TOKEN: - case BACKTICK_TOKEN: - case XML_CDATA_END_TOKEN: - return true; - default: - return false; - } + return switch (nextTokenKind) { + case EOF_TOKEN, + BACKTICK_TOKEN, + XML_CDATA_END_TOKEN -> true; + default -> false; + }; } /** @@ -670,16 +656,14 @@ private STNode parseXMLPIEnd() { } private boolean isEndOfXMLPI(SyntaxKind nextTokenKind) { - switch (nextTokenKind) { - case EOF_TOKEN: - case BACKTICK_TOKEN: - case LT_TOKEN: - case GT_TOKEN: - case XML_PI_END_TOKEN: - return true; - default: - return false; - } + return switch (nextTokenKind) { + case EOF_TOKEN, + BACKTICK_TOKEN, + LT_TOKEN, + GT_TOKEN, + XML_PI_END_TOKEN -> true; + default -> false; + }; } /** @@ -689,14 +673,11 @@ private boolean isEndOfXMLPI(SyntaxKind nextTokenKind) { */ private STNode parseXMLCharacterSet() { STToken nextToken = peek(); - switch (nextToken.kind) { - case XML_TEXT_CONTENT: - return consume(); - case INTERPOLATION_START_TOKEN: - return parseInterpolation(); - default: - throw new IllegalStateException(); - } + return switch (nextToken.kind) { + case XML_TEXT_CONTENT -> consume(); + case INTERPOLATION_START_TOKEN -> parseInterpolation(); + default -> throw new IllegalStateException(); + }; } private Solution recover(STToken token, ParserRuleContext currentCtx) { diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/XMLParserErrorHandler.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/XMLParserErrorHandler.java index 339bcea6d272..7115f0880ea0 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/XMLParserErrorHandler.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/XMLParserErrorHandler.java @@ -54,17 +54,15 @@ public XMLParserErrorHandler(AbstractTokenReader tokenReader) { @Override protected boolean hasAlternativePaths(ParserRuleContext currentCtx) { - switch (currentCtx) { - case XML_CONTENT: - case XML_ATTRIBUTES: - case XML_START_OR_EMPTY_TAG_END: - case XML_ATTRIBUTE_VALUE_ITEM: - case XML_PI_TARGET_RHS: - case XML_OPTIONAL_CDATA_CONTENT: - return true; - default: - return false; - } + return switch (currentCtx) { + case XML_CONTENT, + XML_ATTRIBUTES, + XML_START_OR_EMPTY_TAG_END, + XML_ATTRIBUTE_VALUE_ITEM, + XML_PI_TARGET_RHS, + XML_OPTIONAL_CDATA_CONTENT -> true; + default -> false; + }; } @Override @@ -167,29 +165,15 @@ protected Result seekMatch(ParserRuleContext currentCtx, int lookahead, int curr private Result seekMatchInAlternativePaths(ParserRuleContext currentCtx, int lookahead, int currentDepth, int matchingRulesCount, boolean isEntryPoint) { - ParserRuleContext[] alternativeRules; - switch (currentCtx) { - case XML_CONTENT: - alternativeRules = XML_CONTENT; - break; - case XML_ATTRIBUTES: - alternativeRules = XML_ATTRIBUTES; - break; - case XML_START_OR_EMPTY_TAG_END: - alternativeRules = XML_START_OR_EMPTY_TAG_END; - break; - case XML_ATTRIBUTE_VALUE_ITEM: - alternativeRules = XML_ATTRIBUTE_VALUE_ITEM; - break; - case XML_PI_TARGET_RHS: - alternativeRules = XML_PI_TARGET_RHS; - break; - case XML_OPTIONAL_CDATA_CONTENT: - alternativeRules = XML_OPTIONAL_CDATA_CONTENT; - break; - default: - throw new IllegalStateException("seekMatchInExprRelatedAlternativePaths found: " + currentCtx); - } + ParserRuleContext[] alternativeRules = switch (currentCtx) { + case XML_CONTENT -> XML_CONTENT; + case XML_ATTRIBUTES -> XML_ATTRIBUTES; + case XML_START_OR_EMPTY_TAG_END -> XML_START_OR_EMPTY_TAG_END; + case XML_ATTRIBUTE_VALUE_ITEM -> XML_ATTRIBUTE_VALUE_ITEM; + case XML_PI_TARGET_RHS -> XML_PI_TARGET_RHS; + case XML_OPTIONAL_CDATA_CONTENT -> XML_OPTIONAL_CDATA_CONTENT; + default -> throw new IllegalStateException("seekMatchInExprRelatedAlternativePaths found: " + currentCtx); + }; return seekInAlternativesPaths(lookahead, currentDepth, matchingRulesCount, alternativeRules, isEntryPoint); } @@ -213,45 +197,35 @@ protected ParserRuleContext getNextRule(ParserRuleContext currentCtx, int nextLo return ParserRuleContext.LT_TOKEN; case LT_TOKEN: ParserRuleContext parentCtx = getParentContext(); - switch (parentCtx) { - case XML_START_OR_EMPTY_TAG: - return ParserRuleContext.XML_NAME; - case XML_END_TAG: - return ParserRuleContext.SLASH; - default: - throw new IllegalStateException(" < cannot exist in: " + parentCtx); - } + return switch (parentCtx) { + case XML_START_OR_EMPTY_TAG -> ParserRuleContext.XML_NAME; + case XML_END_TAG -> ParserRuleContext.SLASH; + default -> throw new IllegalStateException(" < cannot exist in: " + parentCtx); + }; case GT_TOKEN: case XML_PI_END: endContext(); return ParserRuleContext.XML_CONTENT; case XML_NAME: parentCtx = getParentContext(); - switch (parentCtx) { - case XML_START_OR_EMPTY_TAG: - return ParserRuleContext.XML_ATTRIBUTES; - case XML_END_TAG: - return ParserRuleContext.GT_TOKEN; - case XML_ATTRIBUTES: - return ParserRuleContext.ASSIGN_OP; - case XML_PI: - return ParserRuleContext.XML_PI_TARGET_RHS; - default: - throw new IllegalStateException("XML name cannot exist in: " + parentCtx); - } + return switch (parentCtx) { + case XML_START_OR_EMPTY_TAG -> ParserRuleContext.XML_ATTRIBUTES; + case XML_END_TAG -> ParserRuleContext.GT_TOKEN; + case XML_ATTRIBUTES -> ParserRuleContext.ASSIGN_OP; + case XML_PI -> ParserRuleContext.XML_PI_TARGET_RHS; + default -> throw new IllegalStateException("XML name cannot exist in: " + parentCtx); + }; case SLASH: parentCtx = getParentContext(); - switch (parentCtx) { - case XML_ATTRIBUTES: + return switch (parentCtx) { + case XML_ATTRIBUTES -> { endContext(); - return ParserRuleContext.GT_TOKEN; - case XML_START_OR_EMPTY_TAG: - return ParserRuleContext.GT_TOKEN; - case XML_END_TAG: - return ParserRuleContext.XML_NAME; - default: - throw new IllegalStateException("slash cannot exist in: " + parentCtx); - } + yield ParserRuleContext.GT_TOKEN; + } + case XML_START_OR_EMPTY_TAG -> ParserRuleContext.GT_TOKEN; + case XML_END_TAG -> ParserRuleContext.XML_NAME; + default -> throw new IllegalStateException("slash cannot exist in: " + parentCtx); + }; case ASSIGN_OP: return ParserRuleContext.XML_QUOTE_START; case XML_ATTRIBUTE: @@ -293,47 +267,30 @@ protected Solution getInsertSolution(ParserRuleContext ctx) { @Override protected SyntaxKind getExpectedTokenKind(ParserRuleContext context) { - switch (context) { - case LT_TOKEN: - case XML_START_OR_EMPTY_TAG: - case XML_END_TAG: - return SyntaxKind.LT_TOKEN; - case GT_TOKEN: - return SyntaxKind.GT_TOKEN; - case SLASH: - return SyntaxKind.SLASH_TOKEN; - case XML_KEYWORD: - return SyntaxKind.XML_KEYWORD; - case XML_NAME: - return SyntaxKind.IDENTIFIER_TOKEN; - case ASSIGN_OP: - return SyntaxKind.EQUAL_TOKEN; - case XML_START_OR_EMPTY_TAG_END: - case XML_ATTRIBUTES: - return SyntaxKind.GT_TOKEN; - case XML_CONTENT: - case XML_TEXT: - return SyntaxKind.BACKTICK_TOKEN; - case XML_COMMENT_START: - return SyntaxKind.XML_COMMENT_START_TOKEN; - case XML_COMMENT_CONTENT: - return SyntaxKind.XML_TEXT_CONTENT; - case XML_COMMENT_END: - return SyntaxKind.XML_COMMENT_END_TOKEN; - case XML_PI: - case XML_PI_START: - return SyntaxKind.XML_PI_START_TOKEN; - case XML_PI_END: - return SyntaxKind.XML_PI_END_TOKEN; - case XML_PI_DATA: - return SyntaxKind.XML_TEXT_CONTENT; - case XML_QUOTE_END: - case XML_QUOTE_START: - return SyntaxKind.DOUBLE_QUOTE_TOKEN; - case XML_CDATA_END: - return SyntaxKind.XML_CDATA_END_TOKEN; - default: - return SyntaxKind.NONE; - } + return switch (context) { + case LT_TOKEN, + XML_START_OR_EMPTY_TAG, + XML_END_TAG -> SyntaxKind.LT_TOKEN; + case GT_TOKEN -> SyntaxKind.GT_TOKEN; + case SLASH -> SyntaxKind.SLASH_TOKEN; + case XML_KEYWORD -> SyntaxKind.XML_KEYWORD; + case XML_NAME -> SyntaxKind.IDENTIFIER_TOKEN; + case ASSIGN_OP -> SyntaxKind.EQUAL_TOKEN; + case XML_START_OR_EMPTY_TAG_END, + XML_ATTRIBUTES -> SyntaxKind.GT_TOKEN; + case XML_CONTENT, + XML_TEXT -> SyntaxKind.BACKTICK_TOKEN; + case XML_COMMENT_START -> SyntaxKind.XML_COMMENT_START_TOKEN; + case XML_COMMENT_CONTENT -> SyntaxKind.XML_TEXT_CONTENT; + case XML_COMMENT_END -> SyntaxKind.XML_COMMENT_END_TOKEN; + case XML_PI, + XML_PI_START -> SyntaxKind.XML_PI_START_TOKEN; + case XML_PI_END -> SyntaxKind.XML_PI_END_TOKEN; + case XML_PI_DATA -> SyntaxKind.XML_TEXT_CONTENT; + case XML_QUOTE_END, + XML_QUOTE_START -> SyntaxKind.DOUBLE_QUOTE_TOKEN; + case XML_CDATA_END -> SyntaxKind.XML_CDATA_END_TOKEN; + default -> SyntaxKind.NONE; + }; } } diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/XMLValidator.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/XMLValidator.java index 1b677272d2ec..08594dd9fcbf 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/XMLValidator.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/XMLValidator.java @@ -22,7 +22,7 @@ * * @since 2.0.0 */ -public class XMLValidator { +public final class XMLValidator { /* * Constants @@ -183,31 +183,31 @@ public class XMLValidator { } // remove special characters - for (int i = 0; i < specialChar.length; i++) { - CHARS[specialChar[i]] = (byte) (CHARS[specialChar[i]] & ~MASK_CONTENT); + for (int k : specialChar) { + CHARS[k] = (byte) (CHARS[k] & ~MASK_CONTENT); } // set space characters - for (int i = 0; i < spaceChar.length; i++) { - CHARS[spaceChar[i]] |= MASK_SPACE; + for (int k : spaceChar) { + CHARS[k] |= MASK_SPACE; } // set name start characters - for (int i = 0; i < nameStartChar.length; i++) { - CHARS[nameStartChar[i]] |= MASK_NAME_START | MASK_NAME | MASK_NCNAME_START | MASK_NCNAME; + for (int k : nameStartChar) { + CHARS[k] |= MASK_NAME_START | MASK_NAME | MASK_NCNAME_START | MASK_NCNAME; } for (int i = 0; i < letterRange.length; i += 2) { for (int j = letterRange[i]; j <= letterRange[i + 1]; j++) { CHARS[j] |= MASK_NAME_START | MASK_NAME | MASK_NCNAME_START | MASK_NCNAME; } } - for (int i = 0; i < letterChar.length; i++) { - CHARS[letterChar[i]] |= MASK_NAME_START | MASK_NAME | MASK_NCNAME_START | MASK_NCNAME; + for (int k : letterChar) { + CHARS[k] |= MASK_NAME_START | MASK_NAME | MASK_NCNAME_START | MASK_NCNAME; } // set name characters - for (int i = 0; i < nameChar.length; i++) { - CHARS[nameChar[i]] |= MASK_NAME | MASK_NCNAME; + for (int k : nameChar) { + CHARS[k] |= MASK_NAME | MASK_NCNAME; } for (int i = 0; i < digitRange.length; i += 2) { for (int j = digitRange[i]; j <= digitRange[i + 1]; j++) { @@ -219,24 +219,24 @@ public class XMLValidator { CHARS[j] |= MASK_NAME | MASK_NCNAME; } } - for (int i = 0; i < combiningCharChar.length; i++) { - CHARS[combiningCharChar[i]] |= MASK_NAME | MASK_NCNAME; + for (int k : combiningCharChar) { + CHARS[k] |= MASK_NAME | MASK_NCNAME; } for (int i = 0; i < extenderRange.length; i += 2) { for (int j = extenderRange[i]; j <= extenderRange[i + 1]; j++) { CHARS[j] |= MASK_NAME | MASK_NCNAME; } } - for (int i = 0; i < extenderChar.length; i++) { - CHARS[extenderChar[i]] |= MASK_NAME | MASK_NCNAME; + for (int k : extenderChar) { + CHARS[k] |= MASK_NAME | MASK_NCNAME; } // remove ':' from allowable MASK_NCNAME_START and MASK_NCNAME chars CHARS[':'] &= ~(MASK_NCNAME_START | MASK_NCNAME); // set Pubid characters - for (int i = 0; i < pubidChar.length; i++) { - CHARS[pubidChar[i]] |= MASK_PUBID; + for (int k : pubidChar) { + CHARS[k] |= MASK_PUBID; } for (int i = 0; i < pubidRange.length; i += 2) { for (int j = pubidRange[i]; j <= pubidRange[i + 1]; j++) { @@ -245,6 +245,9 @@ public class XMLValidator { } } + private XMLValidator() { + } + /* * Public Methods. */ diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/incremental/HybridNode.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/incremental/HybridNode.java index 26dfc79e1647..5c2c6d79ff1a 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/incremental/HybridNode.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/incremental/HybridNode.java @@ -20,9 +20,10 @@ import io.ballerina.compiler.internal.parser.BallerinaLexer; import io.ballerina.compiler.internal.parser.tree.STNode; import io.ballerina.compiler.internal.parser.tree.STToken; -import io.ballerina.compiler.internal.parser.utils.PersistentStack; import io.ballerina.compiler.internal.syntax.SyntaxUtils; +import java.util.Deque; + /** * Represents a {@code STNode} retrieved either from the old syntax tree or from the new text document. * @@ -94,13 +95,13 @@ static class State { int newTextOffset; BallerinaLexer lexer; NodePointer oldTreePtr; - PersistentStack textEditRanges; + Deque textEditRanges; State(int oldTextOffset, int newTextOffset, BallerinaLexer lexer, NodePointer oldTreePtr, - PersistentStack textEditRanges) { + Deque textEditRanges) { this.oldTextOffset = oldTextOffset; this.newTextOffset = newTextOffset; this.lexer = lexer; diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/incremental/HybridNodeStorage.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/incremental/HybridNodeStorage.java index 89ac1e5bce14..9cedfb5d8e5d 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/incremental/HybridNodeStorage.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/incremental/HybridNodeStorage.java @@ -19,7 +19,6 @@ import io.ballerina.compiler.internal.parser.BallerinaLexer; import io.ballerina.compiler.internal.parser.tree.STToken; -import io.ballerina.compiler.internal.parser.utils.PersistentStack; import io.ballerina.compiler.syntax.tree.ModulePartNode; import io.ballerina.compiler.syntax.tree.SyntaxTree; import io.ballerina.compiler.syntax.tree.Token; @@ -27,7 +26,9 @@ import io.ballerina.tools.text.TextEdit; import io.ballerina.tools.text.TextRange; +import java.util.ArrayDeque; import java.util.ArrayList; +import java.util.Deque; import java.util.List; /** @@ -146,18 +147,18 @@ private HybridNode createInitialNode(ModulePartNode oldTree, BallerinaLexer lexer, TextDocumentChange textDocumentChange) { NodePointer oldTreePtr = new NodePointer(oldTree); - PersistentStack textEditRanges = markAffectedRanges(oldTree, textDocumentChange); + Deque textEditRanges = markAffectedRanges(oldTree, textDocumentChange); HybridNode.State state = new HybridNode.State(0, 0, lexer, oldTreePtr.nextChild(), textEditRanges); return new HybridNode(null, state); } - private PersistentStack markAffectedRanges(ModulePartNode oldTree, + private Deque markAffectedRanges(ModulePartNode oldTree, TextDocumentChange textDocumentChange) { int textEditCount = textDocumentChange.getTextEditCount(); - PersistentStack markedTextEdits = PersistentStack.getEmpty(); + Deque markedTextEdits = new ArrayDeque<>(textEditCount); for (int index = textEditCount - 1; index >= 0; index--) { TextEdit textEdit = textDocumentChange.getTextEdit(index); - markedTextEdits = markedTextEdits.push(markAffectedRange(oldTree, textEdit)); + markedTextEdits.push(markAffectedRange(oldTree, textEdit)); } return markedTextEdits; } diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/incremental/HybridNodes.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/incremental/HybridNodes.java index e1c7015ab5ea..0c5d04909b55 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/incremental/HybridNodes.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/incremental/HybridNodes.java @@ -18,19 +18,23 @@ package io.ballerina.compiler.internal.parser.incremental; import io.ballerina.compiler.internal.parser.tree.STToken; -import io.ballerina.compiler.internal.parser.utils.PersistentStack; import io.ballerina.compiler.internal.syntax.SyntaxUtils; import io.ballerina.compiler.syntax.tree.Node; import io.ballerina.compiler.syntax.tree.Token; import io.ballerina.tools.text.TextRange; +import java.util.Deque; + /** * Contains utility methods to retrieve {@code HybridNode}s from * the old syntax tree as well from the new source code. * * @since 1.3.0 */ -class HybridNodes { +final class HybridNodes { + + private HybridNodes() { + } /** * Returns the next node based on the previous node's state and the given kind. @@ -41,14 +45,11 @@ class HybridNodes { */ static HybridNode nextNode(HybridNode prevNode, HybridNode.Kind kind) { HybridNode.State state = prevNode.state().cloneState(); - switch (kind) { - case TOKEN: - return nextToken(state); - case SUBTREE: - return nextSubtree(state); - default: - throw new UnsupportedOperationException("Unsupported HybridNode.Kind: " + kind); - } + return switch (kind) { + case TOKEN -> nextToken(state); + case SUBTREE -> nextSubtree(state); + default -> throw new UnsupportedOperationException("Unsupported HybridNode.Kind: " + kind); + }; } private static HybridNode nextSubtree(HybridNode.State state) { @@ -140,8 +141,7 @@ private static void removeInvalidTextEdits(Token oldToken, HybridNode.State stat if (nextOldTokenStartOffset < textEditRange.oldEndOffset) { return; } - - state.textEditRanges = state.textEditRanges.pop(); + state.textEditRanges.pop(); state.oldTextOffset += textEditRange.newTextLength - textEditRange.oldLength; } @@ -161,7 +161,7 @@ private static boolean isNodeReusable(Node node, HybridNode.State state) { } private static boolean noOverlapWithCurrentTextEdit(Node oldNode, - PersistentStack textEditRanges) { + Deque textEditRanges) { if (textEditRanges.isEmpty()) { return true; } diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/tree/STMissingToken.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/tree/STMissingToken.java index 82bf8ee312c4..de1a30804065 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/tree/STMissingToken.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/tree/STMissingToken.java @@ -61,12 +61,10 @@ public STToken modifyWith(STNode leadingMinutiae, STNode trailingMinutiae) { @Override public Node createFacade(int position, NonTerminalNode parent) { - switch (kind) { - case IDENTIFIER_TOKEN: - return new IdentifierToken(this, position, parent); - default: - return new Token(this, position, parent); - } + return switch (kind) { + case IDENTIFIER_TOKEN -> new IdentifierToken(this, position, parent); + default -> new Token(this, position, parent); + }; } @Override diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/tree/STNodeFlags.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/tree/STNodeFlags.java index 374382de9519..db924eafd3fc 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/tree/STNodeFlags.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/tree/STNodeFlags.java @@ -22,10 +22,14 @@ * * @since 2.0.0 */ -public class STNodeFlags { +public final class STNodeFlags { + public static final byte HAS_DIAGNOSTIC = 1 << 0x1; public static final byte IS_MISSING = 1 << 0x2; + private STNodeFlags() { + } + /** * Checks whether the given flag is set in the given flags. * @param flags the flags to check diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/tree/STTreeModifiers.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/tree/STTreeModifiers.java index c685b71d8471..7b1ead0c21d1 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/tree/STTreeModifiers.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/tree/STTreeModifiers.java @@ -22,7 +22,11 @@ * * @since 2.0.0 */ -public class STTreeModifiers { +public final class STTreeModifiers { + + private STTreeModifiers() { + } + /** * Replaces the given target node with the replacement node and return new root node. * diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/utils/ConditionalExprResolver.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/utils/ConditionalExprResolver.java index be1d55793d2c..1a80cf61210a 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/utils/ConditionalExprResolver.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/utils/ConditionalExprResolver.java @@ -32,7 +32,8 @@ * * @since 2.0.0 */ -public class ConditionalExprResolver { +public final class ConditionalExprResolver { + private static final String BOOLEAN = "boolean"; private static final String DECIMAL = "decimal"; private static final String FLOAT = "float"; @@ -78,20 +79,10 @@ public static STNode getQualifiedNameRefNode(STNode parentNode, boolean leftMost * @return true if modulePrefixIdentifier text is Valid Simple NameRef */ private static boolean isValidSimpleNameRef(STToken modulePrefixIdentifier) { - switch (modulePrefixIdentifier.text()) { - case ERROR: - case FUTURE: - case MAP: - case OBJECT: - case STREAM: - case TABLE: - case TRANSACTION: - case TYPEDESC: - case XML: - return false; - default: - return true; - } + return switch (modulePrefixIdentifier.text()) { + case ERROR, FUTURE, MAP, OBJECT, STREAM, TABLE, TRANSACTION, TYPEDESC, XML -> false; + default -> true; + }; } /** diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/utils/PersistentStack.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/utils/PersistentStack.java deleted file mode 100644 index 07a04d51b629..000000000000 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/utils/PersistentStack.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package io.ballerina.compiler.internal.parser.utils; - -/** - * A persistent/immutable stack implementation. - * - * @param The type of the element - * @since 1.3.0 - */ -public class PersistentStack { - - private static final PersistentStack EMPTY = new PersistentStack<>(null, null); - private final T head; - private final PersistentStack tail; - - private PersistentStack(T head, PersistentStack tail) { - this.head = head; - this.tail = tail; - } - - @SuppressWarnings("unchecked") - public static PersistentStack getEmpty() { - return (PersistentStack) EMPTY; - } - - public PersistentStack pop() { - return tail; - } - - public PersistentStack push(T head) { - return new PersistentStack<>(head, this); - } - - public T peek() { - return head; - } - - public boolean isEmpty() { - return this == EMPTY; - } -} diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/syntax/NodeListUtils.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/syntax/NodeListUtils.java index 6d790e560d52..b669dd1b6ead 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/syntax/NodeListUtils.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/syntax/NodeListUtils.java @@ -25,7 +25,8 @@ * * @since 2.0.0 */ -public class NodeListUtils { +public final class NodeListUtils { + private NodeListUtils() { } diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/syntax/SyntaxUtils.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/syntax/SyntaxUtils.java index 4270b4d4c2d5..ece25e17bfdb 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/syntax/SyntaxUtils.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/syntax/SyntaxUtils.java @@ -27,7 +27,8 @@ * * @since 2.0.0 */ -public class SyntaxUtils { +public final class SyntaxUtils { + private SyntaxUtils() { } diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/syntax/TreeModifiers.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/syntax/TreeModifiers.java index ab4290dda9d3..0827cb84172c 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/syntax/TreeModifiers.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/syntax/TreeModifiers.java @@ -25,7 +25,10 @@ * * @since 2.0.0 */ -public class TreeModifiers { +public final class TreeModifiers { + + private TreeModifiers() { + } /** * Replaces the given target node with the replacement node and return new root node. diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/AbstractNodeFactory.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/AbstractNodeFactory.java index fa8be955f1e1..3fe4c81fc3d0 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/AbstractNodeFactory.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/AbstractNodeFactory.java @@ -26,7 +26,6 @@ import java.util.Collection; import java.util.Collections; import java.util.Objects; -import java.util.stream.Collectors; /** * A factory for creating nodes in the syntax tree. @@ -159,7 +158,7 @@ public static MinutiaeList createMinutiaeList(Collection minutiaeNodes minutiaeNodes.stream() .map(minutiae -> Objects.requireNonNull(minutiae, "minutiae should not be null")) .map(Minutiae::internalNode) - .collect(Collectors.toList())), 0); + .toList()), 0); } public static Minutiae createCommentMinutiae(String text) { @@ -204,7 +203,7 @@ public static NodeList createNodeList(Collection nodes) { nodes.stream() .map(node -> Objects.requireNonNull(node, "node should not be null")) .map(Node::internalNode) - .collect(Collectors.toList())).createUnlinkedFacade()); + .toList()).createUnlinkedFacade()); } public static SeparatedNodeList createSeparatedNodeList(Node... nodes) { @@ -217,12 +216,12 @@ public static SeparatedNodeList createSeparatedNodeList(Node return new SeparatedNodeList<>(STNodeFactory.createNodeList(internalNodes).createUnlinkedFacade()); } - public static SeparatedNodeList createSeparatedNodeList(Collection nodes) { + public static SeparatedNodeList createSeparatedNodeList(Collection nodes) { return new SeparatedNodeList<>(STNodeFactory.createNodeList( nodes.stream() .map(node -> Objects.requireNonNull(node, "node should not be null")) .map(Node::internalNode) - .collect(Collectors.toList())).createUnlinkedFacade()); + .toList()).createUnlinkedFacade()); } protected static STNode getOptionalSTNode(Node node) { diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/MinutiaeList.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/MinutiaeList.java index de03e68723ee..a9ddad56e51c 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/MinutiaeList.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/MinutiaeList.java @@ -28,7 +28,6 @@ import java.util.Iterator; import java.util.List; import java.util.Objects; -import java.util.stream.Collectors; import static io.ballerina.compiler.internal.syntax.NodeListUtils.rangeCheck; import static io.ballerina.compiler.internal.syntax.NodeListUtils.rangeCheckForAdd; @@ -87,7 +86,7 @@ public MinutiaeList addAll(Collection c) { List stNodesToBeAdded = c.stream() .map(minutiae -> Objects.requireNonNull(minutiae, "minutiae should not be null")) .map(Minutiae::internalNode) - .collect(Collectors.toList()); + .toList(); return new MinutiaeList(token, internalListNode.addAll(stNodesToBeAdded), position); @@ -161,7 +160,7 @@ public Minutiae next() { }; } - protected STNode internalNode() { + STNode internalNode() { return internalListNode; } diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/NodeList.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/NodeList.java index 0ed45bc3a307..d11de17d2817 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/NodeList.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/NodeList.java @@ -26,7 +26,6 @@ import java.util.Iterator; import java.util.List; import java.util.Objects; -import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; @@ -85,7 +84,7 @@ public NodeList addAll(Collection c) { List stNodesToBeAdded = c.stream() .map(node -> Objects.requireNonNull(node, "node should not be null")) .map(Node::internalNode) - .collect(Collectors.toList()); + .toList(); return new NodeList<>(internalListNode.addAll(stNodesToBeAdded).createUnlinkedFacade()); } diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/NodeParser.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/NodeParser.java index 501274c63cef..49ce67c451e7 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/NodeParser.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/NodeParser.java @@ -25,7 +25,10 @@ * * @since 1.3.0 */ -public class NodeParser { +public final class NodeParser { + + private NodeParser() { + } /** * Parses the input as an action or expression. diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/NonTerminalNode.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/NonTerminalNode.java index f735188fdc74..c7006d8a0cbd 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/NonTerminalNode.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/NonTerminalNode.java @@ -29,7 +29,6 @@ import java.util.Collections; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; import java.util.stream.IntStream; import static io.ballerina.compiler.internal.syntax.SyntaxUtils.isSTNodePresent; @@ -71,7 +70,7 @@ public Collection childEntries() { IntStream.range(0, bucketCount()) .filter(bucket -> childInBucket(bucket) != null) .mapToObj(bucket -> new ChildNodeEntry(childNames[bucket], childInBucket(bucket))) - .collect(Collectors.toList())); + .toList()); } @Override @@ -92,8 +91,7 @@ public Token findToken(int position) { // If that is the case, return the eof token. // Fixes 24905 if (textRangeWithMinutiae.endOffset() == position && - this instanceof ModulePartNode) { - ModulePartNode modulePartNode = (ModulePartNode) this; + this instanceof ModulePartNode modulePartNode) { return modulePartNode.eofToken(); } diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/SyntaxInfo.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/SyntaxInfo.java index 3fd48abc5f57..17c351c6560a 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/SyntaxInfo.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/SyntaxInfo.java @@ -22,19 +22,21 @@ import java.util.Arrays; import java.util.List; -import java.util.stream.Collectors; /** * A class that provides syntax related information. * * @since 2.0.0 */ -public class SyntaxInfo { +public final class SyntaxInfo { private static final List BALLERINA_KEYWORDS = Arrays.stream(SyntaxKind.values()) .filter(syntaxKind -> SyntaxKind.RE_KEYWORD.compareTo(syntaxKind) > 0) .map(SyntaxKind::stringValue) - .collect(Collectors.toList()); + .toList(); + + private SyntaxInfo() { + } /** * Gives a list of all keywords in the ballerina. diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/TreeModifier.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/TreeModifier.java index 865d3bdb6aea..4f03d221538e 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/TreeModifier.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/TreeModifier.java @@ -20,6 +20,7 @@ import io.ballerina.compiler.internal.parser.tree.STNode; import io.ballerina.compiler.internal.parser.tree.STNodeFactory; +import java.util.Arrays; import java.util.function.Function; /** @@ -3724,7 +3725,7 @@ protected NodeList modifyNodeList(NodeList nodeList) { } protected SeparatedNodeList modifySeparatedNodeList(SeparatedNodeList nodeList) { - Function nodeListCreator = SeparatedNodeList::new; + Function> nodeListCreator = SeparatedNodeList::new; if (nodeList.isEmpty()) { return nodeList; } @@ -3758,7 +3759,7 @@ protected SeparatedNodeList modifySeparatedNodeList(Separate return nodeList; } - STNode stNodeList = STNodeFactory.createNodeList(java.util.Arrays.asList(newSTNodes)); + STNode stNodeList = STNodeFactory.createNodeList(Arrays.asList(newSTNodes)); return nodeListCreator.apply(stNodeList.createUnlinkedFacade()); } @@ -3784,7 +3785,7 @@ private > N modifyGenericNodeList( return nodeList; } - STNode stNodeList = STNodeFactory.createNodeList(java.util.Arrays.asList(newSTNodes)); + STNode stNodeList = STNodeFactory.createNodeList(Arrays.asList(newSTNodes)); return nodeListCreator.apply(stNodeList.createUnlinkedFacade()); } diff --git a/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/ParserTestConstants.java b/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/ParserTestConstants.java index 53bec68b53bd..fb62f7c119e9 100644 --- a/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/ParserTestConstants.java +++ b/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/ParserTestConstants.java @@ -22,7 +22,7 @@ * * @since 1.2.0 */ -public class ParserTestConstants { +public final class ParserTestConstants { public static final String KIND_FIELD = "kind"; @@ -39,4 +39,6 @@ public class ParserTestConstants { public static final String TRAILING_MINUTIAE = "trailingMinutiae"; + private ParserTestConstants() { + } } diff --git a/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/ParserTestUtils.java b/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/ParserTestUtils.java index 6dc3df46bfd5..6a6ee2be437f 100644 --- a/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/ParserTestUtils.java +++ b/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/ParserTestUtils.java @@ -64,7 +64,7 @@ * * @since 1.2.0 */ -public class ParserTestUtils { +public final class ParserTestUtils { private static final Path RESOURCE_DIRECTORY = Paths.get("src/test/resources/"); @@ -74,6 +74,9 @@ public class ParserTestUtils { */ private static final boolean UPDATE_ASSERTS = false; + private ParserTestUtils() { + } + /** * Test parsing a valid source. * @@ -333,15 +336,10 @@ public static boolean isKeyword(SyntaxKind syntaxKind) { } public static boolean isTrivia(SyntaxKind syntaxKind) { - switch (syntaxKind) { - case WHITESPACE_MINUTIAE: - case END_OF_LINE_MINUTIAE: - case COMMENT_MINUTIAE: - case INVALID_NODE_MINUTIAE: - return true; - default: - return false; - } + return switch (syntaxKind) { + case WHITESPACE_MINUTIAE, END_OF_LINE_MINUTIAE, COMMENT_MINUTIAE, INVALID_NODE_MINUTIAE -> true; + default -> false; + }; } public static String getTokenText(STToken token) { @@ -432,1048 +430,560 @@ private static void updateAssertFile(String jsonString, Path assertFilePath) { } private static SyntaxKind getNodeKind(String kind) { - switch (kind) { - case "MODULE_PART": - return SyntaxKind.MODULE_PART; - case "TYPE_DEFINITION": - return SyntaxKind.TYPE_DEFINITION; - case "FUNCTION_DEFINITION": - return SyntaxKind.FUNCTION_DEFINITION; - case "IMPORT_DECLARATION": - return SyntaxKind.IMPORT_DECLARATION; - case "SERVICE_DECLARATION": - return SyntaxKind.SERVICE_DECLARATION; - case "LISTENER_DECLARATION": - return SyntaxKind.LISTENER_DECLARATION; - case "CONST_DECLARATION": - return SyntaxKind.CONST_DECLARATION; - case "MODULE_VAR_DECL": - return SyntaxKind.MODULE_VAR_DECL; - case "XML_NAMESPACE_DECLARATION": - return SyntaxKind.XML_NAMESPACE_DECLARATION; - case "MODULE_XML_NAMESPACE_DECLARATION": - return SyntaxKind.MODULE_XML_NAMESPACE_DECLARATION; - case "ANNOTATION_DECLARATION": - return SyntaxKind.ANNOTATION_DECLARATION; - case "ENUM_DECLARATION": - return SyntaxKind.ENUM_DECLARATION; - case "CLASS_DEFINITION": - return SyntaxKind.CLASS_DEFINITION; + return switch (kind) { + case "MODULE_PART" -> SyntaxKind.MODULE_PART; + case "TYPE_DEFINITION" -> SyntaxKind.TYPE_DEFINITION; + case "FUNCTION_DEFINITION" -> SyntaxKind.FUNCTION_DEFINITION; + case "IMPORT_DECLARATION" -> SyntaxKind.IMPORT_DECLARATION; + case "SERVICE_DECLARATION" -> SyntaxKind.SERVICE_DECLARATION; + case "LISTENER_DECLARATION" -> SyntaxKind.LISTENER_DECLARATION; + case "CONST_DECLARATION" -> SyntaxKind.CONST_DECLARATION; + case "MODULE_VAR_DECL" -> SyntaxKind.MODULE_VAR_DECL; + case "XML_NAMESPACE_DECLARATION" -> SyntaxKind.XML_NAMESPACE_DECLARATION; + case "MODULE_XML_NAMESPACE_DECLARATION" -> SyntaxKind.MODULE_XML_NAMESPACE_DECLARATION; + case "ANNOTATION_DECLARATION" -> SyntaxKind.ANNOTATION_DECLARATION; + case "ENUM_DECLARATION" -> SyntaxKind.ENUM_DECLARATION; + case "CLASS_DEFINITION" -> SyntaxKind.CLASS_DEFINITION; // Others - case "FUNCTION_BODY_BLOCK": - return SyntaxKind.FUNCTION_BODY_BLOCK; - case "LIST": - return SyntaxKind.LIST; - case "RETURN_TYPE_DESCRIPTOR": - return SyntaxKind.RETURN_TYPE_DESCRIPTOR; - case "EXTERNAL_FUNCTION_BODY": - return SyntaxKind.EXTERNAL_FUNCTION_BODY; - case "REQUIRED_PARAM": - return SyntaxKind.REQUIRED_PARAM; - case "INCLUDED_RECORD_PARAM": - return SyntaxKind.INCLUDED_RECORD_PARAM; - case "DEFAULTABLE_PARAM": - return SyntaxKind.DEFAULTABLE_PARAM; - case "REST_PARAM": - return SyntaxKind.REST_PARAM; - case "RECORD_FIELD": - return SyntaxKind.RECORD_FIELD; - case "RECORD_FIELD_WITH_DEFAULT_VALUE": - return SyntaxKind.RECORD_FIELD_WITH_DEFAULT_VALUE; - case "TYPE_REFERENCE": - return SyntaxKind.TYPE_REFERENCE; - case "RECORD_REST_TYPE": - return SyntaxKind.RECORD_REST_TYPE; - case "OBJECT_FIELD": - return SyntaxKind.OBJECT_FIELD; - case "IMPORT_ORG_NAME": - return SyntaxKind.IMPORT_ORG_NAME; - case "MODULE_NAME": - return SyntaxKind.MODULE_NAME; - case "SUB_MODULE_NAME": - return SyntaxKind.SUB_MODULE_NAME; - case "IMPORT_VERSION": - return SyntaxKind.IMPORT_VERSION; - case "IMPORT_PREFIX": - return SyntaxKind.IMPORT_PREFIX; - case "SPECIFIC_FIELD": - return SyntaxKind.SPECIFIC_FIELD; - case "COMPUTED_NAME_FIELD": - return SyntaxKind.COMPUTED_NAME_FIELD; - case "SPREAD_FIELD": - return SyntaxKind.SPREAD_FIELD; - case "ARRAY_DIMENSION": - return SyntaxKind.ARRAY_DIMENSION; - case "METADATA": - return SyntaxKind.METADATA; - case "ANNOTATION": - return SyntaxKind.ANNOTATION; - case "ANNOTATION_ATTACH_POINT": - return SyntaxKind.ANNOTATION_ATTACH_POINT; - case "NAMED_WORKER_DECLARATION": - return SyntaxKind.NAMED_WORKER_DECLARATION; - case "NAMED_WORKER_DECLARATOR": - return SyntaxKind.NAMED_WORKER_DECLARATOR; - case "TYPE_CAST_PARAM": - return SyntaxKind.TYPE_CAST_PARAM; - case "KEY_SPECIFIER": - return SyntaxKind.KEY_SPECIFIER; - case "LET_VAR_DECL": - return SyntaxKind.LET_VAR_DECL; - case "ORDER_KEY": - return SyntaxKind.ORDER_KEY; - case "GROUPING_KEY_VAR_DECLARATION": - return SyntaxKind.GROUPING_KEY_VAR_DECLARATION; - case "GROUPING_KEY_VAR_NAME": - return SyntaxKind.GROUPING_KEY_VAR_NAME; - case "STREAM_TYPE_PARAMS": - return SyntaxKind.STREAM_TYPE_PARAMS; - case "FUNCTION_SIGNATURE": - return SyntaxKind.FUNCTION_SIGNATURE; - case "QUERY_CONSTRUCT_TYPE": - return SyntaxKind.QUERY_CONSTRUCT_TYPE; - case "FROM_CLAUSE": - return SyntaxKind.FROM_CLAUSE; - case "WHERE_CLAUSE": - return SyntaxKind.WHERE_CLAUSE; - case "LET_CLAUSE": - return SyntaxKind.LET_CLAUSE; - case "ON_FAIL_CLAUSE": - return SyntaxKind.ON_FAIL_CLAUSE; - case "QUERY_PIPELINE": - return SyntaxKind.QUERY_PIPELINE; - case "SELECT_CLAUSE": - return SyntaxKind.SELECT_CLAUSE; - case "COLLECT_CLAUSE": - return SyntaxKind.COLLECT_CLAUSE; - case "ORDER_BY_CLAUSE": - return SyntaxKind.ORDER_BY_CLAUSE; - case "GROUP_BY_CLAUSE": - return SyntaxKind.GROUP_BY_CLAUSE; - case "PARENTHESIZED_ARG_LIST": - return SyntaxKind.PARENTHESIZED_ARG_LIST; - case "EXPRESSION_FUNCTION_BODY": - return SyntaxKind.EXPRESSION_FUNCTION_BODY; - case "INFER_PARAM_LIST": - return SyntaxKind.INFER_PARAM_LIST; - case "METHOD_DECLARATION": - return SyntaxKind.METHOD_DECLARATION; - case "TYPED_BINDING_PATTERN": - return SyntaxKind.TYPED_BINDING_PATTERN; - case "BINDING_PATTERN": - return SyntaxKind.BINDING_PATTERN; - case "CAPTURE_BINDING_PATTERN": - return SyntaxKind.CAPTURE_BINDING_PATTERN; - case "LIST_BINDING_PATTERN": - return SyntaxKind.LIST_BINDING_PATTERN; - case "REST_BINDING_PATTERN": - return SyntaxKind.REST_BINDING_PATTERN; - case "FIELD_BINDING_PATTERN": - return SyntaxKind.FIELD_BINDING_PATTERN; - case "MAPPING_BINDING_PATTERN": - return SyntaxKind.MAPPING_BINDING_PATTERN; - case "ERROR_BINDING_PATTERN": - return SyntaxKind.ERROR_BINDING_PATTERN; - case "NAMED_ARG_BINDING_PATTERN": - return SyntaxKind.NAMED_ARG_BINDING_PATTERN; - case "TYPE_PARAMETER": - return SyntaxKind.TYPE_PARAMETER; - case "KEY_TYPE_CONSTRAINT": - return SyntaxKind.KEY_TYPE_CONSTRAINT; - case "RECEIVE_FIELDS": - return SyntaxKind.RECEIVE_FIELDS; - case "REST_TYPE": - return SyntaxKind.REST_TYPE; - case "WAIT_FIELDS_LIST": - return SyntaxKind.WAIT_FIELDS_LIST; - case "WAIT_FIELD": - return SyntaxKind.WAIT_FIELD; - case "ENUM_MEMBER": - return SyntaxKind.ENUM_MEMBER; - case "WILDCARD_BINDING_PATTERN": - return SyntaxKind.WILDCARD_BINDING_PATTERN; - case "MATCH_CLAUSE": - return SyntaxKind.MATCH_CLAUSE; - case "MATCH_GUARD": - return SyntaxKind.MATCH_GUARD; - case "OBJECT_METHOD_DEFINITION": - return SyntaxKind.OBJECT_METHOD_DEFINITION; - case "LIST_MATCH_PATTERN": - return SyntaxKind.LIST_MATCH_PATTERN; - case "REST_MATCH_PATTERN": - return SyntaxKind.REST_MATCH_PATTERN; - case "MAPPING_MATCH_PATTERN": - return SyntaxKind.MAPPING_MATCH_PATTERN; - case "FIELD_MATCH_PATTERN": - return SyntaxKind.FIELD_MATCH_PATTERN; - case "ERROR_MATCH_PATTERN": - return SyntaxKind.ERROR_MATCH_PATTERN; - case "NAMED_ARG_MATCH_PATTERN": - return SyntaxKind.NAMED_ARG_MATCH_PATTERN; - case "ON_CONFLICT_CLAUSE": - return SyntaxKind.ON_CONFLICT_CLAUSE; - case "LIMIT_CLAUSE": - return SyntaxKind.LIMIT_CLAUSE; - case "JOIN_CLAUSE": - return SyntaxKind.JOIN_CLAUSE; - case "ON_CLAUSE": - return SyntaxKind.ON_CLAUSE; - case "RESOURCE_ACCESSOR_DEFINITION": - return SyntaxKind.RESOURCE_ACCESSOR_DEFINITION; - case "RESOURCE_ACCESSOR_DECLARATION": - return SyntaxKind.RESOURCE_ACCESSOR_DECLARATION; - case "RESOURCE_PATH_SEGMENT_PARAM": - return SyntaxKind.RESOURCE_PATH_SEGMENT_PARAM; - case "RESOURCE_PATH_REST_PARAM": - return SyntaxKind.RESOURCE_PATH_REST_PARAM; - case "CLIENT_RESOURCE_ACCESS_ACTION": - return SyntaxKind.CLIENT_RESOURCE_ACCESS_ACTION; - case "COMPUTED_RESOURCE_ACCESS_SEGMENT": - return SyntaxKind.COMPUTED_RESOURCE_ACCESS_SEGMENT; - case "RESOURCE_ACCESS_REST_SEGMENT": - return SyntaxKind.RESOURCE_ACCESS_REST_SEGMENT; - case "ALTERNATE_RECEIVE": - return SyntaxKind.ALTERNATE_RECEIVE; - case "RECEIVE_FIELD": - return SyntaxKind.RECEIVE_FIELD; + case "FUNCTION_BODY_BLOCK" -> SyntaxKind.FUNCTION_BODY_BLOCK; + case "LIST" -> SyntaxKind.LIST; + case "RETURN_TYPE_DESCRIPTOR" -> SyntaxKind.RETURN_TYPE_DESCRIPTOR; + case "EXTERNAL_FUNCTION_BODY" -> SyntaxKind.EXTERNAL_FUNCTION_BODY; + case "REQUIRED_PARAM" -> SyntaxKind.REQUIRED_PARAM; + case "INCLUDED_RECORD_PARAM" -> SyntaxKind.INCLUDED_RECORD_PARAM; + case "DEFAULTABLE_PARAM" -> SyntaxKind.DEFAULTABLE_PARAM; + case "REST_PARAM" -> SyntaxKind.REST_PARAM; + case "RECORD_FIELD" -> SyntaxKind.RECORD_FIELD; + case "RECORD_FIELD_WITH_DEFAULT_VALUE" -> SyntaxKind.RECORD_FIELD_WITH_DEFAULT_VALUE; + case "TYPE_REFERENCE" -> SyntaxKind.TYPE_REFERENCE; + case "RECORD_REST_TYPE" -> SyntaxKind.RECORD_REST_TYPE; + case "OBJECT_FIELD" -> SyntaxKind.OBJECT_FIELD; + case "IMPORT_ORG_NAME" -> SyntaxKind.IMPORT_ORG_NAME; + case "MODULE_NAME" -> SyntaxKind.MODULE_NAME; + case "SUB_MODULE_NAME" -> SyntaxKind.SUB_MODULE_NAME; + case "IMPORT_VERSION" -> SyntaxKind.IMPORT_VERSION; + case "IMPORT_PREFIX" -> SyntaxKind.IMPORT_PREFIX; + case "SPECIFIC_FIELD" -> SyntaxKind.SPECIFIC_FIELD; + case "COMPUTED_NAME_FIELD" -> SyntaxKind.COMPUTED_NAME_FIELD; + case "SPREAD_FIELD" -> SyntaxKind.SPREAD_FIELD; + case "ARRAY_DIMENSION" -> SyntaxKind.ARRAY_DIMENSION; + case "METADATA" -> SyntaxKind.METADATA; + case "ANNOTATION" -> SyntaxKind.ANNOTATION; + case "ANNOTATION_ATTACH_POINT" -> SyntaxKind.ANNOTATION_ATTACH_POINT; + case "NAMED_WORKER_DECLARATION" -> SyntaxKind.NAMED_WORKER_DECLARATION; + case "NAMED_WORKER_DECLARATOR" -> SyntaxKind.NAMED_WORKER_DECLARATOR; + case "TYPE_CAST_PARAM" -> SyntaxKind.TYPE_CAST_PARAM; + case "KEY_SPECIFIER" -> SyntaxKind.KEY_SPECIFIER; + case "LET_VAR_DECL" -> SyntaxKind.LET_VAR_DECL; + case "ORDER_KEY" -> SyntaxKind.ORDER_KEY; + case "GROUPING_KEY_VAR_DECLARATION" -> SyntaxKind.GROUPING_KEY_VAR_DECLARATION; + case "GROUPING_KEY_VAR_NAME" -> SyntaxKind.GROUPING_KEY_VAR_NAME; + case "STREAM_TYPE_PARAMS" -> SyntaxKind.STREAM_TYPE_PARAMS; + case "FUNCTION_SIGNATURE" -> SyntaxKind.FUNCTION_SIGNATURE; + case "QUERY_CONSTRUCT_TYPE" -> SyntaxKind.QUERY_CONSTRUCT_TYPE; + case "FROM_CLAUSE" -> SyntaxKind.FROM_CLAUSE; + case "WHERE_CLAUSE" -> SyntaxKind.WHERE_CLAUSE; + case "LET_CLAUSE" -> SyntaxKind.LET_CLAUSE; + case "ON_FAIL_CLAUSE" -> SyntaxKind.ON_FAIL_CLAUSE; + case "QUERY_PIPELINE" -> SyntaxKind.QUERY_PIPELINE; + case "SELECT_CLAUSE" -> SyntaxKind.SELECT_CLAUSE; + case "COLLECT_CLAUSE" -> SyntaxKind.COLLECT_CLAUSE; + case "ORDER_BY_CLAUSE" -> SyntaxKind.ORDER_BY_CLAUSE; + case "GROUP_BY_CLAUSE" -> SyntaxKind.GROUP_BY_CLAUSE; + case "PARENTHESIZED_ARG_LIST" -> SyntaxKind.PARENTHESIZED_ARG_LIST; + case "EXPRESSION_FUNCTION_BODY" -> SyntaxKind.EXPRESSION_FUNCTION_BODY; + case "INFER_PARAM_LIST" -> SyntaxKind.INFER_PARAM_LIST; + case "METHOD_DECLARATION" -> SyntaxKind.METHOD_DECLARATION; + case "TYPED_BINDING_PATTERN" -> SyntaxKind.TYPED_BINDING_PATTERN; + case "BINDING_PATTERN" -> SyntaxKind.BINDING_PATTERN; + case "CAPTURE_BINDING_PATTERN" -> SyntaxKind.CAPTURE_BINDING_PATTERN; + case "LIST_BINDING_PATTERN" -> SyntaxKind.LIST_BINDING_PATTERN; + case "REST_BINDING_PATTERN" -> SyntaxKind.REST_BINDING_PATTERN; + case "FIELD_BINDING_PATTERN" -> SyntaxKind.FIELD_BINDING_PATTERN; + case "MAPPING_BINDING_PATTERN" -> SyntaxKind.MAPPING_BINDING_PATTERN; + case "ERROR_BINDING_PATTERN" -> SyntaxKind.ERROR_BINDING_PATTERN; + case "NAMED_ARG_BINDING_PATTERN" -> SyntaxKind.NAMED_ARG_BINDING_PATTERN; + case "TYPE_PARAMETER" -> SyntaxKind.TYPE_PARAMETER; + case "KEY_TYPE_CONSTRAINT" -> SyntaxKind.KEY_TYPE_CONSTRAINT; + case "RECEIVE_FIELDS" -> SyntaxKind.RECEIVE_FIELDS; + case "REST_TYPE" -> SyntaxKind.REST_TYPE; + case "WAIT_FIELDS_LIST" -> SyntaxKind.WAIT_FIELDS_LIST; + case "WAIT_FIELD" -> SyntaxKind.WAIT_FIELD; + case "ENUM_MEMBER" -> SyntaxKind.ENUM_MEMBER; + case "WILDCARD_BINDING_PATTERN" -> SyntaxKind.WILDCARD_BINDING_PATTERN; + case "MATCH_CLAUSE" -> SyntaxKind.MATCH_CLAUSE; + case "MATCH_GUARD" -> SyntaxKind.MATCH_GUARD; + case "OBJECT_METHOD_DEFINITION" -> SyntaxKind.OBJECT_METHOD_DEFINITION; + case "LIST_MATCH_PATTERN" -> SyntaxKind.LIST_MATCH_PATTERN; + case "REST_MATCH_PATTERN" -> SyntaxKind.REST_MATCH_PATTERN; + case "MAPPING_MATCH_PATTERN" -> SyntaxKind.MAPPING_MATCH_PATTERN; + case "FIELD_MATCH_PATTERN" -> SyntaxKind.FIELD_MATCH_PATTERN; + case "ERROR_MATCH_PATTERN" -> SyntaxKind.ERROR_MATCH_PATTERN; + case "NAMED_ARG_MATCH_PATTERN" -> SyntaxKind.NAMED_ARG_MATCH_PATTERN; + case "ON_CONFLICT_CLAUSE" -> SyntaxKind.ON_CONFLICT_CLAUSE; + case "LIMIT_CLAUSE" -> SyntaxKind.LIMIT_CLAUSE; + case "JOIN_CLAUSE" -> SyntaxKind.JOIN_CLAUSE; + case "ON_CLAUSE" -> SyntaxKind.ON_CLAUSE; + case "RESOURCE_ACCESSOR_DEFINITION" -> SyntaxKind.RESOURCE_ACCESSOR_DEFINITION; + case "RESOURCE_ACCESSOR_DECLARATION" -> SyntaxKind.RESOURCE_ACCESSOR_DECLARATION; + case "RESOURCE_PATH_SEGMENT_PARAM" -> SyntaxKind.RESOURCE_PATH_SEGMENT_PARAM; + case "RESOURCE_PATH_REST_PARAM" -> SyntaxKind.RESOURCE_PATH_REST_PARAM; + case "CLIENT_RESOURCE_ACCESS_ACTION" -> SyntaxKind.CLIENT_RESOURCE_ACCESS_ACTION; + case "COMPUTED_RESOURCE_ACCESS_SEGMENT" -> SyntaxKind.COMPUTED_RESOURCE_ACCESS_SEGMENT; + case "RESOURCE_ACCESS_REST_SEGMENT" -> SyntaxKind.RESOURCE_ACCESS_REST_SEGMENT; + case "ALTERNATE_RECEIVE" -> SyntaxKind.ALTERNATE_RECEIVE; + case "RECEIVE_FIELD" -> SyntaxKind.RECEIVE_FIELD; // Trivia - case "EOF_TOKEN": - return SyntaxKind.EOF_TOKEN; - case "END_OF_LINE_MINUTIAE": - return SyntaxKind.END_OF_LINE_MINUTIAE; - case "WHITESPACE_MINUTIAE": - return SyntaxKind.WHITESPACE_MINUTIAE; - case "COMMENT_MINUTIAE": - return SyntaxKind.COMMENT_MINUTIAE; - case "INVALID_NODE_MINUTIAE": - return SyntaxKind.INVALID_NODE_MINUTIAE; + case "EOF_TOKEN" -> SyntaxKind.EOF_TOKEN; + case "END_OF_LINE_MINUTIAE" -> SyntaxKind.END_OF_LINE_MINUTIAE; + case "WHITESPACE_MINUTIAE" -> SyntaxKind.WHITESPACE_MINUTIAE; + case "COMMENT_MINUTIAE" -> SyntaxKind.COMMENT_MINUTIAE; + case "INVALID_NODE_MINUTIAE" -> SyntaxKind.INVALID_NODE_MINUTIAE; // Invalid Token - case "INVALID_TOKEN": - return SyntaxKind.INVALID_TOKEN; - case "INVALID_TOKEN_MINUTIAE_NODE": - return SyntaxKind.INVALID_TOKEN_MINUTIAE_NODE; - - default: - return getStatementKind(kind); - } + case "INVALID_TOKEN" -> SyntaxKind.INVALID_TOKEN; + case "INVALID_TOKEN_MINUTIAE_NODE" -> SyntaxKind.INVALID_TOKEN_MINUTIAE_NODE; + default -> getStatementKind(kind); + }; } private static SyntaxKind getStatementKind(String kind) { - switch (kind) { - case "BLOCK_STATEMENT": - return SyntaxKind.BLOCK_STATEMENT; - case "LOCAL_VAR_DECL": - return SyntaxKind.LOCAL_VAR_DECL; - case "ASSIGNMENT_STATEMENT": - return SyntaxKind.ASSIGNMENT_STATEMENT; - case "IF_ELSE_STATEMENT": - return SyntaxKind.IF_ELSE_STATEMENT; - case "ELSE_BLOCK": - return SyntaxKind.ELSE_BLOCK; - case "WHILE_STATEMENT": - return SyntaxKind.WHILE_STATEMENT; - case "DO_STATEMENT": - return SyntaxKind.DO_STATEMENT; - case "CALL_STATEMENT": - return SyntaxKind.CALL_STATEMENT; - case "PANIC_STATEMENT": - return SyntaxKind.PANIC_STATEMENT; - case "CONTINUE_STATEMENT": - return SyntaxKind.CONTINUE_STATEMENT; - case "BREAK_STATEMENT": - return SyntaxKind.BREAK_STATEMENT; - case "FAIL_STATEMENT": - return SyntaxKind.FAIL_STATEMENT; - case "RETURN_STATEMENT": - return SyntaxKind.RETURN_STATEMENT; - case "COMPOUND_ASSIGNMENT_STATEMENT": - return SyntaxKind.COMPOUND_ASSIGNMENT_STATEMENT; - case "LOCAL_TYPE_DEFINITION_STATEMENT": - return SyntaxKind.LOCAL_TYPE_DEFINITION_STATEMENT; - case "ACTION_STATEMENT": - return SyntaxKind.ACTION_STATEMENT; - case "LOCK_STATEMENT": - return SyntaxKind.LOCK_STATEMENT; - case "FORK_STATEMENT": - return SyntaxKind.FORK_STATEMENT; - case "FOREACH_STATEMENT": - return SyntaxKind.FOREACH_STATEMENT; - case "TRANSACTION_STATEMENT": - return SyntaxKind.TRANSACTION_STATEMENT; - case "RETRY_STATEMENT": - return SyntaxKind.RETRY_STATEMENT; - case "ROLLBACK_STATEMENT": - return SyntaxKind.ROLLBACK_STATEMENT; - case "MATCH_STATEMENT": - return SyntaxKind.MATCH_STATEMENT; - case "INVALID_EXPRESSION_STATEMENT": - return SyntaxKind.INVALID_EXPRESSION_STATEMENT; - default: - return getExpressionKind(kind); - } + return switch (kind) { + case "BLOCK_STATEMENT" -> SyntaxKind.BLOCK_STATEMENT; + case "LOCAL_VAR_DECL" -> SyntaxKind.LOCAL_VAR_DECL; + case "ASSIGNMENT_STATEMENT" -> SyntaxKind.ASSIGNMENT_STATEMENT; + case "IF_ELSE_STATEMENT" -> SyntaxKind.IF_ELSE_STATEMENT; + case "ELSE_BLOCK" -> SyntaxKind.ELSE_BLOCK; + case "WHILE_STATEMENT" -> SyntaxKind.WHILE_STATEMENT; + case "DO_STATEMENT" -> SyntaxKind.DO_STATEMENT; + case "CALL_STATEMENT" -> SyntaxKind.CALL_STATEMENT; + case "PANIC_STATEMENT" -> SyntaxKind.PANIC_STATEMENT; + case "CONTINUE_STATEMENT" -> SyntaxKind.CONTINUE_STATEMENT; + case "BREAK_STATEMENT" -> SyntaxKind.BREAK_STATEMENT; + case "FAIL_STATEMENT" -> SyntaxKind.FAIL_STATEMENT; + case "RETURN_STATEMENT" -> SyntaxKind.RETURN_STATEMENT; + case "COMPOUND_ASSIGNMENT_STATEMENT" -> SyntaxKind.COMPOUND_ASSIGNMENT_STATEMENT; + case "LOCAL_TYPE_DEFINITION_STATEMENT" -> SyntaxKind.LOCAL_TYPE_DEFINITION_STATEMENT; + case "ACTION_STATEMENT" -> SyntaxKind.ACTION_STATEMENT; + case "LOCK_STATEMENT" -> SyntaxKind.LOCK_STATEMENT; + case "FORK_STATEMENT" -> SyntaxKind.FORK_STATEMENT; + case "FOREACH_STATEMENT" -> SyntaxKind.FOREACH_STATEMENT; + case "TRANSACTION_STATEMENT" -> SyntaxKind.TRANSACTION_STATEMENT; + case "RETRY_STATEMENT" -> SyntaxKind.RETRY_STATEMENT; + case "ROLLBACK_STATEMENT" -> SyntaxKind.ROLLBACK_STATEMENT; + case "MATCH_STATEMENT" -> SyntaxKind.MATCH_STATEMENT; + case "INVALID_EXPRESSION_STATEMENT" -> SyntaxKind.INVALID_EXPRESSION_STATEMENT; + default -> getExpressionKind(kind); + }; } private static SyntaxKind getExpressionKind(String kind) { - switch (kind) { - case "IDENTIFIER_TOKEN": - return SyntaxKind.IDENTIFIER_TOKEN; - case "BRACED_EXPRESSION": - return SyntaxKind.BRACED_EXPRESSION; - case "BINARY_EXPRESSION": - return SyntaxKind.BINARY_EXPRESSION; - case "STRING_LITERAL": - return SyntaxKind.STRING_LITERAL; - case "STRING_LITERAL_TOKEN": - return SyntaxKind.STRING_LITERAL_TOKEN; - case "NUMERIC_LITERAL": - return SyntaxKind.NUMERIC_LITERAL; - case "BOOLEAN_LITERAL": - return SyntaxKind.BOOLEAN_LITERAL; - case "DECIMAL_INTEGER_LITERAL_TOKEN": - return SyntaxKind.DECIMAL_INTEGER_LITERAL_TOKEN; - case "HEX_INTEGER_LITERAL_TOKEN": - return SyntaxKind.HEX_INTEGER_LITERAL_TOKEN; - case "DECIMAL_FLOATING_POINT_LITERAL_TOKEN": - return SyntaxKind.DECIMAL_FLOATING_POINT_LITERAL_TOKEN; - case "HEX_FLOATING_POINT_LITERAL_TOKEN": - return SyntaxKind.HEX_FLOATING_POINT_LITERAL_TOKEN; - case "ASTERISK_LITERAL": - return SyntaxKind.ASTERISK_LITERAL; - case "FUNCTION_CALL": - return SyntaxKind.FUNCTION_CALL; - case "POSITIONAL_ARG": - return SyntaxKind.POSITIONAL_ARG; - case "NAMED_ARG": - return SyntaxKind.NAMED_ARG; - case "REST_ARG": - return SyntaxKind.REST_ARG; - case "QUALIFIED_NAME_REFERENCE": - return SyntaxKind.QUALIFIED_NAME_REFERENCE; - case "FIELD_ACCESS": - return SyntaxKind.FIELD_ACCESS; - case "METHOD_CALL": - return SyntaxKind.METHOD_CALL; - case "INDEXED_EXPRESSION": - return SyntaxKind.INDEXED_EXPRESSION; - case "CHECK_EXPRESSION": - return SyntaxKind.CHECK_EXPRESSION; - case "MAPPING_CONSTRUCTOR": - return SyntaxKind.MAPPING_CONSTRUCTOR; - case "TYPEOF_EXPRESSION": - return SyntaxKind.TYPEOF_EXPRESSION; - case "UNARY_EXPRESSION": - return SyntaxKind.UNARY_EXPRESSION; - case "TYPE_TEST_EXPRESSION": - return SyntaxKind.TYPE_TEST_EXPRESSION; - case "NIL_LITERAL": - return SyntaxKind.NIL_LITERAL; - case "NULL_LITERAL": - return SyntaxKind.NULL_LITERAL; - case "SIMPLE_NAME_REFERENCE": - return SyntaxKind.SIMPLE_NAME_REFERENCE; - case "TRAP_EXPRESSION": - return SyntaxKind.TRAP_EXPRESSION; - case "LIST_CONSTRUCTOR": - return SyntaxKind.LIST_CONSTRUCTOR; - case "TYPE_CAST_EXPRESSION": - return SyntaxKind.TYPE_CAST_EXPRESSION; - case "TABLE_CONSTRUCTOR": - return SyntaxKind.TABLE_CONSTRUCTOR; - case "LET_EXPRESSION": - return SyntaxKind.LET_EXPRESSION; - case "RAW_TEMPLATE_EXPRESSION": - return SyntaxKind.RAW_TEMPLATE_EXPRESSION; - case "XML_TEMPLATE_EXPRESSION": - return SyntaxKind.XML_TEMPLATE_EXPRESSION; - case "STRING_TEMPLATE_EXPRESSION": - return SyntaxKind.STRING_TEMPLATE_EXPRESSION; - case "REGEX_TEMPLATE_EXPRESSION": - return SyntaxKind.REGEX_TEMPLATE_EXPRESSION; - case "QUERY_EXPRESSION": - return SyntaxKind.QUERY_EXPRESSION; - case "EXPLICIT_ANONYMOUS_FUNCTION_EXPRESSION": - return SyntaxKind.EXPLICIT_ANONYMOUS_FUNCTION_EXPRESSION; - case "IMPLICIT_ANONYMOUS_FUNCTION_EXPRESSION": - return SyntaxKind.IMPLICIT_ANONYMOUS_FUNCTION_EXPRESSION; - case "IMPLICIT_NEW_EXPRESSION": - return SyntaxKind.IMPLICIT_NEW_EXPRESSION; - case "EXPLICIT_NEW_EXPRESSION": - return SyntaxKind.EXPLICIT_NEW_EXPRESSION; - case "ANNOT_ACCESS": - return SyntaxKind.ANNOT_ACCESS; - case "OPTIONAL_FIELD_ACCESS": - return SyntaxKind.OPTIONAL_FIELD_ACCESS; - case "CONDITIONAL_EXPRESSION": - return SyntaxKind.CONDITIONAL_EXPRESSION; - case "TRANSACTIONAL_EXPRESSION": - return SyntaxKind.TRANSACTIONAL_EXPRESSION; - case "BYTE_ARRAY_LITERAL": - return SyntaxKind.BYTE_ARRAY_LITERAL; - case "XML_FILTER_EXPRESSION": - return SyntaxKind.XML_FILTER_EXPRESSION; - case "XML_STEP_EXPRESSION": - return SyntaxKind.XML_STEP_EXPRESSION; - case "XML_NAME_PATTERN_CHAIN": - return SyntaxKind.XML_NAME_PATTERN_CHAIN; - case "XML_ATOMIC_NAME_PATTERN": - return SyntaxKind.XML_ATOMIC_NAME_PATTERN; - case "REQUIRED_EXPRESSION": - return SyntaxKind.REQUIRED_EXPRESSION; - case "OBJECT_CONSTRUCTOR": - return SyntaxKind.OBJECT_CONSTRUCTOR; - case "ERROR_CONSTRUCTOR": - return SyntaxKind.ERROR_CONSTRUCTOR; - case "INFERRED_TYPEDESC_DEFAULT": - return SyntaxKind.INFERRED_TYPEDESC_DEFAULT; - case "SPREAD_MEMBER": - return SyntaxKind.SPREAD_MEMBER; - case "MEMBER_TYPE_DESC": - return SyntaxKind.MEMBER_TYPE_DESC; - default: - return getActionKind(kind); - } + return switch (kind) { + case "IDENTIFIER_TOKEN" -> SyntaxKind.IDENTIFIER_TOKEN; + case "BRACED_EXPRESSION" -> SyntaxKind.BRACED_EXPRESSION; + case "BINARY_EXPRESSION" -> SyntaxKind.BINARY_EXPRESSION; + case "STRING_LITERAL" -> SyntaxKind.STRING_LITERAL; + case "STRING_LITERAL_TOKEN" -> SyntaxKind.STRING_LITERAL_TOKEN; + case "NUMERIC_LITERAL" -> SyntaxKind.NUMERIC_LITERAL; + case "BOOLEAN_LITERAL" -> SyntaxKind.BOOLEAN_LITERAL; + case "DECIMAL_INTEGER_LITERAL_TOKEN" -> SyntaxKind.DECIMAL_INTEGER_LITERAL_TOKEN; + case "HEX_INTEGER_LITERAL_TOKEN" -> SyntaxKind.HEX_INTEGER_LITERAL_TOKEN; + case "DECIMAL_FLOATING_POINT_LITERAL_TOKEN" -> SyntaxKind.DECIMAL_FLOATING_POINT_LITERAL_TOKEN; + case "HEX_FLOATING_POINT_LITERAL_TOKEN" -> SyntaxKind.HEX_FLOATING_POINT_LITERAL_TOKEN; + case "ASTERISK_LITERAL" -> SyntaxKind.ASTERISK_LITERAL; + case "FUNCTION_CALL" -> SyntaxKind.FUNCTION_CALL; + case "POSITIONAL_ARG" -> SyntaxKind.POSITIONAL_ARG; + case "NAMED_ARG" -> SyntaxKind.NAMED_ARG; + case "REST_ARG" -> SyntaxKind.REST_ARG; + case "QUALIFIED_NAME_REFERENCE" -> SyntaxKind.QUALIFIED_NAME_REFERENCE; + case "FIELD_ACCESS" -> SyntaxKind.FIELD_ACCESS; + case "METHOD_CALL" -> SyntaxKind.METHOD_CALL; + case "INDEXED_EXPRESSION" -> SyntaxKind.INDEXED_EXPRESSION; + case "CHECK_EXPRESSION" -> SyntaxKind.CHECK_EXPRESSION; + case "MAPPING_CONSTRUCTOR" -> SyntaxKind.MAPPING_CONSTRUCTOR; + case "TYPEOF_EXPRESSION" -> SyntaxKind.TYPEOF_EXPRESSION; + case "UNARY_EXPRESSION" -> SyntaxKind.UNARY_EXPRESSION; + case "TYPE_TEST_EXPRESSION" -> SyntaxKind.TYPE_TEST_EXPRESSION; + case "NIL_LITERAL" -> SyntaxKind.NIL_LITERAL; + case "NULL_LITERAL" -> SyntaxKind.NULL_LITERAL; + case "SIMPLE_NAME_REFERENCE" -> SyntaxKind.SIMPLE_NAME_REFERENCE; + case "TRAP_EXPRESSION" -> SyntaxKind.TRAP_EXPRESSION; + case "LIST_CONSTRUCTOR" -> SyntaxKind.LIST_CONSTRUCTOR; + case "TYPE_CAST_EXPRESSION" -> SyntaxKind.TYPE_CAST_EXPRESSION; + case "TABLE_CONSTRUCTOR" -> SyntaxKind.TABLE_CONSTRUCTOR; + case "LET_EXPRESSION" -> SyntaxKind.LET_EXPRESSION; + case "RAW_TEMPLATE_EXPRESSION" -> SyntaxKind.RAW_TEMPLATE_EXPRESSION; + case "XML_TEMPLATE_EXPRESSION" -> SyntaxKind.XML_TEMPLATE_EXPRESSION; + case "STRING_TEMPLATE_EXPRESSION" -> SyntaxKind.STRING_TEMPLATE_EXPRESSION; + case "REGEX_TEMPLATE_EXPRESSION" -> SyntaxKind.REGEX_TEMPLATE_EXPRESSION; + case "QUERY_EXPRESSION" -> SyntaxKind.QUERY_EXPRESSION; + case "EXPLICIT_ANONYMOUS_FUNCTION_EXPRESSION" -> SyntaxKind.EXPLICIT_ANONYMOUS_FUNCTION_EXPRESSION; + case "IMPLICIT_ANONYMOUS_FUNCTION_EXPRESSION" -> SyntaxKind.IMPLICIT_ANONYMOUS_FUNCTION_EXPRESSION; + case "IMPLICIT_NEW_EXPRESSION" -> SyntaxKind.IMPLICIT_NEW_EXPRESSION; + case "EXPLICIT_NEW_EXPRESSION" -> SyntaxKind.EXPLICIT_NEW_EXPRESSION; + case "ANNOT_ACCESS" -> SyntaxKind.ANNOT_ACCESS; + case "OPTIONAL_FIELD_ACCESS" -> SyntaxKind.OPTIONAL_FIELD_ACCESS; + case "CONDITIONAL_EXPRESSION" -> SyntaxKind.CONDITIONAL_EXPRESSION; + case "TRANSACTIONAL_EXPRESSION" -> SyntaxKind.TRANSACTIONAL_EXPRESSION; + case "BYTE_ARRAY_LITERAL" -> SyntaxKind.BYTE_ARRAY_LITERAL; + case "XML_FILTER_EXPRESSION" -> SyntaxKind.XML_FILTER_EXPRESSION; + case "XML_STEP_EXPRESSION" -> SyntaxKind.XML_STEP_EXPRESSION; + case "XML_NAME_PATTERN_CHAIN" -> SyntaxKind.XML_NAME_PATTERN_CHAIN; + case "XML_ATOMIC_NAME_PATTERN" -> SyntaxKind.XML_ATOMIC_NAME_PATTERN; + case "REQUIRED_EXPRESSION" -> SyntaxKind.REQUIRED_EXPRESSION; + case "OBJECT_CONSTRUCTOR" -> SyntaxKind.OBJECT_CONSTRUCTOR; + case "ERROR_CONSTRUCTOR" -> SyntaxKind.ERROR_CONSTRUCTOR; + case "INFERRED_TYPEDESC_DEFAULT" -> SyntaxKind.INFERRED_TYPEDESC_DEFAULT; + case "SPREAD_MEMBER" -> SyntaxKind.SPREAD_MEMBER; + case "MEMBER_TYPE_DESC" -> SyntaxKind.MEMBER_TYPE_DESC; + default -> getActionKind(kind); + }; } private static SyntaxKind getActionKind(String kind) { - switch (kind) { - case "REMOTE_METHOD_CALL_ACTION": - return SyntaxKind.REMOTE_METHOD_CALL_ACTION; - case "BRACED_ACTION": - return SyntaxKind.BRACED_ACTION; - case "CHECK_ACTION": - return SyntaxKind.CHECK_ACTION; - case "START_ACTION": - return SyntaxKind.START_ACTION; - case "TRAP_ACTION": - return SyntaxKind.TRAP_ACTION; - case "FLUSH_ACTION": - return SyntaxKind.FLUSH_ACTION; - case "ASYNC_SEND_ACTION": - return SyntaxKind.ASYNC_SEND_ACTION; - case "SYNC_SEND_ACTION": - return SyntaxKind.SYNC_SEND_ACTION; - case "RECEIVE_ACTION": - return SyntaxKind.RECEIVE_ACTION; - case "WAIT_ACTION": - return SyntaxKind.WAIT_ACTION; - case "QUERY_ACTION": - return SyntaxKind.QUERY_ACTION; - case "COMMIT_ACTION": - return SyntaxKind.COMMIT_ACTION; - default: - return getTypeKind(kind); - } + return switch (kind) { + case "REMOTE_METHOD_CALL_ACTION" -> SyntaxKind.REMOTE_METHOD_CALL_ACTION; + case "BRACED_ACTION" -> SyntaxKind.BRACED_ACTION; + case "CHECK_ACTION" -> SyntaxKind.CHECK_ACTION; + case "START_ACTION" -> SyntaxKind.START_ACTION; + case "TRAP_ACTION" -> SyntaxKind.TRAP_ACTION; + case "FLUSH_ACTION" -> SyntaxKind.FLUSH_ACTION; + case "ASYNC_SEND_ACTION" -> SyntaxKind.ASYNC_SEND_ACTION; + case "SYNC_SEND_ACTION" -> SyntaxKind.SYNC_SEND_ACTION; + case "RECEIVE_ACTION" -> SyntaxKind.RECEIVE_ACTION; + case "WAIT_ACTION" -> SyntaxKind.WAIT_ACTION; + case "QUERY_ACTION" -> SyntaxKind.QUERY_ACTION; + case "COMMIT_ACTION" -> SyntaxKind.COMMIT_ACTION; + default -> getTypeKind(kind); + }; } private static SyntaxKind getTypeKind(String kind) { - switch (kind) { - case "TYPE_DESC": - return SyntaxKind.TYPE_DESC; - case "INT_TYPE_DESC": - return SyntaxKind.INT_TYPE_DESC; - case "FLOAT_TYPE_DESC": - return SyntaxKind.FLOAT_TYPE_DESC; - case "DECIMAL_TYPE_DESC": - return SyntaxKind.DECIMAL_TYPE_DESC; - case "BOOLEAN_TYPE_DESC": - return SyntaxKind.BOOLEAN_TYPE_DESC; - case "STRING_TYPE_DESC": - return SyntaxKind.STRING_TYPE_DESC; - case "BYTE_TYPE_DESC": - return SyntaxKind.BYTE_TYPE_DESC; - case "XML_TYPE_DESC": - return SyntaxKind.XML_TYPE_DESC; - case "JSON_TYPE_DESC": - return SyntaxKind.JSON_TYPE_DESC; - case "HANDLE_TYPE_DESC": - return SyntaxKind.HANDLE_TYPE_DESC; - case "ANY_TYPE_DESC": - return SyntaxKind.ANY_TYPE_DESC; - case "ANYDATA_TYPE_DESC": - return SyntaxKind.ANYDATA_TYPE_DESC; - case "NEVER_TYPE_DESC": - return SyntaxKind.NEVER_TYPE_DESC; - case "NIL_TYPE_DESC": - return SyntaxKind.NIL_TYPE_DESC; - case "OPTIONAL_TYPE_DESC": - return SyntaxKind.OPTIONAL_TYPE_DESC; - case "ARRAY_TYPE_DESC": - return SyntaxKind.ARRAY_TYPE_DESC; - case "RECORD_TYPE_DESC": - return SyntaxKind.RECORD_TYPE_DESC; - case "OBJECT_TYPE_DESC": - return SyntaxKind.OBJECT_TYPE_DESC; - case "UNION_TYPE_DESC": - return SyntaxKind.UNION_TYPE_DESC; - case "ERROR_TYPE_DESC": - return SyntaxKind.ERROR_TYPE_DESC; - case "EXPLICIT_TYPE_PARAMS": - return SyntaxKind.EXPLICIT_TYPE_PARAMS; - case "STREAM_TYPE_DESC": - return SyntaxKind.STREAM_TYPE_DESC; - case "FUNCTION_TYPE_DESC": - return SyntaxKind.FUNCTION_TYPE_DESC; - case "TABLE_TYPE_DESC": - return SyntaxKind.TABLE_TYPE_DESC; - case "TUPLE_TYPE_DESC": - return SyntaxKind.TUPLE_TYPE_DESC; - case "PARENTHESISED_TYPE_DESC": - return SyntaxKind.PARENTHESISED_TYPE_DESC; - case "READONLY_TYPE_DESC": - return SyntaxKind.READONLY_TYPE_DESC; - case "DISTINCT_TYPE_DESC": - return SyntaxKind.DISTINCT_TYPE_DESC; - case "INTERSECTION_TYPE_DESC": - return SyntaxKind.INTERSECTION_TYPE_DESC; - case "SINGLETON_TYPE_DESC": - return SyntaxKind.SINGLETON_TYPE_DESC; - case "TYPEDESC_TYPE_DESC": - return SyntaxKind.TYPEDESC_TYPE_DESC; - case "VAR_TYPE_DESC": - return SyntaxKind.VAR_TYPE_DESC; - case "SERVICE_TYPE_DESC": - return SyntaxKind.SERVICE_TYPE_DESC; - case "MAP_TYPE_DESC": - return SyntaxKind.MAP_TYPE_DESC; - case "FUTURE_TYPE_DESC": - return SyntaxKind.FUTURE_TYPE_DESC; - default: - return getOperatorKind(kind); - } + return switch (kind) { + case "TYPE_DESC" -> SyntaxKind.TYPE_DESC; + case "INT_TYPE_DESC" -> SyntaxKind.INT_TYPE_DESC; + case "FLOAT_TYPE_DESC" -> SyntaxKind.FLOAT_TYPE_DESC; + case "DECIMAL_TYPE_DESC" -> SyntaxKind.DECIMAL_TYPE_DESC; + case "BOOLEAN_TYPE_DESC" -> SyntaxKind.BOOLEAN_TYPE_DESC; + case "STRING_TYPE_DESC" -> SyntaxKind.STRING_TYPE_DESC; + case "BYTE_TYPE_DESC" -> SyntaxKind.BYTE_TYPE_DESC; + case "XML_TYPE_DESC" -> SyntaxKind.XML_TYPE_DESC; + case "JSON_TYPE_DESC" -> SyntaxKind.JSON_TYPE_DESC; + case "HANDLE_TYPE_DESC" -> SyntaxKind.HANDLE_TYPE_DESC; + case "ANY_TYPE_DESC" -> SyntaxKind.ANY_TYPE_DESC; + case "ANYDATA_TYPE_DESC" -> SyntaxKind.ANYDATA_TYPE_DESC; + case "NEVER_TYPE_DESC" -> SyntaxKind.NEVER_TYPE_DESC; + case "NIL_TYPE_DESC" -> SyntaxKind.NIL_TYPE_DESC; + case "OPTIONAL_TYPE_DESC" -> SyntaxKind.OPTIONAL_TYPE_DESC; + case "ARRAY_TYPE_DESC" -> SyntaxKind.ARRAY_TYPE_DESC; + case "RECORD_TYPE_DESC" -> SyntaxKind.RECORD_TYPE_DESC; + case "OBJECT_TYPE_DESC" -> SyntaxKind.OBJECT_TYPE_DESC; + case "UNION_TYPE_DESC" -> SyntaxKind.UNION_TYPE_DESC; + case "ERROR_TYPE_DESC" -> SyntaxKind.ERROR_TYPE_DESC; + case "EXPLICIT_TYPE_PARAMS" -> SyntaxKind.EXPLICIT_TYPE_PARAMS; + case "STREAM_TYPE_DESC" -> SyntaxKind.STREAM_TYPE_DESC; + case "FUNCTION_TYPE_DESC" -> SyntaxKind.FUNCTION_TYPE_DESC; + case "TABLE_TYPE_DESC" -> SyntaxKind.TABLE_TYPE_DESC; + case "TUPLE_TYPE_DESC" -> SyntaxKind.TUPLE_TYPE_DESC; + case "PARENTHESISED_TYPE_DESC" -> SyntaxKind.PARENTHESISED_TYPE_DESC; + case "READONLY_TYPE_DESC" -> SyntaxKind.READONLY_TYPE_DESC; + case "DISTINCT_TYPE_DESC" -> SyntaxKind.DISTINCT_TYPE_DESC; + case "INTERSECTION_TYPE_DESC" -> SyntaxKind.INTERSECTION_TYPE_DESC; + case "SINGLETON_TYPE_DESC" -> SyntaxKind.SINGLETON_TYPE_DESC; + case "TYPEDESC_TYPE_DESC" -> SyntaxKind.TYPEDESC_TYPE_DESC; + case "VAR_TYPE_DESC" -> SyntaxKind.VAR_TYPE_DESC; + case "SERVICE_TYPE_DESC" -> SyntaxKind.SERVICE_TYPE_DESC; + case "MAP_TYPE_DESC" -> SyntaxKind.MAP_TYPE_DESC; + case "FUTURE_TYPE_DESC" -> SyntaxKind.FUTURE_TYPE_DESC; + default -> getOperatorKind(kind); + }; } private static SyntaxKind getOperatorKind(String kind) { - switch (kind) { - case "PLUS_TOKEN": - return SyntaxKind.PLUS_TOKEN; - case "MINUS_TOKEN": - return SyntaxKind.MINUS_TOKEN; - case "ASTERISK_TOKEN": - return SyntaxKind.ASTERISK_TOKEN; - case "SLASH_TOKEN": - return SyntaxKind.SLASH_TOKEN; - case "LT_TOKEN": - return SyntaxKind.LT_TOKEN; - case "EQUAL_TOKEN": - return SyntaxKind.EQUAL_TOKEN; - case "DOUBLE_EQUAL_TOKEN": - return SyntaxKind.DOUBLE_EQUAL_TOKEN; - case "TRIPPLE_EQUAL_TOKEN": - return SyntaxKind.TRIPPLE_EQUAL_TOKEN; - case "PERCENT_TOKEN": - return SyntaxKind.PERCENT_TOKEN; - case "GT_TOKEN": - return SyntaxKind.GT_TOKEN; - case "RIGHT_DOUBLE_ARROW_TOKEN": - return SyntaxKind.RIGHT_DOUBLE_ARROW_TOKEN; - case "QUESTION_MARK_TOKEN": - return SyntaxKind.QUESTION_MARK_TOKEN; - case "LT_EQUAL_TOKEN": - return SyntaxKind.LT_EQUAL_TOKEN; - case "GT_EQUAL_TOKEN": - return SyntaxKind.GT_EQUAL_TOKEN; - case "EXCLAMATION_MARK_TOKEN": - return SyntaxKind.EXCLAMATION_MARK_TOKEN; - case "NOT_EQUAL_TOKEN": - return SyntaxKind.NOT_EQUAL_TOKEN; - case "NOT_DOUBLE_EQUAL_TOKEN": - return SyntaxKind.NOT_DOUBLE_EQUAL_TOKEN; - case "BITWISE_AND_TOKEN": - return SyntaxKind.BITWISE_AND_TOKEN; - case "BITWISE_XOR_TOKEN": - return SyntaxKind.BITWISE_XOR_TOKEN; - case "LOGICAL_AND_TOKEN": - return SyntaxKind.LOGICAL_AND_TOKEN; - case "LOGICAL_OR_TOKEN": - return SyntaxKind.LOGICAL_OR_TOKEN; - case "NEGATION_TOKEN": - return SyntaxKind.NEGATION_TOKEN; - case "DOUBLE_LT_TOKEN": - return SyntaxKind.DOUBLE_LT_TOKEN; - case "DOUBLE_GT_TOKEN": - return SyntaxKind.DOUBLE_GT_TOKEN; - case "TRIPPLE_GT_TOKEN": - return SyntaxKind.TRIPPLE_GT_TOKEN; - case "DOUBLE_DOT_LT_TOKEN": - return SyntaxKind.DOUBLE_DOT_LT_TOKEN; - case "ANNOT_CHAINING_TOKEN": - return SyntaxKind.ANNOT_CHAINING_TOKEN; - case "OPTIONAL_CHAINING_TOKEN": - return SyntaxKind.OPTIONAL_CHAINING_TOKEN; - case "ELVIS_TOKEN": - return SyntaxKind.ELVIS_TOKEN; - case "DOT_LT_TOKEN": - return SyntaxKind.DOT_LT_TOKEN; - case "SLASH_LT_TOKEN": - return SyntaxKind.SLASH_LT_TOKEN; - case "DOUBLE_SLASH_DOUBLE_ASTERISK_LT_TOKEN": - return SyntaxKind.DOUBLE_SLASH_DOUBLE_ASTERISK_LT_TOKEN; - case "SLASH_ASTERISK_TOKEN": - return SyntaxKind.SLASH_ASTERISK_TOKEN; - default: - return getSeparatorKind(kind); - } + return switch (kind) { + case "PLUS_TOKEN" -> SyntaxKind.PLUS_TOKEN; + case "MINUS_TOKEN" -> SyntaxKind.MINUS_TOKEN; + case "ASTERISK_TOKEN" -> SyntaxKind.ASTERISK_TOKEN; + case "SLASH_TOKEN" -> SyntaxKind.SLASH_TOKEN; + case "LT_TOKEN" -> SyntaxKind.LT_TOKEN; + case "EQUAL_TOKEN" -> SyntaxKind.EQUAL_TOKEN; + case "DOUBLE_EQUAL_TOKEN" -> SyntaxKind.DOUBLE_EQUAL_TOKEN; + case "TRIPPLE_EQUAL_TOKEN" -> SyntaxKind.TRIPPLE_EQUAL_TOKEN; + case "PERCENT_TOKEN" -> SyntaxKind.PERCENT_TOKEN; + case "GT_TOKEN" -> SyntaxKind.GT_TOKEN; + case "RIGHT_DOUBLE_ARROW_TOKEN" -> SyntaxKind.RIGHT_DOUBLE_ARROW_TOKEN; + case "QUESTION_MARK_TOKEN" -> SyntaxKind.QUESTION_MARK_TOKEN; + case "LT_EQUAL_TOKEN" -> SyntaxKind.LT_EQUAL_TOKEN; + case "GT_EQUAL_TOKEN" -> SyntaxKind.GT_EQUAL_TOKEN; + case "EXCLAMATION_MARK_TOKEN" -> SyntaxKind.EXCLAMATION_MARK_TOKEN; + case "NOT_EQUAL_TOKEN" -> SyntaxKind.NOT_EQUAL_TOKEN; + case "NOT_DOUBLE_EQUAL_TOKEN" -> SyntaxKind.NOT_DOUBLE_EQUAL_TOKEN; + case "BITWISE_AND_TOKEN" -> SyntaxKind.BITWISE_AND_TOKEN; + case "BITWISE_XOR_TOKEN" -> SyntaxKind.BITWISE_XOR_TOKEN; + case "LOGICAL_AND_TOKEN" -> SyntaxKind.LOGICAL_AND_TOKEN; + case "LOGICAL_OR_TOKEN" -> SyntaxKind.LOGICAL_OR_TOKEN; + case "NEGATION_TOKEN" -> SyntaxKind.NEGATION_TOKEN; + case "DOUBLE_LT_TOKEN" -> SyntaxKind.DOUBLE_LT_TOKEN; + case "DOUBLE_GT_TOKEN" -> SyntaxKind.DOUBLE_GT_TOKEN; + case "TRIPPLE_GT_TOKEN" -> SyntaxKind.TRIPPLE_GT_TOKEN; + case "DOUBLE_DOT_LT_TOKEN" -> SyntaxKind.DOUBLE_DOT_LT_TOKEN; + case "ANNOT_CHAINING_TOKEN" -> SyntaxKind.ANNOT_CHAINING_TOKEN; + case "OPTIONAL_CHAINING_TOKEN" -> SyntaxKind.OPTIONAL_CHAINING_TOKEN; + case "ELVIS_TOKEN" -> SyntaxKind.ELVIS_TOKEN; + case "DOT_LT_TOKEN" -> SyntaxKind.DOT_LT_TOKEN; + case "SLASH_LT_TOKEN" -> SyntaxKind.SLASH_LT_TOKEN; + case "DOUBLE_SLASH_DOUBLE_ASTERISK_LT_TOKEN" -> SyntaxKind.DOUBLE_SLASH_DOUBLE_ASTERISK_LT_TOKEN; + case "SLASH_ASTERISK_TOKEN" -> SyntaxKind.SLASH_ASTERISK_TOKEN; + default -> getSeparatorKind(kind); + }; } private static SyntaxKind getSeparatorKind(String kind) { - switch (kind) { - case "OPEN_BRACE_TOKEN": - return SyntaxKind.OPEN_BRACE_TOKEN; - case "CLOSE_BRACE_TOKEN": - return SyntaxKind.CLOSE_BRACE_TOKEN; - case "OPEN_PAREN_TOKEN": - return SyntaxKind.OPEN_PAREN_TOKEN; - case "CLOSE_PAREN_TOKEN": - return SyntaxKind.CLOSE_PAREN_TOKEN; - case "OPEN_BRACKET_TOKEN": - return SyntaxKind.OPEN_BRACKET_TOKEN; - case "CLOSE_BRACKET_TOKEN": - return SyntaxKind.CLOSE_BRACKET_TOKEN; - case "SEMICOLON_TOKEN": - return SyntaxKind.SEMICOLON_TOKEN; - case "DOT_TOKEN": - return SyntaxKind.DOT_TOKEN; - case "COLON_TOKEN": - return SyntaxKind.COLON_TOKEN; - case "COMMA_TOKEN": - return SyntaxKind.COMMA_TOKEN; - case "ELLIPSIS_TOKEN": - return SyntaxKind.ELLIPSIS_TOKEN; - case "OPEN_BRACE_PIPE_TOKEN": - return SyntaxKind.OPEN_BRACE_PIPE_TOKEN; - case "CLOSE_BRACE_PIPE_TOKEN": - return SyntaxKind.CLOSE_BRACE_PIPE_TOKEN; - case "PIPE_TOKEN": - return SyntaxKind.PIPE_TOKEN; - case "AT_TOKEN": - return SyntaxKind.AT_TOKEN; - case "RIGHT_ARROW_TOKEN": - return SyntaxKind.RIGHT_ARROW_TOKEN; - case "BACKTICK_TOKEN": - return SyntaxKind.BACKTICK_TOKEN; - case "DOUBLE_BACKTICK_TOKEN": - return SyntaxKind.DOUBLE_BACKTICK_TOKEN; - case "TRIPLE_BACKTICK_TOKEN": - return SyntaxKind.TRIPLE_BACKTICK_TOKEN; - case "DOUBLE_QUOTE_TOKEN": - return SyntaxKind.DOUBLE_QUOTE_TOKEN; - case "SINGLE_QUOTE_TOKEN": - return SyntaxKind.SINGLE_QUOTE_TOKEN; - case "SYNC_SEND_TOKEN": - return SyntaxKind.SYNC_SEND_TOKEN; - case "LEFT_ARROW_TOKEN": - return SyntaxKind.LEFT_ARROW_TOKEN; - case "HASH_TOKEN": - return SyntaxKind.HASH_TOKEN; - case "BACK_SLASH_TOKEN": - return SyntaxKind.BACK_SLASH_TOKEN; - default: - return getKeywordKind(kind); - } + return switch (kind) { + case "OPEN_BRACE_TOKEN" -> SyntaxKind.OPEN_BRACE_TOKEN; + case "CLOSE_BRACE_TOKEN" -> SyntaxKind.CLOSE_BRACE_TOKEN; + case "OPEN_PAREN_TOKEN" -> SyntaxKind.OPEN_PAREN_TOKEN; + case "CLOSE_PAREN_TOKEN" -> SyntaxKind.CLOSE_PAREN_TOKEN; + case "OPEN_BRACKET_TOKEN" -> SyntaxKind.OPEN_BRACKET_TOKEN; + case "CLOSE_BRACKET_TOKEN" -> SyntaxKind.CLOSE_BRACKET_TOKEN; + case "SEMICOLON_TOKEN" -> SyntaxKind.SEMICOLON_TOKEN; + case "DOT_TOKEN" -> SyntaxKind.DOT_TOKEN; + case "COLON_TOKEN" -> SyntaxKind.COLON_TOKEN; + case "COMMA_TOKEN" -> SyntaxKind.COMMA_TOKEN; + case "ELLIPSIS_TOKEN" -> SyntaxKind.ELLIPSIS_TOKEN; + case "OPEN_BRACE_PIPE_TOKEN" -> SyntaxKind.OPEN_BRACE_PIPE_TOKEN; + case "CLOSE_BRACE_PIPE_TOKEN" -> SyntaxKind.CLOSE_BRACE_PIPE_TOKEN; + case "PIPE_TOKEN" -> SyntaxKind.PIPE_TOKEN; + case "AT_TOKEN" -> SyntaxKind.AT_TOKEN; + case "RIGHT_ARROW_TOKEN" -> SyntaxKind.RIGHT_ARROW_TOKEN; + case "BACKTICK_TOKEN" -> SyntaxKind.BACKTICK_TOKEN; + case "DOUBLE_BACKTICK_TOKEN" -> SyntaxKind.DOUBLE_BACKTICK_TOKEN; + case "TRIPLE_BACKTICK_TOKEN" -> SyntaxKind.TRIPLE_BACKTICK_TOKEN; + case "DOUBLE_QUOTE_TOKEN" -> SyntaxKind.DOUBLE_QUOTE_TOKEN; + case "SINGLE_QUOTE_TOKEN" -> SyntaxKind.SINGLE_QUOTE_TOKEN; + case "SYNC_SEND_TOKEN" -> SyntaxKind.SYNC_SEND_TOKEN; + case "LEFT_ARROW_TOKEN" -> SyntaxKind.LEFT_ARROW_TOKEN; + case "HASH_TOKEN" -> SyntaxKind.HASH_TOKEN; + case "BACK_SLASH_TOKEN" -> SyntaxKind.BACK_SLASH_TOKEN; + default -> getKeywordKind(kind); + }; } private static SyntaxKind getKeywordKind(String kind) { - switch (kind) { - case "PUBLIC_KEYWORD": - return SyntaxKind.PUBLIC_KEYWORD; - case "PRIVATE_KEYWORD": - return SyntaxKind.PRIVATE_KEYWORD; - case "FUNCTION_KEYWORD": - return SyntaxKind.FUNCTION_KEYWORD; - case "TYPE_KEYWORD": - return SyntaxKind.TYPE_KEYWORD; - case "EXTERNAL_KEYWORD": - return SyntaxKind.EXTERNAL_KEYWORD; - case "RETURNS_KEYWORD": - return SyntaxKind.RETURNS_KEYWORD; - case "RECORD_KEYWORD": - return SyntaxKind.RECORD_KEYWORD; - case "OBJECT_KEYWORD": - return SyntaxKind.OBJECT_KEYWORD; - case "REMOTE_KEYWORD": - return SyntaxKind.REMOTE_KEYWORD; - case "CLIENT_KEYWORD": - return SyntaxKind.CLIENT_KEYWORD; - case "ABSTRACT_KEYWORD": - return SyntaxKind.ABSTRACT_KEYWORD; - case "IF_KEYWORD": - return SyntaxKind.IF_KEYWORD; - case "ELSE_KEYWORD": - return SyntaxKind.ELSE_KEYWORD; - case "WHILE_KEYWORD": - return SyntaxKind.WHILE_KEYWORD; - case "TRUE_KEYWORD": - return SyntaxKind.TRUE_KEYWORD; - case "FALSE_KEYWORD": - return SyntaxKind.FALSE_KEYWORD; - case "CHECK_KEYWORD": - return SyntaxKind.CHECK_KEYWORD; - case "CHECKPANIC_KEYWORD": - return SyntaxKind.CHECKPANIC_KEYWORD; - case "FAIL_KEYWORD": - return SyntaxKind.FAIL_KEYWORD; - case "PANIC_KEYWORD": - return SyntaxKind.PANIC_KEYWORD; - case "IMPORT_KEYWORD": - return SyntaxKind.IMPORT_KEYWORD; - case "AS_KEYWORD": - return SyntaxKind.AS_KEYWORD; - case "CONTINUE_KEYWORD": - return SyntaxKind.CONTINUE_KEYWORD; - case "BREAK_KEYWORD": - return SyntaxKind.BREAK_KEYWORD; - case "RETURN_KEYWORD": - return SyntaxKind.RETURN_KEYWORD; - case "SERVICE_KEYWORD": - return SyntaxKind.SERVICE_KEYWORD; - case "ON_KEYWORD": - return SyntaxKind.ON_KEYWORD; - case "RESOURCE_KEYWORD": - return SyntaxKind.RESOURCE_KEYWORD; - case "LISTENER_KEYWORD": - return SyntaxKind.LISTENER_KEYWORD; - case "CONST_KEYWORD": - return SyntaxKind.CONST_KEYWORD; - case "FINAL_KEYWORD": - return SyntaxKind.FINAL_KEYWORD; - case "TYPEOF_KEYWORD": - return SyntaxKind.TYPEOF_KEYWORD; - case "ANNOTATION_KEYWORD": - return SyntaxKind.ANNOTATION_KEYWORD; - case "IS_KEYWORD": - return SyntaxKind.IS_KEYWORD; - case "NOT_IS_KEYWORD": - return SyntaxKind.NOT_IS_KEYWORD; - case "MAP_KEYWORD": - return SyntaxKind.MAP_KEYWORD; - case "FUTURE_KEYWORD": - return SyntaxKind.FUTURE_KEYWORD; - case "TYPEDESC_KEYWORD": - return SyntaxKind.TYPEDESC_KEYWORD; - case "NULL_KEYWORD": - return SyntaxKind.NULL_KEYWORD; - case "LOCK_KEYWORD": - return SyntaxKind.LOCK_KEYWORD; - case "VAR_KEYWORD": - return SyntaxKind.VAR_KEYWORD; - case "SOURCE_KEYWORD": - return SyntaxKind.SOURCE_KEYWORD; - case "WORKER_KEYWORD": - return SyntaxKind.WORKER_KEYWORD; - case "PARAMETER_KEYWORD": - return SyntaxKind.PARAMETER_KEYWORD; - case "FIELD_KEYWORD": - return SyntaxKind.FIELD_KEYWORD; - case "XMLNS_KEYWORD": - return SyntaxKind.XMLNS_KEYWORD; - case "INT_KEYWORD": - return SyntaxKind.INT_KEYWORD; - case "FLOAT_KEYWORD": - return SyntaxKind.FLOAT_KEYWORD; - case "DECIMAL_KEYWORD": - return SyntaxKind.DECIMAL_KEYWORD; - case "BOOLEAN_KEYWORD": - return SyntaxKind.BOOLEAN_KEYWORD; - case "STRING_KEYWORD": - return SyntaxKind.STRING_KEYWORD; - case "BYTE_KEYWORD": - return SyntaxKind.BYTE_KEYWORD; - case "XML_KEYWORD": - return SyntaxKind.XML_KEYWORD; - case "RE_KEYWORD": - return SyntaxKind.RE_KEYWORD; - case "JSON_KEYWORD": - return SyntaxKind.JSON_KEYWORD; - case "HANDLE_KEYWORD": - return SyntaxKind.HANDLE_KEYWORD; - case "ANY_KEYWORD": - return SyntaxKind.ANY_KEYWORD; - case "ANYDATA_KEYWORD": - return SyntaxKind.ANYDATA_KEYWORD; - case "NEVER_KEYWORD": - return SyntaxKind.NEVER_KEYWORD; - case "FORK_KEYWORD": - return SyntaxKind.FORK_KEYWORD; - case "TRAP_KEYWORD": - return SyntaxKind.TRAP_KEYWORD; - case "FOREACH_KEYWORD": - return SyntaxKind.FOREACH_KEYWORD; - case "IN_KEYWORD": - return SyntaxKind.IN_KEYWORD; - case "TABLE_KEYWORD": - return SyntaxKind.TABLE_KEYWORD; - case "KEY_KEYWORD": - return SyntaxKind.KEY_KEYWORD; - case "ERROR_KEYWORD": - return SyntaxKind.ERROR_KEYWORD; - case "LET_KEYWORD": - return SyntaxKind.LET_KEYWORD; - case "STREAM_KEYWORD": - return SyntaxKind.STREAM_KEYWORD; - case "READONLY_KEYWORD": - return SyntaxKind.READONLY_KEYWORD; - case "DISTINCT_KEYWORD": - return SyntaxKind.DISTINCT_KEYWORD; - case "FROM_KEYWORD": - return SyntaxKind.FROM_KEYWORD; - case "WHERE_KEYWORD": - return SyntaxKind.WHERE_KEYWORD; - case "SELECT_KEYWORD": - return SyntaxKind.SELECT_KEYWORD; - case "COLLECT_KEYWORD": - return SyntaxKind.COLLECT_KEYWORD; - case "ORDER_KEYWORD": - return SyntaxKind.ORDER_KEYWORD; - case "BY_KEYWORD": - return SyntaxKind.BY_KEYWORD; - case "GROUP_KEYWORD": - return SyntaxKind.GROUP_KEYWORD; - case "ASCENDING_KEYWORD": - return SyntaxKind.ASCENDING_KEYWORD; - case "DESCENDING_KEYWORD": - return SyntaxKind.DESCENDING_KEYWORD; - case "NEW_KEYWORD": - return SyntaxKind.NEW_KEYWORD; - case "START_KEYWORD": - return SyntaxKind.START_KEYWORD; - case "FLUSH_KEYWORD": - return SyntaxKind.FLUSH_KEYWORD; - case "WAIT_KEYWORD": - return SyntaxKind.WAIT_KEYWORD; - case "DO_KEYWORD": - return SyntaxKind.DO_KEYWORD; - case "TRANSACTION_KEYWORD": - return SyntaxKind.TRANSACTION_KEYWORD; - case "COMMIT_KEYWORD": - return SyntaxKind.COMMIT_KEYWORD; - case "RETRY_KEYWORD": - return SyntaxKind.RETRY_KEYWORD; - case "ROLLBACK_KEYWORD": - return SyntaxKind.ROLLBACK_KEYWORD; - case "TRANSACTIONAL_KEYWORD": - return SyntaxKind.TRANSACTIONAL_KEYWORD; - case "ISOLATED_KEYWORD": - return SyntaxKind.ISOLATED_KEYWORD; - case "ENUM_KEYWORD": - return SyntaxKind.ENUM_KEYWORD; - case "BASE16_KEYWORD": - return SyntaxKind.BASE16_KEYWORD; - case "BASE64_KEYWORD": - return SyntaxKind.BASE64_KEYWORD; - case "MATCH_KEYWORD": - return SyntaxKind.MATCH_KEYWORD; - case "CLASS_KEYWORD": - return SyntaxKind.CLASS_KEYWORD; - case "CONFLICT_KEYWORD": - return SyntaxKind.CONFLICT_KEYWORD; - case "LIMIT_KEYWORD": - return SyntaxKind.LIMIT_KEYWORD; - case "JOIN_KEYWORD": - return SyntaxKind.JOIN_KEYWORD; - case "EQUALS_KEYWORD": - return SyntaxKind.EQUALS_KEYWORD; - case "OUTER_KEYWORD": - return SyntaxKind.OUTER_KEYWORD; - case "CONFIGURABLE_KEYWORD": - return SyntaxKind.CONFIGURABLE_KEYWORD; - case "UNDERSCORE_KEYWORD": - return SyntaxKind.UNDERSCORE_KEYWORD; - default: - return getXMLTemplateKind(kind); - } + return switch (kind) { + case "PUBLIC_KEYWORD" -> SyntaxKind.PUBLIC_KEYWORD; + case "PRIVATE_KEYWORD" -> SyntaxKind.PRIVATE_KEYWORD; + case "FUNCTION_KEYWORD" -> SyntaxKind.FUNCTION_KEYWORD; + case "TYPE_KEYWORD" -> SyntaxKind.TYPE_KEYWORD; + case "EXTERNAL_KEYWORD" -> SyntaxKind.EXTERNAL_KEYWORD; + case "RETURNS_KEYWORD" -> SyntaxKind.RETURNS_KEYWORD; + case "RECORD_KEYWORD" -> SyntaxKind.RECORD_KEYWORD; + case "OBJECT_KEYWORD" -> SyntaxKind.OBJECT_KEYWORD; + case "REMOTE_KEYWORD" -> SyntaxKind.REMOTE_KEYWORD; + case "CLIENT_KEYWORD" -> SyntaxKind.CLIENT_KEYWORD; + case "ABSTRACT_KEYWORD" -> SyntaxKind.ABSTRACT_KEYWORD; + case "IF_KEYWORD" -> SyntaxKind.IF_KEYWORD; + case "ELSE_KEYWORD" -> SyntaxKind.ELSE_KEYWORD; + case "WHILE_KEYWORD" -> SyntaxKind.WHILE_KEYWORD; + case "TRUE_KEYWORD" -> SyntaxKind.TRUE_KEYWORD; + case "FALSE_KEYWORD" -> SyntaxKind.FALSE_KEYWORD; + case "CHECK_KEYWORD" -> SyntaxKind.CHECK_KEYWORD; + case "CHECKPANIC_KEYWORD" -> SyntaxKind.CHECKPANIC_KEYWORD; + case "FAIL_KEYWORD" -> SyntaxKind.FAIL_KEYWORD; + case "PANIC_KEYWORD" -> SyntaxKind.PANIC_KEYWORD; + case "IMPORT_KEYWORD" -> SyntaxKind.IMPORT_KEYWORD; + case "AS_KEYWORD" -> SyntaxKind.AS_KEYWORD; + case "CONTINUE_KEYWORD" -> SyntaxKind.CONTINUE_KEYWORD; + case "BREAK_KEYWORD" -> SyntaxKind.BREAK_KEYWORD; + case "RETURN_KEYWORD" -> SyntaxKind.RETURN_KEYWORD; + case "SERVICE_KEYWORD" -> SyntaxKind.SERVICE_KEYWORD; + case "ON_KEYWORD" -> SyntaxKind.ON_KEYWORD; + case "RESOURCE_KEYWORD" -> SyntaxKind.RESOURCE_KEYWORD; + case "LISTENER_KEYWORD" -> SyntaxKind.LISTENER_KEYWORD; + case "CONST_KEYWORD" -> SyntaxKind.CONST_KEYWORD; + case "FINAL_KEYWORD" -> SyntaxKind.FINAL_KEYWORD; + case "TYPEOF_KEYWORD" -> SyntaxKind.TYPEOF_KEYWORD; + case "ANNOTATION_KEYWORD" -> SyntaxKind.ANNOTATION_KEYWORD; + case "IS_KEYWORD" -> SyntaxKind.IS_KEYWORD; + case "NOT_IS_KEYWORD" -> SyntaxKind.NOT_IS_KEYWORD; + case "MAP_KEYWORD" -> SyntaxKind.MAP_KEYWORD; + case "FUTURE_KEYWORD" -> SyntaxKind.FUTURE_KEYWORD; + case "TYPEDESC_KEYWORD" -> SyntaxKind.TYPEDESC_KEYWORD; + case "NULL_KEYWORD" -> SyntaxKind.NULL_KEYWORD; + case "LOCK_KEYWORD" -> SyntaxKind.LOCK_KEYWORD; + case "VAR_KEYWORD" -> SyntaxKind.VAR_KEYWORD; + case "SOURCE_KEYWORD" -> SyntaxKind.SOURCE_KEYWORD; + case "WORKER_KEYWORD" -> SyntaxKind.WORKER_KEYWORD; + case "PARAMETER_KEYWORD" -> SyntaxKind.PARAMETER_KEYWORD; + case "FIELD_KEYWORD" -> SyntaxKind.FIELD_KEYWORD; + case "XMLNS_KEYWORD" -> SyntaxKind.XMLNS_KEYWORD; + case "INT_KEYWORD" -> SyntaxKind.INT_KEYWORD; + case "FLOAT_KEYWORD" -> SyntaxKind.FLOAT_KEYWORD; + case "DECIMAL_KEYWORD" -> SyntaxKind.DECIMAL_KEYWORD; + case "BOOLEAN_KEYWORD" -> SyntaxKind.BOOLEAN_KEYWORD; + case "STRING_KEYWORD" -> SyntaxKind.STRING_KEYWORD; + case "BYTE_KEYWORD" -> SyntaxKind.BYTE_KEYWORD; + case "XML_KEYWORD" -> SyntaxKind.XML_KEYWORD; + case "RE_KEYWORD" -> SyntaxKind.RE_KEYWORD; + case "JSON_KEYWORD" -> SyntaxKind.JSON_KEYWORD; + case "HANDLE_KEYWORD" -> SyntaxKind.HANDLE_KEYWORD; + case "ANY_KEYWORD" -> SyntaxKind.ANY_KEYWORD; + case "ANYDATA_KEYWORD" -> SyntaxKind.ANYDATA_KEYWORD; + case "NEVER_KEYWORD" -> SyntaxKind.NEVER_KEYWORD; + case "FORK_KEYWORD" -> SyntaxKind.FORK_KEYWORD; + case "TRAP_KEYWORD" -> SyntaxKind.TRAP_KEYWORD; + case "FOREACH_KEYWORD" -> SyntaxKind.FOREACH_KEYWORD; + case "IN_KEYWORD" -> SyntaxKind.IN_KEYWORD; + case "TABLE_KEYWORD" -> SyntaxKind.TABLE_KEYWORD; + case "KEY_KEYWORD" -> SyntaxKind.KEY_KEYWORD; + case "ERROR_KEYWORD" -> SyntaxKind.ERROR_KEYWORD; + case "LET_KEYWORD" -> SyntaxKind.LET_KEYWORD; + case "STREAM_KEYWORD" -> SyntaxKind.STREAM_KEYWORD; + case "READONLY_KEYWORD" -> SyntaxKind.READONLY_KEYWORD; + case "DISTINCT_KEYWORD" -> SyntaxKind.DISTINCT_KEYWORD; + case "FROM_KEYWORD" -> SyntaxKind.FROM_KEYWORD; + case "WHERE_KEYWORD" -> SyntaxKind.WHERE_KEYWORD; + case "SELECT_KEYWORD" -> SyntaxKind.SELECT_KEYWORD; + case "COLLECT_KEYWORD" -> SyntaxKind.COLLECT_KEYWORD; + case "ORDER_KEYWORD" -> SyntaxKind.ORDER_KEYWORD; + case "BY_KEYWORD" -> SyntaxKind.BY_KEYWORD; + case "GROUP_KEYWORD" -> SyntaxKind.GROUP_KEYWORD; + case "ASCENDING_KEYWORD" -> SyntaxKind.ASCENDING_KEYWORD; + case "DESCENDING_KEYWORD" -> SyntaxKind.DESCENDING_KEYWORD; + case "NEW_KEYWORD" -> SyntaxKind.NEW_KEYWORD; + case "START_KEYWORD" -> SyntaxKind.START_KEYWORD; + case "FLUSH_KEYWORD" -> SyntaxKind.FLUSH_KEYWORD; + case "WAIT_KEYWORD" -> SyntaxKind.WAIT_KEYWORD; + case "DO_KEYWORD" -> SyntaxKind.DO_KEYWORD; + case "TRANSACTION_KEYWORD" -> SyntaxKind.TRANSACTION_KEYWORD; + case "COMMIT_KEYWORD" -> SyntaxKind.COMMIT_KEYWORD; + case "RETRY_KEYWORD" -> SyntaxKind.RETRY_KEYWORD; + case "ROLLBACK_KEYWORD" -> SyntaxKind.ROLLBACK_KEYWORD; + case "TRANSACTIONAL_KEYWORD" -> SyntaxKind.TRANSACTIONAL_KEYWORD; + case "ISOLATED_KEYWORD" -> SyntaxKind.ISOLATED_KEYWORD; + case "ENUM_KEYWORD" -> SyntaxKind.ENUM_KEYWORD; + case "BASE16_KEYWORD" -> SyntaxKind.BASE16_KEYWORD; + case "BASE64_KEYWORD" -> SyntaxKind.BASE64_KEYWORD; + case "MATCH_KEYWORD" -> SyntaxKind.MATCH_KEYWORD; + case "CLASS_KEYWORD" -> SyntaxKind.CLASS_KEYWORD; + case "CONFLICT_KEYWORD" -> SyntaxKind.CONFLICT_KEYWORD; + case "LIMIT_KEYWORD" -> SyntaxKind.LIMIT_KEYWORD; + case "JOIN_KEYWORD" -> SyntaxKind.JOIN_KEYWORD; + case "EQUALS_KEYWORD" -> SyntaxKind.EQUALS_KEYWORD; + case "OUTER_KEYWORD" -> SyntaxKind.OUTER_KEYWORD; + case "CONFIGURABLE_KEYWORD" -> SyntaxKind.CONFIGURABLE_KEYWORD; + case "UNDERSCORE_KEYWORD" -> SyntaxKind.UNDERSCORE_KEYWORD; + default -> getXMLTemplateKind(kind); + }; } private static SyntaxKind getXMLTemplateKind(String kind) { - switch (kind) { - case "XML_ELEMENT": - return SyntaxKind.XML_ELEMENT; - case "XML_EMPTY_ELEMENT": - return SyntaxKind.XML_EMPTY_ELEMENT; - case "XML_ELEMENT_START_TAG": - return SyntaxKind.XML_ELEMENT_START_TAG; - case "XML_ELEMENT_END_TAG": - return SyntaxKind.XML_ELEMENT_END_TAG; - case "XML_TEXT": - return SyntaxKind.XML_TEXT; - case "XML_PI": - return SyntaxKind.XML_PI; - case "XML_ATTRIBUTE": - return SyntaxKind.XML_ATTRIBUTE; - case "XML_SIMPLE_NAME": - return SyntaxKind.XML_SIMPLE_NAME; - case "XML_QUALIFIED_NAME": - return SyntaxKind.XML_QUALIFIED_NAME; - case "INTERPOLATION": - return SyntaxKind.INTERPOLATION; - case "INTERPOLATION_START_TOKEN": - return SyntaxKind.INTERPOLATION_START_TOKEN; - case "XML_COMMENT": - return SyntaxKind.XML_COMMENT; - case "XML_COMMENT_START_TOKEN": - return SyntaxKind.XML_COMMENT_START_TOKEN; - case "XML_COMMENT_END_TOKEN": - return SyntaxKind.XML_COMMENT_END_TOKEN; - case "XML_TEXT_CONTENT": - return SyntaxKind.XML_TEXT_CONTENT; - case "XML_PI_START_TOKEN": - return SyntaxKind.XML_PI_START_TOKEN; - case "XML_PI_END_TOKEN": - return SyntaxKind.XML_PI_END_TOKEN; - case "XML_ATTRIBUTE_VALUE": - return SyntaxKind.XML_ATTRIBUTE_VALUE; - case "TEMPLATE_STRING": - return SyntaxKind.TEMPLATE_STRING; - case "XML_CDATA": - return SyntaxKind.XML_CDATA; - case "XML_CDATA_START_TOKEN": - return SyntaxKind.XML_CDATA_START_TOKEN; - case "XML_CDATA_END_TOKEN": - return SyntaxKind.XML_CDATA_END_TOKEN; - default: - return getRegExpTemplateKind(kind); - } + return switch (kind) { + case "XML_ELEMENT" -> SyntaxKind.XML_ELEMENT; + case "XML_EMPTY_ELEMENT" -> SyntaxKind.XML_EMPTY_ELEMENT; + case "XML_ELEMENT_START_TAG" -> SyntaxKind.XML_ELEMENT_START_TAG; + case "XML_ELEMENT_END_TAG" -> SyntaxKind.XML_ELEMENT_END_TAG; + case "XML_TEXT" -> SyntaxKind.XML_TEXT; + case "XML_PI" -> SyntaxKind.XML_PI; + case "XML_ATTRIBUTE" -> SyntaxKind.XML_ATTRIBUTE; + case "XML_SIMPLE_NAME" -> SyntaxKind.XML_SIMPLE_NAME; + case "XML_QUALIFIED_NAME" -> SyntaxKind.XML_QUALIFIED_NAME; + case "INTERPOLATION" -> SyntaxKind.INTERPOLATION; + case "INTERPOLATION_START_TOKEN" -> SyntaxKind.INTERPOLATION_START_TOKEN; + case "XML_COMMENT" -> SyntaxKind.XML_COMMENT; + case "XML_COMMENT_START_TOKEN" -> SyntaxKind.XML_COMMENT_START_TOKEN; + case "XML_COMMENT_END_TOKEN" -> SyntaxKind.XML_COMMENT_END_TOKEN; + case "XML_TEXT_CONTENT" -> SyntaxKind.XML_TEXT_CONTENT; + case "XML_PI_START_TOKEN" -> SyntaxKind.XML_PI_START_TOKEN; + case "XML_PI_END_TOKEN" -> SyntaxKind.XML_PI_END_TOKEN; + case "XML_ATTRIBUTE_VALUE" -> SyntaxKind.XML_ATTRIBUTE_VALUE; + case "TEMPLATE_STRING" -> SyntaxKind.TEMPLATE_STRING; + case "XML_CDATA" -> SyntaxKind.XML_CDATA; + case "XML_CDATA_START_TOKEN" -> SyntaxKind.XML_CDATA_START_TOKEN; + case "XML_CDATA_END_TOKEN" -> SyntaxKind.XML_CDATA_END_TOKEN; + default -> getRegExpTemplateKind(kind); + }; } private static SyntaxKind getRegExpTemplateKind(String kind) { - switch (kind) { - case "RE_SEQUENCE": - return SyntaxKind.RE_SEQUENCE; - case "RE_ATOM_QUANTIFIER": - return SyntaxKind.RE_ATOM_QUANTIFIER; - case "RE_ASSERTION": - return SyntaxKind.RE_ASSERTION; - case "DOLLAR_TOKEN": - return SyntaxKind.DOLLAR_TOKEN; - case "DOT_TOKEN": - return SyntaxKind.DOT_TOKEN; - case "RE_LITERAL_CHAR_DOT_OR_ESCAPE": - return SyntaxKind.RE_LITERAL_CHAR_DOT_OR_ESCAPE; - case "RE_LITERAL_CHAR": - return SyntaxKind.RE_LITERAL_CHAR; - case "RE_NUMERIC_ESCAPE": - return SyntaxKind.RE_NUMERIC_ESCAPE; - case "RE_CONTROL_ESCAPE": - return SyntaxKind.RE_CONTROL_ESCAPE; - case "RE_QUOTE_ESCAPE": - return SyntaxKind.RE_QUOTE_ESCAPE; - case "RE_SIMPLE_CHAR_CLASS_ESCAPE": - return SyntaxKind.RE_SIMPLE_CHAR_CLASS_ESCAPE; - case "RE_SIMPLE_CHAR_CLASS_CODE": - return SyntaxKind.RE_SIMPLE_CHAR_CLASS_CODE; - case "RE_UNICODE_PROPERTY_ESCAPE": - return SyntaxKind.RE_UNICODE_PROPERTY_ESCAPE; - case "RE_PROPERTY": - return SyntaxKind.RE_PROPERTY; - case "RE_UNICODE_SCRIPT": - return SyntaxKind.RE_UNICODE_SCRIPT; - case "RE_UNICODE_SCRIPT_START": - return SyntaxKind.RE_UNICODE_SCRIPT_START; - case "RE_UNICODE_PROPERTY_VALUE": - return SyntaxKind.RE_UNICODE_PROPERTY_VALUE; - case "RE_UNICODE_GENERAL_CATEGORY": - return SyntaxKind.RE_UNICODE_GENERAL_CATEGORY; - case "RE_UNICODE_GENERAL_CATEGORY_START": - return SyntaxKind.RE_UNICODE_GENERAL_CATEGORY_START; - case "RE_UNICODE_GENERAL_CATEGORY_NAME": - return SyntaxKind.RE_UNICODE_GENERAL_CATEGORY_NAME; - case "RE_CHARACTER_CLASS": - return SyntaxKind.RE_CHARACTER_CLASS; - case "RE_CHAR_SET_RANGE": - return SyntaxKind.RE_CHAR_SET_RANGE; - case "RE_CHAR_SET_RANGE_NO_DASH": - return SyntaxKind.RE_CHAR_SET_RANGE_NO_DASH; - case "RE_CHAR_SET_RANGE_WITH_RE_CHAR_SET": - return SyntaxKind.RE_CHAR_SET_RANGE_WITH_RE_CHAR_SET; - case "RE_CHAR_SET_RANGE_NO_DASH_WITH_RE_CHAR_SET": - return SyntaxKind.RE_CHAR_SET_RANGE_NO_DASH_WITH_RE_CHAR_SET; - case "RE_CHAR_SET_ATOM_WITH_RE_CHAR_SET_NO_DASH": - return SyntaxKind.RE_CHAR_SET_ATOM_WITH_RE_CHAR_SET_NO_DASH; - case "RE_CHAR_SET_ATOM_NO_DASH_WITH_RE_CHAR_SET_NO_DASH": - return SyntaxKind.RE_CHAR_SET_ATOM_NO_DASH_WITH_RE_CHAR_SET_NO_DASH; - case "RE_CAPTURING_GROUP": - return SyntaxKind.RE_CAPTURING_GROUP; - case "RE_FLAG_EXPR": - return SyntaxKind.RE_FLAG_EXPR; - case "RE_FLAGS_ON_OFF": - return SyntaxKind.RE_FLAGS_ON_OFF; - case "RE_FLAGS": - return SyntaxKind.RE_FLAGS; - case "RE_FLAGS_VALUE": - return SyntaxKind.RE_FLAGS_VALUE; - case "RE_QUANTIFIER": - return SyntaxKind.RE_QUANTIFIER; - case "RE_BRACED_QUANTIFIER": - return SyntaxKind.RE_BRACED_QUANTIFIER; - case "DIGIT": - return SyntaxKind.DIGIT; - case "ESCAPED_MINUS_TOKEN": - return SyntaxKind.ESCAPED_MINUS_TOKEN; - default: - return getDocumentationKind(kind); - } + return switch (kind) { + case "RE_SEQUENCE" -> SyntaxKind.RE_SEQUENCE; + case "RE_ATOM_QUANTIFIER" -> SyntaxKind.RE_ATOM_QUANTIFIER; + case "RE_ASSERTION" -> SyntaxKind.RE_ASSERTION; + case "DOLLAR_TOKEN" -> SyntaxKind.DOLLAR_TOKEN; + case "DOT_TOKEN" -> SyntaxKind.DOT_TOKEN; + case "RE_LITERAL_CHAR_DOT_OR_ESCAPE" -> SyntaxKind.RE_LITERAL_CHAR_DOT_OR_ESCAPE; + case "RE_LITERAL_CHAR" -> SyntaxKind.RE_LITERAL_CHAR; + case "RE_NUMERIC_ESCAPE" -> SyntaxKind.RE_NUMERIC_ESCAPE; + case "RE_CONTROL_ESCAPE" -> SyntaxKind.RE_CONTROL_ESCAPE; + case "RE_QUOTE_ESCAPE" -> SyntaxKind.RE_QUOTE_ESCAPE; + case "RE_SIMPLE_CHAR_CLASS_ESCAPE" -> SyntaxKind.RE_SIMPLE_CHAR_CLASS_ESCAPE; + case "RE_SIMPLE_CHAR_CLASS_CODE" -> SyntaxKind.RE_SIMPLE_CHAR_CLASS_CODE; + case "RE_UNICODE_PROPERTY_ESCAPE" -> SyntaxKind.RE_UNICODE_PROPERTY_ESCAPE; + case "RE_PROPERTY" -> SyntaxKind.RE_PROPERTY; + case "RE_UNICODE_SCRIPT" -> SyntaxKind.RE_UNICODE_SCRIPT; + case "RE_UNICODE_SCRIPT_START" -> SyntaxKind.RE_UNICODE_SCRIPT_START; + case "RE_UNICODE_PROPERTY_VALUE" -> SyntaxKind.RE_UNICODE_PROPERTY_VALUE; + case "RE_UNICODE_GENERAL_CATEGORY" -> SyntaxKind.RE_UNICODE_GENERAL_CATEGORY; + case "RE_UNICODE_GENERAL_CATEGORY_START" -> SyntaxKind.RE_UNICODE_GENERAL_CATEGORY_START; + case "RE_UNICODE_GENERAL_CATEGORY_NAME" -> SyntaxKind.RE_UNICODE_GENERAL_CATEGORY_NAME; + case "RE_CHARACTER_CLASS" -> SyntaxKind.RE_CHARACTER_CLASS; + case "RE_CHAR_SET_RANGE" -> SyntaxKind.RE_CHAR_SET_RANGE; + case "RE_CHAR_SET_RANGE_NO_DASH" -> SyntaxKind.RE_CHAR_SET_RANGE_NO_DASH; + case "RE_CHAR_SET_RANGE_WITH_RE_CHAR_SET" -> SyntaxKind.RE_CHAR_SET_RANGE_WITH_RE_CHAR_SET; + case "RE_CHAR_SET_RANGE_NO_DASH_WITH_RE_CHAR_SET" -> SyntaxKind.RE_CHAR_SET_RANGE_NO_DASH_WITH_RE_CHAR_SET; + case "RE_CHAR_SET_ATOM_WITH_RE_CHAR_SET_NO_DASH" -> SyntaxKind.RE_CHAR_SET_ATOM_WITH_RE_CHAR_SET_NO_DASH; + case "RE_CHAR_SET_ATOM_NO_DASH_WITH_RE_CHAR_SET_NO_DASH" -> + SyntaxKind.RE_CHAR_SET_ATOM_NO_DASH_WITH_RE_CHAR_SET_NO_DASH; + case "RE_CAPTURING_GROUP" -> SyntaxKind.RE_CAPTURING_GROUP; + case "RE_FLAG_EXPR" -> SyntaxKind.RE_FLAG_EXPR; + case "RE_FLAGS_ON_OFF" -> SyntaxKind.RE_FLAGS_ON_OFF; + case "RE_FLAGS" -> SyntaxKind.RE_FLAGS; + case "RE_FLAGS_VALUE" -> SyntaxKind.RE_FLAGS_VALUE; + case "RE_QUANTIFIER" -> SyntaxKind.RE_QUANTIFIER; + case "RE_BRACED_QUANTIFIER" -> SyntaxKind.RE_BRACED_QUANTIFIER; + case "DIGIT" -> SyntaxKind.DIGIT; + case "ESCAPED_MINUS_TOKEN" -> SyntaxKind.ESCAPED_MINUS_TOKEN; + default -> getDocumentationKind(kind); + }; } private static SyntaxKind getDocumentationKind(String kind) { - switch (kind) { + return switch (kind) { // Documentation reference - case "TYPE_DOC_REFERENCE_TOKEN": - return SyntaxKind.TYPE_DOC_REFERENCE_TOKEN; - case "SERVICE_DOC_REFERENCE_TOKEN": - return SyntaxKind.SERVICE_DOC_REFERENCE_TOKEN; - case "VARIABLE_DOC_REFERENCE_TOKEN": - return SyntaxKind.VARIABLE_DOC_REFERENCE_TOKEN; - case "VAR_DOC_REFERENCE_TOKEN": - return SyntaxKind.VAR_DOC_REFERENCE_TOKEN; - case "ANNOTATION_DOC_REFERENCE_TOKEN": - return SyntaxKind.ANNOTATION_DOC_REFERENCE_TOKEN; - case "MODULE_DOC_REFERENCE_TOKEN": - return SyntaxKind.MODULE_DOC_REFERENCE_TOKEN; - case "FUNCTION_DOC_REFERENCE_TOKEN": - return SyntaxKind.FUNCTION_DOC_REFERENCE_TOKEN; - case "PARAMETER_DOC_REFERENCE_TOKEN": - return SyntaxKind.PARAMETER_DOC_REFERENCE_TOKEN; - case "CONST_DOC_REFERENCE_TOKEN": - return SyntaxKind.CONST_DOC_REFERENCE_TOKEN; + case "TYPE_DOC_REFERENCE_TOKEN" -> SyntaxKind.TYPE_DOC_REFERENCE_TOKEN; + case "SERVICE_DOC_REFERENCE_TOKEN" -> SyntaxKind.SERVICE_DOC_REFERENCE_TOKEN; + case "VARIABLE_DOC_REFERENCE_TOKEN" -> SyntaxKind.VARIABLE_DOC_REFERENCE_TOKEN; + case "VAR_DOC_REFERENCE_TOKEN" -> SyntaxKind.VAR_DOC_REFERENCE_TOKEN; + case "ANNOTATION_DOC_REFERENCE_TOKEN" -> SyntaxKind.ANNOTATION_DOC_REFERENCE_TOKEN; + case "MODULE_DOC_REFERENCE_TOKEN" -> SyntaxKind.MODULE_DOC_REFERENCE_TOKEN; + case "FUNCTION_DOC_REFERENCE_TOKEN" -> SyntaxKind.FUNCTION_DOC_REFERENCE_TOKEN; + case "PARAMETER_DOC_REFERENCE_TOKEN" -> SyntaxKind.PARAMETER_DOC_REFERENCE_TOKEN; + case "CONST_DOC_REFERENCE_TOKEN" -> SyntaxKind.CONST_DOC_REFERENCE_TOKEN; // Documentation - case "MARKDOWN_DOCUMENTATION": - return SyntaxKind.MARKDOWN_DOCUMENTATION; - case "MARKDOWN_DOCUMENTATION_LINE": - return SyntaxKind.MARKDOWN_DOCUMENTATION_LINE; - case "MARKDOWN_REFERENCE_DOCUMENTATION_LINE": - return SyntaxKind.MARKDOWN_REFERENCE_DOCUMENTATION_LINE; - case "MARKDOWN_PARAMETER_DOCUMENTATION_LINE": - return SyntaxKind.MARKDOWN_PARAMETER_DOCUMENTATION_LINE; - case "MARKDOWN_RETURN_PARAMETER_DOCUMENTATION_LINE": - return SyntaxKind.MARKDOWN_RETURN_PARAMETER_DOCUMENTATION_LINE; - case "MARKDOWN_DEPRECATION_DOCUMENTATION_LINE": - return SyntaxKind.MARKDOWN_DEPRECATION_DOCUMENTATION_LINE; - case "MARKDOWN_CODE_LINE": - return SyntaxKind.MARKDOWN_CODE_LINE; - case "DOCUMENTATION_DESCRIPTION": - return SyntaxKind.DOCUMENTATION_DESCRIPTION; - case "BALLERINA_NAME_REFERENCE": - return SyntaxKind.BALLERINA_NAME_REFERENCE; - case "PARAMETER_NAME": - return SyntaxKind.PARAMETER_NAME; - case "DEPRECATION_LITERAL": - return SyntaxKind.DEPRECATION_LITERAL; - case "DOCUMENTATION_STRING": - return SyntaxKind.DOCUMENTATION_STRING; - case "CODE_CONTENT": - return SyntaxKind.CODE_CONTENT; - case "INLINE_CODE_REFERENCE": - return SyntaxKind.INLINE_CODE_REFERENCE; - case "MARKDOWN_CODE_BLOCK": - return SyntaxKind.MARKDOWN_CODE_BLOCK; - + case "MARKDOWN_DOCUMENTATION" -> SyntaxKind.MARKDOWN_DOCUMENTATION; + case "MARKDOWN_DOCUMENTATION_LINE" -> SyntaxKind.MARKDOWN_DOCUMENTATION_LINE; + case "MARKDOWN_REFERENCE_DOCUMENTATION_LINE" -> SyntaxKind.MARKDOWN_REFERENCE_DOCUMENTATION_LINE; + case "MARKDOWN_PARAMETER_DOCUMENTATION_LINE" -> SyntaxKind.MARKDOWN_PARAMETER_DOCUMENTATION_LINE; + case "MARKDOWN_RETURN_PARAMETER_DOCUMENTATION_LINE" -> + SyntaxKind.MARKDOWN_RETURN_PARAMETER_DOCUMENTATION_LINE; + case "MARKDOWN_DEPRECATION_DOCUMENTATION_LINE" -> SyntaxKind.MARKDOWN_DEPRECATION_DOCUMENTATION_LINE; + case "MARKDOWN_CODE_LINE" -> SyntaxKind.MARKDOWN_CODE_LINE; + case "DOCUMENTATION_DESCRIPTION" -> SyntaxKind.DOCUMENTATION_DESCRIPTION; + case "BALLERINA_NAME_REFERENCE" -> SyntaxKind.BALLERINA_NAME_REFERENCE; + case "PARAMETER_NAME" -> SyntaxKind.PARAMETER_NAME; + case "DEPRECATION_LITERAL" -> SyntaxKind.DEPRECATION_LITERAL; + case "DOCUMENTATION_STRING" -> SyntaxKind.DOCUMENTATION_STRING; + case "CODE_CONTENT" -> SyntaxKind.CODE_CONTENT; + case "INLINE_CODE_REFERENCE" -> SyntaxKind.INLINE_CODE_REFERENCE; + case "MARKDOWN_CODE_BLOCK" -> SyntaxKind.MARKDOWN_CODE_BLOCK; + // Unsupported - default: - throw new UnsupportedOperationException("cannot find syntax kind: " + kind); - } + default -> throw new UnsupportedOperationException("cannot find syntax kind: " + kind); + }; } } diff --git a/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/SyntaxTreeJSONGenerator.java b/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/SyntaxTreeJSONGenerator.java index e966fdcd68d6..d2f1bad77efe 100644 --- a/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/SyntaxTreeJSONGenerator.java +++ b/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/SyntaxTreeJSONGenerator.java @@ -57,7 +57,7 @@ * * @since 1.2.0 */ -public class SyntaxTreeJSONGenerator { +public final class SyntaxTreeJSONGenerator { /* * Change the below two constants as required, depending on the type of test. @@ -67,6 +67,9 @@ public class SyntaxTreeJSONGenerator { private static final PrintStream STANDARD_OUT = System.out; private static final Path RESOURCE_DIRECTORY = Paths.get("src/test/resources/"); + private SyntaxTreeJSONGenerator() { + } + public static void main(String[] args) throws IOException { // Using a string source as input // generateJSON("a 7", ParserRuleContext.EXPRESSION); diff --git a/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/TestParser.java b/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/TestParser.java index 302b709022b0..c3e6344bf0dc 100644 --- a/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/TestParser.java +++ b/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/TestParser.java @@ -30,10 +30,13 @@ /** * Test the parser. */ -public class TestParser { +public final class TestParser { private static final PrintStream OUT = System.out; + private TestParser() { + } + public static void main(String[] args) throws IOException { String path = TestParser.class.getClassLoader().getResource("test_parser.bal").getPath(); String content = new String(Files.readAllBytes(Paths.get(path)), StandardCharsets.UTF_8); diff --git a/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/diagnostics/DiagnosticCodeTest.java b/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/diagnostics/DiagnosticCodeTest.java index 4d99ac7673ca..fb7f70810c4d 100644 --- a/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/diagnostics/DiagnosticCodeTest.java +++ b/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/diagnostics/DiagnosticCodeTest.java @@ -73,7 +73,7 @@ private void validateDiagnosticUniqueness(DiagnosticCode[] codes) { } } - private String arrayToString(List listOfStrings) { + private String arrayToString(List listOfStrings) { return String.join(", ", listOfStrings); } } diff --git a/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/tree/DiagnosticsAPITest.java b/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/tree/DiagnosticsAPITest.java index d4e7d25edacd..9e758aff0169 100644 --- a/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/tree/DiagnosticsAPITest.java +++ b/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/tree/DiagnosticsAPITest.java @@ -116,6 +116,7 @@ public function main() { Assert.assertFalse(lineRangeList.isEmpty()); } + @Override protected SyntaxTree parseFile(String sourceFileName) { return super.parseFile(Paths.get("diagnostics").resolve(sourceFileName)); } diff --git a/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/tree/NodeListAPITest.java b/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/tree/NodeListAPITest.java index 4569e5d807af..0ab97184ae3f 100644 --- a/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/tree/NodeListAPITest.java +++ b/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/tree/NodeListAPITest.java @@ -105,6 +105,7 @@ public void testAddMethod() { statementNodes::add, "node_list_test_07.json"); } + @Override protected SyntaxTree parseFile(String sourceFileName) { return super.parseFile(Paths.get("node_list_api").resolve(sourceFileName)); } diff --git a/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/tree/NodeVisitorTest.java b/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/tree/NodeVisitorTest.java index d2d0d78b2254..d13c8942314e 100644 --- a/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/tree/NodeVisitorTest.java +++ b/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/tree/NodeVisitorTest.java @@ -70,6 +70,7 @@ public void testAssignmentStmtNodeVisit() { private static class TokenVisitor extends NodeVisitor { List tokenList = new ArrayList<>(); + @Override public void visit(Token token) { tokenList.add(token.kind()); } @@ -83,6 +84,7 @@ public void visit(Token token) { private static class AssignmentStmtVisitor extends NodeVisitor { List stmtList = new ArrayList<>(); + @Override public void visit(AssignmentStatementNode assignmentStatement) { stmtList.add(assignmentStatement); } diff --git a/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/tree/SyntaxTreeModifierTest.java b/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/tree/SyntaxTreeModifierTest.java index 64b6a6967306..068d2e2139d2 100644 --- a/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/tree/SyntaxTreeModifierTest.java +++ b/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/tree/SyntaxTreeModifierTest.java @@ -223,18 +223,13 @@ public BinaryExpressionNode transform(BinaryExpressionNode binaryExprNode) { Token newOperator; Token oldOperator = binaryExprNode.operator(); - switch (oldOperator.kind()) { - case PLUS_TOKEN: - newOperator = NodeFactory.createToken(SyntaxKind.MINUS_TOKEN, oldOperator.leadingMinutiae(), - oldOperator.trailingMinutiae()); - break; - case ASTERISK_TOKEN: - newOperator = NodeFactory.createToken(SyntaxKind.SLASH_TOKEN, oldOperator.leadingMinutiae(), - oldOperator.trailingMinutiae()); - break; - default: - newOperator = oldOperator; - } + newOperator = switch (oldOperator.kind()) { + case PLUS_TOKEN -> NodeFactory.createToken(SyntaxKind.MINUS_TOKEN, oldOperator.leadingMinutiae(), + oldOperator.trailingMinutiae()); + case ASTERISK_TOKEN -> NodeFactory.createToken(SyntaxKind.SLASH_TOKEN, oldOperator.leadingMinutiae(), + oldOperator.trailingMinutiae()); + default -> oldOperator; + }; return binaryExprNode.modify().withOperator(newOperator).withLhsExpr(newLHSExpr).withRhsExpr(newRHSExpr) .apply(); diff --git a/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/tree/nodeparser/ParseImportDeclarationTest.java b/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/tree/nodeparser/ParseImportDeclarationTest.java index 0a9b6f917455..a24f0a592850 100644 --- a/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/tree/nodeparser/ParseImportDeclarationTest.java +++ b/compiler/ballerina-parser/src/test/java/io/ballerinalang/compiler/parser/test/tree/nodeparser/ParseImportDeclarationTest.java @@ -57,6 +57,7 @@ public void testWithImportDeclRecovery() { ImportDeclarationNode importDeclNode = NodeParser.parseImportDeclaration("%import foobar/foo.bar.baz qux;;"); Assert.assertEquals(importDeclNode.kind(), SyntaxKind.IMPORT_DECLARATION); Assert.assertTrue(importDeclNode.hasDiagnostics()); - Assert.assertEquals(importDeclNode.toString(), " INVALID[%]import foobar/foo.bar.baz MISSING[as]qux; INVALID[;]"); + Assert.assertEquals( + importDeclNode.toString(), " INVALID[%]import foobar/foo.bar.baz MISSING[as]qux; INVALID[;]"); } } diff --git a/compiler/ballerina-tools-api/src/main/java/io/ballerina/tools/diagnostics/DiagnosticFactory.java b/compiler/ballerina-tools-api/src/main/java/io/ballerina/tools/diagnostics/DiagnosticFactory.java index d23235a4db76..71ec305cecf9 100644 --- a/compiler/ballerina-tools-api/src/main/java/io/ballerina/tools/diagnostics/DiagnosticFactory.java +++ b/compiler/ballerina-tools-api/src/main/java/io/ballerina/tools/diagnostics/DiagnosticFactory.java @@ -25,7 +25,7 @@ * * @since 2.0.0 */ -public class DiagnosticFactory { +public final class DiagnosticFactory { private DiagnosticFactory() { } diff --git a/compiler/ballerina-tools-api/src/main/java/io/ballerina/tools/diagnostics/DiagnosticInfo.java b/compiler/ballerina-tools-api/src/main/java/io/ballerina/tools/diagnostics/DiagnosticInfo.java index e685bd37a14d..47bf8ba5b203 100644 --- a/compiler/ballerina-tools-api/src/main/java/io/ballerina/tools/diagnostics/DiagnosticInfo.java +++ b/compiler/ballerina-tools-api/src/main/java/io/ballerina/tools/diagnostics/DiagnosticInfo.java @@ -68,8 +68,7 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (obj instanceof DiagnosticInfo) { - DiagnosticInfo that = (DiagnosticInfo) obj; + if (obj instanceof DiagnosticInfo that) { if (this.code != null) { return this.code.equals(that.code) && this.messageFormat.equals(that.messageFormat) && this.severity.equals(that.severity); diff --git a/compiler/ballerina-tools-api/src/main/java/io/ballerina/tools/text/TextDocuments.java b/compiler/ballerina-tools-api/src/main/java/io/ballerina/tools/text/TextDocuments.java index dfbe48cd8e36..c80cf9ac88fc 100644 --- a/compiler/ballerina-tools-api/src/main/java/io/ballerina/tools/text/TextDocuments.java +++ b/compiler/ballerina-tools-api/src/main/java/io/ballerina/tools/text/TextDocuments.java @@ -20,7 +20,7 @@ /** * Contains a set of helper methods. */ -public class TextDocuments { +public final class TextDocuments { private TextDocuments() { } diff --git a/compiler/ballerina-treegen/src/main/java/io/ballerinalang/compiler/internal/treegen/TreeGen.java b/compiler/ballerina-treegen/src/main/java/io/ballerinalang/compiler/internal/treegen/TreeGen.java index 11be9b79dd91..44dd8a7631af 100644 --- a/compiler/ballerina-treegen/src/main/java/io/ballerinalang/compiler/internal/treegen/TreeGen.java +++ b/compiler/ballerina-treegen/src/main/java/io/ballerinalang/compiler/internal/treegen/TreeGen.java @@ -38,7 +38,6 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; -import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; @@ -55,7 +54,10 @@ * * @since 1.3.0 */ -public class TreeGen { +public final class TreeGen { + + private TreeGen() { + } public static void main(String[] args) { // 1) Load the configuration properties @@ -108,8 +110,7 @@ private static InputStream getSyntaxTreeStream(TreeGenConfig config) { private static HashMap getNodeMetadataMap(TreeGenConfig config) { try (InputStreamReader reader = new InputStreamReader(getNodeMetadataMapStream(config), StandardCharsets.UTF_8)) { - Type mapType = new TypeToken>() { }.getType(); - return new Gson().fromJson(reader, mapType); + return new Gson().fromJson(reader, new TypeToken<>() { }); } catch (Throwable e) { throw new TreeGenException("Failed to parse syntax node metadata. Reason: " + e.getMessage(), e); } diff --git a/compiler/ballerina-treegen/src/main/java/io/ballerinalang/compiler/internal/treegen/targets/node/AbstractNodeTarget.java b/compiler/ballerina-treegen/src/main/java/io/ballerinalang/compiler/internal/treegen/targets/node/AbstractNodeTarget.java index 3f4509c5721a..47839a859c20 100644 --- a/compiler/ballerina-treegen/src/main/java/io/ballerinalang/compiler/internal/treegen/targets/node/AbstractNodeTarget.java +++ b/compiler/ballerina-treegen/src/main/java/io/ballerinalang/compiler/internal/treegen/targets/node/AbstractNodeTarget.java @@ -27,7 +27,6 @@ import java.util.HashMap; import java.util.List; -import java.util.stream.Collectors; /** * The class {@code AbstractNodeTarget} represent a generic entity that converts a @@ -57,7 +56,7 @@ public List execute(SyntaxTree syntaxTree, HashMap generateNodeClass(syntaxNode, nodeMetadataMap)) .map(treeNodeClass -> getSourceText(treeNodeClass, getOutputDir(), getClassName(treeNodeClass))) - .collect(Collectors.toList()); + .toList(); } private TreeNodeClass generateNodeClass(SyntaxNode syntaxNode, HashMap generateNodeClasses(SyntaxTree syntaxTree, .stream() .map(syntaxNode -> convertToTreeNodeClass(syntaxNode, getPackageName(), new ArrayList<>(), nodeMetadataMap)) - .collect(Collectors.toList()); + .toList(); } protected abstract String getPackageName(); diff --git a/compiler/linter-plugin/src/test/java/io/ballerina/compiler/linter/codeactions/test/CodeActionUtils.java b/compiler/linter-plugin/src/test/java/io/ballerina/compiler/linter/codeactions/test/CodeActionUtils.java index 4e89e10dd7f6..ab66d1c39fa8 100644 --- a/compiler/linter-plugin/src/test/java/io/ballerina/compiler/linter/codeactions/test/CodeActionUtils.java +++ b/compiler/linter-plugin/src/test/java/io/ballerina/compiler/linter/codeactions/test/CodeActionUtils.java @@ -38,18 +38,20 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; -import java.util.stream.Collectors; /** * Helper methods for writing code action tests. * * @since 2.0.0 */ -public class CodeActionUtils { +public final class CodeActionUtils { public static final Path RES_DIR = Paths.get("src/test/resources/").toAbsolutePath(); public static final String NEW = ".new"; + private CodeActionUtils() { + } + /** * Get codeactions for the provided cursor position in the provided source file. * @@ -82,7 +84,7 @@ public static List getCodeActions(Project project, Path filePath // Get codeactions for the diagnostic return codeActionManager.codeActions(context).getCodeActions().stream(); }) - .collect(Collectors.toList()); + .toList(); } /** @@ -105,7 +107,7 @@ public static List executeCodeAction(Project project, Path filePat Gson gson = new Gson(); List codeActionArguments = codeAction.getArguments().stream() .map(arg -> CodeActionArgument.from(gson.toJsonTree(arg))) - .collect(Collectors.toList()); + .toList(); CodeActionExecutionContext executionContext = CodeActionExecutionContextImpl.from( filePath.toUri().toString(), diff --git a/distribution/zip/jballerina-tools/build.gradle b/distribution/zip/jballerina-tools/build.gradle index 28dee65f7024..71399d71d782 100644 --- a/distribution/zip/jballerina-tools/build.gradle +++ b/distribution/zip/jballerina-tools/build.gradle @@ -412,7 +412,7 @@ tasks.register('generateDocs', JavaExec) { outputs.dir("$buildDir/api-docs") outputs.cacheIf { true } systemProperty("ballerina.home", "$buildDir") - classpath = files(pathingJar.archivePath) + classpath = files(pathingJar.archiveFile) mainClass = 'org.ballerinalang.plugin.gradle.doc.DocerinaGen' args("$buildDir/api-docs") } diff --git a/docs/bir-spec/src/main/java/org/ballerinalang/birspec/BIRSpecGenerator.java b/docs/bir-spec/src/main/java/org/ballerinalang/birspec/BIRSpecGenerator.java index 9196d2c4ee2d..d2f07e8064a5 100644 --- a/docs/bir-spec/src/main/java/org/ballerinalang/birspec/BIRSpecGenerator.java +++ b/docs/bir-spec/src/main/java/org/ballerinalang/birspec/BIRSpecGenerator.java @@ -30,11 +30,14 @@ /** * Generate BIR spec doc. */ -public class BIRSpecGenerator { +public final class BIRSpecGenerator { private static final String BIR_SPEC_FILE = "/kaitai/bir.ksy"; private static final Yaml yaml = new Yaml(); + private BIRSpecGenerator() { + } + public static void main(String[] args) throws IOException { try (PrintWriter out = new PrintWriter("../compiler/bir-spec.md")) { generateBirSpecMd(out); @@ -57,13 +60,14 @@ private static Object parseResourceAsYAML() throws IOException { } private static String readResourceAsString(String uri) throws IOException { - InputStream inputStream = BIRSpecGenerator.class.getResourceAsStream(uri); - ByteArrayOutputStream result = new ByteArrayOutputStream(); - byte[] buffer = new byte[1024]; - int length; - while ((length = inputStream.read(buffer)) != -1) { - result.write(buffer, 0, length); - } + try (InputStream inputStream = BIRSpecGenerator.class.getResourceAsStream(uri)) { + ByteArrayOutputStream result = new ByteArrayOutputStream(); + byte[] buffer = new byte[1024]; + int length; + while ((length = inputStream.read(buffer)) != -1) { + result.write(buffer, 0, length); + } return result.toString(StandardCharsets.UTF_8); + } } } diff --git a/docs/bir-spec/src/test/java/org/ballerinalang/birspec/BIRTestUtils.java b/docs/bir-spec/src/test/java/org/ballerinalang/birspec/BIRTestUtils.java index 1a6d10391e95..40b517824cb1 100644 --- a/docs/bir-spec/src/test/java/org/ballerinalang/birspec/BIRTestUtils.java +++ b/docs/bir-spec/src/test/java/org/ballerinalang/birspec/BIRTestUtils.java @@ -50,12 +50,12 @@ import java.util.List; import java.util.Map; import java.util.Set; -import java.util.stream.Collectors; +import java.util.stream.Stream; /** * Utility methods to help with testing BIR model. */ -class BIRTestUtils { +final class BIRTestUtils { private static final String TEST_RESOURCES_ROOT = "src/test/resources/test-src"; private static final Path TEST_RESOURCES_ROOT_PATH = Paths.get(TEST_RESOURCES_ROOT); @@ -63,6 +63,9 @@ class BIRTestUtils { private static final String LANG_LIB_TEST_SRC_ROOT = "../../langlib/langlib-test/src/test/resources/test-src"; private static final Path LANG_LIB_TEST_ROOT_PATH = Paths.get(LANG_LIB_TEST_SRC_ROOT); + private BIRTestUtils() { + } + @DataProvider(name = "createTestSources") public static Object[][] createTestDataProvider() throws IOException { assert LANG_LIB_TEST_ROOT_PATH.toFile().exists(); @@ -79,11 +82,12 @@ public static Object[][] createTestDataProvider() throws IOException { } private static List findBallerinaSourceFiles(Path testSourcesPath) throws IOException { - return Files.walk(testSourcesPath) - .filter(file -> Files.isRegularFile(file)) - .map(file -> file.toAbsolutePath().normalize().toString()) - .filter(file -> file.endsWith(".bal") && !file.contains("negative") && !file.contains("subtype")) - .collect(Collectors.toList()); + try (Stream paths = Files.walk(testSourcesPath)) { + return paths.filter(file -> Files.isRegularFile(file)) + .map(file -> file.toAbsolutePath().normalize().toString()) + .filter(file -> file.endsWith(".bal") && !file.contains("negative") && !file.contains("subtype")) + .toList(); + } } static void validateBIRSpec(String testSource) { @@ -649,13 +653,11 @@ private static void assertType(Bir.ConstantPoolEntry constantPoolEntry, BType ex assertFlags(typeInfo.typeFlag(), expectedValue.flags); KaitaiStruct typeStructure = typeInfo.typeStructure(); - if (typeStructure instanceof Bir.TypeObjectOrService) { - Bir.TypeObjectOrService objectOrService = (Bir.TypeObjectOrService) typeStructure; + if (typeStructure instanceof Bir.TypeObjectOrService objectOrService) { BTypeIdSet expTypeIdSet = ((BObjectType) expectedValue.tsymbol.type).typeIdSet; Bir.TypeId actualTypeIdSet = objectOrService.typeIds(); assertDistinctTypeIds(expTypeIdSet, actualTypeIdSet, constantPoolEntry._parent()); - } else if (typeStructure instanceof Bir.TypeError) { - Bir.TypeError errorType = (Bir.TypeError) typeStructure; + } else if (typeStructure instanceof Bir.TypeError errorType) { BTypeIdSet expTypeIdSet = ((BErrorType) expectedValue.tsymbol.type).typeIdSet; Bir.TypeId actualTypeIdSet = errorType.typeIds(); assertDistinctTypeIds(expTypeIdSet, actualTypeIdSet, constantPoolEntry._parent()); @@ -668,14 +670,12 @@ private static void assertDistinctTypeIds(BTypeIdSet expTypeIdSet, Bir.TypeId ac Assert.assertEquals(actualTypeIdSet.secondaryTypeIdCount(), expTypeIdSet.getSecondary().size()); ArrayList primaryTypeId = actualTypeIdSet.primaryTypeId(); - for (int i = 0; i < primaryTypeId.size(); i++) { - Bir.TypeIdSet typeId = primaryTypeId.get(i); + for (Bir.TypeIdSet typeId : primaryTypeId) { Assert.assertTrue(containsTypeId(typeId, expTypeIdSet.getPrimary(), constantPoolSet)); } ArrayList secondaryTypeId = actualTypeIdSet.secondaryTypeId(); - for (int i = 0; i < secondaryTypeId.size(); i++) { - Bir.TypeIdSet typeId = secondaryTypeId.get(i); + for (Bir.TypeIdSet typeId : secondaryTypeId) { Assert.assertTrue(containsTypeId(typeId, expTypeIdSet.getSecondary(), constantPoolSet)); } } diff --git a/docs/language-server/CompilerPluginCodeActions.md b/docs/language-server/CompilerPluginCodeActions.md index df3362171c3b..043d3b40f834 100644 --- a/docs/language-server/CompilerPluginCodeActions.md +++ b/docs/language-server/CompilerPluginCodeActions.md @@ -321,7 +321,7 @@ public class CodeActionUtils { // Get codeactions for the diagnostic return codeActionManager.codeActions(context).getCodeActions().stream(); }) - .collect(Collectors.toList()); + .toList(); } } ``` @@ -387,7 +387,7 @@ public class CodeActionUtils { // JsonElements to objects via deserialization. List codeActionArguments = codeAction.getArguments().stream() .map(arg -> CodeActionArgument.from(GSON.toJsonTree(arg))) - .collect(Collectors.toList()); + .toList(); CodeActionExecutionContext executionContext = CodeActionExecutionContextImpl.from( filePath.toUri().toString(), diff --git a/gradle/ballerinaLangLibBuild.gradle b/gradle/ballerinaLangLibBuild.gradle index 87181cd743ea..08e28397e99b 100644 --- a/gradle/ballerinaLangLibBuild.gradle +++ b/gradle/ballerinaLangLibBuild.gradle @@ -40,23 +40,41 @@ dependencies { balaCreat project(':lib-creator') } +@CacheableTask class BallerinaLangLibBuildTask extends JavaExec { - @Internal def projectDir = '' - @Internal def distCache = '' + @Internal def projectDir = project.layout.buildDirectory.dir("ballerina-src") + @Internal def distCache = project.layout.buildDirectory @Internal def pkgName = project.name @Internal def skipBootstrap = 'false' + @Internal def outputJarFileName = '' + + @InputFiles + @PathSensitive(PathSensitivity.RELATIVE) + def srcDir = project.files("src/main/ballerina") + + @OutputFile + def zipFile = projectDir.map{ it.file("target/" + project.ext.modName + ".zip") } + + @OutputFile + def jarFile = projectDir.map{ it.file("target/" + outputJarFileName + ".jar") } + + @Override @Internal + List getJvmArgumentProviders() { + return super.getJvmArgumentProviders() + } BallerinaLangLibBuildTask() { -// setMain('org.ballerinalang.stdlib.utils.BuildLangLib') - getMainClass().set('org.ballerinalang.stdlib.utils.BuildLangLib') + setMainClass('org.ballerinalang.stdlib.utils.BuildLangLib') + standardOutput = System.out + errorOutput = System.err } @Override void exec() { // jvmArgs '-Xdebug', '-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005' def args = [] - args << projectDir - args << distCache + args << projectDir.get().toString() + args << distCache.get().toString() args << pkgName args << skipBootstrap @@ -101,19 +119,11 @@ tasks.register('copyBallerinaProject', Copy) { } tasks.register('ballerinaLangLibBuild', BallerinaLangLibBuildTask) { - standardOutput = System.out - errorOutput = System.err - projectDir = project.buildDir.toString() + "/ballerina-src" // + modName - distCache = project.buildDir.toString() - classpath = project.configurations.balaCreat + classpath = files(project.configurations.balaCreat, jar.archiveFile) + outputJarFileName = jarFileName dependsOn copyBallerinaProject dependsOn createDistributionCache dependsOn jar - inputs.files("src/main/ballerina") - outputs.file("$buildDir/ballerina-src/target/" + modName + ".zip") - outputs.file("$buildDir/ballerina-src/target/${jarFileName}.jar") - outputs.cacheIf { true } - classpath += files(jar.archivePath) } artifacts { diff --git a/gradle/ballerinaNativeStdLibBuild.gradle b/gradle/ballerinaNativeStdLibBuild.gradle index f58c2326ac53..1722ca8a25cf 100644 --- a/gradle/ballerinaNativeStdLibBuild.gradle +++ b/gradle/ballerinaNativeStdLibBuild.gradle @@ -67,21 +67,40 @@ dependencies { distributionBala project(path: ':ballerina-lang:runtime', configuration: 'distributionBala') } +@CacheableTask class BallerinaLangLibBuildTask extends JavaExec { - @Internal def projectDir = '' - @Internal def distCache = '' + @Internal def projectDir = project.layout.buildDirectory.dir("ballerina-src") + @Internal def distCache = project.layout.buildDirectory @Internal def pkgName = project.name @Internal def skipBootstrap = 'false' + @Internal def outputJarFileName = '' + + @InputFiles + @PathSensitive(PathSensitivity.RELATIVE) + def srcDir = project.files("src/main/ballerina") + + @OutputFile + def zipFile = projectDir.map{ it.file("target/" + project.ext.modName + ".zip") } + + @OutputFile + def jarFile = projectDir.map{ it.file("target/" + outputJarFileName + ".jar") } + + @Override @Internal + List getJvmArgumentProviders() { + return super.getJvmArgumentProviders() + } BallerinaLangLibBuildTask() { setMainClass('org.ballerinalang.stdlib.utils.BuildLangLib') + standardOutput = System.out + errorOutput = System.err } @Override void exec() { def args = [] - args << projectDir - args << distCache + args << projectDir.get().toString() + args << distCache.get().toString() args << pkgName args << skipBootstrap @@ -150,11 +169,8 @@ tasks.register('copyBallerinaProject', Copy) { } tasks.register('ballerinaLangLibBuild', BallerinaLangLibBuildTask) { - standardOutput = System.out - errorOutput = System.err - projectDir = project.buildDir.toString() + "/ballerina-src" // + modName - distCache = project.buildDir.toString() - classpath = project.configurations.balaCreat + classpath = files(project.configurations.balaCreat, jar.archiveFile) + outputJarFileName = jarFileName skipBootstrap = 'true' minHeapSize = "512m" maxHeapSize = "2048m" @@ -163,11 +179,6 @@ tasks.register('ballerinaLangLibBuild', BallerinaLangLibBuildTask) { dependsOn copyBallerinaProject dependsOn createDistributionCache dependsOn jar - inputs.files("src/main/ballerina") - outputs.file("$buildDir/ballerina-src/target/${project.ext.modName}.zip") - outputs.file("$buildDir/ballerina-src/target/${jarFileName}.jar") - outputs.cacheIf { true } - classpath += files(jar.archivePath) } artifacts { diff --git a/gradle/ballerinaStdLibBuild.gradle b/gradle/ballerinaStdLibBuild.gradle index 5f26af1852f4..50b21fa80a3f 100644 --- a/gradle/ballerinaStdLibBuild.gradle +++ b/gradle/ballerinaStdLibBuild.gradle @@ -69,21 +69,40 @@ dependencies { distributionBala project(path: ':ballerina-lang:regexp', configuration: 'distributionBala') } +@CacheableTask class BallerinaLangLibBuildTask extends JavaExec { - @Internal def projectDir = '' - @Internal def distCache = '' + @Internal def projectDir = project.layout.buildDirectory.dir("ballerina-src") + @Internal def distCache = project.layout.buildDirectory @Internal def pkgName = project.name @Internal def skipBootstrap = 'false' + @Internal def outputJarFileName = '' + + @InputFiles + @PathSensitive(PathSensitivity.RELATIVE) + def srcDir = project.files("src/main/ballerina") + + @OutputFile + def zipFile = projectDir.map{ it.file("target/" + project.ext.modName + ".zip") } + + @OutputFile + def jarFile = projectDir.map{ it.file("target/" + outputJarFileName + ".jar") } + + @Override @Internal + List getJvmArgumentProviders() { + return super.getJvmArgumentProviders() + } BallerinaLangLibBuildTask() { - setMain('org.ballerinalang.stdlib.utils.BuildLangLib') + setMainClass('org.ballerinalang.stdlib.utils.BuildLangLib') + standardOutput = System.out + errorOutput = System.err } @Override void exec() { def args = [] - args << projectDir - args << distCache + args << projectDir.get().toString() + args << distCache.get().toString() args << pkgName args << skipBootstrap @@ -161,11 +180,8 @@ tasks.register('copyBallerinaProject', Copy) { } tasks.register('ballerinaLangLibBuild', BallerinaLangLibBuildTask) { - standardOutput = System.out - errorOutput = System.err - projectDir = project.buildDir.toString() + "/ballerina-src" // + modName - distCache = project.buildDir.toString() - classpath = project.configurations.balaCreat + classpath = files(project.configurations.balaCreat, jar.archiveFile) + outputJarFileName = jarFileName skipBootstrap = 'true' minHeapSize = "512m" maxHeapSize = "2048m" @@ -174,11 +190,6 @@ tasks.register('ballerinaLangLibBuild', BallerinaLangLibBuildTask) { dependsOn copyBallerinaProject dependsOn createDistributionCache dependsOn jar - inputs.files("src/main/ballerina") - outputs.file("$buildDir/ballerina-src/target/" + modName + ".zip") - outputs.file("$buildDir/ballerina-src/target/${jarFileName}.jar") - outputs.cacheIf { true } - classpath += files(jar.archivePath) } artifacts { diff --git a/gradle/ballerinaStdLibBuildInternal.gradle b/gradle/ballerinaStdLibBuildInternal.gradle index 0b167903dab1..a32a1a702303 100644 --- a/gradle/ballerinaStdLibBuildInternal.gradle +++ b/gradle/ballerinaStdLibBuildInternal.gradle @@ -69,21 +69,40 @@ dependencies { distributionBala project(path: ':ballerina-lang:regexp', configuration: 'distributionBala') } +@CacheableTask class BallerinaLangLibBuildTask extends JavaExec { - @Internal def projectDir = '' - @Internal def distCache = '' + @Internal def projectDir = project.layout.buildDirectory.dir("ballerina-src") + @Internal def distCache = project.layout.buildDirectory @Internal def pkgName = project.name @Internal def skipBootstrap = 'false' + @Internal def outputJarFileName = '' + + @InputFiles + @PathSensitive(PathSensitivity.RELATIVE) + def srcDir = project.files("src/main/ballerina") + + @OutputFile + def zipFile = projectDir.map{ it.file("target/" + project.ext.modName + ".zip") } + + @OutputFile + def jarFile = projectDir.map{ it.file("target/" + outputJarFileName + ".jar") } + + @Override @Internal + List getJvmArgumentProviders() { + return super.getJvmArgumentProviders() + } BallerinaLangLibBuildTask() { setMainClass('org.ballerinalang.stdlib.utils.BuildLangLib') + standardOutput = System.out + errorOutput = System.err } @Override void exec() { def args = [] - args << projectDir - args << distCache + args << projectDir.get().toString() + args << distCache.get().toString() args << pkgName args << skipBootstrap @@ -159,11 +178,8 @@ tasks.register('copyBallerinaProject', Copy) { } tasks.register('ballerinaLangLibBuild', BallerinaLangLibBuildTask) { - standardOutput = System.out - errorOutput = System.err - projectDir = project.buildDir.toString() + "/ballerina-src" // + modName - distCache = project.buildDir.toString() - classpath = project.configurations.balaCreat + classpath = files(project.configurations.balaCreat, jar.archiveFile) + outputJarFileName = jarFileName skipBootstrap = 'true' minHeapSize = "512m" maxHeapSize = "2048m" @@ -172,11 +188,6 @@ tasks.register('ballerinaLangLibBuild', BallerinaLangLibBuildTask) { dependsOn copyBallerinaProject dependsOn createDistributionCache dependsOn jar - inputs.files("src/main/ballerina") - outputs.file("$buildDir/ballerina-src/target/" + modName + ".zip") - outputs.file("$buildDir/ballerina-src/target/${jarFileName}.jar") - outputs.cacheIf { true } - classpath += files(jar.archivePath) } artifacts { diff --git a/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/Cast.java b/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/Cast.java index f2ceec7020a6..72e64147f88b 100644 --- a/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/Cast.java +++ b/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/Cast.java @@ -38,7 +38,7 @@ * * @since 1.2.5 */ -public class Cast { +public final class Cast { private static final String moduleName = "{ballerina/jballerina.java}"; private static final String annotationName = "@java:Binding"; @@ -46,6 +46,9 @@ public class Cast { private static final String classAttribute = "class"; private static final String jObjField = "jObj"; + private Cast() { + } + public static Object cast(BObject value, BTypedesc castType) { BHandle handleObj; ObjectType objType = (ObjectType) TypeUtils.getImpliedType(value.getType()); @@ -57,10 +60,10 @@ public static Object cast(BObject value, BTypedesc castType) { + jObjField + "` field in `" + valueObjName + "`")); } try { - BMap objAnnotation; + BMap objAnnotation; BString objClass; try { - objAnnotation = (BMap) objType.getAnnotation(StringUtils.fromString(annotationType)); + objAnnotation = (BMap) objType.getAnnotation(StringUtils.fromString(annotationType)); objClass = objAnnotation.getStringValue(StringUtils.fromString(classAttribute)); } catch (Exception e) { return createError(StringUtils.fromString(moduleName + " Error while retrieving details of the `" + @@ -83,7 +86,7 @@ public static Object cast(BObject value, BTypedesc castType) { "parameter: " + e)); } try { - BMap castObjAnnotation = (BMap) castObjType.getAnnotation(StringUtils.fromString(annotationType)); + var castObjAnnotation = (BMap) castObjType.getAnnotation(StringUtils.fromString(annotationType)); castObjClass = castObjAnnotation.getStringValue(StringUtils.fromString(classAttribute)); } catch (Exception e) { return createError(StringUtils.fromString(moduleName + " Error while retrieving details of the `" + diff --git a/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/CreateNull.java b/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/CreateNull.java index fa6b362ef051..fc3949e886c2 100644 --- a/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/CreateNull.java +++ b/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/CreateNull.java @@ -25,7 +25,10 @@ * * @since 1.0.0 */ -public class CreateNull { +public final class CreateNull { + + private CreateNull() { + } public static BHandle createNull() { return ValueCreator.createHandleValue(null); diff --git a/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/FromString.java b/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/FromString.java index 7c554e662799..7858b0972f0e 100644 --- a/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/FromString.java +++ b/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/FromString.java @@ -26,7 +26,10 @@ * * @since 1.0.0 */ -public class FromString { +public final class FromString { + + private FromString() { + } public static BHandle fromString(BString strValue) { return ValueCreator.createHandleValue(strValue == null ? null : strValue.getValue()); diff --git a/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/GetArrayElement.java b/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/GetArrayElement.java index 4a422a03c297..78cc07ff912f 100644 --- a/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/GetArrayElement.java +++ b/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/GetArrayElement.java @@ -26,7 +26,10 @@ * * @since 1.0.0 */ -public class GetArrayElement { +public final class GetArrayElement { + + private GetArrayElement() { + } public static BHandle getArrayElement(BHandle bHandle, long index) { Object[] arr = (Object[]) bHandle.getValue(); diff --git a/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/GetArrayLength.java b/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/GetArrayLength.java index c4bea6efee23..4f91f7e28283 100644 --- a/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/GetArrayLength.java +++ b/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/GetArrayLength.java @@ -26,7 +26,10 @@ * @since 1.0.0 */ -public class GetArrayLength { +public final class GetArrayLength { + + private GetArrayLength() { + } public static long getArrayLength(BHandle bHandle) { Object[] arr = (Object[]) bHandle.getValue(); diff --git a/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/IsNull.java b/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/IsNull.java index d1e893f9f351..cb44926bb6ac 100644 --- a/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/IsNull.java +++ b/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/IsNull.java @@ -24,7 +24,10 @@ * * @since 1.0.0 */ -public class IsNull { +public final class IsNull { + + private IsNull() { + } public static boolean isNull(BHandle value) { return value.getValue() == null; diff --git a/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/JValues.java b/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/JValues.java index df4b2047d99d..14c522ec00d3 100644 --- a/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/JValues.java +++ b/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/JValues.java @@ -27,7 +27,10 @@ * * @since 1.0.0 */ -class JValues { +final class JValues { + + private JValues() { + } static BError getJavaNullReferenceError() { return ErrorHelper.getRuntimeException(ErrorReasons.JAVA_NULL_REFERENCE_ERROR, diff --git a/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/JavaUtils.java b/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/JavaUtils.java index 11539bd79546..c6facb2eb1b2 100644 --- a/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/JavaUtils.java +++ b/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/JavaUtils.java @@ -30,7 +30,8 @@ * * @since 1.0.0 */ -public class JavaUtils { +public final class JavaUtils { + private static final String booleanTypeName = "boolean"; private static final String byteTypeName = "byte"; private static final String shortTypeName = "short"; @@ -42,6 +43,9 @@ public class JavaUtils { private static final Module JAVA_PACKAGE_ID = new Module(RuntimeConstants.BALLERINA_BUILTIN_PKG_PREFIX, "java", "0.9.0"); + private JavaUtils() { + } + /** * Returns the Java Class object associated with the class or interface with the given string name. * @@ -65,25 +69,16 @@ public static Object getClass(BString namebStr) { } private static Class getPrimitiveTypeClass(String name) { - switch (name) { - case booleanTypeName: - return Boolean.TYPE; - case byteTypeName: - return Byte.TYPE; - case shortTypeName: - return Short.TYPE; - case charTypeName: - return Character.TYPE; - case intTypeName: - return Integer.TYPE; - case longTypeName: - return Long.TYPE; - case floatTypeName: - return Float.TYPE; - case doubleTypeName: - return Double.TYPE; - default: - return null; - } + return switch (name) { + case booleanTypeName -> Boolean.TYPE; + case byteTypeName -> Byte.TYPE; + case shortTypeName -> Short.TYPE; + case charTypeName -> Character.TYPE; + case intTypeName -> Integer.TYPE; + case longTypeName -> Long.TYPE; + case floatTypeName -> Float.TYPE; + case doubleTypeName -> Double.TYPE; + default -> null; + }; } } diff --git a/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/SetArrayElement.java b/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/SetArrayElement.java index db166ec05275..315e77a45935 100644 --- a/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/SetArrayElement.java +++ b/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/SetArrayElement.java @@ -26,7 +26,10 @@ * * @since 1.0.0 */ -public class SetArrayElement { +public final class SetArrayElement { + + private SetArrayElement() { + } public static void setArrayElement(Strand strand, BHandle bHandle, long index, BHandle value) { Object[] arr = (Object[]) bHandle.getValue(); diff --git a/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/ToString.java b/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/ToString.java index 7bb6a79824ca..d455106f83e6 100644 --- a/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/ToString.java +++ b/langlib/jballerina.java/src/main/java/org/ballerinalang/langlib/java/ToString.java @@ -26,7 +26,10 @@ * * @since 1.0.0 */ -public class ToString { +public final class ToString { + + private ToString() { + } public static Object toString(BHandle value) { Object referredValue = value.getValue(); diff --git a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/Configurable.java b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/Configurable.java index dd0421acf1b3..27d3e2e927c1 100644 --- a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/Configurable.java +++ b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/Configurable.java @@ -31,7 +31,7 @@ * * @since 2.0 */ -public class Configurable { +public final class Configurable { public static Object hasConfigurableValue(BString orgName, BString moduleName, BString versionNumber, BString configVarName, BTypedesc t) { diff --git a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/Construct.java b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/Construct.java index 940af0b39ba0..9606f3a8778e 100644 --- a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/Construct.java +++ b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/Construct.java @@ -29,7 +29,10 @@ * * @since 1.2.0 */ -public class Construct { +public final class Construct { + + private Construct() { + } public static BStream construct(BTypedesc constraintTd, BTypedesc completionTd, BObject iteratorObj) { return ValueCreator.createStreamValue(TypeCreator.createStreamType(constraintTd.getDescribingType(), diff --git a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/CreateRecordValue.java b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/CreateRecordValue.java index 3423cd2e6b5d..c42a2b143dbb 100644 --- a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/CreateRecordValue.java +++ b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/CreateRecordValue.java @@ -29,7 +29,7 @@ * * @since 2.0 */ -public class CreateRecordValue { +public final class CreateRecordValue { public static Object createRecordFromMap(BMap value, BTypedesc t) { Type describingType = t.getDescribingType(); diff --git a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetAttribute.java b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetAttribute.java index 960f9c75608c..a3eb1965488a 100644 --- a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetAttribute.java +++ b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetAttribute.java @@ -33,7 +33,10 @@ * * @since 1.2.0 */ -public class GetAttribute { +public final class GetAttribute { + + private GetAttribute() { + } public static Object getAttribute(BXml xmlVal, BString attrName, boolean optionalFiledAccess) { if (xmlVal.getNodeType() == XmlNodeType.SEQUENCE && xmlVal.isEmpty()) { diff --git a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetCompletionType.java b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetCompletionType.java index 1537dbd9c2ec..ad4a592f8db8 100644 --- a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetCompletionType.java +++ b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetCompletionType.java @@ -31,7 +31,10 @@ * * @since 2.0.0 */ -public class GetCompletionType { +public final class GetCompletionType { + + private GetCompletionType() { + } public static BTypedesc getCompletionType(BTypedesc td) { Type type = TypeUtils.getImpliedType(td.getDescribingType()); diff --git a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetElementNameNilLifting.java b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetElementNameNilLifting.java index 8c0771729524..4bf36582406c 100644 --- a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetElementNameNilLifting.java +++ b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetElementNameNilLifting.java @@ -28,7 +28,10 @@ * * @since 1.2.0 */ -public class GetElementNameNilLifting { +public final class GetElementNameNilLifting { + + private GetElementNameNilLifting() { + } public static Object getElementNameNilLifting(BXml xmlVal) { if (IsElement.isElement(xmlVal)) { diff --git a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetElementType.java b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetElementType.java index b3d6abba2c58..378194ce0f99 100644 --- a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetElementType.java +++ b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetElementType.java @@ -35,7 +35,7 @@ * * @since 1.2.0 */ -public class GetElementType { +public final class GetElementType { private GetElementType() { } @@ -47,18 +47,14 @@ public static BTypedesc getElementType(Object td) { private static BTypedesc getElementTypeDescValue(Type type) { type = TypeUtils.getImpliedType(type); - switch (type.getTag()) { - case TypeTags.ARRAY_TAG: - return ValueCreator.createTypedescValue(((ArrayType) type).getElementType()); - case TypeTags.TUPLE_TAG: - return ValueCreator.createTypedescValue( - TypeCreator.createUnionType(((TupleType) type).getTupleTypes())); - case TypeTags.FINITE_TYPE_TAG: - // this is reached only for immutable values - return getElementTypeDescValue( - ((BValue) (((FiniteType) type).getValueSpace().iterator().next())).getType()); - default: - return ValueCreator.createTypedescValue(((StreamType) type).getConstrainedType()); - } + return switch (type.getTag()) { + case TypeTags.ARRAY_TAG -> ValueCreator.createTypedescValue(((ArrayType) type).getElementType()); + case TypeTags.TUPLE_TAG -> ValueCreator.createTypedescValue( + TypeCreator.createUnionType(((TupleType) type).getTupleTypes())); + // this is reached only for immutable values + case TypeTags.FINITE_TYPE_TAG -> getElementTypeDescValue( + ((BValue) (((FiniteType) type).getValueSpace().iterator().next())).getType()); + default -> ValueCreator.createTypedescValue(((StreamType) type).getConstrainedType()); + }; } } diff --git a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetElements.java b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetElements.java index 83c5e8974ca4..5d1e88c1bfe4 100644 --- a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetElements.java +++ b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetElements.java @@ -30,12 +30,15 @@ * * @since 1.2.0 */ -public class GetElements { +public final class GetElements { public static final String EMPTY = ""; public static final String STAR = "*"; + private GetElements() { + } + /** * Expected element name format. * elemNames: {nsUrl}elemName | elemName | {nsUrl}* | * @@ -76,9 +79,8 @@ public static BXml getElements(BXml xmlVal, BString[] elemNames) { public static void destructureFilters(BString[] elemNames, ArrayList nsList, ArrayList localNameList) { - int filterCount = elemNames.length; - for (int i = 0; i < filterCount; i++) { - String fullName = elemNames[i].getValue(); + for (BString elemName : elemNames) { + String fullName = elemName.getValue(); int lastIndexOf = fullName.lastIndexOf('}'); if (lastIndexOf < 0) { nsList.add(EMPTY); diff --git a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetFilterFunc.java b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetFilterFunc.java index 95c5d7d00c4c..eec5fbf96713 100644 --- a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetFilterFunc.java +++ b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetFilterFunc.java @@ -31,10 +31,13 @@ * * @since 1.2.0 */ -public class GetFilterFunc { +public final class GetFilterFunc { - public static BFunctionPointer getFilterFunc(Object obj) { - BFunctionPointer bFunctionPointer = (BFunctionPointer) obj; + private GetFilterFunc() { + } + + public static BFunctionPointer getFilterFunc(Object obj) { + BFunctionPointer bFunctionPointer = (BFunctionPointer) obj; FunctionType functionType = (FunctionType) TypeUtils.getImpliedType(bFunctionPointer.getType()); functionType.getParameters()[0].type = TypeCreator.createUnionType(List.of(PredefinedTypes.TYPE_ANY, PredefinedTypes.TYPE_ERROR), 0); diff --git a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetFilteredChildrenFlat.java b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetFilteredChildrenFlat.java index 57e20d5b6540..3862367c9ed0 100644 --- a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetFilteredChildrenFlat.java +++ b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetFilteredChildrenFlat.java @@ -34,7 +34,10 @@ * * @since 1.2.0 */ -public class GetFilteredChildrenFlat { +public final class GetFilteredChildrenFlat { + + private GetFilteredChildrenFlat() { + } public static BXml getFilteredChildrenFlat(BXml xmlVal, long index, BString[] elemNames) { if (xmlVal.getNodeType() == XmlNodeType.ELEMENT) { diff --git a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetIteratorObj.java b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetIteratorObj.java index de452972c924..4285d45cdde5 100644 --- a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetIteratorObj.java +++ b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetIteratorObj.java @@ -26,7 +26,10 @@ * * @since 1.2.0 */ -public class GetIteratorObj { +public final class GetIteratorObj { + + private GetIteratorObj() { + } public static BObject getIteratorObj(BStream strm) { return strm.getIteratorObj(); diff --git a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetMapFunc.java b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetMapFunc.java index 9c4a6a740e94..8b9e6ec77962 100644 --- a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetMapFunc.java +++ b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetMapFunc.java @@ -31,10 +31,13 @@ * * @since 1.2.0 */ -public class GetMapFunc { +public final class GetMapFunc { - public static BFunctionPointer getMapFunc(Object obj) { - BFunctionPointer functionPointer = (BFunctionPointer) obj; + private GetMapFunc() { + } + + public static BFunctionPointer getMapFunc(Object obj) { + BFunctionPointer functionPointer = (BFunctionPointer) obj; FunctionType functionType = (FunctionType) TypeUtils.getImpliedType(functionPointer.getType()); functionType.getParameters()[0].type = TypeCreator.createUnionType(List.of(PredefinedTypes.TYPE_ANY, PredefinedTypes.TYPE_ERROR), 0); diff --git a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetReturnType.java b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetReturnType.java index e87c3024c23a..873d4169e38a 100644 --- a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetReturnType.java +++ b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/GetReturnType.java @@ -29,10 +29,13 @@ * * @since 1.2.0 */ -public class GetReturnType { +public final class GetReturnType { + + private GetReturnType() { + } public static BTypedesc getReturnType(Object obj) { - BFunctionPointer bFunctionPointer = (BFunctionPointer) obj; + BFunctionPointer bFunctionPointer = (BFunctionPointer) obj; FunctionType functionType = (FunctionType) TypeUtils.getImpliedType(bFunctionPointer.getType()); return ValueCreator.createTypedescValue(functionType.getReturnType()); } diff --git a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/InvokeAsExternal.java b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/InvokeAsExternal.java index aa0d955fb6be..e4c1803d38d1 100644 --- a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/InvokeAsExternal.java +++ b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/InvokeAsExternal.java @@ -31,14 +31,17 @@ * * @since 2.0.0 */ -public class InvokeAsExternal { +public final class InvokeAsExternal { private static final StrandMetadata METADATA = new StrandMetadata(BALLERINA_BUILTIN_PKG_PREFIX, "lang.internal", "0.1.0", "invokeAsExternal"); + private InvokeAsExternal() { + } + public static Object invokeAsExternal(Object func, Object[] args) { - BFunctionPointer function = (BFunctionPointer) func; + BFunctionPointer function = (BFunctionPointer) func; List argList = new ArrayList<>(); for (Object arg : args) { argList.add(arg); diff --git a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/IsElement.java b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/IsElement.java index 0c93c8d92754..a1e4bd293286 100644 --- a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/IsElement.java +++ b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/IsElement.java @@ -24,7 +24,10 @@ /** * Helper function to check xml.isElement(). */ -public class IsElement { +public final class IsElement { + + private IsElement() { + } public static boolean isElement(BXml bxml) { if (bxml.getNodeType() == XmlNodeType.ELEMENT) { diff --git a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/SelectDescendants.java b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/SelectDescendants.java index 7eecd7f262d0..01ef799f432c 100644 --- a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/SelectDescendants.java +++ b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/SelectDescendants.java @@ -31,16 +31,19 @@ * * @since 0.92 */ -public class SelectDescendants { +public final class SelectDescendants { private static final String OPERATION = "select descendants from xml"; + private SelectDescendants() { + } + public static BXml selectDescendants(BXml xml, BString[] qnames) { try { List qnameList = new ArrayList<>(); int size = qnames.length; - for (int i = 0; i < size; i++) { - String strQname = qnames[i].getValue(); + for (BString qname : qnames) { + String strQname = qname.getValue(); // remove empty namespace in expanded form i.e `{}local => local` if (strQname.lastIndexOf('}') == 1) { strQname = strQname.substring(2); diff --git a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/SetNarrowType.java b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/SetNarrowType.java index ca538e7d267b..3518836a2fd0 100644 --- a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/SetNarrowType.java +++ b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/SetNarrowType.java @@ -35,14 +35,17 @@ * * @since 1.2.0 */ -public class SetNarrowType { +public final class SetNarrowType { - public static BMap setNarrowType(BTypedesc td, BMap value) { + private SetNarrowType() { + } + + public static BMap setNarrowType(BTypedesc td, BMap value) { RecordType recordType = (RecordType) TypeUtils.getImpliedType(value.getType()); RecordType newRecordType = TypeCreator.createRecordType("narrowType", recordType.getPackage(), recordType.getTypeFlags(), recordType.isSealed(), recordType.getTypeFlags()); - newRecordType.setFields(new HashMap() {{ + newRecordType.setFields(new HashMap<>() {{ put("value", TypeCreator.createField(td.getDescribingType(), "value", SymbolFlags.PUBLIC + SymbolFlags.REQUIRED)); }}); diff --git a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/WorkerChannels.java b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/WorkerChannels.java index 4f53841fd416..bcde4ab88c56 100644 --- a/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/WorkerChannels.java +++ b/langlib/lang.__internal/src/main/java/org/ballerinalang/langlib/internal/WorkerChannels.java @@ -30,7 +30,10 @@ * * @since 2201.9.0 */ -public class WorkerChannels { +public final class WorkerChannels { + + private WorkerChannels() { + } /** * Auto-closes the specified worker channels if they exist; otherwise, closes them upon creation. diff --git a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Enumerate.java b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Enumerate.java index 424c91ba8989..e98b37d8a391 100644 --- a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Enumerate.java +++ b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Enumerate.java @@ -45,7 +45,10 @@ // returnType = {@ReturnType(type = TypeKind.ARRAY, elementType = TypeKind.TUPLE)}, // isPublic = true //) -public class Enumerate { +public final class Enumerate { + + private Enumerate() { + } public static BArray enumerate(BArray arr) { Type arrType = TypeUtils.getImpliedType(arr.getType()); diff --git a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Filter.java b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Filter.java index 0b9c0b6d8daf..27aea12e17a6 100644 --- a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Filter.java +++ b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Filter.java @@ -42,25 +42,19 @@ * * @since 1.0 */ -public class Filter { +public final class Filter { private static final StrandMetadata METADATA = new StrandMetadata(BALLERINA_BUILTIN_PKG_PREFIX, ARRAY_LANG_LIB, ARRAY_VERSION, "filter"); - public static BArray filter(BArray arr, BFunctionPointer func) { + public static BArray filter(BArray arr, BFunctionPointer func) { BArray newArr; Type arrType = TypeUtils.getImpliedType(arr.getType()); - switch (arrType.getTag()) { - case TypeTags.ARRAY_TAG: - newArr = ValueCreator.createArrayValue(TypeCreator.createArrayType(arr.getElementType())); - break; - case TypeTags.TUPLE_TAG: - newArr = ArrayUtils.createEmptyArrayFromTuple(arr); - break; - default: - throw createOpNotSupportedError(arrType, "filter()"); - - } + newArr = switch (arrType.getTag()) { + case TypeTags.ARRAY_TAG -> ValueCreator.createArrayValue(TypeCreator.createArrayType(arr.getElementType())); + case TypeTags.TUPLE_TAG -> ArrayUtils.createEmptyArrayFromTuple(arr); + default -> throw createOpNotSupportedError(arrType, "filter()"); + }; int size = arr.size(); AtomicInteger newArraySize = new AtomicInteger(-1); AtomicInteger index = new AtomicInteger(-1); diff --git a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/ForEach.java b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/ForEach.java index 31fe4996e12d..f89f9957be6e 100644 --- a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/ForEach.java +++ b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/ForEach.java @@ -43,12 +43,15 @@ // args = {@Argument(name = "arr", type = TypeKind.ARRAY), @Argument(name = "func", type = TypeKind.FUNCTION)}, // isPublic = true //) -public class ForEach { +public final class ForEach { private static final StrandMetadata METADATA = new StrandMetadata(BALLERINA_BUILTIN_PKG_PREFIX, ARRAY_LANG_LIB, ARRAY_VERSION, "forEach"); - public static void forEach(BArray arr, BFunctionPointer func) { + private ForEach() { + } + + public static void forEach(BArray arr, BFunctionPointer func) { int size = arr.size(); Type arrType = arr.getType(); GetFunction getFn = getElementAccessFunction(arrType, "forEach()"); diff --git a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/FromBase16.java b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/FromBase16.java index 75dbd35f9df8..aa72c9b07cb5 100644 --- a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/FromBase16.java +++ b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/FromBase16.java @@ -31,7 +31,10 @@ * * @since 1.0 */ -public class FromBase16 { +public final class FromBase16 { + + private FromBase16() { + } public static Object fromBase16(BString str) { if (str.length() % 2 != 0) { diff --git a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/FromBase64.java b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/FromBase64.java index 76e475b82971..f939644d6680 100644 --- a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/FromBase64.java +++ b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/FromBase64.java @@ -30,7 +30,10 @@ * * @since 1.0 */ -public class FromBase64 { +public final class FromBase64 { + + private FromBase64() { + } public static Object fromBase64(BString str) { try { diff --git a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/GetIterator.java b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/GetIterator.java index f77e68fa2088..de4126c9fd5e 100644 --- a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/GetIterator.java +++ b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/GetIterator.java @@ -32,9 +32,12 @@ // returnType = {@ReturnType(type = TypeKind.OBJECT)}, // isPublic = true //) -public class GetIterator { +public final class GetIterator { - public static BIterator iterator(BArray arr) { + private GetIterator() { + } + + public static BIterator iterator(BArray arr) { return arr.getIterator(); } } diff --git a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/IndexOf.java b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/IndexOf.java index ad7f384615ca..4e5ecd691ad4 100644 --- a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/IndexOf.java +++ b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/IndexOf.java @@ -37,7 +37,10 @@ // returnType = {@ReturnType(type = TypeKind.UNION)}, // isPublic = true //) -public class IndexOf { +public final class IndexOf { + + private IndexOf() { + } public static Object indexOf(BArray arr, Object val, long startIndex) { Type arrType = arr.getType(); diff --git a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/LastIndexOf.java b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/LastIndexOf.java index 6904647b372f..63650f6e08c2 100644 --- a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/LastIndexOf.java +++ b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/LastIndexOf.java @@ -37,7 +37,10 @@ // returnType = {@ReturnType(type = TypeKind.UNION)}, // isPublic = true //) -public class LastIndexOf { +public final class LastIndexOf { + + private LastIndexOf() { + } public static Object lastIndexOf(BArray arr, Object val, long startIndex) { Type arrType = arr.getType(); diff --git a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Length.java b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Length.java index 65f614e602a0..a6ec4970f145 100644 --- a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Length.java +++ b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Length.java @@ -31,7 +31,10 @@ // returnType = {@ReturnType(type = TypeKind.INT)}, // isPublic = true //) -public class Length { +public final class Length { + + private Length() { + } public static long length(BArray arr) { return arr.size(); diff --git a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Map.java b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Map.java index 525e39255711..40453b7dcfa2 100644 --- a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Map.java +++ b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Map.java @@ -50,12 +50,15 @@ // returnType = {@ReturnType(type = TypeKind.ARRAY)}, // isPublic = true //) -public class Map { +public final class Map { private static final StrandMetadata METADATA = new StrandMetadata(BALLERINA_BUILTIN_PKG_PREFIX, ARRAY_LANG_LIB, ARRAY_VERSION, "map"); - public static BArray map(BArray arr, BFunctionPointer func) { + private Map() { + } + + public static BArray map(BArray arr, BFunctionPointer func) { Type elemType = ((FunctionType) TypeUtils.getImpliedType(func.getType())).getReturnType(); Type retArrType = TypeCreator.createArrayType(elemType); BArray retArr = ValueCreator.createArrayValue((ArrayType) retArrType); @@ -63,16 +66,11 @@ public static BArray map(BArray arr, BFunctionPointer func) { GetFunction getFn; Type arrType = TypeUtils.getImpliedType(arr.getType()); - switch (arrType.getTag()) { - case TypeTags.ARRAY_TAG: - getFn = BArray::get; - break; - case TypeTags.TUPLE_TAG: - getFn = BArray::getRefValue; - break; - default: - throw createOpNotSupportedError(arrType, "map()"); - } + getFn = switch (arrType.getTag()) { + case TypeTags.ARRAY_TAG -> BArray::get; + case TypeTags.TUPLE_TAG -> BArray::getRefValue; + default -> throw createOpNotSupportedError(arrType, "map()"); + }; AtomicInteger index = new AtomicInteger(-1); AsyncUtils.invokeFunctionPointerAsyncIteratively(func, null, METADATA, size, () -> new Object[]{getFn.get(arr, index.incrementAndGet()), true}, diff --git a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Next.java b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Next.java index 497d33c6e7e2..55a99e2abf32 100644 --- a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Next.java +++ b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Next.java @@ -30,10 +30,14 @@ * * @since 1.0 */ -public class Next { +public final class Next { + + private Next() { + } + //TODO: refactor hard coded values public static Object next(BObject m) { - BIterator arrIterator = (BIterator) m.getNativeData("&iterator&"); + BIterator arrIterator = (BIterator) m.getNativeData("&iterator&"); BArray arr = (BArray) m.get(StringUtils.fromString("m")); if (arrIterator == null) { arrIterator = arr.getIterator(); diff --git a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Pop.java b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Pop.java index 3ae53114f546..0ddc3b324379 100644 --- a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Pop.java +++ b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Pop.java @@ -38,7 +38,7 @@ // returnType = {@ReturnType(type = TypeKind.ANY)}, // isPublic = true //) -public class Pop { +public final class Pop { private static final String FUNCTION_SIGNATURE = "pop()"; diff --git a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Push.java b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Push.java index 1ac7626a0037..2f0693cbcb99 100644 --- a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Push.java +++ b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Push.java @@ -36,10 +36,13 @@ // returnType = {@ReturnType(type = TypeKind.ANY)}, // isPublic = true //) -public class Push { +public final class Push { private static final String FUNCTION_SIGNATURE = "push()"; + private Push() { + } + public static void push(BArray arr, Object... vals) { Type arrType = TypeUtils.getImpliedType(arr.getType()); int nVals = vals.length; diff --git a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Reduce.java b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Reduce.java index 2873491660f4..a4090a9de927 100644 --- a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Reduce.java +++ b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Reduce.java @@ -39,12 +39,15 @@ * * @since 1.0 */ -public class Reduce { +public final class Reduce { private static final StrandMetadata METADATA = new StrandMetadata(BALLERINA_BUILTIN_PKG_PREFIX, ARRAY_LANG_LIB, ARRAY_VERSION, "reduce"); - public static Object reduce(BArray arr, BFunctionPointer func, Object initial) { + private Reduce() { + } + + public static Object reduce(BArray arr, BFunctionPointer func, Object initial) { Type arrType = arr.getType(); int size = arr.size(); GetFunction getFn = getElementAccessFunction(arrType, "reduce()"); diff --git a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Remove.java b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Remove.java index 260fa0e43a2b..7a8ecd5f30c6 100644 --- a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Remove.java +++ b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Remove.java @@ -32,7 +32,10 @@ // returnType = {@ReturnType(type = TypeKind.ANY)}, // isPublic = true //) -public class Remove { +public final class Remove { + + private Remove() { + } public static Object remove(BArray arr, long i) { return ((ArrayValue) arr).remove(i); diff --git a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/RemoveAll.java b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/RemoveAll.java index c6f92ffcb1ab..cd9d7d21579a 100644 --- a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/RemoveAll.java +++ b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/RemoveAll.java @@ -30,7 +30,10 @@ // args = {@Argument(name = "arr", type = TypeKind.ARRAY)}, // isPublic = true //) -public class RemoveAll { +public final class RemoveAll { + + private RemoveAll() { + } public static void removeAll(BArray arr) { SetLength.setLength(arr, 0); diff --git a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Reverse.java b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Reverse.java index 2fcc6fe13daa..9eb39ab72a48 100644 --- a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Reverse.java +++ b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Reverse.java @@ -33,21 +33,15 @@ * * @since 1.0 */ -public class Reverse { +public final class Reverse { public static BArray reverse(BArray arr) { Type arrType = TypeUtils.getImpliedType(arr.getType()); - BArray reversedArr; - switch (arrType.getTag()) { - case TypeTags.ARRAY_TAG: - reversedArr = ValueCreator.createArrayValue(TypeCreator.createArrayType(arr.getElementType())); - break; - case TypeTags.TUPLE_TAG: - reversedArr = ArrayUtils.createEmptyArrayFromTuple(arr); - break; - default: - throw createOpNotSupportedError(arrType, "reverse()"); - } + BArray reversedArr = switch (arrType.getTag()) { + case TypeTags.ARRAY_TAG -> ValueCreator.createArrayValue(TypeCreator.createArrayType(arr.getElementType())); + case TypeTags.TUPLE_TAG -> ArrayUtils.createEmptyArrayFromTuple(arr); + default -> throw createOpNotSupportedError(arrType, "reverse()"); + }; for (int i = arr.size() - 1, j = 0; i >= 0; i--, j++) { reversedArr.add(j, arr.get(i)); } diff --git a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/SetLength.java b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/SetLength.java index d85908a7f2b8..470ab73b2584 100644 --- a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/SetLength.java +++ b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/SetLength.java @@ -30,7 +30,7 @@ // args = {@Argument(name = "arr", type = TypeKind.ARRAY), @Argument(name = "i", type = TypeKind.INT)}, // isPublic = true //) -public class SetLength { +public final class SetLength { public static void setLength(BArray arr, long i) { arr.setLength(i); diff --git a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Shift.java b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Shift.java index 30c7369f4138..bf7f930b3b3c 100644 --- a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Shift.java +++ b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Shift.java @@ -33,7 +33,10 @@ // returnType = {@ReturnType(type = TypeKind.ANY)}, // isPublic = true //) -public class Shift { +public final class Shift { + + private Shift() { + } public static Object shift(BArray arr) { return ((ArrayValue) arr).shift(0); diff --git a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Slice.java b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Slice.java index 5f74fef69ec4..2ab2f69058ce 100644 --- a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Slice.java +++ b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Slice.java @@ -40,7 +40,10 @@ * * @since 1.0 */ -public class Slice { +public final class Slice { + + private Slice() { + } public static BArray slice(BArray arr, long startIndex, long endIndex) { int size = arr.size(); diff --git a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Sort.java b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Sort.java index f1191a84b226..c7e4b3a67b23 100644 --- a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Sort.java +++ b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Sort.java @@ -28,6 +28,7 @@ import io.ballerina.runtime.api.values.BError; import io.ballerina.runtime.api.values.BFunctionPointer; import io.ballerina.runtime.api.values.BMap; +import io.ballerina.runtime.api.values.BString; import io.ballerina.runtime.internal.ValueComparisonUtils; import io.ballerina.runtime.internal.scheduling.Scheduler; import io.ballerina.runtime.internal.types.BTupleType; @@ -45,7 +46,10 @@ * * @since 1.0 */ -public class Sort { +public final class Sort { + + private Sort() { + } public static BArray sort(BArray arr, Object direction, Object func) { BArray sortedArray; @@ -125,7 +129,7 @@ private static void merge(Object[][] input, Object[][] aux, int lo, int mid, int } catch (BError error) { throw ErrorCreator.createError(getModulePrefixedReason(ARRAY_LANG_LIB, INVALID_TYPE_TO_SORT), - (BMap) error.getDetails()); + (BMap) error.getDetails()); } } } diff --git a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/ToBase16.java b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/ToBase16.java index 56ba30f7b9e4..6bbabfb8bb01 100644 --- a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/ToBase16.java +++ b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/ToBase16.java @@ -36,11 +36,15 @@ * * @since 1.0 */ -public class ToBase16 { +public final class ToBase16 { private static final char[] chars = "0123456789abcdef".toCharArray(); private static final BString NOT_SUPPORTED_ERROR_DETAIL = StringUtils.fromString("toBase16() is only supported " + "on 'byte[]'"); + + private ToBase16() { + } + public static BString toBase16(BArray arr) { Type arrType = TypeUtils.getImpliedType(arr.getType()); if (arrType.getTag() != TypeTags.ARRAY_TAG || diff --git a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/ToBase64.java b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/ToBase64.java index 814b388be1ac..58707e693ce1 100644 --- a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/ToBase64.java +++ b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/ToBase64.java @@ -38,11 +38,14 @@ * * @since 1.0 */ -public class ToBase64 { +public final class ToBase64 { private static final BString NOT_SUPPORT_DETAIL_ERROR = StringUtils .fromString("toBase64() is only supported on 'byte[]'"); + private ToBase64() { + } + public static BString toBase64(BArray arr) { Type arrType = TypeUtils.getImpliedType(arr.getType()); if (arrType.getTag() != TypeTags.ARRAY_TAG || diff --git a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Unshift.java b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Unshift.java index d02c83e31335..82e86e55183b 100644 --- a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Unshift.java +++ b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/Unshift.java @@ -25,7 +25,10 @@ * * @since 1.0 */ -public class Unshift { +public final class Unshift { + + private Unshift() { + } public static void unshift(BArray arr, Object... vals) { arr.unshift(vals); diff --git a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/utils/ArrayUtils.java b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/utils/ArrayUtils.java index 1f30f1cd2706..13df1d56986c 100644 --- a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/utils/ArrayUtils.java +++ b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/utils/ArrayUtils.java @@ -47,7 +47,7 @@ * * @since 1.0 */ -public class ArrayUtils { +public final class ArrayUtils { @Deprecated public static void add(BArray arr, int elemTypeTag, long index, Object value) { @@ -73,14 +73,11 @@ public static void add(BArray arr, int elemTypeTag, long index, Object value) { } public static GetFunction getElementAccessFunction(Type arrType, String funcName) { - switch (TypeUtils.getImpliedType(arrType).getTag()) { - case TypeTags.ARRAY_TAG: - return BArray::get; - case TypeTags.TUPLE_TAG: - return BArray::getRefValue; - default: - throw createOpNotSupportedError(arrType, funcName); - } + return switch (TypeUtils.getImpliedType(arrType).getTag()) { + case TypeTags.ARRAY_TAG -> BArray::get; + case TypeTags.TUPLE_TAG -> BArray::getRefValue; + default -> throw createOpNotSupportedError(arrType, funcName); + }; } public static void checkIsArrayOnlyOperation(Type arrType, String op) { diff --git a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/utils/Constants.java b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/utils/Constants.java index f63c76213192..dac5637a42c7 100644 --- a/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/utils/Constants.java +++ b/langlib/lang.array/src/main/java/org/ballerinalang/langlib/array/utils/Constants.java @@ -21,7 +21,7 @@ * * @since 2201.9.0 */ -public class Constants { +public final class Constants { public static final String ARRAY_VERSION = "1.1.0"; diff --git a/langlib/lang.boolean/src/main/java/org/ballerinalang/langlib/bool/Every.java b/langlib/lang.boolean/src/main/java/org/ballerinalang/langlib/bool/Every.java index a11bc89e4325..c70ecd464a36 100644 --- a/langlib/lang.boolean/src/main/java/org/ballerinalang/langlib/bool/Every.java +++ b/langlib/lang.boolean/src/main/java/org/ballerinalang/langlib/bool/Every.java @@ -22,7 +22,11 @@ * * @since 2201.5.0 */ -public class Every { +public final class Every { + + private Every() { + } + public static boolean every(boolean[] bs) { for (boolean b : bs) { if (!b) { diff --git a/langlib/lang.boolean/src/main/java/org/ballerinalang/langlib/bool/FromString.java b/langlib/lang.boolean/src/main/java/org/ballerinalang/langlib/bool/FromString.java index 1bef6359ded0..ce8452f72f22 100644 --- a/langlib/lang.boolean/src/main/java/org/ballerinalang/langlib/bool/FromString.java +++ b/langlib/lang.boolean/src/main/java/org/ballerinalang/langlib/bool/FromString.java @@ -40,11 +40,14 @@ // returnType = {@ReturnType(type = TypeKind.UNION)}, // isPublic = true //) -public class FromString { +public final class FromString { private static final BString ERROR_REASON = getModulePrefixedReason(BOOLEAN_LANG_LIB, BOOLEAN_PARSING_ERROR_IDENTIFIER); + private FromString() { + } + public static Object fromString(BString str) { String s = str.getValue(); try { diff --git a/langlib/lang.boolean/src/main/java/org/ballerinalang/langlib/bool/Some.java b/langlib/lang.boolean/src/main/java/org/ballerinalang/langlib/bool/Some.java index a0efe359f0e7..9725f6fce743 100644 --- a/langlib/lang.boolean/src/main/java/org/ballerinalang/langlib/bool/Some.java +++ b/langlib/lang.boolean/src/main/java/org/ballerinalang/langlib/bool/Some.java @@ -22,7 +22,11 @@ * * @since 2201.5.0 */ -public class Some { +public final class Some { + + private Some() { + } + public static boolean some(boolean[] bs) { for (boolean b : bs) { if (b) { diff --git a/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Abs.java b/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Abs.java index af36c7d67e2f..c9e90d3b9ca3 100644 --- a/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Abs.java +++ b/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Abs.java @@ -32,7 +32,10 @@ // returnType = {@ReturnType(type = TypeKind.DECIMAL)}, // isPublic = true //) -public class Abs { +public final class Abs { + + private Abs() { + } public static BDecimal abs(BDecimal n) { return ValueCreator.createDecimalValue(n.value().abs()); diff --git a/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Avg.java b/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Avg.java index baaa68f8a0dc..6a4c5e7ea9ac 100644 --- a/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Avg.java +++ b/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Avg.java @@ -24,7 +24,11 @@ * * @since 2201.6.0 */ -public class Avg { +public final class Avg { + + private Avg() { + } + public static BDecimal avg(BDecimal n, BDecimal[] ns) { BDecimal sum = n; for (BDecimal d : ns) { diff --git a/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Ceiling.java b/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Ceiling.java index c1f896fa4d4d..86b11d68a284 100644 --- a/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Ceiling.java +++ b/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Ceiling.java @@ -34,7 +34,10 @@ // returnType = {@ReturnType(type = TypeKind.DECIMAL)}, // isPublic = true //) -public class Ceiling { +public final class Ceiling { + + private Ceiling() { + } public static BDecimal ceiling(BDecimal x) { return ValueCreator.createDecimalValue(x.value().setScale(0, RoundingMode.CEILING)); diff --git a/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Floor.java b/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Floor.java index 3f0dd36bdfb7..0470300582b3 100644 --- a/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Floor.java +++ b/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Floor.java @@ -34,7 +34,10 @@ // returnType = {@ReturnType(type = TypeKind.DECIMAL)}, // isPublic = true //) -public class Floor { +public final class Floor { + + private Floor() { + } public static BDecimal floor(BDecimal x) { return ValueCreator.createDecimalValue(x.value().setScale(0, RoundingMode.FLOOR)); diff --git a/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/FromString.java b/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/FromString.java index 1939f87cba74..d854af2a0775 100644 --- a/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/FromString.java +++ b/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/FromString.java @@ -41,11 +41,14 @@ // returnType = {@ReturnType(type = TypeKind.UNION)}, // isPublic = true //) -public class FromString { +public final class FromString { private static final BString ERROR_REASON = getModulePrefixedReason(DECIMAL_LANG_LIB, NUMBER_PARSING_ERROR_IDENTIFIER); + private FromString() { + } + public static Object fromString(BString s) { String decimalFloatingPointNumber = s.getValue(); try { diff --git a/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Max.java b/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Max.java index 090514079c1b..1b74b5fe3285 100644 --- a/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Max.java +++ b/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Max.java @@ -31,13 +31,14 @@ // returnType = {@ReturnType(type = TypeKind.DECIMAL)}, // isPublic = true //) -public class Max { +public final class Max { + + private Max() { + } public static BDecimal max(BDecimal n, BDecimal[] ns) { BDecimal max = n; - int size = ns.length; - for (int i = 0; i < size; i++) { - BDecimal current = ns[i]; + for (BDecimal current : ns) { max = current.value().compareTo(max.value()) >= 0 ? current : max; } return max; diff --git a/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Min.java b/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Min.java index 005243d75ee0..111ac3fd3411 100644 --- a/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Min.java +++ b/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Min.java @@ -31,13 +31,14 @@ // returnType = {@ReturnType(type = TypeKind.DECIMAL)}, // isPublic = true //) -public class Min { +public final class Min { + + private Min() { + } public static BDecimal min(BDecimal n, BDecimal[] ns) { BDecimal min = n; - int size = ns.length; - for (int i = 0; i < size; i++) { - BDecimal current = ns[i]; + for (BDecimal current : ns) { min = current.value().compareTo(min.value()) <= 0 ? current : min; } return min; diff --git a/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Quantize.java b/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Quantize.java index 70f7ab133ad3..46b9c400b39d 100644 --- a/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Quantize.java +++ b/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Quantize.java @@ -31,12 +31,15 @@ * * @since 2201.1.0 */ -public class Quantize { +public final class Quantize { // According to IEEE 754-2008 the maximum number of digits in the significand(precision) of // 128-bit decimal (radix 10) floating-point number equals 34. private static final int MAX_DIGITS_IN_SIGNIFICAND = 34; + private Quantize() { + } + public static BDecimal quantize(BDecimal x, BDecimal y) { BigDecimal quantizeValue = x.value().setScale(y.value().scale(), RoundingMode.HALF_EVEN); if (quantizeValue.precision() > MAX_DIGITS_IN_SIGNIFICAND) { diff --git a/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Round.java b/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Round.java index 4f68984ac6bc..e07351597806 100644 --- a/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Round.java +++ b/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Round.java @@ -36,7 +36,10 @@ // returnType = {@ReturnType(type = TypeKind.DECIMAL)}, // isPublic = true //) -public class Round { +public final class Round { + + private Round() { + } public static BDecimal round(BDecimal x, long fractionDigits) { diff --git a/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Sum.java b/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Sum.java index b4a45b851951..ddf44bcf543b 100644 --- a/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Sum.java +++ b/langlib/lang.decimal/src/main/java/org/ballerinalang/langlib/decimal/Sum.java @@ -32,13 +32,15 @@ // returnType = {@ReturnType(type = TypeKind.DECIMAL)}, // isPublic = true //) -public class Sum { +public final class Sum { + + private Sum() { + } public static BDecimal sum(BDecimal[] ns) { BDecimal sum = ValueCreator.createDecimalValue(BigDecimal.ZERO); - int size = ns.length; - for (int i = 0; i < size; i++) { - sum = sum.add(ns[i]); + for (BDecimal n : ns) { + sum = sum.add(n); } return sum; } diff --git a/langlib/lang.error/src/main/java/org/ballerinalang/langlib/error/Cause.java b/langlib/lang.error/src/main/java/org/ballerinalang/langlib/error/Cause.java index 6ad949f6e010..12df182c21fb 100644 --- a/langlib/lang.error/src/main/java/org/ballerinalang/langlib/error/Cause.java +++ b/langlib/lang.error/src/main/java/org/ballerinalang/langlib/error/Cause.java @@ -29,9 +29,12 @@ // functionName = "cause", // args = {@Argument(name = "value", type = TypeKind.ERROR)}, // returnType = {@ReturnType(type = TypeKind.UNION)}) -public class Cause { +public final class Cause { + private Cause() { + } + @Deprecated public static Object cause(BError value) { return value.getCause(); diff --git a/langlib/lang.error/src/main/java/org/ballerinalang/langlib/error/Detail.java b/langlib/lang.error/src/main/java/org/ballerinalang/langlib/error/Detail.java index 76a9c20bb42b..1e99b5f7d0cb 100644 --- a/langlib/lang.error/src/main/java/org/ballerinalang/langlib/error/Detail.java +++ b/langlib/lang.error/src/main/java/org/ballerinalang/langlib/error/Detail.java @@ -30,9 +30,12 @@ // functionName = "detail", // args = {@Argument(name = "value", type = TypeKind.ERROR)}, // returnType = {@ReturnType(type = TypeKind.ANYDATA)}) -public class Detail { +public final class Detail { - public static BMap detail(BError value) { - return (BMap) value.getDetails(); + private Detail() { + } + + public static BMap detail(BError value) { + return (BMap) value.getDetails(); } } diff --git a/langlib/lang.error/src/main/java/org/ballerinalang/langlib/error/Message.java b/langlib/lang.error/src/main/java/org/ballerinalang/langlib/error/Message.java index 33da114bca58..e791ee4adca5 100644 --- a/langlib/lang.error/src/main/java/org/ballerinalang/langlib/error/Message.java +++ b/langlib/lang.error/src/main/java/org/ballerinalang/langlib/error/Message.java @@ -30,9 +30,12 @@ // functionName = "message", // args = {@Argument(name = "value", type = TypeKind.ERROR)}, // returnType = {@ReturnType(type = TypeKind.STRING)}) -public class Message { +public final class Message { + private Message() { + } + @Deprecated public static BString message(BError value) { return value.getErrorMessage(); diff --git a/langlib/lang.error/src/main/java/org/ballerinalang/langlib/error/StackTrace.java b/langlib/lang.error/src/main/java/org/ballerinalang/langlib/error/StackTrace.java index 398f210a2517..f5acb449a94a 100644 --- a/langlib/lang.error/src/main/java/org/ballerinalang/langlib/error/StackTrace.java +++ b/langlib/lang.error/src/main/java/org/ballerinalang/langlib/error/StackTrace.java @@ -54,7 +54,10 @@ * * @since 0.990.4 */ -public class StackTrace { +public final class StackTrace { + + private StackTrace() { + } public static BObject stackTrace(BError value) { @@ -179,7 +182,7 @@ public boolean getBooleanValue(BString fieldName) { } @Override - public BMap getMapValue(BString fieldName) { + public BMap getMapValue(BString fieldName) { return null; } diff --git a/langlib/lang.error/src/main/java/org/ballerinalang/langlib/error/ToBalString.java b/langlib/lang.error/src/main/java/org/ballerinalang/langlib/error/ToBalString.java index 65929cdd3e1c..5e7560880c11 100644 --- a/langlib/lang.error/src/main/java/org/ballerinalang/langlib/error/ToBalString.java +++ b/langlib/lang.error/src/main/java/org/ballerinalang/langlib/error/ToBalString.java @@ -27,7 +27,11 @@ * * @since 2.0.0 */ -public class ToBalString { +public final class ToBalString { + + private ToBalString() { + } + public static BString toBalString(BError value) { return StringUtils.fromString(StringUtils.getExpressionStringValue(value)); } diff --git a/langlib/lang.error/src/main/java/org/ballerinalang/langlib/error/ToString.java b/langlib/lang.error/src/main/java/org/ballerinalang/langlib/error/ToString.java index ef0462541b8b..e853d35f5565 100644 --- a/langlib/lang.error/src/main/java/org/ballerinalang/langlib/error/ToString.java +++ b/langlib/lang.error/src/main/java/org/ballerinalang/langlib/error/ToString.java @@ -27,7 +27,11 @@ * * @since 2.0.0 */ -public class ToString { +public final class ToString { + + private ToString() { + } + public static BString toString(BError value) { return StringUtils.fromString(StringUtils.getStringValue(value)); } diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Abs.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Abs.java index 8a5c39fab48c..4f8738093828 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Abs.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Abs.java @@ -29,7 +29,10 @@ // returnType = {@ReturnType(type = TypeKind.FLOAT)}, // isPublic = true //) -public class Abs { +public final class Abs { + + private Abs() { + } public static double abs(double n) { return Math.abs(n); diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Acos.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Acos.java index 35937024be91..8b0b4eb17f1e 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Acos.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Acos.java @@ -29,7 +29,10 @@ // returnType = {@ReturnType(type = TypeKind.FLOAT)}, // isPublic = true //) -public class Acos { +public final class Acos { + + private Acos() { + } public static double acos(double x) { return Math.acos(x); diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Asin.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Asin.java index 37f4daba2ab5..351451b66212 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Asin.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Asin.java @@ -29,7 +29,10 @@ // returnType = {@ReturnType(type = TypeKind.FLOAT)}, // isPublic = true //) -public class Asin { +public final class Asin { + + private Asin() { + } public static double asin(double x) { return Math.asin(x); diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Atan.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Atan.java index 3bf207866253..4743b0e1f037 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Atan.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Atan.java @@ -29,7 +29,10 @@ // returnType = {@ReturnType(type = TypeKind.FLOAT)}, // isPublic = true //) -public class Atan { +public final class Atan { + + private Atan() { + } public static double atan(double x) { return Math.atan(x); diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Atan2.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Atan2.java index f4d73522d910..bde5c01b2cdd 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Atan2.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Atan2.java @@ -29,7 +29,10 @@ // returnType = {@ReturnType(type = TypeKind.FLOAT)}, // isPublic = true //) -public class Atan2 { +public final class Atan2 { + + private Atan2() { + } public static double atan2(double y, double x) { return Math.atan2(y, x); diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Avg.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Avg.java index 7fb592ded964..34bb58899d24 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Avg.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Avg.java @@ -22,7 +22,11 @@ * * @since 2201.6.0 */ -public class Avg { +public final class Avg { + + private Avg() { + } + public static double avg(double[] ns) { int size = ns.length; if (size == 0) { diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Cbrt.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Cbrt.java index 2b38d599a33d..7e17642335a6 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Cbrt.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Cbrt.java @@ -29,7 +29,10 @@ // returnType = {@ReturnType(type = TypeKind.FLOAT)}, // isPublic = true //) -public class Cbrt { +public final class Cbrt { + + private Cbrt() { + } public static double cbrt(double x) { return Math.cbrt(x); diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Ceiling.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Ceiling.java index c97a4b587ba6..8d1ac56f6c6c 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Ceiling.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Ceiling.java @@ -29,7 +29,10 @@ // returnType = {@ReturnType(type = TypeKind.FLOAT)}, // isPublic = true //) -public class Ceiling { +public final class Ceiling { + + private Ceiling() { + } public static double ceiling(double x) { return Math.ceil(x); diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Cos.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Cos.java index 3361c9d2c08f..c62ce3d95b8d 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Cos.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Cos.java @@ -29,7 +29,10 @@ // returnType = {@ReturnType(type = TypeKind.FLOAT)}, // isPublic = true //) -public class Cos { +public final class Cos { + + private Cos() { + } public static double cos(double x) { return Math.cos(x); diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Cosh.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Cosh.java index 00a42543d308..c280f1b7f28e 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Cosh.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Cosh.java @@ -29,7 +29,10 @@ // returnType = {@ReturnType(type = TypeKind.FLOAT)}, // isPublic = true //) -public class Cosh { +public final class Cosh { + + private Cosh() { + } public static double cosh(double x) { return Math.cosh(x); diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Exp.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Exp.java index 3b74635e105d..bcc2331cb377 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Exp.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Exp.java @@ -29,7 +29,10 @@ // returnType = {@ReturnType(type = TypeKind.FLOAT)}, // isPublic = true //) -public class Exp { +public final class Exp { + + private Exp() { + } public static double exp(double x) { return Math.exp(x); diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Floor.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Floor.java index 23696b6ecc92..e7c62123a72b 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Floor.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Floor.java @@ -29,7 +29,10 @@ // returnType = {@ReturnType(type = TypeKind.FLOAT)}, // isPublic = true //) -public class Floor { +public final class Floor { + + private Floor() { + } public static double floor(double x) { return Math.floor(x); diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/FromBitsInt.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/FromBitsInt.java index fa0beb5a1847..d3dcb123ef0f 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/FromBitsInt.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/FromBitsInt.java @@ -29,7 +29,10 @@ // returnType = {@ReturnType(type = TypeKind.FLOAT)}, // isPublic = true //) -public class FromBitsInt { +public final class FromBitsInt { + + private FromBitsInt() { + } public static double fromBitsInt(long x) { return Double.longBitsToDouble(x); diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/FromHexString.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/FromHexString.java index b6a705ecb098..c3cdfa535323 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/FromHexString.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/FromHexString.java @@ -34,7 +34,7 @@ * * @since 1.0 */ -public class FromHexString { +public final class FromHexString { private static final Pattern HEX_FLOAT_LITERAL = Pattern.compile("[-+]?0[xX][\\dA-Fa-f.pP\\-+]+"); @@ -54,15 +54,10 @@ public static Object fromHexString(BString s) { } private static boolean isValidHexString(String hexValue) { - switch (hexValue) { - case "+infinity": - case "-infinity": - case "infinity": - case "nan": - return true; - default: - return HEX_FLOAT_LITERAL.matcher(hexValue).matches(); - } + return switch (hexValue) { + case "+infinity", "-infinity", "infinity", "nan" -> true; + default -> HEX_FLOAT_LITERAL.matcher(hexValue).matches(); + }; } private static BError getNumberFormatError(String message) { diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/FromString.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/FromString.java index adbee0a2acfb..afd6f05dfa02 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/FromString.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/FromString.java @@ -41,11 +41,14 @@ // returnType = {@ReturnType(type = TypeKind.UNION)}, // isPublic = true //) -public class FromString { +public final class FromString { private static final BString ERROR_REASON = getModulePrefixedReason(FLOAT_LANG_LIB, NUMBER_PARSING_ERROR_IDENTIFIER); + private FromString() { + } + public static Object fromString(BString s) { String decimalFloatingPointNumber = s.getValue(); try { diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/IsFinite.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/IsFinite.java index e93908675fee..c3be486e09f9 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/IsFinite.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/IsFinite.java @@ -29,7 +29,10 @@ // returnType = {@ReturnType(type = TypeKind.BOOLEAN)}, // isPublic = true //) -public class IsFinite { +public final class IsFinite { + + private IsFinite() { + } public static boolean isFinite(double x) { return Double.isFinite(x); diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/IsInfinite.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/IsInfinite.java index a58a9cec794a..96981d0bd196 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/IsInfinite.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/IsInfinite.java @@ -29,7 +29,10 @@ // returnType = {@ReturnType(type = TypeKind.BOOLEAN)}, // isPublic = true //) -public class IsInfinite { +public final class IsInfinite { + + private IsInfinite() { + } public static boolean isInfinite(double x) { return Double.isInfinite(x); diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/IsNaN.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/IsNaN.java index f1b3210b3013..555d575ec187 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/IsNaN.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/IsNaN.java @@ -29,7 +29,10 @@ // returnType = {@ReturnType(type = TypeKind.BOOLEAN)}, // isPublic = true //) -public class IsNaN { +public final class IsNaN { + + private IsNaN() { + } public static boolean isNaN(double x) { return Double.isNaN(x); diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Log.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Log.java index 7863a5cd2241..d2dfaa2b4140 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Log.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Log.java @@ -29,7 +29,10 @@ // returnType = {@ReturnType(type = TypeKind.FLOAT)}, // isPublic = true //) -public class Log { +public final class Log { + + private Log() { + } public static double log(double x) { return Math.log(x); diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Log10.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Log10.java index 5b695140cf7b..d996a1c0196f 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Log10.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Log10.java @@ -29,7 +29,10 @@ // returnType = {@ReturnType(type = TypeKind.FLOAT)}, // isPublic = true //) -public class Log10 { +public final class Log10 { + + private Log10() { + } public static double log10(double x) { return Math.log10(x); diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Max.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Max.java index 9954529a2699..f76d5498e094 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Max.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Max.java @@ -29,7 +29,7 @@ // returnType = {@ReturnType(type = TypeKind.FLOAT)}, // isPublic = true //) -public class Max { +public final class Max { private Max() { } diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Min.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Min.java index 27e3c014504a..31bd51a837f9 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Min.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Min.java @@ -29,7 +29,7 @@ // returnType = {@ReturnType(type = TypeKind.FLOAT)}, // isPublic = true //) -public class Min { +public final class Min { private Min() { } diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Pow.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Pow.java index ea5c8312a247..e29922469e88 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Pow.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Pow.java @@ -29,7 +29,10 @@ // returnType = {@ReturnType(type = TypeKind.FLOAT)}, // isPublic = true //) -public class Pow { +public final class Pow { + + private Pow() { + } public static double pow(double x, double y) { return Math.pow(x, y); diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Round.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Round.java index dea8cfbb9a7d..6b0cce3093ab 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Round.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Round.java @@ -32,7 +32,10 @@ // returnType = {@ReturnType(type = TypeKind.FLOAT)}, // isPublic = true //) -public class Round { +public final class Round { + + private Round() { + } public static double round(double x, long fractionDigits) { if (Double.isInfinite(x) || Double.isNaN(x) || x == 0.0d) { diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Sin.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Sin.java index d36861c4649f..53cf66c20bc9 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Sin.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Sin.java @@ -29,7 +29,10 @@ // returnType = {@ReturnType(type = TypeKind.FLOAT)}, // isPublic = true //) -public class Sin { +public final class Sin { + + private Sin() { + } public static double sin(double x) { return Math.sin(x); diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Sinh.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Sinh.java index b0aa1b63209c..66749c6a1a42 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Sinh.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Sinh.java @@ -29,7 +29,10 @@ // returnType = {@ReturnType(type = TypeKind.FLOAT)}, // isPublic = true //) -public class Sinh { +public final class Sinh { + + private Sinh() { + } public static double sinh(double x) { return Math.sinh(x); diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Sqrt.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Sqrt.java index 7d20e4c2a10d..a416ec6501ed 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Sqrt.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Sqrt.java @@ -29,7 +29,10 @@ // returnType = {@ReturnType(type = TypeKind.FLOAT)}, // isPublic = true //) -public class Sqrt { +public final class Sqrt { + + private Sqrt() { + } public static double sqrt(double x) { return Math.sqrt(x); diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Sum.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Sum.java index 1bae5746779a..e13f44439e2b 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Sum.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Sum.java @@ -27,13 +27,15 @@ // returnType = {@ReturnType(type = TypeKind.FLOAT)}, // isPublic = true //) -public class Sum { +public final class Sum { + + private Sum() { + } public static double sum(double[] ns) { double sum = 0; - int size = ns.length; - for (int i = 0; i < size; i++) { - sum += ns[i]; + for (double n : ns) { + sum += n; } return sum; } diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Tan.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Tan.java index fa3cff51a05e..9b57d5e7fa8b 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Tan.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Tan.java @@ -29,7 +29,10 @@ // returnType = {@ReturnType(type = TypeKind.FLOAT)}, // isPublic = true //) -public class Tan { +public final class Tan { + + private Tan() { + } public static double tan(double x) { return Math.tan(x); diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Tanh.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Tanh.java index 53b419d86f9d..047d6575ce8b 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Tanh.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/Tanh.java @@ -23,7 +23,10 @@ * * @since 1.0 */ -public class Tanh { +public final class Tanh { + + private Tanh() { + } public static double tanh(double x) { return Math.tanh(x); diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/ToBitsInt.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/ToBitsInt.java index c91a6275b489..37036a52a4f2 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/ToBitsInt.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/ToBitsInt.java @@ -29,7 +29,10 @@ // returnType = {@ReturnType(type = TypeKind.INT)}, // isPublic = true //) -public class ToBitsInt { +public final class ToBitsInt { + + private ToBitsInt() { + } public static long toBitsInt(double x) { return Double.doubleToLongBits(x); diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/ToExpString.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/ToExpString.java index af946f9604ff..b5d4993600ea 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/ToExpString.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/ToExpString.java @@ -32,7 +32,10 @@ * * @since 2201.1.0 */ -public class ToExpString { +public final class ToExpString { + + private ToExpString() { + } public static BString toExpString(double x, Object fractionDigits) { // If `x` is NaN or infinite, the result will be the same as `value:toString`. diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/ToFixedString.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/ToFixedString.java index 61edb256182a..e7cad36e8069 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/ToFixedString.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/ToFixedString.java @@ -31,7 +31,10 @@ * * @since 2201.1.0 */ -public class ToFixedString { +public final class ToFixedString { + + private ToFixedString() { + } public static BString toFixedString(double x, Object fractionDigits) { // If `x` is NaN or infinite, the result will be the same as `value:toString`. diff --git a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/ToHexString.java b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/ToHexString.java index 507dbdd090d3..3cd52a1d7f27 100644 --- a/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/ToHexString.java +++ b/langlib/lang.float/src/main/java/org/ballerinalang/langlib/floatingpoint/ToHexString.java @@ -26,7 +26,10 @@ * * @since 1.0 */ -public class ToHexString { +public final class ToHexString { + + private ToHexString() { + } public static BString toHexString(double n) { return StringUtils.fromString(Double.toHexString(n)); diff --git a/langlib/lang.function/src/main/java/org/ballerinalang/langlib/function/Call.java b/langlib/lang.function/src/main/java/org/ballerinalang/langlib/function/Call.java index 3512ddb5e1bd..8d34453f18b6 100644 --- a/langlib/lang.function/src/main/java/org/ballerinalang/langlib/function/Call.java +++ b/langlib/lang.function/src/main/java/org/ballerinalang/langlib/function/Call.java @@ -33,6 +33,7 @@ import io.ballerina.runtime.internal.values.ArrayValueImpl; import io.ballerina.runtime.internal.values.ListInitialValueEntry; +import java.util.ArrayList; import java.util.LinkedList; import java.util.List; @@ -46,16 +47,19 @@ * * @since 2201.2.0 */ -public class Call { +public final class Call { private static final StrandMetadata METADATA = new StrandMetadata(BALLERINA_BUILTIN_PKG_PREFIX, FUNCTION_LANG_LIB, "1.0.0", "call"); + private Call() { + } + public static Object call(BFunctionPointer func, Object... args) { BFunctionType functionType = (BFunctionType) TypeUtils.getImpliedType(func.getType()); List paramTypes = new LinkedList<>(); List argTypes = new LinkedList<>(); - List argsList = new java.util.ArrayList<>(); + List argsList = new ArrayList<>(); if (checkIsValidPositionalArgs(args, argsList, functionType, paramTypes, argTypes) || checkIsValidRestArgs(args, argsList, functionType, paramTypes, argTypes)) { diff --git a/langlib/lang.future/src/main/java/org/ballerinalang/langlib/future/Cancel.java b/langlib/lang.future/src/main/java/org/ballerinalang/langlib/future/Cancel.java index 76a82d3a22eb..2c29a0c9016e 100644 --- a/langlib/lang.future/src/main/java/org/ballerinalang/langlib/future/Cancel.java +++ b/langlib/lang.future/src/main/java/org/ballerinalang/langlib/future/Cancel.java @@ -26,7 +26,10 @@ // args = {@Argument(name = "f", type = TypeKind.FUTURE)}, // isPublic = true //) -public class Cancel { +public final class Cancel { + + private Cancel() { + } public static void cancel(BFuture futureValue) { futureValue.cancel(); diff --git a/langlib/lang.int/src/main/java/org/ballerinalang/langlib/integer/Abs.java b/langlib/lang.int/src/main/java/org/ballerinalang/langlib/integer/Abs.java index edfacf0b70ec..d4d6109c595a 100644 --- a/langlib/lang.int/src/main/java/org/ballerinalang/langlib/integer/Abs.java +++ b/langlib/lang.int/src/main/java/org/ballerinalang/langlib/integer/Abs.java @@ -37,7 +37,10 @@ // returnType = {@ReturnType(type = TypeKind.INT)}, // isPublic = true //) -public class Abs { +public final class Abs { + + private Abs() { + } public static long abs(long n) { if (n <= Long.MIN_VALUE) { diff --git a/langlib/lang.int/src/main/java/org/ballerinalang/langlib/integer/Avg.java b/langlib/lang.int/src/main/java/org/ballerinalang/langlib/integer/Avg.java index 44edf66a42a0..4f13992db106 100644 --- a/langlib/lang.int/src/main/java/org/ballerinalang/langlib/integer/Avg.java +++ b/langlib/lang.int/src/main/java/org/ballerinalang/langlib/integer/Avg.java @@ -24,7 +24,10 @@ * * @since 2201.6.0 */ -public class Avg { +public final class Avg { + + private Avg() { + } public static BDecimal avg(long n, long[] ns) { BDecimal sum = BDecimal.valueOf(n); diff --git a/langlib/lang.int/src/main/java/org/ballerinalang/langlib/integer/FromHexString.java b/langlib/lang.int/src/main/java/org/ballerinalang/langlib/integer/FromHexString.java index dbf8f94c6f1f..67e867b72c2c 100644 --- a/langlib/lang.int/src/main/java/org/ballerinalang/langlib/integer/FromHexString.java +++ b/langlib/lang.int/src/main/java/org/ballerinalang/langlib/integer/FromHexString.java @@ -31,7 +31,10 @@ * * @since 1.0 */ -public class FromHexString { +public final class FromHexString { + + private FromHexString() { + } public static Object fromHexString(BString s) { try { diff --git a/langlib/lang.int/src/main/java/org/ballerinalang/langlib/integer/FromString.java b/langlib/lang.int/src/main/java/org/ballerinalang/langlib/integer/FromString.java index a0ac8c5de1fe..83e4b6ea4854 100644 --- a/langlib/lang.int/src/main/java/org/ballerinalang/langlib/integer/FromString.java +++ b/langlib/lang.int/src/main/java/org/ballerinalang/langlib/integer/FromString.java @@ -40,10 +40,13 @@ // returnType = {@ReturnType(type = TypeKind.UNION)}, // isPublic = true //) -public class FromString { +public final class FromString { private static final BString ERROR_REASON = getModulePrefixedReason(INT_LANG_LIB, NUMBER_PARSING_ERROR_IDENTIFIER); + private FromString() { + } + public static Object fromString(BString s) { try { return TypeConverter.stringToInt(s.getValue()); diff --git a/langlib/lang.int/src/main/java/org/ballerinalang/langlib/integer/Max.java b/langlib/lang.int/src/main/java/org/ballerinalang/langlib/integer/Max.java index 9eeb6710ebad..7576148e76af 100644 --- a/langlib/lang.int/src/main/java/org/ballerinalang/langlib/integer/Max.java +++ b/langlib/lang.int/src/main/java/org/ballerinalang/langlib/integer/Max.java @@ -29,13 +29,14 @@ // returnType = {@ReturnType(type = TypeKind.INT)}, // isPublic = true //) -public class Max { +public final class Max { + + private Max() { + } public static long max(long n, long[] ns) { long max = n; - int size = ns.length; - for (int i = 0; i < size; i++) { - long current = ns[i]; + for (long current : ns) { max = current >= max ? current : max; } return max; diff --git a/langlib/lang.int/src/main/java/org/ballerinalang/langlib/integer/Min.java b/langlib/lang.int/src/main/java/org/ballerinalang/langlib/integer/Min.java index 8dded76733b6..90e703467204 100644 --- a/langlib/lang.int/src/main/java/org/ballerinalang/langlib/integer/Min.java +++ b/langlib/lang.int/src/main/java/org/ballerinalang/langlib/integer/Min.java @@ -29,13 +29,14 @@ // returnType = {@ReturnType(type = TypeKind.INT)}, // isPublic = true //) -public class Min { +public final class Min { + + private Min() { + } public static long min(long n, long[] ns) { long min = n; - int size = ns.length; - for (int i = 0; i < size; i++) { - long current = ns[i]; + for (long current : ns) { min = current <= min ? current : min; } return min; diff --git a/langlib/lang.int/src/main/java/org/ballerinalang/langlib/integer/Sum.java b/langlib/lang.int/src/main/java/org/ballerinalang/langlib/integer/Sum.java index 70b2aa41a132..fc2c633bd383 100644 --- a/langlib/lang.int/src/main/java/org/ballerinalang/langlib/integer/Sum.java +++ b/langlib/lang.int/src/main/java/org/ballerinalang/langlib/integer/Sum.java @@ -34,7 +34,10 @@ // returnType = {@ReturnType(type = TypeKind.INT)}, // isPublic = true //) -public class Sum { +public final class Sum { + + private Sum() { + } public static long sum(long[] ns) { long sum = 0; diff --git a/langlib/lang.int/src/main/java/org/ballerinalang/langlib/integer/ToHexString.java b/langlib/lang.int/src/main/java/org/ballerinalang/langlib/integer/ToHexString.java index 817924771652..c5930491fce1 100644 --- a/langlib/lang.int/src/main/java/org/ballerinalang/langlib/integer/ToHexString.java +++ b/langlib/lang.int/src/main/java/org/ballerinalang/langlib/integer/ToHexString.java @@ -26,7 +26,10 @@ * * @since 1.0 */ -public class ToHexString { +public final class ToHexString { + + private ToHexString() { + } public static BString toHexString(long n) { if (n < 0) { diff --git a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/Entries.java b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/Entries.java index f64d0a93ee88..14076267715a 100644 --- a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/Entries.java +++ b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/Entries.java @@ -44,7 +44,10 @@ // returnType = {@ReturnType(type = TypeKind.MAP)}, // isPublic = true //) -public class Entries { +public final class Entries { + + private Entries() { + } public static BMap entries(BMap m) { Type newFieldType = getFieldType(m.getType(), "entries()"); diff --git a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/Filter.java b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/Filter.java index ecc520bd02a4..d9d2c06f0159 100644 --- a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/Filter.java +++ b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/Filter.java @@ -45,25 +45,24 @@ * * @since 1.0 */ -public class Filter { +public final class Filter { private static final StrandMetadata METADATA = new StrandMetadata(BALLERINA_BUILTIN_PKG_PREFIX, MAP_LANG_LIB, MAP_VERSION, "filter"); - public static BMap filter(BMap m, BFunctionPointer func) { + private Filter() { + } + + public static BMap filter(BMap m, BFunctionPointer func) { Type mapType = TypeUtils.getImpliedType(m.getType()); - Type constraint; - switch (mapType.getTag()) { - case TypeTags.MAP_TAG: + Type constraint = switch (mapType.getTag()) { + case TypeTags.MAP_TAG -> { MapType type = (MapType) mapType; - constraint = type.getConstrainedType(); - break; - case TypeTags.RECORD_TYPE_TAG: - constraint = MapLibUtils.getCommonTypeForRecordField((RecordType) mapType); - break; - default: - throw createOpNotSupportedError(mapType, "filter()"); - } + yield type.getConstrainedType(); + } + case TypeTags.RECORD_TYPE_TAG -> MapLibUtils.getCommonTypeForRecordField((RecordType) mapType); + default -> throw createOpNotSupportedError(mapType, "filter()"); + }; BMap newMap = ValueCreator.createMapValue(TypeCreator.createMapType(constraint)); int size = m.size(); AtomicInteger index = new AtomicInteger(-1); diff --git a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/ForEach.java b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/ForEach.java index 6b5f4876f8a9..2c3a590b072f 100644 --- a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/ForEach.java +++ b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/ForEach.java @@ -35,12 +35,15 @@ * * @since 1.0 */ -public class ForEach { +public final class ForEach { private static final StrandMetadata METADATA = new StrandMetadata(BALLERINA_BUILTIN_PKG_PREFIX, MAP_LANG_LIB, MAP_VERSION, "forEach"); - public static void forEach(BMap m, BFunctionPointer func) { + private ForEach() { + } + + public static void forEach(BMap m, BFunctionPointer func) { int size = m.size(); AtomicInteger index = new AtomicInteger(-1); Object[] keys = m.getKeys(); diff --git a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/Get.java b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/Get.java index 6e2a92083cb4..7c561c2bfaa8 100644 --- a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/Get.java +++ b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/Get.java @@ -26,7 +26,10 @@ * * @since 1.0 */ -public class Get { +public final class Get { + + private Get() { + } public static Object get(BMap m, BString k) { return m.getOrThrow(k); diff --git a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/GetIterator.java b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/GetIterator.java index 6e6f005a10c2..70fb72e73ccd 100644 --- a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/GetIterator.java +++ b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/GetIterator.java @@ -32,9 +32,12 @@ // returnType = {@ReturnType(type = TypeKind.OBJECT)}, // isPublic = true //) -public class GetIterator { +public final class GetIterator { - public static BIterator iterator(BMap map) { + private GetIterator() { + } + + public static BIterator iterator(BMap map) { return map.getIterator(); } } diff --git a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/GetKeys.java b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/GetKeys.java index fd1c8845ad0e..3fda8476538b 100644 --- a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/GetKeys.java +++ b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/GetKeys.java @@ -34,7 +34,10 @@ // returnType = {@ReturnType(type = TypeKind.ARRAY, elementType = TypeKind.STRING)}, // isPublic = true //) -public class GetKeys { +public final class GetKeys { + + private GetKeys() { + } public static BArray keys(BMap m) { return ValueCreator.createArrayValue((BString[]) m.getKeys()); diff --git a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/HasKey.java b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/HasKey.java index ecab9b33b158..2898f260b242 100644 --- a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/HasKey.java +++ b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/HasKey.java @@ -31,7 +31,10 @@ // returnType = {@ReturnType(type = TypeKind.BOOLEAN)}, // isPublic = true //) -public class HasKey { +public final class HasKey { + + private HasKey() { + } @Deprecated public static boolean hasKey(BMap m, BString k) { diff --git a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/Length.java b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/Length.java index 37ad4de2f8f6..9ca1d1b634c3 100644 --- a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/Length.java +++ b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/Length.java @@ -30,7 +30,10 @@ // args = {@Argument(name = "m", type = TypeKind.MAP)}, // isPublic = true //) -public class Length { +public final class Length { + + private Length() { + } public static long length(BMap m) { return m.size(); diff --git a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/Map.java b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/Map.java index 5d183c98197c..9c5a93a15c4f 100644 --- a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/Map.java +++ b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/Map.java @@ -47,12 +47,15 @@ // returnType = {@ReturnType(type = TypeKind.MAP)}, // isPublic = true //) -public class Map { +public final class Map { private static final StrandMetadata METADATA = new StrandMetadata(BALLERINA_BUILTIN_PKG_PREFIX, MAP_LANG_LIB, MAP_VERSION, "map"); - public static BMap map(BMap m, BFunctionPointer func) { + private Map() { + } + + public static BMap map(BMap m, BFunctionPointer func) { MapType newMapType = TypeCreator.createMapType( ((FunctionType) TypeUtils.getImpliedType(func.getType())).getReturnType()); BMap newMap = ValueCreator.createMapValue(newMapType); diff --git a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/Next.java b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/Next.java index 1d8560b4880b..aa1eb733e2fb 100644 --- a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/Next.java +++ b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/Next.java @@ -38,11 +38,15 @@ // returnType = {@ReturnType(type = TypeKind.RECORD)}, // isPublic = true //) -public class Next { +public final class Next { + + private Next() { + } + //TODO: refactor hard coded values public static Object next(BObject m) { - BIterator mapIterator = (BIterator) m.getNativeData("&iterator&"); - BMap bMap = (BMap) m.get(StringUtils.fromString("m")); + BIterator mapIterator = (BIterator) m.getNativeData("&iterator&"); + BMap bMap = (BMap) m.get(StringUtils.fromString("m")); if (mapIterator == null) { mapIterator = bMap.getIterator(); m.addNativeData("&iterator&", mapIterator); diff --git a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/Reduce.java b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/Reduce.java index ea2c0d9522cf..f94e1a0113af 100644 --- a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/Reduce.java +++ b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/Reduce.java @@ -36,12 +36,12 @@ * * @since 1.0 */ -public class Reduce { +public final class Reduce { private static final StrandMetadata METADATA = new StrandMetadata(BALLERINA_BUILTIN_PKG_PREFIX, MAP_LANG_LIB, MAP_VERSION, "reduce"); - public static Object reduce(BMap m, BFunctionPointer func, Object initial) { + public static Object reduce(BMap m, BFunctionPointer func, Object initial) { int size = m.values().size(); AtomicReference accum = new AtomicReference<>(initial); AtomicInteger index = new AtomicInteger(-1); diff --git a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/Remove.java b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/Remove.java index afac130f12f5..34914231ca15 100644 --- a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/Remove.java +++ b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/Remove.java @@ -37,7 +37,10 @@ * Extern function to remove element from the map. * ballerina.model.map:remove(string) */ -public class Remove { +public final class Remove { + + private Remove() { + } public static Object remove(BMap m, BString k) { Type type = TypeUtils.getImpliedType(m.getType()); diff --git a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/RemoveAll.java b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/RemoveAll.java index cc0ad721ea11..ed37ebbaefca 100644 --- a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/RemoveAll.java +++ b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/RemoveAll.java @@ -34,7 +34,10 @@ * * @since 1.0 */ -public class RemoveAll { +public final class RemoveAll { + + private RemoveAll() { + } public static void removeAll(BMap m) { checkIsMapOnlyOperation(TypeUtils.getImpliedType(m.getType()), "removeAll()"); diff --git a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/RemoveIfHasKey.java b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/RemoveIfHasKey.java index bda4d4f42472..93dc35f3cfa4 100644 --- a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/RemoveIfHasKey.java +++ b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/RemoveIfHasKey.java @@ -35,7 +35,10 @@ * * @since 1.2.0 */ -public class RemoveIfHasKey { +public final class RemoveIfHasKey { + + private RemoveIfHasKey() { + } public static Object removeIfHasKey(BMap m, BString k) { String op = "removeIfHasKey()"; diff --git a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/ToArray.java b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/ToArray.java index 41a0d0e6d007..5af3ac08cd02 100644 --- a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/ToArray.java +++ b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/ToArray.java @@ -46,23 +46,20 @@ // returnType = {@ReturnType(type = TypeKind.ARRAY, elementType = TypeKind.ANY)}, // isPublic = true //) -public class ToArray { +public final class ToArray { + + private ToArray() { + } public static BArray toArray(BMap m) { Type mapType = TypeUtils.getImpliedType(m.getType()); - Type arrElemType; - switch (mapType.getTag()) { - case TypeTags.MAP_TAG: - arrElemType = ((MapType) mapType).getConstrainedType(); - break; - case TypeTags.RECORD_TYPE_TAG: - arrElemType = MapLibUtils.getCommonTypeForRecordField((RecordType) mapType); - break; - default: - throw createOpNotSupportedError(mapType, "toArray()"); - } + Type arrElemType = switch (mapType.getTag()) { + case TypeTags.MAP_TAG -> ((MapType) mapType).getConstrainedType(); + case TypeTags.RECORD_TYPE_TAG -> MapLibUtils.getCommonTypeForRecordField((RecordType) mapType); + default -> throw createOpNotSupportedError(mapType, "toArray()"); + }; - Collection values = m.values(); + Collection values = m.values(); int size = values.size(); int i = 0; switch (TypeUtils.getImpliedType(arrElemType).getTag()) { diff --git a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/util/Constants.java b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/util/Constants.java index a2a4ada9142b..0fa315048c02 100644 --- a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/util/Constants.java +++ b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/util/Constants.java @@ -21,7 +21,7 @@ * * @since 2201.9.0 */ -public class Constants { +public final class Constants { public static final String MAP_VERSION = "1.1.0"; public static final String REMOVE = "remove()"; diff --git a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/util/MapLibUtils.java b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/util/MapLibUtils.java index 5d1cd480b718..bfb5952f3ea3 100644 --- a/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/util/MapLibUtils.java +++ b/langlib/lang.map/src/main/java/org/ballerinalang/langlib/map/util/MapLibUtils.java @@ -47,18 +47,18 @@ * * @since 1.0 */ -public class MapLibUtils { +public final class MapLibUtils { + + private MapLibUtils() { + } public static Type getFieldType(Type mapType, String funcName) { mapType = TypeUtils.getImpliedType(mapType); - switch (mapType.getTag()) { - case TypeTags.MAP_TAG: - return ((MapType) mapType).getConstrainedType(); - case TypeTags.RECORD_TYPE_TAG: - return getCommonTypeForRecordField((RecordType) mapType); - default: - throw createOpNotSupportedError(mapType, funcName); - } + return switch (mapType.getTag()) { + case TypeTags.MAP_TAG -> ((MapType) mapType).getConstrainedType(); + case TypeTags.RECORD_TYPE_TAG -> getCommonTypeForRecordField((RecordType) mapType); + default -> throw createOpNotSupportedError(mapType, funcName); + }; } public static Type getCommonTypeForRecordField(RecordType recordType) { @@ -76,7 +76,7 @@ public static Type getCommonTypeForRecordField(RecordType recordType) { return typeSet.size() == 1 ? typeSet.iterator().next() : TypeCreator.createUnionType(new ArrayList<>(typeSet)); } - public static void validateRecord(BMap m) { + public static void validateRecord(BMap m) { Type type = TypeUtils.getImpliedType(m.getType()); if (type.getTag() != TypeTags.RECORD_TYPE_TAG) { return; @@ -102,7 +102,7 @@ private static BError createOpNotSupportedErrorForRecord(Type type, String field ErrorCodes.FIELD_REMOVAL_NOT_ALLOWED, field, type.getQualifiedName())); } - public static void validateRequiredFieldForRecord(BMap m, String k) { + public static void validateRequiredFieldForRecord(BMap m, String k) { Type type = TypeUtils.getImpliedType(m.getType()); if (type.getTag() == TypeTags.RECORD_TYPE_TAG && isRequiredField((RecordType) type, k)) { throw createOpNotSupportedErrorForRecord(type, k); diff --git a/langlib/lang.query/src/main/java/org/ballerinalang/langlib/query/CheckNaN.java b/langlib/lang.query/src/main/java/org/ballerinalang/langlib/query/CheckNaN.java index c17d0045ca26..2d331ddbf9c5 100644 --- a/langlib/lang.query/src/main/java/org/ballerinalang/langlib/query/CheckNaN.java +++ b/langlib/lang.query/src/main/java/org/ballerinalang/langlib/query/CheckNaN.java @@ -22,7 +22,10 @@ * * @since Swan Lake */ -public class CheckNaN { +public final class CheckNaN { + + private CheckNaN() { + } public static boolean checkNaN(double x) { return Double.isNaN(x); diff --git a/langlib/lang.query/src/main/java/org/ballerinalang/langlib/query/CreateImmutableType.java b/langlib/lang.query/src/main/java/org/ballerinalang/langlib/query/CreateImmutableType.java index 815be504771a..b89b4aad5fb5 100644 --- a/langlib/lang.query/src/main/java/org/ballerinalang/langlib/query/CreateImmutableType.java +++ b/langlib/lang.query/src/main/java/org/ballerinalang/langlib/query/CreateImmutableType.java @@ -17,25 +17,28 @@ * @since 2201.2.0 */ -public class CreateImmutableType { +public final class CreateImmutableType { + + private CreateImmutableType() { + } public static void createImmutableValue(BRefValue value) { value.freezeDirect(); } - public static BTable createImmutableTable(BTable tbl, BArray arr) { + public static BTable createImmutableTable(BTable tbl, BArray arr) { Type type = tbl.getType(); TableType tableType = (TableType) TypeUtils.getImpliedType(type); - BTable immutableTable = new TableValueImpl(type, + BTable immutableTable = new TableValueImpl<>(type, new ArrayValueImpl(arr.getValues(), (ArrayType) TypeUtils.getImpliedType(arr.getType())), new ArrayValueImpl(tableType.getFieldNames(), true)); immutableTable.freezeDirect(); return immutableTable; } - public static BTable createTableWithKeySpecifier(BTable immutableTable, BTypedesc tableType) { + public static BTable createTableWithKeySpecifier(BTable immutableTable, BTypedesc tableType) { TableType type = (TableType) TypeUtils.getImpliedType(tableType.getDescribingType()); - BTable tbl = new TableValueImpl(type, + BTable tbl = new TableValueImpl<>(type, new ArrayValueImpl(((TableType) TypeUtils.getImpliedType(immutableTable.getType())).getFieldNames(), false)); return tbl; diff --git a/langlib/lang.regexp/src/main/java/org/ballerinalang/langlib/regexp/Find.java b/langlib/lang.regexp/src/main/java/org/ballerinalang/langlib/regexp/Find.java index b69bf2b62df8..cafe813faaf0 100644 --- a/langlib/lang.regexp/src/main/java/org/ballerinalang/langlib/regexp/Find.java +++ b/langlib/lang.regexp/src/main/java/org/ballerinalang/langlib/regexp/Find.java @@ -35,7 +35,10 @@ * * @since 2201.3.0 */ -public class Find { +public final class Find { + + private Find() { + } public static BArray find(BRegexpValue regExp, BString str, long startIndex) { checkIndexWithinRange(str, startIndex); diff --git a/langlib/lang.regexp/src/main/java/org/ballerinalang/langlib/regexp/FromString.java b/langlib/lang.regexp/src/main/java/org/ballerinalang/langlib/regexp/FromString.java index a31cf66e2836..e5681f7b0e29 100644 --- a/langlib/lang.regexp/src/main/java/org/ballerinalang/langlib/regexp/FromString.java +++ b/langlib/lang.regexp/src/main/java/org/ballerinalang/langlib/regexp/FromString.java @@ -30,11 +30,14 @@ * * @since 2201.3.0 */ -public class FromString { +public final class FromString { private static final BString ERROR_REASON = getModulePrefixedReason(REGEXP_LANG_LIB, REG_EXP_PARSING_ERROR_IDENTIFIER); + private FromString() { + } + public static Object fromString(BString string) { try { return TypeConverter.stringToRegExp(string.getValue()); diff --git a/langlib/lang.regexp/src/main/java/org/ballerinalang/langlib/regexp/Matches.java b/langlib/lang.regexp/src/main/java/org/ballerinalang/langlib/regexp/Matches.java index 76f6371b223d..0b70603e8a1b 100644 --- a/langlib/lang.regexp/src/main/java/org/ballerinalang/langlib/regexp/Matches.java +++ b/langlib/lang.regexp/src/main/java/org/ballerinalang/langlib/regexp/Matches.java @@ -33,7 +33,11 @@ * * @since 2201.3.0 */ -public class Matches { +public final class Matches { + + private Matches() { + } + public static BArray matchAt(BRegexpValue regExp, BString str, int startIndex) { checkIndexWithinRange(str, startIndex); Matcher matcher = RegexUtil.getMatcher(regExp, str); diff --git a/langlib/lang.regexp/src/main/java/org/ballerinalang/langlib/regexp/RegexUtil.java b/langlib/lang.regexp/src/main/java/org/ballerinalang/langlib/regexp/RegexUtil.java index 9d2f9bc4726a..642d3ece809c 100644 --- a/langlib/lang.regexp/src/main/java/org/ballerinalang/langlib/regexp/RegexUtil.java +++ b/langlib/lang.regexp/src/main/java/org/ballerinalang/langlib/regexp/RegexUtil.java @@ -43,13 +43,18 @@ * * @since 2201.3.0 */ -public class RegexUtil { +public final class RegexUtil { + static final BTupleType SPAN_AS_TUPLE_TYPE = new BTupleType(List.of(PredefinedTypes.TYPE_INT, PredefinedTypes.TYPE_INT, PredefinedTypes.TYPE_STRING)); static final BArrayType GROUPS_AS_SPAN_ARRAY_TYPE = new BArrayType(SPAN_AS_TUPLE_TYPE); static final BArrayType GROUPS_ARRAY_TYPE = new BArrayType(GROUPS_AS_SPAN_ARRAY_TYPE); + + private RegexUtil() { + } + static Matcher getMatcher(BRegexpValue regexpVal, BString inputStr) { try { return getMatcher(regexpVal, inputStr.getValue()); @@ -60,8 +65,8 @@ static Matcher getMatcher(BRegexpValue regexpVal, BString inputStr) { } static int[] getSurrogatePositions(BString str) { - if (str instanceof NonBmpStringValue) { - return ((NonBmpStringValue) str).getSurrogates(); + if (str instanceof NonBmpStringValue nonBmpStringValue) { + return nonBmpStringValue.getSurrogates(); } return new int[0]; } @@ -147,7 +152,7 @@ public static long length(BString value) { return value.length(); } - protected static void checkIndexWithinRange(BString str, long startIndex) { + static void checkIndexWithinRange(BString str, long startIndex) { if (startIndex != (int) startIndex) { throw ErrorHelper.getRuntimeException(ErrorReasons.REGEXP_OPERATION_ERROR, ErrorCodes.INDEX_NUMBER_TOO_LARGE, startIndex); diff --git a/langlib/lang.regexp/src/main/java/org/ballerinalang/langlib/regexp/Split.java b/langlib/lang.regexp/src/main/java/org/ballerinalang/langlib/regexp/Split.java index f9c8a0f80e9b..12c7adffe9bc 100644 --- a/langlib/lang.regexp/src/main/java/org/ballerinalang/langlib/regexp/Split.java +++ b/langlib/lang.regexp/src/main/java/org/ballerinalang/langlib/regexp/Split.java @@ -30,7 +30,10 @@ * * @since 2201.3.0 */ -public class Split { +public final class Split { + + private Split() { + } public static BArray split(BRegexpValue regExp, BString str) { String originalString = str.getValue(); diff --git a/langlib/lang.runtime/src/main/java/org/ballerinalang/langlib/runtime/Constants.java b/langlib/lang.runtime/src/main/java/org/ballerinalang/langlib/runtime/Constants.java index 552472d779c4..1e3d4bd946cc 100644 --- a/langlib/lang.runtime/src/main/java/org/ballerinalang/langlib/runtime/Constants.java +++ b/langlib/lang.runtime/src/main/java/org/ballerinalang/langlib/runtime/Constants.java @@ -23,7 +23,7 @@ /** * Runtime related constants. */ -public class Constants { +public final class Constants { private static final String PACKAGE_NAME = "lang.runtime"; public static final String CALL_STACK_ELEMENT = "CallStackElement"; diff --git a/langlib/lang.runtime/src/main/java/org/ballerinalang/langlib/runtime/GetStackTrace.java b/langlib/lang.runtime/src/main/java/org/ballerinalang/langlib/runtime/GetStackTrace.java index 9fc5bf946db2..c65252f1a5cc 100644 --- a/langlib/lang.runtime/src/main/java/org/ballerinalang/langlib/runtime/GetStackTrace.java +++ b/langlib/lang.runtime/src/main/java/org/ballerinalang/langlib/runtime/GetStackTrace.java @@ -40,10 +40,13 @@ * * @since 2.0.0 */ -public class GetStackTrace { +public final class GetStackTrace { private static final BString EMPTY_ERROR_MESSAGE = StringUtils.fromString(""); + private GetStackTrace() { + } + public static BArray getStackTrace() { List filteredStack = ErrorCreator.createError(EMPTY_ERROR_MESSAGE).getCallStack(); Type recordType = ValueCreator.createRecordValue(Constants.BALLERINA_RUNTIME_PKG_ID, diff --git a/langlib/lang.runtime/src/main/java/org/ballerinalang/langlib/runtime/Registry.java b/langlib/lang.runtime/src/main/java/org/ballerinalang/langlib/runtime/Registry.java index 2a4b29c88737..56b306fe93be 100644 --- a/langlib/lang.runtime/src/main/java/org/ballerinalang/langlib/runtime/Registry.java +++ b/langlib/lang.runtime/src/main/java/org/ballerinalang/langlib/runtime/Registry.java @@ -28,7 +28,7 @@ * * @since 2.0.0 */ -public class Registry { +public final class Registry { public static void registerListener(Environment env, BObject listener) { env.getRuntime().registerListener(listener); @@ -38,7 +38,7 @@ public static void deregisterListener(Environment env, BObject listener) { env.getRuntime().deregisterListener(listener); } - public static void onGracefulStop(Environment env, BFunctionPointer stopHandler) { + public static void onGracefulStop(Environment env, BFunctionPointer stopHandler) { env.getRuntime().registerStopHandler(stopHandler); } diff --git a/langlib/lang.runtime/src/main/java/org/ballerinalang/langlib/runtime/Sleep.java b/langlib/lang.runtime/src/main/java/org/ballerinalang/langlib/runtime/Sleep.java index 8611e7382ea6..b45ec1b1bcc3 100644 --- a/langlib/lang.runtime/src/main/java/org/ballerinalang/langlib/runtime/Sleep.java +++ b/langlib/lang.runtime/src/main/java/org/ballerinalang/langlib/runtime/Sleep.java @@ -32,7 +32,7 @@ * * @since 2.0.0 */ -public class Sleep { +public final class Sleep { private static final int CORE_THREAD_POOL_SIZE = 1; private static final BigDecimal LONG_MAX = new BigDecimal(Long.MAX_VALUE); diff --git a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/CodePointCompare.java b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/CodePointCompare.java index 1f7886bfbfaf..612323e1997c 100644 --- a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/CodePointCompare.java +++ b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/CodePointCompare.java @@ -33,7 +33,10 @@ // returnType = {@ReturnType(type = TypeKind.INT)}, // isPublic = true //) -public class CodePointCompare { +public final class CodePointCompare { + + private CodePointCompare() { + } public static long codePointCompare(BString str1, BString str2) { // Compare each code point of str1 with str2's codepoint at corresponding position. diff --git a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/Concat.java b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/Concat.java index 037322713d53..d16adc257922 100644 --- a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/Concat.java +++ b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/Concat.java @@ -26,14 +26,17 @@ * * @since 1.0 */ -public class Concat { +public final class Concat { + + private Concat() { + } public static BString concat(BString[] str) { StringBuilder stringBuilder = new StringBuilder(); int size = str.length; - for (int i = 0; i < size; i++) { - stringBuilder.append(str[i]); + for (BString bString : str) { + stringBuilder.append(bString); } return StringUtils.fromString(stringBuilder.toString()); diff --git a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/EndsWith.java b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/EndsWith.java index f62374c20a02..ceace542d92e 100644 --- a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/EndsWith.java +++ b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/EndsWith.java @@ -31,7 +31,10 @@ // returnType = {@ReturnType(type = TypeKind.BOOLEAN)}, // isPublic = true //) -public class EndsWith { +public final class EndsWith { + + private EndsWith() { + } public static boolean endsWith(BString str, BString substr) { return str.getValue().endsWith(substr.getValue()); diff --git a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/EqualsIgnoreCaseAscii.java b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/EqualsIgnoreCaseAscii.java index fe591e58d1f8..6ab3074bb4c0 100644 --- a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/EqualsIgnoreCaseAscii.java +++ b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/EqualsIgnoreCaseAscii.java @@ -27,7 +27,7 @@ * * @since 1.2 */ -public class EqualsIgnoreCaseAscii { +public final class EqualsIgnoreCaseAscii { private EqualsIgnoreCaseAscii() { } diff --git a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/FromBytes.java b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/FromBytes.java index 9d36bc9b4a98..93f9f55cd4a2 100644 --- a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/FromBytes.java +++ b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/FromBytes.java @@ -42,7 +42,7 @@ // returnType = {@ReturnType(type = TypeKind.UNION)}, // isPublic = true //) -public class FromBytes { +public final class FromBytes { private FromBytes() { } diff --git a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/FromCodePointInt.java b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/FromCodePointInt.java index a49743c94441..498b8d51d4ee 100644 --- a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/FromCodePointInt.java +++ b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/FromCodePointInt.java @@ -27,7 +27,10 @@ * * @since 1.0 */ -public class FromCodePointInt { +public final class FromCodePointInt { + + private FromCodePointInt() { + } public static Object fromCodePointInt(long codePoint) { diff --git a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/FromCodePointInts.java b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/FromCodePointInts.java index 2f762f91768c..b0fd7a5e5c0d 100644 --- a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/FromCodePointInts.java +++ b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/FromCodePointInts.java @@ -28,7 +28,10 @@ * * @since 1.0 */ -public class FromCodePointInts { +public final class FromCodePointInts { + + private FromCodePointInts() { + } public static Object fromCodePointInts(BArray codePoints) { int codePoint = 0; diff --git a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/GetCodePoint.java b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/GetCodePoint.java index 57700691324e..b1477ddf4f8b 100644 --- a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/GetCodePoint.java +++ b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/GetCodePoint.java @@ -32,7 +32,10 @@ * * @since 1.0 */ -public class GetCodePoint { +public final class GetCodePoint { + + private GetCodePoint() { + } public static long getCodePoint(BString str, long i) { try { diff --git a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/Includes.java b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/Includes.java index fad7c5f8ee77..1f6fcc440436 100644 --- a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/Includes.java +++ b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/Includes.java @@ -29,7 +29,11 @@ * @since 2.0.0 */ -public class Includes { +public final class Includes { + + private Includes() { + } + public static boolean includes(BString str, BString substr, long index) { if (index > Integer.MAX_VALUE) { throw ErrorHelper.getRuntimeException(ErrorReasons.STRING_OPERATION_ERROR, diff --git a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/IndexOf.java b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/IndexOf.java index 33c54b76e654..db7d62a5b04c 100644 --- a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/IndexOf.java +++ b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/IndexOf.java @@ -32,7 +32,10 @@ * * @since 0.8.0 */ -public class IndexOf { +public final class IndexOf { + + private IndexOf() { + } public static Object indexOf(BString bStr, BString subString, long startIndx) { diff --git a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/Join.java b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/Join.java index 165d76b68a93..3a6b2b016f8a 100644 --- a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/Join.java +++ b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/Join.java @@ -35,13 +35,15 @@ // returnType = {@ReturnType(type = TypeKind.STRING)}, // isPublic = true //) -public class Join { +public final class Join { + + private Join() { + } public static BString join(BString separator, Object... strs) { StringJoiner stringJoiner = new StringJoiner(separator.getValue()); - int size = strs.length; - for (int i = 0; i < size; i++) { - String str = ((BString) strs[i]).getValue(); + for (Object o : strs) { + String str = ((BString) o).getValue(); stringJoiner.add(str); } return StringUtils.fromString(stringJoiner.toString()); diff --git a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/LastIndexOf.java b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/LastIndexOf.java index a9e050b32e59..9c593cbe564b 100644 --- a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/LastIndexOf.java +++ b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/LastIndexOf.java @@ -40,7 +40,11 @@ // returnType = {@ReturnType(type = TypeKind.UNION)}, // isPublic = true //) -public class LastIndexOf { +public final class LastIndexOf { + + private LastIndexOf() { + } + public static Object lastIndexOf(BString value, BString subString, long startIndex) { StringUtils.checkForNull(value, subString); if (startIndex > Integer.MAX_VALUE) { diff --git a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/Length.java b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/Length.java index 92a08b2ad801..d7ccd9e1d84c 100644 --- a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/Length.java +++ b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/Length.java @@ -33,7 +33,10 @@ // returnType = {@ReturnType(type = TypeKind.INT)}, // isPublic = true //) -public class Length { +public final class Length { + + private Length() { + } public static long length(BString value) { if (value == null) { diff --git a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/Next.java b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/Next.java index 8199df5a358c..c260ed05f541 100644 --- a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/Next.java +++ b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/Next.java @@ -30,14 +30,14 @@ * * @since 1.0 */ -public class Next { +public final class Next { private Next() { } //TODO: refactor hard coded values public static Object next(BObject stringObject) { - BIterator charIterator = (BIterator) stringObject.getNativeData("&iterator&"); + BIterator charIterator = (BIterator) stringObject.getNativeData("&iterator&"); if (charIterator == null) { BString bString = ((BString) stringObject.get(StringUtils.fromString("m"))); charIterator = bString.getIterator(); diff --git a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/PadEnd.java b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/PadEnd.java index 2d40736910c3..e70464ca5779 100644 --- a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/PadEnd.java +++ b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/PadEnd.java @@ -32,7 +32,10 @@ * @since 2201.1.0 */ -public class PadEnd { +public final class PadEnd { + + private PadEnd() { + } public static BString padEnd(BString str, long len, BString padChar) { int strLength = str.length(); diff --git a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/PadStart.java b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/PadStart.java index aac449c601ab..70110ae7a38a 100644 --- a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/PadStart.java +++ b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/PadStart.java @@ -32,7 +32,10 @@ * @since 2201.1.0 */ -public class PadStart { +public final class PadStart { + + private PadStart() { + } public static BString padStart(BString str, long len, BString padChar) { int strLength = str.length(); diff --git a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/PadZero.java b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/PadZero.java index 30417eeebc87..09c0904079e0 100644 --- a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/PadZero.java +++ b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/PadZero.java @@ -32,7 +32,10 @@ * @since 2201.1.0 */ -public class PadZero { +public final class PadZero { + + private PadZero() { + } public static BString padZero(BString str, long len, BString padChar) { int strLength = str.length(); diff --git a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/StartsWith.java b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/StartsWith.java index f26c5f27b7d1..9e003eefad13 100644 --- a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/StartsWith.java +++ b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/StartsWith.java @@ -30,7 +30,10 @@ // returnType = {@ReturnType(type = TypeKind.BOOLEAN)}, // isPublic = true //) -public class StartsWith { +public final class StartsWith { + + private StartsWith() { + } public static boolean startsWith(BString str, BString substr) { return str.getValue().startsWith(substr.getValue()); diff --git a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/Substring.java b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/Substring.java index 605d942047a4..2d461ae6ff5a 100644 --- a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/Substring.java +++ b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/Substring.java @@ -35,7 +35,10 @@ // returnType = {@ReturnType(type = TypeKind.STRING)}, // isPublic = true //) -public class Substring { +public final class Substring { + + private Substring() { + } public static BString substring(BString value, long startIndex, long endIndex) { if (value == null) { diff --git a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/ToBytes.java b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/ToBytes.java index d934a1407221..5c19fe333578 100644 --- a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/ToBytes.java +++ b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/ToBytes.java @@ -34,7 +34,10 @@ // returnType = {@ReturnType(type = TypeKind.ARRAY, elementType = TypeKind.BYTE)}, // isPublic = true //) -public class ToBytes { +public final class ToBytes { + + private ToBytes() { + } public static BArray toBytes(BString value) { diff --git a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/ToCodePointInt.java b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/ToCodePointInt.java index aba482950ec3..cff4732d776c 100644 --- a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/ToCodePointInt.java +++ b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/ToCodePointInt.java @@ -31,7 +31,10 @@ // returnType = {@ReturnType(type = TypeKind.INT)}, // isPublic = true //) -public class ToCodePointInt { +public final class ToCodePointInt { + + private ToCodePointInt() { + } public static long toCodePointInt(BString ch) { return ch.getCodePoint(0); diff --git a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/ToCodePointInts.java b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/ToCodePointInts.java index c5c6520fc170..799870d25522 100644 --- a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/ToCodePointInts.java +++ b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/ToCodePointInts.java @@ -33,7 +33,10 @@ // returnType = {@ReturnType(type = TypeKind.ARRAY)}, // isPublic = true //) -public class ToCodePointInts { +public final class ToCodePointInts { + + private ToCodePointInts() { + } public static BArray toCodePointInts(BString str) { long[] ints = str.getValue().codePoints().asLongStream().toArray(); diff --git a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/ToLowerAscii.java b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/ToLowerAscii.java index 1ebb55fc867e..ff3769ed9f22 100644 --- a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/ToLowerAscii.java +++ b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/ToLowerAscii.java @@ -30,7 +30,10 @@ * * @since 0.8.0 */ -public class ToLowerAscii { +public final class ToLowerAscii { + + private ToLowerAscii() { + } public static BString toLowerAscii(BString str) { if (str == null) { diff --git a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/ToUpperAscii.java b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/ToUpperAscii.java index e0c7a02170d9..683ac66f5e48 100644 --- a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/ToUpperAscii.java +++ b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/ToUpperAscii.java @@ -30,7 +30,10 @@ * * @since 0.8.0 */ -public class ToUpperAscii { +public final class ToUpperAscii { + + private ToUpperAscii() { + } public static BString toUpperAscii(BString str) { if (str == null) { diff --git a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/Trim.java b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/Trim.java index b324f7fd9fa8..6d70c4c0bf9a 100644 --- a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/Trim.java +++ b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/Trim.java @@ -35,7 +35,10 @@ // returnType = {@ReturnType(type = TypeKind.STRING)}, // isPublic = true //) -public class Trim { +public final class Trim { + + private Trim() { + } public static BString trim(BString str) { if (str == null) { diff --git a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/utils/Constants.java b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/utils/Constants.java index 81b218f3b18b..d11e9f1eb64d 100644 --- a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/utils/Constants.java +++ b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/utils/Constants.java @@ -21,7 +21,7 @@ * * @since 2201.9.0 */ -public class Constants { +public final class Constants { public static final int MIN_UNICODE = 0xD800; public static final int MIDDLE_LIMIT_UNICODE = 0xDFFF; diff --git a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/utils/StringUtils.java b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/utils/StringUtils.java index 07a5f38cd750..3d068b0ca525 100644 --- a/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/utils/StringUtils.java +++ b/langlib/lang.string/src/main/java/org/ballerinalang/langlib/string/utils/StringUtils.java @@ -29,11 +29,14 @@ * * @since 0.995.0 */ -public class StringUtils { +public final class StringUtils { private static final BString NULL_REF_EXCEPTION = io.ballerina.runtime.api.utils.StringUtils .fromString("NullReferenceException"); + private StringUtils() { + } + public static void checkForNull(String... values) { Arrays.stream(values).forEach(value -> { if (value == null) { diff --git a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Add.java b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Add.java index 6b6354204d91..ed6b27a71258 100644 --- a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Add.java +++ b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Add.java @@ -32,13 +32,16 @@ // args = {@Argument(name = "tbl", type = TypeKind.TABLE), @Argument(name = "val", type = TypeKind.ANYDATA)}, // isPublic = true //) -public class Add { +public final class Add { - public static void add(BTable tbl, BMap val) { + private Add() { + } + + public static void add(BTable tbl, BMap val) { tbl.add(val); } - public static void add_bstring(Strand strand, BTable tbl, BMap val) { + public static void add_bstring(Strand strand, BTable tbl, BMap val) { add(tbl, val); } } diff --git a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Filter.java b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Filter.java index 355e5e2377c7..f2d4d58d80c9 100644 --- a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Filter.java +++ b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Filter.java @@ -45,14 +45,17 @@ // returnType = {@ReturnType(type = TypeKind.TABLE)}, // isPublic = true //) -public class Filter { +public final class Filter { private static final StrandMetadata METADATA = new StrandMetadata(BALLERINA_BUILTIN_PKG_PREFIX, TABLE_LANG_LIB, TABLE_VERSION, "filter"); - public static BTable filter(BTable tbl, BFunctionPointer func) { + private Filter() { + } + + public static BTable filter(BTable tbl, BFunctionPointer func) { TableType tableType = (TableType) TypeUtils.getImpliedType(tbl.getType()); - BTable newTable = + BTable newTable = (BTable) ValueCreator.createTableValue(TypeCreator.createTableType(tableType.getConstrainedType(), tableType.getFieldNames(), false)); int size = tbl.size(); diff --git a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Foreach.java b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Foreach.java index 137b6789f468..26831d838531 100644 --- a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Foreach.java +++ b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Foreach.java @@ -40,12 +40,15 @@ // args = {@Argument(name = "tbl", type = TypeKind.TABLE), @Argument(name = "func", type = TypeKind.FUNCTION)}, // isPublic = true //) -public class Foreach { +public final class Foreach { private static final StrandMetadata METADATA = new StrandMetadata(BALLERINA_BUILTIN_PKG_PREFIX, TABLE_LANG_LIB, TABLE_VERSION, "forEach"); - public static void forEach(BTable tbl, BFunctionPointer func) { + private Foreach() { + } + + public static void forEach(BTable tbl, BFunctionPointer func) { int size = tbl.size(); AtomicInteger index = new AtomicInteger(-1); Object[] values = tbl.values().toArray(); diff --git a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Get.java b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Get.java index 15613bb4b925..bc2fd5f7cc4e 100644 --- a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Get.java +++ b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Get.java @@ -32,9 +32,12 @@ // returnType = {@ReturnType(type = TypeKind.ANY)}, // isPublic = true //) -public class Get { +public final class Get { - public static BMap get(BTable tbl, Object key) { - return (BMap) tbl.getOrThrow(key); + private Get() { + } + + public static BMap get(BTable tbl, Object key) { + return (BMap) tbl.getOrThrow(key); } } diff --git a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/GetIterator.java b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/GetIterator.java index b7cc24aee155..e0f2eaedd1e3 100644 --- a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/GetIterator.java +++ b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/GetIterator.java @@ -32,8 +32,12 @@ // returnType = {@ReturnType(type = TypeKind.OBJECT)}, // isPublic = true //) -public class GetIterator { - public static BIterator iterator(BTable tbl) { +public final class GetIterator { + + private GetIterator() { + } + + public static BIterator iterator(BTable tbl) { return tbl.getIterator(); } } diff --git a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/GetKeys.java b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/GetKeys.java index b91dabd3fbb1..0779af3a2eea 100644 --- a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/GetKeys.java +++ b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/GetKeys.java @@ -39,9 +39,12 @@ // returnType = {@ReturnType(type = TypeKind.ARRAY, elementType = TypeKind.ANYDATA)}, // isPublic = true //) -public class GetKeys { +public final class GetKeys { - public static BArray keys(BTable tbl) { + private GetKeys() { + } + + public static BArray keys(BTable tbl) { Type tableKeyType = tbl.getKeyType(); Object[] keys = tbl.getKeys(); switch (tableKeyType.getTag()) { diff --git a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/HasKey.java b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/HasKey.java index fe9111120f7f..9a236bcb676c 100644 --- a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/HasKey.java +++ b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/HasKey.java @@ -32,10 +32,13 @@ // returnType = {@ReturnType(type = TypeKind.BOOLEAN)}, // isPublic = true //) -public class HasKey { +public final class HasKey { + + private HasKey() { + } @Deprecated - public static boolean hasKey(BTable tbl, Object key) { + public static boolean hasKey(BTable tbl, Object key) { return tbl.containsKey(key); } } diff --git a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Length.java b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Length.java index fad5d5365eec..5beb9e634376 100644 --- a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Length.java +++ b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Length.java @@ -32,12 +32,15 @@ // returnType = {@ReturnType(type = TypeKind.INT)}, // isPublic = true //) -public class Length { +public final class Length { - public static long length(BTable tbl) { + private Length() { + } + + public static long length(BTable tbl) { return tbl.size(); } - public static long length_bstring(Strand strand, BTable tbl) { + public static long length_bstring(Strand strand, BTable tbl) { return length(tbl); } } diff --git a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Map.java b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Map.java index 33cb5fcd4054..958cb582efdc 100644 --- a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Map.java +++ b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Map.java @@ -42,18 +42,21 @@ * * @since 1.3.0 */ -public class Map { +public final class Map { private static final StrandMetadata METADATA = new StrandMetadata(BALLERINA_BUILTIN_PKG_PREFIX, TABLE_LANG_LIB, TABLE_VERSION, "map"); - public static BTable map(BTable tbl, BFunctionPointer func) { + private Map() { + } + + public static BTable map(BTable tbl, BFunctionPointer func) { Type newConstraintType = ((FunctionType) TypeUtils.getImpliedType(func.getType())).getReturnType(); TableType tblType = (TableType) TypeUtils.getImpliedType(tbl.getType()); TableType newTableType = TypeCreator.createTableType(newConstraintType, PredefinedTypes.TYPE_NEVER, tblType.isReadOnly()); - BTable newTable = ValueCreator.createTableValue(newTableType); + BTable newTable = (BTable) ValueCreator.createTableValue(newTableType); int size = tbl.size(); Object[] tableValues = tbl.values().toArray(); AtomicInteger index = new AtomicInteger(-1); diff --git a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Next.java b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Next.java index 37d225f746d0..9920b5f8618b 100644 --- a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Next.java +++ b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Next.java @@ -42,14 +42,18 @@ * * @since 1.3.0 */ -public class Next { +public final class Next { private static final BString MUTATED_TABLE_ERROR_DETAIL = StringUtils.fromString("Table was mutated after the " + "iterator was created"); + + private Next() { + } + //TODO: refactor hard coded values public static Object next(BObject t) { - BIterator tableIterator = (BIterator) t.getNativeData("&iterator&"); - BTable table = (BTable) t.get(StringUtils.fromString("t")); + BIterator tableIterator = (BIterator) t.getNativeData("&iterator&"); + BTable table = (BTable) t.get(StringUtils.fromString("t")); BArray keys = (BArray) t.get(StringUtils.fromString("keys")); long initialSize = (long) t.get(StringUtils.fromString("size")); if (tableIterator == null) { @@ -72,7 +76,7 @@ public static Object next(BObject t) { return null; } - private static void handleMutation(BTable table, BArray keys, + private static void handleMutation(BTable table, BArray keys, List returnedKeys, long initialSize) { if (initialSize < table.size() || // Key-less situation, mutation can occur only by calling add() or removeAll() diff --git a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/NextKey.java b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/NextKey.java index fd3271e6a746..8d480a9992ea 100644 --- a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/NextKey.java +++ b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/NextKey.java @@ -26,8 +26,12 @@ * * @since 1.3.0 */ -public class NextKey { - public static long nextKey(BTable tbl) { +public final class NextKey { + + private NextKey() { + } + + public static long nextKey(BTable tbl) { return tbl.getNextKey(); } } diff --git a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Put.java b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Put.java index b954094989bb..acef13542795 100644 --- a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Put.java +++ b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Put.java @@ -32,13 +32,16 @@ // args = {@Argument(name = "tbl", type = TypeKind.TABLE), @Argument(name = "vals", type = TypeKind.ANYDATA)}, // isPublic = true //) -public class Put { +public final class Put { - public static void put(BTable tbl, BMap val) { + private Put() { + } + + public static void put(BTable tbl, BMap val) { tbl.put(val); } - public static void put_bstring(Strand strand, BTable tbl, BMap val) { + public static void put_bstring(Strand strand, BTable tbl, BMap val) { put(tbl, val); } } diff --git a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Reduce.java b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Reduce.java index 69d98468a4a8..9ac6285e711e 100644 --- a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Reduce.java +++ b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Reduce.java @@ -43,12 +43,15 @@ // returnType = {@ReturnType(type = TypeKind.ANY)}, // isPublic = true //) -public class Reduce { +public final class Reduce { private static final StrandMetadata METADATA = new StrandMetadata(BALLERINA_BUILTIN_PKG_PREFIX, TABLE_LANG_LIB, TABLE_VERSION, "reduce"); - public static Object reduce(BTable tbl, BFunctionPointer func, Object initial) { + private Reduce() { + } + + public static Object reduce(BTable tbl, BFunctionPointer func, Object initial) { int size = tbl.values().size(); AtomicReference accum = new AtomicReference<>(initial); AtomicInteger index = new AtomicInteger(-1); diff --git a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Remove.java b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Remove.java index dd0ba766e77a..46996cec372e 100644 --- a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Remove.java +++ b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/Remove.java @@ -32,9 +32,12 @@ // returnType = {@ReturnType(type = TypeKind.ANY)}, // isPublic = true //) -public class Remove { +public final class Remove { - public static BMap remove(BTable tbl, Object key) { - return (BMap) tbl.removeOrThrow(key); + private Remove() { + } + + public static BMap remove(BTable tbl, Object key) { + return (BMap) tbl.removeOrThrow(key); } } diff --git a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/RemoveAll.java b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/RemoveAll.java index 701882eb4487..95bb8d5ad6ed 100644 --- a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/RemoveAll.java +++ b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/RemoveAll.java @@ -31,9 +31,12 @@ * * @since 1.3.0 */ -public class RemoveAll { +public final class RemoveAll { - public static void removeAll(BTable tbl) { + private RemoveAll() { + } + + public static void removeAll(BTable tbl) { try { tbl.clear(); } catch (BError e) { diff --git a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/RemoveIfHasKey.java b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/RemoveIfHasKey.java index dfdba7412593..3bc78868dd7f 100644 --- a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/RemoveIfHasKey.java +++ b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/RemoveIfHasKey.java @@ -31,9 +31,12 @@ // returnType = {@ReturnType(type = TypeKind.ANY)}, // isPublic = true //) -public class RemoveIfHasKey { +public final class RemoveIfHasKey { - public static Object removeIfHasKey(BTable tbl, Object key) { + private RemoveIfHasKey() { + } + + public static Object removeIfHasKey(BTable tbl, Object key) { return tbl.remove(key); } } diff --git a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/ToArray.java b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/ToArray.java index 6d13e2c8f4b1..d7dbff908c3e 100644 --- a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/ToArray.java +++ b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/ToArray.java @@ -40,12 +40,15 @@ // returnType = {@ReturnType(type = TypeKind.ARRAY, elementType = TypeKind.ANYDATA)}, // isPublic = true //) -public class ToArray { +public final class ToArray { - public static BArray toArray(BTable tbl) { + private ToArray() { + } + + public static BArray toArray(BTable tbl) { Type constrainedType = ((TableType) TypeUtils.getImpliedType(tbl.getType())).getConstrainedType(); - Collection values = tbl.values(); + Collection values = tbl.values(); //Basic constrain types not applicable for table type return ValueCreator.createArrayValue(values.toArray(), TypeCreator.createArrayType(constrainedType)); } diff --git a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/utils/Constants.java b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/utils/Constants.java index 31375d17ce6f..c2112e72cf25 100644 --- a/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/utils/Constants.java +++ b/langlib/lang.table/src/main/java/org/ballerinalang/langlib/table/utils/Constants.java @@ -21,7 +21,7 @@ * * @since 2201.9.0 */ -public class Constants { +public final class Constants { public static final String TABLE_VERSION = "0.4.0"; diff --git a/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/AssertError.java b/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/AssertError.java index 3c8147e9ab2c..22688b4ec176 100644 --- a/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/AssertError.java +++ b/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/AssertError.java @@ -29,7 +29,11 @@ * * @since 1.3.0 */ -public class AssertError { +public final class AssertError { + + private AssertError() { + } + public static void assertError(Object value) { if (TypeUtils.getImpliedType(TypeChecker.getType(value)).getTag() != TypeTags.ERROR_TAG) { throw ErrorCreator.createError(StringUtils.fromString("{ballerina/lang.test}AssertionError"), diff --git a/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/AssertFalse.java b/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/AssertFalse.java index 7a2462b6f8ba..5f40288ebd95 100644 --- a/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/AssertFalse.java +++ b/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/AssertFalse.java @@ -26,7 +26,11 @@ * * @since 1.3.0 */ -public class AssertFalse { +public final class AssertFalse { + + private AssertFalse() { + } + public static void assertFalse(boolean value) { if (value) { throw ErrorCreator.createError(StringUtils.fromString("{ballerina/lang.test}AssertionError"), diff --git a/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/AssertNotError.java b/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/AssertNotError.java index 1baef5ef56f8..7fce1c2627b7 100644 --- a/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/AssertNotError.java +++ b/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/AssertNotError.java @@ -29,7 +29,11 @@ * * @since 1.3.0 */ -public class AssertNotError { +public final class AssertNotError { + + private AssertNotError() { + } + public static void assertNotError(Object value) { if (TypeUtils.getImpliedType(TypeChecker.getType(value)).getTag() == TypeTags.ERROR_TAG) { throw ErrorCreator.createError(StringUtils.fromString("{ballerina/lang.test}AssertionError"), diff --git a/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/AssertTrue.java b/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/AssertTrue.java index 71a33b1105de..3c9a5ad2c104 100644 --- a/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/AssertTrue.java +++ b/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/AssertTrue.java @@ -26,7 +26,11 @@ * * @since 1.3.0 */ -public class AssertTrue { +public final class AssertTrue { + + private AssertTrue() { + } + public static void assertTrue(boolean value) { if (!value) { throw ErrorCreator.createError(StringUtils.fromString("{ballerina/lang.test}AssertionError"), diff --git a/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/AssertValueEqual.java b/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/AssertValueEqual.java index 732dc5e2d6af..aeb024a0c8f5 100644 --- a/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/AssertValueEqual.java +++ b/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/AssertValueEqual.java @@ -28,7 +28,11 @@ * * @since 1.3.0 */ -public class AssertValueEqual { +public final class AssertValueEqual { + + private AssertValueEqual() { + } + public static void assertValueEqual(Object expected, Object actual) { if (!TypeChecker.isEqual(expected, actual)) { BString reason = StringUtils.fromString("{ballerina/lang.test}AssertionError"); diff --git a/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/DetachEndpoint.java b/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/DetachEndpoint.java index f7ae08b2974d..90016f437ab2 100644 --- a/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/DetachEndpoint.java +++ b/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/DetachEndpoint.java @@ -21,7 +21,11 @@ /** * @since 2.0.0 */ -public class DetachEndpoint { +public final class DetachEndpoint { + + private DetachEndpoint() { + } + public static void detach() { } diff --git a/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/InitEndPoint.java b/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/InitEndPoint.java index 3c033946e7aa..cd5d404e4172 100644 --- a/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/InitEndPoint.java +++ b/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/InitEndPoint.java @@ -21,7 +21,11 @@ /** * @since 2.0.0 */ -public class InitEndPoint { +public final class InitEndPoint { + + private InitEndPoint() { + } + public static void initEndPoint() { } diff --git a/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/Register.java b/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/Register.java index 366d6d06fa23..4fa311bb3243 100644 --- a/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/Register.java +++ b/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/Register.java @@ -21,7 +21,11 @@ /** * @since 2.0.0 */ -public class Register { +public final class Register { + + private Register() { + } + public static void register() { } diff --git a/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/Start.java b/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/Start.java index 1f3f24e30eb8..7ad834ecd6de 100644 --- a/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/Start.java +++ b/langlib/lang.test/src/main/java/org/ballerinalang/langlib/test/Start.java @@ -21,7 +21,11 @@ /** * @since 2.0.0 */ -public class Start { +public final class Start { + + private Start() { + } + public static void start() { } diff --git a/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/GetData.java b/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/GetData.java index c5bf8a87c653..351f8f5674d8 100644 --- a/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/GetData.java +++ b/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/GetData.java @@ -25,7 +25,10 @@ * * @since 2.0.0-preview1 */ -public class GetData { +public final class GetData { + + private GetData() { + } public static Object getData() { diff --git a/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/GetInfo.java b/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/GetInfo.java index 736393189c57..621f1cfc8566 100644 --- a/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/GetInfo.java +++ b/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/GetInfo.java @@ -26,7 +26,10 @@ * * @since 2.0.0-preview1 */ -public class GetInfo { +public final class GetInfo { + + private GetInfo() { + } public static Object getInfo(BArray xid) { return TransactionResourceManager.getInstance().getTransactionRecord(xid); diff --git a/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/GetRollbackOnly.java b/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/GetRollbackOnly.java index 7e742329541e..c50525184877 100644 --- a/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/GetRollbackOnly.java +++ b/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/GetRollbackOnly.java @@ -26,7 +26,10 @@ * * @since 2.0.0-preview1 */ -public class GetRollbackOnly { +public final class GetRollbackOnly { + + private GetRollbackOnly() { + } public static boolean getRollbackOnly() { TransactionLocalContext transactionLocalContext = Scheduler.getStrand().currentTrxContext; diff --git a/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/Info.java b/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/Info.java index 85b9a046d1ac..9cf41cb7a23b 100644 --- a/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/Info.java +++ b/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/Info.java @@ -31,7 +31,10 @@ * * @since 2.0.0-preview1 */ -public class Info { +public final class Info { + + private Info() { + } public static BMap info() { Strand strand = Scheduler.getStrand(); diff --git a/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/IsTransactional.java b/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/IsTransactional.java index 1639401ece71..10c60f0f8077 100644 --- a/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/IsTransactional.java +++ b/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/IsTransactional.java @@ -25,7 +25,10 @@ * * @since 2.0.0-preview1 */ -public class IsTransactional { +public final class IsTransactional { + + private IsTransactional() { + } public static boolean isTransactional() { return Scheduler.getStrand().isInTransaction(); diff --git a/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/OnCommit.java b/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/OnCommit.java index b433c41bd5b6..94909e3a261a 100644 --- a/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/OnCommit.java +++ b/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/OnCommit.java @@ -28,9 +28,12 @@ * * @since 2.0.0-preview1 */ -public class OnCommit { +public final class OnCommit { - public static void onCommit(BFunctionPointer bFunctionPointer) { + private OnCommit() { + } + + public static void onCommit(BFunctionPointer bFunctionPointer) { TransactionLocalContext transactionLocalContext = Scheduler.getStrand().currentTrxContext; TransactionResourceManager transactionResourceManager = TransactionResourceManager.getInstance(); transactionResourceManager.registerCommittedFunction(transactionLocalContext.getGlobalTransactionId(), diff --git a/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/OnRollback.java b/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/OnRollback.java index 90904711f9b4..a496ee2b6d7d 100644 --- a/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/OnRollback.java +++ b/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/OnRollback.java @@ -28,9 +28,12 @@ * * @since 2.0.0-preview1 */ -public class OnRollback { +public final class OnRollback { - public static void onRollback(BFunctionPointer bFunctionPointer) { + private OnRollback() { + } + + public static void onRollback(BFunctionPointer bFunctionPointer) { TransactionLocalContext transactionLocalContext = Scheduler.getStrand().currentTrxContext; TransactionResourceManager transactionResourceManager = TransactionResourceManager.getInstance(); transactionResourceManager.registerAbortedFunction(transactionLocalContext.getGlobalTransactionId(), diff --git a/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/SetData.java b/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/SetData.java index ab9fd9856b3e..6857dac9087b 100644 --- a/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/SetData.java +++ b/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/SetData.java @@ -26,7 +26,10 @@ * * @since 2.0.0-preview1 */ -public class SetData { +public final class SetData { + + private SetData() { + } public static void setData(Object data) { diff --git a/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/WrapRollbackError.java b/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/WrapRollbackError.java index 16b0e5a54294..2433f68f89bf 100644 --- a/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/WrapRollbackError.java +++ b/langlib/lang.transaction/src/main/java/org/ballerinalang/langlib/transaction/WrapRollbackError.java @@ -26,7 +26,10 @@ * * @since 2.0.0-preview1 */ -public class WrapRollbackError { +public final class WrapRollbackError { + + private WrapRollbackError() { + } public static void wrapRollbackError(Object error) { TransactionLocalContext transactionLocalContext = Scheduler.getStrand().currentTrxContext; diff --git a/langlib/lang.typedesc/src/main/java/org/ballerinalang/langlib/typedesc/TypeIds.java b/langlib/lang.typedesc/src/main/java/org/ballerinalang/langlib/typedesc/TypeIds.java index 43f88eec9a59..63c2e305cc52 100644 --- a/langlib/lang.typedesc/src/main/java/org/ballerinalang/langlib/typedesc/TypeIds.java +++ b/langlib/lang.typedesc/src/main/java/org/ballerinalang/langlib/typedesc/TypeIds.java @@ -44,7 +44,8 @@ * * @since 2.0.0 */ -public class TypeIds { +public final class TypeIds { + private static final String PACKAGE_NAME = "lang.typedesc"; private static final String BALLERINA_BUILTIN_PKG_PREFIX = "ballerina"; private static final String PACKAGE_VERSION = "0"; @@ -59,6 +60,9 @@ public class TypeIds { private static final ArrayType typeIdArrayType = new BArrayType(createTypeId(createModuleId(BALLERINA_TYPEDESC_PKG_ID), "empty").getType()); + private TypeIds() { + } + public static Object typeIds(BTypedesc t, boolean primaryOnly) { Type describingType = t.getDescribingType(); BTypeIdSet typeIdSet = getTypeIdSetForType(describingType); diff --git a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/Clone.java b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/Clone.java index 1452c6c79e7a..4e0f0776f867 100644 --- a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/Clone.java +++ b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/Clone.java @@ -25,7 +25,10 @@ * * @since 1.0 */ -public class Clone { +public final class Clone { + + private Clone() { + } public static Object clone(Object value) { return CloneUtils.cloneValue(value); diff --git a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/CloneReadOnly.java b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/CloneReadOnly.java index 21c2161c575a..97e5da8c6be9 100644 --- a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/CloneReadOnly.java +++ b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/CloneReadOnly.java @@ -25,7 +25,10 @@ * * @since 1.0 */ -public class CloneReadOnly { +public final class CloneReadOnly { + + private CloneReadOnly() { + } public static Object cloneReadOnly(Object value) { return CloneUtils.cloneReadOnly(value); diff --git a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/CloneWithType.java b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/CloneWithType.java index 5c1e2dbb5823..2e5f69205bf2 100644 --- a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/CloneWithType.java +++ b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/CloneWithType.java @@ -34,7 +34,7 @@ * * @since 2.0 */ -public class CloneWithType { +public final class CloneWithType { private CloneWithType() {} diff --git a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/Count.java b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/Count.java index 31d31381ef9b..847539f811ef 100644 --- a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/Count.java +++ b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/Count.java @@ -22,7 +22,11 @@ * * @since 2201.6.0 */ -public class Count { +public final class Count { + + private Count() { + } + public static long count(Object[] values) { return values.length; } diff --git a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/EnsureType.java b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/EnsureType.java index f86f24f90297..ed5e81c9a48f 100644 --- a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/EnsureType.java +++ b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/EnsureType.java @@ -29,7 +29,11 @@ * * @since 2.0.0 */ -public class EnsureType { +public final class EnsureType { + + private EnsureType() { + } + public static Object ensureType(Object value, BTypedesc type) { if (TypeUtils.getImpliedType(TypeChecker.getType(value)).getTag() == TypeTags.ERROR_TAG) { return value; diff --git a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/FromBalString.java b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/FromBalString.java index d371671992a0..aaa7590fe3d6 100644 --- a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/FromBalString.java +++ b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/FromBalString.java @@ -31,7 +31,11 @@ * * @since 2.0.0 */ -public class FromBalString { +public final class FromBalString { + + private FromBalString() { + } + public static Object fromBalString(BString value) { String str = value.getValue(); if (str.equals("null")) { diff --git a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/FromJsonDecimalString.java b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/FromJsonDecimalString.java index a1b12e303822..08c1f3d0789a 100644 --- a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/FromJsonDecimalString.java +++ b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/FromJsonDecimalString.java @@ -32,7 +32,10 @@ * All numbers in the JSON will be represented as decimal values. */ -public class FromJsonDecimalString { +public final class FromJsonDecimalString { + + private FromJsonDecimalString() { + } public static Object fromJsonDecimalString(BString value) { diff --git a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/FromJsonFloatString.java b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/FromJsonFloatString.java index 457a59f35852..2bd36a02060f 100644 --- a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/FromJsonFloatString.java +++ b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/FromJsonFloatString.java @@ -32,7 +32,10 @@ * All numbers in the JSON will be represented as float values. */ -public class FromJsonFloatString { +public final class FromJsonFloatString { + + private FromJsonFloatString() { + } public static Object fromJsonFloatString(BString value) { diff --git a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/FromJsonString.java b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/FromJsonString.java index c74b79ba3542..136afb309b2f 100644 --- a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/FromJsonString.java +++ b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/FromJsonString.java @@ -29,7 +29,10 @@ * * @since 1.0 */ -public class FromJsonString { +public final class FromJsonString { + + private FromJsonString() { + } public static Object fromJsonString(BString value) { diff --git a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/FromJsonStringWithType.java b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/FromJsonStringWithType.java index 254f57a08c9f..5055423f1ddb 100644 --- a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/FromJsonStringWithType.java +++ b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/FromJsonStringWithType.java @@ -32,7 +32,7 @@ * * @since 2.0 */ -public class FromJsonStringWithType { +public final class FromJsonStringWithType { private FromJsonStringWithType() {} diff --git a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/FromJsonWithType.java b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/FromJsonWithType.java index e9818ff43e71..38200fb1980f 100644 --- a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/FromJsonWithType.java +++ b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/FromJsonWithType.java @@ -34,7 +34,7 @@ * * @since 2.0 */ -public class FromJsonWithType { +public final class FromJsonWithType { private FromJsonWithType() {} diff --git a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/IsReadOnly.java b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/IsReadOnly.java index 06d7320528aa..e9419dd968fd 100644 --- a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/IsReadOnly.java +++ b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/IsReadOnly.java @@ -25,9 +25,12 @@ * * @since 1.0 */ -public class IsReadOnly { +public final class IsReadOnly { + + private IsReadOnly() { + } public static boolean isReadOnly(Object value) { - return !(value instanceof BRefValue) || ((BRefValue) value).isFrozen(); + return !(value instanceof BRefValue bRefValue) || bRefValue.isFrozen(); } } diff --git a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/Last.java b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/Last.java index 455dad9a0a7b..d29d3056e766 100644 --- a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/Last.java +++ b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/Last.java @@ -22,7 +22,11 @@ * * @since 2201.6.0 */ -public class Last { +public final class Last { + + private Last() { + } + public static Object last(Object value, Object[] values) { int size = values.length; return size == 0 ? value : values[size - 1]; diff --git a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/MergeJson.java b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/MergeJson.java index ce55b556e6c7..d80d5736ed08 100644 --- a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/MergeJson.java +++ b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/MergeJson.java @@ -26,7 +26,10 @@ * * @since 1.0 */ -public class MergeJson { +public final class MergeJson { + + private MergeJson() { + } public static Object mergeJson(Object j1, Object j2) { return JsonInternalUtils.mergeJson(j1, j2, true); diff --git a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/ToBalString.java b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/ToBalString.java index 6754dfffc4a8..b6e41482b21e 100644 --- a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/ToBalString.java +++ b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/ToBalString.java @@ -26,7 +26,11 @@ * * @since Swan Lake */ -public class ToBalString { +public final class ToBalString { + + private ToBalString() { + } + public static BString toBalString(Object value) { return StringUtils.fromString(StringUtils.getExpressionStringValue(value)); } diff --git a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/ToJson.java b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/ToJson.java index 3228b216920f..5af0c536e4b0 100644 --- a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/ToJson.java +++ b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/ToJson.java @@ -25,7 +25,7 @@ * * @since 2.0 */ -public class ToJson { +public final class ToJson { private ToJson() { } diff --git a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/ToJsonString.java b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/ToJsonString.java index e92e8922249a..e319c30f0fd5 100644 --- a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/ToJsonString.java +++ b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/ToJsonString.java @@ -26,7 +26,10 @@ * * @since 1.0 */ -public class ToJsonString { +public final class ToJsonString { + + private ToJsonString() { + } public static BString toJsonString(Object value) { return StringUtils.fromString(StringUtils.getJsonString(value)); diff --git a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/ToString.java b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/ToString.java index f67dc9a04810..896f6a3e5aec 100644 --- a/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/ToString.java +++ b/langlib/lang.value/src/main/java/org/ballerinalang/langlib/value/ToString.java @@ -26,7 +26,11 @@ * * @since 1.0 */ -public class ToString { +public final class ToString { + + private ToString() { + } + public static BString toString(Object value) { return StringUtils.fromString(StringUtils.getStringValue(value)); } diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/AppendChildren.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/AppendChildren.java index 4c2f4544c712..602686812903 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/AppendChildren.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/AppendChildren.java @@ -34,10 +34,13 @@ // args = {@Argument(name = "children", type = TypeKind.XML)}, // isPublic = true //) -public class AppendChildren { +public final class AppendChildren { private static final String OPERATION = "add children to xml element"; + private AppendChildren() { + } + @Deprecated public static void appendChildren(Strand strand, BXml xml, BXml children) { try { diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Children.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Children.java index 9e3a4f791448..42e2e87f04a7 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Children.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Children.java @@ -37,7 +37,10 @@ // returnType = {@ReturnType(type = TypeKind.XML)}, // isPublic = true //) -public class Children { +public final class Children { + + private Children() { + } public static BXml children(BXml xmlVal) { if (xmlVal.getNodeType() == XmlNodeType.ELEMENT) { diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Concat.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Concat.java index 94660320e610..e9209a005947 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Concat.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Concat.java @@ -32,14 +32,16 @@ * * @since 1.0 */ -public class Concat { +public final class Concat { + + private Concat() { + } public static BXml concat(Object... arrayValue) { List backingArray = new ArrayList<>(); BXml lastItem = null; - for (int i = 0; i < arrayValue.length; i++) { - Object refValue = arrayValue[i]; - if (refValue instanceof BString) { + for (Object refValue : arrayValue) { + if (refValue instanceof BString bString) { if (lastItem != null && lastItem.getNodeType() == XmlNodeType.TEXT) { // If last added item is a string, then concat prev values with this values and replace prev value. String concat = lastItem.getTextValue() + refValue; @@ -48,11 +50,11 @@ public static BXml concat(Object... arrayValue) { lastItem = xmlText; continue; } - BXml xmlText = XmlFactory.createXMLText((BString) refValue); + BXml xmlText = XmlFactory.createXMLText(bString); backingArray.add(xmlText); lastItem = xmlText; - } else if (refValue instanceof BXmlSequence) { - backingArray.addAll(((BXmlSequence) refValue).getChildrenList()); + } else if (refValue instanceof BXmlSequence bXmlSequence) { + backingArray.addAll(bXmlSequence.getChildrenList()); lastItem = (BXml) refValue; } else { backingArray.add((BXml) refValue); diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Copy.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Copy.java index 684d7367f7f3..30a74c8644ab 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Copy.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Copy.java @@ -33,10 +33,13 @@ // returnType = {@ReturnType(type = TypeKind.XML)}, // isPublic = true //) -public class Copy { +public final class Copy { private static final String OPERATION = "copy xml"; + private Copy() { + } + public static BXml copy(Strand strand, BXml xml) { try { return (BXml) xml.copy(new HashMap<>()); diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/CreateComment.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/CreateComment.java index 002207ffb755..ea58650f833b 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/CreateComment.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/CreateComment.java @@ -33,7 +33,10 @@ // returnType = {@ReturnType(type = TypeKind.XML)}, // isPublic = true //) -public class CreateComment { +public final class CreateComment { + + private CreateComment() { + } public static BXml createComment(BString string) { return XmlFactory.createXMLComment(string); diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/CreateElement.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/CreateElement.java index f20c870b00c0..b487ea95eaeb 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/CreateElement.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/CreateElement.java @@ -42,11 +42,15 @@ // returnType = {@ReturnType(type = TypeKind.XML)}, // isPublic = true //) -public class CreateElement { +public final class CreateElement { + private static final String XML = "xml"; private static final String XML_NS_URI_PREFIX = "{" + XMLConstants.XML_NS_URI + "}"; private static final String XMLNS_NS_URI_PREFIX = "{" + XMLConstants.XMLNS_ATTRIBUTE_NS_URI + "}"; + private CreateElement() { + } + public static BXml createElement(BString name, BMap attributes, BXml children) { String prefix = getPrefix(name.getValue(), attributes); BXmlQName xmlqName; diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/CreateProcessingInstruction.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/CreateProcessingInstruction.java index 39836f2f48af..990938b001fd 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/CreateProcessingInstruction.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/CreateProcessingInstruction.java @@ -35,7 +35,10 @@ // returnType = {@ReturnType(type = TypeKind.XML)}, // isPublic = true //) -public class CreateProcessingInstruction { +public final class CreateProcessingInstruction { + + private CreateProcessingInstruction() { + } public static BXml createProcessingInstruction(BString target, BString content) { return XmlFactory.createXMLProcessingInstruction(target, content); diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/CreateText.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/CreateText.java index d67a910a38d9..d6379a71c0a4 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/CreateText.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/CreateText.java @@ -26,7 +26,10 @@ * * @since 2.0.0 */ -public class CreateText { +public final class CreateText { + + private CreateText() { + } public static BXml createText(BString string) { return XmlFactory.createXMLText(string); diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Data.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Data.java index acb02b9200ca..387babc34203 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Data.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Data.java @@ -26,9 +26,13 @@ * * @since 2.0 */ -public class Data { +public final class Data { + private static final BString empty = StringUtils.fromString(""); + private Data() { + } + public static BString data(BXml xmlValue) { if (xmlValue.isEmpty() || IsComment.isComment(xmlValue) diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/ElementChildren.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/ElementChildren.java index dc81cf40d38b..3fdfd2e80827 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/ElementChildren.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/ElementChildren.java @@ -39,7 +39,10 @@ // returnType = {@ReturnType(type = TypeKind.XML)}, // isPublic = true //) -public class ElementChildren { +public final class ElementChildren { + + private ElementChildren() { + } public static BXml elementChildren(BXml xmlVal, Object nameObj) { boolean namedQuery = nameObj != null; diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Elements.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Elements.java index 6f29af4efe82..70f659ec7fe3 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Elements.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Elements.java @@ -38,14 +38,17 @@ // returnType = {@ReturnType(type = TypeKind.XML)}, // isPublic = true //) -public class Elements { +public final class Elements { private static final String OPERATION = "get elements from xml"; + private Elements() { + } + public static BXml elements(BXml xml, Object name) { try { - if (name instanceof BString) { - return xml.elements(((BString) name).getValue()); + if (name instanceof BString bString) { + return xml.elements(bString.getValue()); } return xml.elements(); } catch (Throwable e) { @@ -57,7 +60,7 @@ public static BXml elements(BXml xml, Object name) { private static BXml generateCodePointSequence(BXml value) { List list = new ArrayList<>(); - BIterator bIterator = value.getIterator(); + BIterator bIterator = value.getIterator(); while (bIterator.hasNext()) { list.add((BXml) bIterator.next()); } diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Filter.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Filter.java index 7eb0e0e30f8a..eeab3c7538a3 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Filter.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Filter.java @@ -46,12 +46,15 @@ // returnType = {@ReturnType(type = TypeKind.XML)}, // isPublic = true //) -public class Filter { +public final class Filter { private static final StrandMetadata METADATA = new StrandMetadata(BALLERINA_BUILTIN_PKG_PREFIX, XML_LANG_LIB, XML_VERSION, "filter"); - public static BXml filter(BXml x, BFunctionPointer func) { + private Filter() { + } + + public static BXml filter(BXml x, BFunctionPointer func) { if (x.isSingleton()) { Object[] args = new Object[]{x, true}; func.asyncCall(args, diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/ForEach.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/ForEach.java index c5193c5ad539..2628b4f875d5 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/ForEach.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/ForEach.java @@ -35,12 +35,15 @@ * * @since 1.0 */ -public class ForEach { +public final class ForEach { private static final StrandMetadata METADATA = new StrandMetadata(BALLERINA_BUILTIN_PKG_PREFIX, XML_LANG_LIB, XML_VERSION, "forEach"); - public static void forEach(BXml x, BFunctionPointer func) { + private ForEach() { + } + + public static void forEach(BXml x, BFunctionPointer func) { if (x.isSingleton()) { func.asyncCall(new Object[]{x, true}, METADATA); return; diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/FromString.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/FromString.java index b6e192b76742..39deda4524ce 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/FromString.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/FromString.java @@ -33,7 +33,10 @@ // returnType = {@ReturnType(type = TypeKind.XML)}, // isPublic = true //) -public class FromString { +public final class FromString { + + private FromString() { + } public static Object fromString(BString string) { try { diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Get.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Get.java index b9f2b0b0f966..68add759a154 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Get.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Get.java @@ -39,10 +39,13 @@ // returnType = {@ReturnType(type = TypeKind.XML)}, // isPublic = true //) -public class Get { +public final class Get { public static final int LENGTH_OF_ONE = 1; + private Get() { + } + public static BXml get(BXml xmlVal, long i) { // Handle single xml items XmlNodeType nodeType = xmlVal.getNodeType(); diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetAttributes.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetAttributes.java index ccb2ebaf94f5..afd12577c4ef 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetAttributes.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetAttributes.java @@ -35,7 +35,10 @@ // returnType = {@ReturnType(type = TypeKind.MAP)}, // isPublic = true //) -public class GetAttributes { +public final class GetAttributes { + + private GetAttributes() { + } @SuppressWarnings("unchecked") public static BMap getAttributes(BXml xmlVal) { diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetChildren.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetChildren.java index 4424029fd182..d8fe22039e47 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetChildren.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetChildren.java @@ -33,7 +33,10 @@ // returnType = {@ReturnType(type = TypeKind.XML)}, // isPublic = true //) -public class GetChildren { +public final class GetChildren { + + private GetChildren() { + } public static BXml getChildren(BXml xmlVal) { if (!IsElement.isElement(xmlVal)) { diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetContent.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetContent.java index 7701f3a59896..f7895598b968 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetContent.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetContent.java @@ -31,7 +31,10 @@ * * @since 0.90 */ -public class GetContent { +public final class GetContent { + + private GetContent() { + } public static BString getContent(Object xmlVal) { BXml value = (BXml) xmlVal; diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetDescendants.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetDescendants.java index 63649f5e5c7c..3c61fda7c31f 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetDescendants.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetDescendants.java @@ -26,7 +26,10 @@ * * @since 2.0.0 */ -public class GetDescendants { +public final class GetDescendants { + + private GetDescendants() { + } public static BXml getDescendants(BXml element) { if (!IsElement.isElement(element)) { diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetElementName.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetElementName.java index 01bb7897d906..26ebab4ebef8 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetElementName.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetElementName.java @@ -33,10 +33,13 @@ // returnType = {@ReturnType(type = TypeKind.STRING)}, // isPublic = true //) -public class GetElementName { +public final class GetElementName { private static final String OPERATION = "get element name in xml"; + private GetElementName() { + } + public static String getElementName(Strand strand, BXml xml) { try { return xml.getElementName(); diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetItemType.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetItemType.java index 4a40314029b6..3423cf8a159f 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetItemType.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetItemType.java @@ -34,10 +34,13 @@ // returnType = {@ReturnType(type = TypeKind.STRING)}, // isPublic = true //) -public class GetItemType { +public final class GetItemType { private static final String OPERATION = "get xml item type"; + private GetItemType() { + } + public static Object getItemType(Strand strand, BXml xml) { try { return xml.getItemType(); diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetName.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetName.java index 984dc4e98357..bd6b72a24221 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetName.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetName.java @@ -35,10 +35,13 @@ // returnType = {@ReturnType(type = TypeKind.STRING)}, // isPublic = true //) -public class GetName { +public final class GetName { private static final String OPERATION = "get element name in xml"; + private GetName() { + } + public static BString getName(BXml xmlVal) { if (!IsElement.isElement(xmlVal)) { throw ErrorHelper.getRuntimeException(ErrorCodes.XML_FUNC_TYPE_ERROR, "getName", "element"); diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetTarget.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetTarget.java index 2be262b402cd..d64e97449c71 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetTarget.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetTarget.java @@ -31,7 +31,10 @@ * @since 1.0 */ -public class GetTarget { +public final class GetTarget { + + private GetTarget() { + } public static BString getTarget(BXml xmlValue) { if (!IsProcessingInstruction.isProcessingInstruction(xmlValue)) { diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetTextValue.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetTextValue.java index af33d2989261..21e076262fdb 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetTextValue.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/GetTextValue.java @@ -33,10 +33,13 @@ // returnType = {@ReturnType(type = TypeKind.STRING)}, // isPublic = true //) -public class GetTextValue { +public final class GetTextValue { private static final String OPERATION = "get text from xml"; + private GetTextValue() { + } + public static String getTextValue(Strand strand, BXml xml) { try { return xml.getTextValue(); diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/IsComment.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/IsComment.java index c658d4b4a8b8..caa96cd06426 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/IsComment.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/IsComment.java @@ -28,7 +28,10 @@ * * @since 1.0 */ -public class IsComment { +public final class IsComment { + + private IsComment() { + } public static boolean isComment(BXml xmlValue) { if (xmlValue.getNodeType() == XmlNodeType.COMMENT) { diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/IsElement.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/IsElement.java index 2d529ffff803..b5c2b901e0b1 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/IsElement.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/IsElement.java @@ -31,7 +31,10 @@ // returnType = {@ReturnType(type = TypeKind.BOOLEAN)}, // isPublic = true //) -public class IsElement { +public final class IsElement { + + private IsElement() { + } public static boolean isElement(BXml xmlValue) { return org.ballerinalang.langlib.internal.IsElement.isElement(xmlValue); diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/IsEmpty.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/IsEmpty.java index 6674593d1091..b888b91aecf7 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/IsEmpty.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/IsEmpty.java @@ -33,10 +33,13 @@ // returnType = {@ReturnType(type = TypeKind.BOOLEAN)}, // isPublic = true //) -public class IsEmpty { +public final class IsEmpty { private static final String OPERATION = "check xml is empty"; + private IsEmpty() { + } + public static boolean isEmpty(Strand strand, BXml xml) { try { return xml.isEmpty(); diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/IsProcessingInstruction.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/IsProcessingInstruction.java index f2bd291e6f97..2f8174e97d26 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/IsProcessingInstruction.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/IsProcessingInstruction.java @@ -28,7 +28,10 @@ * * @since 1.0 */ -public class IsProcessingInstruction { +public final class IsProcessingInstruction { + + private IsProcessingInstruction() { + } public static boolean isProcessingInstruction(BXml xmlValue) { if (xmlValue.getNodeType() == XmlNodeType.PI) { diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/IsSingleton.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/IsSingleton.java index c1cf3dfb0feb..6c7ce13c7779 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/IsSingleton.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/IsSingleton.java @@ -33,10 +33,13 @@ // returnType = {@ReturnType(type = TypeKind.BOOLEAN)}, // isPublic = true //) -public class IsSingleton { +public final class IsSingleton { private static final String OPERATION = "check xml is singleton"; + private IsSingleton() { + } + public static boolean isSingleton(Strand strand, BXml xml) { try { return xml.isSingleton(); diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/IsText.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/IsText.java index 329b7c32699c..064067a56439 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/IsText.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/IsText.java @@ -28,7 +28,10 @@ * * @since 1.0 */ -public class IsText { +public final class IsText { + + private IsText() { + } public static boolean isText(BXml xmlValue) { if (xmlValue.getNodeType() == XmlNodeType.TEXT || xmlValue.isEmpty()) { diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Length.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Length.java index 1f94cd4c6fb6..98ec17ad0d8a 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Length.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Length.java @@ -31,7 +31,10 @@ // returnType = {@ReturnType(type = TypeKind.INT)}, // isPublic = true //) -public class Length { +public final class Length { + + private Length() { + } public static long length(BXml xml) { return xml.size(); diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Map.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Map.java index f60a10aa3d51..65bb7b66390f 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Map.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Map.java @@ -46,12 +46,15 @@ // returnType = {@ReturnType(type = TypeKind.XML)}, // isPublic = true //) -public class Map { +public final class Map { private static final StrandMetadata METADATA = new StrandMetadata(BALLERINA_BUILTIN_PKG_PREFIX, XML_LANG_LIB, XML_VERSION, "filter"); - public static BXml map(BXml x, BFunctionPointer func) { + private Map() { + } + + public static BXml map(BXml x, BFunctionPointer func) { if (x.isSingleton()) { func.asyncCall(new Object[]{x, true}, METADATA); return null; diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Next.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Next.java index 6894e72be036..b5a029a1b97d 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Next.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Next.java @@ -38,10 +38,14 @@ // returnType = {@ReturnType(type = TypeKind.RECORD)}, // isPublic = true //) -public class Next { +public final class Next { + + private Next() { + } + //TODO: refactor hard coded values public static Object next(BObject m) { - BIterator xmlIterator = (BIterator) m.getNativeData("&iterator&"); + BIterator xmlIterator = (BIterator) m.getNativeData("&iterator&"); BXml bXml = (BXml) m.get(StringUtils.fromString("m")); if (xmlIterator == null) { diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/RemoveAttribute.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/RemoveAttribute.java index 34d8b58589dc..e23f0f59293f 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/RemoveAttribute.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/RemoveAttribute.java @@ -33,10 +33,13 @@ // args = {@Argument(name = "qname", type = TypeKind.STRING)}, // isPublic = true //) -public class RemoveAttribute { +public final class RemoveAttribute { private static final String OPERATION = "remove attribute"; + private RemoveAttribute() { + } + public static void removeAttribute(Strand strand, BXml xml, String qname) { try { xml.removeAttribute(qname); diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/RemoveChildren.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/RemoveChildren.java index 1d652d777712..68088550f065 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/RemoveChildren.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/RemoveChildren.java @@ -34,10 +34,13 @@ // args = {@Argument(name = "qname", type = TypeKind.STRING)}, // isPublic = true //) -public class RemoveChildren { +public final class RemoveChildren { private static final String OPERATION = "remove children from xml element"; + private RemoveChildren() { + } + public static void removeChildren(Strand strand, BXml xml, String qname) { try { xml.removeChildren(qname); diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Select.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Select.java index 328be8fa8b95..1d289fe2ab25 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Select.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Select.java @@ -34,10 +34,13 @@ // returnType = {@ReturnType(type = TypeKind.XML)}, // isPublic = true //) -public class Select { +public final class Select { private static final String OPERATION = "select elements from xml"; + private Select() { + } + public static BXml select(Strand strand, BXml xml, String qname) { try { return xml.elements(qname); diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/SelectDescendants.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/SelectDescendants.java index d80f50df0d1f..e3779ba7d8db 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/SelectDescendants.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/SelectDescendants.java @@ -37,10 +37,13 @@ // returnType = {@ReturnType(type = TypeKind.XML)}, // isPublic = true //) -public class SelectDescendants { +public final class SelectDescendants { private static final String OPERATION = "select descendants from xml"; + private SelectDescendants() { + } + public static BXml selectDescendants(Strand strand, BXml xml, BArray qnames) { try { // todo: this need to support list of qnames. diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/SetChildren.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/SetChildren.java index f10148529bd8..9c0f2de9a846 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/SetChildren.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/SetChildren.java @@ -45,10 +45,13 @@ // args = {@Argument(name = "children", type = TypeKind.UNION)}, // isPublic = true //) -public class SetChildren { +public final class SetChildren { private static final String OPERATION = "set children to xml element"; + private SetChildren() { + } + public static void setChildren(BXml xml, Object children) { if (!IsElement.isElement(xml)) { throw ErrorHelper.getRuntimeException(ErrorCodes.XML_FUNC_TYPE_ERROR, "setChildren", "element"); diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/SetName.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/SetName.java index 19868a890e9d..5bf32a3d5746 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/SetName.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/SetName.java @@ -39,9 +39,13 @@ // returnType = {@ReturnType(type = TypeKind.NIL)}, // isPublic = true //) -public class SetName { +public final class SetName { + private static final String OPERATION = "set element name in xml"; + private SetName() { + } + public static void setName(BXml xmlVal, BString newNameBStr) { String newName = newNameBStr.getValue(); diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Slice.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Slice.java index 06c3be18372f..d9993fe97fc4 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Slice.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Slice.java @@ -33,10 +33,13 @@ // @Argument(name = "endIndex", type = TypeKind.INT) }, // returnType = { @ReturnType(type = TypeKind.XML) }, isPublic = true //) -public class Slice { +public final class Slice { private static final String OPERATION = "slice xml"; + private Slice() { + } + public static BXml slice(BXml xml, long startIndex, long endIndex) { try { return xml.slice(startIndex, endIndex); diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Strip.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Strip.java index d8353fe2e980..71732d864b0d 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Strip.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Strip.java @@ -36,10 +36,13 @@ // returnType = {@ReturnType(type = TypeKind.XML)}, // isPublic = true //) -public class Strip { +public final class Strip { private static final String OPERATION = "strip xml"; + private Strip() { + } + public static BXml strip(BXml xml) { try { return xml.strip(); diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Text.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Text.java index 497095edcc12..04249ed0d29b 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Text.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Text.java @@ -31,7 +31,11 @@ * * @since 2.0.0 */ -public class Text { +public final class Text { + + private Text() { + } + public static BXml text(BXml xml) { if (xml.getNodeType() == XmlNodeType.TEXT) { return xml; diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/utils/Constants.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/utils/Constants.java index 064a8632e8ac..cfe8003a0b2c 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/utils/Constants.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/utils/Constants.java @@ -21,7 +21,7 @@ * * @since 2201.9.0 */ -public class Constants { +public final class Constants { public static final String XML_VERSION = "0.8.0"; diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/utils/XmlUtils.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/utils/XmlUtils.java index 6cbbd7e4dfb4..aa826736f83e 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/utils/XmlUtils.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/utils/XmlUtils.java @@ -25,7 +25,10 @@ * * @since 2201.9.0 */ -public class XmlUtils { +public final class XmlUtils { + + private XmlUtils() { + } @SafeVarargs public static List getList(E... values) { diff --git a/langlib/langlib-test/src/test/java/org/ballerinalang/langlib/test/LangLibMapTest.java b/langlib/langlib-test/src/test/java/org/ballerinalang/langlib/test/LangLibMapTest.java index 181fde74a14e..dc67b87400f6 100644 --- a/langlib/langlib-test/src/test/java/org/ballerinalang/langlib/test/LangLibMapTest.java +++ b/langlib/langlib-test/src/test/java/org/ballerinalang/langlib/test/LangLibMapTest.java @@ -85,7 +85,7 @@ public void testEntries() { Object returns = BRunUtil.invoke(compileResult, "testEntries"); assertEquals(getType(returns).getTag(), TypeTags.MAP_TAG); - BMap map = (BMap) returns; + BMap map = (BMap) returns; assertEquals(((BMapType) map.getType()).getConstrainedType().getTag(), TypeTags.TUPLE_TAG); assertEquals(map.size(), 3); assertEquals(map.get(StringUtils.fromString("lk")).toString(), "[\"lk\",\"Sri Lanka\"]"); @@ -100,7 +100,7 @@ public void testRemove() { assertEquals(result.get(0).toString(), "United Kingdom"); assertEquals(getType(result.get(1)).getTag(), TypeTags.MAP_TAG); - BMap map = (BMap) result.get(1); + BMap map = (BMap) result.get(1); assertEquals(map.size(), 2); assertEquals(map.get(StringUtils.fromString("lk")).toString(), "Sri Lanka"); assertEquals(map.get(StringUtils.fromString("us")).toString(), "USA"); @@ -118,7 +118,7 @@ public void testRemoveAll() { Object returns = BRunUtil.invoke(compileResult, "testRemoveAll"); assertEquals(getType(returns).getTag(), TypeTags.MAP_TAG); assertEquals(returns.toString(), "{}"); - assertEquals(((BMap) returns).size(), 0); + assertEquals(((BMap) returns).size(), 0); } @Test(dataProvider = "mapKeyProvider") @@ -147,7 +147,7 @@ public void testMap() { Object returns = BRunUtil.invoke(compileResult, "testMap"); assertEquals(getType(returns).getTag(), TypeTags.MAP_TAG); - BMap map = (BMap) returns; + BMap map = (BMap) returns; assertEquals(((BMapType) map.getType()).getConstrainedType().getTag(), TypeTags.FLOAT_TAG); assertEquals(map.size(), 3); assertEquals(map.get(StringUtils.fromString("1")), 5.5d); @@ -166,7 +166,7 @@ public void testFilter() { Object returns = BRunUtil.invoke(compileResult, "testFilter"); assertEquals(getType(returns).getTag(), TypeTags.MAP_TAG); - BMap map = (BMap) returns; + BMap map = (BMap) returns; assertEquals(((BMapType) map.getType()).getConstrainedType().getTag(), TypeTags.DECIMAL_TAG); assertEquals(map.size(), 2); assertEquals(map.get(StringUtils.fromString("1")), ValueCreator.createDecimalValue("12.34")); @@ -186,8 +186,8 @@ public void testAsyncFpArgsWithMaps() { assertTrue(arr.get(0) instanceof Long); assertTrue(arr.get(1) instanceof BMap); assertEquals(arr.get(0), 118L); - assertEquals(((BMap) arr.get(1)).get(StringUtils.fromString("b")), 36L); - assertEquals(((BMap) arr.get(1)).get(StringUtils.fromString("c")), 78L); + assertEquals(((BMap) arr.get(1)).get(StringUtils.fromString("b")), 36L); + assertEquals(((BMap) arr.get(1)).get(StringUtils.fromString("c")), 78L); } @DataProvider(name = "mapKeyProvider") diff --git a/langlib/langlib-test/src/test/java/org/ballerinalang/langlib/test/LangLibRecordTest.java b/langlib/langlib-test/src/test/java/org/ballerinalang/langlib/test/LangLibRecordTest.java index f9a34fa9f820..cc007f3cdb9e 100644 --- a/langlib/langlib-test/src/test/java/org/ballerinalang/langlib/test/LangLibRecordTest.java +++ b/langlib/langlib-test/src/test/java/org/ballerinalang/langlib/test/LangLibRecordTest.java @@ -87,7 +87,7 @@ public void testEntries() { Object returns = BRunUtil.invoke(compileResult, "testEntries"); assertEquals(getType(returns).getTag(), TypeTags.MAP_TAG); - BMap map = (BMap) returns; + BMap map = (BMap) returns; assertEquals(((BMapType) map.getType()).getConstrainedType().getTag(), TypeTags.TUPLE_TAG); assertEquals(map.size(), 2); assertEquals(map.get(StringUtils.fromString("name")).toString(), "[\"name\",\"John Doe\"]"); @@ -142,7 +142,7 @@ public void testMap() { Object returns = BRunUtil.invoke(compileResult, "testMap"); assertEquals(getType(returns).getTag(), TypeTags.MAP_TAG); - BMap map = (BMap) returns; + BMap map = (BMap) returns; assertEquals(((BMapType) map.getType()).getConstrainedType().getTag(), TypeTags.INT_TAG); assertEquals(map.size(), 2); assertEquals(map.get(StringUtils.fromString("name")), 8L); @@ -160,7 +160,7 @@ public void testFilter() { Object returns = BRunUtil.invoke(compileResult, "testFilter"); assertEquals(getType(returns).getTag(), TypeTags.MAP_TAG); - BMap map = (BMap) returns; + BMap map = (BMap) returns; assertEquals(((BMapType) map.getType()).getConstrainedType().getTag(), TypeTags.INT_TAG); assertEquals(map.size(), 2); assertEquals(map.get(StringUtils.fromString("physics")), 75L); diff --git a/langlib/langlib-test/src/test/java/org/ballerinalang/langlib/test/LangLibValueTest.java b/langlib/langlib-test/src/test/java/org/ballerinalang/langlib/test/LangLibValueTest.java index fccc3046e5ee..6854935e4f30 100644 --- a/langlib/langlib-test/src/test/java/org/ballerinalang/langlib/test/LangLibValueTest.java +++ b/langlib/langlib-test/src/test/java/org/ballerinalang/langlib/test/LangLibValueTest.java @@ -261,6 +261,11 @@ public void testXMLToStringWithXMLTextContainingAngleBrackets() { BRunUtil.invoke(compileResult, "testXMLWithAngleBrackets"); } + @Test + public void testXMLSequenceWithOneTextElement() { + BRunUtil.invoke(compileResult, "testXMLSequenceWithOneTextElement"); + } + @Test public void testToStringForTable() { BRunUtil.invoke(compileResult, "testToStringMethodForTable"); diff --git a/langlib/langlib-test/src/test/java/org/ballerinalang/langlib/test/statements/foreach/ForeachArrayTests.java b/langlib/langlib-test/src/test/java/org/ballerinalang/langlib/test/statements/foreach/ForeachArrayTests.java index 640ba239ecf6..e878626babb0 100644 --- a/langlib/langlib-test/src/test/java/org/ballerinalang/langlib/test/statements/foreach/ForeachArrayTests.java +++ b/langlib/langlib-test/src/test/java/org/ballerinalang/langlib/test/statements/foreach/ForeachArrayTests.java @@ -96,8 +96,8 @@ public void testIntArrayComplex() { @Test public void testFloatArrayWithArityOne() { StringBuilder sb = new StringBuilder(); - for (int i = 0; i < fValues.length; i++) { - sb.append(0).append(":").append(fValues[i]).append(" "); + for (double fValue : fValues) { + sb.append(0).append(":").append(fValue).append(" "); } Object returns = BRunUtil.invoke(program, "testFloatArrayWithArityOne"); Assert.assertEquals(returns.toString(), sb.toString()); @@ -116,8 +116,8 @@ public void testFloatArrayWithArityTwo() { @Test public void testStringArrayWithArityOne() { StringBuilder sb = new StringBuilder(); - for (int i = 0; i < sValues.length; i++) { - sb.append(0).append(":").append(sValues[i]).append(" "); + for (String sValue : sValues) { + sb.append(0).append(":").append(sValue).append(" "); } Object returns = BRunUtil.invoke(program, "testStringArrayWithArityOne"); Assert.assertEquals(returns.toString(), sb.toString()); @@ -136,8 +136,8 @@ public void testStringArrayWithArityTwo() { @Test public void testBooleanArrayWithArityOne() { StringBuilder sb = new StringBuilder(); - for (int i = 0; i < bValues.length; i++) { - sb.append(0).append(":").append(bValues[i]).append(" "); + for (boolean bValue : bValues) { + sb.append(0).append(":").append(bValue).append(" "); } Object returns = BRunUtil.invoke(program, "testBooleanArrayWithArityOne"); Assert.assertEquals(returns.toString(), sb.toString()); @@ -156,8 +156,8 @@ public void testBooleanArrayWithArityTwo() { @Test public void testJSONArrayWithArityOne() { StringBuilder sb = new StringBuilder(); - for (int i = 0; i < jValues.length; i++) { - sb.append("0").append(":").append(jValues[i]).append(" "); + for (String jValue : jValues) { + sb.append("0").append(":").append(jValue).append(" "); } Object returns = BRunUtil.invoke(program, "testJSONArrayWithArityOne"); Assert.assertEquals(returns.toString(), sb.toString()); @@ -176,8 +176,8 @@ public void testJSONArrayWithArityTwo() { @Test public void testStructArrayWithArityOne() { StringBuilder sb = new StringBuilder(); - for (int i = 0; i < tValues.length; i++) { - sb.append("0").append(":").append(tValues[i]).append(" "); + for (String tValue : tValues) { + sb.append("0").append(":").append(tValue).append(" "); } Object returns = BRunUtil.invoke(program, "testStructArrayWithArityOne"); Assert.assertEquals(returns.toString(), sb.toString()); diff --git a/langlib/langlib-test/src/test/resources/test-src/valuelib_test.bal b/langlib/langlib-test/src/test/resources/test-src/valuelib_test.bal index 4ea468dd3ef0..d5b54572d3f2 100644 --- a/langlib/langlib-test/src/test/resources/test-src/valuelib_test.bal +++ b/langlib/langlib-test/src/test/resources/test-src/valuelib_test.bal @@ -4565,6 +4565,13 @@ function testEnsureTypeWithJson6() returns json|error { return isMarried; } +function testEnsureTypeWithXMLSequence() returns xml:Text|error { + xml text1 = xml `abcdef`; + xml text2 = xml:map(xml:elements(text1), y => y.getChildren()); + xml:Text|error t1 = text2.ensureType(); + return t1; +} + function testEnsureTypeWithCast1() returns boolean|error { boolean isMarried = check p.married; return isMarried; @@ -4638,6 +4645,7 @@ function testEnsureType() { ]); assert((checkpanic testEnsureTypeWithJson5()), 72.5); assert((checkpanic testEnsureTypeWithJson6()), false); + assert((checkpanic testEnsureTypeWithXMLSequence()), xml `abcdef`); assert((checkpanic testEnsureTypeWithCast1()), false); assert((checkpanic testEnsureTypeWithCast2()), [ 125.0 / 3.0, @@ -4783,6 +4791,14 @@ function testXMLWithAngleBrackets() { panic error("AssertionError : expected: " + expected + " found: " + exy.toString()); } +function testXMLSequenceWithOneTextElement() { + xml text1 = xml `abcdef`; + xml text2 = xml:map(xml:elements(text1), y => y.getChildren()); + var item = text2.cloneWithType(xml:Text); + assertTrue(item is xml:Text); + assertEquality(xml `abcdef`, item); +} + public type KeyVals record {| anydata...; |}; diff --git a/langlib/langlib-test/src/test/resources/test-src/xmllib_test.bal b/langlib/langlib-test/src/test/resources/test-src/xmllib_test.bal index 804601d7c9c9..b224f79a9919 100644 --- a/langlib/langlib-test/src/test/resources/test-src/xmllib_test.bal +++ b/langlib/langlib-test/src/test/resources/test-src/xmllib_test.bal @@ -646,7 +646,7 @@ function testXMLIteratorInvocation() { public isolated function next() returns record {| 'xml:Text value; |}?; } iter3 = seq3.iterator(); - assertEquals((iter3.next()).toString(), "{\"value\":`bit of text1`}"); + assertEquals((iter3.next()).toString(), "{\"value\":`bit of text1 bit of text2`}"); xml d = xml ``; xml<'xml:ProcessingInstruction> seq4 = > d.concat(xml ``); @@ -721,24 +721,25 @@ function getDescendantsSimpleElement() { xml:Element e2 = xml `Empire Burlesque`; xml:Text e3 = xml `Empire Burlesque`; xml:Element e4 = xml `Bob Dylan`; - xml:Text e5 = xml `Bob Dylan`; + xml:Text e5 = xml `Bob Dylan + `; xml:Element e6 = xml `Hide your heartBonnie Tyler`; xml:Element e7 = xml `Hide your heart`; xml:Text e8 = xml `Hide your heart`; xml:Element e9 = xml `Bonnie Tyler`; xml:Text e10 = xml `Bonnie Tyler`; - assertEquals(descendantSeq.length(), 11); + assertEquals(descendantSeq.length(), 10); assertEquals(descendantSeq[0], e1); assertEquals(descendantSeq[1], e2); assertEquals(descendantSeq[2], e3); assertEquals(descendantSeq[3], e4); assertEquals(descendantSeq[4], e5); - assertEquals(descendantSeq[6], e6); - assertEquals(descendantSeq[7], e7); - assertEquals(descendantSeq[8], e8); - assertEquals(descendantSeq[9], e9); - assertEquals(descendantSeq[10], e10); + assertEquals(descendantSeq[5], e6); + assertEquals(descendantSeq[6], e7); + assertEquals(descendantSeq[7], e8); + assertEquals(descendantSeq[8], e9); + assertEquals(descendantSeq[9], e10); } function getDescendantsWithNS() { diff --git a/language-server/modules/langserver-cli/src/main/java/org/ballerinalang/langserver/cmd/LangServerStartCmd.java b/language-server/modules/langserver-cli/src/main/java/org/ballerinalang/langserver/cmd/LangServerStartCmd.java index c60300b4afa2..ad10c2f19466 100644 --- a/language-server/modules/langserver-cli/src/main/java/org/ballerinalang/langserver/cmd/LangServerStartCmd.java +++ b/language-server/modules/langserver-cli/src/main/java/org/ballerinalang/langserver/cmd/LangServerStartCmd.java @@ -17,8 +17,10 @@ import io.ballerina.cli.BLauncherCmd; import io.ballerina.cli.launcher.LauncherUtils; +import org.ballerinalang.langserver.launchers.stdio.Main; import picocli.CommandLine; +import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.Logger; @@ -48,9 +50,9 @@ public void execute() { // Start Language Server LogManager.getLogManager().reset(); - Logger globalLogger = Logger.getLogger(java.util.logging.Logger.GLOBAL_LOGGER_NAME); - globalLogger.setLevel(java.util.logging.Level.OFF); - org.ballerinalang.langserver.launchers.stdio.Main.startServer(System.in, System.out); + Logger globalLogger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); + globalLogger.setLevel(Level.OFF); + Main.startServer(System.in, System.out); } catch (Throwable e) { throw LauncherUtils.createLauncherException("Could not start language server"); } diff --git a/language-server/modules/langserver-commons/src/main/java/org/ballerinalang/langserver/commons/DocumentServiceContext.java b/language-server/modules/langserver-commons/src/main/java/org/ballerinalang/langserver/commons/DocumentServiceContext.java index 137201062cc4..708f3147a500 100644 --- a/language-server/modules/langserver-commons/src/main/java/org/ballerinalang/langserver/commons/DocumentServiceContext.java +++ b/language-server/modules/langserver-commons/src/main/java/org/ballerinalang/langserver/commons/DocumentServiceContext.java @@ -66,7 +66,7 @@ public interface DocumentServiceContext { /** * Get the file path. * - * @return {@link java.nio.file.Path} file path + * @return {@link Path} file path */ Path filePath(); diff --git a/language-server/modules/langserver-commons/src/main/java/org/ballerinalang/langserver/commons/toml/common/TomlCommonUtil.java b/language-server/modules/langserver-commons/src/main/java/org/ballerinalang/langserver/commons/toml/common/TomlCommonUtil.java index e30249664a63..f997d5fefcc1 100644 --- a/language-server/modules/langserver-commons/src/main/java/org/ballerinalang/langserver/commons/toml/common/TomlCommonUtil.java +++ b/language-server/modules/langserver-commons/src/main/java/org/ballerinalang/langserver/commons/toml/common/TomlCommonUtil.java @@ -28,7 +28,7 @@ * * @since 2.0.0 */ -public class TomlCommonUtil { +public final class TomlCommonUtil { public static final String LINE_SEPARATOR = System.lineSeparator(); diff --git a/language-server/modules/langserver-commons/src/main/java/org/ballerinalang/langserver/commons/toml/common/TomlSyntaxTreeUtil.java b/language-server/modules/langserver-commons/src/main/java/org/ballerinalang/langserver/commons/toml/common/TomlSyntaxTreeUtil.java index dcaba8ebcb7f..c32024e8051d 100644 --- a/language-server/modules/langserver-commons/src/main/java/org/ballerinalang/langserver/commons/toml/common/TomlSyntaxTreeUtil.java +++ b/language-server/modules/langserver-commons/src/main/java/org/ballerinalang/langserver/commons/toml/common/TomlSyntaxTreeUtil.java @@ -26,7 +26,7 @@ * * @since 2.0.0 */ -public class TomlSyntaxTreeUtil { +public final class TomlSyntaxTreeUtil { //Toml node types. public static final String NUMBER = "Number"; @@ -95,15 +95,11 @@ public static String trimResourcePath(String resourcePath) { * @return {@link String} default value. */ public static String getDefaultValueForType(ValueType type) { - switch (type) { - case NUMBER: - return "0"; - case BOOLEAN: - return "false"; - case STRING: - default: - return ""; - } + return switch (type) { + case NUMBER -> "0"; + case BOOLEAN -> "false"; + default -> ""; + }; } } diff --git a/language-server/modules/langserver-commons/src/main/java/org/ballerinalang/langserver/commons/toml/common/completion/TomlCompletionUtil.java b/language-server/modules/langserver-commons/src/main/java/org/ballerinalang/langserver/commons/toml/common/completion/TomlCompletionUtil.java index 72c496858b5f..9ee4fd2e6a37 100644 --- a/language-server/modules/langserver-commons/src/main/java/org/ballerinalang/langserver/commons/toml/common/completion/TomlCompletionUtil.java +++ b/language-server/modules/langserver-commons/src/main/java/org/ballerinalang/langserver/commons/toml/common/completion/TomlCompletionUtil.java @@ -49,7 +49,7 @@ * * @since 2.0.0 */ -public class TomlCompletionUtil { +public final class TomlCompletionUtil { private TomlCompletionUtil() { diff --git a/language-server/modules/langserver-commons/src/main/java/org/ballerinalang/langserver/commons/toml/visitor/Table.java b/language-server/modules/langserver-commons/src/main/java/org/ballerinalang/langserver/commons/toml/visitor/Table.java index e5fe308eec64..256a4983bb38 100644 --- a/language-server/modules/langserver-commons/src/main/java/org/ballerinalang/langserver/commons/toml/visitor/Table.java +++ b/language-server/modules/langserver-commons/src/main/java/org/ballerinalang/langserver/commons/toml/visitor/Table.java @@ -18,7 +18,7 @@ package org.ballerinalang.langserver.commons.toml.visitor; /** - * Represents Toml Table node in {@link org.ballerinalang.langserver.commons.toml.visitor.TomlSchemaVisitor}. + * Represents Toml Table node in {@link TomlSchemaVisitor}. * * @since 2.0.0 */ diff --git a/language-server/modules/langserver-commons/src/main/java/org/ballerinalang/langserver/commons/workspace/WorkspaceManager.java b/language-server/modules/langserver-commons/src/main/java/org/ballerinalang/langserver/commons/workspace/WorkspaceManager.java index 021a0f497562..0f35bdd1eff9 100644 --- a/language-server/modules/langserver-commons/src/main/java/org/ballerinalang/langserver/commons/workspace/WorkspaceManager.java +++ b/language-server/modules/langserver-commons/src/main/java/org/ballerinalang/langserver/commons/workspace/WorkspaceManager.java @@ -137,7 +137,7 @@ public interface WorkspaceManager { * Returns syntax tree from the path provided. * * @param filePath file path of the document - * @return {@link io.ballerina.compiler.syntax.tree.SyntaxTree} + * @return {@link SyntaxTree} */ Optional syntaxTree(Path filePath); @@ -146,7 +146,7 @@ public interface WorkspaceManager { * * @param filePath file path of the document * @param cancelChecker Cancel checker for the operation which calls this method - * @return {@link io.ballerina.compiler.syntax.tree.SyntaxTree} + * @return {@link SyntaxTree} */ Optional syntaxTree(Path filePath, CancelChecker cancelChecker); diff --git a/language-server/modules/langserver-commons/src/test/java/org/ballerina/langserver/commons/toml/completion/SchemaVisitorTest.java b/language-server/modules/langserver-commons/src/test/java/org/ballerina/langserver/commons/toml/completion/SchemaVisitorTest.java index 4defd9319457..79d4ab3a960f 100644 --- a/language-server/modules/langserver-commons/src/test/java/org/ballerina/langserver/commons/toml/completion/SchemaVisitorTest.java +++ b/language-server/modules/langserver-commons/src/test/java/org/ballerina/langserver/commons/toml/completion/SchemaVisitorTest.java @@ -31,7 +31,8 @@ import org.testng.annotations.Test; import java.io.IOException; -import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.util.Map; /** @@ -53,9 +54,7 @@ public void test(String configFileName) throws IOException { .resolve("schema_visitor").resolve("schema").resolve(schemaFile).toString()); Gson gson = new Gson(); - Type collectionType = new TypeToken>>() { - }.getType(); - Map> expectedMap = gson.fromJson(expected, collectionType); + Map> expectedMap = gson.fromJson(expected, new TypeToken<>() { }); Schema validationSchema = Schema.from(schemaString); TomlSchemaVisitor visitor = new TomlSchemaVisitor(); @@ -101,7 +100,6 @@ private void updateConfig(Map> response, obj.add("source", configJsonObject.get("source")); obj.add("expected", JsonParser.parseString(json)); String objStr = obj.toString().concat(System.lineSeparator()); - java.nio.file.Files.write(FileUtils.RES_DIR.resolve(configJsonPath), - objStr.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + Files.write(FileUtils.RES_DIR.resolve(configJsonPath), objStr.getBytes(StandardCharsets.UTF_8)); } } diff --git a/language-server/modules/langserver-commons/src/test/java/org/ballerina/langserver/commons/toml/util/FileUtils.java b/language-server/modules/langserver-commons/src/test/java/org/ballerina/langserver/commons/toml/util/FileUtils.java index ad8f06bca32d..721db6fdc08a 100644 --- a/language-server/modules/langserver-commons/src/test/java/org/ballerina/langserver/commons/toml/util/FileUtils.java +++ b/language-server/modules/langserver-commons/src/test/java/org/ballerina/langserver/commons/toml/util/FileUtils.java @@ -32,15 +32,16 @@ * * @since 2.0.0 */ -public class FileUtils { - - private static final JsonParser JSON_PARSER = new JsonParser(); +public final class FileUtils { private static final Logger LOGGER = LoggerFactory.getLogger(FileUtils.class); public static final Path RES_DIR = Paths.get("src/test/resources/").toAbsolutePath(); public static final Path BUILD_DIR = Paths.get("build/").toAbsolutePath(); + private FileUtils() { + } + /** * Get the file content. * @@ -54,7 +55,7 @@ public static JsonObject fileContentAsObject(String filePath) { } catch (IOException ex) { LOGGER.error(ex.getMessage()); } - return JSON_PARSER.parse(contentAsString).getAsJsonObject(); + return JsonParser.parseString(contentAsString).getAsJsonObject(); } /** diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/BallerinaLanguageServer.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/BallerinaLanguageServer.java index 94cba2b35433..69ad5998e81d 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/BallerinaLanguageServer.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/BallerinaLanguageServer.java @@ -17,6 +17,7 @@ import com.google.gson.Gson; import com.google.gson.JsonObject; +import com.google.gson.reflect.TypeToken; import io.ballerina.projects.util.ProjectConstants; import org.ballerinalang.langserver.command.LSCommandExecutorProvidersHolder; import org.ballerinalang.langserver.common.utils.CommonUtil; @@ -115,15 +116,18 @@ public CompletableFuture initialize(InitializeParams params) { final InitializeResult res = new InitializeResult(new ServerCapabilities()); res.getCapabilities().setTextDocumentSync(TextDocumentSyncKind.Full); - Map experimentalClientCapabilities = null; + Map experimentalClientCapabilities = null; if (params.getCapabilities().getExperimental() != null) { experimentalClientCapabilities = new Gson().fromJson(params.getCapabilities().getExperimental().toString(), - HashMap.class); + new TypeToken<>() { + }); } - Map initializationOptions = null; + Map initializationOptions = null; if (params.getInitializationOptions() != null) { - initializationOptions = new Gson().fromJson(params.getInitializationOptions().toString(), HashMap.class); + initializationOptions = new Gson().fromJson(params.getInitializationOptions().toString(), + new TypeToken<>() { + }); } TextDocumentClientCapabilities textDocClientCapabilities = params.getCapabilities().getTextDocument(); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/BallerinaTextDocumentService.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/BallerinaTextDocumentService.java index 7b6fcc24e9a5..23ec7b07b38c 100755 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/BallerinaTextDocumentService.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/BallerinaTextDocumentService.java @@ -114,7 +114,6 @@ import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.function.Function; -import java.util.stream.Collectors; import static org.ballerinalang.formatter.core.FormatterUtils.buildFormattingOptions; @@ -345,7 +344,7 @@ public CompletableFuture>> codeAction(CodeActio cancelChecker); return LangExtensionDelegator.instance().codeActions(params, context, this.serverContext).stream() .map((Function>) Either::forRight) - .collect(Collectors.toList()); + .toList(); } catch (UserErrorException e) { this.clientLogger.notifyUser("Code Action", e); } catch (CancellationException ignore) { diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/BallerinaWorkspaceService.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/BallerinaWorkspaceService.java index 18bd3b4be918..168284561117 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/BallerinaWorkspaceService.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/BallerinaWorkspaceService.java @@ -41,7 +41,6 @@ import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; -import java.util.stream.Collectors; /** * Workspace service implementation for Ballerina. @@ -71,10 +70,9 @@ public void setClientCapabilities(LSClientCapabilities clientCapabilities) { @Override public void didChangeConfiguration(DidChangeConfigurationParams params) { - if (!(params.getSettings() instanceof JsonObject)) { + if (!(params.getSettings() instanceof JsonObject settings)) { return; } - JsonObject settings = (JsonObject) params.getSettings(); if (settings.get("ballerina") != null) { configHolder.updateConfig(settings.get("ballerina")); } else { @@ -111,7 +109,7 @@ public CompletableFuture executeCommand(ExecuteCommandParams params) { return CompletableFuture.supplyAsync(() -> { List commandArguments = params.getArguments().stream() .map(CommandArgument::from) - .collect(Collectors.toList()); + .toList(); ExecuteCommandContext context = ContextBuilder.buildExecuteCommandContext(this.workspaceManagerProxy.get(), this.serverContext, commandArguments, diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/CentralPackageDescriptorLoader.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/CentralPackageDescriptorLoader.java index f87274d549ae..4cdb3a22d3df 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/CentralPackageDescriptorLoader.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/CentralPackageDescriptorLoader.java @@ -146,7 +146,7 @@ public void setOffset(int offset) { } public Map getQueryMap() { - Map params = new HashMap(); + Map params = new HashMap<>(); params.put("readme", "false"); if (getOrganization() != null) { diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/ExtendedClientCapabilityBuilder.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/ExtendedClientCapabilityBuilder.java index 6b811ec5dbda..21d4e0c28746 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/ExtendedClientCapabilityBuilder.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/ExtendedClientCapabilityBuilder.java @@ -30,7 +30,8 @@ * * @since 2.0.0 */ -public class ExtendedClientCapabilityBuilder { +public final class ExtendedClientCapabilityBuilder { + private static List> capabilitySetters; private ExtendedClientCapabilityBuilder() { @@ -46,6 +47,7 @@ public static List get(List configs) { if (capabilitySetters == null) { capabilitySetters = new ArrayList<>(); + @SuppressWarnings("rawtypes") ServiceLoader loader = ServiceLoader.load(BallerinaClientCapabilitySetter.class); for (BallerinaClientCapabilitySetter capabilitySetter : loader) { @@ -56,10 +58,9 @@ public static List get(List configs) { List clientCapabilities = new ArrayList<>(); for (Object config : configs) { - if (!(config instanceof JsonObject)) { + if (!(config instanceof JsonObject jConfig)) { continue; } - JsonObject jConfig = (JsonObject) config; String capabilityName = jConfig.get("name").getAsString(); Optional> setter = capabilitySetters.stream() diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/ExtendedServerCapabilityBuilder.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/ExtendedServerCapabilityBuilder.java index ba9fba99c05e..60c6fe00500a 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/ExtendedServerCapabilityBuilder.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/ExtendedServerCapabilityBuilder.java @@ -28,7 +28,8 @@ * * @since 2.0.0 */ -public class ExtendedServerCapabilityBuilder { +public final class ExtendedServerCapabilityBuilder { + private static List> capabilitySetters; private ExtendedServerCapabilityBuilder() { @@ -43,6 +44,7 @@ public static List get() { if (capabilitySetters == null) { capabilitySetters = new ArrayList<>(); + @SuppressWarnings("rawtypes") ServiceLoader loader = ServiceLoader.load(BallerinaServerCapabilitySetter.class); for (BallerinaServerCapabilitySetter capabilitySetter : loader) { diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/LSClientCapabilitiesImpl.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/LSClientCapabilitiesImpl.java index 65a1c179fbcb..4c4d495560f0 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/LSClientCapabilitiesImpl.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/LSClientCapabilitiesImpl.java @@ -44,8 +44,8 @@ public class LSClientCapabilitiesImpl implements LSClientCapabilities { LSClientCapabilitiesImpl(TextDocumentClientCapabilities textDocCapabilities, WorkspaceClientCapabilities workspaceCapabilities, - Map experimentalClientCapabilities, - Map initializationOptionsMap) { + Map experimentalClientCapabilities, + Map initializationOptionsMap) { this.textDocCapabilities = (textDocCapabilities != null) ? textDocCapabilities : new TextDocumentClientCapabilities(); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/LangExtensionDelegator.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/LangExtensionDelegator.java index 397e73a6d390..ffdef89007e3 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/LangExtensionDelegator.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/LangExtensionDelegator.java @@ -168,8 +168,7 @@ public List codeActions(CodeActionParams params, CodeActio && ext.validate(params)) { List codeActions = ext.execute(params, context, serverContext); for (CodeAction codeAction : codeActions) { - if (codeAction instanceof ResolvableCodeAction) { - ResolvableCodeAction action = (ResolvableCodeAction) codeAction; + if (codeAction instanceof ResolvableCodeAction action) { action.getData().setExtName(ext.getClass().getName()); } actions.add(codeAction); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/CodeActionNodeAnalyzer.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/CodeActionNodeAnalyzer.java index 96423f5fc11b..c0261a3a7de4 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/CodeActionNodeAnalyzer.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/CodeActionNodeAnalyzer.java @@ -205,14 +205,7 @@ public void visit(FunctionDefinitionNode node) { @Override public void visit(TypeDefinitionNode node) { checkAndSetCodeActionNode(node); - - // If cursor was outside object/record type desc, we have to manually check for the type - Node typeDescriptor = node.typeDescriptor(); - if (typeDescriptor.kind() == SyntaxKind.RECORD_TYPE_DESC) { - checkAndSetSyntaxKind(typeDescriptor.kind()); - } else if (typeDescriptor.kind() == SyntaxKind.OBJECT_TYPE_DESC) { - checkAndSetSyntaxKind(typeDescriptor.kind()); - } + checkAndSetSyntaxKind(node.typeDescriptor().kind()); Optional qualifier = node.visibilityQualifier(); int startOffset = qualifier.isEmpty() ? @@ -729,9 +722,9 @@ private boolean isWithinRange(int startOffSet, int endOffset) { @Override protected void visitSyntaxNode(Node node) { // Here we check for the statement nodes explicitly to identify the closest statement node - if (node instanceof StatementNode) { + if (node instanceof StatementNode statementNode) { if (!(node instanceof BlockStatementNode)) { - checkAndSetStatementNode((StatementNode) node); + checkAndSetStatementNode(statementNode); } } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/CodeActionProvidersHolder.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/CodeActionProvidersHolder.java index 96d9773b564c..ef37afac2028 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/CodeActionProvidersHolder.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/CodeActionProvidersHolder.java @@ -30,7 +30,6 @@ import java.util.Map; import java.util.Optional; import java.util.ServiceLoader; -import java.util.stream.Collectors; /** * Represents the Code Action provider factory. @@ -74,14 +73,12 @@ private void loadServices() { if (provider == null) { continue; } - if (provider instanceof RangeBasedCodeActionProvider) { - RangeBasedCodeActionProvider codeActionProvider = (RangeBasedCodeActionProvider) provider; + if (provider instanceof RangeBasedCodeActionProvider codeActionProvider) { for (SyntaxKind nodeType : codeActionProvider.getSyntaxKinds()) { CodeActionProvidersHolder.rangeBasedProviders.get(nodeType).add(codeActionProvider); } } - if (provider instanceof DiagnosticBasedCodeActionProvider) { - DiagnosticBasedCodeActionProvider codeActionProvider = (DiagnosticBasedCodeActionProvider) provider; + if (provider instanceof DiagnosticBasedCodeActionProvider codeActionProvider) { CodeActionProvidersHolder.diagnosticsBasedProviders.add(codeActionProvider); } } @@ -98,7 +95,7 @@ List getActiveRangeBasedProviders(SyntaxKind nodeT return CodeActionProvidersHolder.rangeBasedProviders.get(nodeType).stream() .filter(provider -> provider.isEnabled(ctx.languageServercontext())) .sorted(Comparator.comparingInt(LSCodeActionProvider::priority)) - .collect(Collectors.toList()); + .toList(); } return Collections.emptyList(); } @@ -112,7 +109,7 @@ List getActiveDiagnosticsBasedProviders(CodeA return CodeActionProvidersHolder.diagnosticsBasedProviders.stream() .filter(provider -> provider.isEnabled(ctx.languageServercontext())) .sorted(Comparator.comparingInt(LSCodeActionProvider::priority)) - .collect(Collectors.toList()); + .toList(); } /** diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/CodeActionRouter.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/CodeActionRouter.java index bbf4fa805708..5d32a2289643 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/CodeActionRouter.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/CodeActionRouter.java @@ -52,7 +52,10 @@ * * @since 1.1.1 */ -public class CodeActionRouter { +public final class CodeActionRouter { + + private CodeActionRouter() { + } /** * Returns a list of supported code actions. diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/CodeActionUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/CodeActionUtil.java index 1d75d9443c17..edc1c5658cb7 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/CodeActionUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/CodeActionUtil.java @@ -87,7 +87,6 @@ import java.util.Optional; import java.util.function.Function; import java.util.function.Predicate; -import java.util.stream.Collectors; import static org.ballerinalang.langserver.common.utils.CommonUtil.LINE_SEPARATOR; @@ -96,7 +95,7 @@ * * @since 1.0.1 */ -public class CodeActionUtil { +public final class CodeActionUtil { private CodeActionUtil() { } @@ -309,18 +308,15 @@ public static Map getPossibleTypeSymbols(TypeSymbol typeDesc getPossibleTypeSymbols(arrayTypeSymbol.memberTypeDescriptor(), context, importsAcceptor).entrySet() .forEach(entry -> { ArrayTypeSymbol newArrType = typeBuilder.ARRAY_TYPE.withType(entry.getKey()).build(); - String signature; - switch (newArrType.memberTypeDescriptor().typeKind()) { - case FUNCTION: - case UNION: + String signature = switch (newArrType.memberTypeDescriptor().typeKind()) { + case FUNCTION, UNION -> { String typeName = FunctionGenerator.processModuleIDsInText(importsAcceptor, newArrType.memberTypeDescriptor().signature(), context); - signature = "(" + typeName + ")[]"; - break; - default: - signature = FunctionGenerator.processModuleIDsInText(importsAcceptor, - newArrType.signature(), context); - } + yield "(" + typeName + ")[]"; + } + default -> FunctionGenerator.processModuleIDsInText(importsAcceptor, + newArrType.signature(), context); + }; typesMap.put(newArrType, signature); }); } else { @@ -338,24 +334,18 @@ public static Map getPossibleTypeSymbols(TypeSymbol typeDesc */ public static boolean isJsonMemberType(TypeSymbol typeSymbol) { // type json = () | boolean | int | float | decimal | string | json[] | map; - switch (typeSymbol.typeKind()) { - case NIL: - case BOOLEAN: - case INT: - case FLOAT: - case DECIMAL: - case STRING: - case JSON: - return true; - case ARRAY: - ArrayTypeSymbol arrayTypeSymbol = (ArrayTypeSymbol) typeSymbol; - return isJsonMemberType(arrayTypeSymbol.memberTypeDescriptor()); - case MAP: - MapTypeSymbol mapTypeSymbol = (MapTypeSymbol) typeSymbol; - return isJsonMemberType(mapTypeSymbol.typeParam()); - default: - return false; - } + return switch (typeSymbol.typeKind()) { + case NIL, + BOOLEAN, + INT, + FLOAT, + DECIMAL, + STRING, + JSON -> true; + case ARRAY -> isJsonMemberType(((ArrayTypeSymbol) typeSymbol).memberTypeDescriptor()); + case MAP -> isJsonMemberType(((MapTypeSymbol) typeSymbol).typeParam()); + default -> false; + }; } /** @@ -567,7 +557,7 @@ private static List filterErrorSubTypes(List errorTypeSy List errorTypeSymbolsClone = new ArrayList<>(errorTypeSymbols); return errorTypeSymbolsClone.stream().filter(typeSymbol -> errorTypeSymbols.stream().filter(other -> !other.signature().equals(typeSymbol.signature())) - .noneMatch(typeSymbol::subtypeOf)).collect(Collectors.toList()); + .noneMatch(typeSymbol::subtypeOf)).toList(); } private static Pair, List> getErrorAndNonErrorTypedSymbols( diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/CompilerPluginCodeActionExtension.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/CompilerPluginCodeActionExtension.java index b62c108a942e..7c9edde67fe1 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/CompilerPluginCodeActionExtension.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/CompilerPluginCodeActionExtension.java @@ -61,7 +61,6 @@ import java.util.LinkedList; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; /** * Compiler plugin code action extension implementation for ballerina. @@ -129,7 +128,7 @@ public List execute(CodeActionParams inputParams, return CodeActionUtil.createResolvableCodeAction(codeActionInfo.getTitle(), CodeActionKind.QuickFix, codeActionData); }) - .collect(Collectors.toList()); + .toList(); } @Override @@ -155,7 +154,7 @@ public CodeAction resolve(ResolvableCodeAction codeAction, CodeActionResolveCont List arguments = actionData.stream() .map(gson::toJsonTree) .map(CodeActionArgument::from) - .collect(Collectors.toList()); + .toList(); // Build the execution context and execute code action CodeActionExecutionContext codeActionContext = CodeActionExecutionContextImpl.from( codeActionData.getFileUri(), diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/AddCheckCodeAction.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/AddCheckCodeAction.java index 078481fa9548..73ca4fbfea2c 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/AddCheckCodeAction.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/AddCheckCodeAction.java @@ -46,7 +46,6 @@ import java.util.List; import java.util.Optional; import java.util.Set; -import java.util.stream.Collectors; /** * Code Action for error type handle. @@ -137,7 +136,7 @@ public List getCodeActions(Diagnostic diagnostic, DiagBasedPositionD List errorTypeSymbols = ((UnionTypeSymbol) foundType.get()).memberTypeDescriptors().stream() .filter(typeSymbol -> CommonUtil.getRawType(typeSymbol).typeKind() == TypeDescKind.ERROR) - .collect(Collectors.toList()); + .toList(); ImportsAcceptor acceptor = new ImportsAcceptor(context); List edits = new ArrayList<>(CodeActionUtil.getAddCheckTextEdits( diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/ConvertToReadonlyCloneCodeAction.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/ConvertToReadonlyCloneCodeAction.java index b77a10b5d528..0828a0372631 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/ConvertToReadonlyCloneCodeAction.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/ConvertToReadonlyCloneCodeAction.java @@ -94,18 +94,13 @@ private boolean isCloneReadonlyAvailable(TypeSymbol typeSymbol) { } private String getNewText(NonTerminalNode currentNode) { - String prefix; - switch (currentNode.kind()) { - case LET_EXPRESSION: - case CONDITIONAL_EXPRESSION: - case CHECK_EXPRESSION: - case XML_STEP_EXPRESSION: - prefix = "(" + currentNode.toSourceCode().trim() + ")"; - break; - default: - prefix = currentNode.toSourceCode().trim(); - break; - } + String prefix = switch (currentNode.kind()) { + case LET_EXPRESSION, + CONDITIONAL_EXPRESSION, + CHECK_EXPRESSION, + XML_STEP_EXPRESSION -> "(" + currentNode.toSourceCode().trim() + ")"; + default -> currentNode.toSourceCode().trim(); + }; return prefix + "." + CLONE_READONLY_PREFIX + "()"; } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/CreateFunctionCodeAction.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/CreateFunctionCodeAction.java index 1c785de1552a..920d87f80b1f 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/CreateFunctionCodeAction.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/CreateFunctionCodeAction.java @@ -225,8 +225,7 @@ public CodeAction resolve(ResolvableCodeAction codeAction, CodeActionResolveCont List args = new ArrayList<>(); int argIndex = 1; - List argumentKindList = Arrays. - asList(io.ballerina.compiler.api.symbols.SymbolKind.VARIABLE, SymbolKind.CONSTANT); + List argumentKindList = Arrays.asList(SymbolKind.VARIABLE, SymbolKind.CONSTANT); for (FunctionArgumentNode fnArgNode : fnCallExprNode.get().arguments()) { Optional type = semanticModel.typeOf(fnArgNode); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/ExtractToFunctionCodeAction.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/ExtractToFunctionCodeAction.java index 51100f6ffde8..d19141e3a979 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/ExtractToFunctionCodeAction.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/ExtractToFunctionCodeAction.java @@ -341,7 +341,7 @@ private Optional> getVarAndParamSymbolsWithinRangeForStmts(CodeActi return Optional.of(argsSymbolsForExtractFunction.stream() // getLocation() is present for each symbol .sorted(Comparator.comparingInt(symbol -> symbol.getLocation().get().textRange().startOffset())) - .collect(Collectors.toList())); + .toList()); } /** @@ -550,7 +550,7 @@ private Optional> getVarAndParamSymbolsWithinRangeForExprs(LineRang .filter(symbol -> !PositionUtil.isWithinLineRange(symbol.getLocation().get().lineRange(), matchedLineRange)) .sorted(Comparator.comparingInt(symbol -> symbol.getLocation().get().textRange().startOffset())) - .collect(Collectors.toList())); + .toList()); } private Optional getArgLists(CodeActionContext context, List symbolsList, diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/FillRecordFieldsCodeAction.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/FillRecordFieldsCodeAction.java index 367bfc59f2dd..0e9d2d595721 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/FillRecordFieldsCodeAction.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/FillRecordFieldsCodeAction.java @@ -50,7 +50,6 @@ import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.stream.Collectors; /** * Code Action to autofill record fields. @@ -135,7 +134,7 @@ protected List getFields(MappingConstructorExpressionNode node) { .filter(field -> !field.isMissing() && field.kind() == SyntaxKind.SPECIFIC_FIELD && ((SpecificFieldNode) field).fieldName().kind() == SyntaxKind.IDENTIFIER_TOKEN) .map(field -> ((IdentifierToken) ((SpecificFieldNode) field).fieldName()).text()) - .collect(Collectors.toList()); + .toList(); } private static Optional getMappingConstructorNode(Node node) { diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/IgnoreUnusedVariableCodeAction.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/IgnoreUnusedVariableCodeAction.java index 2a4ad84fb892..e57158b78578 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/IgnoreUnusedVariableCodeAction.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/IgnoreUnusedVariableCodeAction.java @@ -142,9 +142,7 @@ public List getCodeActions(Diagnostic diagnostic, Range editRange = PositionUtil.toRange(bindingPatternNode.lineRange()); textEdit = new TextEdit(editRange, "_"); } else if (bindingPatternNode.kind() == SyntaxKind.FIELD_BINDING_PATTERN) { - if (bindingPatternNode instanceof FieldBindingPatternVarnameNode) { - FieldBindingPatternVarnameNode fieldBindingPattern = - (FieldBindingPatternVarnameNode) bindingPatternNode; + if (bindingPatternNode instanceof FieldBindingPatternVarnameNode fieldBindingPattern) { Position position = PositionUtil.toPosition(fieldBindingPattern.variableName().lineRange().endLine()); Range editRange = new Range(position, position); textEdit = new TextEdit(editRange, ": _"); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/ImplementAllCodeAction.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/ImplementAllCodeAction.java index 667fe6fc1524..c36eb3a00dcb 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/ImplementAllCodeAction.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/ImplementAllCodeAction.java @@ -36,7 +36,6 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; -import java.util.stream.Collectors; import static org.ballerinalang.langserver.codeaction.CodeActionUtil.computePositionDetails; @@ -90,7 +89,7 @@ public List getCodeActions(CodeActionContext context, RangeBasedPosi .isRangeWithinRange(context.range(), PositionUtil.toRange(diag.location().lineRange())) ) .filter(diagnostic -> DIAGNOSTIC_CODES.contains(diagnostic.diagnosticInfo().code())) - .collect(Collectors.toList()); + .toList(); if (diags.isEmpty() || diags.size() == 1) { return Collections.emptyList(); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/changetype/ChangeVariableTypeCodeAction.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/changetype/ChangeVariableTypeCodeAction.java index baf8493d4303..5c2427e26a59 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/changetype/ChangeVariableTypeCodeAction.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/changetype/ChangeVariableTypeCodeAction.java @@ -191,9 +191,9 @@ private Optional getTypeNodeStr(Node node) { } else if (node.kind() == SyntaxKind.QUALIFIED_NAME_REFERENCE) { QualifiedNameReferenceNode qnRefNode = (QualifiedNameReferenceNode) node; return Optional.of(qnRefNode.modulePrefix().text() + ":" + qnRefNode.identifier().text()); - } else if (node instanceof BuiltinSimpleNameReferenceNode) { + } else if (node instanceof BuiltinSimpleNameReferenceNode refNode) { // This case occurs with constant declarations with types - return Optional.of(((BuiltinSimpleNameReferenceNode) node).name().text()); + return Optional.of(refNode.name().text()); } return Optional.empty(); } @@ -225,18 +225,13 @@ private Optional getTypeNode(Node matchedNode, CodeActionContext context) return getLetVarDeclTypeNode((LetVariableDeclarationNode) matchedNode); case LET_EXPRESSION: Node parent = matchedNode.parent(); - switch (parent.kind()) { - case LOCAL_VAR_DECL: - return getLocalVarTypeNode((VariableDeclarationNode) parent); - case MODULE_VAR_DECL: - return getModuleVarTypeNode((ModuleVariableDeclarationNode) parent); - case OBJECT_FIELD: - return getObjectFieldTypeNode((ObjectFieldNode) parent); - case LET_VAR_DECL: - return getLetVarDeclTypeNode((LetVariableDeclarationNode) parent); - default: - return Optional.empty(); - } + return switch (parent.kind()) { + case LOCAL_VAR_DECL -> getLocalVarTypeNode((VariableDeclarationNode) parent); + case MODULE_VAR_DECL -> getModuleVarTypeNode((ModuleVariableDeclarationNode) parent); + case OBJECT_FIELD -> getObjectFieldTypeNode((ObjectFieldNode) parent); + case LET_VAR_DECL -> getLetVarDeclTypeNode((LetVariableDeclarationNode) parent); + default -> Optional.empty(); + }; default: return Optional.empty(); } @@ -259,48 +254,41 @@ private Optional getLetVarDeclTypeNode(LetVariableDeclarationNode node) { } private Optional getVariableName(Node matchedNode) { - switch (matchedNode.kind()) { - case LOCAL_VAR_DECL: - return getVarNameFromBindingPattern(((VariableDeclarationNode) matchedNode) - .typedBindingPattern().bindingPattern()); - case MODULE_VAR_DECL: - return getVarNameFromBindingPattern(((ModuleVariableDeclarationNode) matchedNode) - .typedBindingPattern().bindingPattern()); - case ASSIGNMENT_STATEMENT: + return switch (matchedNode.kind()) { + case LOCAL_VAR_DECL -> getVarNameFromBindingPattern(((VariableDeclarationNode) matchedNode) + .typedBindingPattern().bindingPattern()); + case MODULE_VAR_DECL -> getVarNameFromBindingPattern(((ModuleVariableDeclarationNode) matchedNode) + .typedBindingPattern().bindingPattern()); + case ASSIGNMENT_STATEMENT -> { AssignmentStatementNode assignmentStmtNode = (AssignmentStatementNode) matchedNode; Node varRef = assignmentStmtNode.varRef(); if (varRef.kind() == SyntaxKind.SIMPLE_NAME_REFERENCE) { - return Optional.of(((SimpleNameReferenceNode) varRef).name().text()); + yield Optional.of(((SimpleNameReferenceNode) varRef).name().text()); } else if (varRef.kind() == SyntaxKind.QUALIFIED_NAME_REFERENCE) { - return Optional.of(((QualifiedNameReferenceNode) varRef).identifier().text()); + yield Optional.of(((QualifiedNameReferenceNode) varRef).identifier().text()); } - return Optional.empty(); - case CONST_DECLARATION: + yield Optional.empty(); + } + case CONST_DECLARATION -> { ConstantDeclarationNode constantDecl = (ConstantDeclarationNode) matchedNode; - return Optional.of(constantDecl.variableName().text()); - case OBJECT_FIELD: - return getObjectFieldName((ObjectFieldNode) matchedNode); - case LET_VAR_DECL: - return getLetVarName((LetVariableDeclarationNode) matchedNode); - case LET_EXPRESSION: + yield Optional.of(constantDecl.variableName().text()); + } + case OBJECT_FIELD -> getObjectFieldName((ObjectFieldNode) matchedNode); + case LET_VAR_DECL -> getLetVarName((LetVariableDeclarationNode) matchedNode); + case LET_EXPRESSION -> { Node parent = matchedNode.parent(); - switch (parent.kind()) { - case LOCAL_VAR_DECL: - return getVarNameFromBindingPattern(((VariableDeclarationNode) parent) - .typedBindingPattern().bindingPattern()); - case MODULE_VAR_DECL: - return getVarNameFromBindingPattern(((ModuleVariableDeclarationNode) parent) - .typedBindingPattern().bindingPattern()); - case OBJECT_FIELD: - return getObjectFieldName((ObjectFieldNode) parent); - case LET_VAR_DECL: - return getLetVarName((LetVariableDeclarationNode) parent); - default: - return Optional.empty(); - } - default: - return Optional.empty(); - } + yield switch (parent.kind()) { + case LOCAL_VAR_DECL -> getVarNameFromBindingPattern(((VariableDeclarationNode) parent) + .typedBindingPattern().bindingPattern()); + case MODULE_VAR_DECL -> getVarNameFromBindingPattern(((ModuleVariableDeclarationNode) parent) + .typedBindingPattern().bindingPattern()); + case OBJECT_FIELD -> getObjectFieldName((ObjectFieldNode) parent); + case LET_VAR_DECL -> getLetVarName((LetVariableDeclarationNode) parent); + default -> Optional.empty(); + }; + } + default -> Optional.empty(); + }; } private Optional getVarNameFromBindingPattern(BindingPatternNode bindingPatternNode) { diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/createvar/CreateVariableWithTypeCodeAction.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/createvar/CreateVariableWithTypeCodeAction.java index 72ceae34dadd..19f8cb37d5c1 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/createvar/CreateVariableWithTypeCodeAction.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/createvar/CreateVariableWithTypeCodeAction.java @@ -225,11 +225,7 @@ private List getPossibleTypes(TypeSymbol typeSymbol, CodeActionContext c typeStream = typeStream.map(type -> type + "|" + errorTypeStr); } - List typesList = typeStream.collect(Collectors.toList()); - if (unionType != null) { - typesList.add(0, unionType); - } - return typesList; + return Stream.concat(Stream.ofNullable(unionType), typeStream).toList(); } private boolean isInRemoteMethodCallOrResourceAccess(CodeActionContext context) { diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/docs/AddDocumentationCodeAction.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/docs/AddDocumentationCodeAction.java index cecf10624c29..f7056d1d5996 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/docs/AddDocumentationCodeAction.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/docs/AddDocumentationCodeAction.java @@ -60,7 +60,39 @@ public List getSyntaxKinds() { SyntaxKind.ANNOTATION_DECLARATION, SyntaxKind.MODULE_VAR_DECL, SyntaxKind.ENUM_DECLARATION, - SyntaxKind.CONST_DECLARATION); + SyntaxKind.CONST_DECLARATION, + SyntaxKind.UNION_TYPE_DESC, + SyntaxKind.NIL_TYPE_DESC, + SyntaxKind.ARRAY_TYPE_DESC, + SyntaxKind.INT_TYPE_DESC, + SyntaxKind.BYTE_TYPE_DESC, + SyntaxKind.FLOAT_TYPE_DESC, + SyntaxKind.DECIMAL_TYPE_DESC, + SyntaxKind.STRING_TYPE_DESC, + SyntaxKind.BOOLEAN_TYPE_DESC, + SyntaxKind.XML_TYPE_DESC, + SyntaxKind.JSON_TYPE_DESC, + SyntaxKind.HANDLE_TYPE_DESC, + SyntaxKind.ANY_TYPE_DESC, + SyntaxKind.ANYDATA_TYPE_DESC, + SyntaxKind.NEVER_TYPE_DESC, + SyntaxKind.MAP_TYPE_DESC, + SyntaxKind.ERROR_TYPE_DESC, + SyntaxKind.STREAM_TYPE_DESC, + SyntaxKind.TABLE_TYPE_DESC, + SyntaxKind.FUNCTION_TYPE_DESC, + SyntaxKind.TUPLE_TYPE_DESC, + SyntaxKind.READONLY_TYPE_DESC, + SyntaxKind.FUTURE_TYPE_DESC, + SyntaxKind.SINGLETON_TYPE_DESC, + SyntaxKind.INTERSECTION_TYPE_DESC, + SyntaxKind.QUALIFIED_NAME_REFERENCE, + SyntaxKind.SIMPLE_NAME_REFERENCE, + SyntaxKind.TYPEDESC_TYPE_DESC, + SyntaxKind.DISTINCT_TYPE_DESC, + SyntaxKind.OPTIONAL_TYPE_DESC, + SyntaxKind.PARENTHESISED_TYPE_DESC + ); } @Override diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/imports/OptimizeImportsCodeAction.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/imports/OptimizeImportsCodeAction.java index ffd2ddc53914..1151476f2da9 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/imports/OptimizeImportsCodeAction.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/imports/OptimizeImportsCodeAction.java @@ -180,7 +180,7 @@ protected List organizeFileImports(List o.moduleName().stream().map(Token::text).collect(Collectors.joining("."))) .thenComparing(o -> o.prefix().isPresent() ? o.prefix().get().prefix().text() : "")) - .collect(Collectors.toList()); + .toList(); } protected static void buildEditText(StringBuilder editText, ImportDeclarationNode importNode) { diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codelenses/CodeLensUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codelenses/CodeLensUtil.java index 821e1d315848..96366c49dc16 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codelenses/CodeLensUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codelenses/CodeLensUtil.java @@ -32,7 +32,10 @@ * * @since 0.984.0 */ -public class CodeLensUtil { +public final class CodeLensUtil { + + private CodeLensUtil() { + } /** * Compile and get code lenses. diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/command/CommandUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/command/CommandUtil.java index 626918fcf318..02d59cbe876f 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/command/CommandUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/command/CommandUtil.java @@ -33,7 +33,7 @@ /** * Utilities for the command related operations. */ -public class CommandUtil { +public final class CommandUtil { private CommandUtil() { } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/command/docs/DocumentationGenerator.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/command/docs/DocumentationGenerator.java index c9cd06848868..5bc3f59752d1 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/command/docs/DocumentationGenerator.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/command/docs/DocumentationGenerator.java @@ -61,7 +61,7 @@ * * @since 0.985.0 */ -public class DocumentationGenerator { +public final class DocumentationGenerator { private DocumentationGenerator() { } @@ -105,62 +105,47 @@ public static Optional getDocsRange(NonTerminalNode node) { */ public static Optional getDocumentationEditForNode(NonTerminalNode node, SyntaxTree syntaxTree) { - switch (node.kind()) { - case FUNCTION_DEFINITION: - case RESOURCE_ACCESSOR_DEFINITION: - case OBJECT_METHOD_DEFINITION: { - return Optional.of(generateFunctionDocumentation((FunctionDefinitionNode) node, syntaxTree)); - } - case METHOD_DECLARATION: { - return Optional.of(generateMethodDocumentation((MethodDeclarationNode) node, syntaxTree)); - } - case SERVICE_DECLARATION: { - return Optional.of(generateServiceDocumentation((ServiceDeclarationNode) node, syntaxTree)); - } - case TYPE_DEFINITION: { - return Optional.of(generateRecordOrObjectDocumentation((TypeDefinitionNode) node, syntaxTree)); - } - case CLASS_DEFINITION: { - return Optional.of(generateClassDocumentation((ClassDefinitionNode) node, syntaxTree)); - } - case CONST_DECLARATION: { - return Optional.of(generateModuleMemberDocumentation((ConstantDeclarationNode) node, syntaxTree)); - } - case ENUM_DECLARATION: { - return Optional.of(generateModuleMemberDocumentation((EnumDeclarationNode) node, syntaxTree)); - } - case MODULE_VAR_DECL: { - return Optional.of(generateModuleMemberDocumentation((ModuleVariableDeclarationNode) node, syntaxTree)); - } - case ANNOTATION_DECLARATION: { - return Optional.of(generateAnnotationDocumentation((AnnotationDeclarationNode) node, syntaxTree)); - } - default: - break; - } - return Optional.empty(); + return switch (node.kind()) { + case FUNCTION_DEFINITION, + RESOURCE_ACCESSOR_DEFINITION, + OBJECT_METHOD_DEFINITION -> + Optional.of(generateFunctionDocumentation((FunctionDefinitionNode) node, syntaxTree)); + case METHOD_DECLARATION -> + Optional.of(generateMethodDocumentation((MethodDeclarationNode) node, syntaxTree)); + case SERVICE_DECLARATION -> + Optional.of(generateServiceDocumentation((ServiceDeclarationNode) node, syntaxTree)); + case TYPE_DEFINITION -> + Optional.of(generateRecordOrObjectDocumentation((TypeDefinitionNode) node, syntaxTree)); + case CLASS_DEFINITION -> Optional.of(generateClassDocumentation((ClassDefinitionNode) node, syntaxTree)); + case CONST_DECLARATION -> + Optional.of(generateModuleMemberDocumentation((ConstantDeclarationNode) node, syntaxTree)); + case ENUM_DECLARATION -> + Optional.of(generateModuleMemberDocumentation((EnumDeclarationNode) node, syntaxTree)); + case MODULE_VAR_DECL -> + Optional.of(generateModuleMemberDocumentation((ModuleVariableDeclarationNode) node, syntaxTree)); + case ANNOTATION_DECLARATION -> + Optional.of(generateAnnotationDocumentation((AnnotationDeclarationNode) node, syntaxTree)); + default -> Optional.empty(); + }; } public static Optional getDocumentableSymbol(NonTerminalNode node, SemanticModel semanticModel) { - switch (node.kind()) { - case FUNCTION_DEFINITION: - case OBJECT_METHOD_DEFINITION: - case RESOURCE_ACCESSOR_DEFINITION: - case METHOD_DECLARATION: - case SERVICE_DECLARATION: -// case SERVICE_DECLARATION: { -// ServiceDeclarationNode serviceDeclrNode = (ServiceDeclarationNode) node; -// return semanticModel.symbol(fileName, serviceDeclrNode.typeDescriptor().map(s->s.lineRange() -// .startLine()).); -// } - case TYPE_DEFINITION: - case ANNOTATION_DECLARATION: - case CLASS_DEFINITION: - return semanticModel.symbol(node); - default: - break; - } - return Optional.empty(); + return switch (node.kind()) { + case FUNCTION_DEFINITION, + OBJECT_METHOD_DEFINITION, + RESOURCE_ACCESSOR_DEFINITION, + METHOD_DECLARATION, + SERVICE_DECLARATION, + // SERVICE_DECLARATION -> { + // ServiceDeclarationNode serviceDeclrNode = (ServiceDeclarationNode) node; + // yield semanticModel.symbol(fileName, serviceDeclrNode.typeDescriptor().map(s->s.lineRange() + // .startLine()).); + // } + TYPE_DEFINITION, + ANNOTATION_DECLARATION, + CLASS_DEFINITION -> semanticModel.symbol(node); + default -> Optional.empty(); + }; } /** @@ -241,7 +226,7 @@ private static DocAttachmentInfo generateRecordOrObjectDocumentation(TypeDefinit if (metadata != null && !metadata.annotations().isEmpty()) { docStart = PositionUtil.toRange(metadata.annotations().get(0).lineRange()).getStart(); } - io.ballerina.compiler.syntax.tree.Node typeDesc = typeDefNode.typeDescriptor(); + Node typeDesc = typeDefNode.typeDescriptor(); String desc = String.format("Description.%n"); LinkedHashMap parameters = new LinkedHashMap<>(); switch (typeDesc.kind()) { @@ -312,7 +297,7 @@ private static DocAttachmentInfo getFunctionNodeDocumentation(FunctionSignatureN boolean hasDeprecated = false; if (metadata != null && !metadata.annotations().isEmpty()) { for (AnnotationNode annotationNode : metadata.annotations()) { - io.ballerina.compiler.syntax.tree.Node annotReference = annotationNode.annotReference(); + Node annotReference = annotationNode.annotReference(); if (annotReference.kind() == SyntaxKind.SIMPLE_NAME_REFERENCE && "deprecated".equals(((SimpleNameReferenceNode) annotReference).name().text())) { hasDeprecated = true; @@ -325,11 +310,11 @@ private static DocAttachmentInfo getFunctionNodeDocumentation(FunctionSignatureN // Resource function path parameters if (!resourceNodes.isEmpty()) { resourceNodes.forEach(param-> { - if (param instanceof ResourcePathParameterNode) { + if (param instanceof ResourcePathParameterNode resourcePathParameterNode) { Optional paramName = Optional.empty(); if (param.kind() == SyntaxKind.RESOURCE_PATH_SEGMENT_PARAM || param.kind() == SyntaxKind.RESOURCE_PATH_REST_PARAM) { - paramName = Optional.ofNullable(((ResourcePathParameterNode) param).paramName().orElse(null)); + paramName = Optional.ofNullable(resourcePathParameterNode.paramName().orElse(null)); } paramName.ifPresent(token -> parameters.put(token.text(), "parameter description")); } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/command/executors/PullModuleExecutor.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/command/executors/PullModuleExecutor.java index 0a2b1ef6d397..939cafb945cb 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/command/executors/PullModuleExecutor.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/command/executors/PullModuleExecutor.java @@ -51,7 +51,6 @@ import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; -import java.util.stream.Collectors; /** * Command executor for pulling a package from central. @@ -139,7 +138,7 @@ public Object execute(ExecuteCommandContext context) throws LSCommandExecutorExc .map(PullModuleCodeAction::getMissingModuleNameFromDiagnostic) .filter(Optional::isPresent) .map(Optional::get) - .collect(Collectors.toList()) + .toList() ); if (missingModules.isEmpty()) { throw new UserErrorException("Failed to pull modules!"); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/command/executors/RunExecutor.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/command/executors/RunExecutor.java index a7108393d11a..fca5e5719b6b 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/command/executors/RunExecutor.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/command/executors/RunExecutor.java @@ -32,7 +32,7 @@ /** * Command executor for running a Ballerina file. Each project at most has a single instance running at a time. - * See {@link org.ballerinalang.langserver.command.executors.StopExecutor} for stopping a running instance. + * See {@link StopExecutor} for stopping a running instance. * * @since 2201.6.0 */ @@ -66,8 +66,7 @@ public void listenOutputAsync(ExtendedLanguageClient client, Supplier inSupplier, String channel) { - InputStream in = inSupplier.get(); - try { // Can't use resource style due to SpotBugs bug. + try (InputStream in = inSupplier.get()) { byte[] buffer = new byte[1024]; int count; while ((count = in.read(buffer)) >= 0) { @@ -75,12 +74,7 @@ private static void listenOutput(ExtendedLanguageClient client, Supplier list, StringBuffer stringBuffer) { + public void suggestHelper(TrieNode root, List list, StringBuilder stringBuilder) { if (root.isWord) { - list.add(stringBuffer.toString()); + list.add(stringBuilder.toString()); } if (root.children == null || root.children.isEmpty()) { @@ -65,24 +65,24 @@ public void suggestHelper(TrieNode root, List list, StringBuffer stringB } for (TrieNode child : root.children.values()) { - stringBuffer.append(child.character); - suggestHelper(child, list, stringBuffer); - stringBuffer.setLength(stringBuffer.length() - 1); + stringBuilder.append(child.character); + suggestHelper(child, list, stringBuilder); + stringBuilder.setLength(stringBuilder.length() - 1); } } public List suggest(String prefix) { List list = new ArrayList<>(); TrieNode lastNode = root; - StringBuffer stringBuffer = new StringBuffer(); + StringBuilder stringBuilder = new StringBuilder(); for (char character : prefix.toCharArray()) { lastNode = lastNode.children.get(character); if (lastNode == null) { return list; } - stringBuffer.append(character); + stringBuilder.append(character); } - suggestHelper(lastNode, list, stringBuffer); + suggestHelper(lastNode, list, stringBuilder); return list; } /** diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/constants/CommandConstants.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/constants/CommandConstants.java index 721faa9e2714..80aa9a64b643 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/constants/CommandConstants.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/constants/CommandConstants.java @@ -22,7 +22,7 @@ * * @since v0.964.0 */ -public class CommandConstants { +public final class CommandConstants { public static final String UNDEFINED_MODULE = "undefined module"; public static final String UNDEFINED_FUNCTION = "undefined function"; @@ -224,4 +224,7 @@ public class CommandConstants { public static final String ADD_ALL_TO_CONFIG_TOML = "Add all to Config.toml"; public static final String CREATE_CONFIG_TOML_COMMAND = "create.config.toml"; + + private CommandConstants() { + } } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/constants/ContextConstants.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/constants/ContextConstants.java index 4e7d7cb8fba6..f67775f16623 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/constants/ContextConstants.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/constants/ContextConstants.java @@ -18,7 +18,8 @@ /** * Constants for hover functionality. */ -public class ContextConstants { +public final class ContextConstants { + public static final String FUNCTION = "FUNCTION"; public static final String VARIABLE = "VARIABLE"; public static final String ENDPOINT = "ENDPOINT"; @@ -37,4 +38,7 @@ public class ContextConstants { public static final String DOC_RECEIVER = "RECEIVER"; public static final String DOC_RETURN = "RETURN"; public static final String DOC_VARIABLE = "VARIABLE"; + + private ContextConstants() { + } } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/AnnotationUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/AnnotationUtil.java index fed52932dc4d..06afea2db52c 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/AnnotationUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/AnnotationUtil.java @@ -57,7 +57,7 @@ * * @since 2.0.0 */ -public class AnnotationUtil { +public final class AnnotationUtil { private AnnotationUtil() { } @@ -208,8 +208,7 @@ private static String getAnnotationInsertText(@Nonnull String aliasComponent, An annotationStart.append(" ").append(OPEN_BRACE_KEY).append(LINE_SEPARATOR); List insertTexts = new ArrayList<>(); SnippetContext snippetContext = new SnippetContext(); - for (int i = 0; i < requiredFields.size(); i++) { - RecordFieldSymbol field = requiredFields.get(i); + for (RecordFieldSymbol field : requiredFields) { String fieldInsertionText = "\t" + RecordUtil.getRecordFieldCompletionInsertText(field, snippetContext); insertTexts.add(fieldInsertionText); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/CommonKeys.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/CommonKeys.java index 0c6dca265ace..87bc6fb90158 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/CommonKeys.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/CommonKeys.java @@ -20,7 +20,8 @@ * * @since 2.0.0 */ -public class CommonKeys { +public final class CommonKeys { + private CommonKeys() { } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/CommonUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/CommonUtil.java index a0007ecca57a..ef7080b4e0b2 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/CommonUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/CommonUtil.java @@ -86,7 +86,7 @@ /** * Common utils to be reused in language server implementation. */ -public class CommonUtil { +public final class CommonUtil { public static final String MD_LINE_SEPARATOR = " " + System.lineSeparator(); @@ -654,8 +654,7 @@ public static Optional getMatchingNode(Node currentNode, Predicate p */ public static List getFuncArguments(FunctionSymbol symbol, BallerinaCompletionContext ctx) { List params = CommonUtil.getFunctionParameters(symbol, ctx); - return params.stream().map(param -> getFunctionParamaterSyntax(param, ctx).orElse("")) - .collect(Collectors.toList()); + return params.stream().map(param -> getFunctionParamaterSyntax(param, ctx).orElse("")).toList(); } /** diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/DefaultValueGenerationUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/DefaultValueGenerationUtil.java index 992a209148c6..dc2e9e8eab6d 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/DefaultValueGenerationUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/DefaultValueGenerationUtil.java @@ -39,7 +39,10 @@ * * @since 2201.1.1 */ -public class DefaultValueGenerationUtil { +public final class DefaultValueGenerationUtil { + + private DefaultValueGenerationUtil() { + } /** * Get the default value for the given BType. @@ -131,18 +134,12 @@ public static Optional getDefaultValueForTypeDescKind(TypeDescKind typeK * @see #getDefaultValueForType(TypeSymbol) */ public static Optional getDefaultValueForTypeDescKind(TypeSymbol typeSymbol) { - String defaultValue; TypeDescKind typeKind = typeSymbol.typeKind(); - switch (typeKind) { - case SINGLETON: - defaultValue = typeSymbol.signature(); - break; - case TYPE_REFERENCE: - defaultValue = getDefaultValueForTypeDescKind(CommonUtil.getRawType(typeSymbol)).orElse(null); - break; - default: - defaultValue = getDefaultValueForTypeDescKind(typeKind).orElse(null); - } + String defaultValue = switch (typeKind) { + case SINGLETON -> typeSymbol.signature(); + case TYPE_REFERENCE -> getDefaultValueForTypeDescKind(CommonUtil.getRawType(typeSymbol)).orElse(null); + default -> getDefaultValueForTypeDescKind(typeKind).orElse(null); + }; return Optional.ofNullable(defaultValue); } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/FunctionGenerator.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/FunctionGenerator.java index 1106525e7b93..7059b94fa0a5 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/FunctionGenerator.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/FunctionGenerator.java @@ -36,11 +36,14 @@ /** * Function generator utilities. */ -public class FunctionGenerator { +public final class FunctionGenerator { public static final Pattern FULLY_QUALIFIED_MODULE_ID_PATTERN = Pattern.compile("([\\w]+)\\/([\\w.]+):([^:]+):([\\w]+)[\\|]?"); + private FunctionGenerator() { + } + /** * Returns signature of the provided type. * diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/ModuleUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/ModuleUtil.java index 6504d84d4e78..adc66e30fab5 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/ModuleUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/ModuleUtil.java @@ -51,8 +51,11 @@ * * @since 2201.1.1 */ -public class ModuleUtil { - +public final class ModuleUtil { + + private ModuleUtil() { + } + /** * Filter a type in the module by the name. * @@ -137,8 +140,9 @@ public static String getModulePrefix(ImportsAcceptor importsAcceptor, ModuleID c if (importDeclarationNode.prefix().isPresent()) { pkgPrefix = importDeclarationNode.prefix().get().prefix().text(); } - } else if (existingModuleImports.isEmpty() && context instanceof PositionedOperationContext) { - pkgPrefix = NameUtil.getValidatedSymbolName((PositionedOperationContext) context, pkgPrefix); + } else if (existingModuleImports.isEmpty() && + context instanceof PositionedOperationContext positionedOperationContext) { + pkgPrefix = NameUtil.getValidatedSymbolName(positionedOperationContext, pkgPrefix); } CodeActionModuleId codeActionModuleId = CodeActionModuleId.from(orgName, moduleName, pkgPrefix, moduleID.version()); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/NameUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/NameUtil.java index cb6f8f49ad51..a9f2746d24dd 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/NameUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/NameUtil.java @@ -46,7 +46,10 @@ * * @since 2201.1.1 */ -public class NameUtil { +public final class NameUtil { + + private NameUtil() { + } /** * Generates a random name. @@ -87,18 +90,11 @@ public static String generateVariableName(Symbol symbol, TypeSymbol typeSymbol, name = typeSymbol.getName().get(); } else { TypeSymbol rawType = CommonUtil.getRawType(typeSymbol); - switch (rawType.typeKind()) { - case RECORD: - name = "mappingResult"; - break; - case TUPLE: - case ARRAY: - name = "listResult"; - break; - default: - name = rawType.typeKind().getName() + "Result"; - break; - } + name = switch (rawType.typeKind()) { + case RECORD -> "mappingResult"; + case TUPLE, ARRAY -> "listResult"; + default -> rawType.typeKind().getName() + "Result"; + }; } return generateVariableName(1, name, names); } else { @@ -315,7 +311,7 @@ private static String generateVariableName(int suffix, String name, Set // Remove '_' underscores while (newName.contains("_")) { String[] parts = newName.split("_"); - List restParts = Arrays.stream(parts, 1, parts.length).collect(Collectors.toList()); + List restParts = Arrays.stream(parts, 1, parts.length).toList(); newName = parts[0] + StringUtils.capitalize(String.join("", restParts)); } // If empty, revert to original name diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/PathUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/PathUtil.java index c802fa6f8eb2..ce761bbcd6f2 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/PathUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/PathUtil.java @@ -50,8 +50,11 @@ * * @since 2201.1.1 */ -public class PathUtil { - +public final class PathUtil { + + private PathUtil() { + } + /** * Get the path from given string URI. Even if the given URI's scheme is expr or bala, * we convert it to file scheme and provide a valid Path. diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/PositionUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/PositionUtil.java index d4bbc223cae8..ff356ceb611e 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/PositionUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/PositionUtil.java @@ -34,7 +34,10 @@ * * @since 2201.1.1 */ -public class PositionUtil { +public final class PositionUtil { + + private PositionUtil() { + } /** * Convert the syntax-node line range into a lsp4j range. diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/RecordUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/RecordUtil.java index 3b08863182be..6c94a1cacb16 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/RecordUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/RecordUtil.java @@ -46,7 +46,10 @@ * * @since 2201.1.1 */ -public class RecordUtil { +public final class RecordUtil { + + private RecordUtil() { + } /** * Get completion items list for struct fields. @@ -198,7 +201,7 @@ public static Map getRecordFields(RawTypeSymbolWrappe public static List getMandatoryRecordFields(RecordTypeSymbol recordType) { return recordType.fieldDescriptors().values().stream() .filter(field -> !field.hasDefaultValue() && !field.isOptional()) - .collect(Collectors.toList()); + .toList(); } /** @@ -236,7 +239,7 @@ public static List> getRecordTypeSymbols( .map(tSymbol -> { RecordTypeSymbol recordTypeSymbol = (RecordTypeSymbol) CommonUtil.getRawType(tSymbol); return RawTypeSymbolWrapper.from(tSymbol, recordTypeSymbol); - }).collect(Collectors.toList()); + }).toList(); } return Collections.emptyList(); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/SymbolUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/SymbolUtil.java index 991a4258ee3f..d7412cb8319d 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/SymbolUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/SymbolUtil.java @@ -48,7 +48,6 @@ import java.util.Map; import java.util.Optional; import java.util.function.Predicate; -import java.util.stream.Collectors; import javax.annotation.Nonnull; @@ -57,7 +56,7 @@ * * @since 2.0.0 */ -public class SymbolUtil { +public final class SymbolUtil { public static final String SELF_KW = "self"; @@ -220,34 +219,22 @@ public static Optional getTypeDescriptor(Symbol symbol) { if (symbol == null) { return Optional.empty(); } - switch (symbol.kind()) { - case TYPE_DEFINITION: - return Optional.ofNullable(((TypeDefinitionSymbol) symbol).typeDescriptor()); - case VARIABLE: - return Optional.ofNullable(((VariableSymbol) symbol).typeDescriptor()); - case PARAMETER: - return Optional.ofNullable(((ParameterSymbol) symbol).typeDescriptor()); - case ANNOTATION: - return ((AnnotationSymbol) symbol).typeDescriptor(); - case FUNCTION: - case METHOD: - return Optional.ofNullable(((FunctionSymbol) symbol).typeDescriptor()); - case CONSTANT: - case ENUM_MEMBER: - return Optional.ofNullable(((ConstantSymbol) symbol).typeDescriptor()); - case CLASS: - return Optional.of((ClassSymbol) symbol); - case RECORD_FIELD: - return Optional.ofNullable(((RecordFieldSymbol) symbol).typeDescriptor()); - case OBJECT_FIELD: - return Optional.of(((ObjectFieldSymbol) symbol).typeDescriptor()); - case CLASS_FIELD: - return Optional.of(((ClassFieldSymbol) symbol).typeDescriptor()); - case TYPE: - return Optional.of((TypeSymbol) symbol); - default: - return Optional.empty(); - } + return switch (symbol.kind()) { + case TYPE_DEFINITION -> Optional.ofNullable(((TypeDefinitionSymbol) symbol).typeDescriptor()); + case VARIABLE -> Optional.ofNullable(((VariableSymbol) symbol).typeDescriptor()); + case PARAMETER -> Optional.ofNullable(((ParameterSymbol) symbol).typeDescriptor()); + case ANNOTATION -> ((AnnotationSymbol) symbol).typeDescriptor(); + case FUNCTION, + METHOD -> Optional.ofNullable(((FunctionSymbol) symbol).typeDescriptor()); + case CONSTANT, + ENUM_MEMBER -> Optional.ofNullable(((ConstantSymbol) symbol).typeDescriptor()); + case CLASS -> Optional.of((ClassSymbol) symbol); + case RECORD_FIELD -> Optional.ofNullable(((RecordFieldSymbol) symbol).typeDescriptor()); + case OBJECT_FIELD -> Optional.of(((ObjectFieldSymbol) symbol).typeDescriptor()); + case CLASS_FIELD -> Optional.of(((ClassFieldSymbol) symbol).typeDescriptor()); + case TYPE -> Optional.of((TypeSymbol) symbol); + default -> Optional.empty(); + }; } /** @@ -464,7 +451,7 @@ public static List filterSymbolsByPrefix(List symbolList, if (!completionSearchProvider.checkModuleIndexed(moduleId)) { completionSearchProvider.indexModuleAndModuleSymbolNames(moduleId, symbolList.stream() .map(symbol -> symbol.getName().get()) - .collect(Collectors.toList()), new ArrayList<>(symbolMapWithPrefix.keySet())); + .toList(), new ArrayList<>(symbolMapWithPrefix.keySet())); } List stringList = completionSearchProvider.getSuggestions(prefix); @@ -480,6 +467,6 @@ public static List filterSymbolsByPrefix(List symbolList, private static List getFilteredList(Map symbolMap, List stringList) { return symbolMap.entrySet().stream().filter(stringSymbolEntry -> stringList.contains(stringSymbolEntry.getKey().toLowerCase())).map(Map.Entry::getValue) - .collect(Collectors.toList()); + .toList(); } } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/TypeResolverUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/TypeResolverUtil.java index 1ecc7323a4d8..0afa1154739f 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/TypeResolverUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/TypeResolverUtil.java @@ -50,7 +50,10 @@ * * @since 2201.1.1 */ -public class TypeResolverUtil { +public final class TypeResolverUtil { + + private TypeResolverUtil() { + } /** * Given a set of argument nodes and a function or method call expression node, diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/CompilerPluginCompletionExtension.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/CompilerPluginCompletionExtension.java index 3d4f0f8ea05d..1d5c37d5705a 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/CompilerPluginCompletionExtension.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/CompilerPluginCompletionExtension.java @@ -43,12 +43,12 @@ import org.eclipse.lsp4j.Position; import org.eclipse.lsp4j.Range; import org.eclipse.lsp4j.TextDocumentIdentifier; +import org.eclipse.lsp4j.TextEdit; import org.eclipse.lsp4j.jsonrpc.CancelChecker; import java.util.Collections; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; /** * Completion extension implementation for ballerina compiler plugins. @@ -112,14 +112,14 @@ public List execute(CompletionParams inputParams, TextRange textRange = textEdit.range(); Range range = PositionUtil.toRange(textRange.startOffset(), textRange.endOffset(), context.currentDocument().get().textDocument()); - org.eclipse.lsp4j.TextEdit lsp4jTextEdit = new org.eclipse.lsp4j.TextEdit(); + TextEdit lsp4jTextEdit = new TextEdit(); lsp4jTextEdit.setNewText(textEdit.text()); lsp4jTextEdit.setRange(range); return lsp4jTextEdit; - }).collect(Collectors.toList())); + }).toList()); } return item; - }).collect(Collectors.toList()); + }).toList(); } @Override diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/ProviderFactory.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/ProviderFactory.java index c02cf2a2b963..ad5cfa3d1940 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/ProviderFactory.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/ProviderFactory.java @@ -34,6 +34,7 @@ public class ProviderFactory { private static final ProviderFactory INSTANCE = new ProviderFactory(); private ProviderFactory() { + @SuppressWarnings("rawtypes") ServiceLoader providerServices = ServiceLoader.load(BallerinaCompletionProvider.class); for (BallerinaCompletionProvider provider : providerServices) { diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/CompletionItemBuilder.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/CompletionItemBuilder.java index f76dd3b37a35..76eb952f65fb 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/CompletionItemBuilder.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/CompletionItemBuilder.java @@ -19,12 +19,10 @@ protected CompletionItemBuilder() {} * @return {@link CompletionItemKind} */ protected final CompletionItemKind getKind(Symbol symbol) { - switch (symbol.kind()) { - case ENUM: - return CompletionItemKind.Enum; - default: - return CompletionItemKind.Unit; - } + return switch (symbol.kind()) { + case ENUM -> CompletionItemKind.Enum; + default -> CompletionItemKind.Unit; + }; } /** @@ -34,17 +32,11 @@ protected final CompletionItemKind getKind(Symbol symbol) { * @return {@link CompletionItemKind} */ protected final CompletionItemKind getKind(SnippetBlock snippetBlock) { - switch (snippetBlock.kind()) { - case KEYWORD: - return CompletionItemKind.Keyword; - case TYPE: - return CompletionItemKind.TypeParameter; - case VALUE: - return CompletionItemKind.Value; - case SNIPPET: - case STATEMENT: - default: - return CompletionItemKind.Snippet; - } + return switch (snippetBlock.kind()) { + case KEYWORD -> CompletionItemKind.Keyword; + case TYPE -> CompletionItemKind.TypeParameter; + case VALUE -> CompletionItemKind.Value; + default -> CompletionItemKind.Snippet; + }; } } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/ConstantCompletionItemBuilder.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/ConstantCompletionItemBuilder.java index 0a07b19ff75a..7f0cc7e9ec6a 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/ConstantCompletionItemBuilder.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/ConstantCompletionItemBuilder.java @@ -35,7 +35,8 @@ * * @since 1.0 */ -public class ConstantCompletionItemBuilder { +public final class ConstantCompletionItemBuilder { + private ConstantCompletionItemBuilder() { } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/FieldCompletionItemBuilder.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/FieldCompletionItemBuilder.java index 93bcbc9be3ed..6aca3cc31c40 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/FieldCompletionItemBuilder.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/FieldCompletionItemBuilder.java @@ -44,7 +44,8 @@ * * @since 2.0.0 */ -public class FieldCompletionItemBuilder { +public final class FieldCompletionItemBuilder { + private FieldCompletionItemBuilder() { } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/ForeachCompletionItemBuilder.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/ForeachCompletionItemBuilder.java index a48fd206095c..4e9ef475b835 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/ForeachCompletionItemBuilder.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/ForeachCompletionItemBuilder.java @@ -28,7 +28,7 @@ * * @since 2.0.0 */ -public class ForeachCompletionItemBuilder { +public final class ForeachCompletionItemBuilder { private ForeachCompletionItemBuilder() { } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/FunctionCompletionItemBuilder.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/FunctionCompletionItemBuilder.java index b0374f8d1483..db574a784201 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/FunctionCompletionItemBuilder.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/FunctionCompletionItemBuilder.java @@ -162,7 +162,7 @@ public static CompletionItem buildMethod(@Nonnull FunctionSymbol functionSymbol, return item; } - protected static void setMeta(CompletionItem item, FunctionSymbol functionSymbol, BallerinaCompletionContext ctx) { + static void setMeta(CompletionItem item, FunctionSymbol functionSymbol, BallerinaCompletionContext ctx) { item.setInsertTextFormat(InsertTextFormat.Snippet); item.setKind(CompletionItemKind.Function); if (functionSymbol != null) { diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/NamedArgCompletionItemBuilder.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/NamedArgCompletionItemBuilder.java index 244596412258..c85ec6dc4d8d 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/NamedArgCompletionItemBuilder.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/NamedArgCompletionItemBuilder.java @@ -28,7 +28,7 @@ * * @since 2.0.0 */ -public class NamedArgCompletionItemBuilder { +public final class NamedArgCompletionItemBuilder { private NamedArgCompletionItemBuilder() { diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/ResourcePathCompletionItemBuilder.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/ResourcePathCompletionItemBuilder.java index 74ad4eb2354d..4290158b1529 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/ResourcePathCompletionItemBuilder.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/ResourcePathCompletionItemBuilder.java @@ -35,14 +35,16 @@ import java.util.Collections; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; /** * This class is being used to build resource access completion item. * * @since 2201.2.0 */ -public class ResourcePathCompletionItemBuilder { +public final class ResourcePathCompletionItemBuilder { + + private ResourcePathCompletionItemBuilder() { + } /** * Creates and returns completion items given a resource method symbol. @@ -81,7 +83,7 @@ public static List build(ResourceMethodSymbol resourceMethodSymb item.setFilterText(ResourcePathCompletionUtil .getFilterTextForClientResourceAccessAction(resourceMethodSymbol, segments)); return item; - }).collect(Collectors.toList()); + }).toList(); } private static CompletionItem buildCompletionItem(ResourceMethodSymbol resourceMethodSymbol, diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/ResourcePathCompletionUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/ResourcePathCompletionUtil.java index 55b8bf722607..319d0cd33b78 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/ResourcePathCompletionUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/ResourcePathCompletionUtil.java @@ -43,7 +43,10 @@ * * @since 2201.2.0 */ -public class ResourcePathCompletionUtil { +public final class ResourcePathCompletionUtil { + + private ResourcePathCompletionUtil() { + } /** * Check if the cursor is positioned within the method call context of client resource access action node. @@ -204,21 +207,19 @@ public static boolean checkSubtype(TypeSymbol paramType, TypeSymbol exprType, St if (exprType.subtypeOf(paramType)) { return true; } - switch (paramType.typeKind()) { - case UNION: + return switch (paramType.typeKind()) { + case UNION -> { for (TypeSymbol childSymbol : ((UnionTypeSymbol) paramType).memberTypeDescriptors()) { if (checkSubtype(childSymbol, exprType, exprValue)) { - return true; + yield true; } } - return false; - case SINGLETON: - return paramType.subtypeOf(exprType) && exprValue.equals(paramType.signature()); - case TYPE_REFERENCE: - return paramType.subtypeOf(exprType); - default: - return false; - } + yield false; + } + case SINGLETON -> paramType.subtypeOf(exprType) && exprValue.equals(paramType.signature()); + case TYPE_REFERENCE -> paramType.subtypeOf(exprType); + default -> false; + }; } @@ -272,20 +273,18 @@ private static boolean isStringSubtype(TypeSymbol paramType, TypeSymbol stringTy if (stringType.subtypeOf(paramType)) { return true; } - switch (paramType.typeKind()) { - case UNION: + return switch (paramType.typeKind()) { + case UNION -> { for (TypeSymbol childSymbol : ((UnionTypeSymbol) paramType).memberTypeDescriptors()) { if (isStringSubtype(childSymbol, stringType)) { - return true; + yield true; } } - return false; - case SINGLETON: - case TYPE_REFERENCE: - return paramType.subtypeOf(stringType); - default: - return false; - } + yield false; + } + case SINGLETON, TYPE_REFERENCE -> paramType.subtypeOf(stringType); + default -> false; + }; } private static class ResourceAccessPathPart { diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/ServiceTemplateCompletionItemBuilder.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/ServiceTemplateCompletionItemBuilder.java index 5ef994e99f68..8e0bf629db18 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/ServiceTemplateCompletionItemBuilder.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/ServiceTemplateCompletionItemBuilder.java @@ -28,7 +28,7 @@ * * @since 2.0.0 */ -public class ServiceTemplateCompletionItemBuilder { +public final class ServiceTemplateCompletionItemBuilder { private ServiceTemplateCompletionItemBuilder() { diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/SpreadCompletionItemBuilder.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/SpreadCompletionItemBuilder.java index 39e6e25a8e52..78e1d5ee74f8 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/SpreadCompletionItemBuilder.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/SpreadCompletionItemBuilder.java @@ -33,10 +33,13 @@ * * @since 2201.1.1 */ -public class SpreadCompletionItemBuilder { - +public final class SpreadCompletionItemBuilder { + public static final String SPREAD_OPERATOR = "..."; + private SpreadCompletionItemBuilder() { + } + /** * Build the constant {@link CompletionItem}. * diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/StreamTypeInitCompletionItemBuilder.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/StreamTypeInitCompletionItemBuilder.java index 18d4436c253e..89b3efa43673 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/StreamTypeInitCompletionItemBuilder.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/StreamTypeInitCompletionItemBuilder.java @@ -39,7 +39,7 @@ * * @since 2.0.0 */ -public class StreamTypeInitCompletionItemBuilder { +public final class StreamTypeInitCompletionItemBuilder { private StreamTypeInitCompletionItemBuilder() { } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/TypeCompletionItemBuilder.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/TypeCompletionItemBuilder.java index 91c6b8df6de2..20af7d3ddcca 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/TypeCompletionItemBuilder.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/TypeCompletionItemBuilder.java @@ -39,7 +39,8 @@ * * @since 2.0.0 */ -public class TypeCompletionItemBuilder { +public final class TypeCompletionItemBuilder { + private TypeCompletionItemBuilder() { } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/TypeGuardCompletionItemBuilder.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/TypeGuardCompletionItemBuilder.java index 28d7e07a11ba..cde58bc929f9 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/TypeGuardCompletionItemBuilder.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/TypeGuardCompletionItemBuilder.java @@ -28,7 +28,7 @@ * * @since 2.0 */ -public class TypeGuardCompletionItemBuilder { +public final class TypeGuardCompletionItemBuilder { private TypeGuardCompletionItemBuilder() { } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/XMLNSCompletionItemBuilder.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/XMLNSCompletionItemBuilder.java index 18e3be7d6369..b2ecd0081089 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/XMLNSCompletionItemBuilder.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/builder/XMLNSCompletionItemBuilder.java @@ -26,7 +26,8 @@ * * @since 1.0 */ -public class XMLNSCompletionItemBuilder { +public final class XMLNSCompletionItemBuilder { + private XMLNSCompletionItemBuilder() { } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/AbstractCompletionProvider.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/AbstractCompletionProvider.java index 8a98748024a5..c20fb9e5e50b 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/AbstractCompletionProvider.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/AbstractCompletionProvider.java @@ -189,7 +189,7 @@ protected List getCompletionItemList(List sc if (symbol.kind() == FUNCTION || symbol.kind() == METHOD || symbol.kind() == RESOURCE_METHOD) { FunctionSymbol functionSymbol = (FunctionSymbol) symbol; if (functionSymbol.getName().isPresent() && !functionSymbol.getName().get().contains("$")) { - completionItems.addAll(populateBallerinaFunctionCompletionItems((FunctionSymbol) symbol, ctx)); + completionItems.addAll(populateBallerinaFunctionCompletionItems(functionSymbol, ctx)); } } else if (symbol.kind() == SymbolKind.CONSTANT || symbol.kind() == SymbolKind.ENUM_MEMBER) { CompletionItem constantCItem = ConstantCompletionItemBuilder.build((ConstantSymbol) symbol, ctx); @@ -381,7 +381,7 @@ protected List getModuleCompletionItems(BallerinaCompletionCon List pkgNameComps = Arrays.stream(name.split("\\.")) .map(ModuleUtil::escapeModuleName) .map(CommonUtil::escapeReservedKeyword) - .collect(Collectors.toList()); + .toList(); String label = pkg.packageOrg().value().isEmpty() ? String.join(".", pkgNameComps) : CommonUtil.getPackageLabel(pkg); String aliasComponent = pkgNameComps.get(pkgNameComps.size() - 1); @@ -545,7 +545,7 @@ protected List expressionCompletions(BallerinaCompletionContex List filteredList = visibleSymbols.stream() .filter(symbolFilter) .sorted(Comparator.comparing(symbol -> symbol.getName().get())) - .collect(Collectors.toList()); + .toList(); completionItems.addAll(this.getCompletionItemList(filteredList, context)); completionItems.addAll(this.getBasicAndOtherTypeCompletions(context)); this.getAnonFunctionDefSnippet(context).ifPresent(completionItems::add); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/AnnotationAccessExpressionNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/AnnotationAccessExpressionNodeContext.java index 93aebe1a03b7..df0290eb371c 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/AnnotationAccessExpressionNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/AnnotationAccessExpressionNodeContext.java @@ -48,7 +48,6 @@ import java.util.List; import java.util.Optional; import java.util.function.Predicate; -import java.util.stream.Collectors; import static io.ballerina.compiler.api.symbols.SymbolKind.ANNOTATION; @@ -179,12 +178,12 @@ private static List getAnnotationEntries(BallerinaCompletionCo QNameRefCompletionUtil.getModuleContent(ctx, (QualifiedNameReferenceNode) nodeAtCursor, predicate) .stream() .map(symbol -> (AnnotationSymbol) symbol) - .collect(Collectors.toList()); + .toList(); } else { annotationSymbols = ctx.visibleSymbols(ctx.getCursorPosition()).stream() .filter(predicate) .map(symbol -> (AnnotationSymbol) symbol) - .collect(Collectors.toList()); + .toList(); } return annotationSymbols; diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/AnnotationDeclarationNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/AnnotationDeclarationNodeContext.java index 166aed22c2b2..bcd34ced950a 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/AnnotationDeclarationNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/AnnotationDeclarationNodeContext.java @@ -43,7 +43,6 @@ import java.util.List; import java.util.Optional; import java.util.function.Predicate; -import java.util.stream.Collectors; /** * Completion provider for {@link AnnotationDeclarationNode} context. @@ -72,7 +71,7 @@ public List getCompletions(BallerinaCompletionContext context, } else { List filteredSymbols = context.visibleSymbols(context.getCursorPosition()).stream() .filter(predicate) - .collect(Collectors.toList()); + .toList(); completionItemList.addAll(this.getCompletionItemList(filteredSymbols, context)); completionItemList.addAll(this.getModuleCompletionItems(context)); completionItemList.add(new SnippetCompletionItem(context, Snippet.DEF_RECORD_TYPE_DESC.get())); @@ -135,7 +134,7 @@ private boolean isValidTypeDescForAnnotations(TypeDefinitionSymbol typeDefinitio return rawType.typeKind() == TypeDescKind.MAP || rawType.typeKind() == TypeDescKind.RECORD; } - private List getAnnotationAttachmentPoints(BallerinaCompletionContext context, + private List getAnnotationAttachmentPoints(BallerinaCompletionContext context, AnnotationDeclarationNode node) { AttachmentPointContext attachmentPointContext = getAttachmentPointContext(context, node); List itemSnippets = new ArrayList<>(); @@ -166,7 +165,7 @@ private List getAnnotationAttachmentPoints(BallerinaCompletion return itemSnippets.stream() .map(snippet -> new SnippetCompletionItem(context, snippet.get())) - .collect(Collectors.toList()); + .toList(); } private List anyAttachmentPoints() { diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/AnnotationNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/AnnotationNodeContext.java index df508d49e1ba..46fa1b71f307 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/AnnotationNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/AnnotationNodeContext.java @@ -42,7 +42,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; /** * Completion provider for {@link AnnotationNode} context. @@ -95,7 +94,7 @@ private List getCurrentModuleAnnotations(BallerinaCompletionCo .filter(symbol -> symbol.kind() == SymbolKind.ANNOTATION && this.matchingAnnotation((AnnotationSymbol) symbol, annotationNode, attachedNode, ctx)) .map(symbol -> AnnotationUtil.getAnnotationItem((AnnotationSymbol) symbol, ctx)) - .collect(Collectors.toList()); + .toList(); } private List getAnnotationsInModule(BallerinaCompletionContext context, String alias, @@ -118,7 +117,7 @@ private List getAnnotationsInModule(BallerinaCompletionContext .filter(symbol -> symbol.kind() == SymbolKind.ANNOTATION && this.matchingAnnotation((AnnotationSymbol) symbol, annotationNode, attachedNode, context)) .map(symbol -> AnnotationUtil.getAnnotationItem((AnnotationSymbol) symbol, context)) - .collect(Collectors.toList()); + .toList(); } private Node getAttached(AnnotationNode node) { @@ -142,63 +141,45 @@ private boolean matchingAnnotation(AnnotationSymbol symbol, AnnotationNode annot } } - switch (attachedNode.kind()) { - case SERVICE_DECLARATION: - return AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.SERVICE); - case EXPLICIT_ANONYMOUS_FUNCTION_EXPRESSION: - case IMPLICIT_ANONYMOUS_FUNCTION_EXPRESSION: - case FUNCTION_DEFINITION: - return AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.FUNCTION); - case RESOURCE_ACCESSOR_DEFINITION: - case METHOD_DECLARATION: - case OBJECT_METHOD_DEFINITION: - return AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.FUNCTION) - || AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.OBJECT_METHOD); - case LISTENER_DECLARATION: - return AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.LISTENER); - case NAMED_WORKER_DECLARATION: - case START_ACTION: - return AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.WORKER); - case CONST_DECLARATION: - case ENUM_MEMBER: - return AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.CONST); - case ENUM_DECLARATION: - case TYPE_CAST_PARAM: - case TYPE_DEFINITION: - return AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.TYPE); - case CLASS_DEFINITION: - return AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.CLASS); - case RETURN_TYPE_DESCRIPTOR: - return AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.RETURN); - case OBJECT_FIELD: - return AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.FIELD) - || AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.OBJECT_FIELD); - case RECORD_FIELD: - case RECORD_FIELD_WITH_DEFAULT_VALUE: - return AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.FIELD) - || AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.RECORD_FIELD); - case MODULE_VAR_DECL: - case LOCAL_VAR_DECL: - case LET_VAR_DECL: - return AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.VAR); - case EXTERNAL_FUNCTION_BODY: - return AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.EXTERNAL); - case ANNOTATION_DECLARATION: - return AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.ANNOTATION); - case REQUIRED_PARAM: - case DEFAULTABLE_PARAM: - case REST_PARAM: - return AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.PARAMETER); - case OBJECT_CONSTRUCTOR: - return AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.SERVICE) - && ((ObjectConstructorExpressionNode) attachedNode).objectTypeQualifiers() - .stream() - .anyMatch(token -> token.kind() == SyntaxKind.SERVICE_KEYWORD); - case MEMBER_TYPE_DESC: - return AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.FIELD); - default: - return false; - } + return switch (attachedNode.kind()) { + case SERVICE_DECLARATION -> AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.SERVICE); + case EXPLICIT_ANONYMOUS_FUNCTION_EXPRESSION, + IMPLICIT_ANONYMOUS_FUNCTION_EXPRESSION, + FUNCTION_DEFINITION -> AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.FUNCTION); + case RESOURCE_ACCESSOR_DEFINITION, + METHOD_DECLARATION, + OBJECT_METHOD_DEFINITION -> AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.FUNCTION) + || AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.OBJECT_METHOD); + case LISTENER_DECLARATION -> AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.LISTENER); + case NAMED_WORKER_DECLARATION, + START_ACTION -> AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.WORKER); + case CONST_DECLARATION, + ENUM_MEMBER -> AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.CONST); + case ENUM_DECLARATION, + TYPE_CAST_PARAM, + TYPE_DEFINITION -> AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.TYPE); + case CLASS_DEFINITION -> AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.CLASS); + case RETURN_TYPE_DESCRIPTOR -> AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.RETURN); + case OBJECT_FIELD -> AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.FIELD) + || AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.OBJECT_FIELD); + case RECORD_FIELD, + RECORD_FIELD_WITH_DEFAULT_VALUE -> AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.FIELD) + || AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.RECORD_FIELD); + case MODULE_VAR_DECL, + LOCAL_VAR_DECL, + LET_VAR_DECL -> AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.VAR); + case EXTERNAL_FUNCTION_BODY -> AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.EXTERNAL); + case ANNOTATION_DECLARATION -> AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.ANNOTATION); + case REQUIRED_PARAM, + DEFAULTABLE_PARAM, + REST_PARAM -> AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.PARAMETER); + case OBJECT_CONSTRUCTOR -> AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.SERVICE) + && ((ObjectConstructorExpressionNode) attachedNode).objectTypeQualifiers() + .stream() + .anyMatch(token -> token.kind() == SyntaxKind.SERVICE_KEYWORD); + case MEMBER_TYPE_DESC -> AnnotationUtil.hasAttachment(symbol, AnnotationAttachPoint.FIELD); + default -> false; + }; } @Override diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ArrayTypeDescriptorNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ArrayTypeDescriptorNodeContext.java index 2e314fa5f068..21b17a108013 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ArrayTypeDescriptorNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ArrayTypeDescriptorNodeContext.java @@ -33,7 +33,6 @@ import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; -import java.util.stream.Collectors; /** * Completion provider for {@link ArrayTypeDescriptorNode} context. @@ -65,7 +64,7 @@ public List getCompletions(BallerinaCompletionContext context, } else { List constants = visibleSymbols.stream() .filter(constantFilter()) - .collect(Collectors.toList()); + .toList(); completionItems.addAll(this.getModuleCompletionItems(context)); completionItems.addAll(this.getCompletionItemList(constants, context)); } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/BlockNodeContextProvider.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/BlockNodeContextProvider.java index b0b39da85f4c..11709cf2760d 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/BlockNodeContextProvider.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/BlockNodeContextProvider.java @@ -46,7 +46,6 @@ import java.util.List; import java.util.Optional; import java.util.function.Predicate; -import java.util.stream.Collectors; /** * Generic completion resolver for the Block Nodes. @@ -222,7 +221,7 @@ protected List getSymbolCompletions(BallerinaCompletionContext symbolFilter = symbolFilter.or(symbol -> symbol.kind() == SymbolKind.FUNCTION); List filteredList = visibleSymbols.stream() .filter(symbolFilter) - .collect(Collectors.toList()); + .toList(); return this.getCompletionItemList(filteredList, context); } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ClientResourceAccessActionNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ClientResourceAccessActionNodeContext.java index 0b6fd172fbd4..9c721790c2ef 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ClientResourceAccessActionNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ClientResourceAccessActionNodeContext.java @@ -59,7 +59,6 @@ import java.util.Iterator; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; import java.util.stream.StreamSupport; /** @@ -120,14 +119,13 @@ public List getCompletions(BallerinaCompletionContext context, completionItems.addAll(this.getNamedArgExpressionCompletionItems(context, node)); } } else { - List clientActions = this.getClientActions(expressionType.get()); + List clientActions = this.getClientActions(expressionType.get()); List resourceMethodSymbols = clientActions.stream() .filter(symbol -> symbol.kind() == SymbolKind.RESOURCE_METHOD) - .map(symbol -> (ResourceMethodSymbol) symbol).collect(Collectors.toList()); + .map(symbol -> (ResourceMethodSymbol) symbol).toList(); List remoteMethods = clientActions.stream() .filter(symbol -> symbol.kind() == SymbolKind.METHOD - && ((MethodSymbol) symbol).qualifiers().contains(Qualifier.REMOTE)) - .map(symbol -> (MethodSymbol) symbol).collect(Collectors.toList()); + && symbol.qualifiers().contains(Qualifier.REMOTE)).toList(); if (node.slashToken().isMissing()) { completionItems.addAll(this.getCompletionItemList(remoteMethods, context)); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/CollectClauseNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/CollectClauseNodeContext.java index a3493abe9aa6..c080a44f82db 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/CollectClauseNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/CollectClauseNodeContext.java @@ -30,7 +30,6 @@ import java.util.ArrayList; import java.util.List; -import java.util.stream.Collectors; /** * Completion provider for {@link CollectClauseNode} context. @@ -62,7 +61,7 @@ public List getCompletions(BallerinaCompletionContext context, .filter(symbol -> symbol.getName().isPresent() && !symbol.getName().get().contains("$")) .filter(symbol -> completionItems .addAll(populateBallerinaFunctionCompletionItems(symbol, context))) - .collect(Collectors.toList()); + .toList(); } this.sort(context, node, completionItems); return completionItems; diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ConstantDeclarationNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ConstantDeclarationNodeContext.java index 8e87d4f43c51..965e4eaea76d 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ConstantDeclarationNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ConstantDeclarationNodeContext.java @@ -36,7 +36,6 @@ import java.util.List; import java.util.Optional; import java.util.function.Predicate; -import java.util.stream.Collectors; /** * Completion provider for {@link ModulePartNode} context. @@ -119,7 +118,7 @@ protected List initializerContextCompletions(BallerinaCompleti } else { constants = context.visibleSymbols(context.getCursorPosition()).stream() .filter(predicate) - .collect(Collectors.toList()); + .toList(); completionItems.addAll(this.getModuleCompletionItems(context)); completionItems.add(new SnippetCompletionItem(context, Snippet.KW_TRUE.get())); completionItems.add(new SnippetCompletionItem(context, Snippet.KW_FALSE.get())); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/DistinctTypeDescriptorNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/DistinctTypeDescriptorNodeContext.java index 65834fb91c6f..b5f14e1f3c75 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/DistinctTypeDescriptorNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/DistinctTypeDescriptorNodeContext.java @@ -36,7 +36,6 @@ import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; -import java.util.stream.Collectors; /** * Completion provider for {@link DistinctTypeDescriptorNode} context. @@ -78,7 +77,7 @@ public List getCompletions(BallerinaCompletionContext context, completionItems.add(new SnippetCompletionItem(context, Snippet.DEF_OBJECT_TYPE_DESC_SNIPPET.get())); List filteredSymbols = context.visibleSymbols(context.getCursorPosition()).stream() .filter(predicate) - .collect(Collectors.toList()); + .toList(); completionItems.addAll(this.getCompletionItemList(filteredSymbols, context)); } this.sort(context, node, completionItems); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ErrorConstructorExpressionNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ErrorConstructorExpressionNodeContext.java index 871e55ec620a..8739a46f2dc7 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ErrorConstructorExpressionNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ErrorConstructorExpressionNodeContext.java @@ -51,7 +51,6 @@ import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.stream.Collectors; /** * Completion provider for {@link ErrorConstructorExpressionNode} context. @@ -134,7 +133,7 @@ private List getErrorTypeRefCompletions(BallerinaCompletionCon List errorTypes = ctx.visibleSymbols(ctx.getCursorPosition()).stream() .filter(SymbolUtil.isOfType(TypeDescKind.ERROR) .and(symbol -> !symbol.getName().orElse("").equals(Names.ERROR.getValue()))) - .collect(Collectors.toList()); + .toList(); List completionItems = this.getCompletionItemList(errorTypes, ctx); completionItems.addAll(this.getModuleCompletionItems(ctx)); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ErrorMatchPatternNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ErrorMatchPatternNodeContext.java index 394103915170..a8bba53b0c42 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ErrorMatchPatternNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ErrorMatchPatternNodeContext.java @@ -32,7 +32,6 @@ import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; -import java.util.stream.Collectors; /** * Completion provider for {@link ErrorMatchPatternNode} context. @@ -67,7 +66,7 @@ public List getCompletions(BallerinaCompletionContext context, List visibleSymbols = context.visibleSymbols(context.getCursorPosition()); errorTypes = visibleSymbols.stream() .filter(this.errorTypeFilter()) - .collect(Collectors.toList()); + .toList(); completionItems.addAll(this.getModuleCompletionItems(context)); } completionItems.addAll(this.getCompletionItemList(errorTypes, context)); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ExplicitNewExpressionNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ExplicitNewExpressionNodeContext.java index a29673e0ff01..2b110541484a 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ExplicitNewExpressionNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ExplicitNewExpressionNodeContext.java @@ -43,7 +43,6 @@ import java.util.List; import java.util.Optional; import java.util.function.Predicate; -import java.util.stream.Collectors; /** * Completion provider for {@link ExplicitNewExpressionNode} context. @@ -143,7 +142,7 @@ private List getCompletionsWithinArgs(BallerinaCompletionConte } List completionItems = new ArrayList<>(); if (isNotInNamedArgOnlyContext(ctx, - node.parenthesizedArgList().arguments().stream().collect(Collectors.toList()))) { + node.parenthesizedArgList().arguments().stream().toList())) { completionItems.addAll(this.expressionCompletions(ctx)); } completionItems.addAll(getNamedArgExpressionCompletionItems(ctx, node)); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/FieldAccessContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/FieldAccessContext.java index a73883d9edb7..a231ae323074 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/FieldAccessContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/FieldAccessContext.java @@ -47,7 +47,6 @@ import java.util.List; import java.util.Optional; import java.util.function.Predicate; -import java.util.stream.Collectors; /** * Generic Completion provider for field access providers. @@ -154,7 +153,7 @@ private List getXmlAttributeAccessCompletions(BallerinaComplet */ List xmlNamespaces = context.visibleSymbols(context.getCursorPosition()).stream() .filter(symbol -> symbol.kind() == SymbolKind.XMLNS) - .collect(Collectors.toList()); + .toList(); completionItems.addAll(this.getCompletionItemList(xmlNamespaces, context)); completionItems.addAll(this.getModuleCompletionItems(context)); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/FlushActionNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/FlushActionNodeContext.java index 8f26aaca6232..5d55e8bb9833 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/FlushActionNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/FlushActionNodeContext.java @@ -28,7 +28,6 @@ import java.util.ArrayList; import java.util.List; -import java.util.stream.Collectors; /** * Completion Provider for {@link FlushActionNode} context. @@ -48,7 +47,7 @@ public List getCompletions(BallerinaCompletionContext context, List visibleSymbols = context.visibleSymbols(context.getCursorPosition()); List filteredWorkers = visibleSymbols.stream() .filter(symbol -> symbol.kind() == SymbolKind.WORKER) - .collect(Collectors.toList()); + .toList(); List completionItems = new ArrayList<>(this.getCompletionItemList(filteredWorkers, context)); completionItems.add(new SnippetCompletionItem(context, Snippet.KW_FUNCTION.get())); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/FunctionCallExpressionNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/FunctionCallExpressionNodeContext.java index 0a0d4202e1f6..a9c732987788 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/FunctionCallExpressionNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/FunctionCallExpressionNodeContext.java @@ -31,7 +31,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; /** * Completion Provider for {@link FunctionCallExpressionNode} context. @@ -54,7 +53,7 @@ public List getCompletions(BallerinaCompletionContext ctx, Fun completionItems.addAll(this.getCompletionItemList(QNameRefCompletionUtil .getExpressionContextEntries(ctx, qNameRef), ctx)); } else { - if (this.isNotInNamedArgOnlyContext(ctx, node.arguments().stream().collect(Collectors.toList()))) { + if (this.isNotInNamedArgOnlyContext(ctx, node.arguments().stream().toList())) { completionItems.addAll(this.actionKWCompletions(ctx)); completionItems.addAll(this.expressionCompletions(ctx)); } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/FunctionSignatureNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/FunctionSignatureNodeContext.java index fd9e6bbeee79..6c2fa9b73a0f 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/FunctionSignatureNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/FunctionSignatureNodeContext.java @@ -18,6 +18,7 @@ import io.ballerina.compiler.syntax.tree.FunctionSignatureNode; import io.ballerina.compiler.syntax.tree.NonTerminalNode; import io.ballerina.compiler.syntax.tree.QualifiedNameReferenceNode; +import io.ballerina.compiler.syntax.tree.ReturnTypeDescriptorNode; import io.ballerina.compiler.syntax.tree.SyntaxKind; import io.ballerina.compiler.syntax.tree.Token; import org.ballerinalang.annotation.JavaSPIService; @@ -33,6 +34,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.Optional; /** * Completion provider for {@link FunctionSignatureNode} context. @@ -52,7 +54,7 @@ public List getCompletions(BallerinaCompletionContext context, List completionItems = new ArrayList<>(); if (withinReturnTypeDescContext(context, node)) { - var returnTypeDesc = node.returnTypeDesc(); + Optional returnTypeDesc = node.returnTypeDesc(); if (returnTypeDesc.isEmpty() || returnTypeDesc.get().returnsKeyword().isMissing()) { /* Covers the following cases. diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ImplicitAnonymousFunctionExpressionNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ImplicitAnonymousFunctionExpressionNodeContext.java index fb0920e6418a..abb0d51a8148 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ImplicitAnonymousFunctionExpressionNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ImplicitAnonymousFunctionExpressionNodeContext.java @@ -26,7 +26,7 @@ import java.util.List; /** - * Completion provider for {@link io.ballerina.compiler.syntax.tree.ImplicitAnonymousFunctionExpressionNode} context. + * Completion provider for {@link ImplicitAnonymousFunctionExpressionNode} context. * * @since 2201.1.1 */ diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ImplicitNewExpressionNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ImplicitNewExpressionNodeContext.java index 8b690d94c16c..ef7057c4db3e 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ImplicitNewExpressionNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ImplicitNewExpressionNodeContext.java @@ -24,6 +24,7 @@ import io.ballerina.compiler.api.symbols.TypeDefinitionSymbol; import io.ballerina.compiler.api.symbols.TypeDescKind; import io.ballerina.compiler.api.symbols.TypeSymbol; +import io.ballerina.compiler.syntax.tree.FunctionArgumentNode; import io.ballerina.compiler.syntax.tree.ImplicitNewExpressionNode; import io.ballerina.compiler.syntax.tree.Node; import io.ballerina.compiler.syntax.tree.NonTerminalNode; @@ -43,7 +44,6 @@ import java.util.List; import java.util.Optional; import java.util.function.Predicate; -import java.util.stream.Collectors; /** * Completion provider for {@link ImplicitNewExpressionNode} context. @@ -114,8 +114,8 @@ private List getCompletionsWithinArgs(BallerinaCompletionConte return this.getCompletionItemList(QNameRefCompletionUtil.getExpressionContextEntries(ctx, qNameRef), ctx); } List completionItems = new ArrayList<>(); - List arguments = node.parenthesizedArgList().isPresent() ? - node.parenthesizedArgList().get().arguments().stream().collect(Collectors.toList()) + List arguments = node.parenthesizedArgList().isPresent() ? + node.parenthesizedArgList().get().arguments().stream().toList() : Collections.emptyList(); if (isNotInNamedArgOnlyContext(ctx, arguments)) { completionItems.addAll(this.expressionCompletions(ctx)); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ImportDeclarationNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ImportDeclarationNodeContext.java index a08b04977ace..2032609a213a 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ImportDeclarationNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ImportDeclarationNodeContext.java @@ -90,7 +90,7 @@ public List getCompletions(BallerinaCompletionContext ctx, Imp */ List moduleName = node.moduleName().stream() .filter(token -> !token.isMissing()) - .collect(Collectors.toList()); + .toList(); ArrayList completionItems = new ArrayList<>(); ContextScope contextScope; @@ -230,7 +230,7 @@ private ArrayList orgNameContextCompletions(BallerinaCompletio List pkgNameComps = Arrays.stream(pkgName.split("\\.")) .map(ModuleUtil::escapeModuleName) .map(CommonUtil::escapeReservedKeyword) - .collect(Collectors.toList()); + .toList(); String label = pkg.packageOrg().value().isEmpty() ? String.join(".", pkgNameComps) : CommonUtil.getPackageLabel(pkg); String insertText = orgName.isEmpty() ? "" : orgName + Names.ORG_NAME_SEPARATOR.getValue(); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/IncludedRecordParameterNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/IncludedRecordParameterNodeContext.java index 7474739eda4d..eaff1eded06b 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/IncludedRecordParameterNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/IncludedRecordParameterNodeContext.java @@ -36,7 +36,6 @@ import java.util.Arrays; import java.util.List; import java.util.function.Predicate; -import java.util.stream.Collectors; /** * Completion provider for {@link IncludedRecordParameterNode} context. @@ -68,7 +67,7 @@ public List getCompletions(BallerinaCompletionContext ctx, Inc .filter(symbol -> symbol.kind() == SymbolKind.TYPE_DEFINITION && CommonUtil.getRawType(((TypeDefinitionSymbol) symbol).typeDescriptor()) .typeKind() == TypeDescKind.RECORD) - .collect(Collectors.toList()); + .toList(); // Add the keywords and snippets related to record type descriptor completionItems.addAll(Arrays.asList( new SnippetCompletionItem(ctx, Snippet.KW_RECORD.get()), diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/InvocationNodeContextProvider.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/InvocationNodeContextProvider.java index 1931ec9dd7d2..0b245a219c06 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/InvocationNodeContextProvider.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/InvocationNodeContextProvider.java @@ -209,7 +209,8 @@ private boolean isValidNamedArgContext(BallerinaCompletionContext context, return true; } - protected boolean isNotInNamedArgOnlyContext(BallerinaCompletionContext context, List arguments) { + protected boolean isNotInNamedArgOnlyContext(BallerinaCompletionContext context, + List arguments) { int cursorPosition = context.getCursorPositionInTree(); for (Node child : arguments) { TextRange textRange = child.textRange(); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/KeySpecifierNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/KeySpecifierNodeContext.java index 993c74622483..2bc09e7ac036 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/KeySpecifierNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/KeySpecifierNodeContext.java @@ -113,7 +113,7 @@ private List getKeyCompletionItems(BallerinaCompletionContext .map(Map.Entry::getValue) .filter(recordFieldSymbol -> recordFieldSymbol.getName().isPresent()) .filter(recordFieldSymbol -> SyntaxInfo.isIdentifier(recordFieldSymbol.getName().get())) - .collect(Collectors.toList()); + .toList(); completionItems.addAll(this.getCompletionItemList(commonFields, context)); return completionItems; diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ListConstructorExpressionNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ListConstructorExpressionNodeContext.java index bf20faca5dfb..3fff6651ba77 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ListConstructorExpressionNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ListConstructorExpressionNodeContext.java @@ -45,7 +45,6 @@ import java.util.Collections; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; /** * Completion provider for {@link ListConstructorExpressionNode} context. @@ -79,7 +78,7 @@ public List getCompletions(BallerinaCompletionContext context, return completionItems; } - private List spreadOperatorCompletions(BallerinaCompletionContext context) { + private List spreadOperatorCompletions(BallerinaCompletionContext context) { Optional semanticModel = context.currentSemanticModel(); Optional document = context.currentDocument(); if (semanticModel.isEmpty() || document.isEmpty()) { @@ -124,7 +123,7 @@ private List spreadOperatorCompletions(BallerinaCompletionCont CompletionItem completionItem = SpreadCompletionItemBuilder.build(symbol, typeName, context); return new SpreadCompletionItem(context, completionItem, symbol); - }).collect(Collectors.toList()); + }).toList(); } @Override diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ListenerDeclarationNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ListenerDeclarationNodeContext.java index e27e19d7a516..a7d2077367e2 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ListenerDeclarationNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ListenerDeclarationNodeContext.java @@ -52,7 +52,6 @@ import java.util.List; import java.util.Objects; import java.util.Optional; -import java.util.stream.Collectors; import java.util.stream.Stream; import static io.ballerina.compiler.api.symbols.SymbolKind.FUNCTION; @@ -199,7 +198,7 @@ private List listenersAndPackagesItems(BallerinaCompletionCont List visibleSymbols = context.visibleSymbols(context.getCursorPosition()); List listeners = visibleSymbols.stream() .filter(SymbolUtil::isListener) - .collect(Collectors.toList()); + .toList(); completionItems.addAll(this.getCompletionItemList(listeners, context)); return completionItems; @@ -221,7 +220,7 @@ private List listenersInModule(BallerinaCompletionContext cont Stream classesAndTypeDefs = Stream.concat(module.classes().stream(), module.typeDefinitions().stream()); List listeners = classesAndTypeDefs .filter(SymbolUtil::isListener) - .collect(Collectors.toList()); + .toList(); completionItems.addAll(this.getCompletionItemList(listeners, context)); return completionItems; @@ -330,7 +329,7 @@ protected List expressionCompletions(BallerinaCompletionContex Optional objectTypeDesc = getListenerTypeDesc(context, listenerNode); List filteredList = visibleSymbols.stream() .filter(symbol -> symbol.kind() == VARIABLE || symbol.kind() == FUNCTION) - .collect(Collectors.toList()); + .toList(); completionItems.addAll(this.getCompletionItemList(filteredList, context)); completionItems.addAll(this.getModuleCompletionItems(context)); objectTypeDesc.ifPresent(tDesc -> completionItems.add(this.getImplicitNewCItemForClass(tDesc, context))); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/MappingConstructorExpressionNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/MappingConstructorExpressionNodeContext.java index 0ff4a5b55122..3ac7ca7a3d41 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/MappingConstructorExpressionNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/MappingConstructorExpressionNodeContext.java @@ -42,7 +42,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; /** * Completion provider for {@link MappingConstructorExpressionNode} context. @@ -153,7 +152,7 @@ private List getComputedNameCompletions(BallerinaCompletionCon List filteredList = visibleSymbols.stream() .filter(symbol -> symbol instanceof VariableSymbol || symbol.kind() == SymbolKind.FUNCTION) - .collect(Collectors.toList()); + .toList(); List completionItems = this.getCompletionItemList(filteredList, context); completionItems.addAll(this.getModuleCompletionItems(context)); @@ -166,7 +165,7 @@ protected List getFields(MappingConstructorExpressionNode node) { .filter(field -> !field.isMissing() && field.kind() == SyntaxKind.SPECIFIC_FIELD && ((SpecificFieldNode) field).fieldName().kind() == SyntaxKind.IDENTIFIER_TOKEN) .map(field -> ((IdentifierToken) ((SpecificFieldNode) field).fieldName()).text()) - .collect(Collectors.toList()); + .toList(); } private enum Scope { diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/MappingContextProvider.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/MappingContextProvider.java index dce1a52dda3e..cc22daa05855 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/MappingContextProvider.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/MappingContextProvider.java @@ -56,7 +56,6 @@ import java.util.Map; import java.util.Optional; import java.util.function.Predicate; -import java.util.stream.Collectors; import static io.ballerina.compiler.api.symbols.SymbolKind.FUNCTION; @@ -129,7 +128,7 @@ protected List getVariableCompletionsForFields(BallerinaComple && recFields.get(symbolName.get()).typeDescriptor().typeKind() == typeDescriptor.get().typeKind(); })) - .collect(Collectors.toList()); + .toList(); return this.getCompletionItemList(visibleSymbols, ctx); } @@ -204,7 +203,7 @@ protected List getFieldCompletionItems(BallerinaCompletionCont .filter(this.getVariableFilter()) .filter(varSymbol -> varSymbol.getName().isPresent()) .filter(varSymbol -> !existingFields.contains(varSymbol.getName().get())) - .collect(Collectors.toList()); + .toList(); completionItems.addAll(this.getCompletionItemList(variables, context)); //Spread field can only be used with in a mapping constructor and the fields should be empty if (existingFields.isEmpty() && evalNode.kind() == SyntaxKind.MAPPING_CONSTRUCTOR) { @@ -251,7 +250,7 @@ private List getSpreadFieldCompletionItemsForMap(MappingConstr // For nested maps, we have to treat specially return resolvedType.get().typeKind() == TypeDescKind.MAP && mapTypeSymbol.subtypeOf(resolvedType.get()); - })).collect(Collectors.toList()); + })).toList(); return getSpreadFieldCompletionItemList(visibleSymbols, context); } @@ -268,7 +267,7 @@ private List getSpreadFieldCompletionItemsForRecordFields(Ball Predicate symbolFilter = this.getVariableFilter().or(symbol -> (symbol.kind() == FUNCTION)); List filteredSymbols = context.visibleSymbols(context.getCursorPosition()).stream() .filter(symbolFilter.and(symbol -> isSpreadable(symbol, validFields))) - .collect(Collectors.toList()); + .toList(); return this.getSpreadFieldCompletionItemList(filteredSymbols, context); } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/MappingMatchPatternNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/MappingMatchPatternNodeContext.java index 046870f13e50..684cf12709d7 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/MappingMatchPatternNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/MappingMatchPatternNodeContext.java @@ -29,7 +29,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; /** * Completion provider for {@link MappingMatchPatternNode} context. @@ -67,7 +66,7 @@ protected List getFields(MappingMatchPatternNode node) { .filter(field -> !field.isMissing() && field.kind() == SyntaxKind.FIELD_MATCH_PATTERN && ((FieldMatchPatternNode) field).fieldNameNode().kind() == SyntaxKind.IDENTIFIER_TOKEN) .map(field -> ((FieldMatchPatternNode) field).fieldNameNode().text()) - .collect(Collectors.toList()); + .toList(); } @Override diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/MatchStatementContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/MatchStatementContext.java index 62ed242b7606..0acc7c1002d4 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/MatchStatementContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/MatchStatementContext.java @@ -28,7 +28,6 @@ import java.util.Arrays; import java.util.List; import java.util.function.Predicate; -import java.util.stream.Collectors; /** * Generic Completion provider for match statement related contexts such as match node and pattern clauses. @@ -51,7 +50,7 @@ protected List getPatternClauseCompletions(BallerinaCompletion snippets.forEach(snippet -> completionItems.add(new SnippetCompletionItem(context, snippet.get()))); List filteredConstants = visibleSymbols.stream() .filter(this.constantFilter()) - .collect(Collectors.toList()); + .toList(); completionItems.addAll(this.getCompletionItemList(filteredConstants, context)); completionItems.addAll(this.getModuleCompletionItems(context)); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ModuleXMLNamespaceDeclarationNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ModuleXMLNamespaceDeclarationNodeContext.java index f70fc7793a38..456f7b6dd994 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ModuleXMLNamespaceDeclarationNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ModuleXMLNamespaceDeclarationNodeContext.java @@ -36,7 +36,6 @@ import java.util.List; import java.util.Optional; import java.util.function.Predicate; -import java.util.stream.Collectors; /** * Completion provider for {@link ModuleXMLNamespaceDeclarationNode} context. @@ -68,7 +67,7 @@ public List getCompletions(BallerinaCompletionContext context, } else { List constants = context.visibleSymbols(context.getCursorPosition()).stream() .filter(predicate) - .collect(Collectors.toList()); + .toList(); completionItems.addAll(this.getCompletionItemList(constants, context)); completionItems.addAll(this.getModuleCompletionItems(context)); } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ObjectConstructorExpressionNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ObjectConstructorExpressionNodeContext.java index bc3507f2044a..d60fca68c64e 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ObjectConstructorExpressionNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ObjectConstructorExpressionNodeContext.java @@ -38,7 +38,6 @@ import java.util.Arrays; import java.util.List; import java.util.function.Predicate; -import java.util.stream.Collectors; /** * Completion provider for {@link ObjectConstructorExpressionNode} context. @@ -110,7 +109,7 @@ private List getTypeReferenceCompletions(BallerinaCompletionCo List visibleSymbols = ctx.visibleSymbols(ctx.getCursorPosition()); List objectEntries = visibleSymbols.stream() .filter(predicate) - .collect(Collectors.toList()); + .toList(); List completionItems = this.getCompletionItemList(objectEntries, ctx); completionItems.addAll(this.getModuleCompletionItems(ctx)); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ObjectFieldNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ObjectFieldNodeContext.java index 73b82b157796..93deacabe011 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ObjectFieldNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ObjectFieldNodeContext.java @@ -37,7 +37,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; /** * Completion provider for {@link ObjectFieldNode} context. @@ -88,7 +87,7 @@ private List getExpressionContextCompletions(BallerinaCompleti // Specifically add the class fields as the completion items List classFields = ctx.visibleSymbols(ctx.getCursorPosition()).stream() .filter(symbol -> symbol.kind() == SymbolKind.CLASS_FIELD) - .collect(Collectors.toList()); + .toList(); completionItems.addAll(this.getCompletionItemList(classFields, ctx)); Optional contextType = ctx.getContextType(); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/OnFailClauseNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/OnFailClauseNodeContext.java index c978c1b81141..754c826fb676 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/OnFailClauseNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/OnFailClauseNodeContext.java @@ -35,7 +35,6 @@ import java.util.Collections; import java.util.List; import java.util.function.Predicate; -import java.util.stream.Collectors; /** * Completion provider for {@link OnFailClauseNode} context. @@ -69,7 +68,7 @@ public List getCompletions(BallerinaCompletionContext context, List visibleSymbols = context.visibleSymbols(context.getCursorPosition()); List errEntries = visibleSymbols.stream() .filter(errorPredicate) - .collect(Collectors.toList()); + .toList(); completionItems.addAll(this.getCompletionItemList(errEntries, context)); // Add 'var' completion item diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/PanicStatementNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/PanicStatementNodeContext.java index 49e6f872f8df..503882a60200 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/PanicStatementNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/PanicStatementNodeContext.java @@ -30,7 +30,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; /** * Completion provider for {@link PanicStatementNode} context. @@ -51,7 +50,7 @@ public List getCompletions(BallerinaCompletionContext context, List visibleSymbols = context.visibleSymbols(context.getCursorPosition()); List filteredList = visibleSymbols.stream() .filter(SymbolUtil::isError) - .collect(Collectors.toList()); + .toList(); completionItems.addAll(this.getCompletionItemList(filteredList, context)); completionItems.addAll(this.expressionCompletions(context)); this.sort(context, node, completionItems); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ReceiveActionNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ReceiveActionNodeContext.java index f16f364dc813..3d6db9ef7e36 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ReceiveActionNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ReceiveActionNodeContext.java @@ -27,7 +27,6 @@ import org.ballerinalang.langserver.completions.util.Snippet; import java.util.List; -import java.util.stream.Collectors; /** * Completion provider for {@link ReceiveActionNode}. @@ -47,7 +46,7 @@ public List getCompletions(BallerinaCompletionContext context, List visibleSymbols = context.visibleSymbols(context.getCursorPosition()); List filteredWorkers = visibleSymbols.stream() .filter(symbol -> symbol.kind() == SymbolKind.WORKER) - .collect(Collectors.toList()); + .toList(); List completionItems = this.getCompletionItemList(filteredWorkers, context); completionItems.add(new SnippetCompletionItem(context, Snippet.KW_FUNCTION.get())); this.sort(context, node, completionItems); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/RemoteMethodCallActionNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/RemoteMethodCallActionNodeContext.java index 86050aa93c44..d087019c7ab0 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/RemoteMethodCallActionNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/RemoteMethodCallActionNodeContext.java @@ -17,6 +17,7 @@ import io.ballerina.compiler.api.SemanticModel; import io.ballerina.compiler.api.symbols.FunctionSymbol; +import io.ballerina.compiler.api.symbols.MethodSymbol; import io.ballerina.compiler.api.symbols.Symbol; import io.ballerina.compiler.api.symbols.SymbolKind; import io.ballerina.compiler.api.symbols.TypeSymbol; @@ -36,7 +37,6 @@ import java.util.Collections; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; /** * Handles the completions for the {@link RemoteMethodCallActionNode}. @@ -77,7 +77,7 @@ public List getCompletions(BallerinaCompletionContext context, Covers the following case where a is a client object and we suggest the remote actions (1) a -> g */ - List clientActions = this.getClientActions(expressionType.get()); + List clientActions = this.getClientActions(expressionType.get()); completionItems.addAll(this.getCompletionItemList(clientActions, context)); } else if (TypeResolverUtil.isInMethodCallParameterContext(node, context.getCursorPositionInTree())) { /* @@ -91,7 +91,7 @@ public List getCompletions(BallerinaCompletionContext context, List items = this.getCompletionItemList(exprEntries, context); completionItems.addAll(items); } else { - if (isNotInNamedArgOnlyContext(context, node.arguments().stream().collect(Collectors.toList()))) { + if (isNotInNamedArgOnlyContext(context, node.arguments().stream().toList())) { completionItems.addAll(this.actionKWCompletions(context)); completionItems.addAll(this.expressionCompletions(context)); } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/RequiredParameterNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/RequiredParameterNodeContext.java index dab179c98fa6..62a5a4e08858 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/RequiredParameterNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/RequiredParameterNodeContext.java @@ -36,7 +36,7 @@ import java.util.Optional; /** - * Handles the completions for the {@link io.ballerina.compiler.syntax.tree.RequiredParameterNode}. + * Handles the completions for the {@link RequiredParameterNode}. * * @since 2.0.0 */ diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/RightArrowActionNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/RightArrowActionNodeContext.java index 11d0db2380f3..ee88ba155a15 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/RightArrowActionNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/RightArrowActionNodeContext.java @@ -15,6 +15,7 @@ */ package org.ballerinalang.langserver.completions.providers.context; +import io.ballerina.compiler.api.symbols.MethodSymbol; import io.ballerina.compiler.api.symbols.ObjectTypeSymbol; import io.ballerina.compiler.api.symbols.Qualifier; import io.ballerina.compiler.api.symbols.Symbol; @@ -33,7 +34,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; /** * Parent completion provider for Right arrow action nodes. @@ -63,7 +63,7 @@ protected List getFilteredItems(BallerinaCompletionContext con Covers the following case where a is a client object and we suggest the remote actions (1) a -> g */ - List clientActions = this.getClientActions(expressionType.get()); + List clientActions = this.getClientActions(expressionType.get()); completionItems.addAll(this.getCompletionItemList(clientActions, context)); } else { /* @@ -73,7 +73,7 @@ protected List getFilteredItems(BallerinaCompletionContext con */ List filteredWorkers = visibleSymbols.stream() .filter(symbol -> symbol.kind() == SymbolKind.WORKER) - .collect(Collectors.toList()); + .toList(); completionItems.addAll(this.getCompletionItemList(filteredWorkers, context)); completionItems.add(new SnippetCompletionItem(context, Snippet.KW_FUNCTION.get())); } @@ -87,7 +87,7 @@ protected List getFilteredItems(BallerinaCompletionContext con * @param symbol Endpoint variable symbol to evaluate * @return {@link List} List of extracted actions as Symbol Info */ - public List getClientActions(Symbol symbol) { + public List getClientActions(Symbol symbol) { if (!SymbolUtil.isObject(symbol)) { return new ArrayList<>(); } @@ -95,6 +95,6 @@ public List getClientActions(Symbol symbol) { return ((ObjectTypeSymbol) typeDescriptor).methods().values().stream() .filter(method -> method.qualifiers().contains(Qualifier.REMOTE) || method.qualifiers().contains(Qualifier.RESOURCE)) - .collect(Collectors.toList()); + .toList(); } } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/SelectClauseNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/SelectClauseNodeContext.java index 19d4884e0214..8e08d58407f3 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/SelectClauseNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/SelectClauseNodeContext.java @@ -36,7 +36,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; /** * Completion provider for {@link SelectClauseNode} context. @@ -71,9 +70,8 @@ public List getCompletions(BallerinaCompletionContext context, functionSymbols.stream() .filter(symbol -> symbol.typeDescriptor().restParam().isPresent()) .filter(symbol -> symbol.getName().isPresent() && !symbol.getName().get().contains("$")) - .filter(symbol -> completionItems - .addAll(populateBallerinaFunctionCompletionItems(symbol, context))) - .collect(Collectors.toList()); + .forEach(symbol -> completionItems + .addAll(populateBallerinaFunctionCompletionItems(symbol, context))); } } this.sort(context, node, completionItems); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ServiceDeclarationNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ServiceDeclarationNodeContext.java index 6a41264d482a..de416fda8559 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ServiceDeclarationNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/ServiceDeclarationNodeContext.java @@ -44,7 +44,6 @@ import java.util.List; import java.util.Optional; import java.util.function.Predicate; -import java.util.stream.Collectors; import static org.ballerinalang.langserver.completions.util.SortingUtil.genSortText; import static org.ballerinalang.langserver.completions.util.SortingUtil.genSortTextForModule; @@ -120,7 +119,7 @@ public List getCompletions(BallerinaCompletionContext context, List visibleSymbols = context.visibleSymbols(context.getCursorPosition()); List listeners = visibleSymbols.stream() .filter(predicate) - .collect(Collectors.toList()); + .toList(); completionItems.addAll(this.getCompletionItemList(listeners, context)); completionItems.addAll(this.getModuleCompletionItems(context)); completionItems.add(new SnippetCompletionItem(context, Snippet.KW_NEW.get())); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/StartActionNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/StartActionNodeContext.java index b28ca435f1e5..22eb4d3b2944 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/StartActionNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/StartActionNodeContext.java @@ -37,7 +37,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; import static io.ballerina.compiler.api.symbols.SymbolKind.FUNCTION; @@ -90,7 +89,7 @@ protected List expressionCompletions(BallerinaCompletionContex List visibleSymbols = context.visibleSymbols(context.getCursorPosition()); List filteredList = visibleSymbols.stream() .filter(symbol -> (symbol instanceof VariableSymbol || symbol.kind() == FUNCTION)) - .collect(Collectors.toList()); + .toList(); completionItems.addAll(this.getCompletionItemList(filteredList, context)); return completionItems; } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/SyncSendActionNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/SyncSendActionNodeContext.java index 5bb61f066412..0bff5fdc811b 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/SyncSendActionNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/SyncSendActionNodeContext.java @@ -28,7 +28,6 @@ import java.util.ArrayList; import java.util.List; -import java.util.stream.Collectors; /** * Completion provider for {@link SyncSendActionNode} context. @@ -47,7 +46,7 @@ public List getCompletions(BallerinaCompletionContext context, List visibleSymbols = context.visibleSymbols(context.getCursorPosition()); List filteredWorkers = visibleSymbols.stream() .filter(symbol -> symbol.kind() == SymbolKind.WORKER) - .collect(Collectors.toList()); + .toList(); List completionItems = new ArrayList<>(this.getCompletionItemList(filteredWorkers, context)); completionItems.add(new SnippetCompletionItem(context, Snippet.KW_FUNCTION.get())); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/TypeParameterContextProvider.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/TypeParameterContextProvider.java index a52a4a42dd71..eb23bf375e83 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/TypeParameterContextProvider.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/TypeParameterContextProvider.java @@ -130,7 +130,7 @@ private List getTableTypeDescSymbols(BallerinaCompletionContex */ List filtered = context.visibleSymbols(context.getCursorPosition()).stream() .filter(predicate) - .collect(Collectors.toList()); + .toList(); List completionItems = new ArrayList<>(); completionItems.addAll(this.getModuleCompletionItems(context)); completionItems.addAll(this.getCompletionItemList(filtered, context)); @@ -172,7 +172,7 @@ private List getErrorTypeDescSymbols(BallerinaCompletionContex Arrays.asList(new SnippetCompletionItem(context, Snippet.DEF_RECORD_TYPE_DESC.get()), new SnippetCompletionItem(context, Snippet.DEF_CLOSED_RECORD_TYPE_DESC.get()))); List visibleSymbols = context.visibleSymbols(context.getCursorPosition()); - mappingTypes = visibleSymbols.stream().filter(predicate).collect(Collectors.toList()); + mappingTypes = visibleSymbols.stream().filter(predicate).toList(); completionItems.addAll(this.getCompletionItemList(mappingTypes, context)); completionItems.addAll(this.getModuleCompletionItems(context)); } @@ -213,7 +213,7 @@ private List getXMLTypeDescSymbols(BallerinaCompletionContext // modules and the xml sub types are suggested List filtered = visibleSymbols.stream() .filter(predicate) - .collect(Collectors.toList()); + .toList(); completionItems.addAll(this.getCompletionItemList(filtered, context)); completionItems.addAll(this.getModuleCompletionItems(context)); } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/TypeReferenceNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/TypeReferenceNodeContext.java index cf047d9e3636..869a75b59a8d 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/TypeReferenceNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/TypeReferenceNodeContext.java @@ -35,7 +35,6 @@ import java.util.List; import java.util.Optional; import java.util.function.Predicate; -import java.util.stream.Collectors; /** * Completion provider for {@link TypeReferenceNode} context. @@ -65,7 +64,7 @@ public List getCompletions(BallerinaCompletionContext context, completionItems.addAll(this.getCompletionItemList(moduleContent, context)); } else { List symbols = context.visibleSymbols(context.getCursorPosition()).stream() - .filter(predicate.get()).collect(Collectors.toList()); + .filter(predicate.get()).toList(); completionItems.addAll(this.getCompletionItemList(symbols, context)); completionItems.addAll(this.getModuleCompletionItems(context)); } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/TypeTestExpressionNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/TypeTestExpressionNodeContext.java index 9b69b34b4199..0505dd30ad03 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/TypeTestExpressionNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/TypeTestExpressionNodeContext.java @@ -48,7 +48,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; /** * Completion provider for {@link TypeTestExpressionNode} context. @@ -104,7 +103,7 @@ private List getModuleTypeDescCompletionsForExpression(Balleri if (typeSymbol.get().typeKind() == TypeDescKind.UNION) { typeReferences = ((UnionTypeSymbol) typeSymbol.get()).memberTypeDescriptors().stream() .filter(type -> type.typeKind() == TypeDescKind.TYPE_REFERENCE) - .map(type -> (TypeReferenceTypeSymbol) type).collect(Collectors.toList()); + .map(type -> (TypeReferenceTypeSymbol) type).toList(); } else if (typeSymbol.get().typeKind() == TypeDescKind.TYPE_REFERENCE) { typeReferences = List.of((TypeReferenceTypeSymbol) typeSymbol.get()); } else { diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/WaitActionNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/WaitActionNodeContext.java index 7649bd102bc9..9c52d064b5d9 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/WaitActionNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/WaitActionNodeContext.java @@ -41,7 +41,6 @@ import java.util.List; import java.util.Optional; import java.util.function.Predicate; -import java.util.stream.Collectors; import static io.ballerina.compiler.api.symbols.SymbolKind.FUNCTION; import static io.ballerina.compiler.api.symbols.SymbolKind.PARAMETER; @@ -119,7 +118,7 @@ protected List expressionCompletions(BallerinaCompletionContex .filter(symbol -> (symbol instanceof VariableSymbol || symbol.kind() == PARAMETER || symbol.kind() == FUNCTION || symbol.kind() == WORKER) && !symbol.getName().orElse("").equals(Names.ERROR.getValue())) - .collect(Collectors.toList()); + .toList(); completionItems.addAll(this.getCompletionItemList(filteredList, context)); this.getAnonFunctionDefSnippet(context).ifPresent(completionItems::add); return completionItems; diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/WaitFieldsListNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/WaitFieldsListNodeContext.java index 0e70ed3872db..72cd947a9a60 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/WaitFieldsListNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/WaitFieldsListNodeContext.java @@ -36,7 +36,6 @@ import java.util.List; import java.util.Optional; import java.util.function.Predicate; -import java.util.stream.Collectors; import static io.ballerina.compiler.api.symbols.SymbolKind.WORKER; @@ -79,7 +78,7 @@ protected List expressionCompletions(BallerinaCompletionContex List visibleSymbols = context.visibleSymbols(context.getCursorPosition()); List filteredList = visibleSymbols.stream() .filter(CommonUtil.getVariableFilterPredicate().or(symbol -> symbol.kind() == WORKER)) - .collect(Collectors.toList()); + .toList(); return this.getCompletionItemList(filteredList, context); } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/XMLNSDeclarationNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/XMLNSDeclarationNodeContext.java index eee64d490f37..889bf2593df8 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/XMLNSDeclarationNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/XMLNSDeclarationNodeContext.java @@ -36,7 +36,6 @@ import java.util.List; import java.util.Optional; import java.util.function.Predicate; -import java.util.stream.Collectors; /** * Completion provider for {@link XMLNamespaceDeclarationNode} context. @@ -67,7 +66,7 @@ public List getCompletions(BallerinaCompletionContext context, } else { List constants = context.visibleSymbols(context.getCursorPosition()).stream() .filter(predicate) - .collect(Collectors.toList()); + .toList(); completionItems.addAll(this.getCompletionItemList(constants, context)); completionItems.addAll(this.getModuleCompletionItems(context)); } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/XMLNamePatternChainingNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/XMLNamePatternChainingNodeContext.java index f617d70b9709..169d9465b8e0 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/XMLNamePatternChainingNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/XMLNamePatternChainingNodeContext.java @@ -24,7 +24,6 @@ import org.ballerinalang.langserver.completions.providers.AbstractCompletionProvider; import java.util.List; -import java.util.stream.Collectors; /** * Completion provider for {@link XMLNamePatternChainingNode} context. @@ -41,8 +40,7 @@ public XMLNamePatternChainingNodeContext() { @Override public List getCompletions(BallerinaCompletionContext context, XMLNamePatternChainingNode node) { List visibleSymbols = context.visibleSymbols(context.getCursorPosition()); - List xmlNs = visibleSymbols.stream().filter(symbol -> symbol.kind() == SymbolKind.XMLNS) - .collect(Collectors.toList()); + List xmlNs = visibleSymbols.stream().filter(symbol -> symbol.kind() == SymbolKind.XMLNS).toList(); List completionItems = this.getCompletionItemList(xmlNs, context); this.sort(context, node, completionItems); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/XMLSimpleNameNodeContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/XMLSimpleNameNodeContext.java index be4578fce6b0..f628736bacb0 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/XMLSimpleNameNodeContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/XMLSimpleNameNodeContext.java @@ -24,7 +24,6 @@ import org.ballerinalang.langserver.completions.providers.AbstractCompletionProvider; import java.util.List; -import java.util.stream.Collectors; /** * Completion provider for {@link XMLSimpleNameNode} context. @@ -44,7 +43,7 @@ public List getCompletions(BallerinaCompletionContext context, List xmlNamespaces = visibleSymbols.stream() .filter(symbol -> symbol.kind() == SymbolKind.XMLNS) - .collect(Collectors.toList()); + .toList(); List completionItems = this.getCompletionItemList(xmlNamespaces, context); this.sort(context, node, completionItems); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/util/ClassDefinitionNodeContextUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/util/ClassDefinitionNodeContextUtil.java index 16201d20e86e..ca4a80bdcf1d 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/util/ClassDefinitionNodeContextUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/util/ClassDefinitionNodeContextUtil.java @@ -11,7 +11,8 @@ * * @since 2.0.0 */ -public class ClassDefinitionNodeContextUtil { +public final class ClassDefinitionNodeContextUtil { + private ClassDefinitionNodeContextUtil() { } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/util/ImportDeclarationContextUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/util/ImportDeclarationContextUtil.java index 145fa5c272ed..ac1a8eee9d74 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/util/ImportDeclarationContextUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/util/ImportDeclarationContextUtil.java @@ -30,7 +30,8 @@ * * @since 2.0.0 */ -public class ImportDeclarationContextUtil { +public final class ImportDeclarationContextUtil { + private ImportDeclarationContextUtil() { } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/util/ModulePartNodeContextUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/util/ModulePartNodeContextUtil.java index b59c8179814d..fd5bce2771c5 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/util/ModulePartNodeContextUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/util/ModulePartNodeContextUtil.java @@ -46,7 +46,6 @@ import java.util.List; import java.util.Optional; import java.util.function.Predicate; -import java.util.stream.Collectors; import static org.ballerinalang.langserver.completions.util.SortingUtil.genSortText; @@ -55,7 +54,7 @@ * * @since 2.0.0 */ -public class ModulePartNodeContextUtil { +public final class ModulePartNodeContextUtil { private ModulePartNodeContextUtil() { } @@ -207,7 +206,7 @@ public static boolean onServiceTypeDescContext(Token evalToken, BallerinaComplet */ public static List serviceTypeDescContextSymbols(BallerinaCompletionContext context) { List visibleSymbols = context.visibleSymbols(context.getCursorPosition()); - return visibleSymbols.stream().filter(serviceTypeDescPredicate()).collect(Collectors.toList()); + return visibleSymbols.stream().filter(serviceTypeDescPredicate()).toList(); } /** diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/util/QueryExpressionUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/util/QueryExpressionUtil.java index a6e62f64e2a5..0733ee17d821 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/util/QueryExpressionUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/util/QueryExpressionUtil.java @@ -24,12 +24,14 @@ import java.util.Arrays; import java.util.List; -import java.util.stream.Collectors; /** * A utility to provide completions related to query expressions. */ -public class QueryExpressionUtil { +public final class QueryExpressionUtil { + + private QueryExpressionUtil() { + } public static List getCommonKeywordCompletions(BallerinaCompletionContext context) { return Arrays.asList( @@ -75,6 +77,6 @@ public static List getLangLibMethods(BallerinaCompletionContext langLibMethods.addAll(types.TYPEDESC.langLibMethods()); langLibMethods.addAll(types.XML.langLibMethods()); - return langLibMethods.stream().distinct().collect(Collectors.toList()); + return langLibMethods.stream().distinct().toList(); } } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/util/RegexpCompletionProvider.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/util/RegexpCompletionProvider.java index 72d721095a78..461cb2454eb1 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/util/RegexpCompletionProvider.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/util/RegexpCompletionProvider.java @@ -44,7 +44,7 @@ * * @since 2201.5.0 */ -public class RegexpCompletionProvider { +public final class RegexpCompletionProvider { private static final List WORD_SEPARATOR_ARRAY = Arrays.asList("`", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "-", "=", "+", "[", "{", "]", "}", "\\", "|", ";", ":", "'", "\"", ",", ".", "<", ">", "/", @@ -52,6 +52,9 @@ public class RegexpCompletionProvider { private static final HashSet RE_FLAGS = new HashSet<>(Arrays.asList("i", "m", "s", "x")); + private RegexpCompletionProvider() { + } + public static List getRegexCompletions(NonTerminalNode nodeAtCursor, BallerinaCompletionContext ctx) { diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/CompletionUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/CompletionUtil.java index 2d6875f58927..f8bff6168e0e 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/CompletionUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/CompletionUtil.java @@ -41,12 +41,11 @@ import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.stream.Collectors; /** * Common utility methods for the completion operation. */ -public class CompletionUtil { +public final class CompletionUtil { private CompletionUtil() { } @@ -86,7 +85,7 @@ public static List getCompletionItems(BallerinaCompletionContext return items.stream() .map(LSCompletionItem::getCompletionItem) - .collect(Collectors.toList()); + .toList(); } /** diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/ContextTypeResolver.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/ContextTypeResolver.java index 325bc8fd4c6c..289100ace049 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/ContextTypeResolver.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/ContextTypeResolver.java @@ -730,19 +730,12 @@ public Optional transform(SelectClauseNode node) { // stream from... // from... // In such cases, we take the member type - switch (typeSymbol.get().typeKind()) { - case TABLE: - TableTypeSymbol tableType = (TableTypeSymbol) typeSymbol.get(); - return Optional.of(tableType.rowTypeParameter()); - case STREAM: - StreamTypeSymbol streamType = (StreamTypeSymbol) typeSymbol.get(); - return Optional.of(streamType.typeParameter()); - case ARRAY: - ArrayTypeSymbol arrayType = (ArrayTypeSymbol) typeSymbol.get(); - return Optional.of(arrayType.memberTypeDescriptor()); - default: - return typeSymbol; - } + return switch (typeSymbol.get().typeKind()) { + case TABLE -> Optional.of(((TableTypeSymbol) typeSymbol.get()).rowTypeParameter()); + case STREAM -> Optional.of(((StreamTypeSymbol) typeSymbol.get()).typeParameter()); + case ARRAY -> Optional.of(((ArrayTypeSymbol) typeSymbol.get()).memberTypeDescriptor()); + default -> typeSymbol; + }; } // @Override diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/FieldAccessCompletionResolver.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/FieldAccessCompletionResolver.java index bae7e81a4088..fb07bac435ed 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/FieldAccessCompletionResolver.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/FieldAccessCompletionResolver.java @@ -62,7 +62,6 @@ import java.util.List; import java.util.Optional; import java.util.function.Predicate; -import java.util.stream.Collectors; /** * Symbol resolver for the field access expressions. @@ -157,7 +156,7 @@ public Optional transform(FunctionCallExpressionNode node) { functionName = ((SimpleNameReferenceNode) nameRef).name().text(); visibleEntries = context.visibleSymbols(context.getCursorPosition()).stream() .filter(fSymbolPredicate.or(fPointerPredicate)) - .collect(Collectors.toList()); + .toList(); } else { return Optional.empty(); } @@ -316,8 +315,7 @@ private boolean withValidAccessModifiers(Node exprNode, Symbol symbol, Package c boolean isPublic = false; boolean isResource = false; - if (symbol instanceof Qualifiable) { - Qualifiable qSymbol = (Qualifiable) symbol; + if (symbol instanceof Qualifiable qSymbol) { isPrivate = qSymbol.qualifiers().contains(Qualifier.PRIVATE); isPublic = qSymbol.qualifiers().contains(Qualifier.PUBLIC); isResource = qSymbol.qualifiers().contains(Qualifier.RESOURCE); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/ForeachCompletionUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/ForeachCompletionUtil.java index 34b250943a41..c01f47bef409 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/ForeachCompletionUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/ForeachCompletionUtil.java @@ -55,7 +55,7 @@ * * @since 2.0.0 */ -public class ForeachCompletionUtil { +public final class ForeachCompletionUtil { private static final String VAR_NAME = "item"; private static final String VAR_NAME_RANGE_EXP = "i"; diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/ItemResolverConstants.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/ItemResolverConstants.java index e83301d70f20..1f6c52c9d83a 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/ItemResolverConstants.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/ItemResolverConstants.java @@ -21,7 +21,7 @@ /** * Constants for Item Resolver. */ -public class ItemResolverConstants { +public final class ItemResolverConstants { // Start of Basic Constructs public static final String RETURN = "return"; @@ -167,4 +167,7 @@ public class ItemResolverConstants { public static final String RECORD_KEYWORD = "record"; public static final String OBJECT_KEYWORD = "object"; public static final String OUTER_KEYWORD = "outer"; + + private ItemResolverConstants() { + } } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/QNameRefCompletionUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/QNameRefCompletionUtil.java index 106a144e550e..b5d3e33f6fb7 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/QNameRefCompletionUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/QNameRefCompletionUtil.java @@ -27,18 +27,18 @@ import org.ballerinalang.langserver.commons.BallerinaCompletionContext; import org.ballerinalang.langserver.commons.PositionedOperationContext; -import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.function.Predicate; -import java.util.stream.Collectors; /** * Holds the set of utilities to get the qualified name reference associated Completion Items. * * @since 2.0.0 */ -public class QNameRefCompletionUtil { +public final class QNameRefCompletionUtil { + private QNameRefCompletionUtil() { } @@ -70,7 +70,7 @@ public static List getExpressionContextEntries(BallerinaCompletionContex || symbol.kind() == SymbolKind.TYPE_DEFINITION || symbol.kind() == SymbolKind.CLASS || symbol instanceof VariableSymbol) - .collect(Collectors.toList())).orElseGet(ArrayList::new); + .toList()).orElseGet(Collections::emptyList); } /** @@ -109,8 +109,8 @@ public static List getModuleContent(PositionedOperationContext context, QNameRefCompletionUtil.getAlias(qNameRef)); return module.map(moduleSymbol -> moduleSymbol.allSymbols().stream() .filter(predicate) - .collect(Collectors.toList())) - .orElseGet(ArrayList::new); + .toList()) + .orElseGet(Collections::emptyList); } /** @@ -126,8 +126,8 @@ public static List getTypesInModule(BallerinaCompletionContext context, QNameRefCompletionUtil.getAlias(qNameRef)); return module.map(symbol -> symbol.allSymbols().stream() .filter(CommonUtil.typesFilter()) - .collect(Collectors.toList())) - .orElseGet(ArrayList::new); + .toList()) + .orElseGet(Collections::emptyList); } /** diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/SnippetGenerator.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/SnippetGenerator.java index 99dd74ae568f..9f1bdc2759c6 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/SnippetGenerator.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/SnippetGenerator.java @@ -28,7 +28,7 @@ * * @since 0.982.0 */ -public class SnippetGenerator { +public final class SnippetGenerator { private static final String FILTER_TEXT_SEPARATOR = "_"; diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/SortingUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/SortingUtil.java index 7d1455b1262e..1f1d2c510338 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/SortingUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/SortingUtil.java @@ -66,7 +66,7 @@ * * @since 2.0.0 */ -public class SortingUtil { +public final class SortingUtil { private static final int RANK_UPPER_BOUNDARY = 64; @@ -346,19 +346,11 @@ public static boolean isCompletionItemAssignable(LSCompletionItem completionItem * @return Type Symbol or Empty if type parameter is not present */ public static Optional getTypeParameterFromTypeSymbol(TypeSymbol typeSymbol) { - Optional optionalTypeSymbol; - switch (typeSymbol.typeKind()) { - case TYPEDESC: - optionalTypeSymbol = ((TypeDescTypeSymbol) typeSymbol).typeParameter(); - break; - case FUTURE: - optionalTypeSymbol = ((FutureTypeSymbol) typeSymbol).typeParameter(); - break; - default: - optionalTypeSymbol = Optional.empty(); - break; - } - return optionalTypeSymbol; + return switch (typeSymbol.typeKind()) { + case TYPEDESC -> ((TypeDescTypeSymbol) typeSymbol).typeParameter(); + case FUTURE -> ((FutureTypeSymbol) typeSymbol).typeParameter(); + default -> Optional.empty(); + }; } /** @@ -590,17 +582,12 @@ public static int toRank(BallerinaCompletionContext context, LSCompletionItem co break; case SNIPPET: if (completionItemKind != null) { - switch (completionItemKind) { - case TypeParameter: - rank = 14; - break; - case Snippet: - rank = 16; - break; - case Keyword: - rank = 17; - break; - } + rank = switch (completionItemKind) { + case TypeParameter -> 14; + case Snippet -> 16; + case Keyword -> 17; + default -> rank; + }; } break; case OBJECT_FIELD: diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/TypeGuardCompletionUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/TypeGuardCompletionUtil.java index f9d8431ced81..d0cebce8b510 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/TypeGuardCompletionUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/util/TypeGuardCompletionUtil.java @@ -47,7 +47,7 @@ * * @since 2.0.0 */ -public class TypeGuardCompletionUtil { +public final class TypeGuardCompletionUtil { private static final String TYPE_GUARD_LABEL = "typeguard"; diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/config/CodeLensConfig.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/config/CodeLensConfig.java index 07d11304b5e1..d45de476c82c 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/config/CodeLensConfig.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/config/CodeLensConfig.java @@ -69,10 +69,9 @@ public boolean equals(Object obj) { if (obj == this) { return true; } - if (!(obj instanceof Enabled)) { + if (!(obj instanceof Enabled cc)) { return false; } - Enabled cc = (Enabled) obj; return cc.enabled == enabled; } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/contexts/AbstractDocumentServiceContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/contexts/AbstractDocumentServiceContext.java index 197328235ea1..892e11c2d2d2 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/contexts/AbstractDocumentServiceContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/contexts/AbstractDocumentServiceContext.java @@ -42,7 +42,6 @@ import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.stream.Collectors; import javax.annotation.Nonnull; @@ -161,7 +160,7 @@ public List currentDocImports() { throw new RuntimeException("Cannot find a valid document"); } return ((ModulePartNode) document.get().syntaxTree().rootNode()).imports().stream() - .collect(Collectors.toList()); + .toList(); } @Override diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/contexts/BallerinaContextUtils.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/contexts/BallerinaContextUtils.java index 82d80c3c8636..81e15ad5ef96 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/contexts/BallerinaContextUtils.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/contexts/BallerinaContextUtils.java @@ -28,7 +28,8 @@ * * @since 2.0.0 */ -public class BallerinaContextUtils { +public final class BallerinaContextUtils { + private BallerinaContextUtils() { } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/contexts/CodeActionContextImpl.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/contexts/CodeActionContextImpl.java index 4d8954170163..ad5d4cd125d6 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/contexts/CodeActionContextImpl.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/contexts/CodeActionContextImpl.java @@ -41,7 +41,6 @@ import java.nio.file.Path; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; /** * Language server context implementation. @@ -107,7 +106,7 @@ public List diagnostics(Path filePath project.sourceRoot(); this.diagnostics = compilation.diagnosticResult().diagnostics().stream() .filter(diag -> projectRoot.resolve(diag.location().lineRange().fileName()).equals(filePath)) - .collect(Collectors.toList()); + .toList(); return this.diagnostics; } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/contexts/ContextBuilder.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/contexts/ContextBuilder.java index 6c271e79cdba..e5fa1f4ac401 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/contexts/ContextBuilder.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/contexts/ContextBuilder.java @@ -54,7 +54,7 @@ * * @since 2.0.0 */ -public class ContextBuilder { +public final class ContextBuilder { private ContextBuilder() { } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/definition/DefinitionUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/definition/DefinitionUtil.java index 617354686954..a9cebe0225cc 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/definition/DefinitionUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/definition/DefinitionUtil.java @@ -43,7 +43,10 @@ * * @since 1.2.0 */ -public class DefinitionUtil { +public final class DefinitionUtil { + + private DefinitionUtil() { + } /** * Get the definition. diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/diagnostic/DiagnosticsHelper.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/diagnostic/DiagnosticsHelper.java index 50e7f50e07fe..f6a53e3b8d03 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/diagnostic/DiagnosticsHelper.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/diagnostic/DiagnosticsHelper.java @@ -39,12 +39,13 @@ import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; +import java.util.Deque; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.Stack; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; @@ -63,7 +64,7 @@ public class DiagnosticsHelper { */ private final Map>> lastDiagnosticMap; private CompletableFuture latestScheduled = null; - private final Stack cyclicDependencyErrors; + private final Deque cyclicDependencyErrors; public static DiagnosticsHelper getInstance(LanguageServerContext serverContext) { DiagnosticsHelper diagnosticsHelper = serverContext.get(DIAGNOSTICS_HELPER_KEY); @@ -77,7 +78,7 @@ public static DiagnosticsHelper getInstance(LanguageServerContext serverContext) private DiagnosticsHelper(LanguageServerContext serverContext) { serverContext.put(DIAGNOSTICS_HELPER_KEY, this); this.lastDiagnosticMap = new HashMap<>(); - this.cyclicDependencyErrors = new Stack<>(); + this.cyclicDependencyErrors = new ConcurrentLinkedDeque<>(); } /** diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/documentsymbol/DocumentSymbolUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/documentsymbol/DocumentSymbolUtil.java index 025f9093fbfc..e3a75ba1d550 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/documentsymbol/DocumentSymbolUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/documentsymbol/DocumentSymbolUtil.java @@ -38,7 +38,10 @@ * * @since 2.0.0 */ -public class DocumentSymbolUtil { +public final class DocumentSymbolUtil { + + private DocumentSymbolUtil() { + } /** * get document symbols given the context. diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/connector/BallerinaConnectorListRequest.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/connector/BallerinaConnectorListRequest.java index cab206012f11..f02a08c1eeef 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/connector/BallerinaConnectorListRequest.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/connector/BallerinaConnectorListRequest.java @@ -175,7 +175,7 @@ public String toString() { } public Map getQueryMap() { - Map params = new HashMap(); + Map params = new HashMap<>(); if (getQuery() != null) { params.put("q", getQuery()); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/connector/BallerinaConnectorService.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/connector/BallerinaConnectorService.java index 9230af8e7fb6..2414dc48ffb8 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/connector/BallerinaConnectorService.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/connector/BallerinaConnectorService.java @@ -295,9 +295,9 @@ public CompletableFuture record(BallerinaRecordRequest Gson gson = new Gson(); if (recordNode != null) { - if (recordJson instanceof JsonObject) { + if (recordJson instanceof JsonObject jsonObject) { JsonElement recordsJson = gson.toJsonTree(recordDefJsonMap); - ((JsonObject) recordJson).add("records", recordsJson); + jsonObject.add("records", recordsJson); } recordCache.addRecordAST(request.getOrg(), request.getModule(), request.getVersion(), request.getName(), recordJson); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/connector/Constants.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/connector/Constants.java index 6ae8bf1cb32f..df443a796e23 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/connector/Constants.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/connector/Constants.java @@ -20,7 +20,10 @@ * * @since 2.0.0 */ -public class Constants { +public final class Constants { - protected static final String CAPABILITY_NAME = "ballerinaConnector"; + static final String CAPABILITY_NAME = "ballerinaConnector"; + + private Constants() { + } } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/document/BallerinaDocumentService.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/document/BallerinaDocumentService.java index 5654bb88bf0d..9ec575567a17 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/document/BallerinaDocumentService.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/document/BallerinaDocumentService.java @@ -66,7 +66,6 @@ import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; -import java.util.stream.Collectors; /** * Implementation of Ballerina Document extension for Language Server. @@ -432,7 +431,7 @@ public CompletableFuture> diagnostics(BallerinaPr return diagnosticsHelper.getLatestDiagnostics(context).entrySet().stream() .filter(entry -> fileUri.equals(entry.getKey())) .map((entry) -> new PublishDiagnosticsParams(entry.getKey(), entry.getValue())) - .collect(Collectors.toList()); + .toList(); } catch (Throwable e) { String msg = "Operation 'ballerinaDocument/diagnostics' failed!"; this.clientLogger.logError(DocumentContext.DC_DIAGNOSTICS, msg, e, params.getDocumentIdentifier(), diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/document/BallerinaLocateSyntaxTreeUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/document/BallerinaLocateSyntaxTreeUtil.java index 2b3c85c485e2..e79ca71e96f7 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/document/BallerinaLocateSyntaxTreeUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/document/BallerinaLocateSyntaxTreeUtil.java @@ -37,7 +37,8 @@ * * @since 2.0.0 */ -public class BallerinaLocateSyntaxTreeUtil { +public final class BallerinaLocateSyntaxTreeUtil { + private static final String POSITION = "position"; private static final String LOCATE_PATH_PROPERTY = "isNodePath"; private static final String LOCATED_NODE_PROPERTY = "isLocatedNode"; @@ -46,6 +47,9 @@ public class BallerinaLocateSyntaxTreeUtil { private static final String END_LINE = "endLine"; private static final String END_COLUMN = "endColumn"; + private BallerinaLocateSyntaxTreeUtil() { + } + private enum NodeRange { INCLUSIVE, EQUALS, diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/document/BallerinaTreeModifyUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/document/BallerinaTreeModifyUtil.java index 99a98aa2c725..13cc250fd0f9 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/document/BallerinaTreeModifyUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/document/BallerinaTreeModifyUtil.java @@ -52,7 +52,7 @@ * * @since 1.3.0 */ -public class BallerinaTreeModifyUtil { +public final class BallerinaTreeModifyUtil { private static final String DELETE = "delete"; private static final String IMPORT = "import"; diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/document/BallerinaTriggerModifyUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/document/BallerinaTriggerModifyUtil.java index 30568c7b656a..3e8e7c09c7c6 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/document/BallerinaTriggerModifyUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/document/BallerinaTriggerModifyUtil.java @@ -52,7 +52,7 @@ * * @since 1.3.0 */ -public class BallerinaTriggerModifyUtil { +public final class BallerinaTriggerModifyUtil { // private static final Logger logger = LoggerFactory.getLogger(BallerinaDocumentServiceImpl.class); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/document/Constants.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/document/Constants.java index 9d777ed7534e..9223d936c0b2 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/document/Constants.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/document/Constants.java @@ -20,6 +20,10 @@ * * @since 2.0.0 */ -public class Constants { +public final class Constants { + public static final String CAPABILITY_NAME = "ballerinaDocument"; + + private Constants() { + } } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/document/ExecutorPositionsUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/document/ExecutorPositionsUtil.java index bbb7ca8379ff..ce534e0b3f31 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/document/ExecutorPositionsUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/document/ExecutorPositionsUtil.java @@ -46,20 +46,20 @@ * * @since 2.0.0 */ -public class ExecutorPositionsUtil { - - protected static final String FILE_PATH = "filePath"; - protected static final String KIND = "kind"; - protected static final String FUNC_MAIN = "main"; - protected static final String MODULES = "modules"; - protected static final String GENERATED_MODULES = "generated"; - protected static final String NAME = "name"; - protected static final String RANGE = "range"; - protected static final String SOURCE = "source"; - protected static final String TEST = "test"; - protected static final String TEST_CONFIG = "test:Config"; - - protected static final Gson GSON = new Gson(); +public final class ExecutorPositionsUtil { + + static final String FILE_PATH = "filePath"; + static final String KIND = "kind"; + static final String FUNC_MAIN = "main"; + static final String MODULES = "modules"; + static final String GENERATED_MODULES = "generated"; + static final String NAME = "name"; + static final String RANGE = "range"; + static final String SOURCE = "source"; + static final String TEST = "test"; + static final String TEST_CONFIG = "test:Config"; + + static final Gson GSON = new Gson(); private ExecutorPositionsUtil() { } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/example/BallerinaExampleService.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/example/BallerinaExampleService.java index a9ecb829e48f..fe9f5efad1b3 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/example/BallerinaExampleService.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/example/BallerinaExampleService.java @@ -32,7 +32,6 @@ import java.io.FileInputStream; import java.io.InputStreamReader; -import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; @@ -50,8 +49,7 @@ public class BallerinaExampleService implements ExtendedLanguageServerService { private static final String BBE_DEF_JSON = "index.json"; private static final String EXAMPLES_DIR = "examples"; - private static final Type EXAMPLE_CATEGORY_TYPE = new TypeToken>() { - }.getType(); + private static final TypeToken> EXAMPLE_CATEGORY_TYPE = new TypeToken<>() { }; private LSClientLogger clientLogger; @Override diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/example/Constants.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/example/Constants.java index ade1dfa05ea3..8883605892ab 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/example/Constants.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/example/Constants.java @@ -20,7 +20,10 @@ * * @since 2.0.0 */ -public class Constants { +public final class Constants { - protected static final String CAPABILITY_NAME = "ballerinaExample"; + static final String CAPABILITY_NAME = "ballerinaExample"; + + private Constants() { + } } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/packages/DocumentComponentTransformer.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/packages/DocumentComponentTransformer.java index 51dcefa19899..9592f9828f95 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/packages/DocumentComponentTransformer.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/packages/DocumentComponentTransformer.java @@ -49,10 +49,10 @@ public ModuleObject getModuleObject(Node node) { @Override public Optional transformSyntaxNode(Node node) { - if (!(node instanceof NonTerminalNode)) { + if (!(node instanceof NonTerminalNode nonTerminalNode)) { return Optional.empty(); } - ((NonTerminalNode) node).children().forEach(child -> { + nonTerminalNode.children().forEach(child -> { Optional mapperObject = child.apply(this); if (mapperObject != null) { mapperObject.ifPresent(this.module::addDataObject); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/packages/PackageServiceConstants.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/packages/PackageServiceConstants.java index 292b7d7fb505..453944781521 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/packages/PackageServiceConstants.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/packages/PackageServiceConstants.java @@ -20,25 +20,28 @@ * * @since 2.0.0 */ -public class PackageServiceConstants { +public final class PackageServiceConstants { - protected static final String CAPABILITY_NAME = "ballerinaPackage"; - protected static final String NAME = "name"; - protected static final String FILE_PATH = "filePath"; - protected static final String START_LINE = "startLine"; - protected static final String START_COLUMN = "startColumn"; - protected static final String END_LINE = "endLine"; - protected static final String END_COLUMN = "endColumn"; - protected static final String FUNCTIONS = "functions"; - protected static final String SERVICES = "services"; - protected static final String MODULES = "modules"; - protected static final String RESOURCES = "resources"; - protected static final String RECORDS = "records"; - protected static final String OBJECTS = "objects"; - protected static final String TYPES = "types"; - protected static final String CONSTANTS = "constants"; - protected static final String ENUMS = "enums"; - protected static final String CLASSES = "classes"; - protected static final String LISTENERS = "listeners"; - protected static final String MODULE_LEVEL_VARIABLE = "moduleVariables"; + static final String CAPABILITY_NAME = "ballerinaPackage"; + static final String NAME = "name"; + static final String FILE_PATH = "filePath"; + static final String START_LINE = "startLine"; + static final String START_COLUMN = "startColumn"; + static final String END_LINE = "endLine"; + static final String END_COLUMN = "endColumn"; + static final String FUNCTIONS = "functions"; + static final String SERVICES = "services"; + static final String MODULES = "modules"; + static final String RESOURCES = "resources"; + static final String RECORDS = "records"; + static final String OBJECTS = "objects"; + static final String TYPES = "types"; + static final String CONSTANTS = "constants"; + static final String ENUMS = "enums"; + static final String CLASSES = "classes"; + static final String LISTENERS = "listeners"; + static final String MODULE_LEVEL_VARIABLE = "moduleVariables"; + + private PackageServiceConstants() { + } } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/symbol/BallerinaSymbolService.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/symbol/BallerinaSymbolService.java index 04b4ba348ca4..b92723b35266 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/symbol/BallerinaSymbolService.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/symbol/BallerinaSymbolService.java @@ -234,8 +234,8 @@ public CompletableFuture getTypesFromFnDefinition(Types .orElseThrow(); LinePosition fnPosition = request.getFnPosition(); Symbol fnSymbol = semanticModel.symbol(document, fnPosition).orElseThrow(); - if (fnSymbol instanceof FunctionSymbol) { - FunctionTypeSymbol fnTypeSymbol = ((FunctionSymbol) fnSymbol).typeDescriptor(); + if (fnSymbol instanceof FunctionSymbol functionSymbol) { + FunctionTypeSymbol fnTypeSymbol = functionSymbol.typeDescriptor(); Optional returnType = getTypeForReturnTypeDesc(fnTypeSymbol, request.getReturnTypeDescPosition()); @@ -373,8 +373,7 @@ private SymbolInfoResponse getDocMetadataForNewExpression(Node exprNode, Documen typeSymbol = classTypeSymbol.get(); } - if (typeSymbol instanceof ClassSymbol) { - ClassSymbol classSymbol = (ClassSymbol) typeSymbol; + if (typeSymbol instanceof ClassSymbol classSymbol) { if (classSymbol.initMethod().isEmpty()) { break; } @@ -397,8 +396,7 @@ private SymbolInfoResponse getSymbolDocMetadata(Symbol symbolAtCursor, SymbolInf List symbolParams = new ArrayList<>(); - if (symbolAtCursor instanceof FunctionSymbol) { - FunctionSymbol functionSymbol = (FunctionSymbol) symbolAtCursor; + if (symbolAtCursor instanceof FunctionSymbol functionSymbol) { if (functionSymbol.typeDescriptor().params().isPresent()) { List parameterSymbolList = functionSymbol.typeDescriptor().params().get(); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/symbol/Constants.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/symbol/Constants.java index 2cbbf1dfc47b..724baf13ede1 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/symbol/Constants.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/extensions/ballerina/symbol/Constants.java @@ -20,7 +20,10 @@ * * @since 2.0.0 */ -public class Constants { +public final class Constants { - protected static final String CAPABILITY_NAME = "ballerinaSymbol"; + static final String CAPABILITY_NAME = "ballerinaSymbol"; + + private Constants() { + } } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/foldingrange/FoldingRangeProvider.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/foldingrange/FoldingRangeProvider.java index 31032e616f60..fce4deba7c69 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/foldingrange/FoldingRangeProvider.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/foldingrange/FoldingRangeProvider.java @@ -29,7 +29,10 @@ * * @since 2.0.0 */ -public class FoldingRangeProvider { +public final class FoldingRangeProvider { + + private FoldingRangeProvider() { + } /** * Returns the list of folding ranges for the given syntax tree. diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/hover/APIDocReference.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/hover/APIDocReference.java index 50ccd6bf87a0..610001292a64 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/hover/APIDocReference.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/hover/APIDocReference.java @@ -20,10 +20,13 @@ * * @since 2201.2.0 */ -public class APIDocReference { +public final class APIDocReference { private static final String BASE_URL = "https://lib.ballerina.io/"; + private APIDocReference() { + } + public static String from(String orgName, String moduleName, String version, diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/hover/HoverObjectResolver.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/hover/HoverObjectResolver.java index a97d4d80d51b..a81971168681 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/hover/HoverObjectResolver.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/hover/HoverObjectResolver.java @@ -78,29 +78,22 @@ public HoverObjectResolver(HoverContext context) { * @return {@link Hover} hover object. */ public Hover getHoverObjectForSymbol(Symbol symbol) { - switch (symbol.kind()) { - case FUNCTION: - return getHoverObjectForSymbol((FunctionSymbol) symbol); - case METHOD: - return getHoverObjectForSymbol((MethodSymbol) symbol); - case RESOURCE_METHOD: - return getHoverObjectForSymbol((ResourceMethodSymbol) symbol); - case TYPE_DEFINITION: - return getHoverObjectForSymbol((TypeDefinitionSymbol) symbol); - case CLASS: - return getHoverObjectForSymbol((ClassSymbol) symbol); - case VARIABLE: - return getHoverObjectForSymbol((VariableSymbol) symbol); - case PARAMETER: - return getHoverObjectForSymbol((ParameterSymbol) symbol); - case TYPE: - if (symbol instanceof TypeReferenceTypeSymbol) { - return getHoverObjectForSymbol(((TypeReferenceTypeSymbol) symbol).definition()); + return switch (symbol.kind()) { + case FUNCTION -> getHoverObjectForSymbol((FunctionSymbol) symbol); + case METHOD -> getHoverObjectForSymbol((MethodSymbol) symbol); + case RESOURCE_METHOD -> getHoverObjectForSymbol((ResourceMethodSymbol) symbol); + case TYPE_DEFINITION -> getHoverObjectForSymbol((TypeDefinitionSymbol) symbol); + case CLASS -> getHoverObjectForSymbol((ClassSymbol) symbol); + case VARIABLE -> getHoverObjectForSymbol((VariableSymbol) symbol); + case PARAMETER -> getHoverObjectForSymbol((ParameterSymbol) symbol); + case TYPE -> { + if (symbol instanceof TypeReferenceTypeSymbol refTypeSymbol) { + yield getHoverObjectForSymbol(refTypeSymbol.definition()); } - return HoverUtil.getHoverObject(); - default: - return HoverUtil.getDescriptionOnlyHoverObject(symbol); - } + yield HoverUtil.getHoverObject(); + } + default -> HoverUtil.getDescriptionOnlyHoverObject(symbol); + }; } private Hover getHoverObjectForSymbol(VariableSymbol variableSymbol) { @@ -381,8 +374,7 @@ public Hover getHoverObjectForExpression(Node exprNode) { typeSymbol = classTypeSymbol.get(); } - if (typeSymbol instanceof ClassSymbol) { - ClassSymbol classSymbol = (ClassSymbol) typeSymbol; + if (typeSymbol instanceof ClassSymbol classSymbol) { if (classSymbol.initMethod().isEmpty()) { break; } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/hover/HoverUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/hover/HoverUtil.java index 5458a917f79d..d813adfdac0c 100755 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/hover/HoverUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/hover/HoverUtil.java @@ -51,7 +51,10 @@ /** * Utility class for Hover functionality of language server. */ -public class HoverUtil { +public final class HoverUtil { + + private HoverUtil() { + } /** * Get the hover content. @@ -138,7 +141,7 @@ private static Optional getSymbolAtCursor(HoverContext context, Semantic * * @return {@link Hover} hover object. */ - protected static Hover getHoverObject() { + static Hover getHoverObject() { return getHoverObject(""); } @@ -147,7 +150,7 @@ protected static Hover getHoverObject() { * * @return {@link Hover} hover object. */ - protected static Hover getHoverObject(String content) { + static Hover getHoverObject(String content) { Hover hover = new Hover(); MarkupContent hoverMarkupContent = new MarkupContent(); hoverMarkupContent.setKind(CommonUtil.MARKDOWN_MARKUP_KIND); @@ -164,8 +167,8 @@ protected static Hover getHoverObject(String content) { * @param currentModule Current Module. * @return {@link Boolean} Whether the symbol is visible in the current context. */ - protected static Boolean withValidAccessModifiers(Symbol symbol, Package currentPackage, - ModuleId currentModule, HoverContext context) { + static Boolean withValidAccessModifiers(Symbol symbol, Package currentPackage, + ModuleId currentModule, HoverContext context) { Optional project = context.workspace().project(context.filePath()); Optional typeSymbolModule = symbol.getModule(); @@ -178,8 +181,7 @@ protected static Boolean withValidAccessModifiers(Symbol symbol, Package current boolean isPublic = false; boolean isRemote = false; - if (symbol instanceof Qualifiable) { - Qualifiable qSymbol = (Qualifiable) symbol; + if (symbol instanceof Qualifiable qSymbol) { isPrivate = qSymbol.qualifiers().contains(Qualifier.PRIVATE); isPublic = qSymbol.qualifiers().contains(Qualifier.PUBLIC); isResource = qSymbol.qualifiers().contains(Qualifier.RESOURCE); @@ -201,11 +203,11 @@ protected static Boolean withValidAccessModifiers(Symbol symbol, Package current * @return {@link Hover} */ public static Hover getDescriptionOnlyHoverObject(Symbol symbol) { - if (!(symbol instanceof Documentable) || ((Documentable) symbol).documentation().isEmpty()) { + if (!(symbol instanceof Documentable documentable) || documentable.documentation().isEmpty()) { return HoverUtil.getHoverObject(""); } - return getDescriptionOnlyHoverObject(((Documentable) symbol).documentation().get()); + return getDescriptionOnlyHoverObject(documentable.documentation().get()); } /** diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/inlayhint/InlayHintProvider.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/inlayhint/InlayHintProvider.java index a99621bb7de2..546e90d18ff6 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/inlayhint/InlayHintProvider.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/inlayhint/InlayHintProvider.java @@ -62,14 +62,17 @@ import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.stream.Collectors; /** * Represents the Inlay Hint Provider. * * @since 2201.6.0 */ -public class InlayHintProvider { +public final class InlayHintProvider { + + private InlayHintProvider() { + } + public static List getInlayHint(InlayHintContext context) { LSClientCapabilities lsClientCapabilities = context.languageServercontext().get(LSClientCapabilities.class); if (!lsClientCapabilities.getInitializationOptions().isEnableInlayHints() || @@ -154,7 +157,7 @@ private static Pair, Optional> getParamet return Pair.of(Collections.emptyList(), Optional.empty()); } // Since the method is a lang-lib function, skip the first parameter - return Pair.of(libFunction.get().params().get().stream().skip(1).collect(Collectors.toList()), + return Pair.of(libFunction.get().params().get().stream().skip(1).toList(), libFunction.get().restParam()); } else if (invokableNode.kind() == SyntaxKind.CLIENT_RESOURCE_ACCESS_ACTION) { return context.currentSemanticModel().get() @@ -229,7 +232,7 @@ private static Pair, Optional> getParamet } else if (node.functionName().kind() == SyntaxKind.SIMPLE_NAME_REFERENCE) { functionSymbols = visibleSymbols.stream() .filter(symbol -> symbol.kind() == SymbolKind.FUNCTION) - .map(symbol -> (FunctionSymbol) symbol).collect(Collectors.toList()); + .map(symbol -> (FunctionSymbol) symbol).toList(); functionName = ((SimpleNameReferenceNode) node.functionName()).name().text(); } else { return Pair.of(Collections.emptyList(), Optional.empty()); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/references/DocumentationReferenceFinder.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/references/DocumentationReferenceFinder.java index d331f7ce60fc..d2ef807ed20c 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/references/DocumentationReferenceFinder.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/references/DocumentationReferenceFinder.java @@ -21,25 +21,24 @@ import io.ballerina.compiler.syntax.tree.MarkdownDocumentationNode; import io.ballerina.compiler.syntax.tree.MarkdownParameterDocumentationLineNode; import io.ballerina.compiler.syntax.tree.Node; +import io.ballerina.compiler.syntax.tree.NodeLocation; import io.ballerina.compiler.syntax.tree.NodeTransformer; import io.ballerina.compiler.syntax.tree.RecordFieldNode; import io.ballerina.compiler.syntax.tree.RequiredParameterNode; import io.ballerina.compiler.syntax.tree.SyntaxKind; import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; -import io.ballerina.tools.diagnostics.Location; import org.ballerinalang.langserver.codeaction.CodeActionUtil; import java.util.Collections; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; /** * Finds references for the given symbol within documentation (parameters). * * @since 2201.6.0 */ -public class DocumentationReferenceFinder extends NodeTransformer> { +public class DocumentationReferenceFinder extends NodeTransformer> { private Symbol symbol; @@ -48,7 +47,7 @@ public DocumentationReferenceFinder(Symbol symbol) { } @Override - public List transform(RequiredParameterNode node) { + public List transform(RequiredParameterNode node) { Optional fnDefNode = CodeActionUtil.getEnclosedFunction(node); if (fnDefNode.isEmpty()) { return Collections.emptyList(); @@ -64,7 +63,7 @@ public List transform(RequiredParameterNode node) { } @Override - public List transform(RecordFieldNode node) { + public List transform(RecordFieldNode node) { if (node.parent().parent().kind() != SyntaxKind.TYPE_DEFINITION) { return Collections.emptyList(); } @@ -84,18 +83,18 @@ public List transform(RecordFieldNode node) { * @param mdNode Markdown documentation node * @return List of locations of the parameters within the documentation */ - private List getParameterLocations(MarkdownDocumentationNode mdNode) { + private List getParameterLocations(MarkdownDocumentationNode mdNode) { return mdNode.documentationLines().stream() .filter(line -> line.kind() == SyntaxKind.MARKDOWN_PARAMETER_DOCUMENTATION_LINE) .map(line -> (MarkdownParameterDocumentationLineNode) line) .map(line -> line.parameterName()) .filter(token -> token.text().equals(symbol.getName().get())) .map(paramToken -> paramToken.location()) - .collect(Collectors.toList()); + .toList(); } @Override - protected List transformSyntaxNode(Node node) { + protected List transformSyntaxNode(Node node) { return Collections.emptyList(); } } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/references/ReferencesUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/references/ReferencesUtil.java index 5e64c7abe5a6..f85c7cced045 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/references/ReferencesUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/references/ReferencesUtil.java @@ -18,6 +18,7 @@ import io.ballerina.compiler.api.SemanticModel; import io.ballerina.compiler.api.symbols.Symbol; import io.ballerina.compiler.syntax.tree.ModulePartNode; +import io.ballerina.compiler.syntax.tree.NodeLocation; import io.ballerina.compiler.syntax.tree.NonTerminalNode; import io.ballerina.compiler.syntax.tree.SyntaxKind; import io.ballerina.projects.Document; @@ -44,7 +45,8 @@ /** * Utility class for go to definition functionality of language server. */ -public class ReferencesUtil { +public final class ReferencesUtil { + private ReferencesUtil() { } @@ -60,7 +62,7 @@ public static Map> getReferences(PositionedOperationConte List docReferences = new LinkedList<>(); // Find references in documentation locations.forEach(location -> { - List refs = findReferencesInDocumentation(location, module, context, symbol.get()); + List refs = findReferencesInDocumentation(location, module, context, symbol.get()); if (refs != null && !refs.isEmpty()) { docReferences.addAll(refs); } @@ -92,10 +94,10 @@ public static Map> getReferences(Project project, Symbol return moduleLocationMap; } - private static List findReferencesInDocumentation(Location location, - Module module, - PositionedOperationContext context, - Symbol symbol) { + private static List findReferencesInDocumentation(Location location, + Module module, + PositionedOperationContext context, + Symbol symbol) { Path filePath = PathUtil.getPathFromLocation(module, location); Range range = PositionUtil.getRangeFromLineRange(location.lineRange()); Optional node = context.workspace().syntaxTree(filePath) diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/rename/RenameUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/rename/RenameUtil.java index 463b87b8e231..9dddbf06e161 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/rename/RenameUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/rename/RenameUtil.java @@ -74,7 +74,7 @@ * * @since 2.0.0 */ -public class RenameUtil { +public final class RenameUtil { private RenameUtil() { } @@ -268,8 +268,8 @@ private static Optional getFieldBindingPatternVa } FieldBindingPatternNode fieldBindingPatternNode = (FieldBindingPatternNode) node.parent(); - if (fieldBindingPatternNode instanceof FieldBindingPatternVarnameNode) { - return Optional.of((FieldBindingPatternVarnameNode) fieldBindingPatternNode); + if (fieldBindingPatternNode instanceof FieldBindingPatternVarnameNode fieldBindingPatternVarnameNode) { + return Optional.of(fieldBindingPatternVarnameNode); } return Optional.empty(); } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/semantictokens/SemanticTokensConstants.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/semantictokens/SemanticTokensConstants.java index 586616e844ef..df225471c6cd 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/semantictokens/SemanticTokensConstants.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/semantictokens/SemanticTokensConstants.java @@ -22,7 +22,7 @@ * * @since 2.0.0 */ -public class SemanticTokensConstants { +public final class SemanticTokensConstants { private SemanticTokensConstants() { } @@ -31,9 +31,9 @@ private SemanticTokensConstants() { public static final String REQUEST_METHOD = "textDocument/semanticTokens"; - protected static final String SELF = "self"; + static final String SELF = "self"; - protected static final String READONLY = "readonly"; + static final String READONLY = "readonly"; - protected static final String RETURN = "return"; + static final String RETURN = "return"; } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/semantictokens/SemanticTokensUtils.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/semantictokens/SemanticTokensUtils.java index 5b17b1c2c866..5c3e9a0b1a40 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/semantictokens/SemanticTokensUtils.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/semantictokens/SemanticTokensUtils.java @@ -33,14 +33,13 @@ import java.util.Collections; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; /** * Semantic tokens util class. * * @since 2.0.0 */ -public class SemanticTokensUtils { +public final class SemanticTokensUtils { private SemanticTokensUtils() { } @@ -73,7 +72,7 @@ public static SemanticTokens getSemanticTokens(SemanticTokensContext semanticTok public static List getTokenTypes() { return Arrays.stream(SemanticTokensContext.TokenTypes.values()) .map(SemanticTokensContext.TokenTypes::getValue) - .collect(Collectors.toList()); + .toList(); } /** @@ -84,7 +83,7 @@ public static List getTokenTypes() { public static List getTokenTypeModifiers() { return Arrays.stream(SemanticTokensContext.TokenTypeModifiers.values()) .map(SemanticTokensContext.TokenTypeModifiers::getValue) - .collect(Collectors.toList()); + .toList(); } /** diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/semantictokens/SemanticTokensVisitor.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/semantictokens/SemanticTokensVisitor.java index cfe8eb1a9143..44c34f8f3016 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/semantictokens/SemanticTokensVisitor.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/semantictokens/SemanticTokensVisitor.java @@ -148,8 +148,8 @@ public void visit(MethodDeclarationNode methodDeclarationNode) { @Override public void visit(FunctionCallExpressionNode functionCallExpressionNode) { Node functionName = functionCallExpressionNode.functionName(); - if (functionName instanceof QualifiedNameReferenceNode) { - functionName = ((QualifiedNameReferenceNode) functionName).identifier(); + if (functionName instanceof QualifiedNameReferenceNode qualifiedNameReferenceNode) { + functionName = qualifiedNameReferenceNode.identifier(); } this.addSemanticToken(functionName, TokenTypes.FUNCTION.getId(), 0, false, -1, -1); visitSyntaxNode(functionCallExpressionNode); @@ -278,8 +278,8 @@ public void visit(MarkdownParameterDocumentationLineNode markdownParameterDocume case TYPE_DEFINITION: Node node = markdownParameterDocumentationLineNode.parent().parent().parent(); type = TokenTypes.TYPE_PARAMETER.getId(); - if (node instanceof TypeDefinitionNode) { - SyntaxKind kind = ((TypeDefinitionNode) node).typeDescriptor().kind(); + if (node instanceof TypeDefinitionNode typeDefinitionNode) { + SyntaxKind kind = typeDefinitionNode.typeDescriptor().kind(); if (kind == SyntaxKind.OBJECT_TYPE_DESC || kind == SyntaxKind.RECORD_TYPE_DESC) { type = TokenTypes.PROPERTY.getId(); } @@ -311,8 +311,7 @@ public void visit(TypeDefinitionNode typeDefinitionNode) { modifiers = TokenTypeModifiers.DECLARATION.getId(); break; case INTERSECTION_TYPE_DESC: - if (typeDescriptor instanceof IntersectionTypeDescriptorNode) { - IntersectionTypeDescriptorNode intSecDescriptor = (IntersectionTypeDescriptorNode) typeDescriptor; + if (typeDescriptor instanceof IntersectionTypeDescriptorNode intSecDescriptor) { SyntaxKind left = intSecDescriptor.leftTypeDesc().kind(); SyntaxKind right = intSecDescriptor.rightTypeDesc().kind(); if (left == SyntaxKind.RECORD_TYPE_DESC || right == SyntaxKind.RECORD_TYPE_DESC) { @@ -454,8 +453,7 @@ public void visit(NamedArgumentNode namedArgumentNode) { * @return True if a readonly typeDescriptor is present, false otherwise. */ private boolean isReadonly(Node node) { - if (node instanceof IntersectionTypeDescriptorNode) { - IntersectionTypeDescriptorNode intSecDescriptor = (IntersectionTypeDescriptorNode) node; + if (node instanceof IntersectionTypeDescriptorNode intSecDescriptor) { SyntaxKind left = intSecDescriptor.leftTypeDesc().kind(); SyntaxKind right = intSecDescriptor.rightTypeDesc().kind(); return left == SyntaxKind.READONLY_TYPE_DESC || right == SyntaxKind.READONLY_TYPE_DESC; diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/signature/SignatureHelpUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/signature/SignatureHelpUtil.java index 54b9531e9e4b..0cb3bd8dc3f0 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/signature/SignatureHelpUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/signature/SignatureHelpUtil.java @@ -74,7 +74,6 @@ import java.util.Objects; import java.util.Optional; import java.util.function.Predicate; -import java.util.stream.Collectors; import javax.annotation.Nonnull; @@ -86,7 +85,7 @@ /** * Utility functions for the signature help. */ -public class SignatureHelpUtil { +public final class SignatureHelpUtil { private SignatureHelpUtil() { } @@ -281,7 +280,7 @@ private static Optional getFunctionSymbol(FunctionCallExpressi filteredContent = visibleSymbols.stream() .filter(symbolPredicate.and(symbol -> symbol.getName().isPresent() && symbol.getName().get().equals(funcName))) - .collect(Collectors.toList()); + .toList(); } return filteredContent.stream().findAny(); @@ -327,37 +326,29 @@ private static Optional getFunctionSymbol(Node nodeAtCursor, S } private static Optional getTypeDesc(SignatureContext ctx, ExpressionNode expr) { - switch (expr.kind()) { - case SIMPLE_NAME_REFERENCE: - /* - Captures the following - (1) fieldName - */ - return getTypeDescForNameRef(ctx, (SimpleNameReferenceNode) expr); - case FUNCTION_CALL: - /* - Captures the following - (1) functionName() - */ - return getTypeDescForFunctionCall(ctx, (FunctionCallExpressionNode) expr); - case METHOD_CALL: { - /* - Address the following - (1) test.testMethod() - */ - return getTypeDescForMethodCall(ctx, (MethodCallExpressionNode) expr); - } - case FIELD_ACCESS: { - /* - Address the following - (1) test1.test2 - */ - return getTypeDescForFieldAccess(ctx, (FieldAccessExpressionNode) expr); - } - - default: - return Optional.empty(); - } + return switch (expr.kind()) { + /* + Captures the following + (1) fieldName + */ + case SIMPLE_NAME_REFERENCE -> getTypeDescForNameRef(ctx, (SimpleNameReferenceNode) expr); + /* + Captures the following + (1) functionName() + */ + case FUNCTION_CALL -> getTypeDescForFunctionCall(ctx, (FunctionCallExpressionNode) expr); + /* + Address the following + (1) test.testMethod() + */ + case METHOD_CALL -> getTypeDescForMethodCall(ctx, (MethodCallExpressionNode) expr); + /* + Address the following + (1) test1.test2 + */ + case FIELD_ACCESS -> getTypeDescForFieldAccess(ctx, (FieldAccessExpressionNode) expr); + default -> Optional.empty(); + }; } private static Optional getTypeDescForFieldAccess( @@ -371,16 +362,17 @@ private static Optional getTypeDescForFieldAccess( } TypeSymbol rawType = CommonUtil.getRawType(typeDescriptor.get()); - switch (rawType.typeKind()) { - case OBJECT: + return switch (rawType.typeKind()) { + case OBJECT -> { ObjectFieldSymbol objField = ((ObjectTypeSymbol) rawType).fieldDescriptors().get(fieldName); - return objField != null ? Optional.of(objField.typeDescriptor()) : Optional.empty(); - case RECORD: + yield objField != null ? Optional.of(objField.typeDescriptor()) : Optional.empty(); + } + case RECORD -> { RecordFieldSymbol recField = ((RecordTypeSymbol) rawType).fieldDescriptors().get(fieldName); - return recField != null ? Optional.of(recField.typeDescriptor()) : Optional.empty(); - default: - return Optional.empty(); - } + yield recField != null ? Optional.of(recField.typeDescriptor()) : Optional.empty(); + } + default -> Optional.empty(); + }; } private static Optional getTypeDescForNameRef(SignatureContext context, diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/signature/SignatureInfoModelBuilder.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/signature/SignatureInfoModelBuilder.java index 9d297ba018b8..e1d49f380d99 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/signature/SignatureInfoModelBuilder.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/signature/SignatureInfoModelBuilder.java @@ -49,7 +49,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.stream.Collectors; +import java.util.stream.Stream; /** * A utility for building a SignatureInformation. @@ -182,14 +182,13 @@ private void fillParamInfoModels() { return; } - List parameters = parameterSymbols - .subList(skipFirstParam() ? 1 : 0, parameterSymbols.size()) - .stream() - .map(param -> new Parameter(param, false, false, context)) - .collect(Collectors.toList()); - Optional restParam = functionTypeSymbol.flatMap(FunctionTypeSymbol::restParam); - restParam.ifPresent(parameter -> parameters.add(new Parameter(parameter, false, true, context))); + List parameters = Stream.concat( + parameterSymbols.subList(skipFirstParam() ? 1 : 0, parameterSymbols.size()) + .stream() + .map(param -> new Parameter(param, false, false, context)), + restParam.stream().map(parameter -> new Parameter(parameter, false, true, context)) + ).toList(); // Create a list of param info models for (Parameter param : parameters) { @@ -200,7 +199,7 @@ private void fillParamInfoModels() { includedRecordParams = this.parameterModels.stream() .filter(ParameterInfoModel::isIncludedRecordParam) - .collect(Collectors.toList()); + .toList(); } /** diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/telemetry/TelemetryUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/telemetry/TelemetryUtil.java index fa672d4f64c2..2c94a2d05ea9 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/telemetry/TelemetryUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/telemetry/TelemetryUtil.java @@ -33,12 +33,15 @@ * * @since 2.0.0 */ -public class TelemetryUtil { +public final class TelemetryUtil { private static final String ARG_FEATURE_NAME = "feature.Name"; private static final String ARG_FEATURE_CLASS = "feature.Class"; private static final String ARG_FEATURE_TITLE = "feature.Title"; + private TelemetryUtil() { + } + /** * Sends the provided telemetry event to LS client. * diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/toml/ballerinatoml/completion/BallerinaTomlCompletionContext.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/toml/ballerinatoml/completion/BallerinaTomlCompletionContext.java index 2625db1e6f4c..852d551ba7bb 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/toml/ballerinatoml/completion/BallerinaTomlCompletionContext.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/toml/ballerinatoml/completion/BallerinaTomlCompletionContext.java @@ -44,7 +44,6 @@ import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.stream.Collectors; /** * Ballerina toml completion context. @@ -101,8 +100,7 @@ public List currentDocImports() { throw new RuntimeException("Cannot find a valid document"); } - return ((ModulePartNode) document.get().syntaxTree().rootNode()).imports().stream() - .collect(Collectors.toList()); + return ((ModulePartNode) document.get().syntaxTree().rootNode()).imports().stream().toList(); } @Override diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/toml/ballerinatoml/completion/BallerinaTomlCompletionUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/toml/ballerinatoml/completion/BallerinaTomlCompletionUtil.java index 2692920b0c5c..c41f9c5b1f1d 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/toml/ballerinatoml/completion/BallerinaTomlCompletionUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/toml/ballerinatoml/completion/BallerinaTomlCompletionUtil.java @@ -41,7 +41,10 @@ * * @since 2.0.0 */ -public class BallerinaTomlCompletionUtil { +public final class BallerinaTomlCompletionUtil { + + private BallerinaTomlCompletionUtil() { + } public static List getCompletionItems(TomlCompletionContext ctx, LanguageServerContext serverContext) { diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/util/LSClientUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/util/LSClientUtil.java index 8401c418fb64..0213760beeac 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/util/LSClientUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/util/LSClientUtil.java @@ -26,7 +26,7 @@ * * @since 2.0.0 */ -public class LSClientUtil { +public final class LSClientUtil { public static final String EXECUTE_COMMAND_CAPABILITY_ID = UUID.randomUUID().toString(); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/util/TestUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/util/TestUtil.java index d868abc6820b..14ae6cb5cac4 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/util/TestUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/util/TestUtil.java @@ -115,7 +115,7 @@ /** * Common utils that are reused within test suits. */ -public class TestUtil { +public final class TestUtil { private static final String HOVER = "textDocument/hover"; diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/workspace/BallerinaWorkspaceManager.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/workspace/BallerinaWorkspaceManager.java index 2592c9e0827b..2f5649c8af51 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/workspace/BallerinaWorkspaceManager.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/workspace/BallerinaWorkspaceManager.java @@ -277,7 +277,7 @@ public Optional document(Path filePath, @Nonnull CancelChecker cancelC * Returns syntax tree from the path provided. * * @param filePath file path of the document - * @return {@link io.ballerina.compiler.syntax.tree.SyntaxTree} + * @return {@link SyntaxTree} */ @Override public Optional syntaxTree(Path filePath) { @@ -1422,23 +1422,19 @@ private Optional document(Path filePath, Project project, @Nullable Ca private boolean hasDocumentOrToml(Path filePath, Project project) { String fileName = Optional.of(filePath.getFileName()).get().toString(); - switch (fileName) { - case ProjectConstants.BALLERINA_TOML: - return project.currentPackage().ballerinaToml().isPresent(); - case ProjectConstants.CLOUD_TOML: - return project.currentPackage().cloudToml().isPresent(); - case ProjectConstants.COMPILER_PLUGIN_TOML: - return project.currentPackage().compilerPluginToml().isPresent(); - case ProjectConstants.BAL_TOOL_TOML: - return project.currentPackage().balToolToml().isPresent(); - case ProjectConstants.DEPENDENCIES_TOML: - return project.currentPackage().dependenciesToml().isPresent(); - default: + return switch (fileName) { + case ProjectConstants.BALLERINA_TOML -> project.currentPackage().ballerinaToml().isPresent(); + case ProjectConstants.CLOUD_TOML -> project.currentPackage().cloudToml().isPresent(); + case ProjectConstants.COMPILER_PLUGIN_TOML -> project.currentPackage().compilerPluginToml().isPresent(); + case ProjectConstants.BAL_TOOL_TOML -> project.currentPackage().balToolToml().isPresent(); + case ProjectConstants.DEPENDENCIES_TOML -> project.currentPackage().dependenciesToml().isPresent(); + default -> { if (fileName.endsWith(ProjectConstants.BLANG_SOURCE_EXT)) { - return document(filePath, project, null).isPresent(); + yield document(filePath, project, null).isPresent(); } - return false; - } + yield false; + } + }; } private void reloadProject(ProjectContext projectContext, Path filePath, String operationName) { diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/codeaction/AbstractCodeActionTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/codeaction/AbstractCodeActionTest.java index 6f2b319580a5..6085b7680bdd 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/codeaction/AbstractCodeActionTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/codeaction/AbstractCodeActionTest.java @@ -17,13 +17,13 @@ */ package org.ballerinalang.langserver.codeaction; -import com.google.common.reflect.TypeToken; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; +import com.google.gson.reflect.TypeToken; import org.ballerinalang.langserver.AbstractLSTest; import org.ballerinalang.langserver.common.constants.CommandConstants; import org.ballerinalang.langserver.common.utils.PathUtil; @@ -52,7 +52,6 @@ import java.io.File; import java.io.IOException; -import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -62,7 +61,6 @@ import java.util.List; import java.util.Objects; import java.util.Optional; -import java.util.stream.Collectors; /** * Abstract test for code action related tests. @@ -99,7 +97,7 @@ public void test(String config) throws IOException, WorkspaceDocumentException { Range finalRange = range; diags = diags.stream() .filter(diag -> PositionUtil.isRangeWithinRange(finalRange, diag.getRange())) - .collect(Collectors.toList()); + .toList(); CodeActionContext codeActionContext = new CodeActionContext(diags); String res = getResponse(sourcePath, finalRange, codeActionContext); @@ -161,9 +159,7 @@ public void test(String config) throws IOException, WorkspaceDocumentException { .getAsJsonArray().get(0).getAsJsonObject().get("edits"); } - Type type = new TypeToken>() { - }.getType(); - List actualEdit = gson.fromJson(editsElement, type); + List actualEdit = gson.fromJson(editsElement, new TypeToken<>() { }); List expEdit = expected.edits; actual.edits = actualEdit; if (!expEdit.equals(actualEdit)) { @@ -195,7 +191,25 @@ public void test(String config) throws IOException, WorkspaceDocumentException { sourcePath, actual.edits, testConfig)) { misMatched = true; } - actual.command = actualCommand; + if (actualCommand.get("command").getAsString().equals("ADD_DOC")) { + JsonObject actualNodeRange = getNodeRange(actualArgs); + JsonObject expNodeRange = getNodeRange(expArgs); + assert actualNodeRange != null; + if (!actualNodeRange.equals(expNodeRange)) { + misMatched = true; + JsonArray newArgs = getNodeRangeArgument(actualArgs); + if (newArgs != null) { + JsonObject command = new JsonObject(); + command.add("title", actualCommand.get("title")); + command.add("command", actualCommand.get("command")); + command.add("arguments", getNodeRangeArgument(actualArgs)); + actual.command = command; + } + } + } + if (actual.command == null) { + actual.command = actualCommand; + } } } @@ -230,6 +244,31 @@ public void test(String config) throws IOException, WorkspaceDocumentException { } } + private JsonArray getNodeRangeArgument(JsonArray arguments) { + for (JsonElement arg : arguments) { + JsonObject argObj = arg.getAsJsonObject(); + if ("node.range".equals(argObj.get("key").getAsString())) { + JsonArray array = new JsonArray(1); + array.add(argObj); + return array; + } + } + return null; + } + + private JsonObject getNodeRange(JsonArray args) { + if (args == null) { + return null; + } + for (JsonElement arg : args) { + JsonObject argObj = arg.getAsJsonObject(); + if ("node.range".equals(argObj.get("key").getAsString())) { + return argObj.get("value").getAsJsonObject(); + } + } + return null; + } + public String getResponse(Path sourcePath, Range range, CodeActionContext codeActionContext) { return TestUtil.getCodeActionResponse(getServiceEndpoint(), sourcePath.toString(), range, codeActionContext); } @@ -258,7 +297,7 @@ public void negativeTest(String config) throws IOException, WorkspaceDocumentExc Range finalRange = range; diags = diags.stream() .filter(diag -> PositionUtil.isRangeWithinRange(finalRange, diag.getRange())) - .collect(Collectors.toList()); + .toList(); CodeActionContext codeActionContext = new CodeActionContext(diags); String res = TestUtil.getCodeActionResponse(endpoint, sourcePath.toString(), finalRange, codeActionContext); diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/codeaction/AddDocumentationTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/codeaction/AddDocumentationTest.java index 98e63b05a8ab..437363689374 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/codeaction/AddDocumentationTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/codeaction/AddDocumentationTest.java @@ -68,6 +68,22 @@ public Object[][] dataProvider() { {"serviceDocumentation1.json"}, // Already documented nodes {"documentAlreadyDocumentedConfig1.json"}, + {"singleDocGeneration13.json"}, + {"singleDocGeneration14.json"}, + {"singleDocGeneration15.json"}, + {"singleDocGeneration16.json"}, + {"singleDocGeneration17.json"}, + {"singleDocGeneration18.json"}, + {"singleDocGeneration19.json"}, + {"singleDocGeneration20.json"}, + {"singleDocGeneration21.json"}, + {"singleDocGeneration22.json"}, + {"singleDocGeneration23.json"}, + {"singleDocGeneration24.json"}, + {"singleDocGeneration25.json"}, + {"singleDocGeneration26.json"}, + {"singleDocGeneration27.json"}, + {"singleDocGeneration28.json"}, }; } diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/codeaction/AddModuleToBallerinaTomlCodeActionTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/codeaction/AddModuleToBallerinaTomlCodeActionTest.java index ab0940c21d44..9e2074ff8f58 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/codeaction/AddModuleToBallerinaTomlCodeActionTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/codeaction/AddModuleToBallerinaTomlCodeActionTest.java @@ -36,7 +36,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -import java.util.stream.Collectors; /** * Test class to test module addition to Ballerina.toml. @@ -45,6 +44,7 @@ */ public class AddModuleToBallerinaTomlCodeActionTest extends AbstractCodeActionTest { + @Override protected void setupLanguageServer(TestUtil.LanguageServerBuilder builder) { builder.withInitOption(InitializationOptions.KEY_POSITIONAL_RENAME_SUPPORT, true); } @@ -62,7 +62,7 @@ public void setup() { "x.y", "main.bal"); List localPackages = getLocalPackages(localProjects, languageServer.getWorkspaceManager(), context).stream().map(LSPackageLoader.ModuleInfo::new) - .collect(Collectors.toList()); + .toList(); Mockito.when(getLSPackageLoader().getLocalRepoModules()).thenReturn(localPackages); } catch (Exception e) { //ignore diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/codelenses/CodeLensTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/codelenses/CodeLensTest.java index 75776ad1006e..4e5e3095ebc5 100755 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/codelenses/CodeLensTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/codelenses/CodeLensTest.java @@ -45,7 +45,6 @@ public class CodeLensTest { private final Path functionsBalPath = FileUtils.RES_DIR.resolve("codelens").resolve("functions.bal"); private Endpoint serviceEndpoint; - private static final JsonParser JSON_PARSER = new JsonParser(); private static final Logger log = LoggerFactory.getLogger(CodeLensTest.class); private static final Gson GSON = new Gson(); @@ -65,9 +64,9 @@ private void testCodeLenses(String expectedConfigName, String response) throws I String expected = getExpectedValue(expectedConfigName); List expectedItemList = getFlattenItemList( - JSON_PARSER.parse(expected).getAsJsonObject().getAsJsonArray("result")); + JsonParser.parseString(expected).getAsJsonObject().getAsJsonArray("result")); List responseItemList = getFlattenItemList( - JSON_PARSER.parse(response).getAsJsonObject().getAsJsonArray("result")); + JsonParser.parseString(response).getAsJsonObject().getAsJsonArray("result")); boolean isSubList = getStringListForEvaluation(responseItemList).containsAll( getStringListForEvaluation(expectedItemList)); diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/command/AbstractCommandExecutionTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/command/AbstractCommandExecutionTest.java index d85ac4a46fd1..d82e1561def5 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/command/AbstractCommandExecutionTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/command/AbstractCommandExecutionTest.java @@ -48,8 +48,6 @@ public abstract class AbstractCommandExecutionTest { private final Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); - private final JsonParser parser = new JsonParser(); - private final Path resourcesPath = new File(getClass().getClassLoader().getResource("command").getFile()).toPath(); private static final Logger log = LoggerFactory.getLogger(AbstractCommandExecutionTest.class); @@ -114,19 +112,19 @@ public void cleanupLanguageServer() { TestUtil.shutdownLanguageServer(this.serviceEndpoint); } - private List argsToJson(List args) { - List jsonArgs = new ArrayList<>(); + private List argsToJson(List args) { + List jsonArgs = new ArrayList<>(); for (Object arg : args) { - jsonArgs.add((JsonObject) gson.toJsonTree(arg)); + jsonArgs.add(gson.toJsonTree(arg)); } return jsonArgs; } private JsonObject getCommandResponse(List args, String command) { - List argsList = argsToJson(args); + List argsList = argsToJson(args); ExecuteCommandParams params = new ExecuteCommandParams(command, argsList); String response = TestUtil.getExecuteCommandResponse(params, this.serviceEndpoint).replace("\\r\\n", "\\n"); - JsonObject responseJson = parser.parse(response).getAsJsonObject(); + JsonObject responseJson = JsonParser.parseString(response).getAsJsonObject(); responseJson.remove("id"); return responseJson; } diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/command/PullModuleExecutorTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/command/PullModuleExecutorTest.java index 3946a47193fb..1a32c928260b 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/command/PullModuleExecutorTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/command/PullModuleExecutorTest.java @@ -56,7 +56,6 @@ public class PullModuleExecutorTest { private Endpoint serviceEndpoint; private final Gson gson = new Gson(); - private final JsonParser parser = new JsonParser(); private final Path sourcesDir = new File(getClass().getClassLoader() .getResource("command").getFile()).toPath(); @@ -124,19 +123,19 @@ public void teardown() { } private JsonObject getCommandResponse(List args, String command) { - List argsList = argsToJson(args); + List argsList = argsToJson(args); ExecuteCommandParams params = new ExecuteCommandParams(command, argsList); String response = TestUtil.getExecuteCommandResponse(params, this.serviceEndpoint) .replace("\\r\\n", "\\n"); - JsonObject responseJson = parser.parse(response).getAsJsonObject(); + JsonObject responseJson = JsonParser.parseString(response).getAsJsonObject(); responseJson.remove("id"); return responseJson; } - private List argsToJson(List args) { - List jsonArgs = new ArrayList<>(); + private List argsToJson(List args) { + List jsonArgs = new ArrayList<>(); for (Object arg : args) { - jsonArgs.add((JsonObject) gson.toJsonTree(arg)); + jsonArgs.add(gson.toJsonTree(arg)); } return jsonArgs; } diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/completion/ActionNodeContextTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/completion/ActionNodeContextTest.java index 3871cb26fd33..6679b2413ef2 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/completion/ActionNodeContextTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/completion/ActionNodeContextTest.java @@ -28,6 +28,7 @@ */ public class ActionNodeContextTest extends CompletionTest { + @Override @Test(dataProvider = "completion-data-provider") public void test(String config, String configPath) throws IOException, WorkspaceDocumentException { super.test(config, configPath); diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/completion/CompletionTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/completion/CompletionTest.java index dd7a837dac8d..318a17739c6c 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/completion/CompletionTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/completion/CompletionTest.java @@ -40,12 +40,12 @@ import java.io.File; import java.io.IOException; -import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; +import java.util.stream.Stream; /** * Completion Test Interface. @@ -67,10 +67,8 @@ public void test(String config, String configPath) throws WorkspaceDocumentExcep TestConfig testConfig = gson.fromJson(Files.newBufferedReader(configJsonPath), TestConfig.class); String response = getResponse(testConfig); JsonObject json = JsonParser.parseString(response).getAsJsonObject(); - Type collectionType = new TypeToken>() { - }.getType(); JsonArray resultList = json.getAsJsonObject("result").getAsJsonArray("left"); - List responseItemList = gson.fromJson(resultList, collectionType); + List responseItemList = gson.fromJson(resultList, new TypeToken<>() { }); boolean result = CompletionTestUtil.isSubList(testConfig.getItems(), responseItemList); if (!result) { @@ -124,9 +122,9 @@ protected Object[][] getConfigsList() { return this.testSubset(); } List skippedTests = this.skipList(); - try { - return Files.walk(this.testRoot.resolve(this.getTestResourceDir()).resolve(this.configDir)) - .filter(path -> { + try (Stream configPaths = Files.walk( + this.testRoot.resolve(this.getTestResourceDir()).resolve(this.configDir))) { + return configPaths.filter(path -> { File file = path.toFile(); return file.isFile() && file.getName().endsWith(".json") && !skippedTests.contains(file.getName()); diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/completion/FunctionDefinitionTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/completion/FunctionDefinitionTest.java index 1b567be56ce5..0322e045a33d 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/completion/FunctionDefinitionTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/completion/FunctionDefinitionTest.java @@ -35,6 +35,7 @@ public Object[][] dataProvider() { return this.getConfigsList(); } + @Override @Test(dataProvider = "completion-data-provider") public void test(String config, String configPath) throws IOException, WorkspaceDocumentException { super.test(config, configPath); diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/completion/util/CompletionTestUtil.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/completion/util/CompletionTestUtil.java index 77204e8a7116..84a92a13c08e 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/completion/util/CompletionTestUtil.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/completion/util/CompletionTestUtil.java @@ -27,10 +27,13 @@ /** * Message utils for manipulating the Message objects. */ -public class CompletionTestUtil { +public final class CompletionTestUtil { private static final Gson GSON = new Gson(); + private CompletionTestUtil() { + } + private static String getCompletionItemPropertyString(CompletionItem completionItem) { // TODO: Need to add kind and sort text as well diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/definition/BalaSchemeDefinitionTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/definition/BalaSchemeDefinitionTest.java index 3b9b74f9afec..72245f466ab5 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/definition/BalaSchemeDefinitionTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/definition/BalaSchemeDefinitionTest.java @@ -31,17 +31,20 @@ */ public class BalaSchemeDefinitionTest extends DefinitionTest { + @Override @Test(description = "Test goto definitions", dataProvider = "testDataProvider") public void test(String configPath, String configDir) throws IOException { super.test(configPath, configDir); } + @Override @Test(description = "Test goto definitions for standard libs", dataProvider = "testStdLibDataProvider") public void testStdLibDefinition(String configPath, String configDir) throws IOException, URISyntaxException { super.testStdLibDefinition(configPath, configDir); } + @Override @Test(dataProvider = "testInterStdLibDataProvider") public void testInterStdLibDefinition(String configPath, String configDir) throws IOException, URISyntaxException { super.testInterStdLibDefinition(configPath, configDir); diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/definition/DefinitionTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/definition/DefinitionTest.java index 892cafafd8af..86fc3a8d2627 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/definition/DefinitionTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/definition/DefinitionTest.java @@ -153,6 +153,12 @@ protected Object[][] testDataProvider() throws IOException { {"def_typereference2.json", "project"}, {"def_typereference3.json", "project"}, {"defProject15.json", "project"}, + {"defProject16.json", "project"}, + {"defProject17.json", "project"}, + {"defProject18.json", "project"}, + {"defProject19.json", "project"}, + {"defProject19.json", "project"}, + {"defProject20.json", "project"} }; } diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/diagnostics/DiagnosticsTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/diagnostics/DiagnosticsTest.java index b23317156dd5..6de36e491d62 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/diagnostics/DiagnosticsTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/diagnostics/DiagnosticsTest.java @@ -62,8 +62,6 @@ public class DiagnosticsTest { private final Path testRoot = FileUtils.RES_DIR.resolve("diagnostics"); - private final JsonParser parser = new JsonParser(); - private final Gson gson = new Gson(); private final LanguageServerContext serverContext = new LanguageServerContextImpl(); @@ -82,7 +80,7 @@ public void test(String config) throws IOException, WorkspaceDocumentException { JsonObject configJsonObject = FileUtils.fileContentAsObject(configJsonPath); String response = this.getResponse(configJsonObject); - JsonObject responseJson = parser.parse(response).getAsJsonObject(); + JsonObject responseJson = JsonParser.parseString(response).getAsJsonObject(); JsonObject responseDiags = unifyResponse(responseJson); JsonObject expectedDiags = configJsonObject.get("items").getAsJsonObject(); diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/docsymbol/DocumentSymbolTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/docsymbol/DocumentSymbolTest.java index 6c36d683ab88..b66580ec5896 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/docsymbol/DocumentSymbolTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/docsymbol/DocumentSymbolTest.java @@ -45,8 +45,6 @@ public class DocumentSymbolTest { private Endpoint serviceEndpoint; - private JsonParser parser = new JsonParser(); - private Path sourcesPath = new File(getClass().getClassLoader().getResource("docsymbol").getFile()).toPath(); private static final Logger log = LoggerFactory.getLogger(DocumentSymbolTest.class); @@ -64,7 +62,7 @@ public void testDocumentSymbol(String config, String source) throws IOException JsonObject configJsonObject = FileUtils.fileContentAsObject(configJsonPath); JsonObject expected = configJsonObject.get("expected").getAsJsonObject(); String response = TestUtil.getDocumentSymbolResponse(this.serviceEndpoint, sourcePath.toString()); - JsonObject jsonResponse = parser.parse(response).getAsJsonObject(); + JsonObject jsonResponse = JsonParser.parseString(response).getAsJsonObject(); JsonArray result = jsonResponse.getAsJsonArray("result"); TestUtil.closeDocument(serviceEndpoint, sourcePath); for (JsonElement element : result) { diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/documentsymbol/DocumentSymbolTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/documentsymbol/DocumentSymbolTest.java index 01af75a463c7..78541ec5480a 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/documentsymbol/DocumentSymbolTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/documentsymbol/DocumentSymbolTest.java @@ -24,7 +24,6 @@ public class DocumentSymbolTest { private Path configRoot; private Path sourceRoot; protected Gson gson = new Gson(); - protected JsonParser parser = new JsonParser(); protected Endpoint serviceEndpoint; @BeforeClass @@ -44,7 +43,7 @@ public void test(String configPath) throws IOException { String response = TestUtil.getDocumentSymbolResponse(serviceEndpoint, sourcePath.toString()); TestUtil.closeDocument(serviceEndpoint, sourcePath); JsonArray expected = resultJson.getAsJsonArray("result"); - JsonArray actual = parser.parse(response).getAsJsonObject().getAsJsonArray("result"); + JsonArray actual = JsonParser.parseString(response).getAsJsonObject().getAsJsonArray("result"); Assert.assertEquals(actual, expected); } diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/execpositions/ExecutorPositionsTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/execpositions/ExecutorPositionsTest.java index 8b8416a66797..b342fe381ac7 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/execpositions/ExecutorPositionsTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/execpositions/ExecutorPositionsTest.java @@ -50,8 +50,6 @@ public class ExecutorPositionsTest { private static final String RANGE = "range"; private static final String START_LINE = "startLine"; - private static final JsonParser JSON_PARSER = new JsonParser(); - private Path resourceRoot; private Endpoint serviceEndpoint; @@ -82,8 +80,8 @@ private void compareResponse(String expected, String response) { Path expectedPath = this.resourceRoot.resolve("expected").resolve(expected + ".json"); JsonArray expectedJsonArray = FileUtils.fileContentAsObject(expectedPath.toAbsolutePath().toString()).getAsJsonArray(EXEC_POSITIONS); - JsonArray actualJsonArray = - JSON_PARSER.parse(response).getAsJsonObject().getAsJsonObject("result").getAsJsonArray(EXEC_POSITIONS); + JsonArray actualJsonArray = JsonParser.parseString(response) + .getAsJsonObject().getAsJsonObject("result").getAsJsonArray(EXEC_POSITIONS); actualJsonArray.forEach(jsonExec -> { JsonPrimitive name = jsonExec.getAsJsonObject().getAsJsonPrimitive(NAME); List execObjects = new ArrayList<>(); diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/extensions/LSExtensionTestUtil.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/extensions/LSExtensionTestUtil.java index 9e22a9d84d02..37a1a18b5e0e 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/extensions/LSExtensionTestUtil.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/extensions/LSExtensionTestUtil.java @@ -59,7 +59,7 @@ /** * Provides util methods for testing lang-server extension apis. */ -public class LSExtensionTestUtil { +public final class LSExtensionTestUtil { private static final String AST = "ballerinaDocument/syntaxTree"; private static final String SYNTAX_TREE_MODIFY = "ballerinaDocument/syntaxTreeModify"; @@ -76,7 +76,9 @@ public class LSExtensionTestUtil { private static final String GET_NODE_DEFINITION_BY_POSITION = "ballerinaDocument/syntaxTreeNodeByPosition"; private static final Gson GSON = new Gson(); - private static final JsonParser parser = new JsonParser(); + + private LSExtensionTestUtil() { + } /** * Get the ballerinaDocument/syntaxTree modification response. @@ -91,7 +93,7 @@ public static BallerinaSyntaxTreeResponse modifyAndGetBallerinaSyntaxTree(String Endpoint serviceEndpoint) { BallerinaSyntaxTreeModifyRequest astModifyRequest = new BallerinaSyntaxTreeModifyRequest( TestUtil.getTextDocumentIdentifier(filePath), astModifications); - CompletableFuture result = serviceEndpoint.request(SYNTAX_TREE_MODIFY, astModifyRequest); + CompletableFuture result = serviceEndpoint.request(SYNTAX_TREE_MODIFY, astModifyRequest); return GSON.fromJson(getResult(result), BallerinaSyntaxTreeResponse.class); } @@ -105,7 +107,7 @@ public static BallerinaSyntaxTreeResponse modifyAndGetBallerinaSyntaxTree(String public static BallerinaSyntaxTreeResponse getBallerinaSyntaxTree(String filePath, Endpoint serviceEndpoint) { BallerinaSyntaxTreeRequest astRequest = new BallerinaSyntaxTreeRequest( TestUtil.getTextDocumentIdentifier(filePath)); - CompletableFuture result = serviceEndpoint.request(AST, astRequest); + CompletableFuture result = serviceEndpoint.request(AST, astRequest); return GSON.fromJson(getResult(result), BallerinaSyntaxTreeResponse.class); } @@ -123,7 +125,7 @@ public static BallerinaSyntaxTreeResponse getBallerinaSyntaxTreeByRange(String f BallerinaSyntaxTreeByRangeRequest request = new BallerinaSyntaxTreeByRangeRequest(); request.setDocumentIdentifier(TestUtil.getTextDocumentIdentifier(filePath)); request.setLineRange(range); - CompletableFuture result = serviceEndpoint.request(SYNTAX_TREE_BY_RANGE, request); + CompletableFuture result = serviceEndpoint.request(SYNTAX_TREE_BY_RANGE, request); return GSON.fromJson(getResult(result), BallerinaSyntaxTreeResponse.class); } @@ -140,7 +142,7 @@ public static BallerinaSyntaxTreeResponse getBallerinaSyntaxTreeLocate(String fi Endpoint serviceEndpoint) { BallerinaSyntaxTreeByRangeRequest request = new BallerinaSyntaxTreeByRangeRequest( TestUtil.getTextDocumentIdentifier(filePath), range); - CompletableFuture result = serviceEndpoint.request(SYNTAX_TREE_LOCATE, request); + CompletableFuture result = serviceEndpoint.request(SYNTAX_TREE_LOCATE, request); return GSON.fromJson(getResult(result), BallerinaSyntaxTreeResponse.class); } @@ -174,23 +176,23 @@ public static BallerinaSyntaxTreeResponse getBallerinaSyntaxTreeByName(String fi BallerinaSyntaxTreeByNameRequest request = new BallerinaSyntaxTreeByNameRequest(); request.setDocumentIdentifier(TestUtil.getTextDocumentIdentifier(filePath)); request.setLineRange(range); - CompletableFuture result = serviceEndpoint.request(SYNTAX_TREE_BY_NAME, request); + CompletableFuture result = serviceEndpoint.request(SYNTAX_TREE_BY_NAME, request); return GSON.fromJson(getResult(result), BallerinaSyntaxTreeResponse.class); } - private static JsonObject getResult(CompletableFuture result) { - return parser.parse(TestUtil.getResponseString(result)).getAsJsonObject().getAsJsonObject("result"); + private static JsonObject getResult(CompletableFuture result) { + return JsonParser.parseString(TestUtil.getResponseString(result)).getAsJsonObject().getAsJsonObject("result"); } public static BallerinaConnectorListResponse getConnectors(BallerinaConnectorListRequest request, Endpoint serviceEndpoint) { - CompletableFuture result = serviceEndpoint.request(GET_CONNECTORS, request); + CompletableFuture result = serviceEndpoint.request(GET_CONNECTORS, request); return GSON.fromJson(getResult(result), BallerinaConnectorListResponse.class); } public static JsonObject getConnectorById(String id, Endpoint serviceEndpoint) { BallerinaConnectorRequest connectorRequest = new BallerinaConnectorRequest(id); - CompletableFuture result = serviceEndpoint.request(GET_CONNECTOR, connectorRequest); + CompletableFuture result = serviceEndpoint.request(GET_CONNECTOR, connectorRequest); return getResult(result); } @@ -205,7 +207,7 @@ public static JsonObject getConnectorByFqn(String org, String packageName, Strin String name, Endpoint serviceEndpoint) { BallerinaConnectorRequest connectorRequest = new BallerinaConnectorRequest(org, packageName, module, version, name); - CompletableFuture result = serviceEndpoint.request(GET_CONNECTOR, connectorRequest); + CompletableFuture result = serviceEndpoint.request(GET_CONNECTOR, connectorRequest); return getResult(result); } @@ -230,7 +232,7 @@ public static SymbolInfoResponse getSymbolDocumentation(String filePath, Positio SymbolInfoRequest symbolInfoRequest = new SymbolInfoRequest(); symbolInfoRequest.setPosition(position); symbolInfoRequest.setTextDocumentIdentifier(TestUtil.getTextDocumentIdentifier(filePath)); - CompletableFuture result = serviceEndpoint.request(GET_SYMBOL, symbolInfoRequest); + CompletableFuture result = serviceEndpoint.request(GET_SYMBOL, symbolInfoRequest); return GSON.fromJson(getResult(result), SymbolInfoResponse.class); } diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/extensions/symbol/SymbolServiceTestUtil.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/extensions/symbol/SymbolServiceTestUtil.java index 9c613ddbcf0b..4de9ae94ebb7 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/extensions/symbol/SymbolServiceTestUtil.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/extensions/symbol/SymbolServiceTestUtil.java @@ -21,7 +21,7 @@ /** * Provides util methods for testing symbol service apis. */ -public class SymbolServiceTestUtil { +public final class SymbolServiceTestUtil { public static final String INTEGER = "int"; public static final String STRING = "string"; @@ -34,6 +34,9 @@ public class SymbolServiceTestUtil { public static final String INTERSECTION = "intersection"; public static final String READ_ONLY = "readonly"; + private SymbolServiceTestUtil() { + } + public static boolean isPositionsEquals(LinePosition expectedPosition, LinePosition actualPosition) { return expectedPosition.line() == actualPosition.line() && expectedPosition.offset() == actualPosition.offset(); diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/foldingrange/LineFoldingOnlyTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/foldingrange/LineFoldingOnlyTest.java index 2bcfaf47f444..e4636c6fb6d5 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/foldingrange/LineFoldingOnlyTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/foldingrange/LineFoldingOnlyTest.java @@ -35,8 +35,6 @@ */ public class LineFoldingOnlyTest { - private static final JsonParser JSON_PARSER = new JsonParser(); - private final Path resourcesPath = new File(getClass().getClassLoader().getResource("foldingrange").getFile()).toPath(); private Endpoint serviceEndpoint; @@ -64,7 +62,7 @@ private void compareResponse(String expected, String response) { Path expectedPath = resourcesPath.resolve("expected").resolve(expected); JsonArray expectedJsonArray = FileUtils.fileContentAsObject(expectedPath.toAbsolutePath().toString()).getAsJsonArray("result"); - JsonArray responseJsonArray = JSON_PARSER.parse(response).getAsJsonObject().getAsJsonArray("result"); + JsonArray responseJsonArray = JsonParser.parseString(response).getAsJsonObject().getAsJsonArray("result"); Assert.assertEquals(responseJsonArray, expectedJsonArray, "LineFoldingOnlyTest fails with " + expected + " test case."); } diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/formatting/FormattingTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/formatting/FormattingTest.java index 9b9fb900e2bf..b55dfc53d271 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/formatting/FormattingTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/formatting/FormattingTest.java @@ -71,7 +71,7 @@ public void formatTestSuit() throws IOException { String result = TestUtil.getFormattingResponse(documentFormattingParams, this.serviceEndpoint); Gson gson = new Gson(); ResponseMessage responseMessage = gson.fromJson(result, ResponseMessage.class); - String actual = (String) ((LinkedTreeMap) ((List) responseMessage.getResult()).get(0)).get("newText"); + String actual = (String) ((LinkedTreeMap) ((List) responseMessage.getResult()).get(0)).get("newText"); actual = actual.replaceAll("\\r\\n", "\n"); TestUtil.closeDocument(this.serviceEndpoint, inputFilePath); Assert.assertEquals(actual, expected); @@ -101,7 +101,7 @@ public void formatTestSuiteWithConfigurations() throws IOException { String result = TestUtil.getFormattingResponse(documentFormattingParams, this.serviceEndpoint); Gson gson = new Gson(); ResponseMessage responseMessage = gson.fromJson(result, ResponseMessage.class); - String actual = (String) ((LinkedTreeMap) ((List) responseMessage.getResult()).get(0)).get("newText"); + String actual = (String) ((LinkedTreeMap) ((List) responseMessage.getResult()).get(0)).get("newText"); actual = actual.replaceAll("\\r\\n", "\n"); TestUtil.closeDocument(this.serviceEndpoint, inputFilePath); Assert.assertEquals(actual, expected); diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/hover/HoverPerformanceTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/hover/HoverPerformanceTest.java index 66392bc5f024..c57630a0c4ad 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/hover/HoverPerformanceTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/hover/HoverPerformanceTest.java @@ -39,6 +39,7 @@ public class HoverPerformanceTest extends HoverProviderTest { private final List executionTimes = new ArrayList<>(); + @Override @Test(description = "Test Hover provider", dataProvider = "hover-data-provider", enabled = false) public void testHover(String config) throws IOException { // We run the same test multiple times and take the average of them as the execution time. This is to diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/hover/HoverProviderTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/hover/HoverProviderTest.java index 10deceb73e9f..2027c03ed733 100755 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/hover/HoverProviderTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/hover/HoverProviderTest.java @@ -34,6 +34,7 @@ import java.nio.file.Path; import java.util.Arrays; import java.util.List; +import java.util.stream.Stream; /** * Test hover feature in language server. @@ -87,9 +88,8 @@ protected Object[][] dataProvider() { return this.testSubset(); } List skippedTests = this.skipList(); - try { - return Files.walk(FileUtils.RES_DIR.resolve("hover").resolve("configs")) - .filter(path -> { + try (Stream configPaths = Files.walk(FileUtils.RES_DIR.resolve("hover").resolve("configs"))) { + return configPaths.filter(path -> { File file = path.toFile(); return file.isFile() && file.getName().endsWith(".json") && !skippedTests.contains(file.getName()); diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/implementation/GotoImplementationTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/implementation/GotoImplementationTest.java index eae0d42f1368..3735c4b75bb8 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/implementation/GotoImplementationTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/implementation/GotoImplementationTest.java @@ -42,7 +42,6 @@ public class GotoImplementationTest { private Endpoint serviceEndpoint; private String configRoot = "implementation" + CommonUtil.FILE_SEPARATOR + "expected"; - private JsonParser jsonParser = new JsonParser(); private static final Logger log = LoggerFactory.getLogger(GotoImplementationTest.class); @BeforeClass @@ -60,7 +59,7 @@ public void testGotoImplementation(String configPath, String source) { JsonObject position = configJsonObject.getAsJsonObject("position"); Position cursor = new Position(position.get("line").getAsInt(), position.get("col").getAsInt()); String response = TestUtil.getGotoImplementationResponse(serviceEndpoint, sourcePath.toString(), cursor); - JsonObject responseJson = jsonParser.parse(response).getAsJsonObject(); + JsonObject responseJson = JsonParser.parseString(response).getAsJsonObject(); responseJson.getAsJsonArray("result").forEach(jsonElement -> jsonElement.getAsJsonObject().remove("uri")); JsonObject expected = configJsonObject.getAsJsonObject("expected"); Assert.assertEquals(expected, responseJson, "Test Failed for" + configPath); diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/inlayhint/InlayHintTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/inlayhint/InlayHintTest.java index 1a4ec6c8cdd6..598e88b114b8 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/inlayhint/InlayHintTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/inlayhint/InlayHintTest.java @@ -15,12 +15,12 @@ */ package org.ballerinalang.langserver.inlayhint; -import com.google.common.reflect.TypeToken; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; +import com.google.gson.reflect.TypeToken; import org.ballerinalang.langserver.AbstractLSTest; import org.ballerinalang.langserver.commons.workspace.WorkspaceDocumentException; import org.ballerinalang.langserver.util.FileUtils; @@ -38,12 +38,12 @@ import java.io.File; import java.io.IOException; -import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; +import java.util.stream.Stream; /** * Test class for inlay hints. @@ -71,13 +71,11 @@ public void test(String config, String source) throws WorkspaceDocumentException inlayHintParams.setTextDocument(textDocumentIdentifier); Range range = testConfig.range; - Type collectionType = new TypeToken>() { - }.getType(); String response = getResponse(sourcePath.toString(), range, sourcePath.toString()); JsonObject json = JsonParser.parseString(response).getAsJsonObject(); JsonArray resultList = json.getAsJsonArray("result"); - List responseItemList = gson.fromJson(resultList, collectionType); + List responseItemList = gson.fromJson(resultList, new TypeToken<>() { }); if (responseItemList.size() != testConfig.getResult().size()) { // updateConfig(configPath, testConfig, responseItemList); @@ -200,9 +198,8 @@ protected Object[][] getConfigsList() { return this.testSubset(); } List skippedTests = this.skipList(); - try { - return Files.walk(this.testRoot.resolve("config")) - .filter(path -> { + try (Stream configPaths = Files.walk(this.testRoot.resolve("config"))) { + return configPaths.filter(path -> { File file = path.toFile(); return file.isFile() && file.getName().endsWith(".json") && !skippedTests.contains(file.getName()); diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/lspackageloader/LSPackageLoaderTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/lspackageloader/LSPackageLoaderTest.java index 5389476f2b13..33ee64c67167 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/lspackageloader/LSPackageLoaderTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/lspackageloader/LSPackageLoaderTest.java @@ -43,7 +43,7 @@ import java.util.Optional; /** - * Tests {@link org.ballerinalang.langserver.LSPackageLoader}. + * Tests {@link LSPackageLoader}. * * @since 2201.2.1 */ diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/packages/ComponentsTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/packages/ComponentsTest.java index eeaf2c24a8f8..82bd3a898557 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/packages/ComponentsTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/packages/ComponentsTest.java @@ -43,7 +43,6 @@ public class ComponentsTest { private static final String NAME = "name"; private static final String MODULES = "modules"; - private static final JsonParser JSON_PARSER = new JsonParser(); private static final Gson GSON = new Gson(); private Path resourceRoot; @@ -79,7 +78,7 @@ private void compareResponse(String expected, String response) { JsonArray expectedJsonArray = FileUtils.fileContentAsObject(expectedPath.toAbsolutePath().toString()).getAsJsonArray("result"); JsonArray responseJsonArray = - JSON_PARSER.parse(response).getAsJsonObject().getAsJsonObject("result").getAsJsonArray("packages"); + JsonParser.parseString(response).getAsJsonObject().getAsJsonObject("result").getAsJsonArray("packages"); Assert.assertEquals(responseJsonArray.size(), expectedJsonArray.size(), "Package ComponentsTest fails with " + "incorrect package count."); diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/packages/ConfigSchemaTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/packages/ConfigSchemaTest.java index 5abe71c18e26..29843aa4c28c 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/packages/ConfigSchemaTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/packages/ConfigSchemaTest.java @@ -33,7 +33,6 @@ * Tests Package Config Schema API in Language Server. */ public class ConfigSchemaTest { - private static final JsonParser JSON_PARSER = new JsonParser(); private Path resourceRoot; private Endpoint serviceEndpoint; diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/packages/MetadataTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/packages/MetadataTest.java index ec75c19216d1..9f584187ee57 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/packages/MetadataTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/packages/MetadataTest.java @@ -39,7 +39,6 @@ public class MetadataTest { private static final String PACKAGE_NAME = "packageName"; private static final String PATH = "path"; private static final String KIND = "kind"; - private static final JsonParser JSON_PARSER = new JsonParser(); private Path resourceRoot; private Endpoint serviceEndpoint; @@ -68,7 +67,7 @@ private void compareResponse(String projectName, String response) { Path expectedPath = this.resourceRoot.resolve("metadata").resolve(projectName); JsonObject expectedJsonObject = FileUtils.fileContentAsObject(expectedPath.toAbsolutePath().toString()).getAsJsonObject(); - JsonObject responseJsonObject = JSON_PARSER.parse(response).getAsJsonObject().getAsJsonObject("result"); + JsonObject responseJsonObject = JsonParser.parseString(response).getAsJsonObject().getAsJsonObject("result"); JsonPrimitive packageName = expectedJsonObject.getAsJsonPrimitive(PACKAGE_NAME); if (packageName != null) { Assert.assertEquals(responseJsonObject.getAsJsonPrimitive(PACKAGE_NAME), packageName, diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/rangeformat/RangeFormattingTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/rangeformat/RangeFormattingTest.java index 7eee591221bc..ec97503350e7 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/rangeformat/RangeFormattingTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/rangeformat/RangeFormattingTest.java @@ -77,7 +77,7 @@ public void formatTestSuit() throws IOException { String result = TestUtil.getRangeFormatResponse(params, this.serviceEndpoint); Gson gson = new Gson(); ResponseMessage responseMessage = gson.fromJson(result, ResponseMessage.class); - String actual = (String) ((LinkedTreeMap) ((List) responseMessage.getResult()).get(0)).get("newText"); + String actual = (String) ((LinkedTreeMap) ((List) responseMessage.getResult()).get(0)).get("newText"); actual = actual.replaceAll("\\r\\n", "\n"); TestUtil.closeDocument(this.serviceEndpoint, inputFilePath); Assert.assertEquals(actual, expected); diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/references/BalaSchemeReferencesTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/references/BalaSchemeReferencesTest.java index e94c676ff314..e0f1eeae5533 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/references/BalaSchemeReferencesTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/references/BalaSchemeReferencesTest.java @@ -31,11 +31,13 @@ */ public class BalaSchemeReferencesTest extends ReferencesTest { + @Override @Test(description = "Test reference", dataProvider = "testDataProvider") public void test(String configPath) throws IOException { super.test(configPath); } + @Override @Test(dataProvider = "testReferencesWithinStdLibDataProvider") public void testReferencesWithinStdLib(String configPath) throws IOException, URISyntaxException { super.testReferencesWithinStdLib(configPath); diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/references/ReferenceTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/references/ReferenceTest.java index 77134e2e91b3..5f8074be871c 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/references/ReferenceTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/references/ReferenceTest.java @@ -46,7 +46,6 @@ public class ReferenceTest { private Path configRoot; private Path sourceRoot; protected Gson gson = new Gson(); - protected JsonParser parser = new JsonParser(); protected Endpoint serviceEndpoint; @BeforeClass @@ -69,7 +68,7 @@ public void test(String configPath, String configDir) throws IOException { TestUtil.closeDocument(serviceEndpoint, sourcePath); JsonArray expected = configObject.getAsJsonArray("result"); - JsonArray actual = parser.parse(actualStr).getAsJsonObject().getAsJsonArray("result"); + JsonArray actual = JsonParser.parseString(actualStr).getAsJsonObject().getAsJsonArray("result"); this.alterExpectedUri(expected); this.alterActualUri(actual); Assert.assertEquals(actual, expected); diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/references/ReferencesTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/references/ReferencesTest.java index 44dec980d932..9e48e3a4a0ed 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/references/ReferencesTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/references/ReferencesTest.java @@ -52,7 +52,6 @@ public class ReferencesTest { protected Path configRoot; protected Path sourceRoot; protected Gson gson = new Gson(); - protected JsonParser parser = new JsonParser(); protected Endpoint serviceEndpoint; private static final Logger log = LoggerFactory.getLogger(ReferencesTest.class); @@ -75,7 +74,7 @@ public void test(String configPath) throws IOException { TestUtil.closeDocument(serviceEndpoint, sourcePath); JsonArray expected = configObject.getAsJsonArray("result"); - JsonArray actual = parser.parse(actualStr).getAsJsonObject().get("result").getAsJsonArray(); + JsonArray actual = JsonParser.parseString(actualStr).getAsJsonObject().get("result").getAsJsonArray(); this.alterExpectedUri(expected, sourceRoot); this.alterActualUri(actual); @@ -94,7 +93,7 @@ public void testReferencesWithinStdLib(String configPath) throws IOException, UR String actualStr = getReferencesResponseWithinStdLib(sourcePath, position); JsonArray expected = configObject.getAsJsonArray("result"); - JsonArray actual = parser.parse(actualStr).getAsJsonObject().get("result").getAsJsonArray(); + JsonArray actual = JsonParser.parseString(actualStr).getAsJsonObject().get("result").getAsJsonArray(); this.alterExpectedUri(expected, ballerinaHome); this.alterActualStdLibUri(actual); diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/rename/AbstractRenameTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/rename/AbstractRenameTest.java index 23490d9c5dca..89f425a01511 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/rename/AbstractRenameTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/rename/AbstractRenameTest.java @@ -37,7 +37,6 @@ public abstract class AbstractRenameTest { private Path configRoot; private Path sourceRoot; protected Gson gson = new Gson(); - protected JsonParser parser = new JsonParser(); protected Endpoint serviceEndpoint; @BeforeClass @@ -60,13 +59,13 @@ public void performTest(String configPath, String varName) throws IOException { String prepareResponse = TestUtil.getPrepareRenameResponse(sourcePath.toString(), position, serviceEndpoint); // For invalid positions, response result=null, and is removed by GSON. - Assert.assertEquals(parser.parse(prepareResponse).getAsJsonObject().has("result"), isValidRename, + Assert.assertEquals(JsonParser.parseString(prepareResponse).getAsJsonObject().has("result"), isValidRename, "Expected valid rename position: " + String.valueOf(isValidRename)); String actualStr = TestUtil.getRenameResponse(sourcePath.toString(), position, varName, serviceEndpoint); TestUtil.closeDocument(serviceEndpoint, sourcePath); JsonObject expected = resultJson.getAsJsonObject("result"); - JsonObject actual = parser.parse(actualStr).getAsJsonObject().getAsJsonObject("result"); + JsonObject actual = JsonParser.parseString(actualStr).getAsJsonObject().getAsJsonObject("result"); if (actual == null) { actual = new JsonObject(); } else { diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/rename/ProjectRenameTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/rename/ProjectRenameTest.java index cf490722901b..a8bee9b9f03c 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/rename/ProjectRenameTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/rename/ProjectRenameTest.java @@ -58,6 +58,7 @@ private Object[][] testDataProvider() { }; } + @Override @AfterClass public void shutDownLanguageServer() throws IOException { TestUtil.shutdownLanguageServer(this.serviceEndpoint); diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/rename/RenameTestUtil.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/rename/RenameTestUtil.java index a5bc6a79110e..fd586335398f 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/rename/RenameTestUtil.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/rename/RenameTestUtil.java @@ -28,7 +28,10 @@ /** * An abstract implementation of any rename test. */ -public class RenameTestUtil { +public final class RenameTestUtil { + + private RenameTestUtil() { + } public static void alterExpectedUri(JsonObject expected, Path sourceRoot) throws IOException { if (expected == null) { diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/signature/AbstractSignatureHelpTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/signature/AbstractSignatureHelpTest.java index a3e7c663eb8b..8b472bcb8b82 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/signature/AbstractSignatureHelpTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/signature/AbstractSignatureHelpTest.java @@ -36,6 +36,7 @@ import java.nio.file.Path; import java.util.ArrayList; import java.util.List; +import java.util.stream.Stream; /** * Test class for Signature help. @@ -48,8 +49,6 @@ public abstract class AbstractSignatureHelpTest { private Endpoint serviceEndpoint; - private JsonParser parser = new JsonParser(); - private Path testRoot = new File(getClass().getClassLoader().getResource("signature").getFile()).toPath(); private static final Logger log = LoggerFactory.getLogger(AbstractSignatureHelpTest.class); @@ -69,7 +68,7 @@ public void test(String config, String source) Path sourcePath = testRoot.resolve(configJsonObject.get("source").getAsString()); expected.remove("id"); String response = this.getSignatureResponse(configJsonObject, sourcePath).replace("\\r\\n", "\\n"); - JsonObject responseJson = parser.parse(response).getAsJsonObject(); + JsonObject responseJson = JsonParser.parseString(response).getAsJsonObject(); responseJson.remove("id"); boolean result = expected.equals(responseJson); if (!result) { @@ -81,7 +80,8 @@ public void test(String config, String source) // java.nio.file.Files.write(org.ballerinalang.langserver.util.FileUtils.RES_DIR.resolve(configJsonPath), // obj.toString().getBytes(java.nio.charset.StandardCharsets.UTF_8)); - Assert.fail("Failed Test for: " + configJsonPath); + Assert.fail("Failed Test for: " + configJsonPath + "\n Expected: " + + expected + "\n Found: " + responseJson); } } @@ -103,9 +103,9 @@ protected Object[][] getConfigsList() { return this.testSubset(); } List skippedTests = this.skipList(); - try { - return Files.walk(this.testRoot.resolve(this.getTestResourceDir()).resolve(this.configDir)) - .filter(path -> { + try (Stream configPaths = Files.walk( + this.testRoot.resolve(this.getTestResourceDir()).resolve(this.configDir))) { + return configPaths.filter(path -> { File file = path.toFile(); return file.isFile() && file.getName().endsWith(".json") && !skippedTests.contains(file.getName()); diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/signature/ActionTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/signature/ActionTest.java index 3a2b8012d92f..a9c4bc47d1c6 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/signature/ActionTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/signature/ActionTest.java @@ -27,6 +27,7 @@ * @since 2.0.0 */ public class ActionTest extends AbstractSignatureHelpTest { + @Override @Test(dataProvider = "signature-help-data-provider", description = "Test Signature Help for Actions") public void test(String config, String source) throws WorkspaceDocumentException, InterruptedException, IOException { diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/signature/ExpressionsTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/signature/ExpressionsTest.java index cac5848bc347..6ec2d1bb5fcd 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/signature/ExpressionsTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/signature/ExpressionsTest.java @@ -29,6 +29,7 @@ * @since 2.0.0 */ public class ExpressionsTest extends AbstractSignatureHelpTest { + @Override @Test(dataProvider = "signature-help-data-provider", description = "Test Signature Help for Expressions") public void test(String config, String source) throws WorkspaceDocumentException, InterruptedException, IOException { diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/signature/IncludedRecordParameterTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/signature/IncludedRecordParameterTest.java index d38b302ff4d1..f8c6c41c51ec 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/signature/IncludedRecordParameterTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/signature/IncludedRecordParameterTest.java @@ -28,6 +28,7 @@ */ public class IncludedRecordParameterTest extends AbstractSignatureHelpTest { + @Override @Test(dataProvider = "signature-help-data-provider", description = "Test Signature Help for Included record params") public void test(String config, String source) throws WorkspaceDocumentException, InterruptedException, IOException { diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/signature/StatementTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/signature/StatementTest.java index c74962e8c8b5..07ed1e334a17 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/signature/StatementTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/signature/StatementTest.java @@ -27,6 +27,7 @@ * @since 2.0.0 */ public class StatementTest extends AbstractSignatureHelpTest { + @Override @Test(dataProvider = "signature-help-data-provider", description = "Test Signature Help for Statements") public void test(String config, String source) throws WorkspaceDocumentException, InterruptedException, IOException { diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/stnode/SyntaxTreeNodeTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/stnode/SyntaxTreeNodeTest.java index 539eefcbbe44..9c85f1b95958 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/stnode/SyntaxTreeNodeTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/stnode/SyntaxTreeNodeTest.java @@ -35,7 +35,6 @@ */ public class SyntaxTreeNodeTest { - private static final JsonParser JSON_PARSER = new JsonParser(); private static final String STRING_LITERAL = "STRING_LITERAL"; private static final String MINUTIAE = "WHITESPACE_MINUTIAE"; @@ -54,7 +53,7 @@ public void syntaxTreeNodeTestCase(int start, int end, String expected) throws I Range range = new Range(new Position(start, end), new Position(start, end)); String response = TestUtil.getSyntaxTreeNodeResponse(serviceEndpoint, this.resource.toAbsolutePath().toString(), range); - String actual = JSON_PARSER.parse(response).getAsJsonObject().getAsJsonObject("result") + String actual = JsonParser.parseString(response).getAsJsonObject().getAsJsonObject("result") .getAsJsonPrimitive("kind").getAsString(); Assert.assertEquals(actual, expected, "Document syntaxTreeNode testcase failed for range " + start + " and " + end + "."); diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/toml/ballerinatoml/completion/BallerinaTomlCompletionTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/toml/ballerinatoml/completion/BallerinaTomlCompletionTest.java index a96114ae7f36..b087b3ef73e5 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/toml/ballerinatoml/completion/BallerinaTomlCompletionTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/toml/ballerinatoml/completion/BallerinaTomlCompletionTest.java @@ -39,10 +39,12 @@ import java.io.File; import java.io.IOException; import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; +import java.util.stream.Stream; /** * Completion Test Interface. @@ -56,8 +58,6 @@ public abstract class BallerinaTomlCompletionTest { private final Path testRoot = FileUtils.RES_DIR.resolve("toml" + File.separator + "ballerina_toml" + File.separator + "completion"); - private final JsonParser parser = new JsonParser(); - private final Gson gson = new Gson(); @BeforeClass @@ -72,7 +72,7 @@ public void test(String config, String configPath) throws WorkspaceDocumentExcep JsonObject configJsonObject = FileUtils.fileContentAsObject(configJsonPath); String response = getResponse(configJsonObject); - JsonObject json = parser.parse(response).getAsJsonObject(); + JsonObject json = JsonParser.parseString(response).getAsJsonObject(); Type collectionType = new TypeToken>() { }.getType(); JsonArray resultList = json.getAsJsonObject("result").getAsJsonArray("left"); List responseItemList = gson.fromJson(resultList, collectionType); @@ -132,9 +132,9 @@ protected Object[][] getConfigsList() { return this.testSubset(); } List skippedTests = this.skipList(); - try { - return Files.walk(this.testRoot.resolve("config").resolve(this.getTestResourceDir())) - .filter(path -> { + try (Stream configPaths = Files.walk( + this.testRoot.resolve("config").resolve(this.getTestResourceDir()))) { + return configPaths.filter(path -> { File file = path.toFile(); return file.isFile() && file.getName().endsWith(".json") && !skippedTests.contains(file.getName()); @@ -189,8 +189,7 @@ private void updateConfig(String configJsonPath, JsonObject configJsonObject, Js obj.add("triggerCharacter", configJsonObject.get("triggerCharacter")); } String objStr = obj.toString().concat(System.lineSeparator()); - java.nio.file.Files.write(FileUtils.RES_DIR.resolve(configJsonPath), - objStr.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + Files.write(FileUtils.RES_DIR.resolve(configJsonPath), objStr.getBytes(StandardCharsets.UTF_8)); //This will print nice comparable text in IDE Assert.assertEquals(responseItemList.toString(), expectedItemList.toString(), diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/util/FileUtils.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/util/FileUtils.java index 10ae094c0dbb..86bdbfe95c10 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/util/FileUtils.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/util/FileUtils.java @@ -30,15 +30,16 @@ /** * File utils for reading the file content. */ -public class FileUtils { - - private static final JsonParser JSON_PARSER = new JsonParser(); +public final class FileUtils { private static final Logger LOGGER = LoggerFactory.getLogger(FileUtils.class); public static final Path RES_DIR = Paths.get("src/test/resources/").toAbsolutePath(); public static final Path BUILD_DIR = Paths.get("build/").toAbsolutePath(); + private FileUtils() { + } + /** * Get the file content. * @param filePath path to the file @@ -51,7 +52,7 @@ public static JsonObject fileContentAsObject(String filePath) { } catch (IOException ex) { LOGGER.error(ex.getMessage()); } - return JSON_PARSER.parse(contentAsString).getAsJsonObject(); + return JsonParser.parseString(contentAsString).getAsJsonObject(); } /** diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/util/PerformanceTestUtils.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/util/PerformanceTestUtils.java index d4b9ae8adc59..f5a8ec4ddf36 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/util/PerformanceTestUtils.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/util/PerformanceTestUtils.java @@ -20,9 +20,13 @@ /** * Test utils for running performance tests. */ -public class PerformanceTestUtils { +public final class PerformanceTestUtils { private static final String RES_TIME_THRESHOLD_SYSTEM_PROPERTY = "responseTimeThreshold"; + + private PerformanceTestUtils() { + } + /** * Get response time threshold for Completion Performance Test. */ diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/workspace/TestDidChangeWatchedFiles.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/workspace/TestDidChangeWatchedFiles.java index 9f839fd86721..6fced133410f 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/workspace/TestDidChangeWatchedFiles.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/workspace/TestDidChangeWatchedFiles.java @@ -37,7 +37,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.stream.Collectors; /** * Test the watched file changes. @@ -129,7 +128,7 @@ private void sendSingleFileEvent(Path path, FileChangeType fileChangeType) { private void sendMultipleFileChanges(Map changesMap) { List fileEvents = changesMap.entrySet().stream() .map(entry -> new FileEvent(entry.getKey().toUri().toString(), entry.getValue())) - .collect(Collectors.toList()); + .toList(); DidChangeWatchedFilesParams params = new DidChangeWatchedFilesParams(); params.setChanges(fileEvents); diff --git a/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration12.json b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration12.json index fe88f0071f37..ef1964c22a2f 100644 --- a/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration12.json +++ b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration12.json @@ -19,13 +19,14 @@ "character": 0 }, "end": { - "line": 91, - "character": 10 + "line": 95, + "character": 1 } } } ] - } + }, + "resolvable": false }, { "title": "Document all", @@ -34,7 +35,8 @@ "title": "Document all", "command": "ADD_ALL_DOC", "arguments": [] - } + }, + "resolvable": false } ] } diff --git a/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration13.json b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration13.json new file mode 100644 index 000000000000..cae6435fbe15 --- /dev/null +++ b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration13.json @@ -0,0 +1,32 @@ +{ + "position": { + "line": 97, + "character": 8 + }, + "source": "singleDocGeneration.bal", + "expected": [ + { + "title": "Document this", + "command": { + "title": "Document this", + "command": "ADD_DOC", + "arguments": [ + { + "key": "node.range", + "value": { + "start": { + "line": 97, + "character": 0 + }, + "end": { + "line": 97, + "character": 22 + } + } + } + ] + }, + "resolvable": false + } + ] +} diff --git a/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration14.json b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration14.json new file mode 100644 index 000000000000..e666e360c268 --- /dev/null +++ b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration14.json @@ -0,0 +1,32 @@ +{ + "position": { + "line": 99, + "character": 8 + }, + "source": "singleDocGeneration.bal", + "expected": [ + { + "title": "Document this", + "command": { + "title": "Document this", + "command": "ADD_DOC", + "arguments": [ + { + "key": "node.range", + "value": { + "start": { + "line": 99, + "character": 0 + }, + "end": { + "line": 99, + "character": 21 + } + } + } + ] + }, + "resolvable": false + } + ] +} diff --git a/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration15.json b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration15.json new file mode 100644 index 000000000000..035920868dd2 --- /dev/null +++ b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration15.json @@ -0,0 +1,32 @@ +{ + "position": { + "line": 101, + "character": 8 + }, + "source": "singleDocGeneration.bal", + "expected": [ + { + "title": "Document this", + "command": { + "title": "Document this", + "command": "ADD_DOC", + "arguments": [ + { + "key": "node.range", + "value": { + "start": { + "line": 101, + "character": 0 + }, + "end": { + "line": 101, + "character": 33 + } + } + } + ] + }, + "resolvable": false + } + ] +} diff --git a/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration16.json b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration16.json new file mode 100644 index 000000000000..976ac565f1b1 --- /dev/null +++ b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration16.json @@ -0,0 +1,32 @@ +{ + "position": { + "line": 103, + "character": 7 + }, + "source": "singleDocGeneration.bal", + "expected": [ + { + "title": "Document this", + "command": { + "title": "Document this", + "command": "ADD_DOC", + "arguments": [ + { + "key": "node.range", + "value": { + "start": { + "line": 103, + "character": 0 + }, + "end": { + "line": 103, + "character": 12 + } + } + } + ] + }, + "resolvable": false + } + ] +} diff --git a/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration17.json b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration17.json new file mode 100644 index 000000000000..06abbab9196d --- /dev/null +++ b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration17.json @@ -0,0 +1,32 @@ +{ + "position": { + "line": 105, + "character": 7 + }, + "source": "singleDocGeneration.bal", + "expected": [ + { + "title": "Document this", + "command": { + "title": "Document this", + "command": "ADD_DOC", + "arguments": [ + { + "key": "node.range", + "value": { + "start": { + "line": 105, + "character": 0 + }, + "end": { + "line": 105, + "character": 20 + } + } + } + ] + }, + "resolvable": false + } + ] +} diff --git a/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration18.json b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration18.json new file mode 100644 index 000000000000..54ba45a98328 --- /dev/null +++ b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration18.json @@ -0,0 +1,32 @@ +{ + "position": { + "line": 107, + "character": 6 + }, + "source": "singleDocGeneration.bal", + "expected": [ + { + "title": "Document this", + "command": { + "title": "Document this", + "command": "ADD_DOC", + "arguments": [ + { + "key": "node.range", + "value": { + "start": { + "line": 107, + "character": 0 + }, + "end": { + "line": 107, + "character": 23 + } + } + } + ] + }, + "resolvable": false + } + ] +} diff --git a/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration19.json b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration19.json new file mode 100644 index 000000000000..c4de508d8c56 --- /dev/null +++ b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration19.json @@ -0,0 +1,32 @@ +{ + "position": { + "line": 109, + "character": 10 + }, + "source": "singleDocGeneration.bal", + "expected": [ + { + "title": "Document this", + "command": { + "title": "Document this", + "command": "ADD_DOC", + "arguments": [ + { + "key": "node.range", + "value": { + "start": { + "line": 109, + "character": 0 + }, + "end": { + "line": 109, + "character": 32 + } + } + } + ] + }, + "resolvable": false + } + ] +} diff --git a/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration20.json b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration20.json new file mode 100644 index 000000000000..fe3fff1379d1 --- /dev/null +++ b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration20.json @@ -0,0 +1,32 @@ +{ + "position": { + "line": 112, + "character": 11 + }, + "source": "singleDocGeneration.bal", + "expected": [ + { + "title": "Document this", + "command": { + "title": "Document this", + "command": "ADD_DOC", + "arguments": [ + { + "key": "node.range", + "value": { + "start": { + "line": 112, + "character": 0 + }, + "end": { + "line": 112, + "character": 18 + } + } + } + ] + }, + "resolvable": false + } + ] +} diff --git a/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration21.json b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration21.json new file mode 100644 index 000000000000..c1bbcd4f4a24 --- /dev/null +++ b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration21.json @@ -0,0 +1,32 @@ +{ + "position": { + "line": 114, + "character": 17 + }, + "source": "singleDocGeneration.bal", + "expected": [ + { + "title": "Document this", + "command": { + "title": "Document this", + "command": "ADD_DOC", + "arguments": [ + { + "key": "node.range", + "value": { + "start": { + "line": 114, + "character": 0 + }, + "end": { + "line": 114, + "character": 30 + } + } + } + ] + }, + "resolvable": false + } + ] +} diff --git a/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration22.json b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration22.json new file mode 100644 index 000000000000..bb8b5273d20b --- /dev/null +++ b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration22.json @@ -0,0 +1,32 @@ +{ + "position": { + "line": 115, + "character": 17 + }, + "source": "singleDocGeneration.bal", + "expected": [ + { + "title": "Document this", + "command": { + "title": "Document this", + "command": "ADD_DOC", + "arguments": [ + { + "key": "node.range", + "value": { + "start": { + "line": 115, + "character": 0 + }, + "end": { + "line": 115, + "character": 30 + } + } + } + ] + }, + "resolvable": false + } + ] +} diff --git a/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration23.json b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration23.json new file mode 100644 index 000000000000..1dcbeddb3624 --- /dev/null +++ b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration23.json @@ -0,0 +1,32 @@ +{ + "position": { + "line": 116, + "character": 14 + }, + "source": "singleDocGeneration.bal", + "expected": [ + { + "title": "Document this", + "command": { + "title": "Document this", + "command": "ADD_DOC", + "arguments": [ + { + "key": "node.range", + "value": { + "start": { + "line": 116, + "character": 0 + }, + "end": { + "line": 116, + "character": 24 + } + } + } + ] + }, + "resolvable": false + } + ] +} diff --git a/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration24.json b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration24.json new file mode 100644 index 000000000000..fcba5fd09930 --- /dev/null +++ b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration24.json @@ -0,0 +1,32 @@ +{ + "position": { + "line": 117, + "character": 31 + }, + "source": "singleDocGeneration.bal", + "expected": [ + { + "title": "Document this", + "command": { + "title": "Document this", + "command": "ADD_DOC", + "arguments": [ + { + "key": "node.range", + "value": { + "start": { + "line": 117, + "character": 0 + }, + "end": { + "line": 117, + "character": 58 + } + } + } + ] + }, + "resolvable": false + } + ] +} diff --git a/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration25.json b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration25.json new file mode 100644 index 000000000000..1c9d95f8dbed --- /dev/null +++ b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration25.json @@ -0,0 +1,32 @@ +{ + "position": { + "line": 119, + "character": 15 + }, + "source": "singleDocGeneration.bal", + "expected": [ + { + "title": "Document this", + "command": { + "title": "Document this", + "command": "ADD_DOC", + "arguments": [ + { + "key": "node.range", + "value": { + "start": { + "line": 119, + "character": 0 + }, + "end": { + "line": 119, + "character": 30 + } + } + } + ] + }, + "resolvable": false + } + ] +} diff --git a/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration26.json b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration26.json new file mode 100644 index 000000000000..bcc88970dab5 --- /dev/null +++ b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration26.json @@ -0,0 +1,32 @@ +{ + "position": { + "line": 121, + "character": 20 + }, + "source": "singleDocGeneration.bal", + "expected": [ + { + "title": "Document this", + "command": { + "title": "Document this", + "command": "ADD_DOC", + "arguments": [ + { + "key": "node.range", + "value": { + "start": { + "line": 121, + "character": 0 + }, + "end": { + "line": 121, + "character": 36 + } + } + } + ] + }, + "resolvable": false + } + ] +} diff --git a/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration27.json b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration27.json new file mode 100644 index 000000000000..0a51d389d194 --- /dev/null +++ b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration27.json @@ -0,0 +1,32 @@ +{ + "position": { + "line": 123, + "character": 18 + }, + "source": "singleDocGeneration.bal", + "expected": [ + { + "title": "Document this", + "command": { + "title": "Document this", + "command": "ADD_DOC", + "arguments": [ + { + "key": "node.range", + "value": { + "start": { + "line": 123, + "character": 0 + }, + "end": { + "line": 123, + "character": 24 + } + } + } + ] + }, + "resolvable": false + } + ] +} diff --git a/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration28.json b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration28.json new file mode 100644 index 000000000000..33ea00c66431 --- /dev/null +++ b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration28.json @@ -0,0 +1,32 @@ +{ + "position": { + "line": 124, + "character": 11 + }, + "source": "singleDocGeneration.bal", + "expected": [ + { + "title": "Document this", + "command": { + "title": "Document this", + "command": "ADD_DOC", + "arguments": [ + { + "key": "node.range", + "value": { + "start": { + "line": 124, + "character": 0 + }, + "end": { + "line": 124, + "character": 18 + } + } + } + ] + }, + "resolvable": false + } + ] +} diff --git a/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration9.json b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration9.json index 45a7b60ff67f..5ab8aabde0d3 100644 --- a/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration9.json +++ b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/config/singleDocGeneration9.json @@ -25,7 +25,8 @@ } } ] - } + }, + "resolvable": false } ] } diff --git a/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/source/singleDocGeneration.bal b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/source/singleDocGeneration.bal index 97b2b48608cf..f23f9833a112 100644 --- a/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/source/singleDocGeneration.bal +++ b/language-server/modules/langserver-core/src/test/resources/codeaction/add-documentation/source/singleDocGeneration.bal @@ -94,3 +94,32 @@ enum Color { GREEN, BLUE } + +type Number int|float; + +type IntMap map; + +type StringStream stream; + +type Nil (); + +type IntArray int[]; + +type Pi 3.14285714286d; + +type ReadonlyInt readonly & int; + +type MyInt 12; +type MyInt2 MyInt; + +type MyXMLComment xml:Comment; +type MyXMLElement xml:Element; +type MyXMLText xml:Text; +type MyXMLProcessingInstruction xml:ProcessingInstruction; + +type MyTypeDesc typedesc; + +type MyDistinctError distinct error; + +type MyOptionalInt int?; +type MyInt3 (int); diff --git a/language-server/modules/langserver-core/src/test/resources/definition/expected/project/defProject16.json b/language-server/modules/langserver-core/src/test/resources/definition/expected/project/defProject16.json new file mode 100644 index 000000000000..f4740abb69f9 --- /dev/null +++ b/language-server/modules/langserver-core/src/test/resources/definition/expected/project/defProject16.json @@ -0,0 +1,24 @@ +{ + "source": { + "file": "projectls/defmodsource7.bal" + }, + "position": { + "line": 18, + "character": 23 + }, + "result": [ + { + "range": { + "start": { + "line": 3, + "character": 22 + }, + "end": { + "line": 3, + "character": 25 + } + }, + "uri": "projectls/defmodsource7.bal" + } + ] +} diff --git a/language-server/modules/langserver-core/src/test/resources/definition/expected/project/defProject17.json b/language-server/modules/langserver-core/src/test/resources/definition/expected/project/defProject17.json new file mode 100644 index 000000000000..9ce9cdf32164 --- /dev/null +++ b/language-server/modules/langserver-core/src/test/resources/definition/expected/project/defProject17.json @@ -0,0 +1,24 @@ +{ + "source": { + "file": "projectls/defmodsource7.bal" + }, + "position": { + "line": 19, + "character": 33 + }, + "result": [ + { + "range": { + "start": { + "line": 11, + "character": 22 + }, + "end": { + "line": 11, + "character": 25 + } + }, + "uri": "projectls/defmodsource7.bal" + } + ] +} diff --git a/language-server/modules/langserver-core/src/test/resources/definition/expected/project/defProject18.json b/language-server/modules/langserver-core/src/test/resources/definition/expected/project/defProject18.json new file mode 100644 index 000000000000..24d930b73c9e --- /dev/null +++ b/language-server/modules/langserver-core/src/test/resources/definition/expected/project/defProject18.json @@ -0,0 +1,24 @@ +{ + "source": { + "file": "projectls/defmodsource7.bal" + }, + "position": { + "line": 20, + "character": 22 + }, + "result": [ + { + "range": { + "start": { + "line": 7, + "character": 22 + }, + "end": { + "line": 7, + "character": 26 + } + }, + "uri": "projectls/defmodsource7.bal" + } + ] +} diff --git a/language-server/modules/langserver-core/src/test/resources/definition/expected/project/defProject19.json b/language-server/modules/langserver-core/src/test/resources/definition/expected/project/defProject19.json new file mode 100644 index 000000000000..ec3f3844999c --- /dev/null +++ b/language-server/modules/langserver-core/src/test/resources/definition/expected/project/defProject19.json @@ -0,0 +1,24 @@ +{ + "source": { + "file": "projectls/defmodsource7.bal" + }, + "position": { + "line": 23, + "character": 23 + }, + "result": [ + { + "range": { + "start": { + "line": 1, + "character": 22 + }, + "end": { + "line": 1, + "character": 25 + } + }, + "uri": "projectls/modules/lsmod1/source2.bal" + } + ] +} diff --git a/language-server/modules/langserver-core/src/test/resources/definition/expected/project/defProject20.json b/language-server/modules/langserver-core/src/test/resources/definition/expected/project/defProject20.json new file mode 100644 index 000000000000..60137e95ff77 --- /dev/null +++ b/language-server/modules/langserver-core/src/test/resources/definition/expected/project/defProject20.json @@ -0,0 +1,24 @@ +{ + "source": { + "file": "projectls/defmodsource7.bal" + }, + "position": { + "line": 24, + "character": 34 + }, + "result": [ + { + "range": { + "start": { + "line": 9, + "character": 22 + }, + "end": { + "line": 9, + "character": 25 + } + }, + "uri": "projectls/modules/lsmod1/source2.bal" + } + ] +} diff --git a/language-server/modules/langserver-core/src/test/resources/definition/sources/projectls/defmodsource7.bal b/language-server/modules/langserver-core/src/test/resources/definition/sources/projectls/defmodsource7.bal new file mode 100644 index 000000000000..99ee0ea229c9 --- /dev/null +++ b/language-server/modules/langserver-core/src/test/resources/definition/sources/projectls/defmodsource7.bal @@ -0,0 +1,27 @@ +import projectls.lsmod1; + +public client class MyClient { + resource function get .() returns int { + return 3; + } + + resource function post .() returns int { + return 2; + } + + resource function get books/names() returns string[2] { + return ["book1", "book2"]; + } +} + +function foo() { + MyClient myClient1 = new; + _ = myClient1->/.get; + _ = myClient1->/books/names.get; + _ = myClient1->/.post; + + lsmod1:MyClient myClient2 = new; + _ = myClient2->/.get; + _ = myClient2->/books/names.get; + _ = myClient2->/.post; +} diff --git a/language-server/modules/langserver-core/src/test/resources/definition/sources/projectls/modules/lsmod1/source2.bal b/language-server/modules/langserver-core/src/test/resources/definition/sources/projectls/modules/lsmod1/source2.bal new file mode 100644 index 000000000000..c9f8767f1472 --- /dev/null +++ b/language-server/modules/langserver-core/src/test/resources/definition/sources/projectls/modules/lsmod1/source2.bal @@ -0,0 +1,13 @@ +public client class MyClient { + resource function get .() returns int { + return 3; + } + + resource function post .() returns int { + return 2; + } + + resource function get books/names() returns string[2] { + return ["book1", "book2"]; + } +} diff --git a/language-server/modules/langserver-core/src/test/resources/hover/configs/hover_for_resource_path2.json b/language-server/modules/langserver-core/src/test/resources/hover/configs/hover_for_resource_path2.json index a04d5db61f5a..cd639f0bcb55 100644 --- a/language-server/modules/langserver-core/src/test/resources/hover/configs/hover_for_resource_path2.json +++ b/language-server/modules/langserver-core/src/test/resources/hover/configs/hover_for_resource_path2.json @@ -1,7 +1,7 @@ { "position": { "line": 28, - "character": 39 + "character": 44 }, "source": { "file": "hover_for_resource_path.bal" diff --git a/language-server/modules/langserver-stdlib/src/main/java/org/ballerinalang/langserver/stdlib/ClientAction.java b/language-server/modules/langserver-stdlib/src/main/java/org/ballerinalang/langserver/stdlib/ClientAction.java index 92494df24e38..14406e534fd9 100644 --- a/language-server/modules/langserver-stdlib/src/main/java/org/ballerinalang/langserver/stdlib/ClientAction.java +++ b/language-server/modules/langserver-stdlib/src/main/java/org/ballerinalang/langserver/stdlib/ClientAction.java @@ -28,9 +28,9 @@ * * @since 2201.4.0 */ -public class ClientAction { +public final class ClientAction { - public ClientAction() { + private ClientAction() { } public static Object get(BString path, BTypedesc targetType) { diff --git a/language-server/modules/launchers/stdio-launcher/src/main/java/org/ballerinalang/langserver/launchers/stdio/Main.java b/language-server/modules/launchers/stdio-launcher/src/main/java/org/ballerinalang/langserver/launchers/stdio/Main.java index 0a51c87c419b..673f9c83abd8 100644 --- a/language-server/modules/launchers/stdio-launcher/src/main/java/org/ballerinalang/langserver/launchers/stdio/Main.java +++ b/language-server/modules/launchers/stdio-launcher/src/main/java/org/ballerinalang/langserver/launchers/stdio/Main.java @@ -23,17 +23,22 @@ import java.io.OutputStream; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; +import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.Logger; /** * Entry point of the stdio launcher. */ -public class Main { +public final class Main { + + private Main() { + } + public static void main(String[] args) throws InterruptedException, ExecutionException { LogManager.getLogManager().reset(); - Logger globalLogger = Logger.getLogger(java.util.logging.Logger.GLOBAL_LOGGER_NAME); - globalLogger.setLevel(java.util.logging.Level.OFF); + Logger globalLogger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); + globalLogger.setLevel(Level.OFF); startServer(System.in, System.out); } diff --git a/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/command/BindingsGenerator.java b/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/command/BindingsGenerator.java index 93260bb4df25..85a6a5ba446d 100644 --- a/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/command/BindingsGenerator.java +++ b/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/command/BindingsGenerator.java @@ -285,7 +285,7 @@ private void generateBindings(Set classList, ClassLoader classLoader, Pa for (String c : classList) { try { if (classLoader != null) { - Class classInstance = classLoader.loadClass(c); + Class classInstance = classLoader.loadClass(c); if (classInstance != null && isPublicClass(classInstance)) { JClass jClass = new JClass(classInstance, env); Path filePath; diff --git a/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/model/BFunction.java b/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/model/BFunction.java index 7ed1264eacb4..613b7b4e60c5 100644 --- a/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/model/BFunction.java +++ b/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/model/BFunction.java @@ -34,7 +34,7 @@ public abstract class BFunction { private String externalFunctionName; private String externalReturnType; private String functionName; - private Class declaringClass; + private Class declaringClass; private List parameters = new LinkedList<>(); private List throwables = new LinkedList<>(); private boolean isStatic = true; @@ -70,11 +70,11 @@ public String getFunctionName() { return functionName; } - public Class getDeclaringClass() { + public Class getDeclaringClass() { return declaringClass; } - void setDeclaringClass(Class declaringClass) { + void setDeclaringClass(Class declaringClass) { this.declaringClass = declaringClass; } diff --git a/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/model/JClass.java b/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/model/JClass.java index cd2b303829f6..b75c5c8bb78b 100644 --- a/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/model/JClass.java +++ b/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/model/JClass.java @@ -50,7 +50,7 @@ public class JClass { private final BindgenEnv env; - private final Class currentClass; + private final Class currentClass; private final String prefix; private final String packageName; private final boolean modulesFlag; @@ -65,7 +65,7 @@ public class JClass { private final List constructorList = new ArrayList<>(); private final Map overloadedMethods = new HashMap<>(); - public JClass(Class c, BindgenEnv env) { + public JClass(Class c, BindgenEnv env) { this.env = env; currentClass = c; prefix = c.getName().replace(".", "_").replace("$", "_"); @@ -74,7 +74,7 @@ public JClass(Class c, BindgenEnv env) { shortClassName = getExceptionName(c, shortClassName); modulesFlag = env.getModulesFlag(); - Class sClass = c.getSuperclass(); + Class sClass = c.getSuperclass(); // Iterate until a public super class is found. while (sClass != null && !isPublicClass(sClass)) { sClass = sClass.getSuperclass(); @@ -102,7 +102,7 @@ public JClass(Class c, BindgenEnv env) { } } - private String getExceptionName(Class exception, String name) { + private String getExceptionName(Class exception, String name) { try { // Append the exception class prefix in front of bindings generated for Java exceptions. if (this.getClass().getClassLoader().loadClass(Exception.class.getCanonicalName()) @@ -117,7 +117,7 @@ private String getExceptionName(Class exception, String name) { return name; } - private List getMethodsAsList(Class classObject) { + private List getMethodsAsList(Class classObject) { Method[] declaredMethods = classObject.getMethods(); List classMethods = new LinkedList<>(); for (Method m : declaredMethods) { @@ -128,10 +128,10 @@ private List getMethodsAsList(Class classObject) { return classMethods; } - private void populateConstructors(Constructor[] constructors) { + private void populateConstructors(Constructor[] constructors) { int i = 1; List tempList = new ArrayList<>(); - for (Constructor constructor : constructors) { + for (Constructor constructor : constructors) { if (isPublicConstructor(constructor)) { tempList.add(new JConstructor(constructor, env, this, null)); } @@ -151,7 +151,7 @@ private void populateConstructors(Constructor[] constructors) { } } - private void populateMethods(Class c) { + private void populateMethods(Class c) { List tempList = sortInheritedMethods(getMethodsAsList(c), new ArrayList<>(), c); for (JMethod method : tempList) { setMethodCount(method.getJavaMethodName()); @@ -169,7 +169,7 @@ private void populateMethods(Class c) { } private List sortInheritedMethods(List methods, List sortedMethods, - Class declaringClass) { + Class declaringClass) { if (declaringClass == null) { return sortedMethods; } @@ -189,7 +189,7 @@ private List sortInheritedMethods(List methods, List s return sortInheritedMethods(methods, sortedMethods, declaringClass.getSuperclass()); } - private List getSuperClassMethods(Class superClass, List methods) { + private List getSuperClassMethods(Class superClass, List methods) { if (superClass == null) { return methods; } @@ -257,7 +257,7 @@ private Integer getMethodCount(String methodName) { return overloadedMethods.get(methodName); } - public Class getCurrentClass() { + public Class getCurrentClass() { return currentClass; } diff --git a/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/model/JConstructor.java b/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/model/JConstructor.java index 33d9e35787d2..6f1b6003eee3 100644 --- a/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/model/JConstructor.java +++ b/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/model/JConstructor.java @@ -38,11 +38,11 @@ */ public class JConstructor extends BFunction { - private Class parentClass; + private Class parentClass; private String exceptionName; private String shortClassName; private String exceptionConstName; - private Constructor constructor; + private Constructor constructor; private boolean returnError = false; private boolean hasException = false; // identifies if the Ballerina returns should have an error declared @@ -53,7 +53,7 @@ public class JConstructor extends BFunction { private StringBuilder paramTypes = new StringBuilder(); private Set importedPackages = new HashSet<>(); - JConstructor(Constructor c, BindgenEnv env, JClass jClass, String constructorName) { + JConstructor(Constructor c, BindgenEnv env, JClass jClass, String constructorName) { super(BFunctionKind.CONSTRUCTOR, env); this.constructor = c; parentClass = c.getDeclaringClass(); @@ -101,7 +101,7 @@ public class JConstructor extends BFunction { setExternalFunctionName(parentClass.getName().replace(".", "_").replace("$", "_") + "_" + constructorName); } - private String getExceptionName(Class exception, String name) { + private String getExceptionName(Class exception, String name) { try { // Append the exception class prefix in front of bindings generated for Java exceptions. if (this.getClass().getClassLoader().loadClass(Exception.class.getCanonicalName()) @@ -114,7 +114,7 @@ private String getExceptionName(Class exception, String name) { return name; } - private String getPackageAlias(String shortClassName, Class objectType) { + private String getPackageAlias(String shortClassName, Class objectType) { if (objectType.getPackage() != parentClass.getPackage()) { return objectType.getPackageName().replace(".", "") + ":" + shortClassName; } @@ -169,7 +169,7 @@ public String getReturnType() { return shortClassName; } - public Constructor getConstructor() { + public Constructor getConstructor() { return constructor; } } diff --git a/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/model/JError.java b/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/model/JError.java index 03f9cd368982..fb5401083e35 100644 --- a/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/model/JError.java +++ b/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/model/JError.java @@ -50,7 +50,7 @@ public String getPackageName() { return packageName; } - public Class getCurrentClass() { + public Class getCurrentClass() { return currentClass; } } diff --git a/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/model/JField.java b/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/model/JField.java index 4126fc7890b5..ee5d76f81dc8 100644 --- a/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/model/JField.java +++ b/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/model/JField.java @@ -55,7 +55,7 @@ public class JField extends BFunction { JField(Field field, BFunction.BFunctionKind fieldKind, BindgenEnv env, JClass jClass) { super(fieldKind, env); - Class type = field.getType(); + Class type = field.getType(); fieldType = getBallerinaParamType(type, env); isStatic = isStaticField(field); super.setStatic(isStatic); diff --git a/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/model/JMethod.java b/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/model/JMethod.java index a8b86050de27..c3fd6d65479e 100644 --- a/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/model/JMethod.java +++ b/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/model/JMethod.java @@ -62,7 +62,7 @@ public class JMethod extends BFunction { private boolean isOptionalReturnTypes; private String parentPrefix; - private Class parentClass; + private Class parentClass; private Method method; private String methodName; private String unescapedMethodName; @@ -77,7 +77,7 @@ public class JMethod extends BFunction { private final StringBuilder paramTypes = new StringBuilder(); private final Set importedPackages = new HashSet<>(); - JMethod(Method m, BindgenEnv env, String parentPrefix, Class jClass, int overloaded) { + JMethod(Method m, BindgenEnv env, String parentPrefix, Class jClass, int overloaded) { super(BFunctionKind.METHOD, env); this.env = env; this.parentPrefix = parentPrefix; @@ -96,7 +96,7 @@ public class JMethod extends BFunction { this.isOptionalReturnTypes = env.isOptionalTypes() || env.isOptionalReturnTypes(); // Set the attributes required to identify different return types. - Class returnTypeClass = m.getReturnType(); + Class returnTypeClass = m.getReturnType(); if (!returnTypeClass.equals(Void.TYPE)) { setReturnTypeAttributes(returnTypeClass); } @@ -152,7 +152,7 @@ public class JMethod extends BFunction { } } - private void setReturnTypeAttributes(Class returnTypeClass) { + private void setReturnTypeAttributes(Class returnTypeClass) { hasReturn = true; BindgenUtils.addImportedPackage(returnTypeClass, importedPackages); @@ -197,14 +197,14 @@ private void setReturnTypeAttributes(Class returnTypeClass) { setReturnType(returnType); } - private String getPackageAlias(String shortClassName, Class objectType) { + private String getPackageAlias(String shortClassName, Class objectType) { if (objectType.getPackage() != parentClass.getPackage()) { return objectType.getPackageName().replace(".", "") + ":" + shortClassName; } return shortClassName; } - private String getExceptionName(Class exception, String name) { + private String getExceptionName(Class exception, String name) { try { // Append the exception class prefix in front of bindings generated for Java exceptions. if (this.getClass().getClassLoader().loadClass(Exception.class.getCanonicalName()) diff --git a/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/model/JParameter.java b/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/model/JParameter.java index eacd87aa8e85..aea2e83bfe0f 100644 --- a/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/model/JParameter.java +++ b/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/model/JParameter.java @@ -47,8 +47,8 @@ public class JParameter { private String componentType; private String fieldName; - private Class parentClass; - private Class parameterClass; + private Class parentClass; + private Class parameterClass; private Boolean isObj = false; private Boolean isString = false; @@ -58,7 +58,7 @@ public class JParameter { private Boolean isStringArray = false; private Boolean isPrimitiveArray = false; - JParameter(Class parameterClass, Class parentClass, BindgenEnv env) { + JParameter(Class parameterClass, Class parentClass, BindgenEnv env) { this.env = env; this.parameterClass = parameterClass; this.parentClass = parentClass; @@ -118,7 +118,7 @@ public class JParameter { fieldName = "arg"; } - JParameter(Parameter parameter, Class parentClass, BindgenEnv env) { + JParameter(Parameter parameter, Class parentClass, BindgenEnv env) { this(parameter.getType(), parentClass, env); List reservedWords = Arrays.asList(BALLERINA_RESERVED_WORDS); fieldName = parameter.getName(); @@ -127,8 +127,8 @@ public class JParameter { } } - private void setArrayAttributes(Class parameterClass) { - Class component = parameterClass.getComponentType(); + private void setArrayAttributes(Class parameterClass) { + Class component = parameterClass.getComponentType(); componentType = component.getTypeName(); if (!parameterClass.getComponentType().isPrimitive()) { isObjArray = true; @@ -146,7 +146,7 @@ private void setArrayAttributes(Class parameterClass) { } } - private String getPackageAlias(String shortTypeName, Class parameterClass) { + private String getPackageAlias(String shortTypeName, Class parameterClass) { if (parameterClass.getPackage() != parentClass.getPackage()) { return parameterClass.getPackageName().replace(".", "") + ":" + shortTypeName; } @@ -201,7 +201,7 @@ public Boolean isArray() { return isObjArray || isStringArray || isPrimitiveArray; } - public Class getParameterClass() { + public Class getParameterClass() { return parameterClass; } } diff --git a/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/utils/BindgenConstants.java b/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/utils/BindgenConstants.java index c7612feda73f..6de2bbc6e386 100644 --- a/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/utils/BindgenConstants.java +++ b/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/utils/BindgenConstants.java @@ -22,7 +22,7 @@ * * @since 1.2.0 */ -public class BindgenConstants { +public final class BindgenConstants { private BindgenConstants() { } diff --git a/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/utils/BindgenEnv.java b/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/utils/BindgenEnv.java index b7f2ebe4bb14..1c03935b7f9f 100644 --- a/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/utils/BindgenEnv.java +++ b/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/utils/BindgenEnv.java @@ -104,8 +104,8 @@ public Path getProjectRoot() { return projectRoot; } - public void setSuperClasses(Class superClass) { - Class parent = superClass; + public void setSuperClasses(Class superClass) { + Class parent = superClass; while (parent != null && isPublicClass(parent)) { this.superClasses.add(parent.getName()); parent = parent.getSuperclass(); diff --git a/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/utils/BindgenNodeFactory.java b/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/utils/BindgenNodeFactory.java index d4f87da13a36..333d8e50bc59 100644 --- a/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/utils/BindgenNodeFactory.java +++ b/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/utils/BindgenNodeFactory.java @@ -108,7 +108,7 @@ * * @since 2.0.0 */ -class BindgenNodeFactory { +final class BindgenNodeFactory { private static final Token OPEN_PAREN_TOKEN = createToken(SyntaxKind.OPEN_PAREN_TOKEN); private static final Token CLOSED_PAREN_TOKEN = createToken(CLOSE_PAREN_TOKEN); @@ -128,6 +128,9 @@ class BindgenNodeFactory { createToken(SyntaxKind.OPEN_BRACKET_TOKEN), createToken(SyntaxKind.CLOSE_BRACKET_TOKEN)); + private BindgenNodeFactory() { + } + /** * Create an import declaration name node while providing the organization name, optional prefix, and module names. * diff --git a/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/utils/BindgenUtils.java b/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/utils/BindgenUtils.java index 6ac877e72ace..5746d5227084 100644 --- a/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/utils/BindgenUtils.java +++ b/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/utils/BindgenUtils.java @@ -71,7 +71,7 @@ * * @since 1.2.0 */ -public class BindgenUtils { +public final class BindgenUtils { private BindgenUtils() { } @@ -103,25 +103,12 @@ public static void outputSyntaxTreeFile(JClass jClass, BindgenEnv bindgenEnv, } private static void printOutputFile(String content, String outPath, boolean append) throws BindgenException { - PrintWriter writer = null; - FileWriterWithEncoding fileWriter = null; - try { - fileWriter = new FileWriterWithEncoding(outPath, StandardCharsets.UTF_8, append); - writer = new PrintWriter(fileWriter); + try (FileWriterWithEncoding fileWriter = FileWriterWithEncoding.builder() + .setPath(outPath).setCharset(StandardCharsets.UTF_8).setAppend(append).get(); + PrintWriter writer = new PrintWriter(fileWriter)) { writer.println(Formatter.format(content)); - fileWriter.close(); } catch (IOException | FormatterException e) { throw new BindgenException("error: unable to create the file: " + outPath + " " + e.getMessage(), e); - } finally { - if (writer != null) { - writer.close(); - } - if (fileWriter != null) { - try { - fileWriter.close(); - } catch (IOException ignored) { - } - } } } @@ -139,7 +126,7 @@ public static void createDirectory(String path) throws BindgenException { } } - public static Set addImportedPackage(Class type, Set importedPackages) { + public static Set addImportedPackage(Class type, Set importedPackages) { if (type.isArray()) { type = type.getComponentType(); } @@ -149,7 +136,7 @@ public static Set addImportedPackage(Class type, Set importedPac return importedPackages; } - public static boolean isPublicConstructor(Constructor constructor) { + public static boolean isPublicConstructor(Constructor constructor) { int modifiers = constructor.getModifiers(); return Modifier.isPublic(modifiers); } @@ -164,7 +151,7 @@ public static boolean isPublicMethod(Method method) { return Modifier.isPublic(modifiers); } - public static boolean isPublicClass(Class javaClass) { + public static boolean isPublicClass(Class javaClass) { int modifiers = javaClass.getModifiers(); return Modifier.isPublic(modifiers); } @@ -280,41 +267,23 @@ private static String getBalType(BindgenEnv env, String type) { } private static String getPrimitiveArrayBalType(String type) { - switch (type) { - case INT: - case SHORT: - case CHAR: - case LONG: - return INT_ARRAY; - case FLOAT: - case DOUBLE: - return FLOAT_ARRAY; - case BOOLEAN: - return BOOLEAN_ARRAY; - case BYTE: - return BYTE_ARRAY; - default: - return HANDLE; - } + return switch (type) { + case INT, SHORT, CHAR, LONG -> INT_ARRAY; + case FLOAT, DOUBLE -> FLOAT_ARRAY; + case BOOLEAN -> BOOLEAN_ARRAY; + case BYTE -> BYTE_ARRAY; + default -> HANDLE; + }; } public static String getPrimitiveArrayType(String type) { - switch (type) { - case "[C": - case "[S": - case "[J": - case "[I": - return INT_ARRAY; - case "[D": - case "[F": - return FLOAT_ARRAY; - case "[B": - return BYTE_ARRAY; - case "[Z": - return BOOLEAN_ARRAY; - default: - return type; - } + return switch (type) { + case "[C", "[S", "[J", "[I" -> INT_ARRAY; + case "[D", "[F" -> FLOAT_ARRAY; + case "[B" -> BYTE_ARRAY; + case "[Z" -> BOOLEAN_ARRAY; + default -> type; + }; } public static URLClassLoader getClassLoader(Set jarPaths, ClassLoader parent) throws BindgenException { @@ -381,7 +350,7 @@ public static void setOutStream(PrintStream outStream) { BindgenUtils.outStream = outStream; } - public static String getAlias(Class className, Map aliases) { + public static String getAlias(Class className, Map aliases) { if (!aliases.containsKey(className.getName())) { int i = 2; boolean notAdded = true; diff --git a/misc/ballerina-bindgen/src/test/java/org/ballerinalang/bindgen/BindgenCommandBaseTest.java b/misc/ballerina-bindgen/src/test/java/org/ballerinalang/bindgen/BindgenCommandBaseTest.java index 8a9caaed9905..4767925bfda0 100644 --- a/misc/ballerina-bindgen/src/test/java/org/ballerinalang/bindgen/BindgenCommandBaseTest.java +++ b/misc/ballerina-bindgen/src/test/java/org/ballerinalang/bindgen/BindgenCommandBaseTest.java @@ -29,6 +29,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.Comparator; +import java.util.stream.Stream; /** * Command test supper class. @@ -75,14 +76,15 @@ public void afterMethod() throws IOException { @AfterClass (alwaysRun = true) public void cleanup() throws IOException { - Files.walk(tmpDir) - .sorted(Comparator.reverseOrder()) - .forEach(path -> { - try { - Files.delete(path); - } catch (IOException e) { - Assert.fail(e.getMessage(), e); - } - }); + try (Stream paths = Files.walk(tmpDir)) { + paths.sorted(Comparator.reverseOrder()) + .forEach(path -> { + try { + Files.delete(path); + } catch (IOException e) { + Assert.fail(e.getMessage(), e); + } + }); + } } } diff --git a/misc/ballerina-bindgen/src/test/java/org/ballerinalang/bindgen/BindgenCommandTest.java b/misc/ballerina-bindgen/src/test/java/org/ballerinalang/bindgen/BindgenCommandTest.java index f02952de86a8..730ff7b963bf 100644 --- a/misc/ballerina-bindgen/src/test/java/org/ballerinalang/bindgen/BindgenCommandTest.java +++ b/misc/ballerina-bindgen/src/test/java/org/ballerinalang/bindgen/BindgenCommandTest.java @@ -49,6 +49,7 @@ public class BindgenCommandTest extends BindgenCommandBaseTest { private Path testResources; private String newLine = System.lineSeparator(); + @Override @BeforeClass public void setup() throws IOException { super.setup(); @@ -324,6 +325,7 @@ public void testGenerationOfSuperClasses() throws IOException { "\tjava.lang.Object")); } + @Override @AfterClass public void cleanup() throws IOException { super.cleanup(); diff --git a/misc/ballerina-bindgen/src/test/java/org/ballerinalang/bindgen/FieldsTestResource.java b/misc/ballerina-bindgen/src/test/java/org/ballerinalang/bindgen/FieldsTestResource.java index cdd035671eae..7a706ea35194 100644 --- a/misc/ballerina-bindgen/src/test/java/org/ballerinalang/bindgen/FieldsTestResource.java +++ b/misc/ballerina-bindgen/src/test/java/org/ballerinalang/bindgen/FieldsTestResource.java @@ -62,8 +62,8 @@ public class FieldsTestResource implements InterfaceTestResource { public StringBuilder[] getInstanceObjectArray = new StringBuilder[2]; public Integer[] getInstanceObjectMultiArray1 = new Integer[5]; public Object[] getInstanceObjectMultiArray2 = new Object[2]; - public List getInstanceInterface = new ArrayList<>(); - public AbstractList getInstanceAbstractClass = new ArrayList<>(); + public List getInstanceInterface = new ArrayList<>(); + public AbstractList getInstanceAbstractClass = new ArrayList<>(); public Path getInstanceObject = Paths.get("/test.txt"); public Set getInstanceGenericObject = new HashSet<>(); public System.Logger.Level getInstanceEnumeration = System.Logger.Level.ALL; @@ -111,8 +111,8 @@ public class FieldsTestResource implements InterfaceTestResource { public StringBuilder[] getStaticObjectArray = new StringBuilder[2]; public Integer[] getStaticObjectMultiArray1 = new Integer[2]; public Object[] getStaticObjectMultiArray2 = new Object[2]; - public static List getStaticInterface = new ArrayList<>(); - public static AbstractList getStaticAbstractClass = new ArrayList<>(); + public static List getStaticInterface = new ArrayList<>(); + public static AbstractList getStaticAbstractClass = new ArrayList<>(); public static Path getStaticObject = Paths.get("/test.txt"); public static Set getStaticGenericObject = new HashSet<>(); public static System.Logger.Level getStaticEnumeration = System.Logger.Level.ALL; diff --git a/misc/ballerina-bindgen/src/test/java/org/ballerinalang/bindgen/MavenSupportTest.java b/misc/ballerina-bindgen/src/test/java/org/ballerinalang/bindgen/MavenSupportTest.java index e0cc8db126de..861e9685da8b 100644 --- a/misc/ballerina-bindgen/src/test/java/org/ballerinalang/bindgen/MavenSupportTest.java +++ b/misc/ballerina-bindgen/src/test/java/org/ballerinalang/bindgen/MavenSupportTest.java @@ -47,6 +47,7 @@ public class MavenSupportTest extends BindgenCommandBaseTest { private Path testResources; + @Override @BeforeClass public void setup() throws IOException { super.setup(); @@ -133,6 +134,7 @@ private boolean isJarAvailable(Path directory, String jarName) { return matchingFiles != null; } + @Override @AfterClass public void cleanup() throws IOException { super.cleanup(); diff --git a/misc/ballerina-bindgen/src/test/java/org/ballerinalang/bindgen/MethodsTestResource.java b/misc/ballerina-bindgen/src/test/java/org/ballerinalang/bindgen/MethodsTestResource.java index f4e7fda6e002..a9e7a59361fe 100644 --- a/misc/ballerina-bindgen/src/test/java/org/ballerinalang/bindgen/MethodsTestResource.java +++ b/misc/ballerina-bindgen/src/test/java/org/ballerinalang/bindgen/MethodsTestResource.java @@ -54,15 +54,15 @@ public IOException returnError() { return new IOException(); } - public Map returnInterface() { - return new HashMap(); + public Map returnInterface() { + return new HashMap<>(); } public Set returnGenericObject() { return new HashSet<>(); } - public AbstractSet returnAbstractObject() { + public AbstractSet returnAbstractObject() { return new HashSet<>(); } @@ -73,7 +73,7 @@ public System.Logger.Level returnEnum() { public void errorParam(IOException x, String[] y) { } - public void interfaceParam(Map x, Object[] y, Object[] z) { + public void interfaceParam(Map x, Object[] y, Object[] z) { } public void unsupportedParam(Object[][] y) { @@ -87,7 +87,7 @@ public Set genericObjectParam(Set x, int y, String[] z) { return x; } - public void abstractObjectParam(AbstractSet x, Object y, String z) { + public void abstractObjectParam(AbstractSet x, Object y, String z) { } public System.Logger.Level enumParam(System.Logger.Level x) { @@ -255,15 +255,15 @@ public static IOException returnStaticError() { return new IOException(); } - public static Map returnStaticInterface() { - return new HashMap(); + public static Map returnStaticInterface() { + return new HashMap<>(); } public static Set returnStaticGenericObject() { return new HashSet<>(); } - public static AbstractSet returnStaticAbstractObject() { + public static AbstractSet returnStaticAbstractObject() { return new HashSet<>(); } @@ -271,14 +271,14 @@ public static System.Logger.Level returnStaticEnum() { return System.Logger.Level.INFO; } - public static void interfaceStaticParam(Map x, boolean[] y) { + public static void interfaceStaticParam(Map x, boolean[] y) { } public static Set genericObjectStaticParam(Set x) { return x; } - public static void abstractObjectStaticParam(AbstractSet x, int y, Object z) { + public static void abstractObjectStaticParam(AbstractSet x, int y, Object z) { } public static System.Logger.Level enumStaticParam(System.Logger.Level x, Object[] y) { diff --git a/misc/ballerina-bindgen/src/test/java/org/ballerinalang/bindgen/ModuleMappingTest.java b/misc/ballerina-bindgen/src/test/java/org/ballerinalang/bindgen/ModuleMappingTest.java index f4a95083765d..95d2461d3e33 100644 --- a/misc/ballerina-bindgen/src/test/java/org/ballerinalang/bindgen/ModuleMappingTest.java +++ b/misc/ballerina-bindgen/src/test/java/org/ballerinalang/bindgen/ModuleMappingTest.java @@ -24,8 +24,8 @@ * * @since 2.0.0 */ -public class ModuleMappingTest { +public final class ModuleMappingTest { // Verifies that the module imports are correctly added in a final field. - public static final Comparator BUILD_AWARE_ORDER = null; + public static final Comparator BUILD_AWARE_ORDER = null; } diff --git a/misc/ballerina-gradle-plugins/docerina-gradle-plugin/src/main/java/org/ballerinalang/plugin/gradle/doc/DocerinaGen.java b/misc/ballerina-gradle-plugins/docerina-gradle-plugin/src/main/java/org/ballerinalang/plugin/gradle/doc/DocerinaGen.java index 199aef4477eb..ec18ae9aa6bb 100644 --- a/misc/ballerina-gradle-plugins/docerina-gradle-plugin/src/main/java/org/ballerinalang/plugin/gradle/doc/DocerinaGen.java +++ b/misc/ballerina-gradle-plugins/docerina-gradle-plugin/src/main/java/org/ballerinalang/plugin/gradle/doc/DocerinaGen.java @@ -26,10 +26,13 @@ /** * Generates Ballerina API docs for a given ballerina package. */ -public class DocerinaGen { +public final class DocerinaGen { private static final PrintStream out = System.out; + private DocerinaGen() { + } + /** * Main method to generate Ballerina API docs. * @param args command line arguments diff --git a/misc/ballerinalang-data-mapper/src/main/java/org/ballerinalang/datamapper/AIDataMapperCodeActionUtil.java b/misc/ballerinalang-data-mapper/src/main/java/org/ballerinalang/datamapper/AIDataMapperCodeActionUtil.java index 697ab86f588c..616acdca1f52 100644 --- a/misc/ballerinalang-data-mapper/src/main/java/org/ballerinalang/datamapper/AIDataMapperCodeActionUtil.java +++ b/misc/ballerinalang-data-mapper/src/main/java/org/ballerinalang/datamapper/AIDataMapperCodeActionUtil.java @@ -437,9 +437,7 @@ private String getGeneratedRecordMapping(CodeActionContext context, String found rightRecordJSON.addProperty(TYPE, "object"); rightRecordJSON.add(PROPERTIES, rightSchema); - Map rightSchemaMap = new Gson().fromJson(rightSchema, - new TypeToken>() { - }.getType()); + Map rightSchemaMap = new Gson().fromJson(rightSchema, new TypeToken<>() { }); this.isOptionalMap.clear(); generateOptionalMap(rightSchemaMap, foundTypeRight); @@ -452,9 +450,7 @@ private String getGeneratedRecordMapping(CodeActionContext context, String found leftRecordJSON.addProperty(TYPE, "object"); leftRecordJSON.add(PROPERTIES, leftSchema); - Map leftSchemaMap = new Gson().fromJson(leftSchema, - new TypeToken>() { - }.getType()); + Map leftSchemaMap = new Gson().fromJson(leftSchema, new TypeToken<>() { }); this.leftFieldMap.clear(); getLeftFields(leftSchemaMap, ""); } @@ -484,14 +480,14 @@ private JsonObject insertRestFields(JsonObject rightSchema, String foundTypeRigh private void generateOptionalMap(Map rightSchemaMap, String foundTypeRight) { for (Map.Entry field : rightSchemaMap.entrySet()) { StringBuilder optionalKey = new StringBuilder(foundTypeRight.toLowerCase()); - if (!(((Map) field.getValue()).containsKey(OPTIONAL))) { + if (!(((Map) field.getValue()).containsKey(OPTIONAL))) { optionalKey.append(".").append(field.getKey()); - generateOptionalMap((Map) ((Map) field.getValue()).get(PROPERTIES), + generateOptionalMap((Map) ((Map) field.getValue()).get(PROPERTIES), optionalKey.toString()); - } else if ((boolean) ((Map) field.getValue()).get(OPTIONAL) | + } else if ((boolean) ((Map) field.getValue()).get(OPTIONAL) | (checkForOptionalRecordField(optionalKey.toString()) > 0)) { optionalKey.append(".").append(field.getKey()); - this.isOptionalMap.put(optionalKey.toString(), ((Map) field.getValue()).get(SIGNATURE). + this.isOptionalMap.put(optionalKey.toString(), ((Map) field.getValue()).get(SIGNATURE). toString()); } } @@ -513,14 +509,14 @@ private void getLeftFields(Map leftSchemaMap, String fieldName) if (!fieldName.isEmpty()) { fieldKey.append(fieldName).append("."); } - if (!(((Map) field.getValue()).containsKey(READONLY))) { + if (!(((Map) field.getValue()).containsKey(READONLY))) { fieldKey.append(field.getKey()); - getLeftFields((Map) ((Map) field.getValue()).get(PROPERTIES), + getLeftFields((Map) ((Map) field.getValue()).get(PROPERTIES), fieldKey.toString()); } else { fieldKey.append(field.getKey()); - this.leftFieldMap.put(fieldKey.toString(), ((Map) field.getValue()).get(TYPE).toString()); - if ((((Map) field.getValue()).get(READONLY)).toString().contains("true")) { + this.leftFieldMap.put(fieldKey.toString(), ((Map) field.getValue()).get(TYPE).toString()); + if ((((Map) field.getValue()).get(READONLY)).toString().contains("true")) { this.leftReadOnlyFields.add(field.getKey()); } } @@ -534,9 +530,9 @@ private void getLeftFields(Map leftSchemaMap, String fieldName) * @param schemaFields {@link List} */ private void getSpreadFieldDetails(String key, Collection schemaFields) { - Iterator iterator = schemaFields.iterator(); + Iterator iterator = schemaFields.iterator(); while (iterator.hasNext()) { - RecordFieldSymbol attribute = (RecordFieldSymbol) iterator.next(); + RecordFieldSymbol attribute = iterator.next(); TypeSymbol attributeType = CommonUtil.getRawType(attribute.typeDescriptor()); if (!key.isEmpty()) { @@ -577,12 +573,12 @@ private void getSpreadFieldDetails(String key, Collection sch private void getResponseKeys(Map leftSchemaMap, String keyName) { for (Map.Entry field : leftSchemaMap.entrySet()) { StringBuilder fieldKey = new StringBuilder(); - Map treeMap = null; + Map treeMap = null; if (!keyName.isEmpty()) { fieldKey.append(keyName).append("."); } try { - treeMap = (Map) field.getValue(); + treeMap = (Map) field.getValue(); } catch (Exception e) { //ignore } @@ -757,8 +753,7 @@ private String getMappingFromServer(JsonArray dataToSend, throw new IOException("Error: AI service error"); } } - JsonParser parser = new JsonParser(); - return parser.parse(response.getData()).getAsJsonObject().get("answer").toString(); + return JsonParser.parseString(response.getData()).getAsJsonObject().get("answer").toString(); } catch (IOException e) { throw new IOException("Error connecting the AI service" + e.getMessage(), e); } @@ -876,9 +871,8 @@ private String generateMappingFunction(String mappingFromServer, String foundTyp //To generate the default values try { Map responseMap = new Gson().fromJson( - new JsonParser().parse(mappingFromServer).getAsJsonObject(), - new TypeToken>() { - }.getType()); + JsonParser.parseString(mappingFromServer).getAsJsonObject(), + new TypeToken<>() { }); getResponseKeys(responseMap, ""); HashSet unionKeys = new HashSet<>(this.responseFieldMap.keySet()); unionKeys.addAll(this.leftFieldMap.keySet()); diff --git a/misc/ballerinalang-data-mapper/src/main/java/org/ballerinalang/datamapper/utils/DefaultValueGenerator.java b/misc/ballerinalang-data-mapper/src/main/java/org/ballerinalang/datamapper/utils/DefaultValueGenerator.java index 2822366e76f2..c208a795c931 100644 --- a/misc/ballerinalang-data-mapper/src/main/java/org/ballerinalang/datamapper/utils/DefaultValueGenerator.java +++ b/misc/ballerinalang-data-mapper/src/main/java/org/ballerinalang/datamapper/utils/DefaultValueGenerator.java @@ -23,47 +23,23 @@ /** * Return default value for TypeDescKind. */ -public class DefaultValueGenerator { +public final class DefaultValueGenerator { + + private DefaultValueGenerator() { + } + public static Serializable generateDefaultValues(String type) { - switch (type) { - case "int": - case "Signed8": - case "Unsigned8": - case "Signed16": - case "Unsigned16": - case "Signed32": - case "Unsigned32": - case "byte": - return 0; - case "float": - case "decimal": - return 0.0; - case "string": - case "Char": - return "\"\""; - case "BOOLEAN": - return false; - case "nil": - case "any": - case "union": - case "json": - return "()"; - case "array": - case "tuple": - return "[]"; - case "object": - return "new T()"; - case "record": - case "map": - return "{}"; - case "xml": - case "Element": - case "ProcessingInstruction": - case "Comment": - case "Text": - return "``"; - default: - return ""; - } + return switch (type) { + case "int", "Signed8", "Unsigned8", "Signed16", "Unsigned16", "Signed32", "Unsigned32", "byte" -> 0; + case "float", "decimal" -> 0.0; + case "string", "Char" -> "\"\""; + case "BOOLEAN" -> false; + case "nil", "any", "union", "json" -> "()"; + case "array", "tuple" -> "[]"; + case "object" -> "new T()"; + case "record", "map" -> "{}"; + case "xml", "Element", "ProcessingInstruction", "Comment", "Text" -> "``"; + default -> ""; + }; } } diff --git a/misc/ballerinalang-data-mapper/src/main/java/org/ballerinalang/datamapper/utils/HttpClientRequest.java b/misc/ballerinalang-data-mapper/src/main/java/org/ballerinalang/datamapper/utils/HttpClientRequest.java index a85c8318303b..ce11ee7706b3 100644 --- a/misc/ballerinalang-data-mapper/src/main/java/org/ballerinalang/datamapper/utils/HttpClientRequest.java +++ b/misc/ballerinalang-data-mapper/src/main/java/org/ballerinalang/datamapper/utils/HttpClientRequest.java @@ -34,11 +34,15 @@ /** * This class can be used to send http request. */ -public class HttpClientRequest { +public final class HttpClientRequest { + private static final Logger LOG = LoggerFactory.getLogger(HttpClientRequest.class); private static final int DEFAULT_READ_TIMEOUT = 30000; private static final int DEFAULT_CONNECT_TIMEOUT = 15000; + private HttpClientRequest() { + } + /** * Send an HTTP POST request to a service. * diff --git a/misc/ballerinalang-data-mapper/src/test/java/org/ballerinalang/datamapper/util/DataMapperTestUtils.java b/misc/ballerinalang-data-mapper/src/test/java/org/ballerinalang/datamapper/util/DataMapperTestUtils.java index 301cba00824a..66d61b34af7a 100644 --- a/misc/ballerinalang-data-mapper/src/test/java/org/ballerinalang/datamapper/util/DataMapperTestUtils.java +++ b/misc/ballerinalang-data-mapper/src/test/java/org/ballerinalang/datamapper/util/DataMapperTestUtils.java @@ -37,19 +37,20 @@ import java.nio.file.Path; import java.util.ArrayList; import java.util.List; -import java.util.stream.Collectors; /** * Common utils that are reused within data-mapper test suits. */ -public class DataMapperTestUtils { +public final class DataMapperTestUtils { - private static JsonParser parser = new JsonParser(); private static Path sourcesPath = new File(DataMapperTestUtils.class.getClassLoader().getResource("codeaction") .getFile()).toPath(); private static final LanguageServerContext serverContext = new LanguageServerContextImpl(); private static final WorkspaceManager workspaceManager = new BallerinaWorkspaceManager(serverContext); + private DataMapperTestUtils() { + } + /** * Convert Data-mapper response to Jason Object. @@ -58,7 +59,7 @@ public class DataMapperTestUtils { * @return {@link JsonObject} Response as Jason Object */ private static JsonObject getResponseJson(String response) { - JsonObject responseJson = parser.parse(response).getAsJsonObject(); + JsonObject responseJson = JsonParser.parseString(response).getAsJsonObject(); responseJson.remove("id"); return responseJson; } @@ -87,7 +88,7 @@ public static JsonObject getCodeActionResponse(String source, JsonObject configJ configJsonObject.get("character").getAsInt()); diags = diags.stream(). filter(diag -> PositionUtil.isWithinRange(pos, diag.getRange())) - .collect(Collectors.toList()); + .toList(); CodeActionContext codeActionContext = new CodeActionContext(diags); Range range = new Range(pos, pos); String response = TestUtil.getCodeActionResponse(serviceEndpoint, sourcePath.toString(), range, diff --git a/misc/ballerinalang-data-mapper/src/test/java/org/ballerinalang/datamapper/util/FileUtils.java b/misc/ballerinalang-data-mapper/src/test/java/org/ballerinalang/datamapper/util/FileUtils.java index 892ee8204f00..62adb7de8d84 100644 --- a/misc/ballerinalang-data-mapper/src/test/java/org/ballerinalang/datamapper/util/FileUtils.java +++ b/misc/ballerinalang-data-mapper/src/test/java/org/ballerinalang/datamapper/util/FileUtils.java @@ -30,14 +30,15 @@ /** * File utils for reading the file content. */ -public class FileUtils { - - private static final JsonParser JSON_PARSER = new JsonParser(); +public final class FileUtils { private static final Logger LOGGER = LoggerFactory.getLogger(FileUtils.class); public static final Path RES_DIR = Paths.get("src/test/resources/").toAbsolutePath(); + private FileUtils() { + } + /** * Get the file content. * @param filePath path to the file @@ -50,7 +51,7 @@ public static JsonObject fileContentAsObject(String filePath) { } catch (IOException ex) { LOGGER.error(ex.getMessage()); } - return JSON_PARSER.parse(contentAsString).getAsJsonObject(); + return JsonParser.parseString(contentAsString).getAsJsonObject(); } } diff --git a/misc/ballerinalang-data-mapper/src/test/java/org/ballerinalang/datamapper/util/TestUtil.java b/misc/ballerinalang-data-mapper/src/test/java/org/ballerinalang/datamapper/util/TestUtil.java index ad1d07497065..89751f437ae0 100644 --- a/misc/ballerinalang-data-mapper/src/test/java/org/ballerinalang/datamapper/util/TestUtil.java +++ b/misc/ballerinalang-data-mapper/src/test/java/org/ballerinalang/datamapper/util/TestUtil.java @@ -67,7 +67,7 @@ /** * Common utils that are reused within test suits. */ -public class TestUtil { +public final class TestUtil { private static final String CODE_ACTION = "textDocument/codeAction"; @@ -91,7 +91,7 @@ public static String getCodeActionResponse(Endpoint serviceEndpoint, String file CodeActionContext context) { TextDocumentIdentifier identifier = getTextDocumentIdentifier(filePath); CodeActionParams codeActionParams = new CodeActionParams(identifier, range, context); - CompletableFuture result = serviceEndpoint.request(CODE_ACTION, codeActionParams); + CompletableFuture result = serviceEndpoint.request(CODE_ACTION, codeActionParams); return getResponseString(result); } @@ -182,7 +182,7 @@ public static TextDocumentIdentifier getTextDocumentIdentifier(String filePath) return identifier; } - public static String getResponseString(CompletableFuture completableFuture) { + public static String getResponseString(CompletableFuture completableFuture) { ResponseMessage jsonrpcResponse = new ResponseMessage(); try { jsonrpcResponse.setId("324"); diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/BallerinaStackFrame.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/BallerinaStackFrame.java index 0994d2a0ba94..93fdb18c6a86 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/BallerinaStackFrame.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/BallerinaStackFrame.java @@ -77,7 +77,7 @@ public StackFrameProxyImpl getJStackFrame() { /** * Returns a debugger adapter protocol compatible instance of this breakpoint. * - * @return as an instance of {@link org.eclipse.lsp4j.debug.StackFrame} + * @return as an instance of {@link StackFrame} */ public Optional getAsDAPStackFrame() { if (dapStackFrame != null) { diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/BreakpointProcessor.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/BreakpointProcessor.java index 4289eff9769d..d0043efada68 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/BreakpointProcessor.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/BreakpointProcessor.java @@ -335,8 +335,7 @@ private CompletableFuture evaluateBreakpointCondition(String expression */ void printLogMessage(BreakpointEvent event, LogMessage logMessage, int lineNumber) { try { - if (logMessage instanceof TemplateLogMessage) { - TemplateLogMessage template = (TemplateLogMessage) logMessage; + if (logMessage instanceof TemplateLogMessage template) { List expressions = template.getExpressions(); List evaluationResults = new ArrayList<>(); for (String expression : expressions) { diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/JBallerinaDebugServer.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/JBallerinaDebugServer.java index 9906616e1777..6c4bcdb776b3 100755 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/JBallerinaDebugServer.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/JBallerinaDebugServer.java @@ -492,10 +492,10 @@ public CompletableFuture evaluate(EvaluateArguments args) { return CompletableFuture.completedFuture(response); } else if (variable instanceof BSimpleVariable) { variable.getDapVariable().setVariablesReference(0); - } else if (variable instanceof BCompoundVariable) { + } else if (variable instanceof BCompoundVariable bCompoundVariable) { int variableReference = nextVarReference.getAndIncrement(); variable.getDapVariable().setVariablesReference(variableReference); - loadedCompoundVariables.put(variableReference, (BCompoundVariable) variable); + loadedCompoundVariables.put(variableReference, bCompoundVariable); updateVariableToStackFrameMap(args.getFrameId(), variableReference); } Variable dapVariable = variable.getDapVariable(); @@ -781,10 +781,10 @@ private Variable[] computeGlobalVariables(SuspendedContext context, int stackFra } if (variable instanceof BSimpleVariable) { variable.getDapVariable().setVariablesReference(0); - } else if (variable instanceof BCompoundVariable) { + } else if (variable instanceof BCompoundVariable bCompoundVariable) { int variableReference = nextVarReference.getAndIncrement(); variable.getDapVariable().setVariablesReference(variableReference); - loadedCompoundVariables.put(variableReference, (BCompoundVariable) variable); + loadedCompoundVariables.put(variableReference, bCompoundVariable); updateVariableToStackFrameMap(stackFrameReference, variableReference); } globalVars.add(variable.getDapVariable()); @@ -852,10 +852,10 @@ private Variable getAsDapVariable(String name, Value value, Integer stackFrameRe return null; } else if (variable instanceof BSimpleVariable) { variable.getDapVariable().setVariablesReference(0); - } else if (variable instanceof BCompoundVariable) { + } else if (variable instanceof BCompoundVariable bCompoundVariable) { int variableReference = nextVarReference.getAndIncrement(); variable.getDapVariable().setVariablesReference(variableReference); - loadedCompoundVariables.put(variableReference, (BCompoundVariable) variable); + loadedCompoundVariables.put(variableReference, bCompoundVariable); updateVariableToStackFrameMap(stackFrameRef, variableReference); } return variable.getDapVariable(); @@ -868,12 +868,12 @@ private Variable[] computeChildVariables(VariablesArguments args) { return new Variable[0]; } - if (parentVar instanceof IndexedCompoundVariable) { + if (parentVar instanceof IndexedCompoundVariable indexedCompoundVariable) { // Handles indexed variables. int startIndex = (args.getStart() != null) ? args.getStart() : 0; int count = (args.getCount() != null) ? args.getCount() : 0; - Either, List> childVars = ((IndexedCompoundVariable) parentVar) + Either, List> childVars = indexedCompoundVariable .getIndexedChildVariables(startIndex, count); if (childVars.isLeft()) { // Handles map-type indexed variables. @@ -883,9 +883,9 @@ private Variable[] computeChildVariables(VariablesArguments args) { return createVariableArrayFrom(args, childVars.getRight()); } return new Variable[0]; - } else if (parentVar instanceof NamedCompoundVariable) { + } else if (parentVar instanceof NamedCompoundVariable namedCompoundVariable) { // Handles named variables. - Map childVars = ((NamedCompoundVariable) parentVar).getNamedChildVariables(); + Map childVars = namedCompoundVariable.getNamedChildVariables(); return createVariableArrayFrom(args, childVars); } @@ -901,10 +901,10 @@ private Variable[] createVariableArrayFrom(VariablesArguments args, Map return null; } else if (variable instanceof BSimpleVariable) { variable.getDapVariable().setVariablesReference(0); - } else if (variable instanceof BCompoundVariable) { + } else if (variable instanceof BCompoundVariable bCompoundVariable) { int variableReference = nextVarReference.getAndIncrement(); variable.getDapVariable().setVariablesReference(variableReference); - loadedCompoundVariables.put(variableReference, (BCompoundVariable) variable); + loadedCompoundVariables.put(variableReference, bCompoundVariable); updateVariableToStackFrameMap(args.getVariablesReference(), variableReference); } return variable.getDapVariable(); @@ -1075,8 +1075,8 @@ private void startListeningToProgramOutput() { outputLogger.sendProgramOutput(line); } } catch (Exception e) { - String host = clientConfigHolder instanceof ClientAttachConfigHolder ? - ((ClientAttachConfigHolder) clientConfigHolder).getHostName().orElse(LOCAL_HOST) : LOCAL_HOST; + String host = clientConfigHolder instanceof ClientAttachConfigHolder clientAttachConfigHolder ? + clientAttachConfigHolder.getHostName().orElse(LOCAL_HOST) : LOCAL_HOST; String portName; try { portName = Integer.toString(clientConfigHolder.getDebuggePort()); diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/JDIEventProcessor.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/JDIEventProcessor.java index 218a9aa8a0b3..93722428b10b 100755 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/JDIEventProcessor.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/JDIEventProcessor.java @@ -99,17 +99,14 @@ void startListening() { } private void processEvent(EventSet eventSet, Event event) { - if (event instanceof ClassPrepareEvent) { + if (event instanceof ClassPrepareEvent evt) { if (context.getLastInstruction() != DebugInstruction.STEP_OVER) { - ClassPrepareEvent evt = (ClassPrepareEvent) event; breakpointProcessor.activateUserBreakPoints(evt.referenceType(), true); } eventSet.resume(); - } else if (event instanceof BreakpointEvent) { - BreakpointEvent bpEvent = (BreakpointEvent) event; + } else if (event instanceof BreakpointEvent bpEvent) { breakpointProcessor.processBreakpointEvent(bpEvent); - } else if (event instanceof StepEvent) { - StepEvent stepEvent = (StepEvent) event; + } else if (event instanceof StepEvent stepEvent) { int threadId = (int) stepEvent.thread().uniqueID(); if (isBallerinaSource(stepEvent.location())) { notifyStopEvent(event); @@ -217,10 +214,10 @@ private boolean isBallerinaSource(Location location) { * Notifies DAP client that the remote VM is stopped due to a breakpoint hit / step event. */ void notifyStopEvent(Event event) { - if (event instanceof BreakpointEvent) { - notifyStopEvent(StoppedEventArgumentsReason.BREAKPOINT, ((BreakpointEvent) event).thread().uniqueID()); - } else if (event instanceof StepEvent) { - notifyStopEvent(StoppedEventArgumentsReason.STEP, ((StepEvent) event).thread().uniqueID()); + if (event instanceof BreakpointEvent breakpointEvent) { + notifyStopEvent(StoppedEventArgumentsReason.BREAKPOINT, breakpointEvent.thread().uniqueID()); + } else if (event instanceof StepEvent stepEvent) { + notifyStopEvent(StoppedEventArgumentsReason.STEP, stepEvent.thread().uniqueID()); } } diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/completion/CompletionGenerator.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/completion/CompletionGenerator.java index 64060241667c..0314d826b737 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/completion/CompletionGenerator.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/completion/CompletionGenerator.java @@ -38,7 +38,7 @@ * * @since 2201.1.0 */ -public class CompletionGenerator { +public final class CompletionGenerator { private CompletionGenerator() { } diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/completion/context/AsyncSendActionNodeContext.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/completion/context/AsyncSendActionNodeContext.java index 25a0260bd4d4..f7761b188435 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/completion/context/AsyncSendActionNodeContext.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/completion/context/AsyncSendActionNodeContext.java @@ -15,6 +15,7 @@ */ package org.ballerinalang.debugadapter.completion.context; +import io.ballerina.compiler.api.symbols.MethodSymbol; import io.ballerina.compiler.api.symbols.Symbol; import io.ballerina.compiler.api.symbols.SymbolKind; import io.ballerina.compiler.api.symbols.TypeSymbol; @@ -27,7 +28,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; import static org.ballerinalang.debugadapter.completion.util.CommonUtil.getClientActions; import static org.ballerinalang.debugadapter.completion.util.CompletionUtil.getCompletionItemList; @@ -61,7 +61,7 @@ private List getFilteredItems(CompletionContext context, Express Covers the following case where a is a client object and we suggest the remote actions (1) a -> g */ - List clientActions = getClientActions(expressionType.get()); + List clientActions = getClientActions(expressionType.get()); completionItems.addAll(getCompletionItemList(clientActions, context)); } else { /* @@ -71,7 +71,7 @@ private List getFilteredItems(CompletionContext context, Express */ List filteredWorkers = visibleSymbols.stream() .filter(symbol -> symbol.kind() == SymbolKind.WORKER) - .collect(Collectors.toList()); + .toList(); completionItems.addAll(getCompletionItemList(filteredWorkers, context)); } diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/completion/context/RemoteMethodCallActionNodeContext.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/completion/context/RemoteMethodCallActionNodeContext.java index 8e32e2b37d64..5f60a0de839e 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/completion/context/RemoteMethodCallActionNodeContext.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/completion/context/RemoteMethodCallActionNodeContext.java @@ -15,6 +15,7 @@ */ package org.ballerinalang.debugadapter.completion.context; +import io.ballerina.compiler.api.symbols.MethodSymbol; import io.ballerina.compiler.api.symbols.Symbol; import io.ballerina.compiler.api.symbols.TypeSymbol; import io.ballerina.compiler.syntax.tree.QualifiedNameReferenceNode; @@ -61,7 +62,7 @@ public List getCompletions(CompletionContext context, RemoteMeth Covers the following case where a is a client object and we suggest the remote actions (1) a -> g */ - List clientActions = getClientActions(expressionType.get()); + List clientActions = getClientActions(expressionType.get()); completionItems.addAll(getCompletionItemList(clientActions, context)); } else if (CommonUtil.isInMethodCallParameterContext(context, node)) { /* diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/completion/resolver/FieldAccessCompletionResolver.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/completion/resolver/FieldAccessCompletionResolver.java index ac5d700ac01f..ce964680a078 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/completion/resolver/FieldAccessCompletionResolver.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/completion/resolver/FieldAccessCompletionResolver.java @@ -282,8 +282,7 @@ private boolean withValidAccessModifiers(Node exprNode, Symbol symbol, Package c boolean isPublic = false; boolean isResource = false; - if (symbol instanceof Qualifiable) { - Qualifiable qSymbol = (Qualifiable) symbol; + if (symbol instanceof Qualifiable qSymbol) { isPrivate = qSymbol.qualifiers().contains(Qualifier.PRIVATE); isPublic = qSymbol.qualifiers().contains(Qualifier.PUBLIC); isResource = qSymbol.qualifiers().contains(Qualifier.RESOURCE); @@ -341,34 +340,22 @@ private Optional getTypeDescriptor(Symbol symbol) { if (symbol == null) { return Optional.empty(); } - switch (symbol.kind()) { - case TYPE_DEFINITION: - return Optional.ofNullable(((TypeDefinitionSymbol) symbol).typeDescriptor()); - case VARIABLE: - return Optional.ofNullable(((VariableSymbol) symbol).typeDescriptor()); - case PARAMETER: - return Optional.ofNullable(((ParameterSymbol) symbol).typeDescriptor()); - case ANNOTATION: - return ((AnnotationSymbol) symbol).typeDescriptor(); - case FUNCTION: - case METHOD: - return Optional.ofNullable(((FunctionSymbol) symbol).typeDescriptor()); - case CONSTANT: - case ENUM_MEMBER: - return Optional.ofNullable(((ConstantSymbol) symbol).typeDescriptor()); - case CLASS: - return Optional.of((ClassSymbol) symbol); - case RECORD_FIELD: - return Optional.ofNullable(((RecordFieldSymbol) symbol).typeDescriptor()); - case OBJECT_FIELD: - return Optional.of(((ObjectFieldSymbol) symbol).typeDescriptor()); - case CLASS_FIELD: - return Optional.of(((ClassFieldSymbol) symbol).typeDescriptor()); - case TYPE: - return Optional.of((TypeSymbol) symbol); - default: - return Optional.empty(); - } + return switch (symbol.kind()) { + case TYPE_DEFINITION -> Optional.ofNullable(((TypeDefinitionSymbol) symbol).typeDescriptor()); + case VARIABLE -> Optional.ofNullable(((VariableSymbol) symbol).typeDescriptor()); + case PARAMETER -> Optional.ofNullable(((ParameterSymbol) symbol).typeDescriptor()); + case ANNOTATION -> ((AnnotationSymbol) symbol).typeDescriptor(); + case FUNCTION, + METHOD -> Optional.ofNullable(((FunctionSymbol) symbol).typeDescriptor()); + case CONSTANT, + ENUM_MEMBER -> Optional.ofNullable(((ConstantSymbol) symbol).typeDescriptor()); + case CLASS -> Optional.of((ClassSymbol) symbol); + case RECORD_FIELD -> Optional.ofNullable(((RecordFieldSymbol) symbol).typeDescriptor()); + case OBJECT_FIELD -> Optional.of(((ObjectFieldSymbol) symbol).typeDescriptor()); + case CLASS_FIELD -> Optional.of(((ClassFieldSymbol) symbol).typeDescriptor()); + case TYPE -> Optional.of((TypeSymbol) symbol); + default -> Optional.empty(); + }; } /** diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/completion/util/CommonUtil.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/completion/util/CommonUtil.java index ece0c7076683..1dbc389ef4ec 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/completion/util/CommonUtil.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/completion/util/CommonUtil.java @@ -19,6 +19,7 @@ import io.ballerina.compiler.api.SemanticModel; import io.ballerina.compiler.api.symbols.FunctionTypeSymbol; import io.ballerina.compiler.api.symbols.IntersectionTypeSymbol; +import io.ballerina.compiler.api.symbols.MethodSymbol; import io.ballerina.compiler.api.symbols.ModuleSymbol; import io.ballerina.compiler.api.symbols.ObjectTypeSymbol; import io.ballerina.compiler.api.symbols.ParameterSymbol; @@ -65,7 +66,7 @@ * * @since 2201.1.0 */ -public class CommonUtil { +public final class CommonUtil { private static final Pattern TYPE_NAME_DECOMPOSE_PATTERN = Pattern.compile("([\\w_.]*)/([\\w._]*):([\\w.-]*)"); @@ -425,13 +426,13 @@ public static Map currentDocImportsMap(Comp * @param symbol Endpoint variable symbol to evaluate * @return {@link List} List of extracted actions as Symbol Info */ - public static List getClientActions(Symbol symbol) { + public static List getClientActions(Symbol symbol) { if (!SymbolUtil.isObject(symbol)) { return new ArrayList<>(); } TypeSymbol typeDescriptor = CommonUtil.getRawType(SymbolUtil.getTypeDescriptor(symbol).orElseThrow()); return ((ObjectTypeSymbol) typeDescriptor).methods().values().stream() .filter(method -> method.qualifiers().contains(Qualifier.REMOTE)) - .collect(Collectors.toList()); + .toList(); } } diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/completion/util/CompletionUtil.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/completion/util/CompletionUtil.java index 55a32e832d7f..9db4184b589a 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/completion/util/CompletionUtil.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/completion/util/CompletionUtil.java @@ -54,11 +54,14 @@ * * @since 2.0.0 */ -public class CompletionUtil { +public final class CompletionUtil { private static final String PARENTHESIS = "()"; private static final List triggerCharacters = Arrays.asList(".", ">"); + private CompletionUtil() { + } + /** * Get the updated bal file content which includes debug console expression. * @@ -206,37 +209,19 @@ private static List populateBallerinaFunctionCompletionItems(Sym } private static CompletionItemType getCompletionItemType(Symbol symbol) { - switch (symbol.kind()) { - case MODULE: - return CompletionItemType.MODULE; - case FUNCTION: - return CompletionItemType.FUNCTION; - case METHOD: - case RESOURCE_METHOD: - return CompletionItemType.METHOD; - case VARIABLE: - return CompletionItemType.VARIABLE; - case CLASS: - return CompletionItemType.CLASS; - case RECORD_FIELD: - case OBJECT_FIELD: - case CLASS_FIELD: - return CompletionItemType.FIELD; - case ENUM: - return CompletionItemType.ENUM; - case XMLNS: - case CONSTANT: - case TYPE_DEFINITION: - case TYPE: - case SERVICE_DECLARATION: - case WORKER: - case ANNOTATION: - case ENUM_MEMBER: - case PARAMETER: - case PATH_PARAMETER: - default: - return null; - } + return switch (symbol.kind()) { + case MODULE -> CompletionItemType.MODULE; + case FUNCTION -> CompletionItemType.FUNCTION; + case METHOD, + RESOURCE_METHOD -> CompletionItemType.METHOD; + case VARIABLE -> CompletionItemType.VARIABLE; + case CLASS -> CompletionItemType.CLASS; + case RECORD_FIELD, + OBJECT_FIELD, + CLASS_FIELD -> CompletionItemType.FIELD; + case ENUM -> CompletionItemType.ENUM; + default -> null; + }; } /** diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/completion/util/QNameReferenceUtil.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/completion/util/QNameReferenceUtil.java index 53d74c3ae911..c5de24405d24 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/completion/util/QNameReferenceUtil.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/completion/util/QNameReferenceUtil.java @@ -28,14 +28,13 @@ import java.util.List; import java.util.Optional; import java.util.function.Predicate; -import java.util.stream.Collectors; /** * Holds the set of utilities to get the qualified name reference associated Completion Items. * * @since 2201.1.0 */ -public class QNameReferenceUtil { +public final class QNameReferenceUtil { private QNameReferenceUtil() { } @@ -76,7 +75,7 @@ public static List getModuleContent(CompletionContext context, Optional module = CommonUtil.searchModuleForAlias(context, QNameReferenceUtil.getAlias(qNameRef)); return module.map(moduleSymbol -> moduleSymbol.allSymbols().stream() .filter(predicate) - .collect(Collectors.toList())) + .toList()) .orElseGet(ArrayList::new); } @@ -88,10 +87,10 @@ public static List getModuleContent(CompletionContext context, * @return {@link Boolean} */ public static boolean onQualifiedNameIdentifier(CompletionContext context, Node node) { - if (node.kind() != SyntaxKind.QUALIFIED_NAME_REFERENCE || !(node instanceof QualifiedNameReferenceNode)) { + if (node.kind() != SyntaxKind.QUALIFIED_NAME_REFERENCE || + !(node instanceof QualifiedNameReferenceNode qNameRef)) { return false; } - QualifiedNameReferenceNode qNameRef = (QualifiedNameReferenceNode) node; int colonPos = qNameRef.colon().textRange().startOffset(); int cursor = context.getCursorPositionInTree(); @@ -127,6 +126,6 @@ public static List getExpressionContextEntries(CompletionContext ctx, St || symbol.kind() == SymbolKind.TYPE_DEFINITION || symbol.kind() == SymbolKind.CLASS || symbol instanceof VariableSymbol) - .collect(Collectors.toList())).orElseGet(ArrayList::new); + .toList()).orElseGet(ArrayList::new); } } diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/completion/util/SymbolUtil.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/completion/util/SymbolUtil.java index e792d5b60c3e..a0b3e72e8469 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/completion/util/SymbolUtil.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/completion/util/SymbolUtil.java @@ -38,7 +38,7 @@ * * @since 2201.1.0 */ -public class SymbolUtil { +public final class SymbolUtil { private SymbolUtil() { } @@ -85,34 +85,22 @@ public static Optional getTypeDescriptor(Symbol symbol) { if (symbol == null) { return Optional.empty(); } - switch (symbol.kind()) { - case TYPE_DEFINITION: - return Optional.ofNullable(((TypeDefinitionSymbol) symbol).typeDescriptor()); - case VARIABLE: - return Optional.ofNullable(((VariableSymbol) symbol).typeDescriptor()); - case PARAMETER: - return Optional.ofNullable(((ParameterSymbol) symbol).typeDescriptor()); - case ANNOTATION: - return ((AnnotationSymbol) symbol).typeDescriptor(); - case FUNCTION: - case METHOD: - return Optional.ofNullable(((FunctionSymbol) symbol).typeDescriptor()); - case CONSTANT: - case ENUM_MEMBER: - return Optional.ofNullable(((ConstantSymbol) symbol).typeDescriptor()); - case CLASS: - return Optional.of((ClassSymbol) symbol); - case RECORD_FIELD: - return Optional.ofNullable(((RecordFieldSymbol) symbol).typeDescriptor()); - case OBJECT_FIELD: - return Optional.of(((ObjectFieldSymbol) symbol).typeDescriptor()); - case CLASS_FIELD: - return Optional.of(((ClassFieldSymbol) symbol).typeDescriptor()); - case TYPE: - return Optional.of((TypeSymbol) symbol); - default: - return Optional.empty(); - } + return switch (symbol.kind()) { + case TYPE_DEFINITION -> Optional.ofNullable(((TypeDefinitionSymbol) symbol).typeDescriptor()); + case VARIABLE -> Optional.ofNullable(((VariableSymbol) symbol).typeDescriptor()); + case PARAMETER -> Optional.ofNullable(((ParameterSymbol) symbol).typeDescriptor()); + case ANNOTATION -> ((AnnotationSymbol) symbol).typeDescriptor(); + case FUNCTION, + METHOD -> Optional.ofNullable(((FunctionSymbol) symbol).typeDescriptor()); + case CONSTANT, + ENUM_MEMBER -> Optional.ofNullable(((ConstantSymbol) symbol).typeDescriptor()); + case CLASS -> Optional.of((ClassSymbol) symbol); + case RECORD_FIELD -> Optional.ofNullable(((RecordFieldSymbol) symbol).typeDescriptor()); + case OBJECT_FIELD -> Optional.of(((ObjectFieldSymbol) symbol).typeDescriptor()); + case CLASS_FIELD -> Optional.of(((ClassFieldSymbol) symbol).typeDescriptor()); + case TYPE -> Optional.of((TypeSymbol) symbol); + default -> Optional.empty(); + }; } /** diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/config/ClientConfigHolder.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/config/ClientConfigHolder.java index f34e0877fb78..ebe94c4d886b 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/config/ClientConfigHolder.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/config/ClientConfigHolder.java @@ -74,17 +74,16 @@ public Optional getExtendedCapabilities() { return Optional.of(extendedClientCapabilities); } Object capabilitiesObj = clientRequestArgs.get(ARG_CAPABILITIES); - if (!(capabilitiesObj instanceof Map)) { + if (!(capabilitiesObj instanceof Map capabilities)) { return Optional.empty(); } - Map capabilities = (Map) capabilitiesObj; extendedClientCapabilities = new ExtendedClientCapabilities(); Object readOnlyEditorConfig = capabilities.get(ARG_SUPPORT_READONLY_EDITOR); - if (readOnlyEditorConfig instanceof Boolean) { - extendedClientCapabilities.setSupportsReadOnlyEditors((Boolean) readOnlyEditorConfig); - } else if (readOnlyEditorConfig instanceof String) { - extendedClientCapabilities.setSupportsReadOnlyEditors(Boolean.parseBoolean((String) readOnlyEditorConfig)); + if (readOnlyEditorConfig instanceof Boolean b) { + extendedClientCapabilities.setSupportsReadOnlyEditors(b); + } else if (readOnlyEditorConfig instanceof String s) { + extendedClientCapabilities.setSupportsReadOnlyEditors(Boolean.parseBoolean(s)); } else { extendedClientCapabilities.setSupportsReadOnlyEditors(false); } diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/config/ClientLaunchConfigHolder.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/config/ClientLaunchConfigHolder.java index 4fbcec55e063..dd389dd36049 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/config/ClientLaunchConfigHolder.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/config/ClientLaunchConfigHolder.java @@ -75,10 +75,10 @@ public Optional getBallerinaCommand() { public boolean isNoDebugMode() { if (noDebug == null) { Object noDebugObject = clientRequestArgs.get(ARG_NO_DEBUG); - if (noDebugObject instanceof Boolean) { - noDebug = (Boolean) noDebugObject; - } else if (noDebugObject instanceof String) { - noDebug = Boolean.parseBoolean((String) noDebugObject); + if (noDebugObject instanceof Boolean b) { + noDebug = b; + } else if (noDebugObject instanceof String s) { + noDebug = Boolean.parseBoolean(s); } else { noDebug = false; } @@ -89,10 +89,10 @@ public boolean isNoDebugMode() { public boolean isTestDebug() { if (testDebug == null) { Object testDebugObj = clientRequestArgs.get(ARG_TEST_DEBUG); - if (testDebugObj instanceof Boolean) { - testDebug = (Boolean) testDebugObj; - } else if (testDebugObj instanceof String) { - testDebug = Boolean.parseBoolean((String) testDebugObj); + if (testDebugObj instanceof Boolean b) { + testDebug = b; + } else if (testDebugObj instanceof String s) { + testDebug = Boolean.parseBoolean(s); } else { testDebug = false; } @@ -103,10 +103,10 @@ public boolean isTestDebug() { public boolean isNetworkLogsEnabled() { if (networkLogsEnabled == null) { Object networkLogs = clientRequestArgs.get(ARG_NETWORK_LOGS); - if (networkLogs instanceof Boolean) { - networkLogsEnabled = (Boolean) networkLogs; - } else if (networkLogs instanceof String) { - networkLogsEnabled = Boolean.parseBoolean((String) networkLogs); + if (networkLogs instanceof Boolean b) { + networkLogsEnabled = b; + } else if (networkLogs instanceof String s) { + networkLogsEnabled = Boolean.parseBoolean(s); } else { networkLogsEnabled = false; } diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/EvaluationTypeResolver.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/EvaluationTypeResolver.java index 317d9ff66a3e..bf349ae881f2 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/EvaluationTypeResolver.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/EvaluationTypeResolver.java @@ -179,8 +179,8 @@ protected Optional resolveQualifiedType(String modulePrefix, String typeN * @return true if the given semantic API symbol has 'public' qualifier */ public static boolean isPublicSymbol(Symbol symbol) { - if (symbol instanceof Qualifiable) { - return ((Qualifiable) symbol).qualifiers().stream().anyMatch(qualifier -> qualifier == Qualifier.PUBLIC); + if (symbol instanceof Qualifiable qualifiable) { + return qualifiable.qualifiers().stream().anyMatch(qualifier -> qualifier == Qualifier.PUBLIC); } return true; } diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/ModuleLevelDefinitionFinder.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/ModuleLevelDefinitionFinder.java index 4c069a47da25..76bf93a88afe 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/ModuleLevelDefinitionFinder.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/ModuleLevelDefinitionFinder.java @@ -102,20 +102,20 @@ protected void visitSyntaxNode(Node node) { } // Ignores entry points (main function definitions). - if (node instanceof FunctionDefinitionNode && ((FunctionDefinitionNode) node).functionName().toSourceCode() - .equals(MAIN_FUNCTION_NAME)) { + if (node instanceof FunctionDefinitionNode functionDefinitionNode && + functionDefinitionNode.functionName().toSourceCode().equals(MAIN_FUNCTION_NAME)) { return; } // Ignores external function definitions. - if (node instanceof FunctionDefinitionNode && ((FunctionDefinitionNode) node).functionBody().kind() == - SyntaxKind.EXTERNAL_FUNCTION_BODY) { + if (node instanceof FunctionDefinitionNode functionDefinitionNode && + functionDefinitionNode.functionBody().kind() == SyntaxKind.EXTERNAL_FUNCTION_BODY) { return; } // Ignores type definitions with @builtinSubtype annotations (specific to Ballerina library sources). - if (node instanceof TypeDefinitionNode && ((TypeDefinitionNode) node).metadata().isPresent() - && ((TypeDefinitionNode) node).metadata().get().annotations().stream().anyMatch(annotationNode -> + if (node instanceof TypeDefinitionNode typeDefinitionNode && typeDefinitionNode.metadata().isPresent() + && typeDefinitionNode.metadata().get().annotations().stream().anyMatch(annotationNode -> annotationNode.annotReference().toSourceCode().trim().equalsIgnoreCase(ANNOTATION_BUILTINSUBTYPE))) { return; } diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/NodeBasedArgProcessor.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/NodeBasedArgProcessor.java index 60211cf10f96..8731467a6341 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/NodeBasedArgProcessor.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/NodeBasedArgProcessor.java @@ -191,35 +191,22 @@ public List process(List> argEvaluators) } private static String getParameterTypeName(ParameterNode parameterNode) { - switch (parameterNode.kind()) { - case REQUIRED_PARAM: - return ((RequiredParameterNode) parameterNode).typeName().toSourceCode().trim(); - case DEFAULTABLE_PARAM: - return ((DefaultableParameterNode) parameterNode).typeName().toSourceCode().trim(); - case REST_PARAM: - return ((RestParameterNode) parameterNode).typeName().toSourceCode().trim(); - default: - return UNKNOWN_VALUE; - } + return switch (parameterNode.kind()) { + case REQUIRED_PARAM -> ((RequiredParameterNode) parameterNode).typeName().toSourceCode().trim(); + case DEFAULTABLE_PARAM -> ((DefaultableParameterNode) parameterNode).typeName().toSourceCode().trim(); + case REST_PARAM -> ((RestParameterNode) parameterNode).typeName().toSourceCode().trim(); + default -> UNKNOWN_VALUE; + }; } static String getParameterName(ParameterNode parameterNode) { - Optional paramNameToken; - switch (parameterNode.kind()) { - case REQUIRED_PARAM: - paramNameToken = ((RequiredParameterNode) parameterNode).paramName(); - break; - case DEFAULTABLE_PARAM: - paramNameToken = ((DefaultableParameterNode) parameterNode).paramName(); - break; - case REST_PARAM: - paramNameToken = ((RestParameterNode) parameterNode).paramName(); - break; - default: - paramNameToken = Optional.empty(); - break; - } - - return paramNameToken.isPresent() ? paramNameToken.get().text() : "unknown"; + Optional paramNameToken = switch (parameterNode.kind()) { + case REQUIRED_PARAM -> ((RequiredParameterNode) parameterNode).paramName(); + case DEFAULTABLE_PARAM -> ((DefaultableParameterNode) parameterNode).paramName(); + case REST_PARAM -> ((RestParameterNode) parameterNode).paramName(); + default -> Optional.empty(); + }; + + return paramNameToken.map(Token::text).orElse("unknown"); } } diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/NodeBasedTypeResolver.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/NodeBasedTypeResolver.java index eb4a3ad3f29f..587101d6555c 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/NodeBasedTypeResolver.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/NodeBasedTypeResolver.java @@ -59,13 +59,12 @@ public NodeBasedTypeResolver(EvaluationContext context) { @Override public List resolve(Node typeDescriptor) throws EvaluationException { List resolvedTypes = new ArrayList<>(); - if (typeDescriptor instanceof UnionTypeDescriptorNode) { + if (typeDescriptor instanceof UnionTypeDescriptorNode unionTypeDesc) { // If the type is a union, resolves sub types recursively. - UnionTypeDescriptorNode unionTypeDesc = (UnionTypeDescriptorNode) typeDescriptor; resolvedTypes.addAll(resolve(unionTypeDesc.leftTypeDesc())); resolvedTypes.addAll(resolve(unionTypeDesc.rightTypeDesc())); - } else if (typeDescriptor instanceof ArrayTypeDescriptorNode) { - Value elementType = resolveSingleType(((ArrayTypeDescriptorNode) typeDescriptor).memberTypeDesc()); + } else if (typeDescriptor instanceof ArrayTypeDescriptorNode arrayTypeDesc) { + Value elementType = resolveSingleType(arrayTypeDesc.memberTypeDesc()); resolvedTypes.add(createBArrayType(elementType)); } else { resolvedTypes.add(resolveSingleType(typeDescriptor)); diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/BasicLiteralEvaluator.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/BasicLiteralEvaluator.java index b4c7208a563b..e20b0cd140e5 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/BasicLiteralEvaluator.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/BasicLiteralEvaluator.java @@ -76,19 +76,14 @@ private BasicLiteralEvaluator(EvaluationContext context, Node node, String liter public BExpressionValue evaluate() throws EvaluationException { try { SyntaxKind basicLiteralKind = syntaxNode.kind(); - switch (basicLiteralKind) { - case NIL_LITERAL: - return new BExpressionValue(context, null); - case NUMERIC_LITERAL: - return parseAndGetNumericValue(literalString.trim()); - case BOOLEAN_LITERAL: - return VMUtils.make(context, Boolean.parseBoolean(literalString.trim())); - case STRING_LITERAL: - case TEMPLATE_STRING: - return VMUtils.make(context, literalString); - default: - throw createUnsupportedLiteralError(literalString); - } + return switch (basicLiteralKind) { + case NIL_LITERAL -> new BExpressionValue(context, null); + case NUMERIC_LITERAL -> parseAndGetNumericValue(literalString.trim()); + case BOOLEAN_LITERAL -> VMUtils.make(context, Boolean.parseBoolean(literalString.trim())); + case STRING_LITERAL, + TEMPLATE_STRING -> VMUtils.make(context, literalString); + default -> throw createUnsupportedLiteralError(literalString); + }; } catch (EvaluationException e) { throw e; } catch (Exception e) { diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/BinaryExpressionEvaluator.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/BinaryExpressionEvaluator.java index 5cfd19177587..a0fda0872351 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/BinaryExpressionEvaluator.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/BinaryExpressionEvaluator.java @@ -116,40 +116,31 @@ private BExpressionValue performOperation(BExpressionValue lhs, BExpressionValue BVariable rVar = VariableFactory.getVariable(context, rValue); SyntaxKind operatorType = syntaxNode.operator().kind(); - switch (operatorType) { - case PLUS_TOKEN: - case MINUS_TOKEN: - case ASTERISK_TOKEN: - case SLASH_TOKEN: - case PERCENT_TOKEN: - return performArithmeticOperation(lVar, rVar, operatorType); - case LT_TOKEN: - case GT_TOKEN: - case LT_EQUAL_TOKEN: - case GT_EQUAL_TOKEN: - return compare(lVar, rVar, operatorType); - case BITWISE_AND_TOKEN: - case PIPE_TOKEN: - case BITWISE_XOR_TOKEN: - return performBitwiseOperation(lVar, rVar, operatorType); - case DOUBLE_LT_TOKEN: - case DOUBLE_GT_TOKEN: - case TRIPPLE_GT_TOKEN: - return performShiftOperation(lVar, rVar, operatorType); - case LOGICAL_AND_TOKEN: - case LOGICAL_OR_TOKEN: - return performLogicalOperation(lVar, rVar, operatorType); - case ELVIS_TOKEN: - return conditionalReturn(lVar, rVar); - case DOUBLE_EQUAL_TOKEN: - case NOT_EQUAL_TOKEN: - return checkValueEquality(lVar, rVar, operatorType); - case TRIPPLE_EQUAL_TOKEN: - case NOT_DOUBLE_EQUAL_TOKEN: - return checkReferenceEquality(lVar, rVar, operatorType); - default: - throw createUnsupportedOperationException(lVar, rVar, operatorType); - } + return switch (operatorType) { + case PLUS_TOKEN, + MINUS_TOKEN, + ASTERISK_TOKEN, + SLASH_TOKEN, + PERCENT_TOKEN -> performArithmeticOperation(lVar, rVar, operatorType); + case LT_TOKEN, + GT_TOKEN, + LT_EQUAL_TOKEN, + GT_EQUAL_TOKEN -> compare(lVar, rVar, operatorType); + case BITWISE_AND_TOKEN, + PIPE_TOKEN, + BITWISE_XOR_TOKEN -> performBitwiseOperation(lVar, rVar, operatorType); + case DOUBLE_LT_TOKEN, + DOUBLE_GT_TOKEN, + TRIPPLE_GT_TOKEN -> performShiftOperation(lVar, rVar, operatorType); + case LOGICAL_AND_TOKEN, + LOGICAL_OR_TOKEN -> performLogicalOperation(lVar, rVar, operatorType); + case ELVIS_TOKEN -> conditionalReturn(lVar, rVar); + case DOUBLE_EQUAL_TOKEN, + NOT_EQUAL_TOKEN -> checkValueEquality(lVar, rVar, operatorType); + case TRIPPLE_EQUAL_TOKEN, + NOT_DOUBLE_EQUAL_TOKEN -> checkReferenceEquality(lVar, rVar, operatorType); + default -> throw createUnsupportedOperationException(lVar, rVar, operatorType); + }; } /** @@ -178,26 +169,14 @@ private BExpressionValue performArithmeticOperation(BVariable lVar, BVariable rV argList.add(getValueAsObject(context, lVar)); argList.add(getValueAsObject(context, rVar)); - GeneratedStaticMethod genMethod; - switch (operator) { - case PLUS_TOKEN: - genMethod = getGeneratedMethod(context, B_ARITHMETIC_EXPR_HELPER_CLASS, B_ADD_METHOD); - break; - case MINUS_TOKEN: - genMethod = getGeneratedMethod(context, B_ARITHMETIC_EXPR_HELPER_CLASS, B_SUB_METHOD); - break; - case ASTERISK_TOKEN: - genMethod = getGeneratedMethod(context, B_ARITHMETIC_EXPR_HELPER_CLASS, B_MUL_METHOD); - break; - case SLASH_TOKEN: - genMethod = getGeneratedMethod(context, B_ARITHMETIC_EXPR_HELPER_CLASS, B_DIV_METHOD); - break; - case PERCENT_TOKEN: - genMethod = getGeneratedMethod(context, B_ARITHMETIC_EXPR_HELPER_CLASS, B_MOD_METHOD); - break; - default: - throw createUnsupportedOperationException(lVar, rVar, operator); - } + GeneratedStaticMethod genMethod = switch (operator) { + case PLUS_TOKEN -> getGeneratedMethod(context, B_ARITHMETIC_EXPR_HELPER_CLASS, B_ADD_METHOD); + case MINUS_TOKEN -> getGeneratedMethod(context, B_ARITHMETIC_EXPR_HELPER_CLASS, B_SUB_METHOD); + case ASTERISK_TOKEN -> getGeneratedMethod(context, B_ARITHMETIC_EXPR_HELPER_CLASS, B_MUL_METHOD); + case SLASH_TOKEN -> getGeneratedMethod(context, B_ARITHMETIC_EXPR_HELPER_CLASS, B_DIV_METHOD); + case PERCENT_TOKEN -> getGeneratedMethod(context, B_ARITHMETIC_EXPR_HELPER_CLASS, B_MOD_METHOD); + default -> throw createUnsupportedOperationException(lVar, rVar, operator); + }; genMethod.setArgValues(argList); Value result = genMethod.invokeSafely(); return new BExpressionValue(context, result); @@ -214,23 +193,13 @@ private BExpressionValue compare(BVariable lVar, BVariable rVar, SyntaxKind oper argList.add(getValueAsObject(context, lVar)); argList.add(getValueAsObject(context, rVar)); - GeneratedStaticMethod genMethod; - switch (operator) { - case LT_TOKEN: - genMethod = getGeneratedMethod(context, B_RELATIONAL_EXPR_HELPER_CLASS, B_LT_METHOD); - break; - case LT_EQUAL_TOKEN: - genMethod = getGeneratedMethod(context, B_RELATIONAL_EXPR_HELPER_CLASS, B_LT_EQUALS_METHOD); - break; - case GT_TOKEN: - genMethod = getGeneratedMethod(context, B_RELATIONAL_EXPR_HELPER_CLASS, B_GT_METHOD); - break; - case GT_EQUAL_TOKEN: - genMethod = getGeneratedMethod(context, B_RELATIONAL_EXPR_HELPER_CLASS, B_GT_EQUALS_METHOD); - break; - default: - throw createUnsupportedOperationException(lVar, rVar, operator); - } + GeneratedStaticMethod genMethod = switch (operator) { + case LT_TOKEN -> getGeneratedMethod(context, B_RELATIONAL_EXPR_HELPER_CLASS, B_LT_METHOD); + case LT_EQUAL_TOKEN -> getGeneratedMethod(context, B_RELATIONAL_EXPR_HELPER_CLASS, B_LT_EQUALS_METHOD); + case GT_TOKEN -> getGeneratedMethod(context, B_RELATIONAL_EXPR_HELPER_CLASS, B_GT_METHOD); + case GT_EQUAL_TOKEN -> getGeneratedMethod(context, B_RELATIONAL_EXPR_HELPER_CLASS, B_GT_EQUALS_METHOD); + default -> throw createUnsupportedOperationException(lVar, rVar, operator); + }; genMethod.setArgValues(argList); Value result = genMethod.invokeSafely(); return new BExpressionValue(context, result); @@ -242,20 +211,12 @@ private BExpressionValue performBitwiseOperation(BVariable lVar, BVariable rVar, argList.add(getValueAsObject(context, lVar)); argList.add(getValueAsObject(context, rVar)); - GeneratedStaticMethod genMethod; - switch (operator) { - case BITWISE_AND_TOKEN: - genMethod = getGeneratedMethod(context, B_BITWISE_EXPR_HELPER_CLASS, B_BITWISE_AND_METHOD); - break; - case PIPE_TOKEN: - genMethod = getGeneratedMethod(context, B_BITWISE_EXPR_HELPER_CLASS, B_BITWISE_OR_METHOD); - break; - case BITWISE_XOR_TOKEN: - genMethod = getGeneratedMethod(context, B_BITWISE_EXPR_HELPER_CLASS, B_BITWISE_XOR_METHOD); - break; - default: - throw createUnsupportedOperationException(lVar, rVar, operator); - } + GeneratedStaticMethod genMethod = switch (operator) { + case BITWISE_AND_TOKEN -> getGeneratedMethod(context, B_BITWISE_EXPR_HELPER_CLASS, B_BITWISE_AND_METHOD); + case PIPE_TOKEN -> getGeneratedMethod(context, B_BITWISE_EXPR_HELPER_CLASS, B_BITWISE_OR_METHOD); + case BITWISE_XOR_TOKEN -> getGeneratedMethod(context, B_BITWISE_EXPR_HELPER_CLASS, B_BITWISE_XOR_METHOD); + default -> throw createUnsupportedOperationException(lVar, rVar, operator); + }; genMethod.setArgValues(argList); Value result = genMethod.invokeSafely(); return new BExpressionValue(context, result); @@ -267,20 +228,13 @@ private BExpressionValue performShiftOperation(BVariable lVar, BVariable rVar, S argList.add(getValueAsObject(context, lVar)); argList.add(getValueAsObject(context, rVar)); - GeneratedStaticMethod genMethod; - switch (operator) { - case DOUBLE_LT_TOKEN: - genMethod = getGeneratedMethod(context, B_SHIFT_EXPR_HELPER_CLASS, B_LEFT_SHIFT_METHOD); - break; - case DOUBLE_GT_TOKEN: - genMethod = getGeneratedMethod(context, B_SHIFT_EXPR_HELPER_CLASS, B_SIGNED_RIGHT_SHIFT_METHOD); - break; - case TRIPPLE_GT_TOKEN: - genMethod = getGeneratedMethod(context, B_SHIFT_EXPR_HELPER_CLASS, B_UNSIGNED_RIGHT_SHIFT_METHOD); - break; - default: - throw createUnsupportedOperationException(lVar, rVar, operator); - } + GeneratedStaticMethod genMethod = switch (operator) { + case DOUBLE_LT_TOKEN -> getGeneratedMethod(context, B_SHIFT_EXPR_HELPER_CLASS, B_LEFT_SHIFT_METHOD); + case DOUBLE_GT_TOKEN -> getGeneratedMethod(context, B_SHIFT_EXPR_HELPER_CLASS, B_SIGNED_RIGHT_SHIFT_METHOD); + case TRIPPLE_GT_TOKEN -> + getGeneratedMethod(context, B_SHIFT_EXPR_HELPER_CLASS, B_UNSIGNED_RIGHT_SHIFT_METHOD); + default -> throw createUnsupportedOperationException(lVar, rVar, operator); + }; genMethod.setArgValues(argList); Value result = genMethod.invokeSafely(); return new BExpressionValue(context, result); @@ -292,17 +246,11 @@ private BExpressionValue performLogicalOperation(BVariable lVar, BVariable rVar, argList.add(getValueAsObject(context, lVar)); argList.add(getValueAsObject(context, rVar)); - GeneratedStaticMethod genMethod; - switch (operator) { - case LOGICAL_AND_TOKEN: - genMethod = getGeneratedMethod(context, B_LOGICAL_EXPR_HELPER_CLASS, B_LOGICAL_AND_METHOD); - break; - case LOGICAL_OR_TOKEN: - genMethod = getGeneratedMethod(context, B_LOGICAL_EXPR_HELPER_CLASS, B_LOGICAL_OR_METHOD); - break; - default: - throw createUnsupportedOperationException(lVar, rVar, operator); - } + GeneratedStaticMethod genMethod = switch (operator) { + case LOGICAL_AND_TOKEN -> getGeneratedMethod(context, B_LOGICAL_EXPR_HELPER_CLASS, B_LOGICAL_AND_METHOD); + case LOGICAL_OR_TOKEN -> getGeneratedMethod(context, B_LOGICAL_EXPR_HELPER_CLASS, B_LOGICAL_OR_METHOD); + default -> throw createUnsupportedOperationException(lVar, rVar, operator); + }; genMethod.setArgValues(argList); Value result = genMethod.invokeSafely(); return new BExpressionValue(context, result); diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/ExpressionAsProgramEvaluator.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/ExpressionAsProgramEvaluator.java index 1e6141018069..aa1f0b67ea45 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/ExpressionAsProgramEvaluator.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/ExpressionAsProgramEvaluator.java @@ -510,7 +510,7 @@ private List convertImports(List declarationLi modifier = modifier.withModuleName(newModuleName); return modifier.apply(); - }).collect(Collectors.toList()); + }).toList(); } private void processSnippetFunctionParameters() throws EvaluationException { @@ -555,43 +555,35 @@ private void validateForCompilationErrors(PackageCompilation packageCompilation) * @return type name */ private String getTypeNameString(BVariable bVar) { - switch (bVar.getBType()) { - case BOOLEAN: - case INT: - case FLOAT: - case DECIMAL: - case STRING: - case XML: - case TABLE: - case ERROR: - case FUNCTION: - case FUTURE: - case TYPE_DESC: - case HANDLE: - case STREAM: - case SINGLETON: - case ANY: - case ANYDATA: - case NEVER: - case BYTE: - case SERVICE: - return bVar.getBType().getString(); - case JSON: - return "map"; - case MAP: - return VariableUtils.getMapType(context, bVar.getJvmValue()); - case NIL: - return "()"; - case ARRAY: - return bVar.computeValue().substring(0, bVar.computeValue().indexOf("[")) + "[]"; - case TUPLE: - return bVar.computeValue(); - case RECORD: - case OBJECT: - return resolveObjectType(bVar); - default: - return UNKNOWN_VALUE; - } + return switch (bVar.getBType()) { + case BOOLEAN, + INT, + FLOAT, + DECIMAL, + STRING, + XML, + TABLE, + ERROR, + FUNCTION, + FUTURE, + TYPE_DESC, + HANDLE, + STREAM, + SINGLETON, + ANY, + ANYDATA, + NEVER, + BYTE, + SERVICE -> bVar.getBType().getString(); + case JSON -> "map"; + case MAP -> VariableUtils.getMapType(context, bVar.getJvmValue()); + case NIL -> "()"; + case ARRAY -> bVar.computeValue().substring(0, bVar.computeValue().indexOf("[")) + "[]"; + case TUPLE -> bVar.computeValue(); + case RECORD, + OBJECT -> resolveObjectType(bVar); + default -> UNKNOWN_VALUE; + }; } private String resolveObjectType(BVariable bVar) { diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/FunctionInvocationExpressionEvaluator.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/FunctionInvocationExpressionEvaluator.java index b2f1eff20ac8..041bdb289aae 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/FunctionInvocationExpressionEvaluator.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/FunctionInvocationExpressionEvaluator.java @@ -35,7 +35,6 @@ import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.stream.Collectors; import static io.ballerina.compiler.api.symbols.SymbolKind.FUNCTION; import static org.ballerinalang.debugadapter.evaluation.EvaluationException.createEvaluationException; @@ -102,7 +101,7 @@ private FunctionSymbol resolveFunctionDefinitionSymbol() throws EvaluationExcept functionMatches = resolvedImports.get(modulePrefix.get()).getResolvedSymbol().functions().stream() .filter(symbol -> symbol.getName().isPresent() && modifyName(symbol.getName().get()).equals(functionName)) - .collect(Collectors.toList()); + .toList(); if (functionMatches.size() == 1 && !isPublicSymbol(functionMatches.get(0))) { throw createEvaluationException(NON_PUBLIC_OR_UNDEFINED_ACCESS, functionName); @@ -115,7 +114,7 @@ private FunctionSymbol resolveFunctionDefinitionSymbol() throws EvaluationExcept .filter(symbol -> symbol.kind() == FUNCTION && symbol.getName().isPresent() && modifyName(symbol.getName().get()).equals(functionName)) .map(symbol -> (FunctionSymbol) symbol) - .collect(Collectors.toList()); + .toList(); } if (functionMatches.isEmpty()) { diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/MemberAccessExpressionEvaluator.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/MemberAccessExpressionEvaluator.java index fcd8a9ef9e87..b57bfe7f2d21 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/MemberAccessExpressionEvaluator.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/MemberAccessExpressionEvaluator.java @@ -184,20 +184,20 @@ public BExpressionValue evaluate() throws EvaluationException { try { Value child; - if (containerVar instanceof BXmlItem) { - Value childrenValue = ((BXmlItem) containerVar).getChildByName(FIELD_CHILDREN); + if (containerVar instanceof BXmlItem xmlItem) { + Value childrenValue = xmlItem.getChildByName(FIELD_CHILDREN); BVariable childrenVar = VariableFactory.getVariable(context, childrenValue); - if (childrenVar instanceof IndexedCompoundVariable) { - child = ((IndexedCompoundVariable) childrenVar).getChildByIndex(index); - } else if (childrenVar instanceof NamedCompoundVariable) { - child = ((NamedCompoundVariable) childrenVar).getChildByName(String.valueOf(index)); + if (childrenVar instanceof IndexedCompoundVariable indexedCompoundVariable) { + child = indexedCompoundVariable.getChildByIndex(index); + } else if (childrenVar instanceof NamedCompoundVariable namedCompoundVariable) { + child = namedCompoundVariable.getChildByName(String.valueOf(index)); } else { child = containerVar.getJvmValue(); } - } else if (containerVar instanceof IndexedCompoundVariable) { - child = ((IndexedCompoundVariable) containerVar).getChildByIndex(index); - } else if (containerVar instanceof NamedCompoundVariable) { - child = ((NamedCompoundVariable) containerVar).getChildByName(String.valueOf(index)); + } else if (containerVar instanceof IndexedCompoundVariable indexedCompoundVariable) { + child = indexedCompoundVariable.getChildByIndex(index); + } else if (containerVar instanceof NamedCompoundVariable namedCompoundVariable) { + child = namedCompoundVariable.getChildByName(String.valueOf(index)); } else { child = containerVar.getJvmValue(); } @@ -225,14 +225,14 @@ public BExpressionValue evaluate() throws EvaluationException { */ private int getXmlChildVarCount(BVariable containerVar) { try { - if (containerVar instanceof BXmlItem) { - Value childrenValue = ((BXmlItem) containerVar).getChildByName(FIELD_CHILDREN); + if (containerVar instanceof BXmlItem xmlItem) { + Value childrenValue = xmlItem.getChildByName(FIELD_CHILDREN); BVariable childrenVar = VariableFactory.getVariable(context, childrenValue); - return childrenVar instanceof BCompoundVariable ? - ((BCompoundVariable) childrenVar).getChildrenCount() : 1; + return childrenVar instanceof BCompoundVariable bCompoundVariable ? + bCompoundVariable.getChildrenCount() : 1; } else { - return containerVar instanceof BCompoundVariable ? - ((BCompoundVariable) containerVar).getChildrenCount() : 1; + return containerVar instanceof BCompoundVariable bCompoundVariable ? + bCompoundVariable.getChildrenCount() : 1; } } catch (DebugVariableException e) { return 1; diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/MethodCallExpressionEvaluator.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/MethodCallExpressionEvaluator.java index 49b7ed58d23e..b7a7c4768527 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/MethodCallExpressionEvaluator.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/MethodCallExpressionEvaluator.java @@ -84,10 +84,10 @@ public MethodCallExpressionEvaluator(EvaluationContext context, ExpressionNode m this.syntaxNode = methodCallExpressionNode; this.objectExpressionEvaluator = expression; this.argEvaluators = argEvaluators; - if (syntaxNode instanceof MethodCallExpressionNode) { - this.methodName = ((MethodCallExpressionNode) syntaxNode).methodName().toSourceCode().trim(); - } else if (syntaxNode instanceof RemoteMethodCallActionNode) { - this.methodName = ((RemoteMethodCallActionNode) syntaxNode).methodName().toSourceCode().trim(); + if (syntaxNode instanceof MethodCallExpressionNode methodCallExpr) { + this.methodName = methodCallExpr.methodName().toSourceCode().trim(); + } else if (syntaxNode instanceof RemoteMethodCallActionNode remoteMethodCallActionNode) { + this.methodName = remoteMethodCallActionNode.methodName().toSourceCode().trim(); } else { methodName = UNKNOWN_VALUE; } diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/StringTemplateEvaluator.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/StringTemplateEvaluator.java index 6d26567891b0..a935e80c95b3 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/StringTemplateEvaluator.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/StringTemplateEvaluator.java @@ -77,8 +77,8 @@ public BExpressionValue evaluate() throws EvaluationException { } Value result = EvaluationUtils.concatBStrings(context, templateMemberValues.toArray(new Value[0])); // Converts the result into a BString, if the result is a java string reference. - if (result instanceof StringReference) { - result = EvaluationUtils.getAsBString(context, (StringReference) result); + if (result instanceof StringReference stringReference) { + result = EvaluationUtils.getAsBString(context, stringReference); } return new BExpressionValue(context, result); } catch (EvaluationException e) { diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/UnaryExpressionEvaluator.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/UnaryExpressionEvaluator.java index 550c6a45890a..bee0ee6e1223 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/UnaryExpressionEvaluator.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/UnaryExpressionEvaluator.java @@ -59,23 +59,14 @@ public BExpressionValue evaluate() throws EvaluationException { BExpressionValue result = exprEvaluator.evaluate(); Value valueAsObject = getValueAsObject(context, result.getJdiValue()); - GeneratedStaticMethod genMethod; - switch (syntaxNode.unaryOperator().kind()) { - case PLUS_TOKEN: - genMethod = getGeneratedMethod(context, B_UNARY_EXPR_HELPER_CLASS, B_UNARY_PLUS_METHOD); - break; - case MINUS_TOKEN: - genMethod = getGeneratedMethod(context, B_UNARY_EXPR_HELPER_CLASS, B_UNARY_MINUS_METHOD); - break; - case NEGATION_TOKEN: - genMethod = getGeneratedMethod(context, B_UNARY_EXPR_HELPER_CLASS, B_UNARY_INVERT_METHOD); - break; - case EXCLAMATION_MARK_TOKEN: - genMethod = getGeneratedMethod(context, B_UNARY_EXPR_HELPER_CLASS, B_UNARY_NOT_METHOD); - break; - default: - throw createEvaluationException(INTERNAL_ERROR, syntaxNode.toSourceCode().trim()); - } + GeneratedStaticMethod genMethod = switch (syntaxNode.unaryOperator().kind()) { + case PLUS_TOKEN -> getGeneratedMethod(context, B_UNARY_EXPR_HELPER_CLASS, B_UNARY_PLUS_METHOD); + case MINUS_TOKEN -> getGeneratedMethod(context, B_UNARY_EXPR_HELPER_CLASS, B_UNARY_MINUS_METHOD); + case NEGATION_TOKEN -> getGeneratedMethod(context, B_UNARY_EXPR_HELPER_CLASS, B_UNARY_INVERT_METHOD); + case EXCLAMATION_MARK_TOKEN -> + getGeneratedMethod(context, B_UNARY_EXPR_HELPER_CLASS, B_UNARY_NOT_METHOD); + default -> throw createEvaluationException(INTERNAL_ERROR, syntaxNode.toSourceCode().trim()); + }; genMethod.setArgValues(Collections.singletonList(valueAsObject)); return new BExpressionValue(context, genMethod.invokeSafely()); } catch (EvaluationException e) { diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/XMLTemplateExpressionEvaluator.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/XMLTemplateExpressionEvaluator.java index 925e53f2143a..0c85a45728f4 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/XMLTemplateExpressionEvaluator.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/expression/XMLTemplateExpressionEvaluator.java @@ -68,8 +68,7 @@ public BExpressionValue evaluate() throws EvaluationException { Value result = strToXmlMethod.invokeSafely(); BVariable xmlVar = VariableFactory.getVariable(context, result); - if (xmlVar instanceof BXmlSequence) { - BXmlSequence xmlSequence = (BXmlSequence) xmlVar; + if (xmlVar instanceof BXmlSequence xmlSequence) { if (xmlSequence.getChildrenCount() == 0) { // If the element count is 0, returns an empty XML item. RuntimeStaticMethod createXmlMethod = getRuntimeMethod(context, B_TYPE_CREATOR_CLASS, diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/invokable/RuntimeInstanceMethod.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/invokable/RuntimeInstanceMethod.java index da297339db81..c1ee806346ab 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/invokable/RuntimeInstanceMethod.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/invokable/RuntimeInstanceMethod.java @@ -46,11 +46,11 @@ public RuntimeInstanceMethod(SuspendedContext context, Value objectRef, Method m @Override protected Value invoke() throws EvaluationException { try { - if (!(objectValueRef instanceof ObjectReference)) { + if (!(objectValueRef instanceof ObjectReference objectReference)) { throw createEvaluationException(FUNCTION_EXECUTION_ERROR, methodRef.name()); } List argValueList = getMethodArgs(this); - return ((ObjectReference) objectValueRef).invokeMethod(context.getOwningThread().getThreadReference(), + return objectReference.invokeMethod(context.getOwningThread().getThreadReference(), methodRef, argValueList, 0); } catch (ClassNotLoadedException e) { throw createEvaluationException(FUNCTION_NOT_FOUND, methodRef.name()); diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/invokable/RuntimeStaticMethod.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/invokable/RuntimeStaticMethod.java index f4696e8be06d..54fe5f10f6b5 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/invokable/RuntimeStaticMethod.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/engine/invokable/RuntimeStaticMethod.java @@ -47,11 +47,11 @@ public RuntimeStaticMethod(SuspendedContext context, ReferenceType classRef, Met @Override protected Value invoke() throws EvaluationException { try { - if (!(classRef instanceof ClassType)) { + if (!(classRef instanceof ClassType classType)) { throw createEvaluationException(FUNCTION_EXECUTION_ERROR, methodRef.name()); } List argValueList = getMethodArgs(this); - return ((ClassType) classRef).invokeMethod(context.getFrame().threadProxy().getThreadReference(), + return classType.invokeMethod(context.getFrame().threadProxy().getThreadReference(), methodRef, argValueList, 0); } catch (ClassNotLoadedException e) { throw createEvaluationException(FUNCTION_NOT_FOUND, methodRef.name()); diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/utils/EvaluationUtils.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/utils/EvaluationUtils.java index 61fca330ae5e..a68a704bb478 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/utils/EvaluationUtils.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/utils/EvaluationUtils.java @@ -74,7 +74,7 @@ * * @since 2.0.0 */ -public class EvaluationUtils { +public final class EvaluationUtils { // Debugger runtime helper classes private static final String DEBUGGER_HELPER_PREFIX = "ballerina.debugger_helpers.1."; @@ -279,7 +279,7 @@ public static ReferenceType loadClass(SuspendedContext evaluationContext, String /** * Converts java primitive types into their wrapper implementations, as some of the the JVM runtime util methods - * accepts only the sub classes of @{@link java.lang.Object}. + * accepts only the sub classes of @{@link Object}. */ public static List getAsObjects(SuspendedContext context, List argValueList) throws EvaluationException { @@ -291,7 +291,7 @@ public static List getAsObjects(SuspendedContext context, List arg } /** - * As some of the JVM runtime util method accepts only the sub classes of @{@link java.lang.Object}, + * As some of the JVM runtime util method accepts only the sub classes of @{@link Object}, * java primitive types need to be converted into their wrapper implementations. * * @param value JDI value instance. @@ -310,7 +310,7 @@ public static Value getValueAsObject(SuspendedContext context, Value value) thro */ public static Value unboxValue(SuspendedContext context, Value value) { try { - if (!(value instanceof ObjectReference)) { + if (!(value instanceof ObjectReference objRef)) { return value; } @@ -318,16 +318,16 @@ public static Value unboxValue(SuspendedContext context, Value value) { List method; switch (typeName) { case JAVA_INT_CLASS: - method = ((ObjectReference) value).referenceType().methodsByName(INT_VALUE_METHOD); + method = objRef.referenceType().methodsByName(INT_VALUE_METHOD); break; case JAVA_LONG_CLASS: - method = ((ObjectReference) value).referenceType().methodsByName(LONG_VALUE_METHOD); + method = objRef.referenceType().methodsByName(LONG_VALUE_METHOD); break; case JAVA_FLOAT_CLASS: - method = ((ObjectReference) value).referenceType().methodsByName(FLOAT_VALUE_METHOD); + method = objRef.referenceType().methodsByName(FLOAT_VALUE_METHOD); break; case JAVA_DOUBLE_CLASS: - method = ((ObjectReference) value).referenceType().methodsByName(DOUBLE_VALUE_METHOD); + method = objRef.referenceType().methodsByName(DOUBLE_VALUE_METHOD); break; default: return value; @@ -345,7 +345,7 @@ public static Value unboxValue(SuspendedContext context, Value value) { } /** - * As some of the JVM runtime util method accepts only the sub classes of @{@link java.lang.Object}, + * As some of the JVM runtime util method accepts only the sub classes of @{@link Object}, * java primitive types need to be converted into their wrapper implementations. * * @param variable ballerina variable instance. @@ -518,11 +518,11 @@ public static String constructQualifiedClassName(Symbol symbol) { } /** - * Converts the user given string literal into a {@link com.sun.jdi.StringReference} instance. + * Converts the user given string literal into a {@link StringReference} instance. * * @param context suspended debug context * @param val string value - * @return {@link com.sun.jdi.StringReference} instance + * @return {@link StringReference} instance */ public static Value getAsJString(SuspendedContext context, String val) throws EvaluationException { return context.getAttachedVm().mirrorOf(val); @@ -533,12 +533,12 @@ public static Value getAsJString(SuspendedContext context, String val) throws Ev * so, returns it as a JDI value instance. */ public static Optional getBError(Exception e) { - if (!(e instanceof InvocationException)) { + if (!(e instanceof InvocationException e1)) { return Optional.empty(); } - String typeName = ((InvocationException) e).exception().referenceType().name(); + String typeName = e1.exception().referenceType().name(); if (typeName.equals(B_ERROR_VALUE_CLASS)) { - return Optional.ofNullable(((InvocationException) e).exception()); + return Optional.ofNullable(e1.exception()); } return Optional.empty(); } @@ -640,10 +640,10 @@ private static Optional searchLocalVariables(SuspendedContext Value varValue = context.getFrame().getValue(localVariableProxy); BVariable mapVar = VariableFactory.getVariable(context, varValue); if (mapVar == null || mapVar.getBType() != BVariableType.MAP - || !(mapVar instanceof IndexedCompoundVariable)) { + || !(mapVar instanceof IndexedCompoundVariable indexedCompoundVariable)) { return null; } - return ((IndexedCompoundVariable) mapVar).getChildByName(nameReference); + return indexedCompoundVariable.getChildByName(nameReference); } catch (JdiProxyException | DebugVariableException e) { return null; } diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/utils/FileUtils.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/utils/FileUtils.java index ee8a2eca1ea7..115f63b8c48f 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/utils/FileUtils.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/utils/FileUtils.java @@ -30,7 +30,10 @@ * * @since 2.0.0 */ -public class FileUtils { +public final class FileUtils { + + private FileUtils() { + } /** * Helper method to write a string source to a file. diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/utils/LangLibUtils.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/utils/LangLibUtils.java index 997b4b231a00..0b15c42c1f88 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/utils/LangLibUtils.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/utils/LangLibUtils.java @@ -52,7 +52,7 @@ * * @since 2.0.0 */ -public class LangLibUtils { +public final class LangLibUtils { public static final String LANG_LIB_ORG = "ballerina"; public static final String LANG_LIB_PACKAGE_PREFIX = "lang."; @@ -122,30 +122,22 @@ public static Optional getLangLibFunctionDefinition(Pack } public static String getAssociatedLangLibName(BVariableType bVarType) { - switch (bVarType) { - case INT: - case BYTE: - return INT.getString(); - case ARRAY: - case TUPLE: - return ARRAY.getString(); - case RECORD: - case MAP: - return MAP.getString(); - case FLOAT: - case DECIMAL: - case STRING: - case BOOLEAN: - case STREAM: - case OBJECT: - case ERROR: - case FUTURE: - case TYPE_DESC: - case XML: - case TABLE: - return bVarType.getString(); - default: - return LANG_LIB_VALUE; - } + return switch (bVarType) { + case INT, BYTE -> INT.getString(); + case ARRAY, TUPLE -> ARRAY.getString(); + case RECORD, MAP -> MAP.getString(); + case FLOAT, + DECIMAL, + STRING, + BOOLEAN, + STREAM, + OBJECT, + ERROR, + FUTURE, + TYPE_DESC, + XML, + TABLE -> bVarType.getString(); + default -> LANG_LIB_VALUE; + }; } } diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/utils/VMUtils.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/utils/VMUtils.java index 3625b8822071..cbca39419d2c 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/utils/VMUtils.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/utils/VMUtils.java @@ -29,7 +29,7 @@ * * @since 2.0.0 */ -public class VMUtils { +public final class VMUtils { private VMUtils() { } diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/utils/VariableUtils.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/utils/VariableUtils.java index d55a8ec2cd86..394eb3a5aba9 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/utils/VariableUtils.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/evaluation/utils/VariableUtils.java @@ -43,7 +43,7 @@ * * @since 2.0.0 */ -public class VariableUtils { +public final class VariableUtils { /** * Returns runtime value of the matching constant variable, for the given name. diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/jdi/JvmtiError.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/jdi/JvmtiError.java index b68d0a634e15..fb7ad86c56e0 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/jdi/JvmtiError.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/jdi/JvmtiError.java @@ -19,7 +19,8 @@ /** * (Copied from jvmti.h). */ -public class JvmtiError { +public final class JvmtiError { + private JvmtiError() { } diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/jdi/LocalVariableProxyImpl.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/jdi/LocalVariableProxyImpl.java index 30b39fbd032a..fe954afe54e2 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/jdi/LocalVariableProxyImpl.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/jdi/LocalVariableProxyImpl.java @@ -76,8 +76,7 @@ public int hashCode() { } public boolean equals(Object o) { - if (o instanceof LocalVariableProxyImpl) { - LocalVariableProxyImpl proxy = (LocalVariableProxyImpl) o; + if (o instanceof LocalVariableProxyImpl proxy) { return proxy.myFrame.equals(myFrame) && myVariableName.equals(proxy.myVariableName); } return false; diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/jdi/ObjectReferenceProxyImpl.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/jdi/ObjectReferenceProxyImpl.java index a27b36d7cf81..7e5d3393ea1d 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/jdi/ObjectReferenceProxyImpl.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/jdi/ObjectReferenceProxyImpl.java @@ -28,7 +28,6 @@ import java.util.List; import java.util.Map; -import java.util.stream.Collectors; /** * Proxy implementation for JDI object reference. @@ -109,7 +108,7 @@ public long uniqueID() { */ public List waitingThreads() throws IncompatibleThreadStateException { return getObjectReference().waitingThreads().stream().map(getVirtualMachineProxy()::getThreadReferenceProxy) - .collect(Collectors.toList()); + .toList(); } public ThreadReferenceProxyImpl owningThread() throws IncompatibleThreadStateException { @@ -122,13 +121,13 @@ public int entryCount() throws IncompatibleThreadStateException { @Override public boolean equals(Object o) { - if (!(o instanceof ObjectReferenceProxyImpl)) { + if (!(o instanceof ObjectReferenceProxyImpl proxy)) { return false; } if (this == o) { return true; } - return myObjectReference.equals(((ObjectReferenceProxyImpl) o).myObjectReference); + return myObjectReference.equals(proxy.myObjectReference); } public int hashCode() { diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/jdi/StackFrameProxyImpl.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/jdi/StackFrameProxyImpl.java index 6f3772622039..ca0a141091d0 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/jdi/StackFrameProxyImpl.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/jdi/StackFrameProxyImpl.java @@ -357,10 +357,9 @@ public int hashCode() { } public boolean equals(final Object obj) { - if (!(obj instanceof StackFrameProxyImpl)) { + if (!(obj instanceof StackFrameProxyImpl frameProxy)) { return false; } - StackFrameProxyImpl frameProxy = (StackFrameProxyImpl) obj; if (frameProxy == this) { return true; } diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/jdi/ThreadGroupReferenceProxyImpl.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/jdi/ThreadGroupReferenceProxyImpl.java index 3f502929ab31..90a461ecf136 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/jdi/ThreadGroupReferenceProxyImpl.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/jdi/ThreadGroupReferenceProxyImpl.java @@ -21,7 +21,6 @@ import org.slf4j.LoggerFactory; import java.util.List; -import java.util.stream.Collectors; /** * Proxy implementation for JDI thread group. @@ -77,12 +76,12 @@ public void resume() { public List threads() { return getThreadGroupReference().threads().stream().map(getVirtualMachineProxy()::getThreadReferenceProxy) - .collect(Collectors.toList()); + .toList(); } public List threadGroups() { return getThreadGroupReference().threadGroups().stream().map(getVirtualMachineProxy() - ::getThreadGroupReferenceProxy).collect(Collectors.toList()); + ::getThreadGroupReferenceProxy).toList(); } @Override diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/jdi/VirtualMachineProxyImpl.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/jdi/VirtualMachineProxyImpl.java index f5f3de33cfbe..69c671e01802 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/jdi/VirtualMachineProxyImpl.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/jdi/VirtualMachineProxyImpl.java @@ -592,15 +592,15 @@ public ThreadGroupReferenceProxyImpl getThreadGroupReferenceProxy(ThreadGroupRef public ObjectReferenceProxyImpl getObjectReferenceProxy(ObjectReference objectReference) { if (objectReference != null) { - if (objectReference instanceof ThreadReference) { - return getThreadReferenceProxy((ThreadReference) objectReference); - } else if (objectReference instanceof ThreadGroupReference) { - return getThreadGroupReferenceProxy((ThreadGroupReference) objectReference); + if (objectReference instanceof ThreadReference threadReference) { + return getThreadReferenceProxy(threadReference); + } else if (objectReference instanceof ThreadGroupReference threadGroupReference) { + return getThreadGroupReferenceProxy(threadGroupReference); } else { ObjectReferenceProxyImpl proxy = myObjectReferenceProxies.get(objectReference); if (proxy == null) { - if (objectReference instanceof StringReference) { - proxy = new StringReferenceProxyImpl(this, (StringReference) objectReference); + if (objectReference instanceof StringReference stringReference) { + proxy = new StringReferenceProxyImpl(this, stringReference); } else { proxy = new ObjectReferenceProxyImpl(this, objectReference); } @@ -701,6 +701,9 @@ static final class JNITypeParserReflect { } } + private JNITypeParserReflect() { + } + static String typeNameToSignature(String name) { if (typeNameToSignatureMethod != null) { try { @@ -711,7 +714,7 @@ static String typeNameToSignature(String name) { return null; } - private static Method getDeclaredMethod(Class aClass, String name, Class... parameters) { + private static Method getDeclaredMethod(Class aClass, String name, Class... parameters) { try { Method declaredMethod = aClass.getDeclaredMethod(name, parameters); declaredMethod.setAccessible(true); diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/launcher/DebugAdapterLauncher.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/launcher/DebugAdapterLauncher.java index ad681b65d7d6..fb81d16de558 100755 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/launcher/DebugAdapterLauncher.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/launcher/DebugAdapterLauncher.java @@ -33,16 +33,18 @@ /** * Launch debugger adapter protocol server instance. */ -public class DebugAdapterLauncher { +public final class DebugAdapterLauncher { private static final int DEFAULT_PORT = 4711; private static final Logger LOGGER = LoggerFactory.getLogger(DebugAdapterLauncher.class); + private DebugAdapterLauncher() { + } + public static void main(String[] args) { // Configures debug server port. int debugServerPort = args.length != 0 ? Integer.parseInt(args[0]) : DEFAULT_PORT; - try { - ServerSocket serverSocket = new ServerSocket(debugServerPort); + try (ServerSocket serverSocket = new ServerSocket(debugServerPort)) { PrintStream out = System.out; out.println("Debug server started on " + debugServerPort); diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/utils/OSUtils.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/utils/OSUtils.java index 1fabd1d7d302..bff002548da3 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/utils/OSUtils.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/utils/OSUtils.java @@ -21,7 +21,7 @@ /** * Operating system utils. */ -public class OSUtils { +public final class OSUtils { public static final String WINDOWS = "windows"; public static final String UNIX = "unix"; @@ -29,6 +29,9 @@ public class OSUtils { private static final String OS = System.getProperty("os.name").toLowerCase(Locale.getDefault()); + private OSUtils() { + } + /** * Returns name of the operating system running. null if not a unsupported operating system. * diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/utils/PackageUtils.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/utils/PackageUtils.java index 45244fec0e01..1da8dbe1defc 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/utils/PackageUtils.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/utils/PackageUtils.java @@ -52,7 +52,7 @@ /** * Package Utils. */ -public class PackageUtils { +public final class PackageUtils { public static final String BAL_FILE_EXT = ".bal"; public static final String BAL_TOML_FILE_NAME = "Ballerina.toml"; @@ -67,6 +67,9 @@ public class PackageUtils { private static final String FILE_SEPARATOR_REGEX = File.separatorChar == '\\' ? "\\\\" : File.separator; + private PackageUtils() { + } + /** * Returns the corresponding debug source path based on the given stack frame location. * diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/variable/VariableFactory.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/variable/VariableFactory.java index 7c983744b698..52af26f71dc5 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/variable/VariableFactory.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/variable/VariableFactory.java @@ -103,10 +103,13 @@ *
  • never - no value * */ -public class VariableFactory { +public final class VariableFactory { private static final String TYPEDESC_IDENTIFIER = "$typedesc$"; + private VariableFactory() { + } + public static BVariable getVariable(SuspendedContext context, Value value) { return getVariable(context, "unknown", value); } diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/variable/VariableUtils.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/variable/VariableUtils.java index 65477bdd8553..879dd77df7a3 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/variable/VariableUtils.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/variable/VariableUtils.java @@ -37,7 +37,7 @@ /** * JDI-based debug variable implementation related utilities. */ -public class VariableUtils { +public final class VariableUtils { public static final String FIELD_TYPE = "type"; public static final String FIELD_TYPENAME = "typeName"; @@ -59,6 +59,9 @@ public class VariableUtils { public static final String INTERNAL_TYPE_REF_TYPE = "BTypeReferenceType"; public static final String INTERNAL_TYPE_INTERSECTION_TYPE = "BIntersectionType"; + private VariableUtils() { + } + /** * Returns the corresponding ballerina variable type of a given ballerina backend jvm variable instance. * @@ -470,10 +473,10 @@ public static String removeRedundantQuotes(String str) { */ public static Value getChildVarByName(BVariable variable, String childVarName) throws DebugVariableException, EvaluationException { - if (variable instanceof IndexedCompoundVariable) { - return ((IndexedCompoundVariable) variable).getChildByName(childVarName); - } else if (variable instanceof NamedCompoundVariable) { - return ((NamedCompoundVariable) variable).getChildByName(childVarName); + if (variable instanceof IndexedCompoundVariable indexedCompoundVariable) { + return indexedCompoundVariable.getChildByName(childVarName); + } else if (variable instanceof NamedCompoundVariable namedCompoundVariable) { + return namedCompoundVariable.getChildByName(childVarName); } else { throw createEvaluationException("Field access is not allowed for Ballerina simple types."); } diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/variable/types/BArray.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/variable/types/BArray.java index f42e36be0a6c..31194509e23f 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/variable/types/BArray.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/variable/types/BArray.java @@ -47,10 +47,9 @@ public BArray(SuspendedContext context, String name, Value value) { @Override public String computeValue() { try { - if (!(jvmValue instanceof ObjectReference)) { + if (!(jvmValue instanceof ObjectReference jvmValueRef)) { return UNKNOWN_VALUE; } - ObjectReference jvmValueRef = (ObjectReference) jvmValue; String arrayType = getArrayType(jvmValueRef); int arraySize = getArraySize(jvmValueRef); return String.format("%s[%d]", arrayType, arraySize); @@ -62,10 +61,9 @@ public String computeValue() { @Override protected Either, List> computeChildVariables(int start, int count) { try { - if (!(jvmValue instanceof ObjectReference)) { + if (!(jvmValue instanceof ObjectReference jvmValueRef)) { return Either.forRight(new ArrayList<>()); } - ObjectReference jvmValueRef = (ObjectReference) jvmValue; List fields = jvmValueRef.referenceType().allFields(); Field arrayValueField = jvmValueRef.getValues(fields).entrySet().stream().filter(fieldValueEntry -> fieldValueEntry.getValue() != null && fieldValueEntry.getKey().toString().endsWith("Values")) diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/variable/types/BByte.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/variable/types/BByte.java index de0f9776acf5..a7bbac799a4b 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/variable/types/BByte.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/variable/types/BByte.java @@ -40,8 +40,8 @@ public String computeValue() { // inclusive. It is equivalent to the built-in subtype int:Unsigned8. // Since JDI represents byte values as signed values by default, we need to explicitly converts them to // unsigned values in here. - if (jvmValue instanceof ByteValue) { - byte signedByteValue = ((ByteValue) jvmValue).byteValue(); + if (jvmValue instanceof ByteValue byteValue) { + byte signedByteValue = byteValue.byteValue(); int unsignedValue = signedByteValue & 0xFF; return String.valueOf(unsignedValue); } diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/variable/types/BObject.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/variable/types/BObject.java index 20ef2d622c58..c4a839e7ecbb 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/variable/types/BObject.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/variable/types/BObject.java @@ -50,10 +50,9 @@ public String computeValue() { @Override public Map computeChildVariables() { try { - if (!(jvmValue instanceof ObjectReference)) { + if (!(jvmValue instanceof ObjectReference jvmValueRef)) { return new LinkedHashMap<>(); } - ObjectReference jvmValueRef = (ObjectReference) jvmValue; Map fieldValueMap = jvmValueRef.getValues(jvmValueRef.referenceType().allFields()); Map values = new LinkedHashMap<>(); fieldValueMap.forEach((field, value) -> { @@ -70,10 +69,9 @@ public Map computeChildVariables() { @Override public int getChildrenCount() { try { - if (!(jvmValue instanceof ObjectReference)) { + if (!(jvmValue instanceof ObjectReference jvmValueRef)) { return 0; } - ObjectReference jvmValueRef = (ObjectReference) jvmValue; Map fieldValueMap = jvmValueRef.getValues(jvmValueRef.referenceType().allFields()); long objectFieldCount = fieldValueMap.keySet() .stream() diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/variable/types/BTuple.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/variable/types/BTuple.java index 7b06994aac5c..54dce1b6d074 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/variable/types/BTuple.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/variable/types/BTuple.java @@ -59,10 +59,9 @@ public String computeValue() { @Override public Either, List> computeChildVariables(int start, int count) { try { - if (!(jvmValue instanceof ObjectReference)) { + if (!(jvmValue instanceof ObjectReference jvmValueRef)) { return Either.forRight(new ArrayList<>()); } - ObjectReference jvmValueRef = (ObjectReference) jvmValue; Field valueField = jvmValueRef.referenceType().fieldByName("refValues"); // If count > 0, returns a sublist of the child variables @@ -104,9 +103,9 @@ private String getTupleType(Value jvmValue) { List subValues = ((ArrayReference) typesArray.get()).getValues(); StringJoiner tupleTypes = new StringJoiner(","); subValues.forEach(ref -> { - if (ref instanceof ObjectReference) { - Field typeNameField = ((ObjectReference) ref).referenceType().fieldByName("typeName"); - Value typeNameRef = ((ObjectReference) ref).getValue(typeNameField); + if (ref instanceof ObjectReference objectRef) { + Field typeNameField = objectRef.referenceType().fieldByName("typeName"); + Value typeNameRef = objectRef.getValue(typeNameField); tupleTypes.add(getStringFrom(typeNameRef)); } }); diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/variable/types/BUnknown.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/variable/types/BUnknown.java index aae20304c8e7..c31105a41ba6 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/variable/types/BUnknown.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/variable/types/BUnknown.java @@ -37,10 +37,9 @@ public BUnknown(SuspendedContext context, String name, Value value) { @Override public String computeValue() { - if (!(jvmValue instanceof ObjectReference)) { + if (!(jvmValue instanceof ObjectReference jvmValueRef)) { return UNKNOWN_VALUE; } - ObjectReference jvmValueRef = (ObjectReference) jvmValue; return Optional.of(jvmValueRef).map(ObjectReference::toString).orElse(UNKNOWN_VALUE); } } diff --git a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/variable/types/BXmlSequence.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/variable/types/BXmlSequence.java index d3f1e0014197..8d164e1b3368 100644 --- a/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/variable/types/BXmlSequence.java +++ b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/variable/types/BXmlSequence.java @@ -82,8 +82,8 @@ public Either, List> computeChildVariables(int start, getXmlChildrenInRange.setArgValues(argValues); Value childArray = getXmlChildrenInRange.invokeSafely(); - if (childArray instanceof ArrayReference) { - childValues = ((ArrayReference) childArray).getValues(); + if (childArray instanceof ArrayReference arrayReference) { + childValues = arrayReference.getValues(); } return Either.forRight(childValues); } catch (Exception e) { @@ -111,10 +111,10 @@ private void populateChildrenCount() { getSizeMethod.setArgValues(new ArrayList<>()); Value getSizeResult = getSizeMethod.invokeSafely(); - if (getSizeResult instanceof IntegerValue) { - childrenCount = ((IntegerValue) getSizeResult).intValue(); - } else if (getSizeResult instanceof LongValue) { - childrenCount = ((LongValue) getSizeResult).intValue(); + if (getSizeResult instanceof IntegerValue integerValue) { + childrenCount = integerValue.intValue(); + } else if (getSizeResult instanceof LongValue longValue) { + childrenCount = longValue.intValue(); } else { childrenCount = 0; } diff --git a/misc/debug-adapter/modules/debug-adapter-runtime/src/main/java/org/ballerinalang/debugadapter/runtime/DebuggerRuntime.java b/misc/debug-adapter/modules/debug-adapter-runtime/src/main/java/org/ballerinalang/debugadapter/runtime/DebuggerRuntime.java index ef3bd6e87efa..656e9c49c242 100644 --- a/misc/debug-adapter/modules/debug-adapter-runtime/src/main/java/org/ballerinalang/debugadapter/runtime/DebuggerRuntime.java +++ b/misc/debug-adapter/modules/debug-adapter-runtime/src/main/java/org/ballerinalang/debugadapter/runtime/DebuggerRuntime.java @@ -85,7 +85,7 @@ * @since 2.0.0 */ @SuppressWarnings("unused") -public class DebuggerRuntime { +public final class DebuggerRuntime { private static final String EVALUATOR_STRAND_NAME = "evaluator-strand"; private static final String XML_STEP_SEPARATOR = "/"; @@ -113,7 +113,7 @@ public static Object invokeObjectMethod(BObject bObject, String methodName, Obje final Object[] finalResult = new Object[1]; final Object[] paramValues = args[0] instanceof Strand ? Arrays.copyOfRange(args, 1, args.length) : args; - Function func = o -> bObject.call((Strand) (((Object[]) o)[0]), methodName, paramValues); + Function func = o -> bObject.call((Strand) ((o)[0]), methodName, paramValues); Object resultFuture = scheduler.schedule(new Object[1], func, null, new Callback() { @Override public void notifySuccess(Object result) { @@ -262,8 +262,8 @@ public static Object getAnnotationValue(Object typedescValue, String annotationN "found '" + typedescValue.toString() + "'.")); } Type type = ((TypedescValue) typedescValue).getDescribingType(); - if (type instanceof BAnnotatableType) { - return ((BAnnotatableType) type).getAnnotations().entrySet() + if (type instanceof BAnnotatableType bAnnotatableType) { + return bAnnotatableType.getAnnotations().entrySet() .stream() .filter(annotationEntry -> annotationEntry.getKey().getValue().endsWith(annotationName)) .findFirst() @@ -295,8 +295,8 @@ private static String getBTypeName(Object value) { return "int"; } else if (value instanceof Float || value instanceof Double) { return "float"; - } else if (value instanceof BValue) { - return ((BValue) value).getType().getName(); + } else if (value instanceof BValue bValue) { + return bValue.getType().getName(); } else { return "unknown"; } @@ -439,8 +439,8 @@ public static Object classloadAndInvokeFunction(String executablePath, String ma * @param args Arguments to provide. * @return The result of the invocation. */ - protected static Object invokeMethodDirectly(ClassLoader classLoader, String className, String methodName, - Class[] argTypes, Object[] args) throws Exception { + private static Object invokeMethodDirectly(ClassLoader classLoader, String className, String methodName, + Class[] argTypes, Object[] args) throws Exception { Class clazz = classLoader.loadClass(className); Method method = clazz.getDeclaredMethod(methodName, argTypes); return method.invoke(null, args); diff --git a/misc/debug-adapter/modules/debug-adapter-runtime/src/main/java/org/ballerinalang/debugadapter/runtime/VariableUtils.java b/misc/debug-adapter/modules/debug-adapter-runtime/src/main/java/org/ballerinalang/debugadapter/runtime/VariableUtils.java index 2ca97ca8809a..cd15f0d33bf5 100644 --- a/misc/debug-adapter/modules/debug-adapter-runtime/src/main/java/org/ballerinalang/debugadapter/runtime/VariableUtils.java +++ b/misc/debug-adapter/modules/debug-adapter-runtime/src/main/java/org/ballerinalang/debugadapter/runtime/VariableUtils.java @@ -27,11 +27,14 @@ * @since 2.0.0 */ @SuppressWarnings("unused") -public class VariableUtils { +public final class VariableUtils { private static final String MAP_TYPE_TEMPLATE = "map<%s>"; private static final String UNKNOWN = "unknown"; + private VariableUtils() { + } + /** * Extract map type with constraint from a given BMapValue. * @@ -39,16 +42,14 @@ public class VariableUtils { * @return map type with constraint from a given BMapValue */ public static String getBMapType(Object mapObject) { - if (!(mapObject instanceof MapValueImpl)) { + if (!(mapObject instanceof MapValueImpl mapValue)) { return String.format(MAP_TYPE_TEMPLATE, UNKNOWN); } - MapValueImpl mapValue = (MapValueImpl) mapObject; - if (!(mapValue.getType() instanceof BMapType)) { + if (!(mapValue.getType() instanceof BMapType type)) { return String.format(MAP_TYPE_TEMPLATE, UNKNOWN); } - BMapType type = (BMapType) mapValue.getType(); return String.format(MAP_TYPE_TEMPLATE, type.getConstrainedType().toString()); } } diff --git a/misc/diagram-util/src/main/java/org/ballerinalang/diagramutil/DiagramUtil.java b/misc/diagram-util/src/main/java/org/ballerinalang/diagramutil/DiagramUtil.java index 2e3877497453..c46a1a25d304 100644 --- a/misc/diagram-util/src/main/java/org/ballerinalang/diagramutil/DiagramUtil.java +++ b/misc/diagram-util/src/main/java/org/ballerinalang/diagramutil/DiagramUtil.java @@ -31,7 +31,10 @@ /** * This is the DiagramUtil class for Diagram related Utils which include the JSON conversion of the Syntax Tree. */ -public class DiagramUtil { +public final class DiagramUtil { + + private DiagramUtil() { + } /** * Get the Modified JSON ST with type info. diff --git a/misc/diagram-util/src/main/java/org/ballerinalang/diagramutil/SyntaxTreeDiagnosticsUtil.java b/misc/diagram-util/src/main/java/org/ballerinalang/diagramutil/SyntaxTreeDiagnosticsUtil.java index 263a2f3edb1a..bdf47ae61bf1 100644 --- a/misc/diagram-util/src/main/java/org/ballerinalang/diagramutil/SyntaxTreeDiagnosticsUtil.java +++ b/misc/diagram-util/src/main/java/org/ballerinalang/diagramutil/SyntaxTreeDiagnosticsUtil.java @@ -28,7 +28,11 @@ * @since 2.0.0 */ -public class SyntaxTreeDiagnosticsUtil { +public final class SyntaxTreeDiagnosticsUtil { + + private SyntaxTreeDiagnosticsUtil() { + } + public static JsonArray getDiagnostics(Iterable diagnostics) { JsonArray diagnosticsArray = new JsonArray(); for (Diagnostic diagnostic : diagnostics) { diff --git a/misc/diagram-util/src/main/java/org/ballerinalang/diagramutil/SyntaxTreeMapGenerator.java b/misc/diagram-util/src/main/java/org/ballerinalang/diagramutil/SyntaxTreeMapGenerator.java index 072e1627a826..b93ccda73a55 100644 --- a/misc/diagram-util/src/main/java/org/ballerinalang/diagramutil/SyntaxTreeMapGenerator.java +++ b/misc/diagram-util/src/main/java/org/ballerinalang/diagramutil/SyntaxTreeMapGenerator.java @@ -27,6 +27,7 @@ import io.ballerina.compiler.api.symbols.ObjectTypeSymbol; import io.ballerina.compiler.api.symbols.Qualifier; import io.ballerina.compiler.api.symbols.Symbol; +import io.ballerina.compiler.api.symbols.SymbolKind; import io.ballerina.compiler.api.symbols.TypeDescKind; import io.ballerina.compiler.api.symbols.TypeReferenceTypeSymbol; import io.ballerina.compiler.api.symbols.TypeSymbol; @@ -271,8 +272,7 @@ protected JsonElement transformSyntaxNode(Node node) { if (semanticModel != null) { Optional symbol = this.semanticModel.symbol(node); - if (symbol.isPresent() && (symbol.get() instanceof VariableSymbol)) { - VariableSymbol variableSymbol = (VariableSymbol) symbol.get(); + if (symbol.isPresent() && (symbol.get() instanceof VariableSymbol variableSymbol)) { markVisibleEp(variableSymbol, symbolJson, node); } @@ -297,8 +297,8 @@ protected JsonElement transformSyntaxNode(Node node) { if (semanticModel != null) { Optional expressionSymbol = this.semanticModel.symbol( remoteMethodCallActionNode.expression()); - if (expressionSymbol.isPresent() && expressionSymbol.get() instanceof VariableSymbol) { - VariableSymbol variableSymbol = (VariableSymbol) expressionSymbol.get(); + if (expressionSymbol.isPresent() && + expressionSymbol.get() instanceof VariableSymbol variableSymbol) { markVisibleEp(variableSymbol, symbolJson, remoteMethodCallActionNode.expression(), true); } } @@ -585,9 +585,9 @@ private JsonElement generateTypeJson(Symbol symbol) throws JSONGenerationExcepti throw new JSONGenerationException("Error occurred while generating JSON", e); } - if (prop instanceof Symbol) { + if (prop instanceof Symbol symbolProp) { if (!jsonName.equals("typeDescriptor")) { - nodeJson.add(jsonName, generateTypeJson((Symbol) prop)); + nodeJson.add(jsonName, generateTypeJson(symbolProp)); } // TODO: verify if this is needed and enable (need to add to the nodeJson as well) // } else if (prop instanceof List) { @@ -602,31 +602,30 @@ private JsonElement generateTypeJson(Symbol symbol) throws JSONGenerationExcepti // listPropJson.add((Boolean) listPropItem); // } // } - } else if (prop instanceof Optional && - ((Optional) prop).isPresent() && ((Optional) prop).get() instanceof ModuleSymbol) { - ModuleID ballerinaModuleID = ((ModuleSymbol) ((Optional) prop).get()).id(); + } else if (prop instanceof Optional optionalProp && + optionalProp.isPresent() && optionalProp.get() instanceof ModuleSymbol moduleSymbol) { + ModuleID ballerinaModuleID = moduleSymbol.id(); JsonObject moduleIdJson = new JsonObject(); moduleIdJson.addProperty("orgName", ballerinaModuleID.orgName()); moduleIdJson.addProperty("packageName", ballerinaModuleID.packageName()); moduleIdJson.addProperty("moduleName", ballerinaModuleID.moduleName()); moduleIdJson.addProperty("version", ballerinaModuleID.version()); nodeJson.add("moduleID", moduleIdJson); - } else if (prop instanceof ModuleID) { - ModuleID ballerinaModuleID = (ModuleID) prop; + } else if (prop instanceof ModuleID ballerinaModuleID) { JsonObject moduleIdJson = new JsonObject(); moduleIdJson.addProperty("orgName", ballerinaModuleID.orgName()); moduleIdJson.addProperty("packageName", ballerinaModuleID.packageName()); moduleIdJson.addProperty("moduleName", ballerinaModuleID.moduleName()); moduleIdJson.addProperty("version", ballerinaModuleID.version()); nodeJson.add(jsonName, moduleIdJson); - } else if (prop instanceof TypeDescKind) { - nodeJson.addProperty(jsonName, ((TypeDescKind) prop).getName()); - } else if (prop instanceof io.ballerina.compiler.api.symbols.SymbolKind) { - nodeJson.addProperty(jsonName, ((io.ballerina.compiler.api.symbols.SymbolKind) prop).name()); - } else if (prop instanceof String) { - nodeJson.addProperty(jsonName, (String) prop); - } else if (prop instanceof Boolean) { - nodeJson.addProperty(jsonName, (Boolean) prop); + } else if (prop instanceof TypeDescKind typeDescKind) { + nodeJson.addProperty(jsonName, typeDescKind.getName()); + } else if (prop instanceof SymbolKind symbolKind) { + nodeJson.addProperty(jsonName, symbolKind.name()); + } else if (prop instanceof String s) { + nodeJson.addProperty(jsonName, s); + } else if (prop instanceof Boolean b) { + nodeJson.addProperty(jsonName, b); } } @@ -636,9 +635,9 @@ private JsonElement generateTypeJson(Symbol symbol) throws JSONGenerationExcepti private JsonElement apply(Node node) { JsonObject nodeInfo = new JsonObject(); nodeInfo.addProperty("kind", prettifyKind(node.kind().toString())); - if (node instanceof Token) { + if (node instanceof Token token) { nodeInfo.addProperty("isToken", true); - nodeInfo.addProperty("value", ((Token) node).text()); + nodeInfo.addProperty("value", token.text()); nodeInfo.addProperty("isMissing", node.isMissing()); if (node.lineRange() != null) { LineRange lineRange = node.lineRange(); diff --git a/misc/diagram-util/src/main/java/org/ballerinalang/diagramutil/connector/generator/ConnectorGenerator.java b/misc/diagram-util/src/main/java/org/ballerinalang/diagramutil/connector/generator/ConnectorGenerator.java index dd8dfdbbec18..c7a155861ed7 100644 --- a/misc/diagram-util/src/main/java/org/ballerinalang/diagramutil/connector/generator/ConnectorGenerator.java +++ b/misc/diagram-util/src/main/java/org/ballerinalang/diagramutil/connector/generator/ConnectorGenerator.java @@ -56,7 +56,7 @@ /** * Generate connector metadata using project syntax tree and semantic model. */ -public class ConnectorGenerator { +public final class ConnectorGenerator { private ConnectorGenerator() { } @@ -195,14 +195,13 @@ private static List getConnectorFunctions(SemanticModel semanticModel, ClassDefinitionNode classDefinition) { List functions = new ArrayList<>(); for (Node member : classDefinition.members()) { - if (!(member instanceof FunctionDefinitionNode)) { + if (!(member instanceof FunctionDefinitionNode functionDefinition)) { continue; } - NodeList qualifierList = ((FunctionDefinitionNode) member).qualifierList(); + NodeList qualifierList = functionDefinition.qualifierList(); if ((Generator.containsToken(qualifierList, SyntaxKind.PUBLIC_KEYWORD) || Generator.containsToken(qualifierList, SyntaxKind.REMOTE_KEYWORD) || Generator.containsToken(qualifierList, SyntaxKind.RESOURCE_KEYWORD))) { - FunctionDefinitionNode functionDefinition = (FunctionDefinitionNode) member; String functionName = functionDefinition.functionName().text(); Map funcAnnotation = diff --git a/misc/diagram-util/src/main/java/org/ballerinalang/diagramutil/connector/generator/GeneratorUtils.java b/misc/diagram-util/src/main/java/org/ballerinalang/diagramutil/connector/generator/GeneratorUtils.java index 38802974a998..cd723a85a4c1 100644 --- a/misc/diagram-util/src/main/java/org/ballerinalang/diagramutil/connector/generator/GeneratorUtils.java +++ b/misc/diagram-util/src/main/java/org/ballerinalang/diagramutil/connector/generator/GeneratorUtils.java @@ -55,7 +55,10 @@ /** * Common utils used in project api generators. */ -public class GeneratorUtils { +public final class GeneratorUtils { + + private GeneratorUtils() { + } public static String getDocCodeBlockString(MarkdownCodeBlockNode markdownCodeBlockNode) { StringBuilder doc = new StringBuilder(); @@ -80,11 +83,11 @@ public static String getDocFromMetadata(Optional optionalMetadataN (MarkdownDocumentationNode) optionalMetadataNode.get().documentationString().get() : null; if (docLines != null) { for (Node docLine : docLines.documentationLines()) { - if (docLine instanceof MarkdownDocumentationLineNode) { - doc.append(!((MarkdownDocumentationLineNode) docLine).documentElements().isEmpty() ? - getDocLineString(((MarkdownDocumentationLineNode) docLine).documentElements()) : "\n"); - } else if (docLine instanceof MarkdownCodeBlockNode) { - doc.append(getDocCodeBlockString((MarkdownCodeBlockNode) docLine)); + if (docLine instanceof MarkdownDocumentationLineNode markdownDocLine) { + doc.append(!markdownDocLine.documentElements().isEmpty() ? + getDocLineString(markdownDocLine.documentElements()) : "\n"); + } else if (docLine instanceof MarkdownCodeBlockNode markdownCodeBlock) { + doc.append(getDocCodeBlockString(markdownCodeBlock)); } else { break; } @@ -139,17 +142,16 @@ public static String getParameterDocFromMetadataList(String parameterName, if (docLines != null) { boolean lookForMoreLines = false; for (Node docLine : docLines.documentationLines()) { - if (docLine instanceof MarkdownParameterDocumentationLineNode) { - if (((MarkdownParameterDocumentationLineNode) docLine).parameterName().text() - .equals(parameterName)) { + if (docLine instanceof MarkdownParameterDocumentationLineNode markdownParameterDocumentationLineNode) { + if (markdownParameterDocumentationLineNode.parameterName().text().equals(parameterName)) { parameterDoc.append(getDocLineString(((MarkdownParameterDocumentationLineNode) docLine) .documentElements())); lookForMoreLines = true; } else { lookForMoreLines = false; } - } else if (lookForMoreLines && docLine instanceof MarkdownDocumentationLineNode) { - parameterDoc.append(getDocLineString(((MarkdownDocumentationLineNode) docLine).documentElements())); + } else if (lookForMoreLines && docLine instanceof MarkdownDocumentationLineNode markdownDocLine) { + parameterDoc.append(getDocLineString(markdownDocLine.documentElements())); } } } @@ -173,8 +175,8 @@ public static Map getDisplayAnnotationFromAnnotationsList(NodeLi if (((SpecificFieldNode) fieldNode).valueExpr().isPresent()) { ExpressionNode valueNode = ((SpecificFieldNode) fieldNode).valueExpr().get(); - if (valueNode instanceof BasicLiteralNode) { - String fieldValue = ((BasicLiteralNode) valueNode).literalToken().text(); + if (valueNode instanceof BasicLiteralNode basicLiteralNode) { + String fieldValue = basicLiteralNode.literalToken().text(); if (fieldValue.startsWith("\"") && fieldValue.endsWith("\"")) { fieldValue = fieldValue.substring(1, fieldValue.length() - 1); } diff --git a/misc/diagram-util/src/main/java/org/ballerinalang/diagramutil/connector/models/connector/Type.java b/misc/diagram-util/src/main/java/org/ballerinalang/diagramutil/connector/models/connector/Type.java index 793ef033ddc9..ed74dd4437c7 100644 --- a/misc/diagram-util/src/main/java/org/ballerinalang/diagramutil/connector/models/connector/Type.java +++ b/misc/diagram-util/src/main/java/org/ballerinalang/diagramutil/connector/models/connector/Type.java @@ -226,9 +226,7 @@ public static Optional fromSyntaxNode(Node node, SemanticModel semanticMod } break; default: - if (node instanceof BuiltinSimpleNameReferenceNode) { - BuiltinSimpleNameReferenceNode builtinSimpleNameReferenceNode = - (BuiltinSimpleNameReferenceNode) node; + if (node instanceof BuiltinSimpleNameReferenceNode builtinSimpleNameReferenceNode) { type = Optional.of(new PrimitiveType(builtinSimpleNameReferenceNode.name().text())); } else { type = Optional.of(new PrimitiveType(node.toSourceCode())); @@ -276,11 +274,9 @@ public static void completeVisitedTypeEntry(String typeName, Type typeNode) { public static Type fromSemanticSymbol(Symbol symbol) { Type type = null; - if (symbol instanceof TypeReferenceTypeSymbol) { - TypeReferenceTypeSymbol typeReferenceTypeSymbol = (TypeReferenceTypeSymbol) symbol; + if (symbol instanceof TypeReferenceTypeSymbol typeReferenceTypeSymbol) { type = getEnumType(typeReferenceTypeSymbol, symbol); - } else if (symbol instanceof RecordTypeSymbol) { - RecordTypeSymbol recordTypeSymbol = (RecordTypeSymbol) symbol; + } else if (symbol instanceof RecordTypeSymbol recordTypeSymbol) { String typeName = String.valueOf(recordTypeSymbol.hashCode()); VisitedType visitedType = getVisitedType(typeName); if (visitedType != null) { @@ -294,22 +290,18 @@ public static Type fromSemanticSymbol(Symbol symbol) { completeVisitedTypeEntry(typeName, type); } } - } else if (symbol instanceof ArrayTypeSymbol) { - ArrayTypeSymbol arrayTypeSymbol = (ArrayTypeSymbol) symbol; + } else if (symbol instanceof ArrayTypeSymbol arrayTypeSymbol) { type = new ArrayType(fromSemanticSymbol(arrayTypeSymbol.memberTypeDescriptor())); - } else if (symbol instanceof MapTypeSymbol) { - MapTypeSymbol mapTypeSymbol = (MapTypeSymbol) symbol; + } else if (symbol instanceof MapTypeSymbol mapTypeSymbol) { type = new MapType(fromSemanticSymbol(mapTypeSymbol.typeParam())); - } else if (symbol instanceof TableTypeSymbol) { - TableTypeSymbol tableTypeSymbol = (TableTypeSymbol) symbol; + } else if (symbol instanceof TableTypeSymbol tableTypeSymbol) { TypeSymbol keyConstraint = null; if (tableTypeSymbol.keyConstraintTypeParameter().isPresent()) { keyConstraint = tableTypeSymbol.keyConstraintTypeParameter().get(); } type = new TableType(fromSemanticSymbol(tableTypeSymbol.rowTypeParameter()), tableTypeSymbol.keySpecifiers(), fromSemanticSymbol(keyConstraint)); - } else if (symbol instanceof UnionTypeSymbol) { - UnionTypeSymbol unionSymbol = (UnionTypeSymbol) symbol; + } else if (symbol instanceof UnionTypeSymbol unionSymbol) { String typeName = String.valueOf(unionSymbol.hashCode()); VisitedType visitedType = getVisitedType(typeName); if (visitedType != null) { @@ -319,15 +311,13 @@ public static Type fromSemanticSymbol(Symbol symbol) { type = getUnionType(unionSymbol); completeVisitedTypeEntry(typeName, type); } - } else if (symbol instanceof ErrorTypeSymbol) { - ErrorTypeSymbol errSymbol = (ErrorTypeSymbol) symbol; + } else if (symbol instanceof ErrorTypeSymbol errSymbol) { ErrorType errType = new ErrorType(); if (errSymbol.detailTypeDescriptor() instanceof TypeReferenceTypeSymbol) { errType.detailType = fromSemanticSymbol(errSymbol.detailTypeDescriptor()); } type = errType; - } else if (symbol instanceof IntersectionTypeSymbol) { - IntersectionTypeSymbol intersectionTypeSymbol = (IntersectionTypeSymbol) symbol; + } else if (symbol instanceof IntersectionTypeSymbol intersectionTypeSymbol) { String typeName = String.valueOf(intersectionTypeSymbol.hashCode()); VisitedType visitedType = getVisitedType(typeName); if (visitedType != null) { @@ -337,11 +327,9 @@ public static Type fromSemanticSymbol(Symbol symbol) { type = getIntersectionType(intersectionTypeSymbol); completeVisitedTypeEntry(typeName, type); } - } else if (symbol instanceof StreamTypeSymbol) { - StreamTypeSymbol streamTypeSymbol = (StreamTypeSymbol) symbol; + } else if (symbol instanceof StreamTypeSymbol streamTypeSymbol) { type = getStreamType(streamTypeSymbol); - } else if (symbol instanceof ObjectTypeSymbol) { - ObjectTypeSymbol objectTypeSymbol = (ObjectTypeSymbol) symbol; + } else if (symbol instanceof ObjectTypeSymbol objectTypeSymbol) { ObjectType objectType = new ObjectType(); objectTypeSymbol.fieldDescriptors().forEach((typeName, typeSymbol) -> { Type semanticSymbol = fromSemanticSymbol(typeSymbol); @@ -356,20 +344,17 @@ public static Type fromSemanticSymbol(Symbol symbol) { } }); type = objectType; - } else if (symbol instanceof RecordFieldSymbol) { - RecordFieldSymbol recordFieldSymbol = (RecordFieldSymbol) symbol; + } else if (symbol instanceof RecordFieldSymbol recordFieldSymbol) { type = fromSemanticSymbol(recordFieldSymbol.typeDescriptor()); - } else if (symbol instanceof ParameterSymbol) { - ParameterSymbol parameterSymbol = (ParameterSymbol) symbol; + } else if (symbol instanceof ParameterSymbol parameterSymbol) { type = fromSemanticSymbol(parameterSymbol.typeDescriptor()); if (type != null) { type.defaultable = parameterSymbol.paramKind() == ParameterKind.DEFAULTABLE; } - } else if (symbol instanceof VariableSymbol) { - VariableSymbol variableSymbol = (VariableSymbol) symbol; + } else if (symbol instanceof VariableSymbol variableSymbol) { type = fromSemanticSymbol(variableSymbol.typeDescriptor()); - } else if (symbol instanceof TypeSymbol) { - String typeName = ((TypeSymbol) symbol).signature(); + } else if (symbol instanceof TypeSymbol typeSymbol) { + String typeName = typeSymbol.signature(); if (typeName.startsWith("\"") && typeName.endsWith("\"")) { typeName = typeName.substring(1, typeName.length() - 1); } @@ -383,15 +368,15 @@ private static Type getAlreadyVisitedType(Symbol symbol, String typeName, Visite if (visitedType.isCompleted()) { Type existingType = visitedType.getTypeNode(); if (getClone) { - if (existingType instanceof UnionType) { - return new UnionType((UnionType) existingType); + if (existingType instanceof UnionType unionType) { + return new UnionType(unionType); } return new Type(existingType.getName(), existingType.getTypeName(), existingType.isOptional(), existingType.getTypeInfo(), existingType.isDefaultable(), existingType.getDefaultValue(), existingType.getDisplayAnnotation(), existingType.getDocumentation()); } - if (existingType instanceof RecordType) { - return new RecordType((RecordType) existingType); + if (existingType instanceof RecordType recordType) { + return new RecordType(recordType); } return existingType; } else { diff --git a/misc/diagram-util/src/test/java/org/ballerinalang/diagramutil/TestUtil.java b/misc/diagram-util/src/test/java/org/ballerinalang/diagramutil/TestUtil.java index 829802c6563b..5b420529c890 100644 --- a/misc/diagram-util/src/test/java/org/ballerinalang/diagramutil/TestUtil.java +++ b/misc/diagram-util/src/test/java/org/ballerinalang/diagramutil/TestUtil.java @@ -25,10 +25,14 @@ /** * Utility class for syntax tree gen tests. */ -public class TestUtil { +public final class TestUtil { + public static final Path RES_DIR = Paths.get("src/test/resources/").toAbsolutePath(); public static final Path BUILD_DIR = Paths.get("build/").toAbsolutePath(); + private TestUtil() { + } + public static Path createTempFile(Path filePath) throws IOException { Path tempFilePath = BUILD_DIR.resolve("tmp") .resolve(UUID.randomUUID() + ".bal"); diff --git a/misc/docerina/src/main/java/org/ballerinalang/docgen/Generator.java b/misc/docerina/src/main/java/org/ballerinalang/docgen/Generator.java index 70932cd9014a..baeeb2bf1d10 100644 --- a/misc/docerina/src/main/java/org/ballerinalang/docgen/Generator.java +++ b/misc/docerina/src/main/java/org/ballerinalang/docgen/Generator.java @@ -95,12 +95,12 @@ import java.util.List; import java.util.Optional; import java.util.StringJoiner; -import java.util.stream.Collectors; +import java.util.stream.Stream; /** * Generates the Page bClasses for bal packages. */ -public class Generator { +public final class Generator { private static final String EMPTY_STRING = ""; private static final String RETURN_PARAM_NAME = "return"; @@ -112,6 +112,9 @@ public class Generator { public static final String LISTENER_GRACEFUL_STOP_METHOD_NAME = "gracefulStop"; public static final String DOC_HEADER_PREFIX = "# "; + private Generator() { + } + /** * Generate/Set the module constructs model(docerina model) when the syntax tree for the module is given. * @@ -138,10 +141,10 @@ public static void setModuleFromSyntaxTree(Module module, SyntaxTree syntaxTree, if (classDefinition.visibilityQualifier().isPresent() && classDefinition.visibilityQualifier().get() .kind().equals(SyntaxKind.PUBLIC_KEYWORD)) { BClass cls = getClassModel((ClassDefinitionNode) node, semanticModel, module); - if (cls instanceof Client) { - module.clients.add((Client) cls); - } else if (cls instanceof Listener) { - module.listeners.add((Listener) cls); + if (cls instanceof Client client) { + module.clients.add(client); + } else if (cls instanceof Listener listener) { + module.listeners.add(listener); } else { module.classes.add(cls); } @@ -572,13 +575,11 @@ private static BClass getClassModel(ClassDefinitionNode classDefinitionNode, Sem } // Get functions that are not overridden - List functions = includedFunctions.stream().filter(includedFunction -> + List functions = Stream.concat(includedFunctions.stream().filter(includedFunction -> classFunctions .stream() - .noneMatch(objFunction -> objFunction.name.equals(includedFunction.name))) - .collect(Collectors.toList()); - - functions.addAll(classFunctions); + .noneMatch(objFunction -> objFunction.name.equals(includedFunction.name))), + classFunctions.stream()).toList(); if (containsToken(classDefinitionNode.classTypeQualifiers(), SyntaxKind.CLIENT_KEYWORD)) { return new Client(name, description, descriptionSections, isDeprecated, fields, functions, isReadOnly, @@ -632,8 +633,7 @@ private static BObjectType getObjectTypeModel(ObjectTypeDescriptorNode typeDescr optionalMetadataNode, semanticModel, module); for (Node member : typeDescriptorNode.members()) { - if (member instanceof MethodDeclarationNode) { - MethodDeclarationNode methodNode = (MethodDeclarationNode) member; + if (member instanceof MethodDeclarationNode methodNode) { if (containsToken(methodNode.qualifierList(), SyntaxKind.PUBLIC_KEYWORD) || containsToken(methodNode.qualifierList(), SyntaxKind.REMOTE_KEYWORD) || containsToken(methodNode.qualifierList(), SyntaxKind.RESOURCE_KEYWORD)) { @@ -682,21 +682,18 @@ private static BObjectType getObjectTypeModel(ObjectTypeDescriptorNode typeDescr } } else if (member instanceof TypeReferenceNode) { Type originType = Type.fromNode(member, semanticModel, module); - if (originType instanceof ObjectType) { - includedFunctions.addAll(mapFunctionTypesToFunctions(((ObjectType) originType).functionTypes, + if (originType instanceof ObjectType objectType) { + includedFunctions.addAll(mapFunctionTypesToFunctions(objectType.functionTypes, originType)); } } } // Get functions that are not overridden - List functions = includedFunctions.stream().filter(includedFunction -> - objectFunctions - .stream() - .noneMatch(objFunction -> objFunction.name.equals(includedFunction.name))) - .collect(Collectors.toList()); - - functions.addAll(objectFunctions); + List functions = Stream.concat( + includedFunctions.stream().filter(includedFunction -> objectFunctions.stream() + .noneMatch(objFunction -> objFunction.name.equals(includedFunction.name))), + objectFunctions.stream()).toList(); return new BObjectType(objectName, description, descriptionSections, isDeprecated, fields, functions); } @@ -706,7 +703,7 @@ private static List mapFunctionTypesToFunctions(List fun for (FunctionType functionType : functionTypes) { List parameters = new ArrayList<>(functionType.paramTypes.stream() .map(type -> new DefaultableVariable(type.name, type.description, false, - type.elementType, "")).collect(Collectors.toList())); + type.elementType, "")).toList()); List returnParameters = new ArrayList<>(); if (functionType.returnType != null) { @@ -791,14 +788,13 @@ private static Record getRecordTypeModel(RecordTypeDescriptorNode recordTypeDesc isDeprecated(optionalMetadataNode), isClosed, fields); } - public static List getDefaultableVariableList(NodeList nodeList, + public static List getDefaultableVariableList(NodeList nodeList, Optional optionalMetadataNode, SemanticModel semanticModel, Module module) { List variables = new ArrayList<>(); for (int i = 0; i < nodeList.size(); i++) { Node node = nodeList.get(i); - if (node instanceof RecordFieldWithDefaultValueNode) { - RecordFieldWithDefaultValueNode recordField = (RecordFieldWithDefaultValueNode) node; + if (node instanceof RecordFieldWithDefaultValueNode recordField) { String name = recordField.fieldName().text(); String doc = getDocFromMetadata(recordField.metadata()); if (doc.isEmpty()) { @@ -813,8 +809,7 @@ defaultValue, extractAnnotationAttachmentsFromMetadataNode(semanticModel, defaultableVariable.isReadOnly = true; } variables.add(defaultableVariable); - } else if (node instanceof RecordFieldNode) { - RecordFieldNode recordField = (RecordFieldNode) node; + } else if (node instanceof RecordFieldNode recordField) { String name = recordField.fieldName().text(); String doc = getDocFromMetadata(recordField.metadata()); if (doc.isEmpty()) { @@ -838,8 +833,7 @@ defaultValue, extractAnnotationAttachmentsFromMetadataNode(semanticModel, } else if (!originType.memberTypes.isEmpty()) { variables.add(new DefaultableVariable(originType)); } - } else if (node instanceof ObjectFieldNode) { - ObjectFieldNode objectField = (ObjectFieldNode) node; + } else if (node instanceof ObjectFieldNode objectField) { if (objectField.visibilityQualifier().isPresent() && objectField.visibilityQualifier().get().kind() .equals(SyntaxKind.PUBLIC_KEYWORD)) { String name = objectField.fieldName().text(); @@ -859,15 +853,13 @@ defaultValue, extractAnnotationAttachmentsFromMetadataNode(semanticModel, extractAnnotationAttachmentsFromMetadataNode(semanticModel, objectField.metadata())); variables.add(defaultableVariable); } - } else if (node instanceof RequiredParameterNode) { - RequiredParameterNode requiredParameter = (RequiredParameterNode) node; + } else if (node instanceof RequiredParameterNode requiredParameter) { String paramName = requiredParameter.paramName().isPresent() ? requiredParameter.paramName().get().text() : ""; Type type = Type.fromNode(requiredParameter.typeName(), semanticModel, module); variables.add(new DefaultableVariable(paramName, getParameterDocFromMetadataList(paramName, optionalMetadataNode), isDeprecated(requiredParameter.annotations()), type, "")); - } else if (node instanceof DefaultableParameterNode) { - DefaultableParameterNode defaultableParameter = (DefaultableParameterNode) node; + } else if (node instanceof DefaultableParameterNode defaultableParameter) { String paramName = defaultableParameter.paramName().isPresent() ? defaultableParameter.paramName().get().text() : ""; Type type = Type.fromNode(defaultableParameter.typeName(), semanticModel, module); @@ -876,8 +868,7 @@ defaultValue, extractAnnotationAttachmentsFromMetadataNode(semanticModel, type, defaultableParameter.expression().toString(), extractAnnotationAttachmentsFromAnnotations(semanticModel, defaultableParameter.annotations()))); - } else if (node instanceof RestParameterNode) { - RestParameterNode restParameter = (RestParameterNode) node; + } else if (node instanceof RestParameterNode restParameter) { String paramName = restParameter.paramName().isPresent() ? restParameter.paramName().get().text() : ""; Type type = new Type(paramName); @@ -885,8 +876,7 @@ defaultValue, extractAnnotationAttachmentsFromMetadataNode(semanticModel, type.elementType = Type.fromNode(restParameter.typeName(), semanticModel, module); variables.add(new DefaultableVariable(paramName, getParameterDocFromMetadataList(paramName, optionalMetadataNode), false, type, "")); - } else if (node instanceof IncludedRecordParameterNode) { - IncludedRecordParameterNode includedRecord = (IncludedRecordParameterNode) node; + } else if (node instanceof IncludedRecordParameterNode includedRecord) { String paramName = includedRecord.paramName().isPresent() ? includedRecord.paramName().get().text() : ""; Type type = Type.fromNode(includedRecord.typeName(), semanticModel, module); @@ -971,16 +961,15 @@ private static String getDocFromMetadata(Optional optionalMetadata (MarkdownDocumentationNode) optionalMetadataNode.get().documentationString().get() : null; if (docLines != null) { for (Node docLine : docLines.documentationLines()) { - if (docLine instanceof MarkdownDocumentationLineNode) { - String docLineString = getDocLineString(((MarkdownDocumentationLineNode) docLine). - documentElements()); + if (docLine instanceof MarkdownDocumentationLineNode markdownDocLine) { + String docLineString = getDocLineString(markdownDocLine.documentElements()); if (docLineString.startsWith(DOC_HEADER_PREFIX)) { break; } - doc.append(!((MarkdownDocumentationLineNode) docLine).documentElements().isEmpty() ? - getDocLineString(((MarkdownDocumentationLineNode) docLine).documentElements()) : "\n"); - } else if (docLine instanceof MarkdownCodeBlockNode) { - doc.append(getDocCodeBlockString((MarkdownCodeBlockNode) docLine)); + doc.append(!markdownDocLine.documentElements().isEmpty() ? + getDocLineString(markdownDocLine.documentElements()) : "\n"); + } else if (docLine instanceof MarkdownCodeBlockNode markdownCodeBlock) { + doc.append(getDocCodeBlockString(markdownCodeBlock)); } else { break; } @@ -1001,18 +990,16 @@ private static String getParameterDocFromMetadataList(String parameterName, if (docLines != null) { boolean lookForMoreLines = false; for (Node docLine : docLines.documentationLines()) { - if (docLine instanceof MarkdownParameterDocumentationLineNode) { - if (((MarkdownParameterDocumentationLineNode) docLine).parameterName().text() + if (docLine instanceof MarkdownParameterDocumentationLineNode markdownParamDocLine) { + if (markdownParamDocLine.parameterName().text() .equals(parameterName)) { - parameterDoc.append(getDocLineString(((MarkdownParameterDocumentationLineNode) docLine) - .documentElements())); + parameterDoc.append(getDocLineString(markdownParamDocLine.documentElements())); lookForMoreLines = true; } else { lookForMoreLines = false; } - } else if (lookForMoreLines && docLine instanceof MarkdownDocumentationLineNode) { - String docLineString = getDocLineString(((MarkdownDocumentationLineNode) docLine) - .documentElements()); + } else if (lookForMoreLines && docLine instanceof MarkdownDocumentationLineNode markdownDocLine) { + String docLineString = getDocLineString(markdownDocLine.documentElements()); if (!docLineString.isEmpty()) { parameterDoc.append(docLineString); } else { @@ -1037,9 +1024,8 @@ private static List getDescSectionsDocFromMetaDataList(Optional generateModuleDocMap(io.ballerina.projects.Project project) + public static Map generateModuleDocMap(Project project) throws IOException { Map moduleDocMap = new HashMap<>(); for (io.ballerina.projects.Module module : project.currentPackage().modules()) { @@ -661,8 +664,9 @@ private static List getResourcePaths(Path absolutePkgPath) throws IOExcept Path resourcesDirPath = absolutePkgPath.resolve("resources"); List resources = new ArrayList<>(); if (resourcesDirPath.toFile().exists()) { - resources = Files.walk(resourcesDirPath).filter(path -> !path.equals(resourcesDirPath)).collect(Collectors - .toList()); + try (Stream paths = Files.walk(resourcesDirPath)) { + resources = paths.filter(path -> !path.equals(resourcesDirPath)).toList(); + } } return resources; } diff --git a/misc/docerina/src/main/java/org/ballerinalang/docgen/docs/utils/BallerinaDocUtils.java b/misc/docerina/src/main/java/org/ballerinalang/docgen/docs/utils/BallerinaDocUtils.java index 8cc2967b0d05..cb24f51c8504 100644 --- a/misc/docerina/src/main/java/org/ballerinalang/docgen/docs/utils/BallerinaDocUtils.java +++ b/misc/docerina/src/main/java/org/ballerinalang/docgen/docs/utils/BallerinaDocUtils.java @@ -29,24 +29,28 @@ import java.security.NoSuchAlgorithmException; import java.util.regex.Matcher; import java.util.regex.Pattern; +import java.util.stream.Stream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * Util methods used for doc generation. */ -public class BallerinaDocUtils { +public final class BallerinaDocUtils { private static final boolean debugEnabled = "true".equals(System.getProperty( BallerinaDocConstants.ENABLE_DEBUG_LOGS)); private static final PrintStream out = System.out; + private BallerinaDocUtils() { + } + public static void packageToZipFile(String sourceDirPath, String zipFilePath) throws IOException { Path p = Files.createFile(Paths.get(zipFilePath)); - try (ZipOutputStream zs = new ZipOutputStream(Files.newOutputStream(p))) { - Path pp = Paths.get(sourceDirPath); - Files.walk(pp) - .filter(path -> !Files.isDirectory(path)) + Path pp = Paths.get(sourceDirPath); + try (ZipOutputStream zs = new ZipOutputStream(Files.newOutputStream(p)); + Stream sourcePaths = Files.walk(pp)) { + sourcePaths.filter(path -> !Files.isDirectory(path)) .forEach(path -> { ZipEntry zipEntry = new ZipEntry(pp.relativize(path).toString()); try { diff --git a/misc/docerina/src/main/java/org/ballerinalang/docgen/generator/model/BClass.java b/misc/docerina/src/main/java/org/ballerinalang/docgen/generator/model/BClass.java index d756053b5ce1..1f9c0d991952 100644 --- a/misc/docerina/src/main/java/org/ballerinalang/docgen/generator/model/BClass.java +++ b/misc/docerina/src/main/java/org/ballerinalang/docgen/generator/model/BClass.java @@ -19,7 +19,6 @@ import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; /** * Represent documentation for an BClass. @@ -64,7 +63,7 @@ public Optional getInitMethod(List methods) { public List getOtherMethods(List methods) { return methods.stream() .filter(function -> !function.name.equals("init")) - .collect(Collectors.toList()); + .toList(); } } diff --git a/misc/docerina/src/main/java/org/ballerinalang/docgen/generator/model/Client.java b/misc/docerina/src/main/java/org/ballerinalang/docgen/generator/model/Client.java index 6be5cc73be5d..44f757f23f59 100644 --- a/misc/docerina/src/main/java/org/ballerinalang/docgen/generator/model/Client.java +++ b/misc/docerina/src/main/java/org/ballerinalang/docgen/generator/model/Client.java @@ -18,7 +18,6 @@ import com.google.gson.annotations.Expose; import java.util.List; -import java.util.stream.Collectors; /** * Represent documentation for a Client. @@ -43,18 +42,18 @@ public Client(String name, String description, List descriptionSections, public List getOtherMethods(List methods) { return super.getOtherMethods(methods).stream() .filter(function -> !function.isRemote && !function.isResource) - .collect(Collectors.toList()); + .toList(); } private List getRemoteMethods() { return this.methods.stream() .filter(function -> function.isRemote) - .collect(Collectors.toList()); + .toList(); } private List getResourceMethods() { return this.methods.stream() .filter(function -> function.isResource) - .collect(Collectors.toList()); + .toList(); } } diff --git a/misc/docerina/src/main/java/org/ballerinalang/docgen/generator/model/Listener.java b/misc/docerina/src/main/java/org/ballerinalang/docgen/generator/model/Listener.java index 44567f491c4f..584d5e84dc19 100644 --- a/misc/docerina/src/main/java/org/ballerinalang/docgen/generator/model/Listener.java +++ b/misc/docerina/src/main/java/org/ballerinalang/docgen/generator/model/Listener.java @@ -18,7 +18,6 @@ import com.google.gson.annotations.Expose; import java.util.List; -import java.util.stream.Collectors; /** * Represent documentation for a Listener. @@ -41,7 +40,7 @@ public List getLCMethods(List methods) { .filter(function -> function.name.equals("attach") || function.name.equals("start") || function.name.equals("stop")) - .collect(Collectors.toList()); + .toList(); } @Override @@ -50,6 +49,6 @@ public List getOtherMethods(List methods) { .filter(function -> !(function.name.equals("attach") || function.name.equals("start") || function.name.equals("stop"))) - .collect(Collectors.toList()); + .toList(); } } diff --git a/misc/docerina/src/main/java/org/ballerinalang/docgen/generator/model/Type.java b/misc/docerina/src/main/java/org/ballerinalang/docgen/generator/model/Type.java index 218dcfca7f07..423105fc1b9e 100644 --- a/misc/docerina/src/main/java/org/ballerinalang/docgen/generator/model/Type.java +++ b/misc/docerina/src/main/java/org/ballerinalang/docgen/generator/model/Type.java @@ -143,8 +143,7 @@ public Type() { public static Type fromNode(Node node, SemanticModel semanticModel, Module module) { Type type = new Type(); - if (node instanceof SimpleNameReferenceNode) { - SimpleNameReferenceNode simpleNameReferenceNode = (SimpleNameReferenceNode) node; + if (node instanceof SimpleNameReferenceNode simpleNameReferenceNode) { type.name = simpleNameReferenceNode.name().text(); type.category = "reference"; Optional symbol = Optional.empty(); @@ -156,8 +155,8 @@ public static Type fromNode(Node node, SemanticModel semanticModel, Module modul } } if (symbol != null && symbol.isPresent()) { - if (symbol.get() instanceof TypeReferenceTypeSymbol && - !Type.isPublic(((TypeReferenceTypeSymbol) symbol.get()).definition())) { + if (symbol.get() instanceof TypeReferenceTypeSymbol typeReferenceTypeSymbol && + !Type.isPublic(typeReferenceTypeSymbol.definition())) { type = fromSemanticSymbol(symbol.get(), Optional.empty(), null, false, module); } else { resolveSymbolMetaData(type, symbol.get(), module); @@ -165,8 +164,7 @@ public static Type fromNode(Node node, SemanticModel semanticModel, Module modul } else { type.generateUserDefinedTypeLink = false; } - } else if (node instanceof QualifiedNameReferenceNode) { - QualifiedNameReferenceNode qualifiedNameReferenceNode = (QualifiedNameReferenceNode) node; + } else if (node instanceof QualifiedNameReferenceNode qualifiedNameReferenceNode) { type.moduleName = qualifiedNameReferenceNode.modulePrefix().text(); type.category = "reference"; type.name = qualifiedNameReferenceNode.identifier().text(); @@ -179,8 +177,8 @@ public static Type fromNode(Node node, SemanticModel semanticModel, Module modul } } if (symbol != null && symbol.isPresent()) { - if (symbol.get() instanceof TypeReferenceTypeSymbol && - !Type.isPublic(((TypeReferenceTypeSymbol) symbol.get()).definition())) { + if (symbol.get() instanceof TypeReferenceTypeSymbol typeReferenceTypeSymbol && + !Type.isPublic(typeReferenceTypeSymbol.definition())) { type = fromSemanticSymbol(symbol.get(), Optional.empty(), null, false, module); } else { resolveSymbolMetaData(type, symbol.get(), module); @@ -206,20 +204,17 @@ public static Type fromNode(Node node, SemanticModel semanticModel, Module modul if (symbol != null && symbol.isPresent()) { type = fromSemanticSymbol(symbol.get(), Optional.empty(), null, true, module); } - } else if (node instanceof BuiltinSimpleNameReferenceNode) { - BuiltinSimpleNameReferenceNode builtinSimpleNameReferenceNode = (BuiltinSimpleNameReferenceNode) node; + } else if (node instanceof BuiltinSimpleNameReferenceNode builtinSimpleNameReferenceNode) { type.name = builtinSimpleNameReferenceNode.name().text(); type.category = "builtin"; } else if (node instanceof NilTypeDescriptorNode) { type.name = node.toString(); type.category = "builtin"; - } else if (node instanceof ArrayTypeDescriptorNode) { - ArrayTypeDescriptorNode arrayTypeDescriptorNode = (ArrayTypeDescriptorNode) node; + } else if (node instanceof ArrayTypeDescriptorNode arrayTypeDescriptorNode) { type.isArrayType = true; - type.arrayDimensions = 1; + type.arrayDimensions = arrayTypeDescriptorNode.dimensions().size(); type.elementType = fromNode(arrayTypeDescriptorNode.memberTypeDesc(), semanticModel, module); - } else if (node instanceof OptionalTypeDescriptorNode) { - OptionalTypeDescriptorNode optionalTypeDescriptorNode = (OptionalTypeDescriptorNode) node; + } else if (node instanceof OptionalTypeDescriptorNode optionalTypeDescriptorNode) { type = fromNode(optionalTypeDescriptorNode.typeDescriptor(), semanticModel, module); type.isNullable = true; } else if (node instanceof UnionTypeDescriptorNode) { @@ -228,18 +223,15 @@ public static Type fromNode(Node node, SemanticModel semanticModel, Module modul } else if (node instanceof IntersectionTypeDescriptorNode) { type.isIntersectionType = true; addIntersectionMemberTypes(node, semanticModel, type.memberTypes, module); - } else if (node instanceof RecordTypeDescriptorNode) { - RecordTypeDescriptorNode recordNode = (RecordTypeDescriptorNode) node; + } else if (node instanceof RecordTypeDescriptorNode recordNode) { List fields = new ArrayList<>(); recordNode.fields().forEach(node1 -> { - if (node1 instanceof RecordFieldWithDefaultValueNode) { - RecordFieldWithDefaultValueNode recordField = (RecordFieldWithDefaultValueNode) node1; + if (node1 instanceof RecordFieldWithDefaultValueNode recordField) { Type defField = new Type(); defField.name = recordField.fieldName().text(); defField.elementType = fromNode(recordField.typeName(), semanticModel, module); fields.add(defField); - } else if (node1 instanceof RecordFieldNode) { - RecordFieldNode recordField = (RecordFieldNode) node1; + } else if (node1 instanceof RecordFieldNode recordField) { Type recField = new Type(); recField.name = recordField.fieldName().text(); recField.elementType = fromNode(recordField.typeName(), semanticModel, module); @@ -255,8 +247,7 @@ public static Type fromNode(Node node, SemanticModel semanticModel, Module modul recordNode.recordRestDescriptor().isEmpty() ? CATEGORY_INLINE_CLOSED_RECORD : CATEGORY_INLINE_RECORD; type.memberTypes = fields; - } else if (node instanceof StreamTypeDescriptorNode) { - StreamTypeDescriptorNode streamNode = (StreamTypeDescriptorNode) node; + } else if (node instanceof StreamTypeDescriptorNode streamNode) { StreamTypeParamsNode streamParams = streamNode.streamTypeParamsNode().isPresent() ? (StreamTypeParamsNode) streamNode.streamTypeParamsNode().get() : null; type.name = streamNode.streamKeywordToken().text(); @@ -267,10 +258,9 @@ public static Type fromNode(Node node, SemanticModel semanticModel, Module modul type.memberTypes.add(fromNode(streamParams.rightTypeDescNode().get(), semanticModel, module)); } } - } else if (node instanceof FunctionTypeDescriptorNode) { + } else if (node instanceof FunctionTypeDescriptorNode functionDescNode) { FunctionType functionType = new FunctionType(); functionType.isLambda = true; - FunctionTypeDescriptorNode functionDescNode = (FunctionTypeDescriptorNode) node; functionType.isIsolated = Generator.containsToken(functionDescNode.qualifierList(), SyntaxKind.ISOLATED_KEYWORD); if (functionDescNode.functionSignature().isPresent()) { @@ -286,19 +276,16 @@ public static Type fromNode(Node node, SemanticModel semanticModel, Module modul } } type = functionType; - } else if (node instanceof MapTypeDescriptorNode) { - MapTypeDescriptorNode mapTypeDesc = (MapTypeDescriptorNode) node; + } else if (node instanceof MapTypeDescriptorNode mapTypeDesc) { type.name = "map"; type.category = "map"; type.constraint = fromNode(mapTypeDesc.mapTypeParamsNode().typeNode(), semanticModel, module); - } else if (node instanceof TableTypeDescriptorNode) { - TableTypeDescriptorNode tableTypeDesc = (TableTypeDescriptorNode) node; + } else if (node instanceof TableTypeDescriptorNode tableTypeDesc) { type.name = "table"; type.category = "table"; type.constraint = fromNode(((TypeParameterNode) tableTypeDesc.rowTypeParameterNode()).typeNode(), semanticModel, module); - } else if (node instanceof ParameterizedTypeDescriptorNode) { - ParameterizedTypeDescriptorNode parameterizedTypeNode = (ParameterizedTypeDescriptorNode) node; + } else if (node instanceof ParameterizedTypeDescriptorNode parameterizedTypeNode) { SyntaxKind typeKind = node.kind(); if (typeKind == SyntaxKind.ERROR_TYPE_DESC || typeKind == SyntaxKind.XML_TYPE_DESC) { type.name = parameterizedTypeNode.keywordToken().text(); @@ -312,30 +299,24 @@ public static Type fromNode(Node node, SemanticModel semanticModel, Module modul Type.fromNode(typeParameterNode.typeNode(), semanticModel, module)).orElse(null); type.isTypeDesc = true; } - } else if (node instanceof ObjectTypeDescriptorNode) { - ObjectTypeDescriptorNode objectType = (ObjectTypeDescriptorNode) node; + } else if (node instanceof ObjectTypeDescriptorNode objectType) { type.name = objectType.toString(); type.category = "other"; type.generateUserDefinedTypeLink = false; - } else if (node instanceof SingletonTypeDescriptorNode) { - SingletonTypeDescriptorNode singletonTypeDesc = (SingletonTypeDescriptorNode) node; + } else if (node instanceof SingletonTypeDescriptorNode singletonTypeDesc) { type.name = singletonTypeDesc.simpleContExprNode().toString(); type.category = "other"; type.generateUserDefinedTypeLink = false; - } else if (node instanceof ParenthesisedTypeDescriptorNode) { - ParenthesisedTypeDescriptorNode parenthesisedNode = (ParenthesisedTypeDescriptorNode) node; + } else if (node instanceof ParenthesisedTypeDescriptorNode parenthesisedNode) { type.elementType = fromNode(parenthesisedNode.typedesc(), semanticModel, module); type.isParenthesisedType = true; - } else if (node instanceof TupleTypeDescriptorNode) { - TupleTypeDescriptorNode typeDescriptor = (TupleTypeDescriptorNode) node; + } else if (node instanceof TupleTypeDescriptorNode typeDescriptor) { type.memberTypes.addAll(typeDescriptor.memberTypeDesc().stream().map(memberType -> Type.fromNode(memberType, semanticModel, module)).toList()); type.isTuple = true; - } else if (node instanceof MemberTypeDescriptorNode) { - MemberTypeDescriptorNode member = (MemberTypeDescriptorNode) node; + } else if (node instanceof MemberTypeDescriptorNode member) { type = fromNode(member.typeDescriptor(), semanticModel, module); - } else if (node instanceof RecordRestDescriptorNode) { - RecordRestDescriptorNode recordRestDescriptorNode = (RecordRestDescriptorNode) node; + } else if (node instanceof RecordRestDescriptorNode recordRestDescriptorNode) { type.isRestParam = true; type.elementType = fromNode(recordRestDescriptorNode.typeName(), semanticModel, module); } else { @@ -350,8 +331,7 @@ public static Type fromSemanticSymbol(Symbol symbol, Optional doc TypeReferenceTypeSymbol parentTypeRefSymbol, boolean isTypeInclusion, Module module) { Type type = new Type(); - if (symbol instanceof TypeReferenceTypeSymbol) { - TypeReferenceTypeSymbol typeReferenceTypeSymbol = (TypeReferenceTypeSymbol) symbol; + if (symbol instanceof TypeReferenceTypeSymbol typeReferenceTypeSymbol) { Symbol typeDefinition = typeReferenceTypeSymbol.definition(); // The following condition is required to avoid stackoverflow error, caused by cyclic defintions, @@ -360,13 +340,13 @@ public static Type fromSemanticSymbol(Symbol symbol, Optional doc if (!typeReferenceTypeSymbol.equals(parentTypeRefSymbol) && (!Type.isPublic(typeReferenceTypeSymbol.definition()) || isTypeInclusion)) { // Further process type details - if (typeDefinition instanceof TypeDefinitionSymbol) { + if (typeDefinition instanceof TypeDefinitionSymbol typeDefinitionSymbol) { type = fromSemanticSymbol(typeReferenceTypeSymbol.typeDescriptor(), - ((TypeDefinitionSymbol) typeDefinition).documentation(), typeReferenceTypeSymbol, + typeDefinitionSymbol.documentation(), typeReferenceTypeSymbol, false, module); - } else if (typeDefinition instanceof ClassSymbol) { + } else if (typeDefinition instanceof ClassSymbol classSymbol) { type = fromSemanticSymbol(typeReferenceTypeSymbol.typeDescriptor(), - ((ClassSymbol) typeDefinition).documentation(), typeReferenceTypeSymbol, + classSymbol.documentation(), typeReferenceTypeSymbol, false, module); } } @@ -375,8 +355,7 @@ public static Type fromSemanticSymbol(Symbol symbol, Optional doc type.isPublic = true; } type.name = typeReferenceTypeSymbol.getName().isPresent() ? typeReferenceTypeSymbol.getName().get() : null; - } else if (symbol instanceof RecordTypeSymbol) { - RecordTypeSymbol recordTypeSymbol = (RecordTypeSymbol) symbol; + } else if (symbol instanceof RecordTypeSymbol recordTypeSymbol) { Type recordType = type; recordType.name = recordTypeSymbol.getName().isPresent() ? recordTypeSymbol.getName().get() : ""; recordType.description = documentation.isPresent() && documentation.get().description().isPresent() ? @@ -400,8 +379,7 @@ public static Type fromSemanticSymbol(Symbol symbol, Optional doc recordType.memberTypes.add(recField); }); recordType.category = CATEGORY_INLINE_RECORD; - } else if (symbol instanceof ObjectTypeSymbol) { - ObjectTypeSymbol objectTypeSymbol = (ObjectTypeSymbol) symbol; + } else if (symbol instanceof ObjectTypeSymbol objectTypeSymbol) { ObjectType objType = new ObjectType(); objType.name = objectTypeSymbol.getName().isPresent() ? objectTypeSymbol.getName().get() : ""; objectTypeSymbol.fieldDescriptors().forEach((name, field) -> { @@ -470,42 +448,37 @@ public static Type fromSemanticSymbol(Symbol symbol, Optional doc }); objType.functionTypes = functionTypes; type = objType; - } else if (symbol instanceof MapTypeSymbol) { - MapTypeSymbol mapTypeSymbol = (MapTypeSymbol) symbol; + } else if (symbol instanceof MapTypeSymbol mapTypeSymbol) { type.name = "map"; type.category = "map"; type.constraint = fromSemanticSymbol(mapTypeSymbol.typeParam(), documentation, parentTypeRefSymbol, isTypeInclusion, module); - } else if (symbol instanceof UnionTypeSymbol) { - UnionTypeSymbol unionSymbol = (UnionTypeSymbol) symbol; + } else if (symbol instanceof UnionTypeSymbol unionSymbol) { type.isAnonymousUnionType = true; List unionMembers = new ArrayList<>(); unionSymbol.memberTypeDescriptors().forEach(typeSymbol -> unionMembers.add(fromSemanticSymbol(typeSymbol, documentation, parentTypeRefSymbol, isTypeInclusion, module))); type.memberTypes = unionMembers; - } else if (symbol instanceof IntersectionTypeSymbol) { - IntersectionTypeSymbol intersectionSymbol = (IntersectionTypeSymbol) symbol; + } else if (symbol instanceof IntersectionTypeSymbol intersectionSymbol) { type.isIntersectionType = true; List intersectionMembers = new ArrayList<>(); intersectionSymbol.memberTypeDescriptors().forEach(typeSymbol -> intersectionMembers.add( fromSemanticSymbol(typeSymbol, documentation, parentTypeRefSymbol, isTypeInclusion, module))); type.memberTypes = intersectionMembers; - } else if (symbol instanceof ArrayTypeSymbol) { - ArrayTypeSymbol arrayTypeSymbol = (ArrayTypeSymbol) symbol; + } else if (symbol instanceof ArrayTypeSymbol arrayTypeSymbol) { type.isArrayType = true; type.arrayDimensions = 1; type.elementType = fromSemanticSymbol(arrayTypeSymbol.memberTypeDescriptor(), documentation, parentTypeRefSymbol, isTypeInclusion, module); - } else if (symbol instanceof TypeSymbol) { + } else if (symbol instanceof TypeSymbol typeSymbol) { type.category = "builtin"; - type.name = ((TypeSymbol) symbol).signature(); + type.name = typeSymbol.signature(); } return type; } public static void addUnionMemberTypes(Node node, SemanticModel semanticModel, List members, Module module) { - if (node instanceof UnionTypeDescriptorNode) { - UnionTypeDescriptorNode unionTypeNode = (UnionTypeDescriptorNode) node; + if (node instanceof UnionTypeDescriptorNode unionTypeNode) { addUnionMemberTypes(unionTypeNode.leftTypeDesc(), semanticModel, members, module); addUnionMemberTypes(unionTypeNode.rightTypeDesc(), semanticModel, members, module); return; @@ -515,8 +488,7 @@ public static void addUnionMemberTypes(Node node, SemanticModel semanticModel, L public static void addIntersectionMemberTypes(Node node, SemanticModel semanticModel, List members, Module module) { - if (node instanceof IntersectionTypeDescriptorNode) { - IntersectionTypeDescriptorNode intersectionTypeNode = (IntersectionTypeDescriptorNode) node; + if (node instanceof IntersectionTypeDescriptorNode intersectionTypeNode) { addIntersectionMemberTypes(intersectionTypeNode.leftTypeDesc(), semanticModel, members, module); addIntersectionMemberTypes(intersectionTypeNode.rightTypeDesc(), semanticModel, members, module); return; @@ -540,8 +512,7 @@ public static void resolveSymbolMetaData(Type type, Symbol symbol, Module module if (!type.orgName.equals("UNK_ORG") && (!Objects.equals(type.moduleName, module.id) || !Objects.equals(type.orgName, module.orgName))) { type.category = "libs"; - } else if (symbol instanceof TypeReferenceTypeSymbol) { - TypeReferenceTypeSymbol typeSymbol = (TypeReferenceTypeSymbol) symbol; + } else if (symbol instanceof TypeReferenceTypeSymbol typeSymbol) { if (typeSymbol.definition().kind().equals(SymbolKind.ENUM)) { type.category = "enums"; } else if (typeSymbol.typeDescriptor() != null) { @@ -549,13 +520,11 @@ public static void resolveSymbolMetaData(Type type, Symbol symbol, Module module } } else if (symbol instanceof ConstantSymbol) { type.category = "constants"; - } else if (symbol instanceof VariableSymbol) { - VariableSymbol variableSymbol = (VariableSymbol) symbol; + } else if (symbol instanceof VariableSymbol variableSymbol) { if (variableSymbol.typeDescriptor() != null) { type.category = getTypeCategory(variableSymbol.typeDescriptor()); } - } else if (symbol instanceof TypeDefinitionSymbol) { - TypeDefinitionSymbol typeDefSymbol = (TypeDefinitionSymbol) symbol; + } else if (symbol instanceof TypeDefinitionSymbol typeDefSymbol) { if (typeDefSymbol.typeDescriptor() != null) { type.category = getTypeCategory(typeDefSymbol.typeDescriptor()); } diff --git a/misc/docerina/src/test/java/org/ballerinalang/docgen/tests/GenDocsForBalaTest.java b/misc/docerina/src/test/java/org/ballerinalang/docgen/tests/GenDocsForBalaTest.java index 7a3c85079be1..2e5677b7e2fd 100644 --- a/misc/docerina/src/test/java/org/ballerinalang/docgen/tests/GenDocsForBalaTest.java +++ b/misc/docerina/src/test/java/org/ballerinalang/docgen/tests/GenDocsForBalaTest.java @@ -34,6 +34,7 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.Comparator; +import java.util.stream.Stream; /** * Test generating API docs for a bala. @@ -122,10 +123,11 @@ public void generatingDocsForBalaWithAnnotationTest2() throws IOException { @AfterMethod public void cleanUp() throws IOException { if (Files.exists(this.docsPath)) { - Files.walk(this.docsPath) - .sorted(Comparator.reverseOrder()) + try (Stream paths = Files.walk(this.docsPath)) { + paths.sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(File::delete); + } } } } diff --git a/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java b/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java index 978d39e56b9c..923a5bbf463d 100644 --- a/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java +++ b/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java @@ -47,10 +47,13 @@ /** * Util class for compilation and format execution for formatting CLI tool. */ -class FormatUtil { +final class FormatUtil { static final String CMD_NAME = "format"; private static final PrintStream outStream = System.err; + private FormatUtil() { + } + /** * Execute formatter. * diff --git a/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/Messages.java b/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/Messages.java index f51ea4c00247..bcb84ae7b194 100644 --- a/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/Messages.java +++ b/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/Messages.java @@ -20,7 +20,8 @@ /** * Class to hold the messages generated by the Formatting CLI tool. */ -public class Messages { +public final class Messages { + private static final String ARGUMENT_ERROR = "too many arguments." + System.lineSeparator() + "usage: only one argument, either a ballerina file name or a module " + "name, can be applied at a time with or without the option." + System.lineSeparator() @@ -59,6 +60,9 @@ public class Messages { private static final String MODIFIED_FILES = "modified files:"; + private Messages() { + } + static String getArgumentError() { return ARGUMENT_ERROR; } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/Formatter.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/Formatter.java index 11bc29a40e50..95b693774b72 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/Formatter.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/Formatter.java @@ -58,7 +58,10 @@ /** * Class that exposes the formatting APIs. */ -public class Formatter { +public final class Formatter { + + private Formatter() { + } /** * Formats the provided source string and returns back the formatted source string. @@ -146,104 +149,42 @@ public static SyntaxTree format(SyntaxTree syntaxTree, FormattingOptions options public static String formatExpression(String text) throws FormatterException { FormattingTreeModifier treeModifier = new FormattingTreeModifier(FormattingOptions.builder().build(), null); ExpressionNode parsedNode = NodeParser.parseExpression(text); - ExpressionNode formattedNode; - switch (parsedNode.kind()) { - case ANNOT_ACCESS: - formattedNode = treeModifier.transform((AnnotAccessExpressionNode) parsedNode); - break; - case BINARY_EXPRESSION: - formattedNode = treeModifier.transform((BinaryExpressionNode) parsedNode); - break; - case BRACED_EXPRESSION: - formattedNode = treeModifier.transform((BracedExpressionNode) parsedNode); - break; - case CHECK_EXPRESSION: - formattedNode = treeModifier.transform((CheckExpressionNode) parsedNode); - break; - case CONDITIONAL_EXPRESSION: - formattedNode = treeModifier.transform((ConditionalExpressionNode) parsedNode); - break; - case ERROR_CONSTRUCTOR: - formattedNode = treeModifier.transform((ErrorConstructorExpressionNode) parsedNode); - break; - case EXPLICIT_ANONYMOUS_FUNCTION_EXPRESSION: - formattedNode = treeModifier.transform((ExplicitAnonymousFunctionExpressionNode) parsedNode); - break; - case EXPLICIT_NEW_EXPRESSION: - formattedNode = treeModifier.transform((ExplicitNewExpressionNode) parsedNode); - break; - case FIELD_ACCESS: - formattedNode = treeModifier.transform((FieldAccessExpressionNode) parsedNode); - break; - case FUNCTION_CALL: - formattedNode = treeModifier.transform((FunctionCallExpressionNode) parsedNode); - break; - case IMPLICIT_ANONYMOUS_FUNCTION_EXPRESSION: - formattedNode = treeModifier.transform((ImplicitAnonymousFunctionExpressionNode) parsedNode); - break; - case IMPLICIT_NEW_EXPRESSION: - formattedNode = treeModifier.transform((ImplicitNewExpressionNode) parsedNode); - break; - case INDEXED_EXPRESSION: - formattedNode = treeModifier.transform((IndexedExpressionNode) parsedNode); - break; - case LET_EXPRESSION: - formattedNode = treeModifier.transform((LetExpressionNode) parsedNode); - break; - case LIST_CONSTRUCTOR: - formattedNode = treeModifier.transform((ListConstructorExpressionNode) parsedNode); - break; - case MAPPING_CONSTRUCTOR: - formattedNode = treeModifier.transform((MappingConstructorExpressionNode) parsedNode); - break; - case METHOD_CALL: - formattedNode = treeModifier.transform((MethodCallExpressionNode) parsedNode); - break; - case OBJECT_CONSTRUCTOR: - formattedNode = treeModifier.transform((ObjectConstructorExpressionNode) parsedNode); - break; - case OPTIONAL_FIELD_ACCESS: - formattedNode = treeModifier.transform((OptionalFieldAccessExpressionNode) parsedNode); - break; - case QUERY_EXPRESSION: - formattedNode = treeModifier.transform((QueryExpressionNode) parsedNode); - break; - case REQUIRED_EXPRESSION: - formattedNode = treeModifier.transform((RequiredExpressionNode) parsedNode); - break; - case TABLE_CONSTRUCTOR: - formattedNode = treeModifier.transform((TableConstructorExpressionNode) parsedNode); - break; - case RAW_TEMPLATE_EXPRESSION: - formattedNode = treeModifier.transform((TemplateExpressionNode) parsedNode); - break; - case TRANSACTIONAL_EXPRESSION: - formattedNode = treeModifier.transform((TransactionalExpressionNode) parsedNode); - break; - case TRAP_EXPRESSION: - formattedNode = treeModifier.transform((TrapExpressionNode) parsedNode); - break; - case TYPE_CAST_EXPRESSION: - formattedNode = treeModifier.transform((TypeCastExpressionNode) parsedNode); - break; - case TYPE_TEST_EXPRESSION: - formattedNode = treeModifier.transform((TypeTestExpressionNode) parsedNode); - break; - case TYPEOF_EXPRESSION: - formattedNode = treeModifier.transform((TypeofExpressionNode) parsedNode); - break; - case UNARY_EXPRESSION: - formattedNode = treeModifier.transform((UnaryExpressionNode) parsedNode); - break; - case XML_FILTER_EXPRESSION: - formattedNode = treeModifier.transform((XMLFilterExpressionNode) parsedNode); - break; - case XML_STEP_EXPRESSION: - formattedNode = treeModifier.transform((XMLStepExpressionNode) parsedNode); - break; - default: - throw new FormatterException("Unsupported expression type: " + parsedNode.kind()); - } + ExpressionNode formattedNode = switch (parsedNode.kind()) { + case ANNOT_ACCESS -> treeModifier.transform((AnnotAccessExpressionNode) parsedNode); + case BINARY_EXPRESSION -> treeModifier.transform((BinaryExpressionNode) parsedNode); + case BRACED_EXPRESSION -> treeModifier.transform((BracedExpressionNode) parsedNode); + case CHECK_EXPRESSION -> treeModifier.transform((CheckExpressionNode) parsedNode); + case CONDITIONAL_EXPRESSION -> treeModifier.transform((ConditionalExpressionNode) parsedNode); + case ERROR_CONSTRUCTOR -> treeModifier.transform((ErrorConstructorExpressionNode) parsedNode); + case EXPLICIT_ANONYMOUS_FUNCTION_EXPRESSION -> + treeModifier.transform((ExplicitAnonymousFunctionExpressionNode) parsedNode); + case EXPLICIT_NEW_EXPRESSION -> treeModifier.transform((ExplicitNewExpressionNode) parsedNode); + case FIELD_ACCESS -> treeModifier.transform((FieldAccessExpressionNode) parsedNode); + case FUNCTION_CALL -> treeModifier.transform((FunctionCallExpressionNode) parsedNode); + case IMPLICIT_ANONYMOUS_FUNCTION_EXPRESSION -> + treeModifier.transform((ImplicitAnonymousFunctionExpressionNode) parsedNode); + case IMPLICIT_NEW_EXPRESSION -> treeModifier.transform((ImplicitNewExpressionNode) parsedNode); + case INDEXED_EXPRESSION -> treeModifier.transform((IndexedExpressionNode) parsedNode); + case LET_EXPRESSION -> treeModifier.transform((LetExpressionNode) parsedNode); + case LIST_CONSTRUCTOR -> treeModifier.transform((ListConstructorExpressionNode) parsedNode); + case MAPPING_CONSTRUCTOR -> treeModifier.transform((MappingConstructorExpressionNode) parsedNode); + case METHOD_CALL -> treeModifier.transform((MethodCallExpressionNode) parsedNode); + case OBJECT_CONSTRUCTOR -> treeModifier.transform((ObjectConstructorExpressionNode) parsedNode); + case OPTIONAL_FIELD_ACCESS -> treeModifier.transform((OptionalFieldAccessExpressionNode) parsedNode); + case QUERY_EXPRESSION -> treeModifier.transform((QueryExpressionNode) parsedNode); + case REQUIRED_EXPRESSION -> treeModifier.transform((RequiredExpressionNode) parsedNode); + case TABLE_CONSTRUCTOR -> treeModifier.transform((TableConstructorExpressionNode) parsedNode); + case RAW_TEMPLATE_EXPRESSION -> treeModifier.transform((TemplateExpressionNode) parsedNode); + case TRANSACTIONAL_EXPRESSION -> treeModifier.transform((TransactionalExpressionNode) parsedNode); + case TRAP_EXPRESSION -> treeModifier.transform((TrapExpressionNode) parsedNode); + case TYPE_CAST_EXPRESSION -> treeModifier.transform((TypeCastExpressionNode) parsedNode); + case TYPE_TEST_EXPRESSION -> treeModifier.transform((TypeTestExpressionNode) parsedNode); + case TYPEOF_EXPRESSION -> treeModifier.transform((TypeofExpressionNode) parsedNode); + case UNARY_EXPRESSION -> treeModifier.transform((UnaryExpressionNode) parsedNode); + case XML_FILTER_EXPRESSION -> treeModifier.transform((XMLFilterExpressionNode) parsedNode); + case XML_STEP_EXPRESSION -> treeModifier.transform((XMLStepExpressionNode) parsedNode); + default -> throw new FormatterException("Unsupported expression type: " + parsedNode.kind()); + }; return formattedNode.toSourceCode().strip(); } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java index d0382d6f5ada..e6deaabd2193 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java @@ -69,7 +69,8 @@ /** * Class that contains the util functions used by the formatting tree modifier. */ -public class FormatterUtils { +public final class FormatterUtils { + static final String NEWLINE_SYMBOL = System.getProperty("line.separator"); private static final String FORMAT_FILE_FIELD = "configPath"; private static final String FORMAT_OPTION_FILE_EXT = ".toml"; diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java index 2312f87beb2b..7455db572152 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java @@ -262,9 +262,9 @@ import java.util.Optional; import java.util.function.Predicate; +import static org.ballerinalang.formatter.core.FormatterUtils.getConstDefWidth; import static org.ballerinalang.formatter.core.FormatterUtils.isInlineRange; import static org.ballerinalang.formatter.core.FormatterUtils.openBraceTrailingNLs; -import static org.ballerinalang.formatter.core.FormatterUtils.getConstDefWidth; import static org.ballerinalang.formatter.core.FormatterUtils.sortImportDeclarations; import static org.ballerinalang.formatter.core.FormatterUtils.swapLeadingMinutiae; @@ -3973,21 +3973,15 @@ private boolean isMultilineModuleMember(T node) { return false; } - switch (node.kind()) { - case FUNCTION_DEFINITION: - case CLASS_DEFINITION: - case SERVICE_DECLARATION: - case TYPE_DEFINITION: - case ENUM_DECLARATION: - case ANNOTATION_DECLARATION: - return true; - case MODULE_VAR_DECL: - case MODULE_XML_NAMESPACE_DECLARATION: - case CONST_DECLARATION: - case LISTENER_DECLARATION: - default: - return false; - } + return switch (node.kind()) { + case FUNCTION_DEFINITION, + CLASS_DEFINITION, + SERVICE_DECLARATION, + TYPE_DEFINITION, + ENUM_DECLARATION, + ANNOTATION_DECLARATION -> true; + default -> false; + }; } private boolean isClassOrServiceMultiLineMember(Node node) { @@ -3995,13 +3989,10 @@ private boolean isClassOrServiceMultiLineMember(Node node) { return false; } - switch (node.kind()) { - case OBJECT_METHOD_DEFINITION: - case RESOURCE_ACCESSOR_DEFINITION: - return true; - default: - return false; - } + return switch (node.kind()) { + case OBJECT_METHOD_DEFINITION, RESOURCE_ACCESSOR_DEFINITION -> true; + default -> false; + }; } /** @@ -4849,14 +4840,10 @@ private boolean hasNonWSMinutiae(MinutiaeList minutiaeList) { } private boolean isClosingTypeToken(Token token) { - switch (token.kind()) { - case CLOSE_BRACE_TOKEN: - case CLOSE_BRACE_PIPE_TOKEN: - case CLOSE_BRACKET_TOKEN: - return true; - default: - return false; - } + return switch (token.kind()) { + case CLOSE_BRACE_TOKEN, CLOSE_BRACE_PIPE_TOKEN, CLOSE_BRACKET_TOKEN -> true; + default -> false; + }; } /** diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java index ccf9191dd8e7..c984a3497636 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java @@ -179,6 +179,7 @@ public FormattingOptions build() { spacingFormattingOptions, forceFormattingOptions, importFormattingOptions, queryFormattingOptions); } + @SuppressWarnings("unchecked") public FormattingOptions build(Path root, Object formatSection) throws FormatterException { Optional path = getFormattingFilePath(formatSection, root.toString()); if (path.isEmpty()) { @@ -187,7 +188,7 @@ public FormattingOptions build(Path root, Object formatSection) throws Formatter Map configurations = getFormattingConfigurations(root, path.get()); for (Map.Entry entry : configurations.entrySet()) { Object value = entry.getValue(); - if (!(value instanceof Map)) { + if (!(value instanceof Map)) { continue; } Map configs = (Map) value; diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/FormatterTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/FormatterTest.java index f386e1621e59..0a7a8bc25eda 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/FormatterTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/FormatterTest.java @@ -37,6 +37,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.stream.Stream; /** * The abstract class that is extended by all formatting test classes. @@ -190,9 +191,9 @@ protected Object[][] getConfigsList() { return this.testSubset(); } List skippedTests = this.skipList(); - try { - return Files.walk(this.resourceDirectory.resolve(this.getTestResourceDir()).resolve(ASSERT_DIR)) - .filter(path -> { + try (Stream assertPaths = + Files.walk(this.resourceDirectory.resolve(this.getTestResourceDir()).resolve(ASSERT_DIR))) { + return assertPaths.filter(path -> { File file = path.toFile(); return file.isFile() && file.getName().endsWith(".bal") && !skippedTests.contains(file.getName()); @@ -209,10 +210,9 @@ Object[][] getParserTestConfigs() { return this.testSubset(); } List skippedTests = this.skipList(); - try { - return Files.walk(this.buildDirectory.resolve("resources").resolve("test") - .resolve(this.getTestResourceDir())) - .filter(path -> { + try (Stream testPaths = Files.walk(this.buildDirectory.resolve("resources").resolve("test") + .resolve(this.getTestResourceDir()))) { + return testPaths.filter(path -> { File file = path.toFile(); return file.isFile() && file.getName().endsWith(".bal") && !skippedTests.contains(file.getName()); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/ParserTestFormatter.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/ParserTestFormatter.java index 304e7d8848fd..919525853924 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/ParserTestFormatter.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/ParserTestFormatter.java @@ -20,10 +20,12 @@ import java.io.IOException; import java.nio.file.Files; +import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.Optional; +import java.util.stream.Stream; /** * Test the formatting of parser test cases. @@ -32,6 +34,7 @@ */ public class ParserTestFormatter extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String fileName, String path) throws IOException { super.testParserResources(path); @@ -205,9 +208,8 @@ public String getTestResourceDir() { } private Optional getFilePath(String fileName, String directoryPath) { - try { - return Optional.ofNullable(Files.walk(Paths.get(directoryPath)) - .filter(f -> f.getFileName().toString().equals(fileName)) + try (Stream paths = Files.walk(Paths.get(directoryPath))) { + return Optional.ofNullable(paths.filter(f -> f.getFileName().toString().equals(fileName)) .toList().get(0).toString()); } catch (IOException e) { return Optional.empty(); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/actions/CheckingActionsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/actions/CheckingActionsTest.java index 19f81d7b6f6a..ea8c6da44727 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/actions/CheckingActionsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/actions/CheckingActionsTest.java @@ -29,6 +29,7 @@ */ public class CheckingActionsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/actions/FlushActionsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/actions/FlushActionsTest.java index e4a219cc2498..02e40b72fd1a 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/actions/FlushActionsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/actions/FlushActionsTest.java @@ -29,6 +29,7 @@ */ public class FlushActionsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/actions/QueryActionsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/actions/QueryActionsTest.java index 486569a6a022..76ee08985ed4 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/actions/QueryActionsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/actions/QueryActionsTest.java @@ -29,6 +29,7 @@ */ public class QueryActionsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/actions/SendReceiveActionsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/actions/SendReceiveActionsTest.java index eb6afd45844c..2991d36cae2a 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/actions/SendReceiveActionsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/actions/SendReceiveActionsTest.java @@ -29,6 +29,7 @@ */ public class SendReceiveActionsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/actions/StartActionsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/actions/StartActionsTest.java index 2a92ff18283a..9c0b21fee342 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/actions/StartActionsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/actions/StartActionsTest.java @@ -29,6 +29,7 @@ */ public class StartActionsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/actions/TrapActionsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/actions/TrapActionsTest.java index 12ad48cbbe24..eb830005a91c 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/actions/TrapActionsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/actions/TrapActionsTest.java @@ -29,6 +29,7 @@ */ public class TrapActionsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/actions/TypeCastActionsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/actions/TypeCastActionsTest.java index 7abbb8b7cf4e..24cce567ef22 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/actions/TypeCastActionsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/actions/TypeCastActionsTest.java @@ -29,6 +29,7 @@ */ public class TypeCastActionsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/actions/WaitActionsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/actions/WaitActionsTest.java index 3a77c27383a0..682383298909 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/actions/WaitActionsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/actions/WaitActionsTest.java @@ -29,6 +29,7 @@ */ public class WaitActionsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/LocalConfigurationTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/LocalConfigurationTest.java index b0ef751df782..f852990810ce 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/LocalConfigurationTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/LocalConfigurationTest.java @@ -30,6 +30,7 @@ * @since 2201.9.0 */ public class LocalConfigurationTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { try { diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/RemoteConfigurationTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/RemoteConfigurationTest.java index 5becea390c12..9ec220de229b 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/RemoteConfigurationTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/RemoteConfigurationTest.java @@ -30,6 +30,7 @@ */ public class RemoteConfigurationTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { try { diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/declarations/ClassDefinitionDeclarationsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/declarations/ClassDefinitionDeclarationsTest.java index faf03aca6444..fd9e89c47fa2 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/declarations/ClassDefinitionDeclarationsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/declarations/ClassDefinitionDeclarationsTest.java @@ -33,6 +33,7 @@ public class ClassDefinitionDeclarationsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/declarations/FunctionDefinitionDeclarationsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/declarations/FunctionDefinitionDeclarationsTest.java index de2cba34570a..d706189872e2 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/declarations/FunctionDefinitionDeclarationsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/declarations/FunctionDefinitionDeclarationsTest.java @@ -29,6 +29,7 @@ */ public class FunctionDefinitionDeclarationsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/declarations/ImportDeclarationsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/declarations/ImportDeclarationsTest.java index a53dbffa8290..e3472ae755e0 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/declarations/ImportDeclarationsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/declarations/ImportDeclarationsTest.java @@ -32,11 +32,13 @@ */ public class ImportDeclarationsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider-custom") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); } + @Override @Test(dataProvider = "test-file-provider-custom") public void testWithCustomOptions(String source, String sourcePath, FormattingOptions formattingOptions) throws IOException { diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/declarations/ModuleEnumDeclarationsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/declarations/ModuleEnumDeclarationsTest.java index ffefb50ba14b..9708deb14ec0 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/declarations/ModuleEnumDeclarationsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/declarations/ModuleEnumDeclarationsTest.java @@ -29,6 +29,7 @@ */ public class ModuleEnumDeclarationsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/declarations/ModuleTypeDefinitionDeclarationsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/declarations/ModuleTypeDefinitionDeclarationsTest.java index 344f31a672e6..ddf9bf1272c3 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/declarations/ModuleTypeDefinitionDeclarationsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/declarations/ModuleTypeDefinitionDeclarationsTest.java @@ -29,6 +29,7 @@ */ public class ModuleTypeDefinitionDeclarationsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/declarations/ModuleVariableDeclarationsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/declarations/ModuleVariableDeclarationsTest.java index 52f628a30e02..47a9dee2f56c 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/declarations/ModuleVariableDeclarationsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/declarations/ModuleVariableDeclarationsTest.java @@ -29,6 +29,7 @@ */ public class ModuleVariableDeclarationsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/declarations/ServiceListenerDeclarationsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/declarations/ServiceListenerDeclarationsTest.java index f62a4f8fd961..52c797094b47 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/declarations/ServiceListenerDeclarationsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/declarations/ServiceListenerDeclarationsTest.java @@ -29,6 +29,7 @@ */ public class ServiceListenerDeclarationsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/AdditiveExpressionsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/AdditiveExpressionsTest.java index 6abd6cf90d39..3deb2e35d8a6 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/AdditiveExpressionsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/AdditiveExpressionsTest.java @@ -29,6 +29,7 @@ */ public class AdditiveExpressionsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/BinaryBitwiseExpressionsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/BinaryBitwiseExpressionsTest.java index c2f68c610059..cf4717578dea 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/BinaryBitwiseExpressionsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/BinaryBitwiseExpressionsTest.java @@ -29,6 +29,7 @@ */ public class BinaryBitwiseExpressionsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/ConditionalExpressionsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/ConditionalExpressionsTest.java index 6b02cc0099c6..035911e74424 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/ConditionalExpressionsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/ConditionalExpressionsTest.java @@ -29,6 +29,7 @@ */ public class ConditionalExpressionsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/ConstantExpressionsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/ConstantExpressionsTest.java index 0e4f16d1fd03..5ce1c98df79c 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/ConstantExpressionsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/ConstantExpressionsTest.java @@ -29,6 +29,7 @@ */ public class ConstantExpressionsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/EqualityExpressionsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/EqualityExpressionsTest.java index 34b0819e2239..7076d5c90e11 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/EqualityExpressionsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/EqualityExpressionsTest.java @@ -29,6 +29,7 @@ */ public class EqualityExpressionsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/LetExpressionsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/LetExpressionsTest.java index 435e7503c9a6..e264f15c37ec 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/LetExpressionsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/LetExpressionsTest.java @@ -29,6 +29,7 @@ */ public class LetExpressionsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/LiteralExpressionsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/LiteralExpressionsTest.java index 81547e689c57..814aa5e18512 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/LiteralExpressionsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/LiteralExpressionsTest.java @@ -29,6 +29,7 @@ */ public class LiteralExpressionsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/LogicalExpressionsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/LogicalExpressionsTest.java index 52006b4ee7b8..29e9fa824d25 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/LogicalExpressionsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/LogicalExpressionsTest.java @@ -29,6 +29,7 @@ */ public class LogicalExpressionsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/MultiplicativeExpressionsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/MultiplicativeExpressionsTest.java index 3d74f1ffd13f..6c75765a769e 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/MultiplicativeExpressionsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/MultiplicativeExpressionsTest.java @@ -29,6 +29,7 @@ */ public class MultiplicativeExpressionsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/NewExpressionsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/NewExpressionsTest.java index 0296661308d3..f1ed12e42427 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/NewExpressionsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/NewExpressionsTest.java @@ -29,6 +29,7 @@ */ public class NewExpressionsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/ObjectConstructorExpressionsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/ObjectConstructorExpressionsTest.java index dd359dac9b2b..4ccbbdc6f992 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/ObjectConstructorExpressionsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/ObjectConstructorExpressionsTest.java @@ -29,6 +29,7 @@ */ public class ObjectConstructorExpressionsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/OptionalFieldAccessExpressionsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/OptionalFieldAccessExpressionsTest.java index 1e2ed7d4c0f0..fc3f7e8b9e59 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/OptionalFieldAccessExpressionsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/OptionalFieldAccessExpressionsTest.java @@ -29,6 +29,7 @@ */ public class OptionalFieldAccessExpressionsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/QueryExpressionsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/QueryExpressionsTest.java index 0f0135d119fc..914918b0e471 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/QueryExpressionsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/QueryExpressionsTest.java @@ -29,6 +29,7 @@ */ public class QueryExpressionsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/RangeExpressionsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/RangeExpressionsTest.java index 9ebbcb7bfcfe..36555287bb70 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/RangeExpressionsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/RangeExpressionsTest.java @@ -29,6 +29,7 @@ */ public class RangeExpressionsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/RawTemplateExpressionsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/RawTemplateExpressionsTest.java index f0ed7ae87f24..134ccd9933ea 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/RawTemplateExpressionsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/RawTemplateExpressionsTest.java @@ -29,6 +29,7 @@ */ public class RawTemplateExpressionsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/RelationalExpressionsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/RelationalExpressionsTest.java index 1e14dcfed5cb..bb2663728cfb 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/RelationalExpressionsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/RelationalExpressionsTest.java @@ -29,6 +29,7 @@ */ public class RelationalExpressionsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/ShiftExpressionsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/ShiftExpressionsTest.java index 7e45a80eefd7..2c1eca3d4b7a 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/ShiftExpressionsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/ShiftExpressionsTest.java @@ -29,6 +29,7 @@ */ public class ShiftExpressionsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/StringTemplateExpressionsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/StringTemplateExpressionsTest.java index e108811cf471..054c6736777f 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/StringTemplateExpressionsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/StringTemplateExpressionsTest.java @@ -29,6 +29,7 @@ */ public class StringTemplateExpressionsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/TypeTestExpressionsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/TypeTestExpressionsTest.java index a4d9899e2c6c..f19fdd90d47c 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/TypeTestExpressionsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/TypeTestExpressionsTest.java @@ -29,6 +29,7 @@ */ public class TypeTestExpressionsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/UnaryExpressionsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/UnaryExpressionsTest.java index 8f1616bcebd1..bbb088950528 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/UnaryExpressionsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/UnaryExpressionsTest.java @@ -29,6 +29,7 @@ */ public class UnaryExpressionsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/XMLTemplateExpressionsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/XMLTemplateExpressionsTest.java index eab7b69f8223..31cb0172a049 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/XMLTemplateExpressionsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/expressions/XMLTemplateExpressionsTest.java @@ -29,6 +29,7 @@ */ public class XMLTemplateExpressionsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/misc/BlocksTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/misc/BlocksTest.java index 5f3d09a1b007..5dfe17b85045 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/misc/BlocksTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/misc/BlocksTest.java @@ -29,6 +29,7 @@ */ public class BlocksTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/misc/LineBreaksTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/misc/LineBreaksTest.java index 62c06fcaa895..d4cbcc8e7d30 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/misc/LineBreaksTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/misc/LineBreaksTest.java @@ -29,6 +29,7 @@ */ public class LineBreaksTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/misc/LineWrappingTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/misc/LineWrappingTest.java index 930e2a1d07ff..ab2c39c2284d 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/misc/LineWrappingTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/misc/LineWrappingTest.java @@ -29,6 +29,7 @@ */ public class LineWrappingTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.testWithOptions(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/misc/MetadataTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/misc/MetadataTest.java index eef241774014..d5d5b53d918b 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/misc/MetadataTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/misc/MetadataTest.java @@ -29,6 +29,7 @@ */ public class MetadataTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/AssignmentStatementsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/AssignmentStatementsTest.java index c6725dcd8133..ae6515c6d129 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/AssignmentStatementsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/AssignmentStatementsTest.java @@ -29,6 +29,7 @@ */ public class AssignmentStatementsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/BlockStatementsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/BlockStatementsTest.java index 702a77ae9222..ffcf97be7802 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/BlockStatementsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/BlockStatementsTest.java @@ -29,6 +29,7 @@ */ public class BlockStatementsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/BreakStatementsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/BreakStatementsTest.java index 8d9e85504f0c..86a38734fa11 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/BreakStatementsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/BreakStatementsTest.java @@ -29,6 +29,7 @@ */ public class BreakStatementsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/CallStatementsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/CallStatementsTest.java index acf5ef53b697..ad783e649e2a 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/CallStatementsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/CallStatementsTest.java @@ -29,6 +29,7 @@ */ public class CallStatementsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/CompoundAssignmentStatementsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/CompoundAssignmentStatementsTest.java index 85db29ef8863..45789e616768 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/CompoundAssignmentStatementsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/CompoundAssignmentStatementsTest.java @@ -29,6 +29,7 @@ */ public class CompoundAssignmentStatementsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/ContinueStatementsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/ContinueStatementsTest.java index 75b0dda61309..36d6450d196d 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/ContinueStatementsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/ContinueStatementsTest.java @@ -29,6 +29,7 @@ */ public class ContinueStatementsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/DoStatementsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/DoStatementsTest.java index 4b5888a57798..795d4d4b076a 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/DoStatementsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/DoStatementsTest.java @@ -29,6 +29,7 @@ */ public class DoStatementsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/ForEachStatementsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/ForEachStatementsTest.java index bf93d5e19280..44cf0bb60b10 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/ForEachStatementsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/ForEachStatementsTest.java @@ -29,6 +29,7 @@ */ public class ForEachStatementsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/ForkStatementsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/ForkStatementsTest.java index f792b842df0a..bce1dc256191 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/ForkStatementsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/ForkStatementsTest.java @@ -29,6 +29,7 @@ */ public class ForkStatementsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/IfElseStatementsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/IfElseStatementsTest.java index 4e709f6b959f..114e96270afd 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/IfElseStatementsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/IfElseStatementsTest.java @@ -31,6 +31,7 @@ */ public class IfElseStatementsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); @@ -47,6 +48,7 @@ public String getTestResourceDir() { return Paths.get("statements", "if-else").toString(); } + @Override public List skipList() { ArrayList skip = new ArrayList<>(); skip.add("if_else_statement_6.bal"); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/LocalTypeDefinitionStatementsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/LocalTypeDefinitionStatementsTest.java index de4ab78f2e7b..adb42e0910ad 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/LocalTypeDefinitionStatementsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/LocalTypeDefinitionStatementsTest.java @@ -29,6 +29,7 @@ */ public class LocalTypeDefinitionStatementsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/LockStatementsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/LockStatementsTest.java index 41f36f327de4..781596b8b0fb 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/LockStatementsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/LockStatementsTest.java @@ -29,6 +29,7 @@ */ public class LockStatementsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/MatchStatementsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/MatchStatementsTest.java index 349ca5eb685e..c28998cd9320 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/MatchStatementsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/MatchStatementsTest.java @@ -29,6 +29,7 @@ */ public class MatchStatementsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/PanicStatementsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/PanicStatementsTest.java index 9775b4acb44c..46a64ed9c1d9 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/PanicStatementsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/PanicStatementsTest.java @@ -29,6 +29,7 @@ */ public class PanicStatementsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/ReturnStatementsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/ReturnStatementsTest.java index e06ae0042374..df5beb41edd4 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/ReturnStatementsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/ReturnStatementsTest.java @@ -29,6 +29,7 @@ */ public class ReturnStatementsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/WhileStatementsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/WhileStatementsTest.java index b6bbe384b637..74d3fa7c4849 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/WhileStatementsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/WhileStatementsTest.java @@ -29,6 +29,7 @@ */ public class WhileStatementsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/XMLNSDeclarationStatementsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/XMLNSDeclarationStatementsTest.java index a91427878ae4..4c1f420a41e3 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/XMLNSDeclarationStatementsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/statements/XMLNSDeclarationStatementsTest.java @@ -29,6 +29,7 @@ */ public class XMLNSDeclarationStatementsTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/types/BehaviouralTypesTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/types/BehaviouralTypesTest.java index 2f67311d2348..ac877804a145 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/types/BehaviouralTypesTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/types/BehaviouralTypesTest.java @@ -29,6 +29,7 @@ */ public class BehaviouralTypesTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/types/OtherTypesTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/types/OtherTypesTest.java index 02d76f09b031..a5876f438890 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/types/OtherTypesTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/types/OtherTypesTest.java @@ -29,6 +29,7 @@ */ public class OtherTypesTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/types/SequenceTypesTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/types/SequenceTypesTest.java index 86213e2fbd1d..e36b6ba021b3 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/types/SequenceTypesTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/types/SequenceTypesTest.java @@ -29,6 +29,7 @@ */ public class SequenceTypesTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String config, String configPath) throws IOException { super.test(config, configPath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/types/SimpleTypesTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/types/SimpleTypesTest.java index 24ea50feb139..5446eab2b0d6 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/types/SimpleTypesTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/types/SimpleTypesTest.java @@ -29,6 +29,7 @@ */ public class SimpleTypesTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/types/StructuredTypesTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/types/StructuredTypesTest.java index de0bc066ccea..913bfd37bf34 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/types/StructuredTypesTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/types/StructuredTypesTest.java @@ -29,6 +29,7 @@ */ public class StructuredTypesTest extends FormatterTest { + @Override @Test(dataProvider = "test-file-provider") public void test(String source, String sourcePath) throws IOException { super.test(source, sourcePath); diff --git a/misc/identifier-util/src/main/java/io/ballerina/identifier/Utils.java b/misc/identifier-util/src/main/java/io/ballerina/identifier/Utils.java index 1457dc1248e7..0e87690aa193 100644 --- a/misc/identifier-util/src/main/java/io/ballerina/identifier/Utils.java +++ b/misc/identifier-util/src/main/java/io/ballerina/identifier/Utils.java @@ -28,7 +28,7 @@ * * @since 2.0.0 */ -public class Utils { +public final class Utils { private static final String UNICODE_REGEX = "\\\\(\\\\*)u\\{([a-fA-F0-9]+)\\}"; public static final Pattern UNICODE_PATTERN = Pattern.compile(UNICODE_REGEX); @@ -117,28 +117,18 @@ private static String getFormattedStringForQuotedIdentifiers(char c) { } private static String getFormattedStringForJvmReservedSet(char c) { - switch (c) { - case '\\': - return "0092"; - case '.': - return "0046"; - case ':': - return "0058"; - case ';': - return "0059"; - case '[': - return "0091"; - case ']': - return "0093"; - case '/': - return "0047"; - case '<': - return "0060"; - case '>': - return "0062"; - default: - return null; - } + return switch (c) { + case '\\' -> "0092"; + case '.' -> "0046"; + case ':' -> "0058"; + case ';' -> "0059"; + case '[' -> "0091"; + case ']' -> "0093"; + case '/' -> "0047"; + case '<' -> "0060"; + case '>' -> "0062"; + default -> null; + }; } /** @@ -193,7 +183,7 @@ public static String unescapeBallerina(String text) { */ public static String unescapeUnicodeCodepoints(String identifier) { Matcher matcher = UNICODE_PATTERN.matcher(identifier); - StringBuffer buffer = new StringBuffer(identifier.length()); + StringBuilder buffer = new StringBuilder(identifier.length()); while (matcher.find()) { String leadingSlashes = matcher.group(1); if (isEscapedNumericEscape(leadingSlashes)) { diff --git a/misc/json-to-record-converter/src/main/java/io/ballerina/jsonmapper/JsonToRecordMapper.java b/misc/json-to-record-converter/src/main/java/io/ballerina/jsonmapper/JsonToRecordMapper.java index c504cd39184a..9fa71cca1988 100644 --- a/misc/json-to-record-converter/src/main/java/io/ballerina/jsonmapper/JsonToRecordMapper.java +++ b/misc/json-to-record-converter/src/main/java/io/ballerina/jsonmapper/JsonToRecordMapper.java @@ -82,7 +82,7 @@ * * @since 2201.2.0 */ -public class JsonToRecordMapper { +public final class JsonToRecordMapper { private JsonToRecordMapper() {} @@ -181,7 +181,7 @@ public static JsonToRecordResponse convert(String jsonString, String recordName, Token semicolon = AbstractNodeFactory.createToken(SyntaxKind.SEMICOLON_TOKEN); return NodeFactory.createTypeDefinitionNode(null, null, typeKeyWord, typeName, entry.getValue(), semicolon); - }).collect(Collectors.toList()); + }).toList(); NodeList moduleMembers; if (isRecordTypeDesc) { diff --git a/misc/json-to-record-converter/src/main/java/io/ballerina/jsonmapper/util/ConverterUtils.java b/misc/json-to-record-converter/src/main/java/io/ballerina/jsonmapper/util/ConverterUtils.java index 376787828697..13c9b46fc9c0 100644 --- a/misc/json-to-record-converter/src/main/java/io/ballerina/jsonmapper/util/ConverterUtils.java +++ b/misc/json-to-record-converter/src/main/java/io/ballerina/jsonmapper/util/ConverterUtils.java @@ -45,7 +45,6 @@ import java.util.Comparator; import java.util.List; import java.util.Map; -import java.util.stream.Collectors; import java.util.stream.Stream; import static io.ballerina.identifier.Utils.escapeSpecialCharacters; @@ -200,10 +199,10 @@ public static List extractTypeDescriptorNodes(List extractedTypeNames = new ArrayList<>(); for (TypeDescriptorNode typeDescNode : typeDescNodes) { TypeDescriptorNode extractedTypeDescNode = extractParenthesisedTypeDescNode(typeDescNode); - if (extractedTypeDescNode instanceof UnionTypeDescriptorNode) { + if (extractedTypeDescNode instanceof UnionTypeDescriptorNode unionTypeDescriptorNode) { List childTypeDescNodes = - List.of(((UnionTypeDescriptorNode) extractedTypeDescNode).leftTypeDesc(), - ((UnionTypeDescriptorNode) extractedTypeDescNode).rightTypeDesc()); + List.of(unionTypeDescriptorNode.leftTypeDesc(), + unionTypeDescriptorNode.rightTypeDesc()); addIfNotExist(extractedTypeNames, extractTypeDescriptorNodes(childTypeDescNodes)); } else { addIfNotExist(extractedTypeNames, List.of(extractedTypeDescNode)); @@ -219,12 +218,11 @@ public static List extractTypeDescriptorNodes(List} The sorted TypeDescriptorNode list. */ public static List sortTypeDescriptorNodes(List typeDescriptorNodes) { - List nonArrayNodes = typeDescriptorNodes.stream() - .filter(node -> !(node instanceof ArrayTypeDescriptorNode)).collect(Collectors.toList()); - List arrayNodes = typeDescriptorNodes.stream() - .filter(node -> (node instanceof ArrayTypeDescriptorNode)).collect(Collectors.toList()); - nonArrayNodes.sort(Comparator.comparing(TypeDescriptorNode::toSourceCode)); - arrayNodes.sort((node1, node2) -> { + Stream nonArrayNodes = typeDescriptorNodes.stream() + .filter(node -> !(node instanceof ArrayTypeDescriptorNode)) + .sorted(Comparator.comparing(TypeDescriptorNode::toSourceCode)); + Stream arrayNodes = typeDescriptorNodes.stream() + .filter(node -> (node instanceof ArrayTypeDescriptorNode)).sorted((node1, node2) -> { ArrayTypeDescriptorNode arrayNode1 = (ArrayTypeDescriptorNode) node1; ArrayTypeDescriptorNode arrayNode2 = (ArrayTypeDescriptorNode) node2; return getNumberOfDimensions(arrayNode1).equals(getNumberOfDimensions(arrayNode2)) ? @@ -232,7 +230,7 @@ public static List sortTypeDescriptorNodes(List extractUnionTypeDescNode(TypeDescriptorNo */ public static Integer getNumberOfDimensions(ArrayTypeDescriptorNode arrayNode) { int totalDimensions = arrayNode.dimensions().size(); - if (arrayNode.memberTypeDesc() instanceof ArrayTypeDescriptorNode) { - totalDimensions += getNumberOfDimensions((ArrayTypeDescriptorNode) arrayNode.memberTypeDesc()); + if (arrayNode.memberTypeDesc() instanceof ArrayTypeDescriptorNode arrayTypeDescriptorNode) { + totalDimensions += getNumberOfDimensions(arrayTypeDescriptorNode); } return totalDimensions; } private static TypeDescriptorNode extractParenthesisedTypeDescNode(TypeDescriptorNode typeDescNode) { - if (typeDescNode instanceof ParenthesisedTypeDescriptorNode) { - return extractParenthesisedTypeDescNode(((ParenthesisedTypeDescriptorNode) typeDescNode).typedesc()); + if (typeDescNode instanceof ParenthesisedTypeDescriptorNode parenthesisedTypeDescriptorNode) { + return extractParenthesisedTypeDescNode(parenthesisedTypeDescriptorNode.typedesc()); } else { return typeDescNode; } diff --git a/misc/lib-creator/src/main/java/org/ballerinalang/stdlib/utils/BallerinaToDependancyToml.java b/misc/lib-creator/src/main/java/org/ballerinalang/stdlib/utils/BallerinaToDependancyToml.java index fbb84217d89c..e5782f9f6791 100644 --- a/misc/lib-creator/src/main/java/org/ballerinalang/stdlib/utils/BallerinaToDependancyToml.java +++ b/misc/lib-creator/src/main/java/org/ballerinalang/stdlib/utils/BallerinaToDependancyToml.java @@ -12,8 +12,12 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Stream; -public class BallerinaToDependancyToml { +public final class BallerinaToDependancyToml { + + private BallerinaToDependancyToml() { + } public static void main(String... args) throws IOException { if (args.length == 0) { @@ -23,7 +27,9 @@ public static void main(String... args) throws IOException { Path dir = Paths.get(System.getProperty("user.dir")).resolve(path); PathMatcher pathMatcher = FileSystems.getDefault() .getPathMatcher("glob:**/Ballerina.toml"); - Files.walk(Paths.get("..")).filter(pathMatcher::matches).forEach(BallerinaToDependancyToml::migrate); + try (Stream paths = Files.walk(Paths.get(".."))) { + paths.filter(pathMatcher::matches).forEach(BallerinaToDependancyToml::migrate); + } } public static void migrate(Path ballerinaTomlPath) { diff --git a/misc/lib-creator/src/main/java/org/ballerinalang/stdlib/utils/BuildLangLib.java b/misc/lib-creator/src/main/java/org/ballerinalang/stdlib/utils/BuildLangLib.java index 0be2d737ac4e..772ebe9156ce 100644 --- a/misc/lib-creator/src/main/java/org/ballerinalang/stdlib/utils/BuildLangLib.java +++ b/misc/lib-creator/src/main/java/org/ballerinalang/stdlib/utils/BuildLangLib.java @@ -45,6 +45,7 @@ import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.Optional; +import java.util.stream.Stream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; @@ -56,12 +57,15 @@ * * @since 2.0.0 */ -public class BuildLangLib { +public final class BuildLangLib { static Path projectDir; static Path distCache; static boolean skipBootstrap = false; + private BuildLangLib() { + } + public static void main(String[] args) throws IOException { PrintStream out = System.out; @@ -109,16 +113,19 @@ public static void main(String[] args) throws IOException { Files.createDirectories(balaPath); jBallerinaBackend.emit(JBallerinaBackend.OutputType.BALA, balaPath); - Path balaFilePath = Files.list(balaPath).findAny().orElseThrow(); + Path balaFilePath; + try (Stream paths = Files.list(balaPath)) { + balaFilePath = paths.findAny().orElseThrow(); + } ProjectUtils.extractBala(balaFilePath, balaPath); Files.delete(balaFilePath); // Create zip file Path zipFilePath = targetPath.resolve(pkgDesc.name().value() + ".zip"); - try (ZipOutputStream zs = new ZipOutputStream(Files.newOutputStream(zipFilePath))) { - Files.walk(pkgTargetPath) - .filter(path -> !Files.isDirectory(path)) + try (ZipOutputStream zs = new ZipOutputStream(Files.newOutputStream(zipFilePath)); + Stream paths = Files.walk(pkgTargetPath)) { + paths.filter(path -> !Files.isDirectory(path)) .forEach(path -> { ZipEntry zipEntry = new ZipEntry(pkgTargetPath.relativize(path).toString()); try { diff --git a/misc/ls-extensions/modules/bal-shell-service/src/main/java/io/ballerina/shell/service/Constants.java b/misc/ls-extensions/modules/bal-shell-service/src/main/java/io/ballerina/shell/service/Constants.java index 2d950caae03c..8732c2911b7a 100644 --- a/misc/ls-extensions/modules/bal-shell-service/src/main/java/io/ballerina/shell/service/Constants.java +++ b/misc/ls-extensions/modules/bal-shell-service/src/main/java/io/ballerina/shell/service/Constants.java @@ -20,6 +20,10 @@ * * @since 2201.1.1 */ -public class Constants { +public final class Constants { + public static final String CAPABILITY_NAME = "balShell"; + + private Constants() { + } } diff --git a/misc/ls-extensions/modules/bal-shell-service/src/main/java/io/ballerina/shell/service/ShellWrapper.java b/misc/ls-extensions/modules/bal-shell-service/src/main/java/io/ballerina/shell/service/ShellWrapper.java index 5be6722d812c..ff2bc3b38a4d 100644 --- a/misc/ls-extensions/modules/bal-shell-service/src/main/java/io/ballerina/shell/service/ShellWrapper.java +++ b/misc/ls-extensions/modules/bal-shell-service/src/main/java/io/ballerina/shell/service/ShellWrapper.java @@ -80,9 +80,9 @@ public BalShellGetResultResponse getResult(String source) { PrintStream originalErr = System.err; ConsoleOutCollector consoleOutCollector = new ConsoleOutCollector(); PrintStream printStreamCollector = new PrintStream(consoleOutCollector, false, StandardCharsets.UTF_8); - System.setOut(printStreamCollector); - System.setErr(printStreamCollector); - try { + try (printStreamCollector) { + System.setOut(printStreamCollector); + System.setErr(printStreamCollector); ShellCompilation shellCompilation = evaluator.getCompilation(source); // continue the execution if the compilation is done successfully // info related to errors required for the Ballerina notebook in compilation @@ -123,7 +123,6 @@ public BalShellGetResultResponse getResult(String source) { ); evaluator.resetDiagnostics(); evaluator.clearPreviousVariablesAndModuleDclnsNames(); - printStreamCollector.close(); System.setOut(originalOut); System.setErr(originalErr); } diff --git a/misc/ls-extensions/modules/bal-shell-service/src/main/java/io/ballerina/shell/service/util/Constants.java b/misc/ls-extensions/modules/bal-shell-service/src/main/java/io/ballerina/shell/service/util/Constants.java index aedd469c0b37..7a9bcb149d57 100644 --- a/misc/ls-extensions/modules/bal-shell-service/src/main/java/io/ballerina/shell/service/util/Constants.java +++ b/misc/ls-extensions/modules/bal-shell-service/src/main/java/io/ballerina/shell/service/util/Constants.java @@ -20,9 +20,13 @@ * * @since 2201.1.1 */ -public class Constants { +public final class Constants { + public static final String MIME_TYPE_PLAIN_TEXT = "plain/text"; public static final String MIME_TYPE_TABLE = "ballerina-notebook/table-view"; public static final String MIME_TYPE_JSON = "ballerina-notebook/json-view"; public static final String MIME_TYPE_XML = "ballerina-notebook/xml-view"; + + private Constants() { + } } diff --git a/misc/ls-extensions/modules/bal-shell-service/src/main/java/io/ballerina/shell/service/util/TypeUtils.java b/misc/ls-extensions/modules/bal-shell-service/src/main/java/io/ballerina/shell/service/util/TypeUtils.java index e3ba81083045..270dd268e5c3 100644 --- a/misc/ls-extensions/modules/bal-shell-service/src/main/java/io/ballerina/shell/service/util/TypeUtils.java +++ b/misc/ls-extensions/modules/bal-shell-service/src/main/java/io/ballerina/shell/service/util/TypeUtils.java @@ -26,7 +26,11 @@ * * @since 2201.1.1 */ -public class TypeUtils { +public final class TypeUtils { + + private TypeUtils() { + } + /** * Get applicable mime type for a given type. * @@ -34,24 +38,20 @@ public class TypeUtils { * @return mime type */ public static String getMimeTypeFromName(Type type) { - switch (type.getTag()) { - case TypeTags.JSON_TAG: - case TypeTags.RECORD_TYPE_TAG: - case TypeTags.MAP_TAG: - case TypeTags.ARRAY_TAG: - case TypeTags.TUPLE_TAG: - return Constants.MIME_TYPE_JSON; - case TypeTags.TABLE_TAG: - return Constants.MIME_TYPE_TABLE; - case TypeTags.XML_TAG: - case TypeTags.XML_ELEMENT_TAG: - case TypeTags.XML_PI_TAG: - case TypeTags.XML_COMMENT_TAG: - case TypeTags.XML_TEXT_TAG: - return Constants.MIME_TYPE_XML; - default: - return Constants.MIME_TYPE_PLAIN_TEXT; - } + return switch (type.getTag()) { + case TypeTags.JSON_TAG, + TypeTags.RECORD_TYPE_TAG, + TypeTags.MAP_TAG, + TypeTags.ARRAY_TAG, + TypeTags.TUPLE_TAG -> Constants.MIME_TYPE_JSON; + case TypeTags.TABLE_TAG -> Constants.MIME_TYPE_TABLE; + case TypeTags.XML_TAG, + TypeTags.XML_ELEMENT_TAG, + TypeTags.XML_PI_TAG, + TypeTags.XML_COMMENT_TAG, + TypeTags.XML_TEXT_TAG -> Constants.MIME_TYPE_XML; + default -> Constants.MIME_TYPE_PLAIN_TEXT; + }; } /** @@ -63,23 +63,20 @@ public static String getMimeTypeFromName(Type type) { */ public static String convertToJsonIfAcceptable(Object value) { Type type = io.ballerina.runtime.api.utils.TypeUtils.getType(value); - switch (type.getTag()) { - case TypeTags.JSON_TAG: - case TypeTags.RECORD_TYPE_TAG: - case TypeTags.MAP_TAG: - case TypeTags.ARRAY_TAG: - case TypeTags.TUPLE_TAG: - case TypeTags.TABLE_TAG: - return StringUtils.getJsonString(value); - case TypeTags.XML_TAG: - case TypeTags.XML_ELEMENT_TAG: - case TypeTags.XML_COMMENT_TAG: - case TypeTags.XML_PI_TAG: - case TypeTags.XML_TEXT_TAG: - case TypeTags.OBJECT_TYPE_TAG: - return StringUtils.getStringValue(value); - default: - return StringUtils.getExpressionStringValue(value); - } + return switch (type.getTag()) { + case TypeTags.JSON_TAG, + TypeTags.RECORD_TYPE_TAG, + TypeTags.MAP_TAG, + TypeTags.ARRAY_TAG, + TypeTags.TUPLE_TAG, + TypeTags.TABLE_TAG -> StringUtils.getJsonString(value); + case TypeTags.XML_TAG, + TypeTags.XML_ELEMENT_TAG, + TypeTags.XML_COMMENT_TAG, + TypeTags.XML_PI_TAG, + TypeTags.XML_TEXT_TAG, + TypeTags.OBJECT_TYPE_TAG -> StringUtils.getStringValue(value); + default -> StringUtils.getExpressionStringValue(value); + }; } } diff --git a/misc/ls-extensions/modules/bal-shell-service/src/test/java/io/ballerina/shell/service/test/TestUtils.java b/misc/ls-extensions/modules/bal-shell-service/src/test/java/io/ballerina/shell/service/test/TestUtils.java index 9afddf51e87a..ac40cb78adf4 100644 --- a/misc/ls-extensions/modules/bal-shell-service/src/test/java/io/ballerina/shell/service/test/TestUtils.java +++ b/misc/ls-extensions/modules/bal-shell-service/src/test/java/io/ballerina/shell/service/test/TestUtils.java @@ -30,7 +30,7 @@ * * @since 2201.1.1 */ -public class TestUtils { +public final class TestUtils { /** * Loads GetResultsTestCases from a given file path. diff --git a/misc/ls-extensions/modules/json-to-record-converter/src/main/java/io/ballerina/converters/Constants.java b/misc/ls-extensions/modules/json-to-record-converter/src/main/java/io/ballerina/converters/Constants.java index 4ecfd17bd029..5bcd91e2a95f 100644 --- a/misc/ls-extensions/modules/json-to-record-converter/src/main/java/io/ballerina/converters/Constants.java +++ b/misc/ls-extensions/modules/json-to-record-converter/src/main/java/io/ballerina/converters/Constants.java @@ -20,6 +20,10 @@ * * @since 2.0.0 */ -public class Constants { +public final class Constants { + public static final String CAPABILITY_NAME = "jsonToRecord"; + + private Constants() { + } } diff --git a/misc/ls-extensions/modules/json-to-record-converter/src/main/java/io/ballerina/converters/JsonToRecordConverter.java b/misc/ls-extensions/modules/json-to-record-converter/src/main/java/io/ballerina/converters/JsonToRecordConverter.java index a9dba184541c..a304dbeeb263 100644 --- a/misc/ls-extensions/modules/json-to-record-converter/src/main/java/io/ballerina/converters/JsonToRecordConverter.java +++ b/misc/ls-extensions/modules/json-to-record-converter/src/main/java/io/ballerina/converters/JsonToRecordConverter.java @@ -56,6 +56,7 @@ import java.io.IOException; import java.util.ArrayList; +import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; @@ -73,7 +74,7 @@ * * @since 2.0.0 */ -public class JsonToRecordConverter { +public final class JsonToRecordConverter { private JsonToRecordConverter() { // not called @@ -155,7 +156,8 @@ public static JsonToRecordResponse convert(String jsonString, String recordName, } else { // Sets generated type definition code block NodeList moduleMembers = AbstractNodeFactory.createNodeList( - new ArrayList(typeDefinitionNodes.values())); + new ArrayList<>( + (Collection) (Collection) typeDefinitionNodes.values())); Token eofToken = AbstractNodeFactory.createIdentifierToken(""); ModulePartNode modulePartNode = NodeFactory.createModulePartNode(imports, moduleMembers, eofToken); response.setCodeBlock(Formatter.format(modulePartNode.syntaxTree(), formattingOptions).toSourceCode()); @@ -173,6 +175,7 @@ public static JsonToRecordResponse convert(String jsonString, String recordName, * @return {@link Map} Map of Record Nodes * @throws JsonToRecordConverterException In case of bad record fields */ + @SuppressWarnings("rawtypes") private static Map generateRecords(OpenAPI openApi, boolean isRecordTypeDescriptor, boolean isClosedRecord) throws JsonToRecordConverterException { @@ -227,8 +230,7 @@ private static Map generateRecords(OpenAPI openApi, boo typeDefinitionNodes.put(key, typeDefinitionNode); } } else if (schemaType.equals("array")) { - if (schemaValue instanceof ArraySchema) { - ArraySchema arraySchema = (ArraySchema) schemaValue; + if (schemaValue instanceof ArraySchema arraySchema) { Token openSBracketToken = AbstractNodeFactory.createToken(SyntaxKind.OPEN_BRACKET_TOKEN); Token closeSBracketToken = AbstractNodeFactory.createToken(SyntaxKind.CLOSE_BRACKET_TOKEN); IdentifierToken fieldName = @@ -282,6 +284,7 @@ private static Map generateRecords(OpenAPI openApi, boo * @param typeDefinitionNodes Map of type definition nodes to be updated in case of object type fields * @throws JsonToRecordConverterException In case of bad schema entries */ + @SuppressWarnings("rawtypes") private static void addRecordFields(List required, List recordFieldList, Map.Entry field, Map typeDefinitionNodes, @@ -313,6 +316,7 @@ private static void addRecordFields(List required, List recordFiel * @return {@link TypeDescriptorNode} Type descriptor for record field * @throws JsonToRecordConverterException In case of invalid schema */ + @SuppressWarnings("rawtypes") private static TypeDescriptorNode extractOpenApiSchema(Schema schema, String name, Map typeDefinitionNodes, boolean isRecordTypeDescriptor) @@ -325,8 +329,7 @@ private static TypeDescriptorNode extractOpenApiSchema(Schema schema, String String type = convertOpenAPITypeToBallerina(schemaType.trim()); Token typeName = AbstractNodeFactory.createIdentifierToken(type); return createBuiltinSimpleNameReferenceNode(null, typeName); - } else if (schemaType.equals("array") && schema instanceof ArraySchema) { - final ArraySchema arraySchema = (ArraySchema) schema; + } else if (schemaType.equals("array") && schema instanceof ArraySchema arraySchema) { if (arraySchema.getItems() != null) { Token openSBracketToken = AbstractNodeFactory.createToken(SyntaxKind.OPEN_BRACKET_TOKEN); diff --git a/misc/ls-extensions/modules/json-to-record-converter/src/main/java/io/ballerina/converters/util/Constants.java b/misc/ls-extensions/modules/json-to-record-converter/src/main/java/io/ballerina/converters/util/Constants.java index 2fa368023832..23a03094383b 100644 --- a/misc/ls-extensions/modules/json-to-record-converter/src/main/java/io/ballerina/converters/util/Constants.java +++ b/misc/ls-extensions/modules/json-to-record-converter/src/main/java/io/ballerina/converters/util/Constants.java @@ -24,7 +24,7 @@ * * @since 2.0.0 */ -public class Constants { +public final class Constants { private Constants() {} diff --git a/misc/ls-extensions/modules/json-to-record-converter/src/main/java/io/ballerina/converters/util/ConverterUtils.java b/misc/ls-extensions/modules/json-to-record-converter/src/main/java/io/ballerina/converters/util/ConverterUtils.java index a75bfd40564b..d0e193dd2dee 100644 --- a/misc/ls-extensions/modules/json-to-record-converter/src/main/java/io/ballerina/converters/util/ConverterUtils.java +++ b/misc/ls-extensions/modules/json-to-record-converter/src/main/java/io/ballerina/converters/util/ConverterUtils.java @@ -26,7 +26,11 @@ * * @since 2.0.0 */ -public class ConverterUtils { +public final class ConverterUtils { + + private ConverterUtils() { + } + /** * Method for mapping openApi type to ballerina type. * @@ -34,41 +38,24 @@ public class ConverterUtils { * @return {@link String} Ballerina type */ public static String convertOpenAPITypeToBallerina(String type) { - String convertedType; //In the case where type is not specified return anydata by default if (type == null || type.isEmpty()) { return "anydata"; } - switch (type) { - case Constants.INTEGER: - convertedType = "int"; - break; - case Constants.STRING: - convertedType = "string"; - break; - case Constants.BOOLEAN: - convertedType = "boolean"; - break; - case Constants.ARRAY: - convertedType = "[]"; - break; - case Constants.OBJECT: - convertedType = "record"; - break; - case Constants.DECIMAL: - case Constants.NUMBER: - case Constants.DOUBLE: - convertedType = "decimal"; - break; - case Constants.FLOAT: - convertedType = "float"; - break; - default: - convertedType = "anydata"; - } - return convertedType; + return switch (type) { + case Constants.INTEGER -> "int"; + case Constants.STRING -> "string"; + case Constants.BOOLEAN -> "boolean"; + case Constants.ARRAY -> "[]"; + case Constants.OBJECT -> "record"; + case Constants.DECIMAL, + Constants.NUMBER, + Constants.DOUBLE -> "decimal"; + case Constants.FLOAT -> "float"; + default -> "anydata"; + }; } /** diff --git a/misc/ls-extensions/modules/json-to-record-converter/src/main/java/io/ballerina/converters/util/ErrorMessages.java b/misc/ls-extensions/modules/json-to-record-converter/src/main/java/io/ballerina/converters/util/ErrorMessages.java index 147032b189f2..b1ac70d78a19 100644 --- a/misc/ls-extensions/modules/json-to-record-converter/src/main/java/io/ballerina/converters/util/ErrorMessages.java +++ b/misc/ls-extensions/modules/json-to-record-converter/src/main/java/io/ballerina/converters/util/ErrorMessages.java @@ -22,7 +22,10 @@ * * @since 2.0.0 */ -public class ErrorMessages { +public final class ErrorMessages { + + private ErrorMessages() { + } public static String parserException(String json) { return String.format("Couldn't read the JSON Schema from the given string: %s", json); diff --git a/misc/ls-extensions/modules/json-to-record-converter/src/main/java/io/ballerina/converters/util/SchemaGenerator.java b/misc/ls-extensions/modules/json-to-record-converter/src/main/java/io/ballerina/converters/util/SchemaGenerator.java index 801eea99e68c..96155fd3a0a4 100644 --- a/misc/ls-extensions/modules/json-to-record-converter/src/main/java/io/ballerina/converters/util/SchemaGenerator.java +++ b/misc/ls-extensions/modules/json-to-record-converter/src/main/java/io/ballerina/converters/util/SchemaGenerator.java @@ -35,7 +35,7 @@ * * @since 2.0.0 */ -public class SchemaGenerator { +public final class SchemaGenerator { private SchemaGenerator() { // not called @@ -69,11 +69,9 @@ public static Map generate(JsonNode json) throws JsonToRecordCon } // handle array type - if (json.getNodeType() == JsonNodeType.ARRAY && json instanceof ArrayNode) { + if (json.getNodeType() == JsonNodeType.ARRAY && json instanceof ArrayNode array) { schema.put("type", "array"); - ArrayNode array = (ArrayNode) json; - if (array.isEmpty()) { schema.put("items", new HashMap()); } else { @@ -88,11 +86,10 @@ public static Map generate(JsonNode json) throws JsonToRecordCon return schema; } - if (!(json instanceof ObjectNode)) { + if (!(json instanceof ObjectNode object)) { throw new JsonToRecordConverterException(ErrorMessages.parserException(json.toString())); } // handle object type - ObjectNode object = (ObjectNode) json; schema.put("type", "object"); if (object.isEmpty()) { diff --git a/misc/ls-extensions/modules/json-to-record-converter/src/test/java/io/ballerina/converters/JsonToRecordConverterTests.java b/misc/ls-extensions/modules/json-to-record-converter/src/test/java/io/ballerina/converters/JsonToRecordConverterTests.java index aefbadc7bfa7..2cb01f839f97 100644 --- a/misc/ls-extensions/modules/json-to-record-converter/src/test/java/io/ballerina/converters/JsonToRecordConverterTests.java +++ b/misc/ls-extensions/modules/json-to-record-converter/src/test/java/io/ballerina/converters/JsonToRecordConverterTests.java @@ -35,7 +35,6 @@ import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; -import java.util.stream.Collectors; /** * Tests for JsonToRecordConverter. @@ -400,7 +399,7 @@ public void testJSON2RecordServiceInvalidJSONObject() throws IOException, Execut io.ballerina.jsonmapper.JsonToRecordResponse response = (io.ballerina.jsonmapper.JsonToRecordResponse) result.get(); List generatedDiagnosticMessages = response.getDiagnostics().stream() - .map(JsonToRecordMapperDiagnostic::toString).collect(Collectors.toList()); + .map(JsonToRecordMapperDiagnostic::toString).toList(); List expectedCDiagnosticMessages = List.of("[ERROR] Provided JSON is invalid : " + "Unterminated object at line 5 column 4 path $.position"); Assert.assertEquals(generatedDiagnosticMessages, expectedCDiagnosticMessages); @@ -417,7 +416,7 @@ public void testJSON2RecordServiceNullJSON() throws IOException, ExecutionExcept io.ballerina.jsonmapper.JsonToRecordResponse response = (io.ballerina.jsonmapper.JsonToRecordResponse) result.get(); List generatedDiagnosticMessages = response.getDiagnostics().stream() - .map(JsonToRecordMapperDiagnostic::toString).collect(Collectors.toList()); + .map(JsonToRecordMapperDiagnostic::toString).toList(); List expectedCDiagnosticMessages = List.of("[ERROR] Provided JSON is unsupported. It may be null or have missing types."); Assert.assertEquals(generatedDiagnosticMessages, expectedCDiagnosticMessages); diff --git a/misc/ls-extensions/modules/partial-parser/src/main/java/io/ballerina/parsers/Constants.java b/misc/ls-extensions/modules/partial-parser/src/main/java/io/ballerina/parsers/Constants.java index 37520cf4274f..c69a89b58e7c 100644 --- a/misc/ls-extensions/modules/partial-parser/src/main/java/io/ballerina/parsers/Constants.java +++ b/misc/ls-extensions/modules/partial-parser/src/main/java/io/ballerina/parsers/Constants.java @@ -20,7 +20,11 @@ * * @since 2.0.0 */ -public class Constants { +public final class Constants { + public static final String CAPABILITY_NAME = "partialParser"; public static final int SPACE_COUNT_FOR_ST_TAB = 4; + + private Constants() { + } } diff --git a/misc/ls-extensions/modules/partial-parser/src/main/java/io/ballerina/parsers/STModificationUtil.java b/misc/ls-extensions/modules/partial-parser/src/main/java/io/ballerina/parsers/STModificationUtil.java index f4d6af830d78..8c0fdfd6864f 100644 --- a/misc/ls-extensions/modules/partial-parser/src/main/java/io/ballerina/parsers/STModificationUtil.java +++ b/misc/ls-extensions/modules/partial-parser/src/main/java/io/ballerina/parsers/STModificationUtil.java @@ -27,7 +27,8 @@ * * @since 1.3.0 */ -public class STModificationUtil { +public final class STModificationUtil { + private STModificationUtil() { } diff --git a/misc/ls-extensions/modules/performance-analyzer-services/src/main/java/io/ballerina/Constants.java b/misc/ls-extensions/modules/performance-analyzer-services/src/main/java/io/ballerina/Constants.java index 8fabe906e11f..790e2461f1ef 100644 --- a/misc/ls-extensions/modules/performance-analyzer-services/src/main/java/io/ballerina/Constants.java +++ b/misc/ls-extensions/modules/performance-analyzer-services/src/main/java/io/ballerina/Constants.java @@ -20,7 +20,7 @@ * * @since 2.0.0 */ -public class Constants { +public final class Constants { public static final String CAPABILITY_NAME = "performanceAnalyzer"; static final String ERROR = "error"; @@ -32,4 +32,7 @@ public class Constants { static final String NEXT_NODE = "nextNode"; static final String WORKERS = "workers"; public static final String MAIN_WORKER = "mainWorker"; + + private Constants() { + } } diff --git a/misc/ls-extensions/modules/performance-analyzer-services/src/main/java/io/ballerina/EndpointsFinder.java b/misc/ls-extensions/modules/performance-analyzer-services/src/main/java/io/ballerina/EndpointsFinder.java index 65359907764b..3f4b9d6baca4 100644 --- a/misc/ls-extensions/modules/performance-analyzer-services/src/main/java/io/ballerina/EndpointsFinder.java +++ b/misc/ls-extensions/modules/performance-analyzer-services/src/main/java/io/ballerina/EndpointsFinder.java @@ -53,7 +53,10 @@ * * @since 2.0.0 */ -public class EndpointsFinder { +public final class EndpointsFinder { + + private EndpointsFinder() { + } /** * Get endpoints and action invocations in a given range of a file. diff --git a/misc/ls-extensions/modules/performance-analyzer-services/src/main/java/io/ballerina/PerformanceAnalyzerNodeVisitor.java b/misc/ls-extensions/modules/performance-analyzer-services/src/main/java/io/ballerina/PerformanceAnalyzerNodeVisitor.java index 43de8903c8ac..dcd4fd22d727 100644 --- a/misc/ls-extensions/modules/performance-analyzer-services/src/main/java/io/ballerina/PerformanceAnalyzerNodeVisitor.java +++ b/misc/ls-extensions/modules/performance-analyzer-services/src/main/java/io/ballerina/PerformanceAnalyzerNodeVisitor.java @@ -241,9 +241,8 @@ public void visit(IfElseStatementNode ifElseStatementNode) { ifElseStatementNode.elseBody().ifPresent(elseBody -> elseBody.accept(returnFinder)); } Node ifBodyNodeNextNode = ifBodyNode.getNextNode(); - if ((ifBodyNodeNextNode instanceof IfStatementNode) && returnFinder.isHasReturn() + if ((ifBodyNodeNextNode instanceof IfStatementNode ifBodyNextNode) && returnFinder.isHasReturn() && returnFinder.isHasNestedIfElse() && withinRange) { - IfStatementNode ifBodyNextNode = (IfStatementNode) ifBodyNodeNextNode; ReturningIfStatementNode returningIfStatementNode = new ReturningIfStatementNode(ifBodyNextNode.getIfBody(), ifBodyNextNode.getElseBody(), true); ifStatementNode.setIfBody(returningIfStatementNode); diff --git a/misc/ls-extensions/modules/performance-analyzer-services/src/main/java/io/ballerina/utils/ParserUtil.java b/misc/ls-extensions/modules/performance-analyzer-services/src/main/java/io/ballerina/utils/ParserUtil.java index 0ce41bd73562..67218055b519 100644 --- a/misc/ls-extensions/modules/performance-analyzer-services/src/main/java/io/ballerina/utils/ParserUtil.java +++ b/misc/ls-extensions/modules/performance-analyzer-services/src/main/java/io/ballerina/utils/ParserUtil.java @@ -37,7 +37,7 @@ /** * utils class for ActionInvocationParser. */ -public class ParserUtil { +public final class ParserUtil { public static final String TEST_DIR = "tests"; public static final String MAIN_FUNC_NAME = "main"; @@ -46,6 +46,9 @@ public class ParserUtil { public static final String CLIENT_URL_ATTR_NAME = "url"; public static final String ACTION_PATH_ATTR_NAME = "path"; + private ParserUtil() { + } + public static boolean isSourceUnit(BLangCompilationUnit compilationUnit) { return !(TEST_DIR.equals(compilationUnit.getName().split("/")[0])); @@ -81,11 +84,9 @@ public static boolean isActionInvocation(BLangExpression expression) { public static boolean isURLAttrFromConfig(BLangRecordLiteral.RecordField recordField) { - if (recordField instanceof BLangRecordLiteral.BLangRecordKeyValueField) { - BLangRecordLiteral.BLangRecordKeyValueField recordKeyValue = - (BLangRecordLiteral.BLangRecordKeyValueField) recordField; - if (recordKeyValue.key.expr instanceof BLangSimpleVarRef) { - String recordValue = ((BLangSimpleVarRef) recordKeyValue.key.expr).variableName.value; + if (recordField instanceof BLangRecordLiteral.BLangRecordKeyValueField recordKeyValue) { + if (recordKeyValue.key.expr instanceof BLangSimpleVarRef simpleVarRef) { + String recordValue = simpleVarRef.variableName.value; return recordValue != null && recordValue.toLowerCase(Locale.ENGLISH).contains(CONFIG_URL_KEY); } } @@ -106,8 +107,8 @@ public static boolean isClientObject(BSymbol bSymbol) { private static BType isClientType(BType type) { - if (type instanceof BUnionType) { - for (BType bType : ((BUnionType) type).getMemberTypes()) { + if (type instanceof BUnionType bUnionType) { + for (BType bType : bUnionType.getMemberTypes()) { if (bType.tsymbol != null && SymbolKind.OBJECT.equals(bType.tsymbol.kind) && (bType.tsymbol.flags & Flags.CLIENT) == Flags.CLIENT) { return bType; @@ -125,8 +126,8 @@ private static BType isClientType(BType type) { public static BLangExpression getURLExpressionFromArgs(BLangTypeInit connectorInitExpr) { BSymbol bSymbol = ((BLangInvocation) connectorInitExpr.initInvocation).symbol; - if (bSymbol instanceof BInvokableSymbol) { - List params = ((BInvokableSymbol) bSymbol).getParameters(); + if (bSymbol instanceof BInvokableSymbol bInvokableSymbol) { + List params = bInvokableSymbol.getParameters(); for (int i = 0; i < params.size(); i++) { if (connectorInitExpr.argsExpr.size() > i && (CLIENT_URL_ATTR_NAME.equals(params.get(i).name.value.toLowerCase(Locale.ENGLISH)) @@ -142,8 +143,8 @@ public static BLangExpression getPathExpressionFromArgs(BLangInvocation actionIn BSymbol bSymbol = actionInvocation.symbol; if (bSymbol != null) { - if (bSymbol instanceof BInvokableSymbol) { - List params = ((BInvokableSymbol) bSymbol).getParameters(); + if (bSymbol instanceof BInvokableSymbol bInvokableSymbol) { + List params = bInvokableSymbol.getParameters(); for (int i = 0; i < params.size(); i++) { if (actionInvocation.argExprs.size() > i && (ACTION_PATH_ATTR_NAME.equals(params.get(i).name.value.toLowerCase(Locale.ENGLISH)))) { @@ -164,8 +165,7 @@ public static void getReducedTree(Node parentNode) { getReducedTree(currentNode); - if (currentNode instanceof IfStatementNode) { - IfStatementNode ifStatementNode = (IfStatementNode) currentNode; + if (currentNode instanceof IfStatementNode ifStatementNode) { Node ifBody = ifStatementNode.getIfBody(); Node elseBody = ifStatementNode.getElseBody(); @@ -178,8 +178,7 @@ public static void getReducedTree(Node parentNode) { } } - if (currentNode instanceof IfStatementNode) { - IfStatementNode ifStatementNode = (IfStatementNode) currentNode; + if (currentNode instanceof IfStatementNode ifStatementNode) { if (ifStatementNode.getIfBody() == null && ifStatementNode.getElseBody() == null) { if (ifStatementNode.hasNext()) { parentNode.setNextNode(ifStatementNode.getNextNode()); @@ -187,8 +186,7 @@ public static void getReducedTree(Node parentNode) { parentNode.setNextNode(null); } } - } else if (currentNode instanceof ForStatementNode) { - ForStatementNode forStatementNode = (ForStatementNode) currentNode; + } else if (currentNode instanceof ForStatementNode forStatementNode) { if (forStatementNode.getForBody() == null) { if (forStatementNode.hasNext()) { parentNode.setNextNode(forStatementNode.getNextNode()); diff --git a/misc/ls-extensions/modules/trigger-service/src/main/java/io/ballerina/trigger/entity/BallerinaTriggerListRequest.java b/misc/ls-extensions/modules/trigger-service/src/main/java/io/ballerina/trigger/entity/BallerinaTriggerListRequest.java index 42e76b56efe0..0527bf27cbbe 100644 --- a/misc/ls-extensions/modules/trigger-service/src/main/java/io/ballerina/trigger/entity/BallerinaTriggerListRequest.java +++ b/misc/ls-extensions/modules/trigger-service/src/main/java/io/ballerina/trigger/entity/BallerinaTriggerListRequest.java @@ -174,7 +174,7 @@ public String toString() { } public Map getQueryMap() { - Map params = new HashMap(); + Map params = new HashMap<>(); if (getQuery() != null) { params.put("q", getQuery()); diff --git a/misc/ls-extensions/modules/trigger-service/src/main/java/io/ballerina/trigger/entity/Constants.java b/misc/ls-extensions/modules/trigger-service/src/main/java/io/ballerina/trigger/entity/Constants.java index f6f92aa61189..d8fe20e06a24 100644 --- a/misc/ls-extensions/modules/trigger-service/src/main/java/io/ballerina/trigger/entity/Constants.java +++ b/misc/ls-extensions/modules/trigger-service/src/main/java/io/ballerina/trigger/entity/Constants.java @@ -20,6 +20,10 @@ * * @since 2.0.0 */ -public class Constants { +public final class Constants { + public static final String CAPABILITY_NAME = "ballerinaTrigger"; + + private Constants() { + } } diff --git a/misc/maven-resolver/src/main/java/org/ballerinalang/maven/Utils.java b/misc/maven-resolver/src/main/java/org/ballerinalang/maven/Utils.java index 961804a546e9..dac70a9c32b1 100644 --- a/misc/maven-resolver/src/main/java/org/ballerinalang/maven/Utils.java +++ b/misc/maven-resolver/src/main/java/org/ballerinalang/maven/Utils.java @@ -22,7 +22,11 @@ /** * Utilities for Maven dependency resolving. */ -public class Utils { +public final class Utils { + + private Utils() { + } + /** * Provides jar location path fpr provided maven dependency. * @param targetPath target path dependencies have been resolved diff --git a/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/BallerinaPackageResolver.java b/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/BallerinaPackageResolver.java index 31245e69bf28..bf63a7b66ac8 100644 --- a/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/BallerinaPackageResolver.java +++ b/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/BallerinaPackageResolver.java @@ -101,7 +101,7 @@ SemanticVersion resolveClosestCompatibleCentralVersion(String orgName, String pk "Ballerina central under the org '%s' with name '%s'", orgName, pkgName)); } List availableVersions = publishedVersions.stream().map(SemanticVersion::from) - .collect(Collectors.toList()); + .toList(); Optional compatibleVersion = selectCompatibleVersion(availableVersions, localVersion); if (compatibleVersion.isEmpty()) { diff --git a/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/comparator/DumbNodeListComparator.java b/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/comparator/DumbNodeListComparator.java index 3ed215aac0ed..3e34804c91c9 100644 --- a/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/comparator/DumbNodeListComparator.java +++ b/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/comparator/DumbNodeListComparator.java @@ -59,8 +59,8 @@ public class DumbNodeListComparator implements Comparator { } DumbNodeListComparator(NodeList newNodes, NodeList oldNodes, DiffKind nodeKind) { - this.newNodes = newNodes != null ? newNodes.stream().collect(Collectors.toList()) : null; - this.oldNodes = oldNodes != null ? oldNodes.stream().collect(Collectors.toList()) : null; + this.newNodes = newNodes != null ? newNodes.stream().toList() : null; + this.oldNodes = oldNodes != null ? oldNodes.stream().toList() : null; this.nodeKind = nodeKind; } diff --git a/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/comparator/FunctionComparator.java b/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/comparator/FunctionComparator.java index ff3cfdb3e4e3..b0e48a11371c 100644 --- a/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/comparator/FunctionComparator.java +++ b/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/comparator/FunctionComparator.java @@ -39,7 +39,6 @@ import java.util.LinkedList; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; import static io.ballerina.compiler.syntax.tree.SyntaxKind.ISOLATED_KEYWORD; import static io.ballerina.compiler.syntax.tree.SyntaxKind.PUBLIC_KEYWORD; @@ -164,8 +163,8 @@ private List compareFunctionQualifiers() { private List compareFunctionParams() { List paramDiffs = new ArrayList<>(); - List newParams = newNode.functionSignature().parameters().stream().collect(Collectors.toList()); - List oldParams = oldNode.functionSignature().parameters().stream().collect(Collectors.toList()); + List newParams = newNode.functionSignature().parameters().stream().toList(); + List oldParams = oldNode.functionSignature().parameters().stream().toList(); ParamListComparator paramComparator = new ParamListComparator(newParams, oldParams); paramComparator.computeDiff().ifPresent(diff -> diff --git a/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/comparator/ParamListComparator.java b/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/comparator/ParamListComparator.java index cb8a413b592d..09eea5bca0c7 100644 --- a/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/comparator/ParamListComparator.java +++ b/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/comparator/ParamListComparator.java @@ -111,15 +111,11 @@ public Optional> computeDiff() { } private String getParameterName(Node paramNode) { - switch (paramNode.kind()) { - case REQUIRED_PARAM: - return ((RequiredParameterNode) paramNode).paramName().orElseThrow().text(); - case DEFAULTABLE_PARAM: - return ((DefaultableParameterNode) paramNode).paramName().orElseThrow().text(); - case REST_PARAM: - return ((RestParameterNode) paramNode).paramName().orElseThrow().text(); - default: - return ""; // Todo - } + return switch (paramNode.kind()) { + case REQUIRED_PARAM -> ((RequiredParameterNode) paramNode).paramName().orElseThrow().text(); + case DEFAULTABLE_PARAM -> ((DefaultableParameterNode) paramNode).paramName().orElseThrow().text(); + case REST_PARAM -> ((RestParameterNode) paramNode).paramName().orElseThrow().text(); + default -> ""; // Todo + }; } } diff --git a/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/comparator/ServiceComparator.java b/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/comparator/ServiceComparator.java index 3fd125d3f169..9af1c5967f6d 100644 --- a/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/comparator/ServiceComparator.java +++ b/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/comparator/ServiceComparator.java @@ -43,7 +43,6 @@ import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.stream.Collectors; import static io.ballerina.compiler.syntax.tree.SyntaxKind.ISOLATED_KEYWORD; import static io.ballerina.semver.checker.util.SyntaxTreeUtils.getFunctionIdentifier; @@ -145,8 +144,8 @@ private List compareServiceTypeDesc() { private List compareAttachPoints() { // TODO: implement attach point comparator Optional diff = new DumbNodeListComparator<>( - newNode.absoluteResourcePath().stream().collect(Collectors.toList()), - oldNode.absoluteResourcePath().stream().collect(Collectors.toList())) + newNode.absoluteResourcePath().stream().toList(), + oldNode.absoluteResourcePath().stream().toList()) .computeDiff(); return diff.>map(Collections::singletonList).orElseGet(ArrayList::new); } @@ -160,8 +159,8 @@ private List compareListenerExpressions() { new DumbNodeComparator<>(newListener, oldListener, DiffKind.SERVICE_LISTENER_EXPR).computeDiff() .ifPresent(listenerDiffs::add); } else { - new DumbNodeListComparator<>(newNode.expressions().stream().collect(Collectors.toList()), - oldNode.expressions().stream().collect(Collectors.toList())).computeDiff() + new DumbNodeListComparator<>(newNode.expressions().stream().toList(), + oldNode.expressions().stream().toList()).computeDiff() .ifPresent(listenerDiffs::add); } diff --git a/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/util/DiffUtils.java b/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/util/DiffUtils.java index 3ce66bd615e6..0bbc9302b0b0 100644 --- a/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/util/DiffUtils.java +++ b/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/util/DiffUtils.java @@ -43,7 +43,7 @@ * * @since 2201.2.0 */ -public class DiffUtils { +public final class DiffUtils { // Attributes defined for the JSON representation of diffs. public static final String DIFF_ATTR_KIND = "kind"; @@ -53,6 +53,9 @@ public class DiffUtils { public static final String DIFF_ATTR_CHILDREN = "childDiffs"; private static final String UNKNOWN = "unknown"; + private DiffUtils() { + } + /** * Returns the summary of changes in string format based on the current version, last published version and the set * of detected changes. @@ -139,10 +142,10 @@ public static String stringifyDiff(Diff diff) { .append(getDiffSign(diff)) .append(" "); - if ((diff instanceof NodeDiff) && ((NodeDiff) diff).getMessage().isPresent()) { - sb.append(((NodeDiff) diff).getMessage().get()); - } else if ((diff instanceof NodeListDiff) && ((NodeListDiff) diff).getMessage().isPresent()) { - sb.append(((NodeListDiff) diff).getMessage().get()); + if ((diff instanceof NodeDiff nodeDiff) && nodeDiff.getMessage().isPresent()) { + sb.append(nodeDiff.getMessage().get()); + } else if ((diff instanceof NodeListDiff nodeListDiff) && nodeListDiff.getMessage().isPresent()) { + sb.append(nodeListDiff.getMessage().get()); } else { sb.append(diff.getKind() != null && diff.getKind() != DiffKind.UNKNOWN ? diff.getKind().toString() : getDiffTypeName(diff)) @@ -233,52 +236,42 @@ private static String getModuleName(ModuleDiff moduleDiff) { * @param diff diff type */ private static String getDiffSign(Diff diff) { - switch (diff.getType()) { - case NEW: - return "[++]"; - case REMOVED: - return "[--]"; - case MODIFIED: - return "[+-]"; - case UNKNOWN: - default: - return "[??]"; - } + return switch (diff.getType()) { + case NEW -> "[++]"; + case REMOVED -> "[--]"; + case MODIFIED -> "[+-]"; + default -> "[??]"; + }; } private static String getDiffVerb(Diff diff) { - switch (diff.getType()) { - case NEW: - return "added"; - case REMOVED: - return "removed"; - case MODIFIED: - return "modified"; - case UNKNOWN: - default: - return "?"; - } + return switch (diff.getType()) { + case NEW -> "added"; + case REMOVED -> "removed"; + case MODIFIED -> "modified"; + default -> "?"; + }; } private static String getDiffName(Diff diff) { - if (diff instanceof PackageDiff) { - return getPackageName((PackageDiff) diff); - } else if (diff instanceof ModuleDiff) { - return getModuleName((ModuleDiff) diff); - } else if (diff instanceof FunctionDiff) { - return getFunctionName((FunctionDiff) diff); - } else if (diff instanceof ServiceDiff) { - return getServiceName((ServiceDiff) diff); - } else if (diff instanceof ModuleVarDiff) { - return getModuleVariableName((ModuleVarDiff) diff); - } else if (diff instanceof ModuleConstantDiff) { - return getModuleConstantName((ModuleConstantDiff) diff); - } else if (diff instanceof ClassDiff) { - return getModuleClassName((ClassDiff) diff); - } else if (diff instanceof TypeDefinitionDiff) { - return getModuleTypeDefName((TypeDefinitionDiff) diff); - } else if (diff instanceof EnumDiff) { - return getModuleEnumName((EnumDiff) diff); + if (diff instanceof PackageDiff packageDiff) { + return getPackageName(packageDiff); + } else if (diff instanceof ModuleDiff moduleDiff) { + return getModuleName(moduleDiff); + } else if (diff instanceof FunctionDiff funcDiff) { + return getFunctionName(funcDiff); + } else if (diff instanceof ServiceDiff serviceDiff) { + return getServiceName(serviceDiff); + } else if (diff instanceof ModuleVarDiff moduleVarDiff) { + return getModuleVariableName(moduleVarDiff); + } else if (diff instanceof ModuleConstantDiff moduleConstantDiff) { + return getModuleConstantName(moduleConstantDiff); + } else if (diff instanceof ClassDiff classDiff) { + return getModuleClassName(classDiff); + } else if (diff instanceof TypeDefinitionDiff typeDefDiff) { + return getModuleTypeDefName(typeDefDiff); + } else if (diff instanceof EnumDiff enumDiff) { + return getModuleEnumName(enumDiff); } else { return UNKNOWN; } @@ -302,8 +295,7 @@ public static String getDiffTypeName(Diff diff) { return "type definition"; } else if (diff instanceof EnumDiff) { return "enum declaration"; - } else if (diff instanceof FunctionDiff) { - FunctionDiff functionDiff = (FunctionDiff) diff; + } else if (diff instanceof FunctionDiff functionDiff) { if (functionDiff.isResource()) { return "resource function"; } else if (functionDiff.isRemote()) { @@ -337,8 +329,7 @@ private static String getDiffIndentation(Diff diff) { return " ".repeat(6); } else if (diff instanceof ObjectFieldDiff) { return " ".repeat(6); - } else if (diff instanceof FunctionDiff) { - FunctionDiff functionDiff = (FunctionDiff) diff; + } else if (diff instanceof FunctionDiff functionDiff) { if (functionDiff.isResource()) { return " ".repeat(6); } else if (functionDiff.isRemote()) { diff --git a/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/util/PackageUtils.java b/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/util/PackageUtils.java index d32d80315c1e..150885d3f8f9 100644 --- a/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/util/PackageUtils.java +++ b/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/util/PackageUtils.java @@ -41,7 +41,10 @@ * * @since 2201.2.0 */ -public class PackageUtils { +public final class PackageUtils { + + private PackageUtils() { + } /** * Loads the target ballerina source package instance using the Project API, from the file path of the open/active @@ -52,15 +55,12 @@ public class PackageUtils { public static Package loadPackage(Path filePath) throws SemverToolException { try { Project project = PackageUtils.loadProject(filePath); - switch (project.kind()) { - case BUILD_PROJECT: - case BALA_PROJECT: - return project.currentPackage(); - case SINGLE_FILE_PROJECT: - throw new SemverToolException("semver checker tool is not applicable for single file projects."); - default: - throw new SemverToolException("semver checker tool is not applicable for " + project.kind().name()); - } + return switch (project.kind()) { + case BUILD_PROJECT, + BALA_PROJECT -> project.currentPackage(); + case SINGLE_FILE_PROJECT -> throw new SemverToolException( + "semver checker tool is not applicable for single file projects."); + }; } catch (ProjectException e) { throw new SemverToolException(String.format("failed to load Ballerina package at: '%s'%sreason: %s", filePath.toAbsolutePath(), System.lineSeparator(), e.getMessage())); diff --git a/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/util/SemverUtils.java b/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/util/SemverUtils.java index de5b2e08bb71..d0c2c3efca14 100644 --- a/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/util/SemverUtils.java +++ b/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/util/SemverUtils.java @@ -26,11 +26,14 @@ * * @since 2201.2.0 */ -public class SemverUtils { +public final class SemverUtils { private static final String SEMVER_FORMAT = "%d.%d.%d"; public static final String BAL_FILE_EXT = ".bal"; + private SemverUtils() { + } + public static String calculateSuggestedVersion(SemanticVersion prevVersion, PackageDiff packageDiff) { if (packageDiff == null) { return prevVersion.toString(); diff --git a/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/util/SyntaxTreeUtils.java b/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/util/SyntaxTreeUtils.java index 1e74a4a4e33f..54c7fe1bc4d2 100644 --- a/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/util/SyntaxTreeUtils.java +++ b/misc/semver-checker/modules/semver-checker-core/src/main/java/io/ballerina/semver/checker/util/SyntaxTreeUtils.java @@ -40,7 +40,10 @@ * * @since 2201.2.0 */ -public class SyntaxTreeUtils { +public final class SyntaxTreeUtils { + + private SyntaxTreeUtils() { + } /** * Returns the node typename of the given {@link SyntaxKind} instance. diff --git a/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/comparator/ClassComparatorTest.java b/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/comparator/ClassComparatorTest.java index 1ea0a8124600..78e6681c18b9 100644 --- a/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/comparator/ClassComparatorTest.java +++ b/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/comparator/ClassComparatorTest.java @@ -245,115 +245,42 @@ public void testClassResourceMethodReturn(JsonElement testData) throws Exception @DataProvider(name = "classTestDataProvider") public Object[] classTestDataProvider(Method method) throws SemverTestException { - String filePath; - switch (method.getName()) { - case "testClassAnnotation": - filePath = CLASS_ANNOTATION_TESTCASE; - break; - case "testClassDocumentation": - filePath = CLASS_DOCUMENTATION_TESTCASE; - break; - case "testClassIdentifier": - filePath = CLASS_IDENTIFIER_TESTCASE; - break; - case "testClassQualifier": - filePath = CLASS_QUALIFIER_TESTCASE; - break; - case "testAdvanceClass": - filePath = ADVANCE_CLASS_TESTCASE; - break; - - case "testClassMemberObjectFieldAnnotation": - filePath = OBJECT_FIELD_ANNOTATION_TESTCASE; - break; - case "testClassMemberObjectFieldDocumentation": - filePath = OBJECT_FIELD_DOCUMENTATION_TESTCASE; - break; - case "testClassMemberObjectFieldIdentifier": - filePath = OBJECT_FIELD_IDENTIFIER_TESTCASE; - break; - case "testClassMemberObjectFieldQualifier": - filePath = OBJECT_FIELD_QUALIFIER_TESTCASE; - break; - case "testClassMemberObjectFieldType": - filePath = OBJECT_FIELD_TYPE_TESTCASE; - break; - case "testClassMemberObjectFieldValue": - filePath = OBJECT_FIELD_VALUE_TESTCASE; - break; - - case "testClassMethodDocumentation": - filePath = METHOD_DOCUMENTATION_TESTCASE; - break; - case "testClassMethodBody": - filePath = METHOD_BODY_TESTCASE; - break; - case "testClassMethodIdentifier": - filePath = METHOD_IDENTIFIER_TESTCASE; - break; - case "testClassMethodParameter": - filePath = METHOD_PARAMETER_TESTCASE; - break; - case "testClassMethodQualifier": - filePath = METHOD_QUALIFIER_TESTCASE; - break; - case "testClassMethodReturn": - filePath = METHOD_RETURN_TESTCASE; - break; - case "testClassMethodAnnotation": - filePath = METHOD_ANNOTATION_TESTCASE; - break; - - case "testClassRemoteMethodDocumentation": - filePath = REMOTE_METHOD_DOCUMENTATION_TESTCASE; - break; - case "testClassRemoteMethodBody": - filePath = REMOTE_METHOD_BODY_TESTCASE; - break; - case "testClassRemoteMethodIdentifier": - filePath = REMOTE_METHOD_IDENTIFIER_TESTCASE; - break; - case "testClassRemoteMethodParameter": - filePath = REMOTE_METHOD_PARAMETER_TESTCASE; - break; - case "testClassRemoteMethodQualifier": - filePath = REMOTE_METHOD_QUALIFIER_TESTCASE; - break; - case "testClassRemoteMethodReturn": - filePath = REMOTE_METHOD_RETURN_TESTCASE; - break; - case "testClassRemoteMethodAnnotation": - filePath = REMOTE_METHOD_ANNOTATION_TESTCASE; - break; - - case "testClassResourceMethodDocumentation": - filePath = RESOURCE_METHOD_DOC_TESTCASE; - break; - case "testClassResourceMethodBody": - filePath = RESOURCE_METHOD_BODY_TESTCASE; - break; - case "testClassResourceMethodIdentifier": - filePath = RESOURCE_METHOD_IDENTIFIER_TESTCASE; - break; - case "testClassResourceMethodParameter": - filePath = RESOURCE_METHOD_PARAMETER_TESTCASE; - break; - case "testClassResourceMethodQualifier": - filePath = RESOURCE_METHOD_QUALIFIER_TESTCASE; - break; - case "testClassResourceMethodReturn": - filePath = RESOURCE_METHOD_RETURN_TESTCASE; - break; - case "testClassResourceMethodAnnotation": - filePath = RESOURCE_METHOD_ANNOTATION_TESTCASE; - break; - default: - filePath = null; - } + String filePath = switch (method.getName()) { + case "testClassAnnotation" -> CLASS_ANNOTATION_TESTCASE; + case "testClassDocumentation" -> CLASS_DOCUMENTATION_TESTCASE; + case "testClassIdentifier" -> CLASS_IDENTIFIER_TESTCASE; + case "testClassQualifier" -> CLASS_QUALIFIER_TESTCASE; + case "testAdvanceClass" -> ADVANCE_CLASS_TESTCASE; + case "testClassMemberObjectFieldAnnotation" -> OBJECT_FIELD_ANNOTATION_TESTCASE; + case "testClassMemberObjectFieldDocumentation" -> OBJECT_FIELD_DOCUMENTATION_TESTCASE; + case "testClassMemberObjectFieldIdentifier" -> OBJECT_FIELD_IDENTIFIER_TESTCASE; + case "testClassMemberObjectFieldQualifier" -> OBJECT_FIELD_QUALIFIER_TESTCASE; + case "testClassMemberObjectFieldType" -> OBJECT_FIELD_TYPE_TESTCASE; + case "testClassMemberObjectFieldValue" -> OBJECT_FIELD_VALUE_TESTCASE; + case "testClassMethodDocumentation" -> METHOD_DOCUMENTATION_TESTCASE; + case "testClassMethodBody" -> METHOD_BODY_TESTCASE; + case "testClassMethodIdentifier" -> METHOD_IDENTIFIER_TESTCASE; + case "testClassMethodParameter" -> METHOD_PARAMETER_TESTCASE; + case "testClassMethodQualifier" -> METHOD_QUALIFIER_TESTCASE; + case "testClassMethodReturn" -> METHOD_RETURN_TESTCASE; + case "testClassMethodAnnotation" -> METHOD_ANNOTATION_TESTCASE; + case "testClassRemoteMethodDocumentation" -> REMOTE_METHOD_DOCUMENTATION_TESTCASE; + case "testClassRemoteMethodBody" -> REMOTE_METHOD_BODY_TESTCASE; + case "testClassRemoteMethodIdentifier" -> REMOTE_METHOD_IDENTIFIER_TESTCASE; + case "testClassRemoteMethodParameter" -> REMOTE_METHOD_PARAMETER_TESTCASE; + case "testClassRemoteMethodQualifier" -> REMOTE_METHOD_QUALIFIER_TESTCASE; + case "testClassRemoteMethodReturn" -> REMOTE_METHOD_RETURN_TESTCASE; + case "testClassRemoteMethodAnnotation" -> REMOTE_METHOD_ANNOTATION_TESTCASE; + case "testClassResourceMethodDocumentation" -> RESOURCE_METHOD_DOC_TESTCASE; + case "testClassResourceMethodBody" -> RESOURCE_METHOD_BODY_TESTCASE; + case "testClassResourceMethodIdentifier" -> RESOURCE_METHOD_IDENTIFIER_TESTCASE; + case "testClassResourceMethodParameter" -> RESOURCE_METHOD_PARAMETER_TESTCASE; + case "testClassResourceMethodQualifier" -> RESOURCE_METHOD_QUALIFIER_TESTCASE; + case "testClassResourceMethodReturn" -> RESOURCE_METHOD_RETURN_TESTCASE; + case "testClassResourceMethodAnnotation" -> RESOURCE_METHOD_ANNOTATION_TESTCASE; + default -> throw new SemverTestException("Failed to load dataset for method: " + method.getName()); + }; - if (filePath == null) { - throw new SemverTestException("Failed to load dataset for method: " + method.getName()); - } try (FileReader reader = new FileReader(filePath)) { Object testCaseObject = JsonParser.parseReader(reader); JsonArray fileData = (JsonArray) testCaseObject; diff --git a/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/comparator/ConstantComparatorTest.java b/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/comparator/ConstantComparatorTest.java index b731a629b135..487555f3a912 100644 --- a/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/comparator/ConstantComparatorTest.java +++ b/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/comparator/ConstantComparatorTest.java @@ -84,36 +84,17 @@ public void testAdvanceConstant(JsonElement testData) throws Exception { @DataProvider(name = "constantTestDataProvider") public Object[] functionTestDataProvider(Method method) throws SemverTestException { - String filePath; - switch (method.getName()) { - case "testConstantAnnotation": - filePath = CONSTANT_ANNOTATION_TESTCASE; - break; - case "testConstantDocumentation": - filePath = CONSTANT_DOCUMENTATION_TESTCASE; - break; - case "testConstantExpression": - filePath = CONSTANT_EXPRESSION_TESTCASE; - break; - case "testConstantIdentifier": - filePath = CONSTANT_IDENTIFIER_TESTCASE; - break; - case "testConstantQualifier": - filePath = CONSTANT_QUALIFIER_TESTCASE; - break; - case "testConstantTypeDescriptor": - filePath = CONSTANT_TYPE_DESCRIPTOR_TESTCASE; - break; - case "testAdvanceConstant": - filePath = ADVANCE_CONSTANT_TESTCASE; - break; - default: - filePath = null; - } + String filePath = switch (method.getName()) { + case "testConstantAnnotation" -> CONSTANT_ANNOTATION_TESTCASE; + case "testConstantDocumentation" -> CONSTANT_DOCUMENTATION_TESTCASE; + case "testConstantExpression" -> CONSTANT_EXPRESSION_TESTCASE; + case "testConstantIdentifier" -> CONSTANT_IDENTIFIER_TESTCASE; + case "testConstantQualifier" -> CONSTANT_QUALIFIER_TESTCASE; + case "testConstantTypeDescriptor" -> CONSTANT_TYPE_DESCRIPTOR_TESTCASE; + case "testAdvanceConstant" -> ADVANCE_CONSTANT_TESTCASE; + default -> throw new SemverTestException("Failed to load dataset for method: " + method.getName()); + }; - if (filePath == null) { - throw new SemverTestException("Failed to load dataset for method: " + method.getName()); - } try (FileReader reader = new FileReader(filePath)) { Object testCaseObject = JsonParser.parseReader(reader); JsonArray fileData = (JsonArray) testCaseObject; diff --git a/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/comparator/EnumerationComparatorTest.java b/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/comparator/EnumerationComparatorTest.java index 0bea47b02d3a..df5271a0ce24 100644 --- a/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/comparator/EnumerationComparatorTest.java +++ b/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/comparator/EnumerationComparatorTest.java @@ -80,33 +80,16 @@ public void testAdvanceEnumeration(JsonElement testData) throws Exception { @DataProvider(name = "enumerationTestDataProvider") public Object[] enumerationTestDataProvider(Method method) throws SemverTestException { - String filePath; - switch (method.getName()) { - case "testEnumerationAnnotation": - filePath = ENUMERATION_ANNOTATION_TESTCASE; - break; - case "testEnumerationDocumentation": - filePath = ENUMERATION_DOCUMENTATION_TESTCASE; - break; - case "testEnumerationIdentifier": - filePath = ENUMERATION_IDENTIFIER_TESTCASE; - break; - case "testEnumerationQualifier": - filePath = ENUMERATION_QUALIFIER_TESTCASE; - break; - case "testEnumerationMember": - filePath = ENUMERATION_MEMBER_TESTCASE; - break; - case "testAdvanceEnumeration": - filePath = ADVANCE_ENUMERATION_TESTCASE; - break; - default: - filePath = null; - } + String filePath = switch (method.getName()) { + case "testEnumerationAnnotation" -> ENUMERATION_ANNOTATION_TESTCASE; + case "testEnumerationDocumentation" -> ENUMERATION_DOCUMENTATION_TESTCASE; + case "testEnumerationIdentifier" -> ENUMERATION_IDENTIFIER_TESTCASE; + case "testEnumerationQualifier" -> ENUMERATION_QUALIFIER_TESTCASE; + case "testEnumerationMember" -> ENUMERATION_MEMBER_TESTCASE; + case "testAdvanceEnumeration" -> ADVANCE_ENUMERATION_TESTCASE; + default -> throw new SemverTestException("Failed to load dataset for method: " + method.getName()); + }; - if (filePath == null) { - throw new SemverTestException("Failed to load dataset for method: " + method.getName()); - } try (FileReader reader = new FileReader(filePath)) { Object testCaseObject = JsonParser.parseReader(reader); JsonArray fileData = (JsonArray) testCaseObject; diff --git a/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/comparator/FunctionComparatorTest.java b/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/comparator/FunctionComparatorTest.java index 402af54f54c7..cc25696772b4 100644 --- a/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/comparator/FunctionComparatorTest.java +++ b/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/comparator/FunctionComparatorTest.java @@ -92,39 +92,18 @@ public void testAdvanceFunction(JsonElement testData) throws Exception { @DataProvider(name = "functionTestDataProvider") public Object[] functionTestDataProvider(Method method) throws SemverTestException { - String filePath; - switch (method.getName()) { - case "testFunctionAnnotation": - filePath = FUNCTION_ANNOTATION_TESTCASE; - break; - case "testFunctionDocumentation": - filePath = FUNCTION_DOCUMENTATION_TESTCASE; - break; - case "testFunctionBody": - filePath = FUNCTION_BODY_TESTCASE; - break; - case "testFunctionIdentifier": - filePath = FUNCTION_IDENTIFIER_TESTCASE; - break; - case "testFunctionParameter": - filePath = FUNCTION_PARAMETER_TESTCASE; - break; - case "testFunctionQualifier": - filePath = FUNCTION_QUALIFIER_TESTCASE; - break; - case "testFunctionReturn": - filePath = FUNCTION_RETURN_TESTCASE; - break; - case "testAdvanceFunction": - filePath = ADVANCE_FUNCTION_TESTCASE; - break; - default: - filePath = null; - } + String filePath = switch (method.getName()) { + case "testFunctionAnnotation" -> FUNCTION_ANNOTATION_TESTCASE; + case "testFunctionDocumentation" -> FUNCTION_DOCUMENTATION_TESTCASE; + case "testFunctionBody" -> FUNCTION_BODY_TESTCASE; + case "testFunctionIdentifier" -> FUNCTION_IDENTIFIER_TESTCASE; + case "testFunctionParameter" -> FUNCTION_PARAMETER_TESTCASE; + case "testFunctionQualifier" -> FUNCTION_QUALIFIER_TESTCASE; + case "testFunctionReturn" -> FUNCTION_RETURN_TESTCASE; + case "testAdvanceFunction" -> ADVANCE_FUNCTION_TESTCASE; + default -> throw new SemverTestException("Failed to load dataset for method: " + method.getName()); + }; - if (filePath == null) { - throw new SemverTestException("Failed to load dataset for method: " + method.getName()); - } try (FileReader reader = new FileReader(filePath)) { Object testCaseObject = JsonParser.parseReader(reader); JsonArray fileData = (JsonArray) testCaseObject; diff --git a/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/comparator/ServiceComparatorTest.java b/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/comparator/ServiceComparatorTest.java index 7007397df5be..5365986ef012 100644 --- a/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/comparator/ServiceComparatorTest.java +++ b/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/comparator/ServiceComparatorTest.java @@ -251,115 +251,42 @@ public void testResourceServiceMethodReturn(JsonElement testData) throws Excepti @DataProvider(name = "serviceTestDataProvider") public Object[] serviceTestDataProvider(Method method) throws SemverTestException { - String filePath; - switch (method.getName()) { - case "testServiceAnnotation": - filePath = SERVICE_ANNOTATION_TESTCASE; - break; - case "testServiceDocumentation": - filePath = SERVICE_DOCUMENTATION_TESTCASE; - break; - case "testServiceAttachPoint": - filePath = SERVICE_ATTACH_POINT_TESTCASE; - break; - case "testServiceListenerExpressionList": - filePath = SERVICE_LISTENER_TESTCASE; - break; - case "testServiceQualifier": - filePath = SERVICE_ISOLATED_QUALIFIER_TESTCASE; - break; - case "testAdvanceServiceDeclaration": - filePath = ADVANCE_SERVICE_TESTCASE; - break; - - case "testServiceMemberObjectFieldAnnotation": - filePath = OBJECT_FIELD_ANNOTATION_TESTCASE; - break; - case "testServiceMemberObjectFieldDocumentation": - filePath = OBJECT_FIELD_DOCUMENTATION_TESTCASE; - break; - case "testServiceMemberObjectFieldIdentifier": - filePath = OBJECT_FIELD_IDENTIFIER_TESTCASE; - break; - case "testServiceMemberObjectFieldQualifier": - filePath = OBJECT_FIELD_QUALIFIER_TESTCASE; - break; - case "testServiceMemberObjectFieldType": - filePath = OBJECT_FIELD_TYPE_TESTCASE; - break; - case "testServiceMemberObjectFieldValue": - filePath = OBJECT_FIELD_VALUE_TESTCASE; - break; - - case "testServiceMethodDocumentation": - filePath = METHOD_DOCUMENTATION_TESTCASE; - break; - case "testServiceMethodBody": - filePath = METHOD_BODY_TESTCASE; - break; - case "testServiceMethodIdentifier": - filePath = METHOD_IDENTIFIER_TESTCASE; - break; - case "testServiceMethodParameter": - filePath = METHOD_PARAMETER_TESTCASE; - break; - case "testServiceMethodQualifier": - filePath = METHOD_QUALIFIER_TESTCASE; - break; - case "testServiceMethodReturn": - filePath = METHOD_RETURN_TESTCASE; - break; - case "testServiceMethodAnnotation": - filePath = METHOD_ANNOTATION_TESTCASE; - break; - - case "testRemoteServiceMethodDocumentation": - filePath = REMOTE_METHOD_DOCUMENTATION_TESTCASE; - break; - case "testRemoteServiceMethodBody": - filePath = REMOTE_METHOD_BODY_TESTCASE; - break; - case "testRemoteServiceMethodIdentifier": - filePath = REMOTE_METHOD_IDENTIFIER_TESTCASE; - break; - case "testRemoteServiceMethodParameter": - filePath = REMOTE_METHOD_PARAMETER_TESTCASE; - break; - case "testRemoteServiceMethodQualifier": - filePath = REMOTE_METHOD_QUALIFIER_TESTCASE; - break; - case "testRemoteServiceMethodReturn": - filePath = REMOTE_METHOD_RETURN_TESTCASE; - break; - case "testRemoteServiceMethodAnnotation": - filePath = REMOTE_METHOD_ANNOTATION_TESTCASE; - break; - - case "testResourceServiceMethodDocumentation": - filePath = RESOURCE_METHOD_DOC_TESTCASE; - break; - case "testResourceServiceMethodBody": - filePath = RESOURCE_METHOD_BODY_TESTCASE; - break; - case "testResourceServiceMethodIdentifier": - filePath = RESOURCE_METHOD_IDENTIFIER_TESTCASE; - break; - case "testResourceServiceMethodParameter": - filePath = RESOURCE_METHOD_PARAMETER_TESTCASE; - break; - case "testResourceServiceMethodQualifier": - filePath = RESOURCE_METHOD_QUALIFIER_TESTCASE; - break; - case "testResourceServiceMethodReturn": - filePath = RESOURCE_METHOD_RETURN_TESTCASE; - break; - case "testResourceServiceMethodAnnotation": - filePath = RESOURCE_METHOD_ANNOTATION_TESTCASE; - break; - - default: - filePath = null; - } + String filePath = switch (method.getName()) { + case "testServiceAnnotation" -> SERVICE_ANNOTATION_TESTCASE; + case "testServiceDocumentation" -> SERVICE_DOCUMENTATION_TESTCASE; + case "testServiceAttachPoint" -> SERVICE_ATTACH_POINT_TESTCASE; + case "testServiceListenerExpressionList" -> SERVICE_LISTENER_TESTCASE; + case "testServiceQualifier" -> SERVICE_ISOLATED_QUALIFIER_TESTCASE; + case "testAdvanceServiceDeclaration" -> ADVANCE_SERVICE_TESTCASE; + case "testServiceMemberObjectFieldAnnotation" -> OBJECT_FIELD_ANNOTATION_TESTCASE; + case "testServiceMemberObjectFieldDocumentation" -> OBJECT_FIELD_DOCUMENTATION_TESTCASE; + case "testServiceMemberObjectFieldIdentifier" -> OBJECT_FIELD_IDENTIFIER_TESTCASE; + case "testServiceMemberObjectFieldQualifier" -> OBJECT_FIELD_QUALIFIER_TESTCASE; + case "testServiceMemberObjectFieldType" -> OBJECT_FIELD_TYPE_TESTCASE; + case "testServiceMemberObjectFieldValue" -> OBJECT_FIELD_VALUE_TESTCASE; + case "testServiceMethodDocumentation" -> METHOD_DOCUMENTATION_TESTCASE; + case "testServiceMethodBody" -> METHOD_BODY_TESTCASE; + case "testServiceMethodIdentifier" -> METHOD_IDENTIFIER_TESTCASE; + case "testServiceMethodParameter" -> METHOD_PARAMETER_TESTCASE; + case "testServiceMethodQualifier" -> METHOD_QUALIFIER_TESTCASE; + case "testServiceMethodReturn" -> METHOD_RETURN_TESTCASE; + case "testServiceMethodAnnotation" -> METHOD_ANNOTATION_TESTCASE; + case "testRemoteServiceMethodDocumentation" -> REMOTE_METHOD_DOCUMENTATION_TESTCASE; + case "testRemoteServiceMethodBody" -> REMOTE_METHOD_BODY_TESTCASE; + case "testRemoteServiceMethodIdentifier" -> REMOTE_METHOD_IDENTIFIER_TESTCASE; + case "testRemoteServiceMethodParameter" -> REMOTE_METHOD_PARAMETER_TESTCASE; + case "testRemoteServiceMethodQualifier" -> REMOTE_METHOD_QUALIFIER_TESTCASE; + case "testRemoteServiceMethodReturn" -> REMOTE_METHOD_RETURN_TESTCASE; + case "testRemoteServiceMethodAnnotation" -> REMOTE_METHOD_ANNOTATION_TESTCASE; + case "testResourceServiceMethodDocumentation" -> RESOURCE_METHOD_DOC_TESTCASE; + case "testResourceServiceMethodBody" -> RESOURCE_METHOD_BODY_TESTCASE; + case "testResourceServiceMethodIdentifier" -> RESOURCE_METHOD_IDENTIFIER_TESTCASE; + case "testResourceServiceMethodParameter" -> RESOURCE_METHOD_PARAMETER_TESTCASE; + case "testResourceServiceMethodQualifier" -> RESOURCE_METHOD_QUALIFIER_TESTCASE; + case "testResourceServiceMethodReturn" -> RESOURCE_METHOD_RETURN_TESTCASE; + case "testResourceServiceMethodAnnotation" -> RESOURCE_METHOD_ANNOTATION_TESTCASE; + default -> null; + }; if (filePath == null) { throw new SemverTestException("Failed to load dataset for method: " + method.getName()); diff --git a/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/comparator/TypeComparatorTest.java b/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/comparator/TypeComparatorTest.java index 11aa81447be4..8fc598e148e6 100644 --- a/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/comparator/TypeComparatorTest.java +++ b/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/comparator/TypeComparatorTest.java @@ -408,165 +408,57 @@ public void testOtherTypeUnion(JsonElement testData) throws Exception { @DataProvider(name = "typeDefinitionTestDataProvider") public Object[] typeDefinitionTestDataProvider(Method method) throws SemverTestException { - String filePath; - switch (method.getName()) { - case "testTypeAnnotation": - filePath = TYPE_ANNOTATION_TESTCASE; - break; - case "testTypeDocumentation": - filePath = TYPE_DOCUMENTATION_TESTCASE; - break; - case "testTypeIdentifier": - filePath = TYPE_IDENTIFIER_TESTCASE; - break; - case "testTypeQualifier": - filePath = TYPE_QUALIFIER_TESTCASE; - break; - case "testAdvanceType": - filePath = ADVANCE_TESTCASE; - break; - - case "testSimpleTypeBoolean": - filePath = SIMPLE_BOOLEAN_TESTCASE; - break; - case "testSimpleTypeFloat": - filePath = SIMPLE_FLOAT_TESTCASE; - break; - case "testSimpleTypeInt": - filePath = SIMPLE_INT_TESTCASE; - break; - case "testSimpleTypeNil": - filePath = SIMPLE_NIL_TESTCASE; - break; - - case "testSequenceTypeString": - filePath = SEQUENCE_STRING_TESTCASE; - break; - case "testSequenceTypeXml": - filePath = SEQUENCE_XML_TESTCASE; - break; - - case "testStructuredTypeList": - filePath = STRUCTURED_LIST_TESTCASE; - break; - case "testStructuredTypeMap": - filePath = STRUCTURED_MAP_TESTCASE; - break; - case "testStructuredTypeTable": - filePath = STRUCTURED_TABLE_TESTCASE; - break; - - case "testBehaviouralTypeError": - filePath = BEHAVIOURAL_ERROR_TESTCASE; - break; - case "testBehaviouralTypeFuture": - filePath = BEHAVIOURAL_FUTURE_TESTCASE; - break; - case "testBehaviouralTypeHandle": - filePath = BEHAVIOURAL_HANDLE_TESTCASE; - break; - case "testBehaviouralTypeStream": - filePath = BEHAVIOURAL_STREAM_TESTCASE; - break; - case "testBehaviouralTypeTypeDesc": - filePath = BEHAVIOURAL_TYPE_DESC_TESTCASE; - break; - - case "testBehaviouralTypeFunctionParameter": - filePath = BEHAVIOURAL_FUNCTION_PARAMETER_TESTCASE; - break; - case "testBehaviouralTypeFunctionQualifier": - filePath = BEHAVIOURAL_FUNCTION_QUALIFIER_TESTCASE; - break; - case "testBehaviouralTypeFunctionReturn": - filePath = BEHAVIOURAL_FUNCTION_RETURN_TESTCASE; - break; - - case "testBehaviouralTypeObjectMethodAnnotation": - filePath = BEHAVIOURAL_OBJ_METHOD_ANNOTATION_TESTCASE; - break; - case "testBehaviouralTypeObjectMethodDocumentation": - filePath = BEHAVIOURAL_OBJ_METHOD_DOCUMENTATION_TESTCASE; - break; - case "testBehaviouralTypeObjectMethodBody": - filePath = BEHAVIOURAL_OBJ_METHOD_BODY_TESTCASE; - break; - case "testBehaviouralTypeObjectMethodIdentifier": - filePath = BEHAVIOURAL_OBJ_METHOD_IDENTIFIER_TESTCASE; - break; - case "testBehaviouralTypeObjectMethodParameter": - filePath = BEHAVIOURAL_OBJ_METHOD_PARAMETER_TESTCASE; - break; - case "testBehaviouralTypeObjectMethodQualifier": - filePath = BEHAVIOURAL_OBJ_METHOD_QUALIFIER_TESTCASE; - break; - case "testBehaviouralTypeObjectMethodReturn": - filePath = BEHAVIOURAL_OBJ_METHOD_RETURN_TESTCASE; - break; - - case "testBehaviouralTypeObjectFieldAnnotation": - filePath = BEHAVIOURAL_OBJ_FIELD_ANNOTATION_TESTCASE; - break; - case "testBehaviouralTypeObjectFieldDocumentation": - filePath = BEHAVIOURAL_OBJ_FIELD_DOCUMENTATION_TESTCASE; - break; - case "testBehaviouralTypeObjectFieldIdentifier": - filePath = BEHAVIOURAL_OBJ_FIELD_IDENTIFIER_TESTCASE; - break; - case "testBehaviouralTypeObjectFieldQualifier": - filePath = BEHAVIOURAL_OBJ_FIELD_QUALIFIER_TESTCASE; - break; - case "testBehaviouralTypeObjectFieldType": - filePath = BEHAVIOURAL_OBJ_FIELD_TESTCASE; - break; - - case "testBehaviouralTypeObjectQualifier": - filePath = BEHAVIOURAL_OBJ_QUALIFIER_TESTCASE; - break; - - case "testOtherTypeAnyData": - filePath = OTHER_ANY_DATA_TESTCASE; - break; - case "testOtherTypeAnyType": - filePath = OTHER_ANY_TESTCASE; - break; - case "testOtherTypeByte": - filePath = OTHER_BYTE_TESTCASE; - break; - case "testOtherTypeDistinct": - filePath = OTHER_DISTINCT_TESTCASE; - break; - case "testOtherTypeIntersection": - filePath = OTHER_INTERSECTION_TESTCASE; - break; - case "testOtherTypeJsonType": - filePath = OTHER_JSON_TESTCASE; - break; - case "testOtherTypeNeverType": - filePath = OTHER_NEVER_TESTCASE; - break; - case "testOtherTypeOptional": - filePath = OTHER_OPTIONAL_TESTCASE; - break; - case "testOtherTypeReadOnly": - filePath = OTHER_READ_ONLY_TESTCASE; - break; - case "testOtherTypeRecord": - filePath = OTHER_RECORD_TESTCASE; - break; - case "testOtherTypeSingleton": - filePath = OTHER_SINGLETON_TESTCASE; - break; - case "testOtherTypeTypeReference": - filePath = OTHER_TYPE_REFERENCE_TESTCASE; - break; - case "testOtherTypeUnion": - filePath = OTHER_UNION_TESTCASE; - break; - - default: - filePath = null; - } + String filePath = switch (method.getName()) { + case "testTypeAnnotation" -> TYPE_ANNOTATION_TESTCASE; + case "testTypeDocumentation" -> TYPE_DOCUMENTATION_TESTCASE; + case "testTypeIdentifier" -> TYPE_IDENTIFIER_TESTCASE; + case "testTypeQualifier" -> TYPE_QUALIFIER_TESTCASE; + case "testAdvanceType" -> ADVANCE_TESTCASE; + case "testSimpleTypeBoolean" -> SIMPLE_BOOLEAN_TESTCASE; + case "testSimpleTypeFloat" -> SIMPLE_FLOAT_TESTCASE; + case "testSimpleTypeInt" -> SIMPLE_INT_TESTCASE; + case "testSimpleTypeNil" -> SIMPLE_NIL_TESTCASE; + case "testSequenceTypeString" -> SEQUENCE_STRING_TESTCASE; + case "testSequenceTypeXml" -> SEQUENCE_XML_TESTCASE; + case "testStructuredTypeList" -> STRUCTURED_LIST_TESTCASE; + case "testStructuredTypeMap" -> STRUCTURED_MAP_TESTCASE; + case "testStructuredTypeTable" -> STRUCTURED_TABLE_TESTCASE; + case "testBehaviouralTypeError" -> BEHAVIOURAL_ERROR_TESTCASE; + case "testBehaviouralTypeFuture" -> BEHAVIOURAL_FUTURE_TESTCASE; + case "testBehaviouralTypeHandle" -> BEHAVIOURAL_HANDLE_TESTCASE; + case "testBehaviouralTypeStream" -> BEHAVIOURAL_STREAM_TESTCASE; + case "testBehaviouralTypeTypeDesc" -> BEHAVIOURAL_TYPE_DESC_TESTCASE; + case "testBehaviouralTypeFunctionParameter" -> BEHAVIOURAL_FUNCTION_PARAMETER_TESTCASE; + case "testBehaviouralTypeFunctionQualifier" -> BEHAVIOURAL_FUNCTION_QUALIFIER_TESTCASE; + case "testBehaviouralTypeFunctionReturn" -> BEHAVIOURAL_FUNCTION_RETURN_TESTCASE; + case "testBehaviouralTypeObjectMethodAnnotation" -> BEHAVIOURAL_OBJ_METHOD_ANNOTATION_TESTCASE; + case "testBehaviouralTypeObjectMethodDocumentation" -> BEHAVIOURAL_OBJ_METHOD_DOCUMENTATION_TESTCASE; + case "testBehaviouralTypeObjectMethodBody" -> BEHAVIOURAL_OBJ_METHOD_BODY_TESTCASE; + case "testBehaviouralTypeObjectMethodIdentifier" -> BEHAVIOURAL_OBJ_METHOD_IDENTIFIER_TESTCASE; + case "testBehaviouralTypeObjectMethodParameter" -> BEHAVIOURAL_OBJ_METHOD_PARAMETER_TESTCASE; + case "testBehaviouralTypeObjectMethodQualifier" -> BEHAVIOURAL_OBJ_METHOD_QUALIFIER_TESTCASE; + case "testBehaviouralTypeObjectMethodReturn" -> BEHAVIOURAL_OBJ_METHOD_RETURN_TESTCASE; + case "testBehaviouralTypeObjectFieldAnnotation" -> BEHAVIOURAL_OBJ_FIELD_ANNOTATION_TESTCASE; + case "testBehaviouralTypeObjectFieldDocumentation" -> BEHAVIOURAL_OBJ_FIELD_DOCUMENTATION_TESTCASE; + case "testBehaviouralTypeObjectFieldIdentifier" -> BEHAVIOURAL_OBJ_FIELD_IDENTIFIER_TESTCASE; + case "testBehaviouralTypeObjectFieldQualifier" -> BEHAVIOURAL_OBJ_FIELD_QUALIFIER_TESTCASE; + case "testBehaviouralTypeObjectFieldType" -> BEHAVIOURAL_OBJ_FIELD_TESTCASE; + case "testBehaviouralTypeObjectQualifier" -> BEHAVIOURAL_OBJ_QUALIFIER_TESTCASE; + case "testOtherTypeAnyData" -> OTHER_ANY_DATA_TESTCASE; + case "testOtherTypeAnyType" -> OTHER_ANY_TESTCASE; + case "testOtherTypeByte" -> OTHER_BYTE_TESTCASE; + case "testOtherTypeDistinct" -> OTHER_DISTINCT_TESTCASE; + case "testOtherTypeIntersection" -> OTHER_INTERSECTION_TESTCASE; + case "testOtherTypeJsonType" -> OTHER_JSON_TESTCASE; + case "testOtherTypeNeverType" -> OTHER_NEVER_TESTCASE; + case "testOtherTypeOptional" -> OTHER_OPTIONAL_TESTCASE; + case "testOtherTypeReadOnly" -> OTHER_READ_ONLY_TESTCASE; + case "testOtherTypeRecord" -> OTHER_RECORD_TESTCASE; + case "testOtherTypeSingleton" -> OTHER_SINGLETON_TESTCASE; + case "testOtherTypeTypeReference" -> OTHER_TYPE_REFERENCE_TESTCASE; + case "testOtherTypeUnion" -> OTHER_UNION_TESTCASE; + default -> null; + }; if (filePath == null) { throw new SemverTestException("Failed to load dataset for method: " + method.getName()); diff --git a/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/comparator/VariableComparatorTest.java b/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/comparator/VariableComparatorTest.java index 54a00870b653..faa5bec2f7f1 100644 --- a/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/comparator/VariableComparatorTest.java +++ b/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/comparator/VariableComparatorTest.java @@ -84,32 +84,16 @@ public void testAdvanceVariable(JsonElement testData) throws Exception { @DataProvider(name = "variableTestDataProvider") public Object[] functionTestDataProvider(Method method) throws SemverTestException { - String filePath; - switch (method.getName()) { - case "testVariableAnnotation": - filePath = VARIABLE_ANNOTATION_TESTCASE; - break; - case "testVariableDocumentation": - filePath = VARIABLE_DOCUMENTATION_TESTCASE; - break; - case "testVariableValue": - filePath = VARIABLE_VALUE_TESTCASE; - break; - case "testVariableIdentifier": - filePath = VARIABLE_IDENTIFIER_TESTCASE; - break; - case "testVariableQualifier": - filePath = VARIABLE_QUALIFIER_TESTCASE; - break; - case "testVariableTypeDescriptor": - filePath = VARIABLE_TYPE_DESCRIPTOR_TESTCASE; - break; - case "testAdvanceVariable": - filePath = ADVANCE_VARIABLE_TESTCASE; - break; - default: - filePath = null; - } + String filePath = switch (method.getName()) { + case "testVariableAnnotation" -> VARIABLE_ANNOTATION_TESTCASE; + case "testVariableDocumentation" -> VARIABLE_DOCUMENTATION_TESTCASE; + case "testVariableValue" -> VARIABLE_VALUE_TESTCASE; + case "testVariableIdentifier" -> VARIABLE_IDENTIFIER_TESTCASE; + case "testVariableQualifier" -> VARIABLE_QUALIFIER_TESTCASE; + case "testVariableTypeDescriptor" -> VARIABLE_TYPE_DESCRIPTOR_TESTCASE; + case "testAdvanceVariable" -> ADVANCE_VARIABLE_TESTCASE; + default -> null; + }; if (filePath == null) { throw new SemverTestException("Failed to load dataset for method: " + method.getName()); diff --git a/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/util/FileUtils.java b/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/util/FileUtils.java index 5919466209d8..66ba0abf6fcd 100644 --- a/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/util/FileUtils.java +++ b/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/util/FileUtils.java @@ -28,7 +28,10 @@ * * @since 2201.2.0 */ -public class FileUtils { +public final class FileUtils { + + private FileUtils() { + } /** * @param file Name of the expected file diff --git a/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/util/ProjectUtils.java b/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/util/ProjectUtils.java index f3a8eb85fa69..c4a7aea619ef 100644 --- a/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/util/ProjectUtils.java +++ b/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/util/ProjectUtils.java @@ -31,7 +31,7 @@ * * @since 2201.2.0 */ -public class ProjectUtils { +public final class ProjectUtils { public static final String BAL_TOML_FILE_NAME = "Ballerina.toml"; public static final String BAL_FILE_EXT = ".bal"; @@ -42,6 +42,9 @@ public class ProjectUtils { private static final String PACKAGE_NAME = "test_package"; private static final String PACKAGE_VERSION = "1.0.0"; + private ProjectUtils() { + } + public static BuildProject createProject(String mainBalContent) throws Exception { // Creates a new directory in the default temporary file directory. tempProjectDir = Files.createTempDirectory(TEMP_DIR_PREFIX + System.currentTimeMillis()); diff --git a/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/util/TestUtils.java b/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/util/TestUtils.java index aa69908b5249..66e06b030193 100644 --- a/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/util/TestUtils.java +++ b/misc/semver-checker/modules/semver-checker-core/src/test/java/org/ballerinalang/semver/checker/util/TestUtils.java @@ -34,12 +34,15 @@ * * @since 2201.2.0 */ -public class TestUtils { +public final class TestUtils { private static final String JSON_ATTR_OLD_CODE = "oldCode"; private static final String JSON_ATTR_NEW_CODE = "newCode"; private static final String JSON_ATTR_EXPECTED_RESULTS = "expectedOutput"; + private TestUtils() { + } + /** * Executes test cases using the provided data set. * diff --git a/misc/syntax-api-calls-gen/src/main/java/io/ballerina/syntaxapicallsgen/SyntaxApiCallsGen.java b/misc/syntax-api-calls-gen/src/main/java/io/ballerina/syntaxapicallsgen/SyntaxApiCallsGen.java index 092d2ad4f78d..62e979fa8697 100644 --- a/misc/syntax-api-calls-gen/src/main/java/io/ballerina/syntaxapicallsgen/SyntaxApiCallsGen.java +++ b/misc/syntax-api-calls-gen/src/main/java/io/ballerina/syntaxapicallsgen/SyntaxApiCallsGen.java @@ -30,7 +30,11 @@ * * @since 2.0.0 */ -public class SyntaxApiCallsGen { +public final class SyntaxApiCallsGen { + + private SyntaxApiCallsGen() { + } + /** * Run the process with the given configurations. * diff --git a/misc/syntax-api-calls-gen/src/main/java/io/ballerina/syntaxapicallsgen/formatter/SegmentFormatter.java b/misc/syntax-api-calls-gen/src/main/java/io/ballerina/syntaxapicallsgen/formatter/SegmentFormatter.java index 7a1ed0e0c383..71394b1ad5ef 100644 --- a/misc/syntax-api-calls-gen/src/main/java/io/ballerina/syntaxapicallsgen/formatter/SegmentFormatter.java +++ b/misc/syntax-api-calls-gen/src/main/java/io/ballerina/syntaxapicallsgen/formatter/SegmentFormatter.java @@ -52,14 +52,11 @@ public static SegmentFormatter getFormatter(SyntaxApiCallsGenConfig config) thro * @return Created formatter. */ protected static SegmentFormatter getInternalFormatter(SyntaxApiCallsGenConfig config) { - switch (config.formatter()) { - case NONE: - return new NoFormatter(); - case VARIABLE: - return new VariableFormatter(); - default: - return new DefaultFormatter(); - } + return switch (config.formatter()) { + case NONE -> new NoFormatter(); + case VARIABLE -> new VariableFormatter(); + default -> new DefaultFormatter(); + }; } /** diff --git a/misc/syntax-api-calls-gen/src/main/java/io/ballerina/syntaxapicallsgen/formatter/VariableFormatter.java b/misc/syntax-api-calls-gen/src/main/java/io/ballerina/syntaxapicallsgen/formatter/VariableFormatter.java index e6e400ff1d83..228920970aab 100644 --- a/misc/syntax-api-calls-gen/src/main/java/io/ballerina/syntaxapicallsgen/formatter/VariableFormatter.java +++ b/misc/syntax-api-calls-gen/src/main/java/io/ballerina/syntaxapicallsgen/formatter/VariableFormatter.java @@ -23,10 +23,12 @@ import io.ballerina.syntaxapicallsgen.segment.Segment; import io.ballerina.syntaxapicallsgen.segment.factories.SegmentFactory; +import java.util.ArrayDeque; +import java.util.Deque; import java.util.HashMap; +import java.util.Iterator; import java.util.Locale; import java.util.Map; -import java.util.Stack; /** * Grouped Variable formatter. @@ -51,9 +53,9 @@ public class VariableFormatter extends SegmentFormatter { @Override public String format(Segment segment) { - if (segment instanceof NodeFactorySegment) { + if (segment instanceof NodeFactorySegment nodeFactorySegment) { variableCount = new HashMap<>(); - return MINUTIAE_LIST_DEF + processNode((NodeFactorySegment) segment); + return MINUTIAE_LIST_DEF + processNode(nodeFactorySegment); } throw new SyntaxApiCallsGenException("Expected a valid node segment but fount parsed segment of " + segment); } @@ -66,7 +68,7 @@ public String format(Segment segment) { */ private NamedContent processToken(NodeFactorySegment token) { StringBuilder stringBuilder = new StringBuilder(); - Stack params = new Stack<>(); + Deque params = new ArrayDeque<>(); token.forEach(params::push); NamedContent namedContent = new NamedContent(token.getType(), variableCount); @@ -75,8 +77,9 @@ private NamedContent processToken(NodeFactorySegment token) { // Define and add minutiae boolean minutiaeNodesPresent = false; if (params.size() >= 2) { - Segment lastSegment1 = params.get(params.size() - 1); - Segment lastSegment2 = params.get(params.size() - 2); + Iterator paramIterator = params.iterator(); + Segment lastSegment1 = paramIterator.next(); + Segment lastSegment2 = paramIterator.next(); if (lastSegment1 instanceof NodeFactorySegment && lastSegment2 instanceof NodeFactorySegment && ((NodeFactorySegment) lastSegment1).isMinutiae() @@ -95,7 +98,7 @@ private NamedContent processToken(NodeFactorySegment token) { // Add params and minutiae while (!params.isEmpty()) { - factorySegment.addParameter(params.remove(0)); + factorySegment.addParameter(params.removeLast()); } if (minutiaeNodesPresent) { @@ -130,8 +133,7 @@ private NamedContent processNode(NodeFactorySegment segment) { StringBuilder stringBuilder = new StringBuilder(); NodeFactorySegment factorySegment = segment.createCopy(); for (Segment child : segment) { - if (child instanceof NodeFactorySegment) { - NodeFactorySegment childFactoryCall = (NodeFactorySegment) child; + if (child instanceof NodeFactorySegment childFactoryCall) { NamedContent namedContent = processNode(childFactoryCall); stringBuilder.append(namedContent.content); factorySegment.addParameter(SegmentFactory.createCodeSegment(namedContent.name)); diff --git a/misc/syntax-api-calls-gen/src/main/java/io/ballerina/syntaxapicallsgen/parser/SyntaxApiCallsGenParser.java b/misc/syntax-api-calls-gen/src/main/java/io/ballerina/syntaxapicallsgen/parser/SyntaxApiCallsGenParser.java index 80db764d4026..38140935ede0 100644 --- a/misc/syntax-api-calls-gen/src/main/java/io/ballerina/syntaxapicallsgen/parser/SyntaxApiCallsGenParser.java +++ b/misc/syntax-api-calls-gen/src/main/java/io/ballerina/syntaxapicallsgen/parser/SyntaxApiCallsGenParser.java @@ -57,14 +57,11 @@ protected SyntaxApiCallsGenParser(long timeoutMs) { */ public static SyntaxApiCallsGenParser fromConfig(SyntaxApiCallsGenConfig config) { long timeoutMs = config.parserTimeout(); - switch (config.parser()) { - case EXPRESSION: - return new ExpressionParser(timeoutMs); - case STATEMENT: - return new StatementParser(timeoutMs); - default: - return new ModuleParser(timeoutMs); - } + return switch (config.parser()) { + case EXPRESSION -> new ExpressionParser(timeoutMs); + case STATEMENT -> new StatementParser(timeoutMs); + default -> new ModuleParser(timeoutMs); + }; } /** @@ -74,8 +71,7 @@ public static SyntaxApiCallsGenParser fromConfig(SyntaxApiCallsGenConfig config) * @param diagnostic Diagnostic to show. * @return The string with position highlighted. */ - public static String highlightDiagnostic(TextDocument textDocument, - io.ballerina.tools.diagnostics.Diagnostic diagnostic) { + public static String highlightDiagnostic(TextDocument textDocument, Diagnostic diagnostic) { // Get the source code String space = " "; String sourceLine = textDocument.line(diagnostic.location().lineRange().startLine().line()).text(); diff --git a/misc/syntax-api-calls-gen/src/main/java/io/ballerina/syntaxapicallsgen/segment/factories/MinutiaeSegmentFactory.java b/misc/syntax-api-calls-gen/src/main/java/io/ballerina/syntaxapicallsgen/segment/factories/MinutiaeSegmentFactory.java index 500ef2872a73..22ae0f7119d3 100644 --- a/misc/syntax-api-calls-gen/src/main/java/io/ballerina/syntaxapicallsgen/segment/factories/MinutiaeSegmentFactory.java +++ b/misc/syntax-api-calls-gen/src/main/java/io/ballerina/syntaxapicallsgen/segment/factories/MinutiaeSegmentFactory.java @@ -30,13 +30,17 @@ * * @since 2.0.0 */ -public class MinutiaeSegmentFactory { +public final class MinutiaeSegmentFactory { + private static final String CREATE_EMPTY_MINUTIAE_LIST_METHOD_NAME = "createEmptyMinutiaeList"; private static final String CREATE_MINUTIAE_LIST_METHOD_NAME = "createMinutiaeList"; private static final String CREATE_COMMENT_METHOD_NAME = "createCommentMinutiae"; private static final String CREATE_WHITESPACE_METHOD_NAME = "createWhitespaceMinutiae"; private static final String CREATE_EOL_METHOD_NAME = "createEndOfLineMinutiae"; + private MinutiaeSegmentFactory() { + } + /** * Converts a {@link MinutiaeList} to a {@link Segment}. * diff --git a/misc/syntax-api-calls-gen/src/main/java/io/ballerina/syntaxapicallsgen/segment/factories/NodeSegmentFactory.java b/misc/syntax-api-calls-gen/src/main/java/io/ballerina/syntaxapicallsgen/segment/factories/NodeSegmentFactory.java index d2ba8cdb9f93..be7b625bc6f2 100644 --- a/misc/syntax-api-calls-gen/src/main/java/io/ballerina/syntaxapicallsgen/segment/factories/NodeSegmentFactory.java +++ b/misc/syntax-api-calls-gen/src/main/java/io/ballerina/syntaxapicallsgen/segment/factories/NodeSegmentFactory.java @@ -67,10 +67,10 @@ public static NodeSegmentFactory fromConfig(SyntaxApiCallsGenConfig config) { public Segment createNodeSegment(Node node) { if (node == null) { return SegmentFactory.createNullSegment(); - } else if (node instanceof Token) { - return tokenSegmentFactory.createTokenSegment((Token) node); - } else if (node instanceof NonTerminalNode) { - return nonTerminalSegmentFactory.createNonTerminalSegment((NonTerminalNode) node); + } else if (node instanceof Token token) { + return tokenSegmentFactory.createTokenSegment(token); + } else if (node instanceof NonTerminalNode nonTerminalNode) { + return nonTerminalSegmentFactory.createNonTerminalSegment(nonTerminalNode); } else { throw new SyntaxApiCallsGenException("Expected non terminal or token. " + "Found unexpected node type for: " + node); diff --git a/misc/syntax-api-calls-gen/src/main/java/io/ballerina/syntaxapicallsgen/segment/factories/SegmentFactory.java b/misc/syntax-api-calls-gen/src/main/java/io/ballerina/syntaxapicallsgen/segment/factories/SegmentFactory.java index 695f86e059ba..a26a1b11d981 100644 --- a/misc/syntax-api-calls-gen/src/main/java/io/ballerina/syntaxapicallsgen/segment/factories/SegmentFactory.java +++ b/misc/syntax-api-calls-gen/src/main/java/io/ballerina/syntaxapicallsgen/segment/factories/SegmentFactory.java @@ -29,9 +29,13 @@ * * @since 2.0.0 */ -public class SegmentFactory { +public final class SegmentFactory { + private static final String NULL_LITERAL = "null"; + private SegmentFactory() { + } + /** * Creates a factory method to create given node type. * diff --git a/misc/syntax-api-calls-gen/src/test/java/io/ballerina/syntaxapicallsgen/test/FileReaderUtils.java b/misc/syntax-api-calls-gen/src/test/java/io/ballerina/syntaxapicallsgen/test/FileReaderUtils.java index bc58eb0aae0b..8f37151f5b83 100644 --- a/misc/syntax-api-calls-gen/src/test/java/io/ballerina/syntaxapicallsgen/test/FileReaderUtils.java +++ b/misc/syntax-api-calls-gen/src/test/java/io/ballerina/syntaxapicallsgen/test/FileReaderUtils.java @@ -32,9 +32,13 @@ * * @since 2.0.0 */ -public class FileReaderUtils { +public final class FileReaderUtils { + private static final String SPECIAL_DELIMITER = "\\A"; + private FileReaderUtils() { + } + /** * Reads a file path content from the resources directory. * diff --git a/misc/syntax-api-calls-gen/src/test/java/io/ballerina/syntaxapicallsgen/test/e2e/AbstractSegmentTest.java b/misc/syntax-api-calls-gen/src/test/java/io/ballerina/syntaxapicallsgen/test/e2e/AbstractSegmentTest.java index d2c6334d1c59..f6f830c5cad0 100644 --- a/misc/syntax-api-calls-gen/src/test/java/io/ballerina/syntaxapicallsgen/test/e2e/AbstractSegmentTest.java +++ b/misc/syntax-api-calls-gen/src/test/java/io/ballerina/syntaxapicallsgen/test/e2e/AbstractSegmentTest.java @@ -131,9 +131,8 @@ private TemplatePrivilegedAction(String javaCode) { @Override public TemplateCode run() { - try { + try (CachedCompiler compiler = new CachedCompiler(null, null)) { ClassLoader classLoader = new SegmentClassLoader(); - CachedCompiler compiler = new CachedCompiler(null, null); Class templateCodeImpl = compiler.loadFromJava(classLoader, TEMPLATE_PACKAGE_NAME, javaCode); return (TemplateCode) templateCodeImpl.getDeclaredConstructor().newInstance(); } catch (ReflectiveOperationException e) { diff --git a/misc/testerina/modules/testerina-compiler-plugin/src/main/java/org/ballerinalang/testerina/compiler/TestExecutionGenerationTask.java b/misc/testerina/modules/testerina-compiler-plugin/src/main/java/org/ballerinalang/testerina/compiler/TestExecutionGenerationTask.java index 690283f7161d..9f1c8ecb77a9 100644 --- a/misc/testerina/modules/testerina-compiler-plugin/src/main/java/org/ballerinalang/testerina/compiler/TestExecutionGenerationTask.java +++ b/misc/testerina/modules/testerina-compiler-plugin/src/main/java/org/ballerinalang/testerina/compiler/TestExecutionGenerationTask.java @@ -184,7 +184,7 @@ private static void generateClassMockedFunctionMapping(Package pack, SourceGener rootNode.accept(testFunctionVisitor); for (FunctionDefinitionNode func : testFunctionVisitor.getTestStaticFunctions()) { FunctionBodyNode functionBodyNode = func.functionBody(); - NodeList statements = ((FunctionBodyBlockNode) functionBodyNode).statements(); + NodeList statements = ((FunctionBodyBlockNode) functionBodyNode).statements(); for (int i = 0; i < statements.size(); i++) { StatementNode statementNode = (StatementNode) statements.get(i); diff --git a/misc/testerina/modules/testerina-compiler-plugin/src/main/java/org/ballerinalang/testerina/compiler/TesterinaCodeAnalyzer.java b/misc/testerina/modules/testerina-compiler-plugin/src/main/java/org/ballerinalang/testerina/compiler/TesterinaCodeAnalyzer.java index b54e0a675e4f..8f574120d739 100644 --- a/misc/testerina/modules/testerina-compiler-plugin/src/main/java/org/ballerinalang/testerina/compiler/TesterinaCodeAnalyzer.java +++ b/misc/testerina/modules/testerina-compiler-plugin/src/main/java/org/ballerinalang/testerina/compiler/TesterinaCodeAnalyzer.java @@ -50,13 +50,10 @@ public void init(CodeAnalysisContext analysisContext) { analysisContext.addSyntaxNodeAnalysisTask(syntaxNodeAnalysisContext -> { // Traverses class and service definition nodes to check if test definitions are specified within // the class for functions - if (syntaxNodeAnalysisContext.node() instanceof ClassDefinitionNode) { - ClassDefinitionNode classDefinitionNode = (ClassDefinitionNode) syntaxNodeAnalysisContext.node(); + if (syntaxNodeAnalysisContext.node() instanceof ClassDefinitionNode classDefinitionNode) { classDefinitionNode.members().forEach(member -> validateTestAnnotation(syntaxNodeAnalysisContext, member)); - } else if (syntaxNodeAnalysisContext.node() instanceof ServiceDeclarationNode) { - ServiceDeclarationNode serviceDeclarationNode = - (ServiceDeclarationNode) syntaxNodeAnalysisContext.node(); + } else if (syntaxNodeAnalysisContext.node() instanceof ServiceDeclarationNode serviceDeclarationNode) { serviceDeclarationNode.members().forEach(member -> validateTestAnnotation(syntaxNodeAnalysisContext, member)); } @@ -64,8 +61,7 @@ public void init(CodeAnalysisContext analysisContext) { } private static void validateTestAnnotation(SyntaxNodeAnalysisContext syntaxNodeAnalysisContext, Node member) { - if (member instanceof FunctionDefinitionNode) { - FunctionDefinitionNode funcDefNode = (FunctionDefinitionNode) member; + if (member instanceof FunctionDefinitionNode funcDefNode) { funcDefNode.metadata().ifPresent(metadata -> metadata.annotations().forEach(annotation -> { if (annotation.annotReference().kind() == SyntaxKind.QUALIFIED_NAME_REFERENCE) { diff --git a/misc/testerina/modules/testerina-compiler-plugin/src/main/java/org/ballerinalang/testerina/compiler/TesterinaCompilerPluginConstants.java b/misc/testerina/modules/testerina-compiler-plugin/src/main/java/org/ballerinalang/testerina/compiler/TesterinaCompilerPluginConstants.java index c8cab84384ee..8b26a1bb128f 100644 --- a/misc/testerina/modules/testerina-compiler-plugin/src/main/java/org/ballerinalang/testerina/compiler/TesterinaCompilerPluginConstants.java +++ b/misc/testerina/modules/testerina-compiler-plugin/src/main/java/org/ballerinalang/testerina/compiler/TesterinaCompilerPluginConstants.java @@ -23,7 +23,7 @@ * * @since 2201.3.0 */ -public class TesterinaCompilerPluginConstants { +public final class TesterinaCompilerPluginConstants { public static final String TEST_REGISTER_FUNCTION = "registerTest"; public static final String SET_OPTIONS_FUNCTION = "setTestOptions"; diff --git a/misc/testerina/modules/testerina-compiler-plugin/src/main/java/org/ballerinalang/testerina/compiler/TesterinaCompilerPluginUtils.java b/misc/testerina/modules/testerina-compiler-plugin/src/main/java/org/ballerinalang/testerina/compiler/TesterinaCompilerPluginUtils.java index f6e099bd7c69..7e19cc476a47 100644 --- a/misc/testerina/modules/testerina-compiler-plugin/src/main/java/org/ballerinalang/testerina/compiler/TesterinaCompilerPluginUtils.java +++ b/misc/testerina/modules/testerina-compiler-plugin/src/main/java/org/ballerinalang/testerina/compiler/TesterinaCompilerPluginUtils.java @@ -63,7 +63,10 @@ * * @since 2201.3.0 */ -public class TesterinaCompilerPluginUtils { +public final class TesterinaCompilerPluginUtils { + + private TesterinaCompilerPluginUtils() { + } public static void addSetTestOptionsCall(List statements) { // Add the statement, 'test:setTestOptions();' @@ -336,7 +339,7 @@ public static PositionalArgumentNode getPositionalArg(String argName) { NodeFactory.createSimpleNameReferenceNode(NodeFactory.createIdentifierToken(argName))); } - public static void writeCacheMapAsJson(Map map, Path path, String fileName) { + public static void writeCacheMapAsJson(Map map, Path path, String fileName) { if (!Files.exists(path)) { try { Files.createDirectories(path); diff --git a/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/TesterinaSystemPackageRepositoryProvider.java b/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/TesterinaSystemPackageRepositoryProvider.java index 8236a86a3ba6..5829f91d5bb3 100644 --- a/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/TesterinaSystemPackageRepositoryProvider.java +++ b/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/TesterinaSystemPackageRepositoryProvider.java @@ -22,6 +22,8 @@ import org.wso2.ballerinalang.compiler.packaging.repo.JarRepo; import org.wso2.ballerinalang.compiler.packaging.repo.Repo; +import java.nio.file.Path; + /** * This represents the standard Ballerina built-in system package repository provider. * @@ -31,7 +33,7 @@ public class TesterinaSystemPackageRepositoryProvider implements SystemPackageRepositoryProvider { @Override - public Repo loadRepository() { + public Repo loadRepository() { return new JarRepo(SystemPackageRepositoryProvider.getClassUri(this)); } diff --git a/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/core/AssertionDiffEvaluator.java b/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/core/AssertionDiffEvaluator.java index 77532cb0bd24..2440aa318422 100644 --- a/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/core/AssertionDiffEvaluator.java +++ b/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/core/AssertionDiffEvaluator.java @@ -33,11 +33,14 @@ /** * Evaluates assertion values to find the difference inline. */ -public class AssertionDiffEvaluator { +public final class AssertionDiffEvaluator { private static final String PARTITION_REGEX = "(?<=\\G.{80})"; private static final int MAX_ARG_LENGTH = 80; + private AssertionDiffEvaluator() { + } + /** * Get a list of String values by separating the lines from a String value. * @param value String @@ -47,12 +50,12 @@ private static List getValueList(String value) { List valueList = new ArrayList<>(); if (value.contains("\n")) { String[] valueArray = value.split("\n"); - for (int i = 0; i < valueArray.length; i++) { - if (valueArray[i].length() > MAX_ARG_LENGTH) { - String[] partitions = valueArray[i].split(PARTITION_REGEX); + for (String item : valueArray) { + if (item.length() > MAX_ARG_LENGTH) { + String[] partitions = item.split(PARTITION_REGEX); valueList.addAll(Arrays.asList(partitions)); } else { - valueList.add(valueArray[i]); + valueList.add(item); } } } else { diff --git a/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/core/BallerinaTypeCheck.java b/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/core/BallerinaTypeCheck.java index f21994085c2f..a6d9800af418 100644 --- a/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/core/BallerinaTypeCheck.java +++ b/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/core/BallerinaTypeCheck.java @@ -26,7 +26,7 @@ /** * Type check function ballerina/test#getBallerinaType. */ -public class BallerinaTypeCheck { +public final class BallerinaTypeCheck { /** * Mark the constructor as private. diff --git a/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/core/MockAnnotationProcessor.java b/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/core/MockAnnotationProcessor.java index d7bcf39d2813..656d70c443ab 100644 --- a/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/core/MockAnnotationProcessor.java +++ b/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/core/MockAnnotationProcessor.java @@ -54,7 +54,6 @@ import java.util.List; import java.util.Map; -import java.util.stream.Collectors; import static io.ballerina.runtime.api.constants.RuntimeConstants.FILE_NAME_PERIOD_SEPARATOR; @@ -108,7 +107,7 @@ public void process(SimpleVariableNode simpleVariableNode, List annotations) { BLangPackage parent = (BLangPackage) ((BLangFunction) functionNode).parent; String packageName = getPackageName(parent); - annotations = annotations.stream().distinct().collect(Collectors.toList()); + annotations = annotations.stream().distinct().toList(); // Iterate through all the annotations for (AnnotationAttachmentNode attachmentNode : annotations) { diff --git a/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/core/TestProcessor.java b/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/core/TestProcessor.java index ee435282707f..58415ce0e3d5 100644 --- a/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/core/TestProcessor.java +++ b/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/core/TestProcessor.java @@ -460,9 +460,9 @@ private void processGroupsAnnotation(AnnotationNode annotationNode, String funct if (VALUE_FIELD_NAME.equals(getFieldName(specificField))) { ExpressionNode valueExpr = specificField.valueExpr().orElse(null); if (SyntaxKind.LIST_CONSTRUCTOR == valueExpr.kind() && - valueExpr instanceof ListConstructorExpressionNode) { + valueExpr instanceof ListConstructorExpressionNode listConstructorExprNode) { List groupList = new ArrayList<>(); - ((ListConstructorExpressionNode) valueExpr).expressions().forEach( + listConstructorExprNode.expressions().forEach( expression -> groupList.add(getStringValue(expression))); if (isBeforeGroups) { suite.addBeforeGroupsFunction(functionName, groupList); @@ -512,9 +512,9 @@ private void processTestAnnotation(AnnotationNode annotationNode, String functio } if (GROUP_ANNOTATION_NAME.equals(fieldName)) { if (SyntaxKind.LIST_CONSTRUCTOR == valueExpr.kind() && - valueExpr instanceof ListConstructorExpressionNode) { + valueExpr instanceof ListConstructorExpressionNode listConstructorExprNode) { List groupList = new ArrayList<>(); - ((ListConstructorExpressionNode) valueExpr).expressions().forEach( + listConstructorExprNode.expressions().forEach( expression -> groupList.add(getStringValue(expression))); test.setGroups(groupList); suite.addTestToGroups(test); @@ -552,9 +552,9 @@ private void processTestAnnotation(AnnotationNode annotationNode, String functio } if (DEPENDS_ON_FUNCTIONS.equals(fieldName)) { if (SyntaxKind.LIST_CONSTRUCTOR == valueExpr.kind() && - valueExpr instanceof ListConstructorExpressionNode) { + valueExpr instanceof ListConstructorExpressionNode listConstructorExprNode) { List dependsOnFunctions = new ArrayList<>(); - ((ListConstructorExpressionNode) valueExpr).expressions().forEach( + listConstructorExprNode.expressions().forEach( expression -> dependsOnFunctions.add(getStringValue(expression))); for (String function : dependsOnFunctions) { test.addDependsOnTestFunction(function); diff --git a/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/natives/CommonUtils.java b/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/natives/CommonUtils.java index 3f7e32ec4010..0407093949d0 100644 --- a/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/natives/CommonUtils.java +++ b/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/natives/CommonUtils.java @@ -28,7 +28,10 @@ * * @since 2201.9.0 */ -public class CommonUtils { +public final class CommonUtils { + + private CommonUtils() { + } /** * Get the current time in milliseconds. @@ -45,7 +48,7 @@ public static BDecimal currentTimeInMillis() { * @param func The function pointer * @return Whether the parameters are concurrency safe */ - public static Object isFunctionParamConcurrencySafe(BFunctionPointer func) { + public static Object isFunctionParamConcurrencySafe(BFunctionPointer func) { FunctionType functionType = (FunctionType) func.getType(); Parameter[] functionParameters = functionType.getParameters(); for (Parameter functionParameter : functionParameters) { @@ -62,11 +65,11 @@ private static boolean isSubTypeOfReadOnly(Type type) { return true; } - if (!(type instanceof UnionType)) { + if (!(type instanceof UnionType unionType)) { return false; } - for (Type memberType : ((UnionType) type).getMemberTypes()) { + for (Type memberType : unionType.getMemberTypes()) { if (!isSubTypeOfReadOnly(memberType)) { return false; } diff --git a/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/natives/Executor.java b/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/natives/Executor.java index 2208d88f8c6e..996a0ec6cf56 100644 --- a/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/natives/Executor.java +++ b/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/natives/Executor.java @@ -39,7 +39,7 @@ * * @since 0.995.0 */ -public class Executor { +public final class Executor { private Executor() { } diff --git a/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/natives/io/FileUtils.java b/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/natives/io/FileUtils.java index aa1a0334a7c5..68dd961897ff 100644 --- a/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/natives/io/FileUtils.java +++ b/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/natives/io/FileUtils.java @@ -37,7 +37,10 @@ * * @since 2201.3.0 */ -public class FileUtils { +public final class FileUtils { + + private FileUtils() { + } public static void writeContent(BString targetPath, BString content) throws Exception { diff --git a/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/natives/io/StringUtils.java b/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/natives/io/StringUtils.java index 30715e99e9e6..77a5bf9703bb 100644 --- a/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/natives/io/StringUtils.java +++ b/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/natives/io/StringUtils.java @@ -48,7 +48,7 @@ * * @since 2.0.0 */ -public class StringUtils { +public final class StringUtils { private static final String CHAR_PREFIX = "$"; private static List specialCharacters = new ArrayList<>(Arrays.asList(",", "\\n", "\\r", "\\t", "\n", "\r", diff --git a/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/natives/mock/FunctionMock.java b/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/natives/mock/FunctionMock.java index cd5bb9167a5a..c63e32652b39 100644 --- a/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/natives/mock/FunctionMock.java +++ b/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/natives/mock/FunctionMock.java @@ -30,7 +30,10 @@ /** * Class that contains inter-op function related to function mocking. */ -public class FunctionMock { +public final class FunctionMock { + + private FunctionMock() { + } public static BError thenReturn(BObject caseObj) { BObject mockFunctionObj = caseObj.getObjectValue(StringUtils.fromString("mockFuncObj")); diff --git a/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/natives/mock/GenericMockObjectValue.java b/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/natives/mock/GenericMockObjectValue.java index cefa9aeb627c..9410493360e5 100644 --- a/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/natives/mock/GenericMockObjectValue.java +++ b/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/natives/mock/GenericMockObjectValue.java @@ -115,6 +115,7 @@ public boolean getBooleanValue(BString fieldName) { return false; } + @SuppressWarnings("rawtypes") @Override public BMap getMapValue(BString fieldName) { return null; diff --git a/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/natives/mock/MockConstants.java b/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/natives/mock/MockConstants.java index b9ad4781bf2f..04a7af134284 100644 --- a/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/natives/mock/MockConstants.java +++ b/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/natives/mock/MockConstants.java @@ -24,7 +24,7 @@ /** * Constants related to mocking. */ -public class MockConstants { +public final class MockConstants { public static final String DEFAULT_MOCK_OBJ_ANON = "$anonType$"; public static final String FUNCTION_CALL_PLACEHOLDER = "__CALL__"; @@ -57,4 +57,7 @@ public class MockConstants { public static final String REST_PARAMETER_INDICATOR = "::"; public static final String REST_PARAM_PLACEHOLDER = "^^"; public static final String CASE_ID_DELIMITER = "-"; + + private MockConstants() { + } } diff --git a/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/natives/mock/ObjectMock.java b/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/natives/mock/ObjectMock.java index c7d6040f90c6..d53085fc89a0 100644 --- a/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/natives/mock/ObjectMock.java +++ b/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/natives/mock/ObjectMock.java @@ -54,7 +54,7 @@ /** * Class that contains inter-op function related to mocking. */ -public class ObjectMock { +public final class ObjectMock { private ObjectMock() { } @@ -72,8 +72,8 @@ public static BObject mock(BTypedesc bTypedesc, ObjectValue objectValue) { // handle user-defined mock object if (objectValueType.getMethods().length == 0 && objectValueType.getFields().isEmpty() && - (objectValueType instanceof BClientType && - ((BClientType) objectValueType).getResourceMethods().length == 0)) { + (objectValueType instanceof BClientType bClientType && + bClientType.getResourceMethods().length == 0)) { String detail = "mock object type '" + objectValueType.getName() + "' should have at least one member function or field declared."; throw ErrorCreator.createError( @@ -90,8 +90,8 @@ public static BObject mock(BTypedesc bTypedesc, ObjectValue objectValue) { throw error; } } - if (objectValueType instanceof BClientType) { - for (MethodType attachedFunction : ((BClientType) objectValueType).getResourceMethods()) { + if (objectValueType instanceof BClientType bClientType) { + for (MethodType attachedFunction : bClientType.getResourceMethods()) { BError error = validateFunctionSignatures(attachedFunction, ((BClientType) bTypedesc.getDescribingType()).getResourceMethods()); if (error != null) { @@ -232,7 +232,7 @@ private static boolean validateAccessor(String resourcePath, String accessor, Re * @param pathParams path parameters map provided by the user * @return an optional error if a validation fails */ - public static BError validatePathParams(BObject caseObj, BMap pathParams) { + public static BError validatePathParams(BObject caseObj, BMap pathParams) { String functionName = caseObj.getStringValue(StringUtils.fromString(MockConstants.FUNCTION_NAME)).toString(); String[] pathSegments = functionName.split(MockConstants.PATH_SEPARATOR); for (int i = 0; i < pathSegments.length; i++) { @@ -323,12 +323,12 @@ public static BError validateArguments(BObject caseObj) { // validate if each argument is compatible with the type given in the function signature int i = 0; - for (BIterator it = argsList.getIterator(); it.hasNext(); i++) { + for (BIterator it = argsList.getIterator(); it.hasNext(); i++) { Type paramType = TypeUtils.getImpliedType(attachedFunction.getType().getParameters()[i].type); - if (paramType instanceof UnionType) { + if (paramType instanceof UnionType unionType) { Object arg = it.next(); boolean isTypeAvailable = false; - List memberTypes = ((UnionType) paramType).getMemberTypes(); + List memberTypes = unionType.getMemberTypes(); for (Type memberType : memberTypes) { if (TypeChecker.checkIsType(arg, memberType)) { isTypeAvailable = true; @@ -398,14 +398,14 @@ public static BError validatePathArgs(BObject caseObj) { // validate if each argument is compatible with the type given in the function signature int counter = 0; - for (BIterator bIterator = argsList.getIterator(); bIterator.hasNext(); counter++) { + for (BIterator bIterator = argsList.getIterator(); bIterator.hasNext(); counter++) { String detail = "incorrect type of path provided for '" + pathParamPlaceHolder[counter] + "' to mock the function '" + functionName; Type paramType = TypeUtils.getImpliedType(attachedFunction.getType().getParameters()[counter].type); - if (paramType instanceof UnionType) { + if (paramType instanceof UnionType unionType) { Object arg = bIterator.next(); boolean isTypeAvailable = false; - List memberTypes = ((UnionType) paramType).getMemberTypes(); + List memberTypes = unionType.getMemberTypes(); for (Type memberType : memberTypes) { if (TypeChecker.checkIsType(arg, memberType)) { isTypeAvailable = true; @@ -478,15 +478,15 @@ public static BError validateResourceArguments(BObject caseObj) { // validate if each argument is compatible with the type given in the function signature int counter = 0; - for (BIterator bIterator = argsList.getIterator(); bIterator.hasNext(); counter++) { + for (BIterator bIterator = argsList.getIterator(); bIterator.hasNext(); counter++) { String detail = "incorrect type of argument provided at position '" + (counter + 1) + "' " + "to mock the function '" + functionName; Type paramType = TypeUtils.getImpliedType(attachedFunction.getType() .getParameters()[counter + pathSegmentCount].type); - if (paramType instanceof UnionType) { + if (paramType instanceof UnionType unionType) { Object arg = bIterator.next(); boolean isTypeAvailable = false; - List memberTypes = ((UnionType) paramType).getMemberTypes(); + List memberTypes = unionType.getMemberTypes(); for (Type memberType : memberTypes) { if (TypeChecker.checkIsType(arg, memberType)) { isTypeAvailable = true; @@ -845,16 +845,13 @@ private static boolean validateReturnValueForResourcePath( private static boolean isValidReturnValue(Object returnVal, MethodType attachedFunction) { Type functionReturnType = TypeUtils.getImpliedType( attachedFunction.getType().getReturnParameterType()); - switch (functionReturnType.getTag()) { - case TypeTags.UNION_TAG: - return validateUnionValue(returnVal, (UnionType) functionReturnType); - case TypeTags.STREAM_TAG: - return validateStreamValue(returnVal, (StreamType) functionReturnType); - case TypeTags.PARAMETERIZED_TYPE_TAG: - return validateParameterizedValue(returnVal, (ParameterizedType) functionReturnType); - default: - return TypeChecker.checkIsType(returnVal, functionReturnType); - } + return switch (functionReturnType.getTag()) { + case TypeTags.UNION_TAG -> validateUnionValue(returnVal, (UnionType) functionReturnType); + case TypeTags.STREAM_TAG -> validateStreamValue(returnVal, (StreamType) functionReturnType); + case TypeTags.PARAMETERIZED_TYPE_TAG -> + validateParameterizedValue(returnVal, (ParameterizedType) functionReturnType); + default -> TypeChecker.checkIsType(returnVal, functionReturnType); + }; } /** @@ -899,8 +896,8 @@ private static BError validateFunctionSignatures(MethodType func, Type paramTypeAttachedFunc = TypeUtils.getImpliedType(attachedFunction.getType().getParameters()[i].type); Type paramType = TypeUtils.getImpliedType(parameters[i].type); - if (paramTypeAttachedFunc instanceof UnionType) { - if (!(paramType instanceof UnionType)) { + if (paramTypeAttachedFunc instanceof UnionType unionParamTypeAttachedFunc) { + if (!(paramType instanceof UnionType unionParamType)) { String detail = "incompatible parameter type provided at position " + (i + 1) + " in" + " function '" + functionName + "()'. parameter should be of union type "; return ErrorCreator.createError( @@ -910,9 +907,8 @@ private static BError validateFunctionSignatures(MethodType func, null, new MapValueImpl<>(PredefinedTypes.TYPE_ERROR_DETAIL)); } else { - Type[] memberTypes = - ((UnionType) paramTypeAttachedFunc).getMemberTypes().toArray(new Type[0]); - Type[] providedTypes = ((UnionType) paramType).getMemberTypes().toArray(new Type[0]); + Type[] memberTypes = unionParamTypeAttachedFunc.getMemberTypes().toArray(new Type[0]); + Type[] providedTypes = unionParamType.getMemberTypes().toArray(new Type[0]); for (int j = 0; j < memberTypes.length; j++) { if (!TypeChecker.checkIsType(providedTypes[j], memberTypes[j])) { BString detail = StringUtils diff --git a/misc/testerina/modules/testerina-runtime/src/main/java/org/ballerinalang/test/runtime/BTestMain.java b/misc/testerina/modules/testerina-runtime/src/main/java/org/ballerinalang/test/runtime/BTestMain.java index d4902ec5ee91..f19fec562cc8 100644 --- a/misc/testerina/modules/testerina-runtime/src/main/java/org/ballerinalang/test/runtime/BTestMain.java +++ b/misc/testerina/modules/testerina-runtime/src/main/java/org/ballerinalang/test/runtime/BTestMain.java @@ -67,95 +67,96 @@ /** * Main class to init the test suit. */ -public class BTestMain { +public final class BTestMain { + private static final PrintStream out = System.out; static TestReport testReport; static ClassLoader classLoader; static Map> classVsMockFunctionsMap = new HashMap<>(); + private BTestMain() { + } + public static void main(String[] args) throws IOException { int exitStatus = 0; int result; - if (args.length >= 4) { //running using the suite json - boolean isFatJarExecution = Boolean.parseBoolean(args[0]); - Path testSuiteJsonPath = Paths.get(args[1]); - Path targetPath = Paths.get(args[2]); - Path testCache = targetPath.resolve(ProjectConstants.CACHES_DIR_NAME) - .resolve(ProjectConstants.TESTS_CACHE_DIR_NAME); - String jacocoAgentJarPath = args[3]; - boolean report = Boolean.parseBoolean(args[4]); - boolean coverage = Boolean.parseBoolean(args[5]); - - if (report || coverage) { - testReport = new TestReport(); - } + if (args.length < 4) { + Runtime.getRuntime().exit(1); + } + //running using the suite json + boolean isFatJarExecution = Boolean.parseBoolean(args[0]); + Path testSuiteJsonPath = Paths.get(args[1]); + Path targetPath = Paths.get(args[2]); + Path testCache = targetPath.resolve(ProjectConstants.CACHES_DIR_NAME) + .resolve(ProjectConstants.TESTS_CACHE_DIR_NAME); + String jacocoAgentJarPath = args[3]; + boolean report = Boolean.parseBoolean(args[4]); + boolean coverage = Boolean.parseBoolean(args[5]); + + if (report || coverage) { + testReport = new TestReport(); + } - out.println(); - out.print("Running Tests"); - if (coverage) { - out.print(" with Coverage"); + out.println(); + out.print("Running Tests"); + if (coverage) { + out.print(" with Coverage"); + } + out.println(); + + try (InputStream is = isFatJarExecution ? + BTestMain.class.getResourceAsStream(TesterinaConstants.PATH_SEPARATOR + testSuiteJsonPath) : null) { + BufferedReader br; + if (is != null) { + br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)); + } else { + br = Files.newBufferedReader(testSuiteJsonPath, StandardCharsets.UTF_8); } - out.println(); - - try (InputStream is = isFatJarExecution ? - BTestMain.class.getResourceAsStream(TesterinaConstants.PATH_SEPARATOR - + testSuiteJsonPath) - : null) { - BufferedReader br; - if (is != null) { - br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)); - } else { - br = Files.newBufferedReader(testSuiteJsonPath, StandardCharsets.UTF_8); - } - Gson gson = new Gson(); - Map testSuiteMap = gson.fromJson(br, - new TypeToken>() { }.getType()); - if (!testSuiteMap.isEmpty()) { - for (Map.Entry entry : testSuiteMap.entrySet()) { - String moduleName = entry.getKey(); - TestSuite testSuite = entry.getValue(); - String packageName = testSuite.getPackageName(); - out.println("\n\t" + (moduleName.equals(packageName) ? - (moduleName.equals(TesterinaConstants.DOT) ? testSuite.getSourceFileName() : moduleName) - : packageName + TesterinaConstants.DOT + moduleName)); - - testSuite.setModuleName(moduleName); - List testExecutionDependencies = testSuite.getTestExecutionDependencies(); - - if (isFatJarExecution && !testSuite.getMockFunctionNamesMap().isEmpty()) { - classLoader = createInitialCustomClassLoader(); - } else { - // Even if it is fat jar execution but there are no mock functions, - // We can use the URLClassLoader - classLoader = createURLClassLoader(getURLList(testExecutionDependencies)); - } + Gson gson = new Gson(); + Map testSuiteMap = gson.fromJson(br, new TypeToken<>() { }); + if (!testSuiteMap.isEmpty()) { + for (Map.Entry entry : testSuiteMap.entrySet()) { + String moduleName = entry.getKey(); + TestSuite testSuite = entry.getValue(); + String packageName = testSuite.getPackageName(); + out.println("\n\t" + (moduleName.equals(packageName) ? + (moduleName.equals(TesterinaConstants.DOT) ? testSuite.getSourceFileName() : moduleName) + : packageName + TesterinaConstants.DOT + moduleName)); - if (!testSuite.getMockFunctionNamesMap().isEmpty()) { - if (coverage) { - testExecutionDependencies.add(jacocoAgentJarPath); - } - String instrumentDir = testCache.resolve(TesterinaConstants.COVERAGE_DIR) - .resolve(TesterinaConstants.JACOCO_INSTRUMENTED_DIR).toString(); - replaceMockedFunctions(testSuite, testExecutionDependencies, instrumentDir, - coverage, isFatJarExecution); - } - String[] testArgs = new String[]{targetPath.toString(), packageName, moduleName}; - for (int i = 4; i < args.length; i++) { - testArgs = Arrays.copyOf(testArgs, testArgs.length + 1); - testArgs[testArgs.length - 1] = args[i]; + testSuite.setModuleName(moduleName); + List testExecutionDependencies = testSuite.getTestExecutionDependencies(); + + if (isFatJarExecution && !testSuite.getMockFunctionNamesMap().isEmpty()) { + classLoader = createInitialCustomClassLoader(); + } else { + // Even if it is fat jar execution but there are no mock functions, + // We can use the URLClassLoader + classLoader = createURLClassLoader(getURLList(testExecutionDependencies)); + } + + if (!testSuite.getMockFunctionNamesMap().isEmpty()) { + if (coverage) { + testExecutionDependencies.add(jacocoAgentJarPath); } - result = startTestSuit(Paths.get(testSuite.getSourceRootPath()), testSuite, classLoader, - testArgs); - exitStatus = (result == 1) ? result : exitStatus; + String instrumentDir = testCache.resolve(TesterinaConstants.COVERAGE_DIR) + .resolve(TesterinaConstants.JACOCO_INSTRUMENTED_DIR).toString(); + replaceMockedFunctions(testSuite, testExecutionDependencies, instrumentDir, + coverage, isFatJarExecution); } - } else { - exitStatus = 1; + String[] testArgs = new String[]{targetPath.toString(), packageName, moduleName}; + for (int i = 4; i < args.length; i++) { + testArgs = Arrays.copyOf(testArgs, testArgs.length + 1); + testArgs[testArgs.length - 1] = args[i]; + } + result = startTestSuit(Paths.get(testSuite.getSourceRootPath()), testSuite, classLoader, + testArgs); + exitStatus = (result == 1) ? result : exitStatus; } - br.close(); + } else { + exitStatus = 1; } - } else { - exitStatus = 1; + br.close(); } Runtime.getRuntime().exit(exitStatus); } @@ -326,14 +327,9 @@ public static byte[] getModifiedClassBytes(String className, List functi private static byte[] replaceMethodBody(Method method, Method mockMethod, String instrumentDir, boolean coverage) { Class clazz = method.getDeclaringClass(); ClassReader cr; - try { - InputStream ins; - if (coverage) { - String instrumentedClassPath = instrumentDir + "/" + clazz.getName().replace(".", "/") + ".class"; - ins = new FileInputStream(instrumentedClassPath); - } else { - ins = clazz.getResourceAsStream(clazz.getSimpleName() + ".class"); - } + try (InputStream ins = coverage ? new FileInputStream( + instrumentDir + "/" + clazz.getName().replace(".", "/") + ".class") : + clazz.getResourceAsStream(clazz.getSimpleName() + ".class")) { cr = new ClassReader(requireNonNull(ins)); } catch (IOException e) { throw new BallerinaTestException("failed to get the class reader object for the class " diff --git a/misc/testerina/modules/testerina-runtime/src/main/java/org/ballerinalang/test/runtime/entity/CoverageReport.java b/misc/testerina/modules/testerina-runtime/src/main/java/org/ballerinalang/test/runtime/entity/CoverageReport.java index a84f893d792d..020bde2d9756 100644 --- a/misc/testerina/modules/testerina-runtime/src/main/java/org/ballerinalang/test/runtime/entity/CoverageReport.java +++ b/misc/testerina/modules/testerina-runtime/src/main/java/org/ballerinalang/test/runtime/entity/CoverageReport.java @@ -58,6 +58,7 @@ import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.stream.Stream; import static io.ballerina.identifier.Utils.decodeIdentifier; import static org.ballerinalang.test.runtime.util.TesterinaConstants.BIN_DIR; @@ -618,17 +619,14 @@ private List getExclusionJarList(JBallerinaBackend jBallerinaBackend, Pack } private List getPlatformLibsList(JBallerinaBackend jBallerinaBackend, Package pkg) { - List platformLibsList = new ArrayList<>(); - Collection otherJarDependencies = jBallerinaBackend.platformLibraryDependencies( - pkg.packageId(), PlatformLibraryScope.DEFAULT); - otherJarDependencies.addAll(jBallerinaBackend.platformLibraryDependencies( - pkg.packageId(), PlatformLibraryScope.PROVIDED)); - for (PlatformLibrary otherJarDependency : otherJarDependencies) { - if (!platformLibsList.contains(otherJarDependency.path())) { - platformLibsList.add(otherJarDependency.path()); - } - } - return platformLibsList; + return Stream.concat( + jBallerinaBackend.platformLibraryDependencies( + pkg.packageId(), PlatformLibraryScope.DEFAULT).stream(), + jBallerinaBackend.platformLibraryDependencies( + pkg.packageId(), PlatformLibraryScope.PROVIDED).stream()) + .map(PlatformLibrary::path) + .distinct() + .toList(); } private List getDependencyJarList(JBallerinaBackend jBallerinaBackend) { @@ -645,10 +643,12 @@ private List getDependencyJarList(JBallerinaBackend jBallerinaBackend) { dependencyPathList.add(generatedJarLibrary.path()); } } - Collection otherJarDependencies = jBallerinaBackend.platformLibraryDependencies( - pkg.packageId(), PlatformLibraryScope.DEFAULT); - otherJarDependencies.addAll(jBallerinaBackend.platformLibraryDependencies( - pkg.packageId(), PlatformLibraryScope.PROVIDED)); + Collection otherJarDependencies = Stream.concat( + jBallerinaBackend.platformLibraryDependencies( + pkg.packageId(), PlatformLibraryScope.DEFAULT).stream(), + jBallerinaBackend.platformLibraryDependencies( + pkg.packageId(), PlatformLibraryScope.PROVIDED).stream()).toList(); + for (PlatformLibrary otherJarDependency : otherJarDependencies) { if (!dependencyPathList.contains(otherJarDependency.path())) { dependencyPathList.add(otherJarDependency.path()); diff --git a/misc/testerina/modules/testerina-runtime/src/main/java/org/ballerinalang/test/runtime/entity/PartialCoverageModifiedCounter.java b/misc/testerina/modules/testerina-runtime/src/main/java/org/ballerinalang/test/runtime/entity/PartialCoverageModifiedCounter.java index d8e009513d88..cef9b34f3ac2 100644 --- a/misc/testerina/modules/testerina-runtime/src/main/java/org/ballerinalang/test/runtime/entity/PartialCoverageModifiedCounter.java +++ b/misc/testerina/modules/testerina-runtime/src/main/java/org/ballerinalang/test/runtime/entity/PartialCoverageModifiedCounter.java @@ -55,24 +55,17 @@ private void modifyCoverageNumbers() { /** * As implemented in Jacoco API. - * org.jacoco.core.internal.analysis.CounterImpl#getValue(org.jacoco.core.analysis.ICounter.CounterValue) + * {@link org.jacoco.core.internal.analysis.CounterImpl#getValue(org.jacoco.core.analysis.ICounter.CounterValue)} */ @Override public double getValue(CounterValue value) { - switch (value) { - case TOTALCOUNT: - return getTotalCount(); - case MISSEDCOUNT: - return getMissedCount(); - case COVEREDCOUNT: - return getCoveredCount(); - case MISSEDRATIO: - return getMissedRatio(); - case COVEREDRATIO: - return getCoveredRatio(); - default: - throw new RuntimeException("No such CounterValue object"); - } + return switch (value) { + case TOTALCOUNT -> getTotalCount(); + case MISSEDCOUNT -> getMissedCount(); + case COVEREDCOUNT -> getCoveredCount(); + case MISSEDRATIO -> getMissedRatio(); + case COVEREDRATIO -> getCoveredRatio(); + }; } @Override @@ -101,7 +94,7 @@ public double getMissedRatio() { } /** - * As implemented in org.jacoco.core.internal.analysis.CounterImpl#getStatus(). + * As implemented in {@link org.jacoco.core.internal.analysis.CounterImpl#getStatus()}. */ @Override public int getStatus() { diff --git a/misc/testerina/modules/testerina-runtime/src/main/java/org/ballerinalang/test/runtime/entity/TestReport.java b/misc/testerina/modules/testerina-runtime/src/main/java/org/ballerinalang/test/runtime/entity/TestReport.java index f0fbf1181fdb..75e2146a98ec 100644 --- a/misc/testerina/modules/testerina-runtime/src/main/java/org/ballerinalang/test/runtime/entity/TestReport.java +++ b/misc/testerina/modules/testerina-runtime/src/main/java/org/ballerinalang/test/runtime/entity/TestReport.java @@ -22,7 +22,6 @@ import java.util.ArrayList; import java.util.Comparator; import java.util.List; -import java.util.stream.Collectors; /** * Final test report with coverage (if enabled). @@ -139,11 +138,11 @@ public void finalizeTestResults(boolean coverage) { // sort the module list to be in the alphabetical order moduleStatus = moduleStatus.stream() .sorted(Comparator.comparing(ModuleStatus::getName)) - .collect(Collectors.toList()); + .toList(); moduleCoverage = moduleCoverage.stream() .sorted(Comparator.comparing(ModuleCoverage::getName)) - .collect(Collectors.toList()); + .toList(); } public float getCoveragePercentage() { diff --git a/misc/testerina/modules/testerina-runtime/src/main/java/org/ballerinalang/test/runtime/util/CodeCoverageUtils.java b/misc/testerina/modules/testerina-runtime/src/main/java/org/ballerinalang/test/runtime/util/CodeCoverageUtils.java index b83e5990e092..16603eb38028 100644 --- a/misc/testerina/modules/testerina-runtime/src/main/java/org/ballerinalang/test/runtime/util/CodeCoverageUtils.java +++ b/misc/testerina/modules/testerina-runtime/src/main/java/org/ballerinalang/test/runtime/util/CodeCoverageUtils.java @@ -49,7 +49,6 @@ import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.Enumeration; import java.util.List; @@ -75,7 +74,8 @@ * * @since 1.2.0 */ -public class CodeCoverageUtils { +public final class CodeCoverageUtils { + private static final String REPORT_ZIP_DIRECTORY = Paths.get(System.getProperty(BALLERINA_HOME)) .resolve(BALLERINA_HOME_LIB).resolve(TesterinaConstants.TOOLS_DIR_NAME) .resolve(TesterinaConstants.COVERAGE_DIR).resolve(REPORT_ZIP_NAME).toString() @@ -168,7 +168,7 @@ private static String normalizeRegexPattern(String pattern) { private static boolean isIncluded(String path, String includesInCoverage) { boolean isIncluded = false; if (includesInCoverage != null) { - List includedPackages = Arrays.asList(includesInCoverage.split(":")); + String[] includedPackages = includesInCoverage.split(":"); for (String packageName : includedPackages) { packageName = packageName.replace(".", "/"); Pattern pattern = Pattern.compile(normalizeRegexPattern(packageName)); diff --git a/misc/testerina/modules/testerina-runtime/src/main/java/org/ballerinalang/test/runtime/util/JacocoInstrumentUtils.java b/misc/testerina/modules/testerina-runtime/src/main/java/org/ballerinalang/test/runtime/util/JacocoInstrumentUtils.java index 09e3afb893bc..897a45a11be9 100644 --- a/misc/testerina/modules/testerina-runtime/src/main/java/org/ballerinalang/test/runtime/util/JacocoInstrumentUtils.java +++ b/misc/testerina/modules/testerina-runtime/src/main/java/org/ballerinalang/test/runtime/util/JacocoInstrumentUtils.java @@ -36,20 +36,24 @@ * * @since 2201.2.0 */ -public class JacocoInstrumentUtils { +public final class JacocoInstrumentUtils { private static final Instrumenter instrumenter = new Instrumenter(new OfflineInstrumentationAccessGenerator()); + private JacocoInstrumentUtils() { + } + public static void instrumentOffline(List projectModuleJarList, Path destDir, List mockClassNames) throws IOException, ClassNotFoundException { - URLClassLoader classLoader = new URLClassLoader(projectModuleJarList.toArray(new URL[0])); - for (String className : mockClassNames) { - Class clazz = classLoader.loadClass(className); - File file = new File(destDir.toString(), className.replace(".", "/") + ".class"); - file.getParentFile().mkdirs(); - try (InputStream input = clazz.getResourceAsStream(clazz.getSimpleName() + ".class"); - OutputStream output = new FileOutputStream(file)) { - instrumenter.instrumentAll(input, output, className); + try (URLClassLoader classLoader = new URLClassLoader(projectModuleJarList.toArray(new URL[0]))) { + for (String className : mockClassNames) { + Class clazz = classLoader.loadClass(className); + File file = new File(destDir.toString(), className.replace(".", "/") + ".class"); + file.getParentFile().mkdirs(); + try (InputStream input = clazz.getResourceAsStream(clazz.getSimpleName() + ".class"); + OutputStream output = new FileOutputStream(file)) { + instrumenter.instrumentAll(input, output, className); + } } } } diff --git a/misc/testerina/modules/testerina-runtime/src/main/java/org/ballerinalang/test/runtime/util/TesterinaConstants.java b/misc/testerina/modules/testerina-runtime/src/main/java/org/ballerinalang/test/runtime/util/TesterinaConstants.java index 357c4ce4ba9b..001490e070c0 100644 --- a/misc/testerina/modules/testerina-runtime/src/main/java/org/ballerinalang/test/runtime/util/TesterinaConstants.java +++ b/misc/testerina/modules/testerina-runtime/src/main/java/org/ballerinalang/test/runtime/util/TesterinaConstants.java @@ -23,7 +23,7 @@ * * @since 0.970.0 */ -public class TesterinaConstants { +public final class TesterinaConstants { public static final String DOT_REPLACER = "&0046"; public static final String BALLERINA_SOURCE_ROOT = "ballerina.source.root"; @@ -111,7 +111,7 @@ private TesterinaConstants() { * * @since 2201.9.0 */ - public static class RunTimeArgs { + public static final class RunTimeArgs { public static final int IS_FAT_JAR_EXECUTION = 0; public static final int TEST_SUITE_JSON_PATH = 1; public static final int TARGET_DIR = 2; @@ -124,5 +124,8 @@ public static class RunTimeArgs { public static final int IS_RERUN_TEST_EXECUTION = 9; public static final int LIST_GROUPS = 10; public static final int IS_PARALLEL_EXECUTION = 11; + + private RunTimeArgs() { + } } } diff --git a/misc/testerina/modules/testerina-runtime/src/main/java/org/ballerinalang/test/runtime/util/TesterinaUtils.java b/misc/testerina/modules/testerina-runtime/src/main/java/org/ballerinalang/test/runtime/util/TesterinaUtils.java index 3cfc160eedd8..98542b9ee40c 100644 --- a/misc/testerina/modules/testerina-runtime/src/main/java/org/ballerinalang/test/runtime/util/TesterinaUtils.java +++ b/misc/testerina/modules/testerina-runtime/src/main/java/org/ballerinalang/test/runtime/util/TesterinaUtils.java @@ -38,6 +38,7 @@ import java.util.List; import java.util.Optional; import java.util.regex.Pattern; +import java.util.stream.Stream; import static io.ballerina.identifier.Utils.encodeNonFunctionIdentifier; import static io.ballerina.runtime.api.constants.RuntimeConstants.BLANG_SRC_FILE_SUFFIX; @@ -52,7 +53,7 @@ /** * Utility methods. */ -public class TesterinaUtils { +public final class TesterinaUtils { private static final PrintStream errStream = System.err; @@ -64,6 +65,9 @@ public class TesterinaUtils { private static final String START_FUNCTION_SUFFIX = "."; private static final String STOP_FUNCTION_SUFFIX = "."; + private TesterinaUtils() { + } + /** * Cleans up any remaining testerina metadata. * @@ -72,7 +76,9 @@ public class TesterinaUtils { public static void cleanUpDir(Path path) { try { if (Files.exists(path)) { - Files.walk(path).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete); + try (Stream paths = Files.walk(path)) { + paths.sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete); + } } } catch (IOException e) { errStream.println("Error occurred while deleting the dir : " + path + " with error : " @@ -127,9 +133,9 @@ private static int execute(TestSuite suite, ClassLoader classLoader, String[] ar private static void startSuite(Class initClazz, String[] args) { // Call test module main Object response = runTestModuleMain(initClazz, args, String[].class); - if (response instanceof Throwable) { + if (response instanceof Throwable throwable) { throw new BallerinaTestException("dependant module execution for test suite failed due to " + - RuntimeUtils.formatErrorMessage((Throwable) response), (Throwable) response); + RuntimeUtils.formatErrorMessage(throwable), throwable); } } @@ -325,8 +331,7 @@ private static void handleWildCards(List filteredList, List suiteT } } - public static List getSingleExecutionTestsOld( - List currentTests, List functions) { + public static List getSingleExecutionTestsOld(List currentTests, List functions) { return Collections.emptyList(); } diff --git a/misc/toml-parser/src/main/java/io/ballerina/toml/internal/diagnostics/DiagnosticMessageHelper.java b/misc/toml-parser/src/main/java/io/ballerina/toml/internal/diagnostics/DiagnosticMessageHelper.java index 311cc576c72d..7d61302a7c10 100644 --- a/misc/toml-parser/src/main/java/io/ballerina/toml/internal/diagnostics/DiagnosticMessageHelper.java +++ b/misc/toml-parser/src/main/java/io/ballerina/toml/internal/diagnostics/DiagnosticMessageHelper.java @@ -28,7 +28,8 @@ * * @since 2.0.0 */ -public class DiagnosticMessageHelper { +public final class DiagnosticMessageHelper { + private static final ResourceBundle messages = ResourceBundle.getBundle( "toml_diagnostic_message", Locale.getDefault()); diff --git a/misc/toml-parser/src/main/java/io/ballerina/toml/internal/parser/LexerTerminals.java b/misc/toml-parser/src/main/java/io/ballerina/toml/internal/parser/LexerTerminals.java index 49fb5c3afa9c..531a478b2778 100644 --- a/misc/toml-parser/src/main/java/io/ballerina/toml/internal/parser/LexerTerminals.java +++ b/misc/toml-parser/src/main/java/io/ballerina/toml/internal/parser/LexerTerminals.java @@ -22,7 +22,8 @@ * * @since 1.2.0 */ -public class LexerTerminals { +public final class LexerTerminals { + // Keywords public static final String TRUE = "true"; public static final String FALSE = "false"; @@ -59,5 +60,8 @@ public class LexerTerminals { public static final char FORM_FEED = 0xC; public static final char BACKSLASH = '\\'; + private LexerTerminals() { + } + //New } diff --git a/misc/toml-parser/src/main/java/io/ballerina/toml/internal/parser/ParserFactory.java b/misc/toml-parser/src/main/java/io/ballerina/toml/internal/parser/ParserFactory.java index f36e39b96a41..7f421e098e4c 100644 --- a/misc/toml-parser/src/main/java/io/ballerina/toml/internal/parser/ParserFactory.java +++ b/misc/toml-parser/src/main/java/io/ballerina/toml/internal/parser/ParserFactory.java @@ -28,7 +28,7 @@ * * @since 2.0.0 */ -public class ParserFactory { +public final class ParserFactory { private ParserFactory() { } diff --git a/misc/toml-parser/src/main/java/io/ballerina/toml/internal/parser/SyntaxErrors.java b/misc/toml-parser/src/main/java/io/ballerina/toml/internal/parser/SyntaxErrors.java index 2ff7bd2f88a6..895a36543b75 100644 --- a/misc/toml-parser/src/main/java/io/ballerina/toml/internal/parser/SyntaxErrors.java +++ b/misc/toml-parser/src/main/java/io/ballerina/toml/internal/parser/SyntaxErrors.java @@ -38,7 +38,7 @@ * * @since 2.0.0 */ -public class SyntaxErrors { +public final class SyntaxErrors { private SyntaxErrors() { } @@ -89,52 +89,36 @@ public static STToken createMissingTokenWithDiagnostics(SyntaxKind expectedKind, } private static DiagnosticCode getErrorCode(ParserRuleContext currentCtx) { - switch (currentCtx) { - case STRING_BODY: - return DiagnosticErrorCode.ERROR_MISSING_STRING_LITERAL; - case ASSIGN_OP: - return DiagnosticErrorCode.ERROR_MISSING_EQUAL_TOKEN; - case ARRAY_VALUE_LIST_END: - case TABLE_END: - case ARRAY_TABLE_FIRST_END: - case ARRAY_TABLE_SECOND_END: - return DiagnosticErrorCode.ERROR_MISSING_CLOSE_BRACKET_TOKEN; - case COMMA: - return DiagnosticErrorCode.ERROR_MISSING_COMMA_TOKEN; - case ARRAY_VALUE_LIST_START: - case TABLE_START: - case ARRAY_TABLE_FIRST_START: - case ARRAY_TABLE_SECOND_START: - return DiagnosticErrorCode.ERROR_MISSING_OPEN_BRACKET_TOKEN; - case INLINE_TABLE_END: - return DiagnosticErrorCode.ERROR_MISSING_CLOSE_BRACE_TOKEN; - case INLINE_TABLE_START: - return DiagnosticErrorCode.ERROR_MISSING_OPEN_BRACE_TOKEN; - case DOT: - return DiagnosticErrorCode.ERROR_MISSING_DOT_TOKEN; - case STRING_END: - case STRING_START: - return DiagnosticErrorCode.ERROR_MISSING_DOUBLE_QUOTE_TOKEN; - case MULTILINE_STRING_START: - case MULTILINE_STRING_END: - return DiagnosticErrorCode.ERROR_MISSING_TRIPLE_DOUBLE_QUOTE_TOKEN; - case LITERAL_STRING_END: - case LITERAL_STRING_START: - return DiagnosticErrorCode.ERROR_MISSING_SINGLE_QUOTE_TOKEN; - case MULTILINE_LITERAL_STRING_START: - case MULTILINE_LITERAL_STRING_END: - return DiagnosticErrorCode.ERROR_MISSING_TRIPLE_SINGLE_QUOTE_TOKEN; - case DECIMAL_INTEGER_LITERAL: - case DECIMAL_FLOATING_POINT_LITERAL: - case BOOLEAN_LITERAL: - return DiagnosticErrorCode.ERROR_MISSING_VALUE; - case NEWLINE: - return DiagnosticErrorCode.ERROR_MISSING_NEW_LINE; - case IDENTIFIER_LITERAL: - return DiagnosticErrorCode.ERROR_MISSING_IDENTIFIER; - default: - return DiagnosticErrorCode.ERROR_SYNTAX_ERROR; - } + return switch (currentCtx) { + case STRING_BODY -> DiagnosticErrorCode.ERROR_MISSING_STRING_LITERAL; + case ASSIGN_OP -> DiagnosticErrorCode.ERROR_MISSING_EQUAL_TOKEN; + case ARRAY_VALUE_LIST_END, + TABLE_END, + ARRAY_TABLE_FIRST_END, + ARRAY_TABLE_SECOND_END -> DiagnosticErrorCode.ERROR_MISSING_CLOSE_BRACKET_TOKEN; + case COMMA -> DiagnosticErrorCode.ERROR_MISSING_COMMA_TOKEN; + case ARRAY_VALUE_LIST_START, + TABLE_START, + ARRAY_TABLE_FIRST_START, + ARRAY_TABLE_SECOND_START -> DiagnosticErrorCode.ERROR_MISSING_OPEN_BRACKET_TOKEN; + case INLINE_TABLE_END -> DiagnosticErrorCode.ERROR_MISSING_CLOSE_BRACE_TOKEN; + case INLINE_TABLE_START -> DiagnosticErrorCode.ERROR_MISSING_OPEN_BRACE_TOKEN; + case DOT -> DiagnosticErrorCode.ERROR_MISSING_DOT_TOKEN; + case STRING_END, + STRING_START -> DiagnosticErrorCode.ERROR_MISSING_DOUBLE_QUOTE_TOKEN; + case MULTILINE_STRING_START, + MULTILINE_STRING_END -> DiagnosticErrorCode.ERROR_MISSING_TRIPLE_DOUBLE_QUOTE_TOKEN; + case LITERAL_STRING_END, + LITERAL_STRING_START -> DiagnosticErrorCode.ERROR_MISSING_SINGLE_QUOTE_TOKEN; + case MULTILINE_LITERAL_STRING_START, + MULTILINE_LITERAL_STRING_END -> DiagnosticErrorCode.ERROR_MISSING_TRIPLE_SINGLE_QUOTE_TOKEN; + case DECIMAL_INTEGER_LITERAL, + DECIMAL_FLOATING_POINT_LITERAL, + BOOLEAN_LITERAL -> DiagnosticErrorCode.ERROR_MISSING_VALUE; + case NEWLINE -> DiagnosticErrorCode.ERROR_MISSING_NEW_LINE; + case IDENTIFIER_LITERAL -> DiagnosticErrorCode.ERROR_MISSING_IDENTIFIER; + default -> DiagnosticErrorCode.ERROR_SYNTAX_ERROR; + }; } /** diff --git a/misc/toml-parser/src/main/java/io/ballerina/toml/internal/parser/TomlLexer.java b/misc/toml-parser/src/main/java/io/ballerina/toml/internal/parser/TomlLexer.java index cd779a007d38..84479165fc41 100644 --- a/misc/toml-parser/src/main/java/io/ballerina/toml/internal/parser/TomlLexer.java +++ b/misc/toml-parser/src/main/java/io/ballerina/toml/internal/parser/TomlLexer.java @@ -522,17 +522,16 @@ private STNode processWhitespaces() { */ private STNode processEndOfLine() { char c = reader.peek(); - switch (c) { - case LexerTerminals.NEWLINE: - return STNodeFactory.createMinutiae(SyntaxKind.END_OF_LINE_MINUTIAE, "\n"); - case LexerTerminals.CARRIAGE_RETURN: + return switch (c) { + case LexerTerminals.NEWLINE -> STNodeFactory.createMinutiae(SyntaxKind.END_OF_LINE_MINUTIAE, "\n"); + case LexerTerminals.CARRIAGE_RETURN -> { if (reader.peek(1) == LexerTerminals.NEWLINE) { reader.advance(); } - return STNodeFactory.createMinutiae(SyntaxKind.END_OF_LINE_MINUTIAE, "\r\n"); - default: - throw new IllegalStateException(); - } + yield STNodeFactory.createMinutiae(SyntaxKind.END_OF_LINE_MINUTIAE, "\r\n"); + } + default -> throw new IllegalStateException(); + }; } /** @@ -654,13 +653,11 @@ private STToken processDecimalFloatLiteral() { nextChar = peek(); } - switch (nextChar) { - case 'e': - case 'E': - return processExponent(); - } + return switch (nextChar) { + case 'e', 'E' -> processExponent(); + default -> getLiteral(SyntaxKind.DECIMAL_FLOAT_TOKEN); + }; - return getLiteral(SyntaxKind.DECIMAL_FLOAT_TOKEN); } /** @@ -754,18 +751,13 @@ private STToken processKey() { } String tokenText = getLexeme(); - switch (tokenText) { - case LexerTerminals.TRUE: - return getSyntaxToken(SyntaxKind.TRUE_KEYWORD); - case LexerTerminals.FALSE: - return getSyntaxToken(SyntaxKind.FALSE_KEYWORD); - case LexerTerminals.INF: - return getSyntaxToken(SyntaxKind.INF_TOKEN); - case LexerTerminals.NAN: - return getSyntaxToken(SyntaxKind.NAN_TOKEN); - default: - return getUnquotedKey(); - } + return switch (tokenText) { + case LexerTerminals.TRUE -> getSyntaxToken(SyntaxKind.TRUE_KEYWORD); + case LexerTerminals.FALSE -> getSyntaxToken(SyntaxKind.FALSE_KEYWORD); + case LexerTerminals.INF -> getSyntaxToken(SyntaxKind.INF_TOKEN); + case LexerTerminals.NAN -> getSyntaxToken(SyntaxKind.NAN_TOKEN); + default -> getUnquotedKey(); + }; } /** @@ -801,22 +793,20 @@ private boolean isEndOfInvalidToken() { } int currentChar = peek(); - switch (currentChar) { - case LexerTerminals.NEWLINE: - case LexerTerminals.CARRIAGE_RETURN: - case LexerTerminals.SPACE: - case LexerTerminals.TAB: - case LexerTerminals.SEMICOLON: - case LexerTerminals.OPEN_BRACE: - case LexerTerminals.CLOSE_BRACE: - case LexerTerminals.OPEN_BRACKET: - case LexerTerminals.CLOSE_BRACKET: - case LexerTerminals.OPEN_PARANTHESIS: - case LexerTerminals.CLOSE_PARANTHESIS: - return true; - default: - return false; - } + return switch (currentChar) { + case LexerTerminals.NEWLINE, + LexerTerminals.CARRIAGE_RETURN, + LexerTerminals.SPACE, + LexerTerminals.TAB, + LexerTerminals.SEMICOLON, + LexerTerminals.OPEN_BRACE, + LexerTerminals.CLOSE_BRACE, + LexerTerminals.OPEN_BRACKET, + LexerTerminals.CLOSE_BRACKET, + LexerTerminals.OPEN_PARANTHESIS, + LexerTerminals.CLOSE_PARANTHESIS -> true; + default -> false; + }; } /** diff --git a/misc/toml-parser/src/main/java/io/ballerina/toml/internal/parser/TomlParser.java b/misc/toml-parser/src/main/java/io/ballerina/toml/internal/parser/TomlParser.java index d39f36efb8d6..c359e4929fad 100644 --- a/misc/toml-parser/src/main/java/io/ballerina/toml/internal/parser/TomlParser.java +++ b/misc/toml-parser/src/main/java/io/ballerina/toml/internal/parser/TomlParser.java @@ -198,19 +198,19 @@ private STNode parseInlineKeyValuePairs() { private STNode parseInlineKeyValuePair() { STToken nextToken = peek(); - switch (nextToken.kind) { - case IDENTIFIER_LITERAL: - case SINGLE_QUOTE_TOKEN: - case DOUBLE_QUOTE_TOKEN: - case TRUE_KEYWORD: - case FALSE_KEYWORD: - case DECIMAL_INT_TOKEN: - case DECIMAL_FLOAT_TOKEN: - return parseKeyValue(true); - default: + return switch (nextToken.kind) { + case IDENTIFIER_LITERAL, + SINGLE_QUOTE_TOKEN, + DOUBLE_QUOTE_TOKEN, + TRUE_KEYWORD, + FALSE_KEYWORD, + DECIMAL_INT_TOKEN, + DECIMAL_FLOAT_TOKEN -> parseKeyValue(true); + default -> { recover(peek(), ParserRuleContext.INLINE_TABLE_ENTRY_START); - return parseInlineKeyValuePair(); - } + yield parseInlineKeyValuePair(); + } + }; } private boolean isEndOfInlineTable(STToken token) { @@ -218,16 +218,15 @@ private boolean isEndOfInlineTable(STToken token) { } private STNode parseInlineTableEntryEnd() { - switch (peek().kind) { - case COMMA_TOKEN: - return consume(); - case CLOSE_BRACE_TOKEN: - // null marks the end of values - return null; - default: + return switch (peek().kind) { + case COMMA_TOKEN -> consume(); + // null marks the end of values + case CLOSE_BRACE_TOKEN -> null; + default -> { recover(peek(), ParserRuleContext.INLINE_TABLE_ENTRY_END); - return parseInlineTableEntryEnd(); - } + yield parseInlineTableEntryEnd(); + } + }; } private STNode parseOpenBrace() { @@ -390,25 +389,20 @@ private STNode parseIdentifierLiteral() { private STNode parseSingleKey() { STToken nextToken = peek(); - switch (nextToken.kind) { - case DECIMAL_INT_TOKEN: - case DECIMAL_FLOAT_TOKEN: - return parseNumericalNode(); - case TRUE_KEYWORD: - case FALSE_KEYWORD: - return parseBoolean(); - case IDENTIFIER_LITERAL: - return parseIdentifierLiteral(); - case DOUBLE_QUOTE_TOKEN: - return parseStringValue(); - case SINGLE_QUOTE_TOKEN: - return parseLiteralStringValue(); - case EQUAL_TOKEN: - return null; - default: + return switch (nextToken.kind) { + case DECIMAL_INT_TOKEN, + DECIMAL_FLOAT_TOKEN -> parseNumericalNode(); + case TRUE_KEYWORD, + FALSE_KEYWORD -> parseBoolean(); + case IDENTIFIER_LITERAL -> parseIdentifierLiteral(); + case DOUBLE_QUOTE_TOKEN -> parseStringValue(); + case SINGLE_QUOTE_TOKEN -> parseLiteralStringValue(); + case EQUAL_TOKEN -> null; + default -> { recover(peek(), ParserRuleContext.KEY_START); - return parseSingleKey(); - } + yield parseSingleKey(); + } + }; } private STNode parseKeyList(STNode firstKey) { @@ -437,17 +431,15 @@ private STNode parseKeyList(STNode firstKey) { private STNode parseKeyEnd() { STToken token = peek(); - switch (token.kind) { - case DOT_TOKEN: - return consume(); - case EQUAL_TOKEN: - case CLOSE_BRACKET_TOKEN: - // null marks the end of values - return null; - default: + return switch (token.kind) { + case DOT_TOKEN -> consume(); + // null marks the end of values + case EQUAL_TOKEN, CLOSE_BRACKET_TOKEN -> null; + default -> { recover(token, ParserRuleContext.KEY_END); - return parseKeyEnd(); - } + yield parseKeyEnd(); + } + }; } private STNode parseEquals() { @@ -475,34 +467,27 @@ private STNode parseEquals() { */ private STNode parseValue() { STToken token = peek(); - switch (token.kind) { - case DOUBLE_QUOTE_TOKEN: - return parseStringValue(); - case TRIPLE_DOUBLE_QUOTE_TOKEN: - return parseMultilineStringValue(); - case SINGLE_QUOTE_TOKEN: - return parseLiteralStringValue(); - case TRIPLE_SINGLE_QUOTE_TOKEN: - return parseMultilineLiteralStringValue(); - case DECIMAL_INT_TOKEN: - case DECIMAL_FLOAT_TOKEN: - case HEX_INTEGER_LITERAL_TOKEN: - case OCTAL_INTEGER_LITERAL_TOKEN: - case BINARY_INTEGER_LITERAL_TOKEN: - case PLUS_TOKEN: - case MINUS_TOKEN: - return parseNumericalNode(); - case TRUE_KEYWORD: - case FALSE_KEYWORD: - return parseBoolean(); - case OPEN_BRACKET_TOKEN: - return parseArray(); - case OPEN_BRACE_TOKEN: - return parseInlineTable(); - default: + return switch (token.kind) { + case DOUBLE_QUOTE_TOKEN -> parseStringValue(); + case TRIPLE_DOUBLE_QUOTE_TOKEN -> parseMultilineStringValue(); + case SINGLE_QUOTE_TOKEN -> parseLiteralStringValue(); + case TRIPLE_SINGLE_QUOTE_TOKEN -> parseMultilineLiteralStringValue(); + case DECIMAL_INT_TOKEN, + DECIMAL_FLOAT_TOKEN, + HEX_INTEGER_LITERAL_TOKEN, + OCTAL_INTEGER_LITERAL_TOKEN, + BINARY_INTEGER_LITERAL_TOKEN, + PLUS_TOKEN, + MINUS_TOKEN -> parseNumericalNode(); + case TRUE_KEYWORD, + FALSE_KEYWORD -> parseBoolean(); + case OPEN_BRACKET_TOKEN -> parseArray(); + case OPEN_BRACE_TOKEN -> parseInlineTable(); + default -> { recover(token, ParserRuleContext.VALUE); - return parseValue(); - } + yield parseValue(); + } + }; } private STNode parseNumericalNode() { @@ -513,18 +498,13 @@ private STNode parseNumericalNode() { } private SyntaxKind getNumericLiteralKind(SyntaxKind tokenKind) { - switch (tokenKind) { - case DECIMAL_INT_TOKEN: - return DEC_INT; - case HEX_INTEGER_LITERAL_TOKEN: - return HEX_INT; - case OCTAL_INTEGER_LITERAL_TOKEN: - return OCT_INT; - case BINARY_INTEGER_LITERAL_TOKEN: - return BINARY_INT; - default: - return FLOAT; - } + return switch (tokenKind) { + case DECIMAL_INT_TOKEN -> DEC_INT; + case HEX_INTEGER_LITERAL_TOKEN -> HEX_INT; + case OCTAL_INTEGER_LITERAL_TOKEN -> OCT_INT; + case BINARY_INTEGER_LITERAL_TOKEN -> BINARY_INT; + default -> FLOAT; + }; } private STNode parseNumericalToken() { @@ -538,16 +518,14 @@ private STNode parseNumericalToken() { } private boolean isNumericalLiteral(STToken token) { - switch (token.kind) { - case DECIMAL_INT_TOKEN: - case DECIMAL_FLOAT_TOKEN: - case HEX_INTEGER_LITERAL_TOKEN: - case OCTAL_INTEGER_LITERAL_TOKEN: - case BINARY_INTEGER_LITERAL_TOKEN: - return true; - default: - return false; - } + return switch (token.kind) { + case DECIMAL_INT_TOKEN, + DECIMAL_FLOAT_TOKEN, + HEX_INTEGER_LITERAL_TOKEN, + OCTAL_INTEGER_LITERAL_TOKEN, + BINARY_INTEGER_LITERAL_TOKEN -> true; + default -> false; + }; } private STNode parseSign() { @@ -791,49 +769,43 @@ private STNode parseArrayValues(STNode firstValue) { } private STNode parseValueEnd() { - switch (peek().kind) { - case COMMA_TOKEN: - return consume(); - case CLOSE_BRACKET_TOKEN: - // null marks the end of values - return null; - case NEWLINE: + return switch (peek().kind) { + case COMMA_TOKEN -> consume(); + // null marks the end of values + case CLOSE_BRACKET_TOKEN -> null; + case NEWLINE -> { consume(); - return parseValueEnd(); - default: + yield parseValueEnd(); + } + default -> { recover(peek(), ParserRuleContext.ARRAY_VALUE_END); - return parseValueEnd(); - } + yield parseValueEnd(); + } + }; } private STNode parseArrayValue() { STToken nextToken = peek(); - switch (nextToken.kind) { - case DOUBLE_QUOTE_TOKEN: - return parseStringValue(); - case TRIPLE_DOUBLE_QUOTE_TOKEN: - return parseMultilineStringValue(); - case SINGLE_QUOTE_TOKEN: - return parseLiteralStringValue(); - case TRIPLE_SINGLE_QUOTE_TOKEN: - return parseMultilineLiteralStringValue(); - case DECIMAL_INT_TOKEN: - case DECIMAL_FLOAT_TOKEN: - case TRUE_KEYWORD: - case FALSE_KEYWORD: - return parseValue(); - case OPEN_BRACKET_TOKEN: - return parseArray(); - case CLOSE_BRACKET_TOKEN: - return null; - case OPEN_BRACE_TOKEN: - return parseInlineTable(); - case NEWLINE: + return switch (nextToken.kind) { + case DOUBLE_QUOTE_TOKEN -> parseStringValue(); + case TRIPLE_DOUBLE_QUOTE_TOKEN -> parseMultilineStringValue(); + case SINGLE_QUOTE_TOKEN -> parseLiteralStringValue(); + case TRIPLE_SINGLE_QUOTE_TOKEN -> parseMultilineLiteralStringValue(); + case DECIMAL_INT_TOKEN, + DECIMAL_FLOAT_TOKEN, + TRUE_KEYWORD, + FALSE_KEYWORD -> parseValue(); + case OPEN_BRACKET_TOKEN -> parseArray(); + case CLOSE_BRACKET_TOKEN -> null; + case OPEN_BRACE_TOKEN -> parseInlineTable(); + case NEWLINE -> { consume(); - return parseArrayValue(); - default: + yield parseArrayValue(); + } + default -> { recover(peek(), ParserRuleContext.ARRAY_VALUE_START); - return parseArrayValue(); - } + yield parseArrayValue(); + } + }; } } diff --git a/misc/toml-parser/src/main/java/io/ballerina/toml/internal/parser/TomlParserErrorHandler.java b/misc/toml-parser/src/main/java/io/ballerina/toml/internal/parser/TomlParserErrorHandler.java index 36d5de134874..058992c488a8 100644 --- a/misc/toml-parser/src/main/java/io/ballerina/toml/internal/parser/TomlParserErrorHandler.java +++ b/misc/toml-parser/src/main/java/io/ballerina/toml/internal/parser/TomlParserErrorHandler.java @@ -423,74 +423,46 @@ protected ParserRuleContext getNextRule(ParserRuleContext currentCtx, int nextLo */ @Override protected SyntaxKind getExpectedTokenKind(ParserRuleContext ctx) { - switch (ctx) { - case TOML_TABLE: - return SyntaxKind.TABLE; - case TOML_TABLE_ARRAY: - return SyntaxKind.TABLE_ARRAY; - case KEY_VALUE_PAIR: - return SyntaxKind.KEY_VALUE; - case ASSIGN_OP: - return SyntaxKind.EQUAL_TOKEN; - case IDENTIFIER_LITERAL: - return SyntaxKind.IDENTIFIER_LITERAL; - case EOF: - return SyntaxKind.EOF_TOKEN; - case COMMA: - return SyntaxKind.COMMA_TOKEN; - case STRING_START: - case STRING_END: - return SyntaxKind.DOUBLE_QUOTE_TOKEN; - case LITERAL_STRING_START: - case LITERAL_STRING_END: - return SyntaxKind.SINGLE_QUOTE_TOKEN; - case MULTILINE_STRING_START: - case MULTILINE_STRING_END: - return SyntaxKind.TRIPLE_DOUBLE_QUOTE_TOKEN; - case MULTILINE_LITERAL_STRING_START: - case MULTILINE_LITERAL_STRING_END: - return SyntaxKind.TRIPLE_SINGLE_QUOTE_TOKEN; - case STRING_BODY: - case LITERAL_STRING_BODY: - case MULTILINE_STRING_BODY: - case MULTILINE_LITERAL_STRING_BODY: - return SyntaxKind.IDENTIFIER_LITERAL; - case INLINE_TABLE_START: - return SyntaxKind.OPEN_BRACE_TOKEN; - case ARRAY_VALUE_LIST_START: - case TABLE_START: - return SyntaxKind.OPEN_BRACKET_TOKEN; - case ARRAY_VALUE_LIST_END: - case TABLE_END: - return SyntaxKind.CLOSE_BRACKET_TOKEN; - case INLINE_TABLE_END: - return SyntaxKind.CLOSE_BRACE_TOKEN; - case DECIMAL_INTEGER_LITERAL: - return SyntaxKind.DECIMAL_INT_TOKEN; - case HEX_INTEGER_LITERAL: - return SyntaxKind.HEX_INTEGER_LITERAL_TOKEN; - case OCTAL_INTEGER_LITERAL: - return SyntaxKind.OCTAL_INTEGER_LITERAL_TOKEN; - case BINARY_INTEGER_LITERAL: - return SyntaxKind.BINARY_INTEGER_LITERAL_TOKEN; - case DECIMAL_FLOATING_POINT_LITERAL: - return SyntaxKind.DECIMAL_FLOAT_TOKEN; - case BOOLEAN_LITERAL: - return SyntaxKind.FALSE_KEYWORD; - case NEWLINE: - return SyntaxKind.NEWLINE; - case DOT: - return SyntaxKind.DOT_TOKEN; - case ARRAY_TABLE_FIRST_END: - case ARRAY_TABLE_SECOND_END: - return SyntaxKind.CLOSE_BRACKET_TOKEN; - case ARRAY_TABLE_FIRST_START: - case ARRAY_TABLE_SECOND_START: - return SyntaxKind.OPEN_BRACKET_TOKEN; - case SIGN_TOKEN: - return SyntaxKind.PLUS_TOKEN; - default: - return SyntaxKind.NONE; - } + return switch (ctx) { + case TOML_TABLE -> SyntaxKind.TABLE; + case TOML_TABLE_ARRAY -> SyntaxKind.TABLE_ARRAY; + case KEY_VALUE_PAIR -> SyntaxKind.KEY_VALUE; + case ASSIGN_OP -> SyntaxKind.EQUAL_TOKEN; + case IDENTIFIER_LITERAL -> SyntaxKind.IDENTIFIER_LITERAL; + case EOF -> SyntaxKind.EOF_TOKEN; + case COMMA -> SyntaxKind.COMMA_TOKEN; + case STRING_START, + STRING_END -> SyntaxKind.DOUBLE_QUOTE_TOKEN; + case LITERAL_STRING_START, + LITERAL_STRING_END -> SyntaxKind.SINGLE_QUOTE_TOKEN; + case MULTILINE_STRING_START, + MULTILINE_STRING_END -> SyntaxKind.TRIPLE_DOUBLE_QUOTE_TOKEN; + case MULTILINE_LITERAL_STRING_START, + MULTILINE_LITERAL_STRING_END -> SyntaxKind.TRIPLE_SINGLE_QUOTE_TOKEN; + case STRING_BODY, + LITERAL_STRING_BODY, + MULTILINE_STRING_BODY, + MULTILINE_LITERAL_STRING_BODY -> SyntaxKind.IDENTIFIER_LITERAL; + case INLINE_TABLE_START -> SyntaxKind.OPEN_BRACE_TOKEN; + case ARRAY_VALUE_LIST_START, + TABLE_START -> SyntaxKind.OPEN_BRACKET_TOKEN; + case ARRAY_VALUE_LIST_END, + TABLE_END -> SyntaxKind.CLOSE_BRACKET_TOKEN; + case INLINE_TABLE_END -> SyntaxKind.CLOSE_BRACE_TOKEN; + case DECIMAL_INTEGER_LITERAL -> SyntaxKind.DECIMAL_INT_TOKEN; + case HEX_INTEGER_LITERAL -> SyntaxKind.HEX_INTEGER_LITERAL_TOKEN; + case OCTAL_INTEGER_LITERAL -> SyntaxKind.OCTAL_INTEGER_LITERAL_TOKEN; + case BINARY_INTEGER_LITERAL -> SyntaxKind.BINARY_INTEGER_LITERAL_TOKEN; + case DECIMAL_FLOATING_POINT_LITERAL -> SyntaxKind.DECIMAL_FLOAT_TOKEN; + case BOOLEAN_LITERAL -> SyntaxKind.FALSE_KEYWORD; + case NEWLINE -> SyntaxKind.NEWLINE; + case DOT -> SyntaxKind.DOT_TOKEN; + case ARRAY_TABLE_FIRST_END, + ARRAY_TABLE_SECOND_END -> SyntaxKind.CLOSE_BRACKET_TOKEN; + case ARRAY_TABLE_FIRST_START, + ARRAY_TABLE_SECOND_START -> SyntaxKind.OPEN_BRACKET_TOKEN; + case SIGN_TOKEN -> SyntaxKind.PLUS_TOKEN; + default -> SyntaxKind.NONE; + }; } } diff --git a/misc/toml-parser/src/main/java/io/ballerina/toml/internal/parser/tree/STMissingToken.java b/misc/toml-parser/src/main/java/io/ballerina/toml/internal/parser/tree/STMissingToken.java index e923b1d75ceb..df6548cb511d 100644 --- a/misc/toml-parser/src/main/java/io/ballerina/toml/internal/parser/tree/STMissingToken.java +++ b/misc/toml-parser/src/main/java/io/ballerina/toml/internal/parser/tree/STMissingToken.java @@ -60,12 +60,10 @@ public STToken modifyWith(STNode leadingMinutiae, STNode trailingMinutiae) { @Override public Node createFacade(int position, NonTerminalNode parent) { - switch (kind) { - case IDENTIFIER_LITERAL: - return new IdentifierToken(this, position, parent); - default: - return new Token(this, position, parent); - } + return switch (kind) { + case IDENTIFIER_LITERAL -> new IdentifierToken(this, position, parent); + default -> new Token(this, position, parent); + }; } @Override diff --git a/misc/toml-parser/src/main/java/io/ballerina/toml/internal/parser/tree/STTreeModifiers.java b/misc/toml-parser/src/main/java/io/ballerina/toml/internal/parser/tree/STTreeModifiers.java index 898e23b8ac37..5ad48e305b35 100644 --- a/misc/toml-parser/src/main/java/io/ballerina/toml/internal/parser/tree/STTreeModifiers.java +++ b/misc/toml-parser/src/main/java/io/ballerina/toml/internal/parser/tree/STTreeModifiers.java @@ -22,7 +22,11 @@ * * @since 2.0.0 */ -public class STTreeModifiers { +public final class STTreeModifiers { + + private STTreeModifiers() { + } + /** * Replaces the given target node with the replacement node and return new root node. * diff --git a/misc/toml-parser/src/main/java/io/ballerina/toml/internal/syntax/NodeListUtils.java b/misc/toml-parser/src/main/java/io/ballerina/toml/internal/syntax/NodeListUtils.java index cb8894ba3ec7..ab1a89850d2e 100644 --- a/misc/toml-parser/src/main/java/io/ballerina/toml/internal/syntax/NodeListUtils.java +++ b/misc/toml-parser/src/main/java/io/ballerina/toml/internal/syntax/NodeListUtils.java @@ -25,7 +25,8 @@ * * @since 2.0.0 */ -public class NodeListUtils { +public final class NodeListUtils { + private NodeListUtils() { } diff --git a/misc/toml-parser/src/main/java/io/ballerina/toml/internal/syntax/SyntaxUtils.java b/misc/toml-parser/src/main/java/io/ballerina/toml/internal/syntax/SyntaxUtils.java index 8724b32ab980..b66764472454 100644 --- a/misc/toml-parser/src/main/java/io/ballerina/toml/internal/syntax/SyntaxUtils.java +++ b/misc/toml-parser/src/main/java/io/ballerina/toml/internal/syntax/SyntaxUtils.java @@ -27,7 +27,8 @@ * * @since 2.0.0 */ -public class SyntaxUtils { +public final class SyntaxUtils { + private SyntaxUtils() { } diff --git a/misc/toml-parser/src/main/java/io/ballerina/toml/internal/syntax/TreeModifiers.java b/misc/toml-parser/src/main/java/io/ballerina/toml/internal/syntax/TreeModifiers.java index 0e1cdc6edb16..1f4c0ae20b62 100644 --- a/misc/toml-parser/src/main/java/io/ballerina/toml/internal/syntax/TreeModifiers.java +++ b/misc/toml-parser/src/main/java/io/ballerina/toml/internal/syntax/TreeModifiers.java @@ -25,7 +25,10 @@ * * @since 2.0.0 */ -public class TreeModifiers { +public final class TreeModifiers { + + private TreeModifiers() { + } /** * Replaces the given target node with the replacement node and return new root node. diff --git a/misc/toml-parser/src/main/java/io/ballerina/toml/semantic/ast/TomlKeyEntryNode.java b/misc/toml-parser/src/main/java/io/ballerina/toml/semantic/ast/TomlKeyEntryNode.java index ee1ea0a3f8cb..27afc1896060 100644 --- a/misc/toml-parser/src/main/java/io/ballerina/toml/semantic/ast/TomlKeyEntryNode.java +++ b/misc/toml-parser/src/main/java/io/ballerina/toml/semantic/ast/TomlKeyEntryNode.java @@ -27,14 +27,14 @@ */ public class TomlKeyEntryNode extends TomlNode { - private final TomlBasicValueNode name; + private final TomlBasicValueNode name; - public TomlKeyEntryNode(ValueNode valueNode, TomlBasicValueNode name) { + public TomlKeyEntryNode(ValueNode valueNode, TomlBasicValueNode name) { super(valueNode, name.kind(), name.location()); this.name = name; } - public TomlBasicValueNode name() { + public TomlBasicValueNode name() { return name; } diff --git a/misc/toml-parser/src/main/java/io/ballerina/toml/semantic/ast/TomlTransformer.java b/misc/toml-parser/src/main/java/io/ballerina/toml/semantic/ast/TomlTransformer.java index e313194120b1..76b33e7890b1 100644 --- a/misc/toml-parser/src/main/java/io/ballerina/toml/semantic/ast/TomlTransformer.java +++ b/misc/toml-parser/src/main/java/io/ballerina/toml/semantic/ast/TomlTransformer.java @@ -426,7 +426,7 @@ private TomlKeyNode getTomlKeyNode(KeyNode identifier) { SeparatedNodeList identifierList = identifier.value(); List nodeList = new ArrayList<>(); for (Node node : identifierList) { - TomlBasicValueNode transformedNode = (TomlBasicValueNode) node.apply(this); + TomlBasicValueNode transformedNode = (TomlBasicValueNode) node.apply(this); nodeList.add(new TomlKeyEntryNode((ValueNode) node, transformedNode)); } return new TomlKeyNode(identifier, nodeList, getTomlNodeListLocation(nodeList)); diff --git a/misc/toml-parser/src/main/java/io/ballerina/toml/syntax/tree/AbstractNodeFactory.java b/misc/toml-parser/src/main/java/io/ballerina/toml/syntax/tree/AbstractNodeFactory.java index 5af73017a47d..51de768d1e02 100644 --- a/misc/toml-parser/src/main/java/io/ballerina/toml/syntax/tree/AbstractNodeFactory.java +++ b/misc/toml-parser/src/main/java/io/ballerina/toml/syntax/tree/AbstractNodeFactory.java @@ -27,7 +27,6 @@ import java.util.Collection; import java.util.Collections; import java.util.Objects; -import java.util.stream.Collectors; /** * A factory for creating nodes in the syntax tree. @@ -143,7 +142,7 @@ public static MinutiaeList createMinutiaeList(Collection minutiaeNodes minutiaeNodes.stream() .map(minutiae -> Objects.requireNonNull(minutiae, "minutiae should not be null")) .map(Minutiae::internalNode) - .collect(Collectors.toList())), 0); + .toList()), 0); } public static Minutiae createCommentMinutiae(String text) { @@ -188,7 +187,7 @@ public static NodeList createNodeList(Collection nodes) { nodes.stream() .map(node -> Objects.requireNonNull(node, "node should not be null")) .map(Node::internalNode) - .collect(Collectors.toList())).createUnlinkedFacade()); + .toList()).createUnlinkedFacade()); } public static SeparatedNodeList createSeparatedNodeList(Node... nodes) { @@ -206,7 +205,7 @@ public static SeparatedNodeList createSeparatedNodeList(Coll nodes.stream() .map(node -> Objects.requireNonNull(node, "node should not be null")) .map(Node::internalNode) - .collect(Collectors.toList())).createUnlinkedFacade()); + .toList()).createUnlinkedFacade()); } protected static STNode getOptionalSTNode(Node node) { diff --git a/misc/toml-parser/src/main/java/io/ballerina/toml/syntax/tree/MinutiaeList.java b/misc/toml-parser/src/main/java/io/ballerina/toml/syntax/tree/MinutiaeList.java index c76d63b43fd1..3fe19c63b730 100644 --- a/misc/toml-parser/src/main/java/io/ballerina/toml/syntax/tree/MinutiaeList.java +++ b/misc/toml-parser/src/main/java/io/ballerina/toml/syntax/tree/MinutiaeList.java @@ -28,7 +28,6 @@ import java.util.Iterator; import java.util.List; import java.util.Objects; -import java.util.stream.Collectors; import static io.ballerina.toml.internal.syntax.NodeListUtils.rangeCheck; import static io.ballerina.toml.internal.syntax.NodeListUtils.rangeCheckForAdd; @@ -87,7 +86,7 @@ public MinutiaeList addAll(Collection c) { List stNodesToBeAdded = c.stream() .map(minutiae -> Objects.requireNonNull(minutiae, "minutiae should not be null")) .map(Minutiae::internalNode) - .collect(Collectors.toList()); + .toList(); return new MinutiaeList(token, internalListNode.addAll(stNodesToBeAdded), position); @@ -161,7 +160,7 @@ public Minutiae next() { }; } - protected STNode internalNode() { + STNode internalNode() { return internalListNode; } diff --git a/misc/toml-parser/src/main/java/io/ballerina/toml/syntax/tree/NodeList.java b/misc/toml-parser/src/main/java/io/ballerina/toml/syntax/tree/NodeList.java index a2f5fd7b9000..e0fb3cc7628e 100644 --- a/misc/toml-parser/src/main/java/io/ballerina/toml/syntax/tree/NodeList.java +++ b/misc/toml-parser/src/main/java/io/ballerina/toml/syntax/tree/NodeList.java @@ -26,7 +26,6 @@ import java.util.Iterator; import java.util.List; import java.util.Objects; -import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; @@ -85,7 +84,7 @@ public NodeList addAll(Collection c) { List stNodesToBeAdded = c.stream() .map(node -> Objects.requireNonNull(node, "node should not be null")) .map(Node::internalNode) - .collect(Collectors.toList()); + .toList(); return new NodeList<>(internalListNode.addAll(stNodesToBeAdded).createUnlinkedFacade()); } diff --git a/misc/toml-parser/src/main/java/io/ballerina/toml/syntax/tree/NonTerminalNode.java b/misc/toml-parser/src/main/java/io/ballerina/toml/syntax/tree/NonTerminalNode.java index 886c1840d3da..891c931a06ed 100644 --- a/misc/toml-parser/src/main/java/io/ballerina/toml/syntax/tree/NonTerminalNode.java +++ b/misc/toml-parser/src/main/java/io/ballerina/toml/syntax/tree/NonTerminalNode.java @@ -28,7 +28,6 @@ import java.util.Collections; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; import java.util.stream.IntStream; import static io.ballerina.toml.internal.syntax.SyntaxUtils.isSTNodePresent; @@ -70,7 +69,7 @@ public Collection childEntries() { IntStream.range(0, bucketCount()) .filter(bucket -> childInBucket(bucket) != null) .mapToObj(bucket -> new ChildNodeEntry(childNames[bucket], childInBucket(bucket))) - .collect(Collectors.toList())); + .toList()); } @Override @@ -91,8 +90,7 @@ public Token findToken(int position) { // If that is the case, return the eof token. // Fixes 24905 if (textRangeWithMinutiae.endOffset() == position && - this instanceof DocumentNode) { - DocumentNode modulePartNode = (DocumentNode) this; + this instanceof DocumentNode modulePartNode) { return modulePartNode.eofToken(); } diff --git a/misc/toml-parser/src/main/java/io/ballerina/toml/syntax/tree/TreeModifier.java b/misc/toml-parser/src/main/java/io/ballerina/toml/syntax/tree/TreeModifier.java index 29a57213035f..1b0298d57639 100644 --- a/misc/toml-parser/src/main/java/io/ballerina/toml/syntax/tree/TreeModifier.java +++ b/misc/toml-parser/src/main/java/io/ballerina/toml/syntax/tree/TreeModifier.java @@ -20,6 +20,7 @@ import io.ballerina.toml.internal.parser.tree.STNode; import io.ballerina.toml.internal.parser.tree.STNodeFactory; +import java.util.Arrays; import java.util.function.Function; /** @@ -222,7 +223,7 @@ protected NodeList modifyNodeList(NodeList nodeList) { } protected SeparatedNodeList modifySeparatedNodeList(SeparatedNodeList nodeList) { - Function nodeListCreator = SeparatedNodeList::new; + Function> nodeListCreator = SeparatedNodeList::new; if (nodeList.isEmpty()) { return nodeList; } @@ -256,7 +257,7 @@ protected SeparatedNodeList modifySeparatedNodeList(Separate return nodeList; } - STNode stNodeList = STNodeFactory.createNodeList(java.util.Arrays.asList(newSTNodes)); + STNode stNodeList = STNodeFactory.createNodeList(Arrays.asList(newSTNodes)); return nodeListCreator.apply(stNodeList.createUnlinkedFacade()); } @@ -282,7 +283,7 @@ private > N modifyGenericNodeList( return nodeList; } - STNode stNodeList = STNodeFactory.createNodeList(java.util.Arrays.asList(newSTNodes)); + STNode stNodeList = STNodeFactory.createNodeList(Arrays.asList(newSTNodes)); return nodeListCreator.apply(stNodeList.createUnlinkedFacade()); } diff --git a/misc/toml-parser/src/main/java/io/ballerina/toml/validator/BoilerplateGenerator.java b/misc/toml-parser/src/main/java/io/ballerina/toml/validator/BoilerplateGenerator.java index 04e9c3f1dcc4..57254127c3e7 100644 --- a/misc/toml-parser/src/main/java/io/ballerina/toml/validator/BoilerplateGenerator.java +++ b/misc/toml-parser/src/main/java/io/ballerina/toml/validator/BoilerplateGenerator.java @@ -163,7 +163,7 @@ private static boolean isDefaultValuesExist(Map children for (AbstractSchema value : children.values()) { //If Anything other than array or table if (!(value.type() == Type.OBJECT || value.type() == Type.ARRAY)) { - if (((PrimitiveValueSchema) value).defaultValue().isPresent()) { + if (((PrimitiveValueSchema) value).defaultValue().isPresent()) { return true; } } diff --git a/misc/toml-parser/src/main/java/io/ballerina/toml/validator/SampleNodeGenerator.java b/misc/toml-parser/src/main/java/io/ballerina/toml/validator/SampleNodeGenerator.java index 4be8b5a8f222..cce378c1d23f 100644 --- a/misc/toml-parser/src/main/java/io/ballerina/toml/validator/SampleNodeGenerator.java +++ b/misc/toml-parser/src/main/java/io/ballerina/toml/validator/SampleNodeGenerator.java @@ -36,9 +36,13 @@ * * @since v2.0.0 */ -public class SampleNodeGenerator { +public final class SampleNodeGenerator { + private static final String NEW_LINE = System.lineSeparator(); + private SampleNodeGenerator() { + } + public static KeyValueNode createStringKV(String key, String value, String description) { KeyNode keyNode = getKeyNode(key); Token assign = getAssignToken(); diff --git a/misc/toml-parser/src/main/java/io/ballerina/toml/validator/ValidationUtil.java b/misc/toml-parser/src/main/java/io/ballerina/toml/validator/ValidationUtil.java index 30ab7d3f3522..70254eeb7537 100644 --- a/misc/toml-parser/src/main/java/io/ballerina/toml/validator/ValidationUtil.java +++ b/misc/toml-parser/src/main/java/io/ballerina/toml/validator/ValidationUtil.java @@ -34,7 +34,10 @@ * * @since 2.0.0 */ -public class ValidationUtil { +public final class ValidationUtil { + + private ValidationUtil() { + } public static String getTypeErrorMessage(AbstractSchema schema, TomlType found, String key) { Map message = schema.message(); @@ -47,23 +50,14 @@ public static String getTypeErrorMessage(AbstractSchema schema, TomlType found, } public static Type tomlTypeValueToSchemaType(TomlType tomlType) { - switch (tomlType) { - case STRING: - return Type.STRING; - case DOUBLE: - case INTEGER: - return Type.NUMBER; - case BOOLEAN: - return Type.BOOLEAN; - case ARRAY: - case TABLE_ARRAY: - return Type.ARRAY; - case TABLE: - case INLINE_TABLE: - return Type.OBJECT; - default: - throw new IllegalArgumentException("Toml type is a invalid value"); - } + return switch (tomlType) { + case STRING -> Type.STRING; + case DOUBLE, INTEGER -> Type.NUMBER; + case BOOLEAN -> Type.BOOLEAN; + case ARRAY, TABLE_ARRAY -> Type.ARRAY; + case TABLE, INLINE_TABLE -> Type.OBJECT; + default -> throw new IllegalArgumentException("Toml type is a invalid value"); + }; } public static TomlDiagnostic getTomlDiagnostic(TomlNodeLocation location, String code, String template, diff --git a/misc/toml-parser/src/test/java/toml/parser/test/ParserTestConstants.java b/misc/toml-parser/src/test/java/toml/parser/test/ParserTestConstants.java index 28dd5d20bd0b..97a993f0eeda 100644 --- a/misc/toml-parser/src/test/java/toml/parser/test/ParserTestConstants.java +++ b/misc/toml-parser/src/test/java/toml/parser/test/ParserTestConstants.java @@ -23,7 +23,7 @@ * * @since 1.2.0 */ -public class ParserTestConstants { +public final class ParserTestConstants { public static final String KIND_FIELD = "kind"; @@ -40,4 +40,6 @@ public class ParserTestConstants { public static final String TRAILING_MINUTIAE = "trailingMinutiae"; + private ParserTestConstants() { + } } diff --git a/misc/toml-parser/src/test/java/toml/parser/test/ParserTestUtils.java b/misc/toml-parser/src/test/java/toml/parser/test/ParserTestUtils.java index 6817db152063..875c4924a956 100644 --- a/misc/toml-parser/src/test/java/toml/parser/test/ParserTestUtils.java +++ b/misc/toml-parser/src/test/java/toml/parser/test/ParserTestUtils.java @@ -56,7 +56,7 @@ * * @since 1.2.0 */ -public class ParserTestUtils { +public final class ParserTestUtils { private static final Path RESOURCE_DIRECTORY = Paths.get("src/test/resources/"); @@ -66,6 +66,9 @@ public class ParserTestUtils { */ private static final boolean UPDATE_ASSERTS = false; + private ParserTestUtils() { + } + /** * Test parsing a valid source. * @@ -325,33 +328,26 @@ public static boolean isKeyword(SyntaxKind syntaxKind) { } public static boolean isTrivia(SyntaxKind syntaxKind) { - switch (syntaxKind) { - case WHITESPACE_MINUTIAE: - case END_OF_LINE_MINUTIAE: - case COMMENT_MINUTIAE: - case INVALID_NODE_MINUTIAE: - return true; - default: - return false; - } + return switch (syntaxKind) { + case WHITESPACE_MINUTIAE, END_OF_LINE_MINUTIAE, COMMENT_MINUTIAE, INVALID_NODE_MINUTIAE -> true; + default -> false; + }; } public static String getTokenText(STToken token) { - switch (token.kind) { - case IDENTIFIER_LITERAL: + return switch (token.kind) { + case IDENTIFIER_LITERAL -> { String text = ((STIdentifierToken) token).text; - return cleanupText(text); - case STRING_LITERAL: - case DECIMAL_INT_TOKEN: - case DECIMAL_FLOAT_TOKEN: - case TRUE_KEYWORD: - case FALSE_KEYWORD: - return token.text(); - case INVALID_TOKEN: - return token.text(); - default: - return token.kind.toString(); - } + yield cleanupText(text); + } + case STRING_LITERAL, + DECIMAL_INT_TOKEN, + DECIMAL_FLOAT_TOKEN, + TRUE_KEYWORD, + FALSE_KEYWORD -> token.text(); + case INVALID_TOKEN -> token.text(); + default -> token.kind.toString(); + }; } private static String cleanupText(String text) { @@ -393,123 +389,66 @@ private static void updateAssertFile(String jsonString, Path assertFilePath) { } private static SyntaxKind getNodeKind(String kind) { - switch (kind) { - case "INLINE_TABLE": - return SyntaxKind.INLINE_TABLE; - case "NEW_LINE": - return SyntaxKind.NEWLINE; - case "TRUE_KEYWORD": - return SyntaxKind.TRUE_KEYWORD; - case "FALSE_KEYWORD": - return SyntaxKind.FALSE_KEYWORD; - case "OPEN_BRACE_TOKEN": - return SyntaxKind.OPEN_BRACE_TOKEN; - case "CLOSE_BRACE_TOKEN": - return SyntaxKind.CLOSE_BRACE_TOKEN; - case "OPEN_BRACKET_TOKEN": - return SyntaxKind.OPEN_BRACKET_TOKEN; - case "CLOSE_BRACKET_TOKEN": - return SyntaxKind.CLOSE_BRACKET_TOKEN; - case "DOT_TOKEN": - return SyntaxKind.DOT_TOKEN; - case "COMMA_TOKEN": - return SyntaxKind.COMMA_TOKEN; - case "HASH_TOKEN": - return SyntaxKind.HASH_TOKEN; - case "DOUBLE_QUOTE_TOKEN": - return SyntaxKind.DOUBLE_QUOTE_TOKEN; - case "SINGLE_QUOTE_TOKEN": - return SyntaxKind.SINGLE_QUOTE_TOKEN; - case "TRIPLE_DOUBLE_QUOTE_TOKEN": - return SyntaxKind.TRIPLE_DOUBLE_QUOTE_TOKEN; - case "TRIPLE_SINGLE_QUOTE_TOKEN": - return SyntaxKind.TRIPLE_SINGLE_QUOTE_TOKEN; - case "EQUAL_TOKEN": - return SyntaxKind.EQUAL_TOKEN; - case "PLUS_TOKEN": - return SyntaxKind.PLUS_TOKEN; - case "MINUS_TOKEN": - return SyntaxKind.MINUS_TOKEN; - case "STRING_LITERAL_TOKEN": - return SyntaxKind.STRING_LITERAL_TOKEN; - case "IDENTIFIER_LITERAL": - return SyntaxKind.IDENTIFIER_LITERAL; - case "STRING_LITERAL": - return SyntaxKind.STRING_LITERAL; - case "LITERAL_STRING": - return SyntaxKind.LITERAL_STRING; - case "WHITESPACE_MINUTIAE": - return SyntaxKind.WHITESPACE_MINUTIAE; - case "END_OF_LINE_MINUTIAE": - return SyntaxKind.END_OF_LINE_MINUTIAE; - case "COMMENT_MINUTIAE": - return SyntaxKind.COMMENT_MINUTIAE; - case "INVALID_NODE_MINUTIAE": - return SyntaxKind.INVALID_NODE_MINUTIAE; - case "INVALID_TOKEN": - return SyntaxKind.INVALID_TOKEN; - case "INVALID_TOKEN_MINUTIAE_NODE": - return SyntaxKind.INVALID_TOKEN_MINUTIAE_NODE; - case "MARKDOWN_DOCUMENTATION_LINE": - return SyntaxKind.MARKDOWN_DOCUMENTATION_LINE; - case "TABLE": - return SyntaxKind.TABLE; - case "KEY_VALUE": - return SyntaxKind.KEY_VALUE; - case "TABLE_ARRAY": - return SyntaxKind.TABLE_ARRAY; - case "KEY": - return SyntaxKind.KEY; - case "DEC_INT": - return SyntaxKind.DEC_INT; - case "HEX_INT": - return SyntaxKind.HEX_INT; - case "OCT_INT": - return SyntaxKind.OCT_INT; - case "BINARY_INT": - return SyntaxKind.BINARY_INT; - case "FLOAT": - return SyntaxKind.FLOAT; - case "INF_TOKEN": - return SyntaxKind.INF_TOKEN; - case "NAN_TOKEN": - return SyntaxKind.NAN_TOKEN; - case "ML_STRING_LITERAL": - return SyntaxKind.ML_STRING_LITERAL; - case "DECIMAL_INT_TOKEN": - return SyntaxKind.DECIMAL_INT_TOKEN; - case "DECIMAL_FLOAT_TOKEN": - return SyntaxKind.DECIMAL_FLOAT_TOKEN; - case "HEX_INTEGER_LITERAL_TOKEN": - return SyntaxKind.HEX_INTEGER_LITERAL_TOKEN; - case "OCTAL_INTEGER_LITERAL_TOKEN": - return SyntaxKind.OCTAL_INTEGER_LITERAL_TOKEN; - case "BINARY_INTEGER_LITERAL_TOKEN": - return SyntaxKind.BINARY_INTEGER_LITERAL_TOKEN; - case "BOOLEAN": - return SyntaxKind.BOOLEAN; - case "OFFSET_DATE_TIME": - return SyntaxKind.OFFSET_DATE_TIME; - case "LOCAL_DATE_TIME": - return SyntaxKind.LOCAL_DATE_TIME; - case "LOCAL_DATE": - return SyntaxKind.LOCAL_DATE; - case "LOCAL_TIME": - return SyntaxKind.LOCAL_TIME; - case "ARRAY": - return SyntaxKind.ARRAY; - case "INVALID": - return SyntaxKind.INVALID; - case "MODULE_PART": - return SyntaxKind.MODULE_PART; - case "EOF_TOKEN": - return SyntaxKind.EOF_TOKEN; - case "LIST": - return SyntaxKind.LIST; - case "NONE": - return SyntaxKind.NONE; - } - return null; + return switch (kind) { + case "INLINE_TABLE" -> SyntaxKind.INLINE_TABLE; + case "NEW_LINE" -> SyntaxKind.NEWLINE; + case "TRUE_KEYWORD" -> SyntaxKind.TRUE_KEYWORD; + case "FALSE_KEYWORD" -> SyntaxKind.FALSE_KEYWORD; + case "OPEN_BRACE_TOKEN" -> SyntaxKind.OPEN_BRACE_TOKEN; + case "CLOSE_BRACE_TOKEN" -> SyntaxKind.CLOSE_BRACE_TOKEN; + case "OPEN_BRACKET_TOKEN" -> SyntaxKind.OPEN_BRACKET_TOKEN; + case "CLOSE_BRACKET_TOKEN" -> SyntaxKind.CLOSE_BRACKET_TOKEN; + case "DOT_TOKEN" -> SyntaxKind.DOT_TOKEN; + case "COMMA_TOKEN" -> SyntaxKind.COMMA_TOKEN; + case "HASH_TOKEN" -> SyntaxKind.HASH_TOKEN; + case "DOUBLE_QUOTE_TOKEN" -> SyntaxKind.DOUBLE_QUOTE_TOKEN; + case "SINGLE_QUOTE_TOKEN" -> SyntaxKind.SINGLE_QUOTE_TOKEN; + case "TRIPLE_DOUBLE_QUOTE_TOKEN" -> SyntaxKind.TRIPLE_DOUBLE_QUOTE_TOKEN; + case "TRIPLE_SINGLE_QUOTE_TOKEN" -> SyntaxKind.TRIPLE_SINGLE_QUOTE_TOKEN; + case "EQUAL_TOKEN" -> SyntaxKind.EQUAL_TOKEN; + case "PLUS_TOKEN" -> SyntaxKind.PLUS_TOKEN; + case "MINUS_TOKEN" -> SyntaxKind.MINUS_TOKEN; + case "STRING_LITERAL_TOKEN" -> SyntaxKind.STRING_LITERAL_TOKEN; + case "IDENTIFIER_LITERAL" -> SyntaxKind.IDENTIFIER_LITERAL; + case "STRING_LITERAL" -> SyntaxKind.STRING_LITERAL; + case "LITERAL_STRING" -> SyntaxKind.LITERAL_STRING; + case "WHITESPACE_MINUTIAE" -> SyntaxKind.WHITESPACE_MINUTIAE; + case "END_OF_LINE_MINUTIAE" -> SyntaxKind.END_OF_LINE_MINUTIAE; + case "COMMENT_MINUTIAE" -> SyntaxKind.COMMENT_MINUTIAE; + case "INVALID_NODE_MINUTIAE" -> SyntaxKind.INVALID_NODE_MINUTIAE; + case "INVALID_TOKEN" -> SyntaxKind.INVALID_TOKEN; + case "INVALID_TOKEN_MINUTIAE_NODE" -> SyntaxKind.INVALID_TOKEN_MINUTIAE_NODE; + case "MARKDOWN_DOCUMENTATION_LINE" -> SyntaxKind.MARKDOWN_DOCUMENTATION_LINE; + case "TABLE" -> SyntaxKind.TABLE; + case "KEY_VALUE" -> SyntaxKind.KEY_VALUE; + case "TABLE_ARRAY" -> SyntaxKind.TABLE_ARRAY; + case "KEY" -> SyntaxKind.KEY; + case "DEC_INT" -> SyntaxKind.DEC_INT; + case "HEX_INT" -> SyntaxKind.HEX_INT; + case "OCT_INT" -> SyntaxKind.OCT_INT; + case "BINARY_INT" -> SyntaxKind.BINARY_INT; + case "FLOAT" -> SyntaxKind.FLOAT; + case "INF_TOKEN" -> SyntaxKind.INF_TOKEN; + case "NAN_TOKEN" -> SyntaxKind.NAN_TOKEN; + case "ML_STRING_LITERAL" -> SyntaxKind.ML_STRING_LITERAL; + case "DECIMAL_INT_TOKEN" -> SyntaxKind.DECIMAL_INT_TOKEN; + case "DECIMAL_FLOAT_TOKEN" -> SyntaxKind.DECIMAL_FLOAT_TOKEN; + case "HEX_INTEGER_LITERAL_TOKEN" -> SyntaxKind.HEX_INTEGER_LITERAL_TOKEN; + case "OCTAL_INTEGER_LITERAL_TOKEN" -> SyntaxKind.OCTAL_INTEGER_LITERAL_TOKEN; + case "BINARY_INTEGER_LITERAL_TOKEN" -> SyntaxKind.BINARY_INTEGER_LITERAL_TOKEN; + case "BOOLEAN" -> SyntaxKind.BOOLEAN; + case "OFFSET_DATE_TIME" -> SyntaxKind.OFFSET_DATE_TIME; + case "LOCAL_DATE_TIME" -> SyntaxKind.LOCAL_DATE_TIME; + case "LOCAL_DATE" -> SyntaxKind.LOCAL_DATE; + case "LOCAL_TIME" -> SyntaxKind.LOCAL_TIME; + case "ARRAY" -> SyntaxKind.ARRAY; + case "INVALID" -> SyntaxKind.INVALID; + case "MODULE_PART" -> SyntaxKind.MODULE_PART; + case "EOF_TOKEN" -> SyntaxKind.EOF_TOKEN; + case "LIST" -> SyntaxKind.LIST; + case "NONE" -> SyntaxKind.NONE; + default -> null; + }; } public static void assertLineRange(LineRange lineRange, int startLine, int startOffset, int endLine, diff --git a/misc/toml-parser/src/test/java/toml/parser/test/SyntaxTreeJSONGenerator.java b/misc/toml-parser/src/test/java/toml/parser/test/SyntaxTreeJSONGenerator.java index 61216e22d6c7..e2899d7e6b0b 100644 --- a/misc/toml-parser/src/test/java/toml/parser/test/SyntaxTreeJSONGenerator.java +++ b/misc/toml-parser/src/test/java/toml/parser/test/SyntaxTreeJSONGenerator.java @@ -48,7 +48,7 @@ * * @since 1.2.0 */ -public class SyntaxTreeJSONGenerator { +public final class SyntaxTreeJSONGenerator { /* * Change the below two constants as required, depending on the type of test. @@ -57,6 +57,9 @@ public class SyntaxTreeJSONGenerator { private static final PrintStream STANDARD_OUT = System.out; private static final Path RESOURCE_DIRECTORY = Paths.get("src/test/resources/"); + private SyntaxTreeJSONGenerator() { + } + public static void main(String[] args) throws IOException { Path syntax = RESOURCE_DIRECTORY.resolve(Paths.get("syntax")); diff --git a/misc/toml-parser/src/test/java/toml/parser/test/TestToml.java b/misc/toml-parser/src/test/java/toml/parser/test/TestToml.java index bff07c5f39c5..fba79f0ac120 100644 --- a/misc/toml-parser/src/test/java/toml/parser/test/TestToml.java +++ b/misc/toml-parser/src/test/java/toml/parser/test/TestToml.java @@ -31,10 +31,13 @@ /** * Test the parser. */ -public class TestToml { +public final class TestToml { private static final PrintStream OUT = System.out; + private TestToml() { + } + public static void main(String[] args) throws IOException { String path = "src/test/resources/basic-toml.toml"; testAPI(path); diff --git a/misc/toml-parser/src/test/java/toml/parser/test/TestTomlValidator.java b/misc/toml-parser/src/test/java/toml/parser/test/TestTomlValidator.java index 011724d711b8..1a814f4e31c9 100644 --- a/misc/toml-parser/src/test/java/toml/parser/test/TestTomlValidator.java +++ b/misc/toml-parser/src/test/java/toml/parser/test/TestTomlValidator.java @@ -33,9 +33,13 @@ * * @since 2.0.0 */ -public class TestTomlValidator { +public final class TestTomlValidator { + private static final PrintStream OUT = System.out; + private TestTomlValidator() { + } + public static void main(String [] args) throws IOException { Path resourceDirectory = Paths.get("src", "test", "resources", "validator", "sample-schema.json"); TomlValidator validator = new TomlValidator(Schema.from(resourceDirectory)); diff --git a/misc/toml-parser/src/test/java/toml/parser/test/api/object/ToObjectTest.java b/misc/toml-parser/src/test/java/toml/parser/test/api/object/ToObjectTest.java index de8eeef5d06a..52709cecddf4 100644 --- a/misc/toml-parser/src/test/java/toml/parser/test/api/object/ToObjectTest.java +++ b/misc/toml-parser/src/test/java/toml/parser/test/api/object/ToObjectTest.java @@ -148,7 +148,7 @@ public void testToObject() throws IOException { Assert.assertEquals(thirdTableStr1, "tableArr kv1 third"); } - class NewObject { + private static class NewObject { private String simplekv; private String simplekv1; private int simpleint; @@ -191,7 +191,7 @@ public List getTableArr() { } } - class Table { + private static class Table { private String tableKv; private String tableKv1; private Child child; @@ -209,7 +209,7 @@ public Child getChild() { } } - class Child { + static class Child { private String tableKvChild; private String tableKv1Child; private GrandChild grandchild; @@ -227,7 +227,7 @@ public GrandChild getGrandChild() { } } - class GrandChild { + static class GrandChild { private String tableKvGrandChild; private String tableKv1GrandChild; @@ -240,7 +240,7 @@ public String getTableKv1GrandChild() { } } - class TableArr { + static class TableArr { private String tableKv; private String tableKv1; diff --git a/misc/toml-parser/src/test/java/toml/parser/test/diagnostics/DiagnosticCodeTest.java b/misc/toml-parser/src/test/java/toml/parser/test/diagnostics/DiagnosticCodeTest.java index 7abae0b2038d..3baa05ab3e53 100644 --- a/misc/toml-parser/src/test/java/toml/parser/test/diagnostics/DiagnosticCodeTest.java +++ b/misc/toml-parser/src/test/java/toml/parser/test/diagnostics/DiagnosticCodeTest.java @@ -66,7 +66,7 @@ private void validateDiagnosticUniqueness(DiagnosticCode[] codes) { } } - private String arrayToString(List listOfStrings) { + private String arrayToString(List listOfStrings) { return String.join(", ", listOfStrings); } } diff --git a/misc/xml-to-record-converter/src/main/java/io/ballerina/xmltorecordconverter/Constants.java b/misc/xml-to-record-converter/src/main/java/io/ballerina/xmltorecordconverter/Constants.java index 35906b9cc9f7..b5dd55a950bf 100644 --- a/misc/xml-to-record-converter/src/main/java/io/ballerina/xmltorecordconverter/Constants.java +++ b/misc/xml-to-record-converter/src/main/java/io/ballerina/xmltorecordconverter/Constants.java @@ -23,6 +23,10 @@ * * @since 2201.7.2 */ -public class Constants { +public final class Constants { + public static final String CAPABILITY_NAME = "xmlToRecord"; + + private Constants() { + } } diff --git a/misc/xml-to-record-converter/src/main/java/io/ballerina/xmltorecordconverter/XMLToRecordConverter.java b/misc/xml-to-record-converter/src/main/java/io/ballerina/xmltorecordconverter/XMLToRecordConverter.java index 253e1507553e..5e3dd99c406e 100644 --- a/misc/xml-to-record-converter/src/main/java/io/ballerina/xmltorecordconverter/XMLToRecordConverter.java +++ b/misc/xml-to-record-converter/src/main/java/io/ballerina/xmltorecordconverter/XMLToRecordConverter.java @@ -87,7 +87,7 @@ * * @since 2201.7.2 */ -public class XMLToRecordConverter { +public final class XMLToRecordConverter { private XMLToRecordConverter() {} @@ -97,7 +97,8 @@ private XMLToRecordConverter() {} public static XMLToRecordResponse convert(String xmlValue, boolean isRecordTypeDesc, boolean isClosed, boolean forceFormatRecordFields, - String textFieldName, boolean withNameSpaces) { + String textFieldName, boolean withNameSpaces, boolean withoutAttributes, + boolean withoutAttributeAnnot) { Map recordToTypeDescNodes = new LinkedHashMap<>(); Map recordToAnnotationNodes = new LinkedHashMap<>(); Map recordToElementNodes = new LinkedHashMap<>(); @@ -116,7 +117,8 @@ public static XMLToRecordResponse convert(String xmlValue, boolean isRecordTypeD Element rootElement = doc.getDocumentElement(); generateRecords(rootElement, isClosed, recordToTypeDescNodes, recordToAnnotationNodes, - recordToElementNodes, diagnosticMessages, textFieldName, withNameSpaces); + recordToElementNodes, diagnosticMessages, textFieldName, withNameSpaces, withoutAttributes, + withoutAttributeAnnot); } catch (ParserConfigurationException parserConfigurationException) { DiagnosticMessage message = DiagnosticMessage.xmlToRecordConverter100(null); diagnosticMessages.add(message); @@ -187,7 +189,7 @@ public static XMLToRecordResponse convert(String xmlValue, boolean isRecordTypeD */ public static XMLToRecordResponse convert(String xmlValue, boolean isRecordTypeDesc, boolean isClosed, boolean forceFormatRecordFields) { - return convert(xmlValue, isRecordTypeDesc, isClosed, forceFormatRecordFields, null, true); + return convert(xmlValue, isRecordTypeDesc, isClosed, forceFormatRecordFields, null, true, false, false); } private static void generateRecords(Element xmlElement, boolean isClosed, @@ -195,7 +197,8 @@ private static void generateRecords(Element xmlElement, boolean isClosed, Map recordToAnnotationsNodes, Map recordToElementNodes, List diagnosticMessages, - String textFieldName, boolean withNameSpace) { + String textFieldName, boolean withNameSpace, boolean withoutAttributes, + boolean withoutAttributeAnnot) { Token recordKeyWord = AbstractNodeFactory.createToken(SyntaxKind.RECORD_KEYWORD); Token bodyStartDelimiter = AbstractNodeFactory.createToken(isClosed ? SyntaxKind.OPEN_BRACE_PIPE_TOKEN : SyntaxKind.OPEN_BRACE_TOKEN); @@ -204,7 +207,7 @@ private static void generateRecords(Element xmlElement, boolean isClosed, List recordFields = getRecordFieldsForXMLElement(xmlElement, isClosed, recordToTypeDescNodes, recordToAnnotationsNodes, recordToElementNodes, diagnosticMessages, textFieldName, - withNameSpace); + withNameSpace, withoutAttributes, withoutAttributeAnnot); if (recordToTypeDescNodes.containsKey(xmlNodeName)) { RecordTypeDescriptorNode previousRecordTypeDescriptorNode = (RecordTypeDescriptorNode) recordToTypeDescNodes.get(xmlNodeName); @@ -237,7 +240,8 @@ private static List getRecordFieldsForXMLElement(Element xmlElement, boole Map recordToAnnotationNodes, Map recordToElementNodes, List diagnosticMessages, - String textFieldName, boolean withNameSpace) { + String textFieldName, boolean withNameSpace, + boolean withoutAttributes, boolean withoutAttributeAnnot) { List recordFields = new ArrayList<>(); String xmlNodeName = xmlElement.getNodeName(); @@ -249,16 +253,17 @@ private static List getRecordFieldsForXMLElement(Element xmlElement, boole Element xmlElementNode = (Element) xmlNode; boolean isLeafXMLElementNode = isLeafXMLElementNode(xmlElementNode); NamedNodeMap xmlAttributesMap = xmlElementNode.getAttributes(); - if (!isLeafXMLElementNode || xmlAttributesMap.getLength() > 1 + if (!isLeafXMLElementNode || (!withoutAttributes && (xmlAttributesMap.getLength() > 1 || (xmlAttributesMap.getLength() == 1 - && !XMLNS_PREFIX.equals(xmlAttributesMap.item(0).getPrefix()))) { + && !XMLNS_PREFIX.equals(xmlAttributesMap.item(0).getPrefix()))))) { generateRecords(xmlElementNode, isClosed, recordToTypeDescNodes, recordToAnnotationNodes, - recordToElementNodes, diagnosticMessages, textFieldName, withNameSpace); + recordToElementNodes, diagnosticMessages, textFieldName, withNameSpace, withoutAttributes, + withoutAttributeAnnot); } Map prefixMap = hasMultipleFieldsWithSameName(xmlNodeList, xmlElementNode.getLocalName()); RecordFieldNode recordField = getRecordField(xmlElementNode, false, withNameSpace, - prefixMap.size() > 1); + prefixMap.size() > 1, withoutAttributes); if (withNameSpace && xmlElementNode.getPrefix() != null) { int indexOfRecordFieldNode = IntStream.range(0, recordFields.size()) @@ -315,18 +320,18 @@ private static List getRecordFieldsForXMLElement(Element xmlElement, boole AnnotationNode xmlNSNode = getXMLNamespaceNode(prefix, xmlNode.getNodeValue()); recordToAnnotationNodes.put(xmlNodeName, xmlNSNode); } else if (!isLeafXMLElementNode(xmlElement) && !XMLNS_PREFIX.equals(xmlNode.getPrefix()) - && !XMLNS_PREFIX.equals(xmlNode.getLocalName())) { + && !XMLNS_PREFIX.equals(xmlNode.getLocalName()) && !withoutAttributes) { if (elementNames.contains(xmlNode.getNodeName())) { continue; } - Node recordField = getRecordField(xmlNode, withNameSpace); + Node recordField = getRecordField(xmlNode, withNameSpace, withoutAttributeAnnot); recordFields.add(recordField); } } } int attributeLength = xmlElement.getAttributes().getLength(); org.w3c.dom.Node attributeItem = xmlElement.getAttributes().item(0); - if (isLeafXMLElementNode(xmlElement) && attributeLength > 0) { + if (isLeafXMLElementNode(xmlElement) && attributeLength > 0 && !withoutAttributes) { if (attributeLength == 1 && attributeItem.getPrefix() != null && XMLNS_PREFIX.equals(attributeItem.getPrefix())) { return recordFields; @@ -345,7 +350,7 @@ private static List getRecordFieldsForXMLElement(Element xmlElement, boole if (xmlAttributeNode.getNodeType() == org.w3c.dom.Node.ATTRIBUTE_NODE && !XMLNS_PREFIX.equals(xmlAttributeNode.getPrefix()) && !XMLNS_PREFIX.equals(xmlAttributeNode.getLocalName())) { - Node recordField = getRecordField(xmlAttributeNode, withNameSpace); + Node recordField = getRecordField(xmlAttributeNode, withNameSpace, withoutAttributeAnnot); recordFields.add(recordField); } } @@ -467,7 +472,8 @@ private static List updateRecordFields(Map previo } private static RecordFieldNode getRecordField(Element xmlElementNode, boolean isOptionalField, - boolean withNameSpace, boolean sameFieldExists) { + boolean withNameSpace, boolean sameFieldExists, + boolean withoutAttributes) { Token typeName; Token questionMarkToken = AbstractNodeFactory.createToken(SyntaxKind.QUESTION_MARK_TOKEN); IdentifierToken fieldName = @@ -478,7 +484,7 @@ private static RecordFieldNode getRecordField(Element xmlElementNode, boolean is NamedNodeMap xmlAttributesMap = xmlElementNode.getAttributes(); if (isLeafXMLElementNode(xmlElementNode) && (xmlAttributesMap.getLength() == 0 || (xmlAttributesMap.getLength() == 1 - && XMLNS_PREFIX.equals(xmlAttributesMap.item(0).getPrefix())))) { + && XMLNS_PREFIX.equals(xmlAttributesMap.item(0).getPrefix())) || withoutAttributes)) { typeName = getPrimitiveTypeName(xmlElementNode.getFirstChild().getNodeValue()); } else { // At the moment all are considered as Objects here @@ -507,7 +513,8 @@ private static RecordFieldNode getRecordField(Element xmlElementNode, boolean is metadataNode, null, fieldTypeName, fieldName, optionalFieldToken, semicolonToken); } - private static Node getRecordField(org.w3c.dom.Node xmlAttributeNode, boolean withNamespace) { + private static Node getRecordField(org.w3c.dom.Node xmlAttributeNode, boolean withNamespace, + boolean withoutAttributeAnnot) { Token typeName = AbstractNodeFactory.createToken(SyntaxKind.STRING_KEYWORD); TypeDescriptorNode fieldTypeName = NodeFactory.createBuiltinSimpleNameReferenceNode(typeName.kind(), typeName); IdentifierToken fieldName = @@ -520,7 +527,8 @@ private static Node getRecordField(org.w3c.dom.Node xmlAttributeNode, boolean wi } annotations.add(getXMLAttributeNode()); NodeList annotationNodes = NodeFactory.createNodeList(annotations); - MetadataNode metadataNode = NodeFactory.createMetadataNode(null, annotationNodes); + MetadataNode metadataNode = withoutAttributeAnnot ? null : + NodeFactory.createMetadataNode(null, annotationNodes); if (xmlAttributeNode.getPrefix() != null && xmlAttributeNode.getPrefix().equals(XMLNS_PREFIX)) { diff --git a/misc/xml-to-record-converter/src/main/java/io/ballerina/xmltorecordconverter/XMLToRecordConverterService.java b/misc/xml-to-record-converter/src/main/java/io/ballerina/xmltorecordconverter/XMLToRecordConverterService.java index c0f7b3782040..8e0b5252eff9 100644 --- a/misc/xml-to-record-converter/src/main/java/io/ballerina/xmltorecordconverter/XMLToRecordConverterService.java +++ b/misc/xml-to-record-converter/src/main/java/io/ballerina/xmltorecordconverter/XMLToRecordConverterService.java @@ -48,9 +48,11 @@ public CompletableFuture convert(XMLToRecordRequest request boolean forceFormatRecordFields = request.getForceFormatRecordFields(); String textFieldName = request.getTextFieldName(); boolean withNameSpace = request.getIsWithNameSpace(); + boolean withoutAttributes = request.getWithoutAttributes(); + boolean withoutAttributeAnnot = request.getWithoutAttributeAnnot(); return XMLToRecordConverter.convert(xmlValue, isRecordTypeDesc, isClosed, forceFormatRecordFields, - textFieldName, withNameSpace); + textFieldName, withNameSpace, withoutAttributes, withoutAttributeAnnot); }); } diff --git a/misc/xml-to-record-converter/src/main/java/io/ballerina/xmltorecordconverter/XMLToRecordRequest.java b/misc/xml-to-record-converter/src/main/java/io/ballerina/xmltorecordconverter/XMLToRecordRequest.java index be28d7cadfb4..46b0607c2a6c 100644 --- a/misc/xml-to-record-converter/src/main/java/io/ballerina/xmltorecordconverter/XMLToRecordRequest.java +++ b/misc/xml-to-record-converter/src/main/java/io/ballerina/xmltorecordconverter/XMLToRecordRequest.java @@ -31,15 +31,20 @@ public class XMLToRecordRequest { private final boolean forceFormatRecordFields; private final String textFieldName; private final boolean withNameSpace; + private final boolean withoutAttributes; + private final boolean withoutAttributeAnnot; public XMLToRecordRequest(String xmlValue, boolean isRecordTypeDesc, boolean isClosed, - boolean forceFormatRecordFields, String textFieldName, boolean withNameSpace) { + boolean forceFormatRecordFields, String textFieldName, boolean withNameSpace, + boolean withoutAttributes, boolean withoutAttributeAnnot) { this.xmlValue = xmlValue; this.isRecordTypeDesc = isRecordTypeDesc; this.isClosed = isClosed; this.forceFormatRecordFields = forceFormatRecordFields; this.textFieldName = textFieldName; this.withNameSpace = withNameSpace; + this.withoutAttributes = withoutAttributes; + this.withoutAttributeAnnot = withoutAttributeAnnot; } public String getXmlValue() { @@ -65,4 +70,12 @@ public String getTextFieldName() { public boolean getIsWithNameSpace() { return withNameSpace; } + + public boolean getWithoutAttributes() { + return withoutAttributes; + } + + public boolean getWithoutAttributeAnnot() { + return withoutAttributeAnnot; + } } diff --git a/misc/xml-to-record-converter/src/main/java/io/ballerina/xmltorecordconverter/diagnostic/DiagnosticUtils.java b/misc/xml-to-record-converter/src/main/java/io/ballerina/xmltorecordconverter/diagnostic/DiagnosticUtils.java index e4cc4e920290..5766eb9bee9f 100644 --- a/misc/xml-to-record-converter/src/main/java/io/ballerina/xmltorecordconverter/diagnostic/DiagnosticUtils.java +++ b/misc/xml-to-record-converter/src/main/java/io/ballerina/xmltorecordconverter/diagnostic/DiagnosticUtils.java @@ -27,7 +27,7 @@ * * @since 2201.7.2 */ -public class DiagnosticUtils { +public final class DiagnosticUtils { private DiagnosticUtils() {} diff --git a/misc/xml-to-record-converter/src/main/java/io/ballerina/xmltorecordconverter/util/ConverterUtils.java b/misc/xml-to-record-converter/src/main/java/io/ballerina/xmltorecordconverter/util/ConverterUtils.java index fc665a513cd8..0a2100f94e26 100644 --- a/misc/xml-to-record-converter/src/main/java/io/ballerina/xmltorecordconverter/util/ConverterUtils.java +++ b/misc/xml-to-record-converter/src/main/java/io/ballerina/xmltorecordconverter/util/ConverterUtils.java @@ -42,7 +42,7 @@ * * @since 2201.7.2 */ -public class ConverterUtils { +public final class ConverterUtils { private ConverterUtils() {} @@ -99,10 +99,10 @@ public static List extractTypeDescriptorNodes(List extractedTypeNames = new ArrayList<>(); for (TypeDescriptorNode typeDescNode : typeDescNodes) { TypeDescriptorNode extractedTypeDescNode = extractParenthesisedTypeDescNode(typeDescNode); - if (extractedTypeDescNode instanceof UnionTypeDescriptorNode) { + if (extractedTypeDescNode instanceof UnionTypeDescriptorNode unionTypeDescriptorNode) { List childTypeDescNodes = - List.of(((UnionTypeDescriptorNode) extractedTypeDescNode).leftTypeDesc(), - ((UnionTypeDescriptorNode) extractedTypeDescNode).rightTypeDesc()); + List.of(unionTypeDescriptorNode.leftTypeDesc(), + unionTypeDescriptorNode.rightTypeDesc()); addIfNotExist(extractedTypeNames, extractTypeDescriptorNodes(childTypeDescNodes)); } else { addIfNotExist(extractedTypeNames, List.of(extractedTypeDescNode)); @@ -135,7 +135,7 @@ public static List sortTypeDescriptorNodes(List extractUnionTypeDescNode(TypeDescriptorNo */ public static Integer getNumberOfDimensions(ArrayTypeDescriptorNode arrayNode) { int totalDimensions = arrayNode.dimensions().size(); - if (arrayNode.memberTypeDesc() instanceof ArrayTypeDescriptorNode) { - totalDimensions += getNumberOfDimensions((ArrayTypeDescriptorNode) arrayNode.memberTypeDesc()); + if (arrayNode.memberTypeDesc() instanceof ArrayTypeDescriptorNode arrayTypeDescriptorNode) { + totalDimensions += getNumberOfDimensions(arrayTypeDescriptorNode); } return totalDimensions; } private static TypeDescriptorNode extractArrayTypeDescNode(ArrayTypeDescriptorNode arrayTypeDescNode) { - if (arrayTypeDescNode.memberTypeDesc() instanceof ArrayTypeDescriptorNode) { - return extractArrayTypeDescNode((ArrayTypeDescriptorNode) arrayTypeDescNode.memberTypeDesc()); + if (arrayTypeDescNode.memberTypeDesc() instanceof ArrayTypeDescriptorNode arrayTypeDescriptorNode) { + return extractArrayTypeDescNode(arrayTypeDescriptorNode); } return arrayTypeDescNode.memberTypeDesc(); } private static TypeDescriptorNode extractParenthesisedTypeDescNode(TypeDescriptorNode typeDescNode) { - if (typeDescNode instanceof ParenthesisedTypeDescriptorNode) { - return extractParenthesisedTypeDescNode(((ParenthesisedTypeDescriptorNode) typeDescNode).typedesc()); + if (typeDescNode instanceof ParenthesisedTypeDescriptorNode parenthesisedTypeDescriptorNode) { + return extractParenthesisedTypeDescNode(parenthesisedTypeDescriptorNode.typedesc()); } return typeDescNode; } diff --git a/misc/xml-to-record-converter/src/test/java/io/ballerina/xmltorecordconverter/XMLToRecordConverterTests.java b/misc/xml-to-record-converter/src/test/java/io/ballerina/xmltorecordconverter/XMLToRecordConverterTests.java index 70b9a80c073c..f94e22944551 100644 --- a/misc/xml-to-record-converter/src/test/java/io/ballerina/xmltorecordconverter/XMLToRecordConverterTests.java +++ b/misc/xml-to-record-converter/src/test/java/io/ballerina/xmltorecordconverter/XMLToRecordConverterTests.java @@ -229,6 +229,20 @@ public class XMLToRecordConverterTests { private final Path sample37Bal = RES_DIR.resolve(BAL_DIR) .resolve("sample_37.bal"); + private final Path sample38XML = RES_DIR.resolve(XML_DIR) + .resolve("sample_38.xml"); + private final Path sample39Bal = RES_DIR.resolve(BAL_DIR) + .resolve("sample_39.bal"); + private final Path sample40Bal = RES_DIR.resolve(BAL_DIR) + .resolve("sample_40.bal"); + + private final Path sample39XML = RES_DIR.resolve(XML_DIR) + .resolve("sample_39.xml"); + private final Path sample41Bal = RES_DIR.resolve(BAL_DIR) + .resolve("sample_41.bal"); + private final Path sample42Bal = RES_DIR.resolve(BAL_DIR) + .resolve("sample_42.bal"); + private static final String XMLToRecordServiceEP = "xmlToRecord/convert"; @@ -407,7 +421,7 @@ public void testWithMultipleAttributes() throws IOException { public void testXMLWithNamespacesWithoutNamespaceAttribute() throws IOException { String xmlFileContent = Files.readString(sample19XML); String generatedCodeBlock = XMLToRecordConverter.convert(xmlFileContent, false, false, false, - "amount", false).getCodeBlock().replaceAll("\\s+", ""); + "amount", false, false, false).getCodeBlock().replaceAll("\\s+", ""); String expectedCodeBlock = Files.readString(sample19Bal).replaceAll("\\s+", ""); Assert.assertEquals(generatedCodeBlock, expectedCodeBlock); } @@ -416,7 +430,7 @@ public void testXMLWithNamespacesWithoutNamespaceAttribute() throws IOException public void testXMLWithMultipleAttributesAndNamespacesWithoutAnnotations() throws IOException { String xmlFileContent = Files.readString(sample20XML); String generatedCodeBlock = XMLToRecordConverter.convert(xmlFileContent, false, false, false, - null, false).getCodeBlock().replaceAll("\\s+", ""); + null, false, false, false).getCodeBlock().replaceAll("\\s+", ""); String expectedCodeBlock = Files.readString(sample20Bal).replaceAll("\\s+", ""); Assert.assertEquals(generatedCodeBlock, expectedCodeBlock); } @@ -425,7 +439,7 @@ public void testXMLWithMultipleAttributesAndNamespacesWithoutAnnotations() throw public void testXMLWithMultipleAttributesAndNamespacesWithAnnotations() throws IOException { String xmlFileContent = Files.readString(sample21XML); String generatedCodeBlock = XMLToRecordConverter.convert(xmlFileContent, false, false, false, - null, true).getCodeBlock().replaceAll("\\s+", ""); + null, true, false, false).getCodeBlock().replaceAll("\\s+", ""); String expectedCodeBlock = Files.readString(sample21Bal).replaceAll("\\s+", ""); Assert.assertEquals(generatedCodeBlock, expectedCodeBlock); } @@ -434,7 +448,7 @@ public void testXMLWithMultipleAttributesAndNamespacesWithAnnotations() throws I public void testXMLWithoutNamespacePrefix() throws IOException { String xmlFileContent = Files.readString(sample22XML); String generatedCodeBlock = XMLToRecordConverter.convert(xmlFileContent, false, false, false, - null, true).getCodeBlock().replaceAll("\\s+", ""); + null, true, false, false).getCodeBlock().replaceAll("\\s+", ""); String expectedCodeBlock = Files.readString(sample22Bal).replaceAll("\\s+", ""); Assert.assertEquals(generatedCodeBlock, expectedCodeBlock); } @@ -443,7 +457,7 @@ public void testXMLWithoutNamespacePrefix() throws IOException { public void testXMLWithConflictingElementAndAttributeNames() throws IOException { String xmlFileContent = Files.readString(sample23XML); String generatedCodeBlock = XMLToRecordConverter.convert(xmlFileContent, false, false, false, - null, true).getCodeBlock().replaceAll("\\s+", ""); + null, true, false, false).getCodeBlock().replaceAll("\\s+", ""); String expectedCodeBlock = Files.readString(sample23Bal).replaceAll("\\s+", ""); Assert.assertEquals(generatedCodeBlock, expectedCodeBlock); } @@ -452,7 +466,7 @@ public void testXMLWithConflictingElementAndAttributeNames() throws IOException public void testXMLWithoutNamespaces() throws IOException { String xmlFileContent = Files.readString(sample24XML); String generatedCodeBlock = XMLToRecordConverter.convert(xmlFileContent, false, false, false, - null, false).getCodeBlock().replaceAll("\\s+", ""); + null, false, false, false).getCodeBlock().replaceAll("\\s+", ""); String expectedCodeBlock = Files.readString(sample24Bal).replaceAll("\\s+", ""); Assert.assertEquals(generatedCodeBlock, expectedCodeBlock); } @@ -462,7 +476,7 @@ public void testXMLToRecordService() throws IOException, ExecutionException, Int Endpoint serviceEndpoint = TestUtil.initializeLanguageSever(); String xmlValue = Files.readString(sample0XML); - XMLToRecordRequest request = new XMLToRecordRequest(xmlValue, false, false, false, null, true); + XMLToRecordRequest request = new XMLToRecordRequest(xmlValue, false, false, false, null, true, false, false); CompletableFuture result = serviceEndpoint.request(XMLToRecordServiceEP, request); XMLToRecordResponse response = (XMLToRecordResponse) result.get(); String generatedCodeBlock = response.getCodeBlock().replaceAll("\\s+", ""); @@ -476,7 +490,8 @@ public void testXMLToRecordServiceWithFieldNameAndWithoutNamespace() Endpoint serviceEndpoint = TestUtil.initializeLanguageSever(); String xmlValue = Files.readString(sample25XML); - XMLToRecordRequest request = new XMLToRecordRequest(xmlValue, false, false, false, "__text", false); + XMLToRecordRequest request = new XMLToRecordRequest(xmlValue, false, false, false, "__text", + false, false, false); CompletableFuture result = serviceEndpoint.request(XMLToRecordServiceEP, request); XMLToRecordResponse response = (XMLToRecordResponse) result.get(); String generatedCodeBlock = response.getCodeBlock().replaceAll("\\s+", ""); @@ -497,7 +512,7 @@ public void testXMLWithMultipleAttributes() throws IOException { public void testXMLWithoutNamespaceAnnotations() throws IOException { String xmlFileContent = Files.readString(sample27XML); String generatedCodeBlock = XMLToRecordConverter.convert(xmlFileContent, false, false, false, - null, false).getCodeBlock().replaceAll("\\s+", ""); + null, false, false, false).getCodeBlock().replaceAll("\\s+", ""); String expectedCodeBlock = Files.readString(sample27Bal).replaceAll("\\s+", ""); Assert.assertEquals(generatedCodeBlock, expectedCodeBlock); } @@ -506,7 +521,7 @@ public void testXMLWithoutNamespaceAnnotations() throws IOException { public void testXMLWithMultipleNamespacesAndSameElement() throws IOException { String xmlFileContent = Files.readString(sample28XML); String generatedCodeBlock = XMLToRecordConverter.convert(xmlFileContent, false, false, false, - null, true).getCodeBlock().replaceAll("\\s+", ""); + null, true, false, false).getCodeBlock().replaceAll("\\s+", ""); String expectedCodeBlock = Files.readString(sample28Bal).replaceAll("\\s+", ""); Assert.assertEquals(generatedCodeBlock, expectedCodeBlock); } @@ -515,7 +530,7 @@ public void testXMLWithMultipleNamespacesAndSameElement() throws IOException { public void testXMLWithMultipleNamespaces2() throws IOException { String xmlFileContent = Files.readString(sample29XML); String generatedCodeBlock = XMLToRecordConverter.convert(xmlFileContent, false, false, false, - null, true).getCodeBlock().replaceAll("\\s+", ""); + null, true, false, false).getCodeBlock().replaceAll("\\s+", ""); String expectedCodeBlock = Files.readString(sample29Bal).replaceAll("\\s+", ""); Assert.assertEquals(generatedCodeBlock, expectedCodeBlock); } @@ -524,7 +539,7 @@ public void testXMLWithMultipleNamespaces2() throws IOException { public void testXMLWithMultipleNamespaces3() throws IOException { String xmlFileContent = Files.readString(sample30XML); String generatedCodeBlock = XMLToRecordConverter.convert(xmlFileContent, false, false, false, - null, true).getCodeBlock().replaceAll("\\s+", ""); + null, true, false, false).getCodeBlock().replaceAll("\\s+", ""); String expectedCodeBlock = Files.readString(sample30Bal).replaceAll("\\s+", ""); Assert.assertEquals(generatedCodeBlock, expectedCodeBlock); } @@ -533,7 +548,7 @@ public void testXMLWithMultipleNamespaces3() throws IOException { public void testXMLWithoutNamespaceAnnotation() throws IOException { String xmlFileContent = Files.readString(sample31XML); String generatedCodeBlock = XMLToRecordConverter.convert(xmlFileContent, false, false, false, - null, false).getCodeBlock().replaceAll("\\s+", ""); + null, false, false, false).getCodeBlock().replaceAll("\\s+", ""); String expectedCodeBlock = Files.readString(sample31Bal).replaceAll("\\s+", ""); Assert.assertEquals(generatedCodeBlock, expectedCodeBlock); } @@ -542,7 +557,7 @@ public void testXMLWithoutNamespaceAnnotation() throws IOException { public void testXMLWithSameElementAndWithoutMultipleNamespaces() throws IOException { String xmlFileContent = Files.readString(sample32XML); String generatedCodeBlock = XMLToRecordConverter.convert(xmlFileContent, false, false, false, - null, false).getCodeBlock().replaceAll("\\s+", ""); + null, false, false, false).getCodeBlock().replaceAll("\\s+", ""); String expectedCodeBlock = Files.readString(sample32Bal).replaceAll("\\s+", ""); Assert.assertEquals(generatedCodeBlock, expectedCodeBlock); } @@ -551,7 +566,7 @@ public void testXMLWithSameElementAndWithoutMultipleNamespaces() throws IOExcept public void textXMLWithDefaultValueNode() throws IOException { String xmlFileContent = Files.readString(sample33XML); String generatedCodeBlock = XMLToRecordConverter.convert(xmlFileContent, false, false, false, - null, true).getCodeBlock().replaceAll("\\s+", ""); + null, true, false, false).getCodeBlock().replaceAll("\\s+", ""); String expectedCodeBlock = Files.readString(sample33Bal).replaceAll("\\s+", ""); Assert.assertEquals(generatedCodeBlock, expectedCodeBlock); } @@ -560,7 +575,7 @@ public void textXMLWithDefaultValueNode() throws IOException { public void textXMLWithDefaultValueNode2() throws IOException { String xmlFileContent = Files.readString(sample34XML); String generatedCodeBlock = XMLToRecordConverter.convert(xmlFileContent, false, false, false, - "__text", true).getCodeBlock().replaceAll("\\s+", ""); + "__text", true, false, false).getCodeBlock().replaceAll("\\s+", ""); String expectedCodeBlock = Files.readString(sample34Bal).replaceAll("\\s+", ""); Assert.assertEquals(generatedCodeBlock, expectedCodeBlock); } @@ -569,7 +584,7 @@ public void textXMLWithDefaultValueNode2() throws IOException { public void textXMLWithDefaultNamespace() throws IOException { String xmlFileContent = Files.readString(sample35XML); String generatedCodeBlock = XMLToRecordConverter.convert(xmlFileContent, false, false, false, - "__text", true).getCodeBlock().replaceAll("\\s+", ""); + "__text", true, false, false).getCodeBlock().replaceAll("\\s+", ""); String expectedCodeBlock = Files.readString(sample35Bal).replaceAll("\\s+", ""); Assert.assertEquals(generatedCodeBlock, expectedCodeBlock); } @@ -578,7 +593,7 @@ public void textXMLWithDefaultNamespace() throws IOException { public void textXMLWithDefaultNamespace2() throws IOException { String xmlFileContent = Files.readString(sample36XML); String generatedCodeBlock = XMLToRecordConverter.convert(xmlFileContent, false, false, false, - "__text", true).getCodeBlock().replaceAll("\\s+", ""); + "__text", true, false, false).getCodeBlock().replaceAll("\\s+", ""); String expectedCodeBlock = Files.readString(sample36Bal).replaceAll("\\s+", ""); Assert.assertEquals(generatedCodeBlock, expectedCodeBlock); } @@ -587,8 +602,44 @@ public void textXMLWithDefaultNamespace2() throws IOException { public void textXMLWithDefaultNamespace3() throws IOException { String xmlFileContent = Files.readString(sample37XML); String generatedCodeBlock = XMLToRecordConverter.convert(xmlFileContent, false, false, false, - "__text", true).getCodeBlock().replaceAll("\\s+", ""); + "__text", true, false, false).getCodeBlock().replaceAll("\\s+", ""); String expectedCodeBlock = Files.readString(sample37Bal).replaceAll("\\s+", ""); Assert.assertEquals(generatedCodeBlock, expectedCodeBlock); } + + @Test(description = "textXMLWithoutAttributes") + public void textXMLWithoutAttributes() throws IOException { + String xmlFileContent = Files.readString(sample38XML); + String generatedCodeBlock = XMLToRecordConverter.convert(xmlFileContent, false, false, false, + null, true, true, false).getCodeBlock().replaceAll("\\s+", ""); + String expectedCodeBlock = Files.readString(sample39Bal).replaceAll("\\s+", ""); + Assert.assertEquals(generatedCodeBlock, expectedCodeBlock); + } + + @Test(description = "textXMLWithoutAttributeAnnotation") + public void textXMLWithoutAttributeAnnotation() throws IOException { + String xmlFileContent = Files.readString(sample38XML); + String generatedCodeBlock = XMLToRecordConverter.convert(xmlFileContent, false, false, false, + "__text", false, false, true).getCodeBlock().replaceAll("\\s+", ""); + String expectedCodeBlock = Files.readString(sample40Bal).replaceAll("\\s+", ""); + Assert.assertEquals(generatedCodeBlock, expectedCodeBlock); + } + + @Test(description = "textXMLWithoutMultipleAttributeAnnotation") + public void textXMLWithoutMultipleAttributeAnnotation() throws IOException { + String xmlFileContent = Files.readString(sample39XML); + String generatedCodeBlock = XMLToRecordConverter.convert(xmlFileContent, false, false, false, + "__text", false, false, true).getCodeBlock().replaceAll("\\s+", ""); + String expectedCodeBlock = Files.readString(sample41Bal).replaceAll("\\s+", ""); + Assert.assertEquals(generatedCodeBlock, expectedCodeBlock); + } + + @Test(description = "textXMLWithNamespacesAndWithoutAttributeAnnotation") + public void textXMLWithNamespacesAndWithoutAttributeAnnotation() throws IOException { + String xmlFileContent = Files.readString(sample39XML); + String generatedCodeBlock = XMLToRecordConverter.convert(xmlFileContent, false, false, false, + "__text", true, false, true).getCodeBlock().replaceAll("\\s+", ""); + String expectedCodeBlock = Files.readString(sample42Bal).replaceAll("\\s+", ""); + Assert.assertEquals(generatedCodeBlock, expectedCodeBlock); + } } diff --git a/misc/xml-to-record-converter/src/test/resources/ballerina/sample_39.bal b/misc/xml-to-record-converter/src/test/resources/ballerina/sample_39.bal new file mode 100644 index 000000000000..7e40d68e6076 --- /dev/null +++ b/misc/xml-to-record-converter/src/test/resources/ballerina/sample_39.bal @@ -0,0 +1,11 @@ +type Book record { + string title; + string author; + int year; + decimal price; +}; + +@xmldata:Name {value: "bookstore"} +type Bookstore record { + Book book; +}; diff --git a/misc/xml-to-record-converter/src/test/resources/ballerina/sample_40.bal b/misc/xml-to-record-converter/src/test/resources/ballerina/sample_40.bal new file mode 100644 index 000000000000..30d9306ba750 --- /dev/null +++ b/misc/xml-to-record-converter/src/test/resources/ballerina/sample_40.bal @@ -0,0 +1,22 @@ +type Title record { + string __text; + string lang; +}; + +type Price record { + decimal __text; + string currency; +}; + +type Book record { + Title title; + string author; + int year; + Price price; + string category; +}; + +@xmldata:Name {value: "bookstore"} +type Bookstore record { + Book book; +}; diff --git a/misc/xml-to-record-converter/src/test/resources/ballerina/sample_41.bal b/misc/xml-to-record-converter/src/test/resources/ballerina/sample_41.bal new file mode 100644 index 000000000000..de7054486b68 --- /dev/null +++ b/misc/xml-to-record-converter/src/test/resources/ballerina/sample_41.bal @@ -0,0 +1,37 @@ +type Book_Title record { + string __text; + string edition; + string format; + string lang; + string pages; +}; + +type Book_Price record { + decimal __text; + string currency; +}; + +type Book_Book record { + Book_Title title; + string author; + string publisher; + string publish_date; + int isbn; + Book_Price price; + string available; + string id; + string shelf; +}; + +type Books record { + string genre; + Book_Book book; +}; + +@xmldata:Name {value: "library"} +type Library record { + Books books; + string established; + string genre; + string location; +}; diff --git a/misc/xml-to-record-converter/src/test/resources/ballerina/sample_42.bal b/misc/xml-to-record-converter/src/test/resources/ballerina/sample_42.bal new file mode 100644 index 000000000000..87853261f06e --- /dev/null +++ b/misc/xml-to-record-converter/src/test/resources/ballerina/sample_42.bal @@ -0,0 +1,44 @@ +type Book_Title record { + string __text; + string edition; + string format; + string lang; + string pages; +}; + +type Book_Price record { + decimal __text; + string currency; +}; + +type Book_Book record { + @xmldata:Namespace {prefix: "book", uri: "http://example.com/books"} + Book_Title title; + @xmldata:Namespace {prefix: "book", uri: "http://example.com/books"} + string author; + @xmldata:Namespace {prefix: "book", uri: "http://example.com/books"} + string publisher; + @xmldata:Namespace {prefix: "book", uri: "http://example.com/books"} + string publish_date; + @xmldata:Namespace {prefix: "book", uri: "http://example.com/books"} + int isbn; + @xmldata:Namespace {prefix: "book", uri: "http://example.com/books"} + Book_Price price; + string available; + string id; + string shelf; +}; + +type Books record { + string genre; + @xmldata:Namespace {prefix: "book", uri: "http://example.com/books"} + Book_Book book; +}; + +@xmldata:Name {value: "library"} +type Library record { + Books books; + string established; + string genre; + string location; +}; diff --git a/misc/xml-to-record-converter/src/test/resources/xml/sample_38.xml b/misc/xml-to-record-converter/src/test/resources/xml/sample_38.xml new file mode 100644 index 000000000000..fb2f40571d64 --- /dev/null +++ b/misc/xml-to-record-converter/src/test/resources/xml/sample_38.xml @@ -0,0 +1,8 @@ + + + Harry Potter + J.K. Rowling + 2005 + 29.99 + + diff --git a/misc/xml-to-record-converter/src/test/resources/xml/sample_39.xml b/misc/xml-to-record-converter/src/test/resources/xml/sample_39.xml new file mode 100644 index 000000000000..c0f3d434cd84 --- /dev/null +++ b/misc/xml-to-record-converter/src/test/resources/xml/sample_39.xml @@ -0,0 +1,13 @@ + + + Programming + + XML Developer's Guide + John Doe + Tech Press + 2000-10-01 + 1234567890 + 49.99 + + + diff --git a/project-api/project-api-test/src/test/java/io/ballerina/projects/test/BaseTest.java b/project-api/project-api-test/src/test/java/io/ballerina/projects/test/BaseTest.java index 771b19d2b5d1..d48c5e81eb90 100644 --- a/project-api/project-api-test/src/test/java/io/ballerina/projects/test/BaseTest.java +++ b/project-api/project-api-test/src/test/java/io/ballerina/projects/test/BaseTest.java @@ -40,6 +40,7 @@ import java.nio.file.Paths; import java.util.List; import java.util.stream.Collectors; +import java.util.stream.Stream; import static io.ballerina.projects.test.TestUtils.replaceDistributionVersionOfDependenciesToml; import static io.ballerina.projects.util.ProjectConstants.CENTRAL_REPOSITORY_CACHE_NAME; @@ -97,7 +98,10 @@ protected void cacheDependencyToLocalRepo(Path dependency) throws IOException { .resolve("samjs").resolve("package_c").resolve("0.1.0").resolve("any"); Files.createDirectories(localRepoBalaCache); jBallerinaBackend.emit(JBallerinaBackend.OutputType.BALA, localRepoBalaCache); - Path balaPath = Files.list(localRepoBalaCache).findAny().orElseThrow(); + Path balaPath; + try (Stream paths = Files.list(localRepoBalaCache)) { + balaPath = paths.findAny().orElseThrow(); + } ProjectUtils.extractBala(balaPath, localRepoBalaCache); try { Files.delete(balaPath); @@ -142,7 +146,10 @@ private void cacheDependencyToCentralRepository(BuildProject dependencyProject, } Files.createDirectories(centralRepoBalaCache); jBallerinaBackend.emit(JBallerinaBackend.OutputType.BALA, centralRepoBalaCache); - Path balaPath = Files.list(centralRepoBalaCache).findAny().orElseThrow(); + Path balaPath; + try (Stream paths = Files.list(centralRepoBalaCache)) { + balaPath = paths.findAny().orElseThrow(); + } ProjectUtils.extractBala(balaPath, centralRepoBalaCache); try { Files.delete(balaPath); diff --git a/project-api/project-api-test/src/test/java/io/ballerina/projects/test/PackageResolutionIntegrationTests.java b/project-api/project-api-test/src/test/java/io/ballerina/projects/test/PackageResolutionIntegrationTests.java index 24fc2ca5737c..a384825a8184 100644 --- a/project-api/project-api-test/src/test/java/io/ballerina/projects/test/PackageResolutionIntegrationTests.java +++ b/project-api/project-api-test/src/test/java/io/ballerina/projects/test/PackageResolutionIntegrationTests.java @@ -894,10 +894,11 @@ private void afterMethod(ITestContext ctx) throws IOException { public void afterClass() throws IOException { Path advResBalaDir = testBuildDirectory.resolve("user-home").resolve("repositories") .resolve("central.ballerina.io").resolve("bala").resolve("adv_res"); - Files.walk(advResBalaDir) - .map(Path::toFile) - .sorted((o1, o2) -> -o1.compareTo(o2)) - .forEach(File::delete); + try (Stream paths = Files.walk(advResBalaDir)) { + paths.map(Path::toFile) + .sorted((o1, o2) -> -o1.compareTo(o2)) + .forEach(File::delete); + } } private static void deleteDependenciesTomlAndBuildFile(Path packagePath) throws IOException { diff --git a/project-api/project-api-test/src/test/java/io/ballerina/projects/test/TestBirAndJarCache.java b/project-api/project-api-test/src/test/java/io/ballerina/projects/test/TestBirAndJarCache.java index 921c2ac3f37e..41dc5e89cd6f 100644 --- a/project-api/project-api-test/src/test/java/io/ballerina/projects/test/TestBirAndJarCache.java +++ b/project-api/project-api-test/src/test/java/io/ballerina/projects/test/TestBirAndJarCache.java @@ -88,23 +88,25 @@ public void testBirAndJarCaching() throws IOException { // numOfModules * 2 : This includes testable jars as well, including the resources.jar Assert.assertEquals(testCompilationCache.jarCachedCount, numOfModules + 1); - Stream pathStream = Files.find(cacheDirPath, 100, + try (Stream pathStream = Files.find(cacheDirPath, 100, (path, fileAttributes) -> !Files.isDirectory(path) && (path.getFileName().toString().endsWith(".bir") || - path.getFileName().toString().endsWith(".jar"))); - - List foundPaths = pathStream - .map(path -> path.getFileName().toString()) - .toList(); - for (ModuleId moduleId : currentPackage.moduleIds()) { - Module module = currentPackage.module(moduleId); - ModuleName moduleName = module.moduleName(); - String jarName = getThinJarFileName(module.descriptor().org(), - moduleName.toString(), - module.descriptor().version()); - Assert.assertTrue(foundPaths.contains(jarName + BLANG_COMPILED_JAR_EXT)); + path.getFileName().toString().endsWith(".jar")))) { + + List foundPaths = pathStream + .map(path -> path.getFileName().toString()) + .toList(); + + for (ModuleId moduleId : currentPackage.moduleIds()) { + Module module = currentPackage.module(moduleId); + ModuleName moduleName = module.moduleName(); + String jarName = getThinJarFileName(module.descriptor().org(), + moduleName.toString(), + module.descriptor().version()); + Assert.assertTrue(foundPaths.contains(jarName + BLANG_COMPILED_JAR_EXT)); + } + Assert.assertTrue(foundPaths.contains(RESOURCE_DIR_NAME + BLANG_COMPILED_JAR_EXT)); } - Assert.assertTrue(foundPaths.contains(RESOURCE_DIR_NAME + BLANG_COMPILED_JAR_EXT)); } @Test diff --git a/project-api/project-api-test/src/test/java/io/ballerina/projects/test/TestBuildProject.java b/project-api/project-api-test/src/test/java/io/ballerina/projects/test/TestBuildProject.java index 6bdfd9dd7c76..2e6c049362b4 100644 --- a/project-api/project-api-test/src/test/java/io/ballerina/projects/test/TestBuildProject.java +++ b/project-api/project-api-test/src/test/java/io/ballerina/projects/test/TestBuildProject.java @@ -302,7 +302,7 @@ public void testDiagnostics() { // Verify paths in packageCompilation diagnostics List diagnosticFilePaths = compilation.diagnosticResult().diagnostics().stream().map(diagnostic -> - diagnostic.location().lineRange().fileName()).distinct().collect(Collectors.toList()); + diagnostic.location().lineRange().fileName()).distinct().toList(); for (String path : expectedPaths) { Assert.assertTrue(diagnosticFilePaths.contains(path), diagnosticFilePaths.toString()); @@ -1707,17 +1707,18 @@ public void testGetResourcesOfDependencies() throws IOException { Path execPath = buildProject.sourceRoot().resolve(TARGET_DIR_NAME).resolve("temp.jar"); jBallerinaBackend.emit(JBallerinaBackend.OutputType.EXEC, execPath); - JarFile execJar = new JarFile(execPath.toString()); - String resourceName = RESOURCE_DIR_NAME + "/asmaj-project-info.properties"; - String depResourceName = RESOURCE_DIR_NAME + "/project-info.properties"; + try (JarFile execJar = new JarFile(execPath.toString())) { + String resourceName = RESOURCE_DIR_NAME + "/asmaj-project-info.properties"; + String depResourceName = RESOURCE_DIR_NAME + "/project-info.properties"; - Assert.assertNotNull(execJar.getJarEntry(resourceName)); - try (InputStream inputStream = execJar.getInputStream(execJar.getJarEntry(resourceName))) { - Assert.assertTrue(new String(inputStream.readAllBytes()).contains("asmaj")); - } - Assert.assertNotNull(execJar.getJarEntry(depResourceName)); - try (InputStream inputStream = execJar.getInputStream(execJar.getJarEntry(depResourceName))) { - Assert.assertTrue(new String(inputStream.readAllBytes()).contains("samjs")); + Assert.assertNotNull(execJar.getJarEntry(resourceName)); + try (InputStream inputStream = execJar.getInputStream(execJar.getJarEntry(resourceName))) { + Assert.assertTrue(new String(inputStream.readAllBytes()).contains("asmaj")); + } + Assert.assertNotNull(execJar.getJarEntry(depResourceName)); + try (InputStream inputStream = execJar.getInputStream(execJar.getJarEntry(depResourceName))) { + Assert.assertTrue(new String(inputStream.readAllBytes()).contains("samjs")); + } } } @@ -1746,59 +1747,63 @@ public void testAddResources() throws IOException { jBallerinaBackend.emit(JBallerinaBackend.OutputType.EXEC, execPath); // 4. Verify the existence of resources in thin jar, testable jar and executable jar - JarFile execJar = new JarFile(execPath.toString()); - - for (ModuleId moduleId : buildProject.currentPackage().moduleIds()) { - Module module = buildProject.currentPackage().module(moduleId); - Path moduleJarPath = buildProject.sourceRoot().resolve(TARGET_DIR_NAME).resolve(CACHES_DIR_NAME) - .resolve(module.descriptor().org().toString()) - .resolve(module.descriptor().packageName().toString()) - .resolve(module.descriptor().version().toString()).resolve("java17") - .resolve(module.descriptor().org().toString() + "-" + module.descriptor().name().toString() + "-" - + module.descriptor().version().toString() + ".jar"); - JarFile jar = new JarFile(moduleJarPath.toString()); - for (String name : getResources(buildProject.currentPackage().module(moduleId))) { - Assert.assertNotNull(jar.getJarEntry(name)); - Assert.assertNotNull(execJar.getJarEntry(name)); - } + try (JarFile execJar = new JarFile(execPath.toString())) { - Path testableJarPath = buildProject.sourceRoot().resolve(TARGET_DIR_NAME).resolve(CACHES_DIR_NAME) + for (ModuleId moduleId : buildProject.currentPackage().moduleIds()) { + Module module = buildProject.currentPackage().module(moduleId); + Path moduleJarPath = buildProject.sourceRoot().resolve(TARGET_DIR_NAME).resolve(CACHES_DIR_NAME) .resolve(module.descriptor().org().toString()) .resolve(module.descriptor().packageName().toString()) .resolve(module.descriptor().version().toString()).resolve("java17") .resolve(module.descriptor().org().toString() + "-" + module.descriptor().name().toString() + "-" - + module.descriptor().version().toString() + "-testable.jar"); - if (Files.exists(testableJarPath)) { - JarFile testableJar = new JarFile(testableJarPath.toString()); - for (String name : getResources(buildProject.currentPackage().module(moduleId))) { - Assert.assertNotNull(testableJar.getJarEntry(name)); - } - for (String name : getTestResources(buildProject.currentPackage().module(moduleId))) { - Assert.assertNotNull(testableJar.getJarEntry(name)); + + module.descriptor().version().toString() + ".jar"); + try (JarFile jar = new JarFile(moduleJarPath.toString())) { + for (String name : getResources(buildProject.currentPackage().module(moduleId))) { + Assert.assertNotNull(jar.getJarEntry(name)); + Assert.assertNotNull(execJar.getJarEntry(name)); + } } + Path testableJarPath = buildProject.sourceRoot().resolve(TARGET_DIR_NAME).resolve(CACHES_DIR_NAME) + .resolve(module.descriptor().org().toString()) + .resolve(module.descriptor().packageName().toString()) + .resolve(module.descriptor().version().toString()).resolve("java17") + .resolve(module.descriptor().org().toString() + "-" + + module.descriptor().name().toString() + "-" + + module.descriptor().version().toString() + "-testable.jar"); + if (Files.exists(testableJarPath)) { + try (JarFile testableJar = new JarFile(testableJarPath.toString())) { + for (String name : getResources(buildProject.currentPackage().module(moduleId))) { + Assert.assertNotNull(testableJar.getJarEntry(name)); + } + for (String name : getTestResources(buildProject.currentPackage().module(moduleId))) { + Assert.assertNotNull(testableJar.getJarEntry(name)); + } + } + } } - } - // Assert resources of dependencies - for (ResolvedPackageDependency resolvedPackageDependency : + + // Assert resources of dependencies + for (ResolvedPackageDependency resolvedPackageDependency : buildProject.currentPackage().getResolution().dependencyGraph().toTopologicallySortedList()) { - Package depPackage = resolvedPackageDependency.packageInstance(); - for (ModuleId moduleId : depPackage.moduleIds()) { - for (String name : getResources(depPackage.module(moduleId))) { - Assert.assertNotNull(execJar.getJarEntry(name)); + Package depPackage = resolvedPackageDependency.packageInstance(); + for (ModuleId moduleId : depPackage.moduleIds()) { + for (String name : getResources(depPackage.module(moduleId))) { + Assert.assertNotNull(execJar.getJarEntry(name)); + } } - } + } } - Path balaPath = buildProject.sourceRoot().resolve(TARGET_DIR_NAME); jBallerinaBackend.emit(JBallerinaBackend.OutputType.BALA, balaPath); - JarFile bala = new JarFile(balaPath.resolve("sameera-myproject-any-0.1.0.bala").toString()); + try (JarFile bala = new JarFile(balaPath.resolve("sameera-myproject-any-0.1.0.bala").toString())) { - for (ModuleId moduleId : buildProject.currentPackage().moduleIds()) { - for (String name : getResourcesInBala(buildProject.currentPackage().module(moduleId))) { - Assert.assertNotNull(bala.getJarEntry(name)); + for (ModuleId moduleId : buildProject.currentPackage().moduleIds()) { + for (String name : getResourcesInBala(buildProject.currentPackage().module(moduleId))) { + Assert.assertNotNull(bala.getJarEntry(name)); + } } } } @@ -2250,7 +2255,7 @@ public void testDocumentsOrder() { PackageCompilation compilation = currentPackage.getCompilation(); List actualDiagnosticPaths = compilation.diagnosticResult().diagnostics().stream().map(diagnostic -> - diagnostic.location().lineRange().fileName()).distinct().collect(Collectors.toList()); + diagnostic.location().lineRange().fileName()).distinct().toList(); List expectedDiagnosticPaths = Arrays.asList( "main.bal", Paths.get("tests").resolve("main_test.bal").toString(), diff --git a/project-api/project-api-test/src/test/java/io/ballerina/projects/test/TestBuildProjectWithGeneratedSources.java b/project-api/project-api-test/src/test/java/io/ballerina/projects/test/TestBuildProjectWithGeneratedSources.java index 19071691641c..727e64cbcdd9 100644 --- a/project-api/project-api-test/src/test/java/io/ballerina/projects/test/TestBuildProjectWithGeneratedSources.java +++ b/project-api/project-api-test/src/test/java/io/ballerina/projects/test/TestBuildProjectWithGeneratedSources.java @@ -30,6 +30,8 @@ import org.testng.annotations.AfterClass; import org.testng.annotations.Test; +import java.io.PrintWriter; +import java.io.StringWriter; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collection; @@ -189,7 +191,9 @@ private static BuildProject loadBuildProject(Path projectPath, BuildOptions buil buildProject = TestUtils.loadBuildProject(projectPath, buildOptions); } } catch (Exception e) { - Assert.fail(e.getMessage()); + StringWriter errors = new StringWriter(); + e.printStackTrace(new PrintWriter(errors)); + Assert.fail(errors.toString()); } return buildProject; } diff --git a/project-api/project-api-test/src/test/java/io/ballerina/projects/test/TestUtils.java b/project-api/project-api-test/src/test/java/io/ballerina/projects/test/TestUtils.java index 14fa27bbd2e7..7f5e8417ae25 100644 --- a/project-api/project-api-test/src/test/java/io/ballerina/projects/test/TestUtils.java +++ b/project-api/project-api-test/src/test/java/io/ballerina/projects/test/TestUtils.java @@ -51,10 +51,13 @@ * * @since 2.0.0 */ -public class TestUtils { +public final class TestUtils { private static final String OS = System.getProperty("os.name").toLowerCase(Locale.getDefault()); + private TestUtils() { + } + public static String getDiagnosticsAsString(DiagnosticResult diagnosticResult) { return diagnosticResult.diagnostics().stream().map( diagnostic -> diagnostic.toString() + "\n").collect(Collectors.joining()); diff --git a/project-api/project-api-test/src/test/java/io/ballerina/projects/test/plugins/LanguageServerExtensionTests.java b/project-api/project-api-test/src/test/java/io/ballerina/projects/test/plugins/LanguageServerExtensionTests.java index 32810faa8eb8..6fe39b80cbf0 100644 --- a/project-api/project-api-test/src/test/java/io/ballerina/projects/test/plugins/LanguageServerExtensionTests.java +++ b/project-api/project-api-test/src/test/java/io/ballerina/projects/test/plugins/LanguageServerExtensionTests.java @@ -67,7 +67,6 @@ import java.nio.file.Paths; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; /** * Tests for language server's extensions. @@ -125,7 +124,7 @@ public void testOneCompilerPluginWithOneCodeAction() { List arguments = info.get().getArguments(); arguments = arguments.stream() .map(codeActionArgument -> CodeActionArgument.from(gson.toJsonTree(codeActionArgument))) - .collect(Collectors.toList()); + .toList(); Assert.assertFalse(arguments.isEmpty()); diff --git a/project-api/test-artifacts/diagnostic-utils-lib/src/main/java/io/samjs/jarlibrary/diagnosticutils/DiagnosticUtils.java b/project-api/test-artifacts/diagnostic-utils-lib/src/main/java/io/samjs/jarlibrary/diagnosticutils/DiagnosticUtils.java index e2dd08419a09..93b3b901c562 100644 --- a/project-api/test-artifacts/diagnostic-utils-lib/src/main/java/io/samjs/jarlibrary/diagnosticutils/DiagnosticUtils.java +++ b/project-api/test-artifacts/diagnostic-utils-lib/src/main/java/io/samjs/jarlibrary/diagnosticutils/DiagnosticUtils.java @@ -28,7 +28,10 @@ * * @since 2.0.0 */ -public class DiagnosticUtils { +public final class DiagnosticUtils { + + private DiagnosticUtils() { + } public static Diagnostic createDiagnostic(String code, String messageFormat, diff --git a/project-api/test-artifacts/pkg-provided-compiler-plugin-with-shared-data/src/main/java/io/context/plugins/Util.java b/project-api/test-artifacts/pkg-provided-compiler-plugin-with-shared-data/src/main/java/io/context/plugins/Util.java index 056cf3baa734..519e012eda93 100644 --- a/project-api/test-artifacts/pkg-provided-compiler-plugin-with-shared-data/src/main/java/io/context/plugins/Util.java +++ b/project-api/test-artifacts/pkg-provided-compiler-plugin-with-shared-data/src/main/java/io/context/plugins/Util.java @@ -34,7 +34,10 @@ * * @since 2201.8.7 */ -public class Util { +public final class Util { + + private Util() { + } public static void reportDiagnostic(SyntaxNodeAnalysisContext context, CompilationDiagnostic diagnosticCode, Location location, Object... args) { diff --git a/project-api/test-artifacts/string-utils-lib/src/main/java/io/samjs/jarlibrary/stringutils/StringUtils.java b/project-api/test-artifacts/string-utils-lib/src/main/java/io/samjs/jarlibrary/stringutils/StringUtils.java index abbad8245665..0d3c8fcad2b0 100644 --- a/project-api/test-artifacts/string-utils-lib/src/main/java/io/samjs/jarlibrary/stringutils/StringUtils.java +++ b/project-api/test-artifacts/string-utils-lib/src/main/java/io/samjs/jarlibrary/stringutils/StringUtils.java @@ -20,7 +20,10 @@ /** * A dummy string utils implementation. */ -public class StringUtils { +public final class StringUtils { + + private StringUtils() { + } public static boolean isEmpty(String value) { return value.isEmpty(); diff --git a/semtypes/src/main/java/io/ballerina/semtype/PredefinedType.java b/semtypes/src/main/java/io/ballerina/semtype/PredefinedType.java index d162e4d60018..fcad89624357 100644 --- a/semtypes/src/main/java/io/ballerina/semtype/PredefinedType.java +++ b/semtypes/src/main/java/io/ballerina/semtype/PredefinedType.java @@ -24,7 +24,8 @@ * * @since 2.0.0 */ -public class PredefinedType { +public final class PredefinedType { + public static final UniformTypeBitSet NEVER = uniformTypeUnion(0); public static final UniformTypeBitSet NIL = uniformType(UniformTypeCode.UT_NIL); public static final UniformTypeBitSet BOOLEAN = uniformType(UniformTypeCode.UT_BOOLEAN); @@ -64,6 +65,9 @@ public class PredefinedType { | (1 << UniformTypeCode.UT_STRING)); public static final SemType BYTE = IntSubtype.intWidthUnsigned(8); + private PredefinedType() { + } + private static UniformTypeBitSet uniformTypeUnion(int bitset) { return new UniformTypeBitSet(bitset); } diff --git a/semtypes/src/main/java/io/ballerina/semtype/UniformTypeCode.java b/semtypes/src/main/java/io/ballerina/semtype/UniformTypeCode.java index d186adaf00dc..2b3adf472510 100644 --- a/semtypes/src/main/java/io/ballerina/semtype/UniformTypeCode.java +++ b/semtypes/src/main/java/io/ballerina/semtype/UniformTypeCode.java @@ -24,7 +24,8 @@ * * @since 2.0.0 */ -public class UniformTypeCode { +public final class UniformTypeCode { + // Inherently immutable public static final int UT_NIL = 0x00; public static final int UT_BOOLEAN = 0x01; @@ -65,4 +66,7 @@ public class UniformTypeCode { static final int UT_READONLY = (1 << UT_COUNT_RO) - 1; static final int UT_RW_MASK = UT_MASK ^ ~UT_READONLY; + + private UniformTypeCode() { + } } diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/LangLibFunctionTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/LangLibFunctionTest.java index 970714a69876..a53f787555b1 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/LangLibFunctionTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/LangLibFunctionTest.java @@ -255,11 +255,11 @@ public Object[][] getXMLInfo() { return new Object[][]{ {68, 8, XML, expFunctions}, {69, 17, TYPE_REFERENCE, Stream.concat(expFunctions.stream(), elementFuncs.stream()) - .collect(Collectors.toList())}, + .toList()}, {79, 31, TYPE_REFERENCE, Stream.concat(expFunctions.stream(), piFuncs.stream()) - .collect(Collectors.toList())}, + .toList()}, {80, 17, TYPE_REFERENCE, Stream.concat(expFunctions.stream(), commentFuncs.stream()) - .collect(Collectors.toList())}, + .toList()}, {81, 14, TYPE_REFERENCE, expFunctions}, }; } @@ -384,7 +384,7 @@ public Object[][] getTableInfo() { return new Object[][]{ {64, 22, expFunctions}, - {65, 32, Stream.concat(expFunctions.stream(), additionalFuncs.stream()).collect(Collectors.toList())}, + {65, 32, Stream.concat(expFunctions.stream(), additionalFuncs.stream()).toList()}, {66, 37, expFunctions}, }; } diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/ServiceSemanticAPITest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/ServiceSemanticAPITest.java index 903a9e2cccf6..7eee893952a6 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/ServiceSemanticAPITest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/ServiceSemanticAPITest.java @@ -49,7 +49,6 @@ import java.util.Arrays; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; import java.util.stream.Stream; import static io.ballerina.compiler.api.symbols.Qualifier.FINAL; @@ -325,10 +324,10 @@ private List getFilteredSymbolNames(List symbols) { return symbols.stream() .filter(s -> s.getModule().isPresent() && !"ballerina".equals(s.getModule().get().getModule().get().id().orgName())) - .collect(Collectors.toList()); + .toList(); } private List concatSymbols(List moduleSymbols, String... symbols) { - return Stream.concat(moduleSymbols.stream(), Arrays.stream(symbols)).collect(Collectors.toList()); + return Stream.concat(moduleSymbols.stream(), Arrays.stream(symbols)).toList(); } } diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/SymbolAtCursorTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/SymbolAtCursorTest.java index bbeb41c6a182..3e37244ad8d6 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/SymbolAtCursorTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/SymbolAtCursorTest.java @@ -285,20 +285,12 @@ public void testVarsWithFunctionType(int line, int col, String name, SymbolKind assertEquals(symbol.get().kind(), symbolKind); assertEquals(symbol.get().getName().get(), name); - TypeSymbol type; - switch (symbolKind) { - case RECORD_FIELD: - type = ((RecordFieldSymbol) symbol.get()).typeDescriptor(); - break; - case OBJECT_FIELD: - type = ((ObjectFieldSymbol) symbol.get()).typeDescriptor(); - break; - case VARIABLE: - type = ((VariableSymbol) symbol.get()).typeDescriptor(); - break; - default: - throw new IllegalStateException("Unexpected symbol kind: " + symbolKind); - } + TypeSymbol type = switch (symbolKind) { + case RECORD_FIELD -> ((RecordFieldSymbol) symbol.get()).typeDescriptor(); + case OBJECT_FIELD -> ((ObjectFieldSymbol) symbol.get()).typeDescriptor(); + case VARIABLE -> ((VariableSymbol) symbol.get()).typeDescriptor(); + default -> throw new IllegalStateException("Unexpected symbol kind: " + symbolKind); + }; assertEquals(type.typeKind(), TYPE_REFERENCE); } diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/SymbolBIRTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/SymbolBIRTest.java index 895a47ded61e..3dcc761049cc 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/SymbolBIRTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/SymbolBIRTest.java @@ -357,8 +357,8 @@ private List getModuleSymbolInfo() { private List createSymbolInfoList(Object[][] infoArr) { List symInfo = new ArrayList<>(); - for (int i = 0; i < infoArr.length; i++) { - symInfo.add(new SymbolInfo((String) infoArr[i][0], (SymbolKind) infoArr[i][1])); + for (Object[] objects : infoArr) { + symInfo.add(new SymbolInfo((String) objects[0], (SymbolKind) objects[1])); } return symInfo; } @@ -378,11 +378,10 @@ public boolean equals(Object obj) { return true; } - if (!(obj instanceof SymbolInfo)) { + if (!(obj instanceof SymbolInfo info)) { return false; } - SymbolInfo info = (SymbolInfo) obj; return this.name.equals(info.name) && this.kind == info.kind; } diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/SymbolEquivalenceTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/SymbolEquivalenceTest.java index 72c7db7885b7..5a287003768d 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/SymbolEquivalenceTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/SymbolEquivalenceTest.java @@ -34,7 +34,6 @@ import org.testng.annotations.Test; import java.util.List; -import java.util.stream.Collectors; import static io.ballerina.compiler.api.symbols.SymbolKind.RECORD_FIELD; import static io.ballerina.semantic.api.test.util.SemanticAPITestUtils.getDefaultModulesSemanticModel; @@ -72,7 +71,7 @@ public void setup() { public void testSymbols(List positions) { List symbols = positions.stream() .map(pos -> model.symbol(srcFile, pos).get()) - .collect(Collectors.toList()); + .toList(); assertSymbols(symbols); } @@ -113,7 +112,7 @@ public void testTypeRefEquivalence() { SemanticModel typeRefModel = SemanticAPITestUtils.getDefaultModulesSemanticModel("test-src/typedesc_test.bal"); List symbols = positions.stream() .map(pos -> typeRefModel.symbol(typesSrcFile, pos).get()) - .collect(Collectors.toList()); + .toList(); assertSymbols(symbols); } @@ -122,18 +121,13 @@ public void testTypeRefEquivalence() { public void testTypedescriptors(List positions) { List types = positions.stream() .map(pos -> typesModel.symbol(typesSrcFile, pos).get()) - .map(s -> { - switch (s.kind()) { - case RECORD_FIELD: - return ((RecordFieldSymbol) s).typeDescriptor(); - case PARAMETER: - return ((ParameterSymbol) s).typeDescriptor(); - case VARIABLE: - return ((VariableSymbol) s).typeDescriptor(); - } - throw new AssertionError("Unexpected symbol kind: " + s.kind()); + .map(s -> switch (s.kind()) { + case RECORD_FIELD -> ((RecordFieldSymbol) s).typeDescriptor(); + case PARAMETER -> ((ParameterSymbol) s).typeDescriptor(); + case VARIABLE -> ((VariableSymbol) s).typeDescriptor(); + default -> throw new AssertionError("Unexpected symbol kind: " + s.kind()); }) - .collect(Collectors.toList()); + .toList(); assertTypeSymbols(types); } diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/SymbolLookupTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/SymbolLookupTest.java index f54ab542482b..0a26fc95a1d4 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/SymbolLookupTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/SymbolLookupTest.java @@ -41,7 +41,6 @@ import java.util.Arrays; import java.util.List; import java.util.Map; -import java.util.stream.Collectors; import java.util.stream.Stream; import static io.ballerina.compiler.api.symbols.DiagnosticState.REDECLARED; @@ -418,6 +417,6 @@ private String createSymbolString(Symbol symbol) { } private List concatSymbols(List moduleSymbols, String... symbols) { - return Stream.concat(moduleSymbols.stream(), Arrays.stream(symbols)).collect(Collectors.toList()); + return Stream.concat(moduleSymbols.stream(), Arrays.stream(symbols)).toList(); } } diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/TestSourcesTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/TestSourcesTest.java index 906d9dcf6c4d..440564936f2f 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/TestSourcesTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/TestSourcesTest.java @@ -37,7 +37,6 @@ import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; import static io.ballerina.compiler.api.symbols.TypeDescKind.FLOAT; import static io.ballerina.compiler.api.symbols.TypeDescKind.INT; @@ -99,7 +98,7 @@ public void testVisibleSymbols(int line, int col, List expSymbols) { String moduleName = sym.getModule().get().id().moduleName(); return moduleName.equals("semapi.baz") || !moduleName.startsWith("lang."); }) - .collect(Collectors.toList()); + .toList(); assertEquals(symbols.size(), expSymbols.size()); assertList(symbols, expSymbols); diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/TypedescriptorTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/TypedescriptorTest.java index a74913517056..3ff673aa836f 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/TypedescriptorTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/TypedescriptorTest.java @@ -1186,12 +1186,10 @@ public boolean equals(Object obj) { if (this == obj) { return true; } - if (!(obj instanceof SymbolInfo)) { + if (!(obj instanceof SymbolInfo that)) { return false; } - SymbolInfo that = (SymbolInfo) obj; - return line == that.line && column == that.column && srcFile.equals(that.srcFile) && diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/TypesTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/TypesTest.java index 6457bbcaad37..e10ce2d2076d 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/TypesTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/TypesTest.java @@ -316,17 +316,12 @@ private void assertSymbolTypeDesc(Symbol symbol, SymbolKind symbolKind, TypeDesc } private Optional getTypeSymbolOfTypeDef(Symbol symbol) { - switch (symbol.kind()) { - case TYPE_DEFINITION: - return Optional.of(((TypeDefinitionSymbol) symbol).typeDescriptor()); - case CONSTANT: - case ENUM_MEMBER: - return Optional.of(((ConstantSymbol) symbol).typeDescriptor()); - case ENUM: - return Optional.of(((EnumSymbol) symbol).typeDescriptor()); - case CLASS: - return Optional.of((ClassSymbol) symbol); - } - return Optional.empty(); + return switch (symbol.kind()) { + case TYPE_DEFINITION -> Optional.of(((TypeDefinitionSymbol) symbol).typeDescriptor()); + case CONSTANT, ENUM_MEMBER -> Optional.of(((ConstantSymbol) symbol).typeDescriptor()); + case ENUM -> Optional.of(((EnumSymbol) symbol).typeDescriptor()); + case CLASS -> Optional.of((ClassSymbol) symbol); + default -> Optional.empty(); + }; } } diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/actions/SymbolsInResourceAccessActionTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/actions/SymbolsInResourceAccessActionTest.java index 8e20625914f2..0916a5d733f7 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/actions/SymbolsInResourceAccessActionTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/actions/SymbolsInResourceAccessActionTest.java @@ -79,7 +79,7 @@ public Object[][] getResourceAccessActionPosAndPathSegments() { {43, 25, "get", Map.of( "foo", PathSegment.Kind.NAMED_SEGMENT, "[string id]", PathSegment.Kind.PATH_PARAMETER)}, - {44, 28, "post", Map.of( + {44, 39, "post", Map.of( "bar", PathSegment.Kind.NAMED_SEGMENT, "[string... ids]", PathSegment.Kind.PATH_REST_PARAMETER)}, {66, 11, "get", Map.of( @@ -108,7 +108,7 @@ public void testSymbolsInResourceAccessAction(int line, int col, String name, Sy public Object[][] getSymbolPosInResourceAccessAction() { return new Object[][]{ {42, 23, "fooClient", SymbolKind.VARIABLE}, // fooClient->/foo - {42, 32, null, null}, // ->/foo + {42, 32, "get", SymbolKind.RESOURCE_METHOD}, // ->/foo {42, 34, "get", SymbolKind.RESOURCE_METHOD}, // ->/ {42, 35, "foo", SymbolKind.PATH_NAME_SEGMENT}, // ->/foo {42, 49, "x", SymbolKind.CONSTANT}, // ["3"](x, 2); diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/AnnotationRefsTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/AnnotationRefsTest.java index 243f89cb0fc2..c6b68b9c20e3 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/AnnotationRefsTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/AnnotationRefsTest.java @@ -31,6 +31,7 @@ @Test public class AnnotationRefsTest extends FindAllReferencesTest { + @Override @DataProvider(name = "PositionProvider") public Object[][] getLookupPositions() { return new Object[][]{ diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/CyclicUnionRefsTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/CyclicUnionRefsTest.java index a7f79ef7f299..5c0019ec4fa8 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/CyclicUnionRefsTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/CyclicUnionRefsTest.java @@ -32,6 +32,7 @@ @Test public class CyclicUnionRefsTest extends FindAllReferencesTest { + @Override @DataProvider(name = "PositionProvider") public Object[][] getLookupPositions() { Location defLocation = location(16, 5, 16); diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindModulePrefixRefsTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindModulePrefixRefsTest.java index 3eeed4f9e36e..9f686e694394 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindModulePrefixRefsTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindModulePrefixRefsTest.java @@ -36,6 +36,7 @@ @Test public class FindModulePrefixRefsTest extends FindAllReferencesTest { + @Override @BeforeClass public void setup() { CompileResult compileResult = BCompileUtil.compileAndCacheBala("test-src/testproject"); @@ -46,6 +47,7 @@ public void setup() { super.setup(); } + @Override @DataProvider(name = "PositionProvider") public Object[][] getLookupPositions() { return new Object[][]{ diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsAcrossFilesTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsAcrossFilesTest.java index bdc2902ba3db..96a5b9b253ab 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsAcrossFilesTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsAcrossFilesTest.java @@ -39,6 +39,7 @@ @Test public class FindRefsAcrossFilesTest extends FindAllReferencesTest { + @Override @BeforeClass public void setup() { Project project = BCompileUtil.loadProject(getTestSourcePath()); @@ -47,6 +48,7 @@ public void setup() { srcFile = getDocument(baz); } + @Override @DataProvider(name = "PositionProvider") public Object[][] getLookupPositions() { return new Object[][]{ diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInBindingPatternsTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInBindingPatternsTest.java index 00aa130f6309..a99ecd441df8 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInBindingPatternsTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInBindingPatternsTest.java @@ -31,6 +31,7 @@ @Test public class FindRefsInBindingPatternsTest extends FindAllReferencesTest { + @Override @DataProvider(name = "PositionProvider") public Object[][] getLookupPositions() { return new Object[][]{ diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInClassObjectTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInClassObjectTest.java index 710fda243c58..f94997c57183 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInClassObjectTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInClassObjectTest.java @@ -32,6 +32,7 @@ @Test public class FindRefsInClassObjectTest extends FindAllReferencesTest { + @Override @DataProvider(name = "PositionProvider") public Object[][] getLookupPositions() { return new Object[][]{ @@ -82,6 +83,7 @@ public String getTestSourcePath() { return "test-src/find-all-ref/find_refs_in_class_object.bal"; } + @Override @AfterClass public void tearDown() { super.tearDown(); diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInConditionalStmtTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInConditionalStmtTest.java index cf7048edf2c8..cb81d0b31039 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInConditionalStmtTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInConditionalStmtTest.java @@ -31,6 +31,7 @@ @Test public class FindRefsInConditionalStmtTest extends FindAllReferencesTest { + @Override @DataProvider(name = "PositionProvider") public Object[][] getLookupPositions() { return new Object[][]{ diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInDoStmtTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInDoStmtTest.java index fa3dd12a1095..e1d36864ed35 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInDoStmtTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInDoStmtTest.java @@ -31,6 +31,7 @@ @Test public class FindRefsInDoStmtTest extends FindAllReferencesTest { + @Override @DataProvider(name = "PositionProvider") public Object[][] getLookupPositions() { return new Object[][]{ diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInErrorBindingPatternsTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInErrorBindingPatternsTest.java index c93059b8f146..4f0c8b292891 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInErrorBindingPatternsTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInErrorBindingPatternsTest.java @@ -29,6 +29,7 @@ @Test public class FindRefsInErrorBindingPatternsTest extends FindAllReferencesTest { + @Override @DataProvider(name = "PositionProvider") public Object[][] getLookupPositions() { return new Object[][]{ diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInErrorConstructorTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInErrorConstructorTest.java index ee16ec787d0c..77b3c8d00ccc 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInErrorConstructorTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInErrorConstructorTest.java @@ -31,6 +31,7 @@ @Test public class FindRefsInErrorConstructorTest extends FindAllReferencesTest { + @Override @DataProvider(name = "PositionProvider") public Object[][] getLookupPositions() { return new Object[][]{ diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInExprsTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInExprsTest.java index 84f855a5a14f..696bfb851c1d 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInExprsTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInExprsTest.java @@ -31,6 +31,7 @@ @Test public class FindRefsInExprsTest extends FindAllReferencesTest { + @Override @DataProvider(name = "PositionProvider") public Object[][] getLookupPositions() { return new Object[][]{ diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInFailTrtryStmtTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInFailTrtryStmtTest.java index 140ccc72bb65..7a68cae1e9e4 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInFailTrtryStmtTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInFailTrtryStmtTest.java @@ -31,6 +31,7 @@ @Test public class FindRefsInFailTrtryStmtTest extends FindAllReferencesTest { + @Override @DataProvider(name = "PositionProvider") public Object[][] getLookupPositions() { return new Object[][]{ diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInLambdasTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInLambdasTest.java index d94c2325bb9c..3a3b01d098ea 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInLambdasTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInLambdasTest.java @@ -31,6 +31,7 @@ @Test public class FindRefsInLambdasTest extends FindAllReferencesTest { + @Override @DataProvider(name = "PositionProvider") public Object[][] getLookupPositions() { return new Object[][]{ diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInMatchStmtTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInMatchStmtTest.java index 937aa9db950f..1636d7c153e5 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInMatchStmtTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInMatchStmtTest.java @@ -31,6 +31,7 @@ @Test public class FindRefsInMatchStmtTest extends FindAllReferencesTest { + @Override @DataProvider(name = "PositionProvider") public Object[][] getLookupPositions() { return new Object[][]{ diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInRecordTypeDefTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInRecordTypeDefTest.java index 2dbca80363ce..69575b7564fb 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInRecordTypeDefTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInRecordTypeDefTest.java @@ -31,6 +31,7 @@ @Test public class FindRefsInRecordTypeDefTest extends FindAllReferencesTest { + @Override @DataProvider(name = "PositionProvider") public Object[][] getLookupPositions() { return new Object[][]{ diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInRegCompoundStmtTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInRegCompoundStmtTest.java index 9635658c9ed6..a94773a79702 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInRegCompoundStmtTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInRegCompoundStmtTest.java @@ -31,6 +31,7 @@ @Test public class FindRefsInRegCompoundStmtTest extends FindAllReferencesTest { + @Override @DataProvider(name = "PositionProvider") public Object[][] getLookupPositions() { return new Object[][]{ diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInResourceAccessActionTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInResourceAccessActionTest.java index 14e94c139ac3..70cdf9ec0dc8 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInResourceAccessActionTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInResourceAccessActionTest.java @@ -31,6 +31,7 @@ @Test public class FindRefsInResourceAccessActionTest extends FindAllReferencesTest { + @Override @DataProvider(name = "PositionProvider") public Object[][] getLookupPositions() { return new Object[][]{ @@ -43,8 +44,9 @@ public Object[][] getLookupPositions() { List.of(location(22, 22, 25), location(46, 15, 16)) }, - {46, 16, location(22, 26, 27), - List.of() + {46, 16, location(22, 22, 25), + List.of(location(22, 22, 25), + location(46, 15, 16)) }, // Resource function invocation // Note: The symbol location of the resource-function is set to function-name's location @@ -62,9 +64,11 @@ public Object[][] getLookupPositions() { List.of(location(35, 22, 25), location(52, 26, 36)) }, - {54, 29, location(39, 22, 26), - List.of(location(39, 22, 26), - location(54, 29, 39)) + {54, 29, location(39, 22, 26), List.of() + }, + {54, 31, location(39, 27, 30), + List.of(location(39, 27, 30), + location(54, 30, 33)) }, // Resource path name segments {47, 36, location(25, 26, 29), diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInServiceDeclTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInServiceDeclTest.java index e28f14888035..750684ab1da5 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInServiceDeclTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInServiceDeclTest.java @@ -31,6 +31,7 @@ @Test public class FindRefsInServiceDeclTest extends FindAllReferencesTest { + @Override @DataProvider(name = "PositionProvider") public Object[][] getLookupPositions() { return new Object[][]{ diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInTestsTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInTestsTest.java index 628a7bd6d52e..bba32bf4c551 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInTestsTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInTestsTest.java @@ -38,6 +38,7 @@ @Test public class FindRefsInTestsTest extends FindAllReferencesTest { + @Override @BeforeClass public void setup() { Project project = BCompileUtil.loadProject(getTestSourcePath()); @@ -47,6 +48,7 @@ public void setup() { srcFile = baz.document(id); } + @Override @DataProvider(name = "PositionProvider") public Object[][] getLookupPositions() { return new Object[][]{ diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInTransactionalStmtTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInTransactionalStmtTest.java index 5487bc825bfc..3226b826ffd0 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInTransactionalStmtTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInTransactionalStmtTest.java @@ -31,6 +31,7 @@ @Test public class FindRefsInTransactionalStmtTest extends FindAllReferencesTest { + @Override @DataProvider(name = "PositionProvider") public Object[][] getLookupPositions() { return new Object[][]{ diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInTupleTypeTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInTupleTypeTest.java index 30bc5fc23f8c..bda3ceeecf24 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInTupleTypeTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInTupleTypeTest.java @@ -31,6 +31,7 @@ @Test public class FindRefsInTupleTypeTest extends FindAllReferencesTest { + @Override @DataProvider(name = "PositionProvider") public Object[][] getLookupPositions() { return new Object[][]{ diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInWorkersTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInWorkersTest.java index 46b54f7208b6..f19a722388e9 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInWorkersTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsInWorkersTest.java @@ -31,6 +31,7 @@ @Test public class FindRefsInWorkersTest extends FindAllReferencesTest { + @Override @DataProvider(name = "PositionProvider") public Object[][] getLookupPositions() { return new Object[][]{ diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsOfEnumsTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsOfEnumsTest.java index 22e1eca4833e..432b8e8ced7c 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsOfEnumsTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/FindRefsOfEnumsTest.java @@ -31,6 +31,7 @@ @Test public class FindRefsOfEnumsTest extends FindAllReferencesTest { + @Override @DataProvider(name = "PositionProvider") public Object[][] getLookupPositions() { return new Object[][]{ diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/XMLRefsTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/XMLRefsTest.java index b935d1791e48..9c9b59b17d20 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/XMLRefsTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/allreferences/XMLRefsTest.java @@ -31,6 +31,7 @@ @Test public class XMLRefsTest extends FindAllReferencesTest { + @Override @DataProvider(name = "PositionProvider") public Object[][] getLookupPositions() { return new Object[][]{ diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/symbolbynode/SymbolByClientResourceAccessActionTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/symbolbynode/SymbolByClientResourceAccessActionTest.java index 44d0eb0b710b..f152d0ca5908 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/symbolbynode/SymbolByClientResourceAccessActionTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/symbolbynode/SymbolByClientResourceAccessActionTest.java @@ -28,6 +28,7 @@ import io.ballerina.compiler.syntax.tree.ComputedResourceAccessSegmentNode; import io.ballerina.compiler.syntax.tree.Node; import io.ballerina.compiler.syntax.tree.NodeVisitor; +import org.testng.Assert; import org.testng.annotations.Test; import java.util.List; @@ -79,23 +80,15 @@ public void visit(ClientResourceAccessActionNode clientResourceAccessActionNode) @Override public void visit(ComputedResourceAccessSegmentNode computedResourceAccessSegmentNode) { - List expPathSignatures = List.of("path2", "[string id]", "path4"); - ResourceMethodSymbol symbol = - (ResourceMethodSymbol) assertSymbol(computedResourceAccessSegmentNode, model, RESOURCE_METHOD, - "post"); - symbol.resourcePath(); - assertEquals(symbol.resourcePath().kind(), ResourcePath.Kind.PATH_SEGMENT_LIST); - - PathSegmentList pathSegmentList = (PathSegmentList) symbol.resourcePath(); - assertTrue(pathSegmentList.list().stream() - .allMatch(pathSeg -> expPathSignatures.contains(pathSeg.signature()))); + Optional symbol = model.symbol(computedResourceAccessSegmentNode); + Assert.assertTrue(symbol.isEmpty()); } }; } @Override void verifyAssertCount() { - assertEquals(getAssertCount(), 3); + assertEquals(getAssertCount(), 2); } private Symbol assertSymbol(Node node, SemanticModel model, SymbolKind kind, String name) { diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/symbols/ClassSymbolTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/symbols/ClassSymbolTest.java index 982387fdca33..3f50ae544f34 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/symbols/ClassSymbolTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/symbols/ClassSymbolTest.java @@ -42,7 +42,6 @@ import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; import static io.ballerina.compiler.api.symbols.SymbolKind.CLASS; import static io.ballerina.compiler.api.symbols.SymbolKind.CLASS_FIELD; @@ -88,7 +87,7 @@ public void testSymbolAtCursor() { assertEquals(initMethod.getName().get(), "init"); assertEquals(initMethod.typeDescriptor().params().get().stream() .map(p -> p.getName().get()) - .collect(Collectors.toList()), fieldNames); + .toList(), fieldNames); } @Test diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/symbols/ConstAnnotationAttachmentSymbolTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/symbols/ConstAnnotationAttachmentSymbolTest.java index 566fce5270de..93a4660c67c7 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/symbols/ConstAnnotationAttachmentSymbolTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/symbols/ConstAnnotationAttachmentSymbolTest.java @@ -87,7 +87,7 @@ public void testValuesInConstantAnnotationAttachment() { // Test const value assertTrue(constVal.value() instanceof HashMap); - HashMap valueMap = (HashMap) constVal.value(); + HashMap valueMap = (HashMap) constVal.value(); assertTrue(valueMap.get("id") instanceof BallerinaConstantValue); BallerinaConstantValue idValue = @@ -99,7 +99,7 @@ public void testValuesInConstantAnnotationAttachment() { BallerinaConstantValue permValue = (BallerinaConstantValue) valueMap.get("perm"); assertEquals(permValue.valueType().typeKind(), TypeDescKind.RECORD); assertTrue(permValue.value() instanceof HashMap); - HashMap permMap = (HashMap) permValue.value(); + HashMap permMap = (HashMap) permValue.value(); assertEquals(((BallerinaConstantValue) permMap.get("a")).value(), 1L); assertEquals(((BallerinaConstantValue) permMap.get("a")).valueType().typeKind(), TypeDescKind.INT); assertEquals(((BallerinaConstantValue) permMap.get("b")).value(), 2L); diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/symbols/ConstDeclSymbolTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/symbols/ConstDeclSymbolTest.java index 973ed06a2ce9..a84c26328fa9 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/symbols/ConstDeclSymbolTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/symbols/ConstDeclSymbolTest.java @@ -167,7 +167,7 @@ public void testValuesInConstantAnnotationAttachment() { // Test const value assertTrue(constVal.value() instanceof HashMap); - HashMap valueMap = (HashMap) constVal.value(); + HashMap valueMap = (HashMap) constVal.value(); assertTrue(valueMap.get("id") instanceof BallerinaConstantValue); BallerinaConstantValue idValue = @@ -180,7 +180,7 @@ public void testValuesInConstantAnnotationAttachment() { (BallerinaConstantValue) valueMap.get("perm"); assertEquals(permValue.valueType().typeKind(), TypeDescKind.RECORD); assertTrue(permValue.value() instanceof HashMap); - HashMap permMap = (HashMap) permValue.value(); + HashMap permMap = (HashMap) permValue.value(); assertEquals(((BallerinaConstantValue) permMap.get("a")).value(), 1L); assertEquals(((BallerinaConstantValue) permMap.get("a")).valueType().typeKind(), TypeDescKind.INT); assertEquals(((BallerinaConstantValue) permMap.get("b")).value(), 2L); diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/symbols/UnionTypeSymbolTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/symbols/UnionTypeSymbolTest.java index 10ea35627803..bcb5c91c089b 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/symbols/UnionTypeSymbolTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/symbols/UnionTypeSymbolTest.java @@ -32,7 +32,6 @@ import org.testng.annotations.Test; import java.util.List; -import java.util.stream.Collectors; import static io.ballerina.semantic.api.test.util.SemanticAPITestUtils.assertBasicsAndGetSymbol; import static io.ballerina.semantic.api.test.util.SemanticAPITestUtils.getDefaultModulesSemanticModel; @@ -69,7 +68,7 @@ public void testUnionTypeMemberTypes(int line, int col, String name, List memberTypeDescKindList = memberTypeDescriptors .stream() .map(TypeSymbol::typeKind) - .collect(Collectors.toList()); + .toList(); assertList(memberTypeDescKindList, expTypeList); } @@ -112,7 +111,7 @@ public void testSingletonMembers() { .stream() .filter(member -> member.typeKind() == TypeDescKind.SINGLETON) .map(TypeSymbol::signature) - .collect(Collectors.toList()); + .toList(); assertList(signatures, List.of("\"int\"", "\"string\"", "100", "\"200\"", "true")); } diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByAccessExprTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByAccessExprTest.java index edc3ba798a05..589d58936c57 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByAccessExprTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByAccessExprTest.java @@ -111,6 +111,7 @@ public void visit(AnnotAccessExpressionNode annotAccessExpressionNode) { }; } + @Override void verifyAssertCount() { assertEquals(getAssertCount(), 7); } diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByAnonFunctionTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByAnonFunctionTest.java index d28e47085db5..f74dafbe4dc9 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByAnonFunctionTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByAnonFunctionTest.java @@ -69,6 +69,7 @@ public void visit(FunctionCallExpressionNode functionCallExpressionNode) { }; } + @Override void verifyAssertCount() { assertEquals(getAssertCount(), 4); } diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByCallExprTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByCallExprTest.java index dea452ce50ee..9ddc265e40b9 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByCallExprTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByCallExprTest.java @@ -62,6 +62,7 @@ public void visit(MethodCallExpressionNode methodCallExpressionNode) { }; } + @Override void verifyAssertCount() { assertEquals(getAssertCount(), 2); } diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByConstructorExprTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByConstructorExprTest.java index 9e93debbcb8b..a97e08ba39f5 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByConstructorExprTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByConstructorExprTest.java @@ -108,6 +108,7 @@ public void visit(ErrorConstructorExpressionNode errorConstructorExpressionNode) }; } + @Override void verifyAssertCount() { assertEquals(getAssertCount(), 8); } diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByErrorHandlingExprTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByErrorHandlingExprTest.java index 8197b712fb8b..605cc55d6229 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByErrorHandlingExprTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByErrorHandlingExprTest.java @@ -70,6 +70,7 @@ public void visit(TrapExpressionNode trapExpressionNode) { }; } + @Override void verifyAssertCount() { assertEquals(getAssertCount(), 3); } diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByLiteralTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByLiteralTest.java index 474fbf82febe..9719fa7f548c 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByLiteralTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByLiteralTest.java @@ -89,6 +89,7 @@ public void visit(BasicLiteralNode basicLiteralNode) { }; } + @Override void verifyAssertCount() { assertEquals(getAssertCount(), 9); } diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByMiscExprTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByMiscExprTest.java index a9c3f4366cf0..55f05734b4f9 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByMiscExprTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByMiscExprTest.java @@ -66,26 +66,12 @@ public void visit(UnaryExpressionNode unaryExpressionNode) { @Override public void visit(BinaryExpressionNode binaryExpressionNode) { - TypeDescKind typeKind; - switch (OperatorKind.valueFrom(binaryExpressionNode.operator().text())) { - case SUB: - case MUL: - case ADD: - case DIV: - typeKind = INT; - break; - case GREATER_EQUAL: - case NOT_EQUAL: - case EQUAL: - case AND: - typeKind = BOOLEAN; - break; - case CLOSED_RANGE: - typeKind = OBJECT; - break; - default: - throw new IllegalStateException(); - } + TypeDescKind typeKind = switch (OperatorKind.valueFrom(binaryExpressionNode.operator().text())) { + case SUB, MUL, ADD, DIV -> INT; + case GREATER_EQUAL, NOT_EQUAL, EQUAL, AND -> BOOLEAN; + case CLOSED_RANGE -> OBJECT; + default -> throw new IllegalStateException(); + }; assertType(binaryExpressionNode, model, typeKind); binaryExpressionNode.rhsExpr().accept(this); @@ -120,6 +106,7 @@ public void visit(XMLStepExpressionNode xmlStepExpressionNode) { }; } + @Override void verifyAssertCount() { assertEquals(getAssertCount(), 16); } diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByReferenceTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByReferenceTest.java index 9227ab9f3041..0008780d9a77 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByReferenceTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByReferenceTest.java @@ -64,22 +64,17 @@ public void visit(QualifiedNameReferenceNode qualifiedNameReferenceNode) { @Override public void visit(BuiltinSimpleNameReferenceNode builtinSimpleNameReferenceNode) { - TypeDescKind typeKind; - switch (builtinSimpleNameReferenceNode.kind()) { - case FLOAT_TYPE_DESC: - typeKind = FLOAT; - break; - case INT_TYPE_DESC: - typeKind = INT; - break; - default: - throw new IllegalStateException(); - } + TypeDescKind typeKind = switch (builtinSimpleNameReferenceNode.kind()) { + case FLOAT_TYPE_DESC -> FLOAT; + case INT_TYPE_DESC -> INT; + default -> throw new IllegalStateException(); + }; assertType(builtinSimpleNameReferenceNode, model, typeKind); } }; } + @Override void verifyAssertCount() { assertEquals(getAssertCount(), 4); } diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByTemplateExprTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByTemplateExprTest.java index 98fd2ed8547d..cffcd52101e6 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByTemplateExprTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByTemplateExprTest.java @@ -56,26 +56,18 @@ NodeVisitor getNodeVisitor(SemanticModel model) { @Override public void visit(TemplateExpressionNode templateExpressionNode) { - TypeDescKind expTypeKind; - switch (templateExpressionNode.kind()) { - case STRING_TEMPLATE_EXPRESSION: - expTypeKind = STRING; - break; - case XML_TEMPLATE_EXPRESSION: - expTypeKind = TYPE_REFERENCE; - break; - case RAW_TEMPLATE_EXPRESSION: - expTypeKind = TYPE_REFERENCE; - break; - default: - throw new IllegalStateException(); - } + TypeDescKind expTypeKind = switch (templateExpressionNode.kind()) { + case STRING_TEMPLATE_EXPRESSION -> STRING; + case XML_TEMPLATE_EXPRESSION, RAW_TEMPLATE_EXPRESSION -> TYPE_REFERENCE; + default -> throw new IllegalStateException(); + }; assertType(templateExpressionNode, model, expTypeKind, templateExpressionNode.kind()); } }; } + @Override void verifyAssertCount() { assertEquals(getAssertCount(), 3); } diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByTypeExprTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByTypeExprTest.java index 0503c4863e8f..7e029e1f84a4 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByTypeExprTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/deprecated/TypeByTypeExprTest.java @@ -70,6 +70,7 @@ public void visit(TypeTestExpressionNode typeTestExpressionNode) { }; } + @Override void verifyAssertCount() { assertEquals(getAssertCount(), 3); } diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByAccessExprTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByAccessExprTest.java index 6512362d11b0..2bfc1bde5852 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByAccessExprTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByAccessExprTest.java @@ -111,6 +111,7 @@ public void visit(AnnotAccessExpressionNode annotAccessExpressionNode) { }; } + @Override void verifyAssertCount() { assertEquals(getAssertCount(), 7); } diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByAnonFunctionTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByAnonFunctionTest.java index b6768b434885..0d8a4c9d4f0a 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByAnonFunctionTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByAnonFunctionTest.java @@ -68,6 +68,7 @@ public void visit(FunctionCallExpressionNode functionCallExpressionNode) { }; } + @Override void verifyAssertCount() { assertEquals(getAssertCount(), 4); } diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByCallExprTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByCallExprTest.java index 8807483b6cd5..c11a009163c7 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByCallExprTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByCallExprTest.java @@ -62,6 +62,7 @@ public void visit(MethodCallExpressionNode methodCallExpressionNode) { }; } + @Override void verifyAssertCount() { assertEquals(getAssertCount(), 2); } diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByConstructorExprTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByConstructorExprTest.java index 28c2f0cc4e12..1cefe50a4258 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByConstructorExprTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByConstructorExprTest.java @@ -108,6 +108,7 @@ public void visit(ErrorConstructorExpressionNode errorConstructorExpressionNode) }; } + @Override void verifyAssertCount() { assertEquals(getAssertCount(), 8); } diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByErrorHandlingExprTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByErrorHandlingExprTest.java index 5a6b72c53327..8da9240c16be 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByErrorHandlingExprTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByErrorHandlingExprTest.java @@ -70,6 +70,7 @@ public void visit(TrapExpressionNode trapExpressionNode) { }; } + @Override void verifyAssertCount() { assertEquals(getAssertCount(), 3); } diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByLiteralTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByLiteralTest.java index 3f39c121d6d7..4e5bc6b12a2e 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByLiteralTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByLiteralTest.java @@ -89,6 +89,7 @@ public void visit(BasicLiteralNode basicLiteralNode) { }; } + @Override void verifyAssertCount() { assertEquals(getAssertCount(), 9); } diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByMiscExprTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByMiscExprTest.java index 832779d6c393..7a21db27cb3d 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByMiscExprTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByMiscExprTest.java @@ -66,26 +66,12 @@ public void visit(UnaryExpressionNode unaryExpressionNode) { @Override public void visit(BinaryExpressionNode binaryExpressionNode) { - TypeDescKind typeKind; - switch (OperatorKind.valueFrom(binaryExpressionNode.operator().text())) { - case SUB: - case MUL: - case ADD: - case DIV: - typeKind = INT; - break; - case GREATER_EQUAL: - case NOT_EQUAL: - case EQUAL: - case AND: - typeKind = BOOLEAN; - break; - case CLOSED_RANGE: - typeKind = OBJECT; - break; - default: - throw new IllegalStateException(); - } + TypeDescKind typeKind = switch (OperatorKind.valueFrom(binaryExpressionNode.operator().text())) { + case SUB, MUL, ADD, DIV -> INT; + case GREATER_EQUAL, NOT_EQUAL, EQUAL, AND -> BOOLEAN; + case CLOSED_RANGE -> OBJECT; + default -> throw new IllegalStateException(); + }; assertType(binaryExpressionNode, model, typeKind); binaryExpressionNode.rhsExpr().accept(this); @@ -120,6 +106,7 @@ public void visit(XMLStepExpressionNode xmlStepExpressionNode) { }; } + @Override void verifyAssertCount() { assertEquals(getAssertCount(), 16); } diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByReferenceTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByReferenceTest.java index 6784f5f10ae1..69dd4141af9b 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByReferenceTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByReferenceTest.java @@ -69,6 +69,7 @@ public void visit(BuiltinSimpleNameReferenceNode builtinSimpleNameReferenceNode) }; } + @Override void verifyAssertCount() { assertEquals(getAssertCount(), 4); } diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByTemplateExprTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByTemplateExprTest.java index bff2bcfa836c..6c6d823d3a51 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByTemplateExprTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByTemplateExprTest.java @@ -56,26 +56,18 @@ NodeVisitor getNodeVisitor(SemanticModel model) { @Override public void visit(TemplateExpressionNode templateExpressionNode) { - TypeDescKind expTypeKind; - switch (templateExpressionNode.kind()) { - case STRING_TEMPLATE_EXPRESSION: - expTypeKind = STRING; - break; - case XML_TEMPLATE_EXPRESSION: - expTypeKind = TYPE_REFERENCE; - break; - case RAW_TEMPLATE_EXPRESSION: - expTypeKind = TYPE_REFERENCE; - break; - default: - throw new IllegalStateException(); - } + TypeDescKind expTypeKind = switch (templateExpressionNode.kind()) { + case STRING_TEMPLATE_EXPRESSION -> STRING; + case XML_TEMPLATE_EXPRESSION, RAW_TEMPLATE_EXPRESSION -> TYPE_REFERENCE; + default -> throw new IllegalStateException(); + }; assertType(templateExpressionNode, model, expTypeKind, templateExpressionNode.kind()); } }; } + @Override void verifyAssertCount() { assertEquals(getAssertCount(), 3); } diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByTypeExprTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByTypeExprTest.java index c20d8503ba80..6358847fa8b5 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByTypeExprTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/typebynode/newapi/TypeByTypeExprTest.java @@ -70,6 +70,7 @@ public void visit(TypeTestExpressionNode typeTestExpressionNode) { }; } + @Override void verifyAssertCount() { assertEquals(getAssertCount(), 3); } diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/util/SemanticAPITestUtils.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/util/SemanticAPITestUtils.java index 3a4dd5737d60..c12a31476fc1 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/util/SemanticAPITestUtils.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/util/SemanticAPITestUtils.java @@ -55,7 +55,10 @@ * * @since 2.0.0 */ -public class SemanticAPITestUtils { +public final class SemanticAPITestUtils { + + private SemanticAPITestUtils() { + } public static Document getDocumentForSingleSource(Project project) { Package currentPackage = project.currentPackage(); @@ -151,12 +154,12 @@ public static Map getSymbolsInFile(SemanticModel model, Document } public static List getSymbolNames(List mainList, String... args) { - return Stream.concat(mainList.stream(), Stream.of(args)).collect(Collectors.toList()); + return Stream.concat(mainList.stream(), Stream.of(args)).toList(); } @SafeVarargs public static List getSymbolNames(List... lists) { - return Arrays.stream(lists).flatMap(Collection::stream).collect(Collectors.toList()); + return Arrays.stream(lists).flatMap(Collection::stream).toList(); } public static List getSymbolNames(BPackageSymbol pkgSymbol, int symTag) { diff --git a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/visiblesymbols/BaseVisibleSymbolsTest.java b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/visiblesymbols/BaseVisibleSymbolsTest.java index 883c0c1e2cda..67f03cb4f1c3 100644 --- a/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/visiblesymbols/BaseVisibleSymbolsTest.java +++ b/tests/ballerina-compiler-api-test/src/test/java/io/ballerina/semantic/api/test/visiblesymbols/BaseVisibleSymbolsTest.java @@ -37,7 +37,6 @@ import java.util.List; import java.util.Map; import java.util.function.Consumer; -import java.util.stream.Collectors; import java.util.stream.Stream; import static io.ballerina.semantic.api.test.util.SemanticAPITestUtils.getDocumentForSingleSource; @@ -91,7 +90,7 @@ Consumer> getAdditionalAssertions() { } List concat(List list, ExpectedSymbolInfo... symbols) { - return Stream.concat(list.stream(), Stream.of(symbols)).collect(Collectors.toList()); + return Stream.concat(list.stream(), Stream.of(symbols)).toList(); } static class ExpectedSymbolInfo { diff --git a/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/BAssertUtil.java b/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/BAssertUtil.java index a8eee413d23d..cc5a143e67ac 100644 --- a/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/BAssertUtil.java +++ b/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/BAssertUtil.java @@ -26,11 +26,14 @@ * * @since 2.0.0 */ -public class BAssertUtil { +public final class BAssertUtil { private static final String CARRIAGE_RETURN_CHAR = "\\r"; private static final String EMPTY_STRING = ""; + private BAssertUtil() { + } + /** * Assert an error. * diff --git a/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/BCompileUtil.java b/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/BCompileUtil.java index 72905986706d..89cb62d24209 100644 --- a/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/BCompileUtil.java +++ b/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/BCompileUtil.java @@ -42,6 +42,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.stream.Stream; import static io.ballerina.projects.util.ProjectConstants.CACHES_DIR_NAME; import static io.ballerina.projects.util.ProjectConstants.DIST_CACHE_DIRECTORY; @@ -51,7 +52,7 @@ * * @since 2.0.0 */ -public class BCompileUtil { +public final class BCompileUtil { private static final Path testSourcesDirectory = Paths.get("src/test/resources").toAbsolutePath().normalize(); private static final Path testBuildDirectory = Paths.get("build").toAbsolutePath().normalize(); @@ -187,8 +188,8 @@ public static CompileResult compileAndCacheBala(Path projectPath, Path repoPath, currentPackage.packageName().toString(), currentPackage.packageVersion().toString(), repoPath); jBallerinaBackend.emit(JBallerinaBackend.OutputType.BALA, balaCachePath); Path balaFilePath; - try { - balaFilePath = Files.list(balaCachePath).filter(path -> + try (Stream paths = Files.list(balaCachePath)) { + balaFilePath = paths.filter(path -> path.toString().endsWith(ProjectConstants.BLANG_COMPILED_PKG_BINARY_EXT)).findAny().orElseThrow(); String platform = getPlatformFromBala(balaFilePath.getFileName().toString(), currentPackage.packageName().toString(), currentPackage.packageVersion().toString()); diff --git a/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/BRunUtil.java b/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/BRunUtil.java index c12f004575bd..60c0be17edf4 100644 --- a/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/BRunUtil.java +++ b/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/BRunUtil.java @@ -25,6 +25,7 @@ import io.ballerina.runtime.api.async.StrandMetadata; import io.ballerina.runtime.api.creators.ErrorCreator; import io.ballerina.runtime.api.utils.StringUtils; +import io.ballerina.runtime.api.values.BError; import io.ballerina.runtime.internal.configurable.providers.ConfigDetails; import io.ballerina.runtime.internal.launch.LaunchUtils; import io.ballerina.runtime.internal.scheduling.Scheduler; @@ -76,7 +77,7 @@ * * @since 2.0.0 */ -public class BRunUtil { +public final class BRunUtil { private static final Boolean IS_WINDOWS = System.getProperty("os.name").toLowerCase(Locale.getDefault()) .contains("win"); @@ -190,9 +191,9 @@ private static Object invoke(CompileResult compileResult, BIRNode.BIRFunction fu if (t instanceof BLangTestException) { throw ErrorCreator.createError(StringUtils.fromString(t.getMessage())); } - if (t instanceof io.ballerina.runtime.api.values.BError) { + if (t instanceof BError bError) { throw ErrorCreator.createError(StringUtils.fromString( - "error: " + ((io.ballerina.runtime.api.values.BError) t).getPrintableStackTrace())); + "error: " + bError.getPrintableStackTrace())); } if (t instanceof StackOverflowError) { throw ErrorCreator.createError(StringUtils.fromString("error: " + @@ -384,16 +385,15 @@ public static void runInit(CompileResult compileResult) throws ClassNotFoundExce // } } - private static void directRun(Class initClazz, String functionName, Class[] paramTypes, Object[] args) { + private static void directRun(Class initClazz, String functionName, Class[] paramTypes, Object[] args) { String funcName = JvmCodeGenUtil.cleanupFunctionName(functionName); String errorMsg = "Failed to invoke the function '%s' due to %s"; Object response; try { final Method method = initClazz.getDeclaredMethod(funcName, paramTypes); response = method.invoke(null, args); - if (response instanceof Throwable) { - throw new BLangTestException(String.format(errorMsg, funcName, response), - (Throwable) response); + if (response instanceof Throwable throwable) { + throw new BLangTestException(String.format(errorMsg, funcName, response), throwable); } } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw new BLangTestException(String.format(errorMsg, funcName, e.getMessage()), e); @@ -430,8 +430,8 @@ private static void runOnSchedule(Class initClazz, BLangIdentifier name, Sche return method.invoke(null, objects[0]); } catch (InvocationTargetException e) { Throwable targetException = e.getTargetException(); - if (targetException instanceof RuntimeException) { - throw (RuntimeException) targetException; + if (targetException instanceof RuntimeException runtimeException) { + throw runtimeException; } else { throw new RuntimeException(targetException); } @@ -445,8 +445,8 @@ private static void runOnSchedule(Class initClazz, BLangIdentifier name, Sche scheduler.start(); final Throwable t = out.panic; if (t != null) { - if (t instanceof ErrorValue) { - throw new BLangTestException("error: " + ((ErrorValue) t).getPrintableStackTrace()); + if (t instanceof ErrorValue errorValue) { + throw new BLangTestException("error: " + errorValue.getPrintableStackTrace()); } throw (RuntimeException) t; } diff --git a/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/agent/BallerinaServerAgent.java b/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/agent/BallerinaServerAgent.java index 8c4969205650..f6cc39bbdb40 100644 --- a/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/agent/BallerinaServerAgent.java +++ b/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/agent/BallerinaServerAgent.java @@ -36,7 +36,8 @@ * * @since 0.982.0 */ -public class BallerinaServerAgent { +public final class BallerinaServerAgent { + private static PrintStream outStream = System.err; /** @@ -77,6 +78,9 @@ public class BallerinaServerAgent { private static String agentHost = DEFAULT_AGENT_HOST; private static int agentPort = DEFAULT_AGENT_PORT; + private BallerinaServerAgent() { + } + /** * This method will be called before invoking ballerina Main method. * diff --git a/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/agent/server/WebServer.java b/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/agent/server/WebServer.java index 2b13bfd014ec..4d4c4f14b83f 100644 --- a/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/agent/server/WebServer.java +++ b/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/agent/server/WebServer.java @@ -191,10 +191,9 @@ public void channelReadComplete(final ChannelHandlerContext ctx) { */ @Override protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception { - if (!(o instanceof FullHttpRequest)) { + if (!(o instanceof FullHttpRequest request)) { return; } - final FullHttpRequest request = (FullHttpRequest) o; final HttpMethod method = request.method(); final String uri = request.uri(); diff --git a/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/context/Constant.java b/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/context/Constant.java index 0f5c92e5fed8..c5a0a7f02fe6 100644 --- a/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/context/Constant.java +++ b/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/context/Constant.java @@ -20,7 +20,8 @@ /** * Constant used for server startup. */ -public class Constant { +public final class Constant { + //Name of the system property define the location of the service distribution public static final String SYSTEM_PROP_SERVER_ZIP = "server.zip"; //Name of the system property define the location of the jballerina service distribution @@ -50,4 +51,7 @@ public class Constant { public static final String BALLERINA_AGENT_PATH = "ballerina.agent.path"; public static final String JACOCO_AGENT_ARG_LINE = "jacoco.agent.argLine"; + + private Constant() { + } } diff --git a/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/context/Utils.java b/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/context/Utils.java index 296df21824b5..ff1a971cf7ba 100644 --- a/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/context/Utils.java +++ b/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/context/Utils.java @@ -36,7 +36,7 @@ /** * Utility class for test integration common functions. */ -public class Utils { +public final class Utils { private static final Logger log = LoggerFactory.getLogger(Utils.class); diff --git a/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/util/BFileUtil.java b/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/util/BFileUtil.java index 77e6ceb8aa7e..4af5862baa39 100644 --- a/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/util/BFileUtil.java +++ b/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/util/BFileUtil.java @@ -35,16 +35,20 @@ import java.nio.file.attribute.BasicFileAttributes; import java.util.List; import java.util.Objects; +import java.util.stream.Stream; /** * Utility methods for doing file operations. * * @since 0.975.0 */ -public class BFileUtil { +public final class BFileUtil { private static final String IGNORE = ".gitignore"; + private BFileUtil() { + } + /** * Copy a file or directory to a target location. * @@ -110,7 +114,9 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IO @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { if (Files.exists(dir)) { - Files.list(dir).forEach(BFileUtil::delete); + try (Stream paths = Files.list(dir)) { + paths.forEach(BFileUtil::delete); + } } return FileVisitResult.CONTINUE; } @@ -131,8 +137,12 @@ public static void deleteAll(Path path, String pattern) throws IOException { if (!Files.exists(path)) { return; } - List files = Files.find(path, Integer.MAX_VALUE, (p, attribute) -> - p.toString().contains(pattern)).toList(); + List files; + try (Stream paths = Files.find(path, Integer.MAX_VALUE, (p, attribute) -> + p.toString().contains(pattern))) { + files = paths.toList(); + } + for (Path file : files) { BFileUtil.delete(file); } diff --git a/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/util/HttpClientRequest.java b/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/util/HttpClientRequest.java index 772e3b029373..284895672721 100644 --- a/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/util/HttpClientRequest.java +++ b/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/util/HttpClientRequest.java @@ -41,10 +41,14 @@ /** * This class can be used to send http request. */ -public class HttpClientRequest { +public final class HttpClientRequest { + private static final Logger LOG = LoggerFactory.getLogger(HttpClientRequest.class); private static final int DEFAULT_READ_TIMEOUT = 30000; + private HttpClientRequest() { + } + /** * Sends an HTTP GET request to a url. * @@ -116,13 +120,10 @@ public static HttpResponse doPost(String endpoint, String postBody, Map addBreakPoint(BallerinaTestDebugPoint br throws BallerinaTestException { testBreakpoints.add(breakpoint); List breakpointsToBeSent = new ArrayList<>(); - for (org.ballerinalang.debugger.test.utils.BallerinaTestDebugPoint bp : testBreakpoints) { + for (BallerinaTestDebugPoint bp : testBreakpoints) { if (bp.getSource().getPath().equals(breakpoint.getSource().getPath())) { breakpointsToBeSent.add(bp); } @@ -310,7 +310,7 @@ private SetBreakpointsResponse setBreakpoints(List brea public void removeBreakPoint(BallerinaTestDebugPoint breakpoint) throws BallerinaTestException { testBreakpoints.remove(breakpoint); List breakpointsToBeSent = new ArrayList<>(); - for (org.ballerinalang.debugger.test.utils.BallerinaTestDebugPoint bp : testBreakpoints) { + for (BallerinaTestDebugPoint bp : testBreakpoints) { if (bp.getSource().getPath().equals(breakpoint.getSource().getPath())) { breakpointsToBeSent.add(bp); } diff --git a/tests/jballerina-debugger-integration-test/src/main/java/org/ballerinalang/debugger/test/utils/DebugUtils.java b/tests/jballerina-debugger-integration-test/src/main/java/org/ballerinalang/debugger/test/utils/DebugUtils.java index d2b3225b26eb..162a00ac73f1 100644 --- a/tests/jballerina-debugger-integration-test/src/main/java/org/ballerinalang/debugger/test/utils/DebugUtils.java +++ b/tests/jballerina-debugger-integration-test/src/main/java/org/ballerinalang/debugger/test/utils/DebugUtils.java @@ -22,10 +22,13 @@ /** * Util class for debug related operations. */ -public class DebugUtils { +public final class DebugUtils { public static final String JBAL_DEBUG_CMD_NAME = "start-debugger-adapter"; + private DebugUtils() { + } + /** * Finds an available port. * diff --git a/tests/jballerina-debugger-integration-test/src/main/java/org/ballerinalang/debugger/test/utils/FileUtils.java b/tests/jballerina-debugger-integration-test/src/main/java/org/ballerinalang/debugger/test/utils/FileUtils.java index 68ff4e8b0f69..87662e728d2b 100644 --- a/tests/jballerina-debugger-integration-test/src/main/java/org/ballerinalang/debugger/test/utils/FileUtils.java +++ b/tests/jballerina-debugger-integration-test/src/main/java/org/ballerinalang/debugger/test/utils/FileUtils.java @@ -22,13 +22,14 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import java.util.stream.Stream; import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; /** * Util class for file operations. */ -public class FileUtils { +public final class FileUtils { static final String URI_SCHEME_BALA = "bala"; static final String URI_SCHEME_FILE = "file"; @@ -36,6 +37,9 @@ public class FileUtils { static final String FILE_SEPARATOR = File.separator; static final String FILE_SEPARATOR_REGEX = File.separatorChar == '\\' ? "\\\\" : File.separator; + private FileUtils() { + } + /** * Recursively copy a directory from a source to destination. * @@ -44,7 +48,9 @@ public class FileUtils { * @throws IOException thrown when as error occurs when copying from src to dest */ public static void copyFolder(Path src, Path dest) throws IOException { - Files.walk(src).forEach(source -> copy(source, dest.resolve(src.relativize(source)))); + try (Stream paths = Files.walk(src)) { + paths.forEach(source -> copy(source, dest.resolve(src.relativize(source)))); + } } private static void copy(Path source, Path dest) { diff --git a/tests/jballerina-debugger-integration-test/src/main/java/org/ballerinalang/debugger/test/utils/client/connection/ProcessStreamConnectionProvider.java b/tests/jballerina-debugger-integration-test/src/main/java/org/ballerinalang/debugger/test/utils/client/connection/ProcessStreamConnectionProvider.java index a35cc9800f96..0df593274dec 100644 --- a/tests/jballerina-debugger-integration-test/src/main/java/org/ballerinalang/debugger/test/utils/client/connection/ProcessStreamConnectionProvider.java +++ b/tests/jballerina-debugger-integration-test/src/main/java/org/ballerinalang/debugger/test/utils/client/connection/ProcessStreamConnectionProvider.java @@ -138,8 +138,7 @@ private void killProcessWithDescendants(Process parent) { @Override public boolean equals(Object obj) { - if (obj instanceof ProcessStreamConnectionProvider) { - ProcessStreamConnectionProvider other = (ProcessStreamConnectionProvider) obj; + if (obj instanceof ProcessStreamConnectionProvider other) { return commands.size() == other.commands.size() && new HashSet<>(commands).equals(new HashSet<>(other.commands)) && workingDir.equals(other.workingDir); diff --git a/tests/jballerina-debugger-integration-test/src/main/java/org/ballerinalang/debugger/test/utils/client/connection/SocketStreamConnectionProvider.java b/tests/jballerina-debugger-integration-test/src/main/java/org/ballerinalang/debugger/test/utils/client/connection/SocketStreamConnectionProvider.java index 3f0fc914bb9f..17d43bee955d 100644 --- a/tests/jballerina-debugger-integration-test/src/main/java/org/ballerinalang/debugger/test/utils/client/connection/SocketStreamConnectionProvider.java +++ b/tests/jballerina-debugger-integration-test/src/main/java/org/ballerinalang/debugger/test/utils/client/connection/SocketStreamConnectionProvider.java @@ -156,8 +156,7 @@ public void stop() { @Override public boolean equals(Object obj) { - if (obj instanceof SocketStreamConnectionProvider) { - SocketStreamConnectionProvider other = (SocketStreamConnectionProvider) obj; + if (obj instanceof SocketStreamConnectionProvider other) { return port == other.port && address.equals(other.address) && super.equals(obj); } return false; diff --git a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/BreakpointVerificationTest.java b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/BreakpointVerificationTest.java index e5b34ac36dca..4e4603e10776 100644 --- a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/BreakpointVerificationTest.java +++ b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/BreakpointVerificationTest.java @@ -35,7 +35,6 @@ import java.util.Arrays; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; /** * Test implementation for debug breakpoint verification scenarios. @@ -54,6 +53,7 @@ public class BreakpointVerificationTest extends BaseTestCase { private static final int DOCUMENTATION_START = MATCH_STMT_START + 8; private static final int WORKER_DCLN_START = DOCUMENTATION_START + 10; + @Override @BeforeClass public void setup() { String testProjectName = "breakpoint-verification-tests"; @@ -106,7 +106,7 @@ public void testOnTheFlyBreakpointVerification() throws BallerinaTestException { List breakPoints = Arrays.stream(breakpointResponse.get().getBreakpoints()) .map(breakpoint -> new BallerinaTestDebugPoint(Path.of(breakpoint.getSource().getPath()), breakpoint.getLine(), breakpoint.isVerified())) - .collect(Collectors.toList()); + .toList(); assertBreakpointChanges(breakPoints); } @@ -147,6 +147,7 @@ private void assertVerifiedBreakpoints(List breakpoints } } + @Override @AfterMethod(alwaysRun = true) public void cleanUp() { debugTestRunner.terminateDebugSession(); diff --git a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/CallStackDebugTest.java b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/CallStackDebugTest.java index 3974ec5f0036..6cad16fbe1ce 100644 --- a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/CallStackDebugTest.java +++ b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/CallStackDebugTest.java @@ -41,6 +41,7 @@ public class CallStackDebugTest extends BaseTestCase { DebugTestRunner debugTestRunner; + @Override @BeforeClass public void setup() { String testProjectName = "callstack-tests"; @@ -123,6 +124,7 @@ public void strandDebugTest() throws BallerinaTestException { Assert.assertEquals(threads.length, 1); } + @Override @AfterMethod(alwaysRun = true) public void cleanUp() { debugTestRunner.terminateDebugSession(); diff --git a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/ConditionalBreakpointTest.java b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/ConditionalBreakpointTest.java index 9f55b222d0a0..21973b05ebff 100644 --- a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/ConditionalBreakpointTest.java +++ b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/ConditionalBreakpointTest.java @@ -39,6 +39,7 @@ public class ConditionalBreakpointTest extends BaseTestCase { DebugTestRunner debugTestRunner; + @Override @BeforeClass public void setup() { String testProjectName = "conditional-breakpoint-tests"; @@ -130,6 +131,7 @@ public void testConditionalBreakpointScenarios() throws BallerinaTestException { Assert.assertEquals(debugHitInfo.getLeft(), debugTestRunner.testBreakpoints.get(14)); } + @Override @AfterMethod(alwaysRun = true) public void cleanUp() { debugTestRunner.terminateDebugSession(); diff --git a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/ControlFlowDebugTest.java b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/ControlFlowDebugTest.java index e69f778791b4..622e23148a20 100644 --- a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/ControlFlowDebugTest.java +++ b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/ControlFlowDebugTest.java @@ -43,6 +43,7 @@ public class ControlFlowDebugTest extends BaseTestCase { DebugTestRunner debugTestRunner; + @Override @BeforeClass public void setup() { String testProjectName = "control-flow-tests"; @@ -181,6 +182,7 @@ public void testControlFlowDebugScenarios() throws BallerinaTestException { debugTestRunner.assertVariable(asyncChildVariables, "result", "90", "int"); } + @Override @AfterMethod(alwaysRun = true) public void cleanUp() { debugTestRunner.terminateDebugSession(); diff --git a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/DebugInstructionTest.java b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/DebugInstructionTest.java index b967c66ded5b..041df59f7acb 100644 --- a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/DebugInstructionTest.java +++ b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/DebugInstructionTest.java @@ -40,6 +40,7 @@ public class DebugInstructionTest extends BaseTestCase { DebugTestRunner debugTestRunner; + @Override @BeforeClass public void setup() { } @@ -158,6 +159,7 @@ public void debugPauseTest() throws BallerinaTestException { || debugHitInfo.getLeft().equals(new BallerinaTestDebugPoint(mainFilePath, 21))); } + @Override @AfterMethod(alwaysRun = true) public void cleanUp() { debugTestRunner.terminateDebugSession(); diff --git a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/DebugOutputTest.java b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/DebugOutputTest.java index a3370ce0b4c7..5cce2c720b67 100644 --- a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/DebugOutputTest.java +++ b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/DebugOutputTest.java @@ -42,6 +42,7 @@ public class DebugOutputTest extends BaseTestCase { DebugTestRunner debugTestRunner; + @Override @BeforeClass public void setup() { String testProjectName = "debug-output-tests"; @@ -92,6 +93,7 @@ public void testProgramOutput() throws BallerinaTestException { "'localhost:")); } + @Override @AfterMethod(alwaysRun = true) public void cleanUp() { debugTestRunner.terminateDebugSession(); diff --git a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/DebugTerminationTest.java b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/DebugTerminationTest.java index 12752eec9074..61d51aafae08 100644 --- a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/DebugTerminationTest.java +++ b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/DebugTerminationTest.java @@ -38,6 +38,7 @@ public class DebugTerminationTest extends BaseTestCase { DebugTestRunner debugTestRunner; private boolean isTerminationFound; + @Override @BeforeClass public void setup() { String testProjectName = "debug-termination-tests"; @@ -97,6 +98,7 @@ public void testDebugTerminationContinue() throws BallerinaTestException { Assert.assertTrue(isTerminationFound); } + @Override @AfterMethod(alwaysRun = true) public void cleanUp() { debugTestRunner.terminateDebugSession(); diff --git a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/LangLibDebugTest.java b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/LangLibDebugTest.java index 40db2f058d63..ee355a65b187 100644 --- a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/LangLibDebugTest.java +++ b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/LangLibDebugTest.java @@ -43,6 +43,7 @@ public class LangLibDebugTest extends BaseTestCase { private DebugTestRunner debugTestRunner; + @Override @BeforeClass public void setup() { String testProjectName = "langlib-debug-tests"; @@ -103,6 +104,7 @@ public void testLangLibClassDebug() throws BallerinaTestException { } } + @Override @AfterMethod(alwaysRun = true) public void cleanUp() { debugTestRunner.terminateDebugSession(); diff --git a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/LanguageConstructDebugTest.java b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/LanguageConstructDebugTest.java index a93a1f22d87e..946ff53249a7 100644 --- a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/LanguageConstructDebugTest.java +++ b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/LanguageConstructDebugTest.java @@ -43,6 +43,7 @@ public class LanguageConstructDebugTest extends BaseTestCase { DebugTestRunner debugTestRunner; + @Override @BeforeClass public void setup() { String testProjectName = "language-construct-tests"; @@ -132,6 +133,7 @@ public void testWorkerScenarios() throws BallerinaTestException { Assert.assertEquals(debugHitInfo.getLeft(), debugTestRunner.testBreakpoints.get(1)); } + @Override @AfterMethod(alwaysRun = true) public void cleanUp() { debugTestRunner.terminateDebugSession(); diff --git a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/LogPointTest.java b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/LogPointTest.java index a21865e9c71f..56faf303782d 100644 --- a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/LogPointTest.java +++ b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/LogPointTest.java @@ -41,6 +41,7 @@ public class LogPointTest extends BaseTestCase { DebugTestRunner debugTestRunner; + @Override @BeforeClass public void setup() { String testProjectName = "logpoint-tests-1"; @@ -153,6 +154,7 @@ public void testLogPointValueChanges() throws BallerinaTestException { Assert.assertEquals(outputInfo.getRight().getCategory(), OutputEventArgumentsCategory.STDOUT); } + @Override @AfterMethod(alwaysRun = true) public void cleanUp() { debugTestRunner.terminateDebugSession(); diff --git a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/ModuleBreakpointTest.java b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/ModuleBreakpointTest.java index a8b60b1a9874..b545f72bc410 100644 --- a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/ModuleBreakpointTest.java +++ b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/ModuleBreakpointTest.java @@ -40,6 +40,7 @@ public class ModuleBreakpointTest extends BaseTestCase { DebugTestRunner debugTestRunner; + @Override @BeforeClass public void setup() { String testProjectName = "breakpoint-tests"; @@ -99,6 +100,7 @@ public void testMultipleBreakpointsInNonDefaultModuleTests() throws BallerinaTes Assert.assertEquals(debugHitInfo.getLeft(), debugTestRunner.testBreakpoints.get(1)); } + @Override @AfterMethod(alwaysRun = true) public void cleanUp() { debugTestRunner.terminateDebugSession(); diff --git a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/RecursiveDebugTest.java b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/RecursiveDebugTest.java index b82fae4e6e48..c9cb706cc6d2 100644 --- a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/RecursiveDebugTest.java +++ b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/RecursiveDebugTest.java @@ -37,6 +37,7 @@ public class RecursiveDebugTest extends BaseTestCase { DebugTestRunner debugTestRunner; + @Override @BeforeClass public void setup() { String testProjectName = "recursive-tests"; @@ -78,6 +79,7 @@ public void testStepRequestsOnRecursiveFunctions() throws BallerinaTestException // Assert.assertEquals(debugHitInfo.getLeft(), debugTestRunner.testBreakpoints.get(36)); } + @Override @AfterMethod(alwaysRun = true) public void cleanUp() { debugTestRunner.terminateDebugSession(); diff --git a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/completions/DebugCompletionTest.java b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/completions/DebugCompletionTest.java index c272f60a7ac6..e9d0ea4bddaa 100644 --- a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/completions/DebugCompletionTest.java +++ b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/completions/DebugCompletionTest.java @@ -42,6 +42,7 @@ public class DebugCompletionTest extends BaseTestCase { DebugTestRunner debugTestRunner; Map completions; + @Override @BeforeClass public void setup() { String testProjectName = "completions-tests"; @@ -142,6 +143,7 @@ private void assertCompletionSuggestions() throws BallerinaTestException { debugTestRunner.assertCompletions(completions, "sayHello()"); } + @Override @AfterClass(alwaysRun = true) public void cleanUp() { debugTestRunner.terminateDebugSession(); diff --git a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/evaluation/DependencyEvaluationTest.java b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/evaluation/DependencyEvaluationTest.java index 4350dc474086..33263dace74e 100644 --- a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/evaluation/DependencyEvaluationTest.java +++ b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/evaluation/DependencyEvaluationTest.java @@ -35,6 +35,7 @@ public class DependencyEvaluationTest extends BaseTestCase { protected DebugTestRunner debugTestRunner; + @Override @BeforeClass(alwaysRun = true) public void setup() throws BallerinaTestException { String testProjectName = "evaluation-tests-2"; @@ -66,6 +67,7 @@ protected void testEvaluationsOnLangLibs() throws BallerinaTestException { "select j select i", "int[3]", "array"); } + @Override @AfterClass(alwaysRun = true) public void cleanUp() { debugTestRunner.terminateDebugSession(); diff --git a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/evaluation/ExpressionEvaluationNegativeTest.java b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/evaluation/ExpressionEvaluationNegativeTest.java index 7a7ba97bb01a..2da4add849b2 100644 --- a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/evaluation/ExpressionEvaluationNegativeTest.java +++ b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/evaluation/ExpressionEvaluationNegativeTest.java @@ -35,6 +35,7 @@ */ public abstract class ExpressionEvaluationNegativeTest extends ExpressionEvaluationBaseTest { + @Override @BeforeClass(alwaysRun = true) public void setup() throws BallerinaTestException { prepareForEvaluation(); @@ -508,6 +509,7 @@ public void remoteCallActionEvaluationTest() throws BallerinaTestException { String.format(REMOTE_METHOD_NOT_FOUND.getString(), "undefinedFunction", "Child")); } + @Override @AfterClass(alwaysRun = true) public void cleanUp() { debugTestRunner.terminateDebugSession(); diff --git a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/evaluation/ExpressionEvaluationTest.java b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/evaluation/ExpressionEvaluationTest.java index 07a474a1b25d..89e968274cb9 100644 --- a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/evaluation/ExpressionEvaluationTest.java +++ b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/evaluation/ExpressionEvaluationTest.java @@ -28,6 +28,7 @@ */ public abstract class ExpressionEvaluationTest extends ExpressionEvaluationBaseTest { + @Override @BeforeClass(alwaysRun = true) public void setup() throws BallerinaTestException { prepareForEvaluation(); @@ -920,6 +921,7 @@ public void remoteCallActionEvaluationTest() throws BallerinaTestException { "168", "int"); } + @Override @AfterClass(alwaysRun = true) public void cleanUp() { debugTestRunner.terminateDebugSession(); diff --git a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/run/DebugEngageTest.java b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/run/DebugEngageTest.java index 5d362ab757ef..ed6c1d2ffc9c 100644 --- a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/run/DebugEngageTest.java +++ b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/run/DebugEngageTest.java @@ -41,6 +41,7 @@ public class DebugEngageTest extends BaseTestCase { DebugTestRunner debugTestRunner; + @Override @BeforeClass public void setup() { String testProjectName = "breakpoint-tests"; @@ -60,6 +61,7 @@ public void testNonBallerinaInputSource() throws BallerinaTestException { Assert.assertEquals(debugHitInfo.getLeft(), debugTestRunner.testBreakpoints.get(0)); } + @Override @AfterMethod(alwaysRun = true) public void cleanUp() { debugTestRunner.terminateDebugSession(); diff --git a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/run/MultiModuleRunDebugTest.java b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/run/MultiModuleRunDebugTest.java index 5b03b52cd9d0..97394acaceb1 100644 --- a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/run/MultiModuleRunDebugTest.java +++ b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/run/MultiModuleRunDebugTest.java @@ -41,6 +41,7 @@ public class MultiModuleRunDebugTest extends BaseTestCase { DebugTestRunner debugTestRunner; + @Override @BeforeClass public void setup() { String testProjectName = "breakpoint-tests"; @@ -124,6 +125,7 @@ public void testMultiModuleDebugScenarios() throws BallerinaTestException { Assert.assertEquals(debugHitInfo.getLeft(), debugTestRunner.testBreakpoints.get(3)); } + @Override @AfterMethod(alwaysRun = true) public void cleanUp() { debugTestRunner.terminateDebugSession(); diff --git a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/run/SingleBalFileRunDebugTest.java b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/run/SingleBalFileRunDebugTest.java index f0c35fc7ca5f..20b357ed50dc 100644 --- a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/run/SingleBalFileRunDebugTest.java +++ b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/run/SingleBalFileRunDebugTest.java @@ -39,6 +39,7 @@ public class SingleBalFileRunDebugTest extends BaseTestCase { DebugTestRunner debugTestRunner; + @Override @BeforeClass public void setup() { String testProjectName = "basic-project"; @@ -77,6 +78,7 @@ public void testSingleBalFileDebugScenarios() throws BallerinaTestException { Assert.assertEquals(debugHitInfo.getLeft(), new BallerinaTestDebugPoint(debugTestRunner.testEntryFilePath, 29)); } + @Override @AfterClass(alwaysRun = true) public void cleanUp() { debugTestRunner.terminateDebugSession(); diff --git a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/runinterminal/SingleFileRunInTerminalTest.java b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/runinterminal/SingleFileRunInTerminalTest.java index 6dd53fbf59e8..23a19d1985a5 100644 --- a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/runinterminal/SingleFileRunInTerminalTest.java +++ b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/runinterminal/SingleFileRunInTerminalTest.java @@ -33,6 +33,7 @@ public class SingleFileRunInTerminalTest extends BaseTestCase { DebugTestRunner debugTestRunner; boolean didRunInIntegratedTerminal; + @Override @BeforeMethod(alwaysRun = true) public void setup() throws BallerinaTestException { String testFolderName = "basic-project"; @@ -96,6 +97,7 @@ public void testLaunchWithoutConfig() throws BallerinaTestException { Assert.assertFalse(didRunInIntegratedTerminal); } + @Override @AfterMethod(alwaysRun = true) public void cleanUp() { debugTestRunner.terminateDebugSession(); diff --git a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/test/MultiModuleTestDebugTest.java b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/test/MultiModuleTestDebugTest.java index ab8cb0d5f3cb..24c1349d3848 100644 --- a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/test/MultiModuleTestDebugTest.java +++ b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/test/MultiModuleTestDebugTest.java @@ -46,6 +46,7 @@ public class MultiModuleTestDebugTest extends BaseTestCase { DebugTestRunner debugTestRunner; + @Override @BeforeClass public void setup() { String testProjectName = "breakpoint-tests"; @@ -121,6 +122,7 @@ public void testSelectiveTestsDebug() throws BallerinaTestException { Assert.assertEquals(debugHitInfo.getLeft(), debugTestRunner.testBreakpoints.get(2)); } + @Override @AfterMethod(alwaysRun = true) public void cleanUp() { debugTestRunner.terminateDebugSession(); diff --git a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/variables/VariableQueryTest.java b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/variables/VariableQueryTest.java index 1567fd912657..422fdb016d06 100644 --- a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/variables/VariableQueryTest.java +++ b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/variables/VariableQueryTest.java @@ -43,6 +43,7 @@ public class VariableQueryTest extends BaseTestCase { Map localVariables = new HashMap<>(); DebugTestRunner debugTestRunner; + @Override @BeforeClass public void setup() throws BallerinaTestException { String testProjectName = "variable-query-tests"; @@ -206,6 +207,7 @@ public void xmlVariableQueryTest() throws BallerinaTestException { debugTestRunner.assertVariable(xmlGrandChildrenVariables, "[0]", "900", "xml"); } + @Override @AfterClass(alwaysRun = true) public void cleanUp() { debugTestRunner.terminateDebugSession(); diff --git a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/variables/VariableVisibilityTest.java b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/variables/VariableVisibilityTest.java index 33b8147939fb..cf0c359c4ada 100644 --- a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/variables/VariableVisibilityTest.java +++ b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/adapter/variables/VariableVisibilityTest.java @@ -45,6 +45,7 @@ public class VariableVisibilityTest extends BaseTestCase { Map localVariables = new HashMap<>(); DebugTestRunner debugTestRunner; + @Override @BeforeClass public void setup() { String testProjectName = "variable-tests"; @@ -533,6 +534,7 @@ public void workerVariableVisibilityTest() throws BallerinaTestException { Assert.assertFalse(localVariables.containsKey("a")); } + @Override @AfterMethod(alwaysRun = true) public void cleanUp() { debugTestRunner.terminateDebugSession(); diff --git a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/remote/BallerinaRunRemoteDebugTest.java b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/remote/BallerinaRunRemoteDebugTest.java index c1863fac4a50..8ed12fc044a0 100644 --- a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/remote/BallerinaRunRemoteDebugTest.java +++ b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/remote/BallerinaRunRemoteDebugTest.java @@ -43,6 +43,7 @@ public class BallerinaRunRemoteDebugTest extends BaseTestCase { DebugTestRunner debugTestRunner; private static final String REMOTE_DEBUG_LISTENING = "Listening for transport dt_socket at address: "; + @Override @BeforeClass public void setup() throws BallerinaTestException { testProjectName = "basic-project"; @@ -102,6 +103,7 @@ public void testBalJarInDebugMode(String... debugOptions) throws BallerinaTestEx clientLeecher.waitForText(20000); } + @Override @AfterMethod(alwaysRun = true) public void cleanUp() { debugTestRunner.terminateDebugSession(); diff --git a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/remote/BallerinaTestRemoteDebugTest.java b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/remote/BallerinaTestRemoteDebugTest.java index 5bdba67c0aae..b4cda34da8ea 100644 --- a/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/remote/BallerinaTestRemoteDebugTest.java +++ b/tests/jballerina-debugger-integration-test/src/test/java/org/ballerinalang/debugger/test/remote/BallerinaTestRemoteDebugTest.java @@ -36,6 +36,7 @@ public class BallerinaTestRemoteDebugTest extends BaseTestCase { private BMainInstance balClient; DebugTestRunner debugTestRunner; + @Override @BeforeClass public void setup() throws BallerinaTestException { String testProjectName = "basic-project"; @@ -54,6 +55,7 @@ public void testSuspendOnBallerinaModuleTest() throws BallerinaTestException { clientLeecher.waitForText(20000); } + @Override @AfterMethod(alwaysRun = true) public void cleanUp() { debugTestRunner.terminateDebugSession(); diff --git a/tests/jballerina-integration-test/src/test/java/org/ballerinalang/test/bindgen/BindgenTestCase.java b/tests/jballerina-integration-test/src/test/java/org/ballerinalang/test/bindgen/BindgenTestCase.java index 8fe658299492..31e5ab228d24 100644 --- a/tests/jballerina-integration-test/src/test/java/org/ballerinalang/test/bindgen/BindgenTestCase.java +++ b/tests/jballerina-integration-test/src/test/java/org/ballerinalang/test/bindgen/BindgenTestCase.java @@ -29,6 +29,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.stream.Stream; import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; import static org.ballerinalang.test.context.LogLeecher.LeecherType.ERROR; @@ -89,7 +90,9 @@ public void bindgenTest() throws BallerinaTestException { } public void copyFolder(Path src, Path dest) throws IOException { - Files.walk(src).forEach(source -> copy(source, dest.resolve(src.relativize(source)))); + try (Stream paths = Files.walk(src)) { + paths.forEach(source -> copy(source, dest.resolve(src.relativize(source)))); + } } private void copy(Path source, Path dest) { diff --git a/tests/jballerina-integration-test/src/test/java/org/ballerinalang/test/packaging/PackerinaTestUtils.java b/tests/jballerina-integration-test/src/test/java/org/ballerinalang/test/packaging/PackerinaTestUtils.java index b8ba374f9a53..291e70d05e85 100644 --- a/tests/jballerina-integration-test/src/test/java/org/ballerinalang/test/packaging/PackerinaTestUtils.java +++ b/tests/jballerina-integration-test/src/test/java/org/ballerinalang/test/packaging/PackerinaTestUtils.java @@ -25,6 +25,7 @@ import java.util.Comparator; import java.util.HashMap; import java.util.Map; +import java.util.stream.Stream; import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; @@ -33,7 +34,10 @@ * * @since 0.982.0 */ -public class PackerinaTestUtils { +public final class PackerinaTestUtils { + + private PackerinaTestUtils() { + } /** * Delete files inside directories. @@ -45,15 +49,16 @@ public static void deleteFiles(Path dirPath) throws IOException { if (dirPath == null) { return; } - Files.walk(dirPath) - .sorted(Comparator.reverseOrder()) - .forEach(path -> { - try { - Files.delete(path); - } catch (IOException e) { - Assert.fail(e.getMessage(), e); - } - }); + try (Stream paths = Files.walk(dirPath)) { + paths.sorted(Comparator.reverseOrder()) + .forEach(path -> { + try { + Files.delete(path); + } catch (IOException e) { + Assert.fail(e.getMessage(), e); + } + }); + } } /** @@ -76,7 +81,9 @@ public static Map getEnvVariables() { * @throws IOException throw if there is any error occur while copying directories. */ public static void copyFolder(Path src, Path dest) throws IOException { - Files.walk(src).forEach(source -> copy(source, dest.resolve(src.relativize(source)))); + try (Stream paths = Files.walk(src)) { + paths.forEach(source -> copy(source, dest.resolve(src.relativize(source)))); + } } /** diff --git a/tests/jballerina-integration-test/src/test/java/org/ballerinalang/test/runtime/api/RuntimeAPICall.java b/tests/jballerina-integration-test/src/test/java/org/ballerinalang/test/runtime/api/RuntimeAPICall.java index a4bb7147658a..540192eedcf4 100644 --- a/tests/jballerina-integration-test/src/test/java/org/ballerinalang/test/runtime/api/RuntimeAPICall.java +++ b/tests/jballerina-integration-test/src/test/java/org/ballerinalang/test/runtime/api/RuntimeAPICall.java @@ -31,7 +31,10 @@ * * @since 2201.9.0 */ -public class RuntimeAPICall { +public final class RuntimeAPICall { + + private RuntimeAPICall() { + } public static void main(String[] args) { Module module = new Module("testorg", "function_invocation", "1"); diff --git a/tests/jballerina-integration-test/src/test/java/org/ballerinalang/test/runtime/api/RuntimeAPICallNegative.java b/tests/jballerina-integration-test/src/test/java/org/ballerinalang/test/runtime/api/RuntimeAPICallNegative.java index 57160c8376b9..7bd0608771a0 100644 --- a/tests/jballerina-integration-test/src/test/java/org/ballerinalang/test/runtime/api/RuntimeAPICallNegative.java +++ b/tests/jballerina-integration-test/src/test/java/org/ballerinalang/test/runtime/api/RuntimeAPICallNegative.java @@ -29,10 +29,13 @@ * * @since 2201.9.0 */ -public class RuntimeAPICallNegative { +public final class RuntimeAPICallNegative { private static final PrintStream out = System.out; + private RuntimeAPICallNegative() { + } + public static void main(String[] args) { Module module = new Module("testorg", "function_invocation", "1"); Runtime balRuntime = Runtime.from(module); diff --git a/tests/jballerina-integration-test/src/test/java/org/ballerinalang/test/semver/FileUtils.java b/tests/jballerina-integration-test/src/test/java/org/ballerinalang/test/semver/FileUtils.java index 3fedca54fb81..74c29c945d02 100644 --- a/tests/jballerina-integration-test/src/test/java/org/ballerinalang/test/semver/FileUtils.java +++ b/tests/jballerina-integration-test/src/test/java/org/ballerinalang/test/semver/FileUtils.java @@ -32,7 +32,10 @@ * * @since 2201.2.2 */ -public class FileUtils { +public final class FileUtils { + + private FileUtils() { + } /** * Delete files inside directories. diff --git a/tests/jballerina-integration-test/src/test/java/org/ballerinalang/test/testarina/TestarinaTestCase.java b/tests/jballerina-integration-test/src/test/java/org/ballerinalang/test/testarina/TestarinaTestCase.java index e217f10de5ce..fd8b9981cf29 100644 --- a/tests/jballerina-integration-test/src/test/java/org/ballerinalang/test/testarina/TestarinaTestCase.java +++ b/tests/jballerina-integration-test/src/test/java/org/ballerinalang/test/testarina/TestarinaTestCase.java @@ -29,6 +29,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.stream.Stream; import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; import static org.ballerinalang.test.packaging.PackerinaTestUtils.deleteFiles; @@ -71,7 +72,9 @@ public void testServiceTesting() throws Exception { public void copyFolder(Path src, Path dest) throws IOException { - Files.walk(src).forEach(source -> copy(source, dest.resolve(src.relativize(source)))); + try (Stream paths = Files.walk(src)) { + paths.forEach(source -> copy(source, dest.resolve(src.relativize(source)))); + } } private void copy(Path source, Path dest) { diff --git a/tests/jballerina-integration-test/src/test/java/org/ballerinalang/test/troubleshoot/StrandDumpTest.java b/tests/jballerina-integration-test/src/test/java/org/ballerinalang/test/troubleshoot/StrandDumpTest.java index 5f143179bf79..a8149b761ee6 100644 --- a/tests/jballerina-integration-test/src/test/java/org/ballerinalang/test/troubleshoot/StrandDumpTest.java +++ b/tests/jballerina-integration-test/src/test/java/org/ballerinalang/test/troubleshoot/StrandDumpTest.java @@ -37,7 +37,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.stream.Collectors; import java.util.stream.Stream; /** @@ -175,7 +174,7 @@ private static void populateLeechers(List leecherList, Path leecherF private static List readFileNonEmptyLines(Path filePath) throws BallerinaTestException { try (Stream fileLines = Files.lines(filePath)) { - return fileLines.filter(s -> !s.isBlank()).collect(Collectors.toList()); + return fileLines.filter(s -> !s.isBlank()).toList(); } catch (IOException e) { throw new BallerinaTestException("Failure to read from the file: " + filePath); } diff --git a/tests/jballerina-integration-test/src/test/java/org/ballerinalang/test/util/SQLDBUtils.java b/tests/jballerina-integration-test/src/test/java/org/ballerinalang/test/util/SQLDBUtils.java index cc8f51def2f7..6fc74658293c 100644 --- a/tests/jballerina-integration-test/src/test/java/org/ballerinalang/test/util/SQLDBUtils.java +++ b/tests/jballerina-integration-test/src/test/java/org/ballerinalang/test/util/SQLDBUtils.java @@ -36,11 +36,14 @@ /** * Util class for SQL DB Tests. */ -public class SQLDBUtils { +public final class SQLDBUtils { public static final String DB_DIRECTORY = System.getProperty("libdir") + File.separator + "tempdb" + File.separator; private static final Logger LOG = LoggerFactory.getLogger(SQLDBUtils.class); + private SQLDBUtils() { + } + /** * Delete all the files and sub directories which matches given prefix in a given directory. * @@ -144,6 +147,7 @@ public FileBasedTestDatabase(DBType dbType, String databaseScript, String dbDire initDatabase(jdbcUrl, username, password, databaseScript); } + @Override public void stop() { BFileUtil.deleteDirectory(new File(this.dbDirectory)); } diff --git a/tests/jballerina-semtype-test/src/test/java/io/ballerina/test/utils/Constants.java b/tests/jballerina-semtype-test/src/test/java/io/ballerina/test/utils/Constants.java index e11df2519f05..765fd3739307 100644 --- a/tests/jballerina-semtype-test/src/test/java/io/ballerina/test/utils/Constants.java +++ b/tests/jballerina-semtype-test/src/test/java/io/ballerina/test/utils/Constants.java @@ -22,9 +22,13 @@ * * @since 2.0.0 */ -public class Constants { +public final class Constants { + public static final String SUBTYPE_SYMBOL = "<:"; public static final String COMMENT = "// "; public static final String FAILING_FILE = "-f.bal"; public static final String DISABLED_FILE = "-d.bal"; + + private Constants() { + } } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/runtime/api/tests/Async.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/runtime/api/tests/Async.java index 6b7d0deada77..515a6b499d90 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/runtime/api/tests/Async.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/runtime/api/tests/Async.java @@ -37,7 +37,10 @@ * * @since 2.0.0 */ -public class Async { +public final class Async { + + private Async() { + } public static long getFieldValWithNoArgs(Environment env, BObject obj) { invokeMethodAsyncSequentially(env, obj, "getFieldValWithNoArgs"); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/runtime/api/tests/Enums.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/runtime/api/tests/Enums.java index ec24dc350e0e..1dc38289ba57 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/runtime/api/tests/Enums.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/runtime/api/tests/Enums.java @@ -47,10 +47,13 @@ * * @since 2201.1.0 */ -public class Enums { +public final class Enums { private static final Module enumModule = new Module("testorg", "values.enum", "1"); + private Enums() { + } + public static BArray createEnumArray(BString enumName) { List memberTypes = new ArrayList<>(2); Set valuesSpace = new LinkedHashSet<>(); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/runtime/api/tests/Environments.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/runtime/api/tests/Environments.java index 0f5167bff193..cd048d6c0b46 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/runtime/api/tests/Environments.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/runtime/api/tests/Environments.java @@ -32,7 +32,10 @@ * * @since 2201.5.0 */ -public class Environments { +public final class Environments { + + private Environments() { + } public static void callClientGetGreeting(Environment env, long p1, BString p2, boolean pn, BArray path, long t1, BString t2, boolean tn) { diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/runtime/api/tests/Errors.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/runtime/api/tests/Errors.java index 024a98770200..d3984351e0f8 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/runtime/api/tests/Errors.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/runtime/api/tests/Errors.java @@ -43,10 +43,13 @@ * * @since 2.0.0 */ -public class Errors { +public final class Errors { private static Module errorModule = new Module("testorg", "errors.error_utils", "1"); + private Errors() { + } + public static BError getError(BString errorName) { BMap errorDetails = ValueCreator.createMapValue(); errorDetails.put(StringUtils.fromString("cause"), StringUtils.fromString("Person age cannot be negative")); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/runtime/api/tests/JsonValues.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/runtime/api/tests/JsonValues.java index 0d602ce171a5..c79f1193afb0 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/runtime/api/tests/JsonValues.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/runtime/api/tests/JsonValues.java @@ -37,11 +37,14 @@ import static io.ballerina.runtime.api.utils.JsonUtils.convertJSONToRecord; /** - * This class contains a set of utility methods required for @{@link io.ballerina.runtime.api.utils.JsonUtils} testing. + * This class contains a set of utility methods required for @{@link JsonUtils} testing. * * @since 2201.0.0 */ -public class JsonValues { +public final class JsonValues { + + private JsonValues() { + } public static BMap testConvertJSONToRecord(Object record, BTypedesc t) throws BError { Type describingType = t.getDescribingType(); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/runtime/api/tests/Stream.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/runtime/api/tests/Stream.java index e3b98c85e157..a64829486840 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/runtime/api/tests/Stream.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/runtime/api/tests/Stream.java @@ -32,7 +32,10 @@ * * @since 2201.9.0 */ -public class Stream { +public final class Stream { + + private Stream() { + } public static Object convertStringToType(BString s, BTypedesc t) { String str = s.getValue(); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/runtime/api/tests/TypeReference.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/runtime/api/tests/TypeReference.java index 146badd90dce..7062413ebe9b 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/runtime/api/tests/TypeReference.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/runtime/api/tests/TypeReference.java @@ -57,7 +57,10 @@ * * @since 2201.4.0 */ -public class TypeReference { +public final class TypeReference { + + private TypeReference() { + } public static Boolean validateGetDetailType(BTypedesc typedesc) { BErrorType errorType = (BErrorType) TypeUtils.getImpliedType(typedesc.getDescribingType()); @@ -140,7 +143,7 @@ public static Boolean validateStreamType(BTypedesc value1, BStream value2) { return true; } - public static Boolean validateTableType(BTypedesc typedesc, TableValue tableValue) { + public static Boolean validateTableType(BTypedesc typedesc, TableValue tableValue) { BTableType tableType = (BTableType) TypeUtils.getImpliedType(typedesc.getDescribingType()); if (tableType.getConstrainedType().getTag() != TypeTags.TYPE_REFERENCED_TYPE_TAG || tableValue.getKeyType().getTag() != TypeTags.TYPE_REFERENCED_TYPE_TAG || @@ -238,7 +241,7 @@ public static Boolean validateBArray(BArray value1, BArray value2) { return true; } - public static Boolean validateBMap(BMap value1, BMap value2) { + public static Boolean validateBMap(BMap value1, BMap value2) { if (value1.getType().getTag() != TypeTags.TYPE_REFERENCED_TYPE_TAG || value2.getType().getTag() != TypeTags.TYPE_REFERENCED_TYPE_TAG) { throw ErrorCreator.createError(StringUtils.fromString("BMap getType API provided a non type " + @@ -255,7 +258,7 @@ public static Boolean validateBError(BError value) { return true; } - public static Boolean validateBFunctionPointer(BFunctionPointer value) { + public static Boolean validateBFunctionPointer(BFunctionPointer value) { if (value.getType().getTag() != TypeTags.TYPE_REFERENCED_TYPE_TAG) { throw ErrorCreator.createError(StringUtils.fromString("Function Pointer getType API provided a non " + "type reference type.")); @@ -283,7 +286,7 @@ public static boolean validateUnionTypeNarrowing(Object value, BTypedesc typedes return true; } - public static boolean validateTableKeys(BTable table) { + public static boolean validateTableKeys(BTable table) { if (table.getType().getTag() != TypeTags.TYPE_REFERENCED_TYPE_TAG || table.size() != 1 || table.getKeyType().getTag() != TypeTags.TUPLE_TAG) { throw ErrorCreator.createError(StringUtils.fromString("Table keys does not provide type-reference " + diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/runtime/api/tests/Values.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/runtime/api/tests/Values.java index fd2725a3f154..0a4eb03403e9 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/runtime/api/tests/Values.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/runtime/api/tests/Values.java @@ -83,7 +83,7 @@ * * @since 2.0.0 */ -public class Values { +public final class Values { private static final Module objectModule = new Module("testorg", "values.objects", "1"); private static final Module recordModule = new Module("testorg", "values.records", "1"); @@ -93,6 +93,9 @@ public class Values { private static final BError constraintError = ErrorCreator.createError(StringUtils.fromString("Validation failed for 'minValue' constraint(s).")); + private Values() { + } + public static BMap getRecord(BString recordName) { HashMap address = new HashMap<>(); address.put("city", StringUtils.fromString("Nugegoda")); @@ -182,7 +185,7 @@ public static BString getFunctionString(BObject object, BString methodName) { return StringUtils.fromString(""); } - public static BString getParamTypesString(BFunctionPointer func) { + public static BString getParamTypesString(BFunctionPointer func) { BFunctionType funcType = (BFunctionType) func.getType(); StringBuilder sb = new StringBuilder(); for (Type type : funcType.getParameterTypes()) { @@ -329,7 +332,7 @@ public static Object validate(Object value, BTypedesc typedesc) { BMap annotations = ((AnnotatableType) describingType).getAnnotations(); if (annotations.containsKey(intAnnotation)) { Object annotValue = annotations.get(intAnnotation); - Long minValue = (Long) ((BMap) annotValue).get(StringUtils.fromString("minValue")); + Long minValue = (Long) ((BMap) annotValue).get(StringUtils.fromString("minValue")); if (((Long) value) >= minValue) { return value; } @@ -339,11 +342,12 @@ public static Object validate(Object value, BTypedesc typedesc) { public static Object validateRecord(Object value, BTypedesc typedesc) { Type describingType = typedesc.getDescribingType(); - Long age = ((BMap) value).getIntValue(StringUtils.fromString("age")); + Long age = ((BMap) value).getIntValue(StringUtils.fromString("age")); for (Field field : ((BRecordType) describingType).getFields().values()) { BMap annotations = ((AnnotatableType) field.getFieldType()).getAnnotations(); if (annotations.containsKey(intAnnotation)) { - Long minValue = (Long) ((BMap) annotations.get(intAnnotation)).get(StringUtils.fromString("minValue")); + Long minValue = (Long) ((BMap) annotations.get(intAnnotation)) + .get(StringUtils.fromString("minValue")); if (age < minValue) { return constraintError; } @@ -357,7 +361,7 @@ public static Object validateArrayElements(Object value, BTypedesc typedesc) { BMap annotations = ((AnnotatableType) describingType).getAnnotations(); if (annotations.containsKey(intAnnotation)) { Object annotValue = annotations.get(intAnnotation); - Long minValue = (Long) ((BMap) annotValue).get(StringUtils.fromString("minValue")); + Long minValue = (Long) ((BMap) annotValue).get(StringUtils.fromString("minValue")); for (Object element : ((BArray) value).getValues()) { if (((Long) element) >= minValue) { return value; @@ -373,7 +377,7 @@ public static Object validateArrayConstraint(Object value, BTypedesc typedesc) { BString annotKey = StringUtils.fromString("testorg/types.typeref:1:Array"); if (annotations.containsKey(annotKey)) { Object annotValue = annotations.get(annotKey); - Long maxLength = (Long) ((BMap) annotValue).get(StringUtils.fromString("maxLength")); + Long maxLength = (Long) ((BMap) annotValue).get(StringUtils.fromString("maxLength")); BArray array = (BArray) value; if (maxLength < array.getLength()) { return ErrorCreator.createError( @@ -386,7 +390,7 @@ public static Object validateArrayConstraint(Object value, BTypedesc typedesc) { return constraintError; } annotValue = annotations.get(intAnnotation); - Long minValue = (Long) ((BMap) annotValue).get(StringUtils.fromString("minValue")); + Long minValue = (Long) ((BMap) annotValue).get(StringUtils.fromString("minValue")); for (int i = 0; i < array.getLength(); i++) { if (((Long) array.get(i)) < minValue) { return constraintError; @@ -396,7 +400,7 @@ public static Object validateArrayConstraint(Object value, BTypedesc typedesc) { return value; } - public static Object validateFunctionParameterExtern(BFunctionPointer fpValue) { + public static Object validateFunctionParameterExtern(BFunctionPointer fpValue) { return validateFunctionType((FunctionType) fpValue.getType()); } @@ -470,10 +474,10 @@ public static Boolean checkInlineRecordAnnotations(BTypedesc typedesc, BTypedesc throw ErrorCreator.createError(StringUtils.fromString("Annotation is not available.")); } BString annotKey = StringUtils.fromString("testorg/types.typeref:1:String"); - return TypeChecker.checkIsType(((BMap) annotation).get(annotKey), constraint.getDescribingType()); + return TypeChecker.checkIsType(((BMap) annotation).get(annotKey), constraint.getDescribingType()); } - public static BString getParameterName(BFunctionPointer fpValue) { + public static BString getParameterName(BFunctionPointer fpValue) { Parameter parameter = ((BFunctionType) fpValue.getType()).getParameters()[0]; return StringUtils.fromString(parameter.name); } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/servicetests/ServiceAnnotValue.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/servicetests/ServiceAnnotValue.java index 5f4cb4cc75fd..8b5a90b8c902 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/servicetests/ServiceAnnotValue.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/servicetests/ServiceAnnotValue.java @@ -31,19 +31,23 @@ * * @since 2.0.0 */ -public class ServiceAnnotValue { - static HashMap serviceAnnotMap = new HashMap(); +public final class ServiceAnnotValue { + + static HashMap> serviceAnnotMap = new HashMap<>(); private static BObject listener; private static boolean started; private static int serviceCount = 0; + private ServiceAnnotValue() { + } + public static Object attach(BObject servObj, Object name) { // get service annotation and add it to the hash map BServiceType serviceType = (BServiceType) servObj.getType(); try { Field annotations = BAnnotatableType.class.getDeclaredField("annotations"); annotations.setAccessible(true); - MapValue annotationMap = (MapValue) annotations.get(serviceType); + MapValue annotationMap = (MapValue) annotations.get(serviceType); serviceCount++; serviceAnnotMap.put(serviceCount, annotationMap); } catch (NoSuchFieldException | IllegalAccessException e) { @@ -78,7 +82,7 @@ public static int getServiceCount() { return serviceCount; } - public static BMap getAnnotationsAtServiceAttach(int serviceNum) { + public static BMap getAnnotationsAtServiceAttach(int serviceNum) { return serviceAnnotMap.get(serviceNum); } } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/servicetests/ServiceValue.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/servicetests/ServiceValue.java index 73d272548cf0..e497230cd829 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/servicetests/ServiceValue.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/servicetests/ServiceValue.java @@ -50,12 +50,16 @@ * * @since 2.0.0 */ -public class ServiceValue { +public final class ServiceValue { + private static BObject service; private static BObject listener; private static boolean started; private static String[] names; - private static MapValue annotationMap; // captured at attach method + private static MapValue annotationMap; // captured at attach method + + private ServiceValue() { + } public static BFuture callMethod(Environment env, BObject l, BString name) { @@ -118,7 +122,7 @@ public static Object attach(BObject servObj, Object name) { Field annotations = BAnnotatableType.class.getDeclaredField("annotations"); annotations.setAccessible(true); Object annotationMap = annotations.get(serviceType); - ServiceValue.annotationMap = (MapValue) annotationMap; + ServiceValue.annotationMap = (MapValue) annotationMap; } catch (NoSuchFieldException | IllegalAccessException e) { throw new AssertionError(); } @@ -141,7 +145,7 @@ public static void reset() { ServiceValue.listener = null; ServiceValue.started = false; ServiceValue.names = new String[0]; - ServiceValue.annotationMap = new MapValueImpl(); + ServiceValue.annotationMap = new MapValueImpl<>(); } public static BObject getListener() { @@ -176,7 +180,7 @@ public static BArray getServicePath() { return new ArrayValueImpl(names, false); } - public static BMap getAnnotationsAtServiceAttach() { + public static BMap getAnnotationsAtServiceAttach() { return ServiceValue.annotationMap; } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/tests/Accumulator.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/tests/Accumulator.java index a029b6a464c9..84f1610f4090 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/tests/Accumulator.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/tests/Accumulator.java @@ -35,7 +35,10 @@ * * @since 1.0.0 */ -public class Accumulator { +public final class Accumulator { + + private Accumulator() { + } public static void accumulate(Environment env, ObjectValue intFunction, long from, long to) { Runtime runtime = env.getRuntime(); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/tests/Annotations.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/tests/Annotations.java index e91bd6e8877a..34bd07abf091 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/tests/Annotations.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/tests/Annotations.java @@ -25,7 +25,10 @@ * * @since 2.0.0 */ -public class Annotations { +public final class Annotations { + + private Annotations() { + } public static BString externalFunction(boolean b) { if (b) { diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/tests/AsyncInterop.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/tests/AsyncInterop.java index 13754a5f185c..4e8b44733c91 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/tests/AsyncInterop.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/tests/AsyncInterop.java @@ -32,7 +32,10 @@ * * @since 1.0.0 */ -public class AsyncInterop { +public final class AsyncInterop { + + private AsyncInterop() { + } public static int countSlowly() { CompletableFuture future = AsyncUtils.markAsync(); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/tests/MockListener.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/tests/MockListener.java index c33d01036773..766ca8f58ebe 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/tests/MockListener.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/tests/MockListener.java @@ -30,11 +30,14 @@ /** * A mock listener for testing services. It can be used to invoke a resource in the service. */ -public class MockListener { +public final class MockListener { private static BObject service; private static BError err; + private MockListener() { + } + public static Object attach(BObject servObj) { service = servObj; return null; diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/tests/StaticMethods.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/tests/StaticMethods.java index d2373e574212..dbbc467a1bd0 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/tests/StaticMethods.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/tests/StaticMethods.java @@ -79,7 +79,7 @@ * * @since 1.0.0 */ -public class StaticMethods { +public final class StaticMethods { private static final BArrayType intArrayType = new BArrayType(PredefinedTypes.TYPE_INT); private static final BArrayType jsonArrayType = new BArrayType(PredefinedTypes.TYPE_JSON); @@ -131,7 +131,7 @@ public static BDecimal getNullInsteadOfBDecimal() { } // This scenario is for map value to be passed to interop and return array value. - public static ArrayValue getArrayValueFromMap(BString key, MapValue mapValue) { + public static ArrayValue getArrayValueFromMap(BString key, MapValue mapValue) { ArrayValue arrayValue = (ArrayValue) ValueCreator.createArrayValue(intArrayType); arrayValue.add(0, 1); long fromMap = (long) mapValue.get(key); @@ -140,7 +140,7 @@ public static ArrayValue getArrayValueFromMap(BString key, MapValue mapValue) { } public static BMap acceptRefTypesAndReturnMap(ObjectValue a, ArrayValue b, Object c, - ErrorValue d, Object e, Object f, MapValue g) { + ErrorValue d, Object e, Object f, MapValue g) { BMap mapValue = ValueCreator.createMapValue(); mapValue.put(StringUtils.fromString("a"), a); mapValue.put(StringUtils.fromString("b"), b); @@ -161,33 +161,23 @@ public static BError acceptStringErrorReturn(BString msg) { } public static Object acceptIntUnionReturn(int flag) { - switch (flag) { - case 1: - return 25; - case 2: - return StringUtils.fromString("sample value return"); - case 3: - return 54.88; - case 4: - return null; - case 5: - return ValueCreator.createMapValue(TypeCreator.createMapType(PredefinedTypes.TYPE_ANYDATA)); - default: - return true; - } + return switch (flag) { + case 1 -> 25; + case 2 -> StringUtils.fromString("sample value return"); + case 3 -> 54.88; + case 4 -> null; + case 5 -> ValueCreator.createMapValue(TypeCreator.createMapType(PredefinedTypes.TYPE_ANYDATA)); + default -> true; + }; } public static Object acceptIntAnyReturn(int flag) { - switch (flag) { - case 1: - return 25; - case 2: - return "sample value return"; - case 3: - return 54.88; - default: - return true; - } + return switch (flag) { + case 1 -> 25; + case 2 -> "sample value return"; + case 3 -> 54.88; + default -> true; + }; } public static Object acceptNothingInvalidAnydataReturn() { @@ -205,7 +195,7 @@ public static int acceptObjectAndReturnField(ObjectValue p) { return ((Long) p.get(StringUtils.fromString("age"))).intValue(); } - public static MapValue acceptRecordAndRecordReturn(MapValue e, BString newVal) { + public static MapValue acceptRecordAndRecordReturn(MapValue e, BString newVal) { e.put(StringUtils.fromString("name"), newVal); return e; } @@ -284,7 +274,7 @@ public static int[] acceptIntReturnIntArrayThrowsCheckedException(long a) throws } } - public static ArrayValue getArrayValueFromMapWhichThrowsCheckedException(BString key, MapValue mapValue) + public static ArrayValue getArrayValueFromMapWhichThrowsCheckedException(BString key, MapValue mapValue) throws JavaInteropTestCheckedException { ArrayValue arrayValue = (ArrayValue) ValueCreator.createArrayValue(intArrayType); arrayValue.add(0, 1); @@ -297,7 +287,7 @@ public static BMap acceptRefTypesAndReturnMapWhichThrowsChecked ArrayValue b, Object c, ErrorValue d, Object e, Object f, - MapValue g) + MapValue g) throws JavaInteropTestCheckedException { BMap mapValue = ValueCreator.createMapValue(); mapValue.put(StringUtils.fromString("a"), a); @@ -343,16 +333,12 @@ public static long acceptIntErrorUnionReturnWhichThrowsUncheckedException() thro public static Object acceptIntUnionReturnWhichThrowsCheckedException(int flag) throws JavaInteropTestCheckedException { - switch (flag) { - case 1: - return 25; - case 2: - return "sample value return"; - case 3: - return 54.88; - default: - return true; - } + return switch (flag) { + case 1 -> 25; + case 2 -> "sample value return"; + case 3 -> 54.88; + default -> true; + }; } public static ObjectValue acceptObjectAndObjectReturnWhichThrowsCheckedException(ObjectValue p, int newVal) @@ -361,21 +347,21 @@ public static ObjectValue acceptObjectAndObjectReturnWhichThrowsCheckedException return p; } - public static MapValue acceptRecordAndRecordReturnWhichThrowsCheckedException( + public static MapValue acceptRecordAndRecordReturnWhichThrowsCheckedException( MapValue e, BString newVal) throws JavaInteropTestCheckedException { e.put(StringUtils.fromString("name"), newVal); return e; } - public static BMap getMapOrError(BString swaggerFilePath, MapValue apiDef) + public static BMap getMapOrError(BString swaggerFilePath, MapValue apiDef) throws JavaInteropTestCheckedException { BString finalBasePath = StringUtils.fromString("basePath"); AtomicLong runCount = new AtomicLong(0L); ArrayValue arrayValue = new ArrayValueImpl(new BArrayType(ValueCreator.createRecordValue(new Module( "", "."), "ResourceDefinition").getType())); - BMap apiDefinitions = ValueCreator.createRecordValue(new Module("", + BMap apiDefinitions = ValueCreator.createRecordValue(new Module("", "."), "ApiDefinition"); - BMap resource = ValueCreator.createRecordValue(new Module("", + BMap resource = ValueCreator.createRecordValue(new Module("", "."), "ResourceDefinition"); resource.put(StringUtils.fromString("path"), finalBasePath); resource.put(StringUtils.fromString("method"), StringUtils.fromString("Method string")); @@ -515,7 +501,7 @@ public static ArrayValue getValues(MapValue intMap, MapValue(2) {{ add(PredefinedTypes.TYPE_INT); add(PredefinedTypes.TYPE_STRING); }}), length, true), entries); @@ -529,7 +515,7 @@ public static ObjectValue echoObject(ObjectValue obj) { return obj; } - public static boolean echoImmutableRecordField(MapValue value, BString key) { + public static boolean echoImmutableRecordField(MapValue value, BString key) { return value.getBooleanValue(key); } @@ -605,17 +591,14 @@ private static void sleep() { public static Object acceptAndReturnReadOnly(Object value) { Type type = TypeUtils.getImpliedType(TypeChecker.getType(value)); - switch (type.getTag()) { - case TypeTags.INT_TAG: - return 100L; - case TypeTags.ARRAY_TAG: - case TypeTags.OBJECT_TYPE_TAG: - return value; - case TypeTags.RECORD_TYPE_TAG: - case TypeTags.MAP_TAG: - return ((MapValue) value).get(StringUtils.fromString("first")); - } - return StringUtils.fromString("other"); + return switch (type.getTag()) { + case TypeTags.INT_TAG -> 100L; + case TypeTags.ARRAY_TAG, + TypeTags.OBJECT_TYPE_TAG -> value; + case TypeTags.RECORD_TYPE_TAG, + TypeTags.MAP_TAG -> ((MapValue) value).get(StringUtils.fromString("first")); + default -> StringUtils.fromString("other"); + }; } public static void getNilAsReadOnly() { @@ -645,7 +628,7 @@ public static BError getErrorAsReadOnly(BError e) { return e; } - public static FPValue getFunctionPointerAsReadOnly(FPValue func) { + public static FPValue getFunctionPointerAsReadOnly(FPValue func) { return func; } @@ -669,11 +652,11 @@ public static ArrayValue getListAsReadOnly(ArrayValue list) { return list; } - public static MapValue getMappingAsReadOnly(MapValue mp) { + public static MapValue getMappingAsReadOnly(MapValue mp) { return mp; } - public static TableValue getTableAsReadOnly(TableValue tb) { + public static TableValue getTableAsReadOnly(TableValue tb) { return tb; } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/tests/Timer.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/tests/Timer.java index 23396c56f264..dc31fb7be535 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/tests/Timer.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/tests/Timer.java @@ -30,7 +30,10 @@ * * @since 1.0.0 */ -public class Timer { +public final class Timer { + + private Timer() { + } public static void startTimer(Environment env, int interval, int count, ObjectValue object) { Runtime runtime = env.getRuntime(); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/tests/VariableReturnType.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/tests/VariableReturnType.java index e1a2a8686c51..962888ab48c7 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/tests/VariableReturnType.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/nativeimpl/jvm/tests/VariableReturnType.java @@ -75,7 +75,7 @@ * * @since 2.0.0-preview1 */ -public class VariableReturnType { +public final class VariableReturnType { private static final BString NAME = new BmpStringValue("name"); private static final BString AGE = new BmpStringValue("age"); @@ -85,6 +85,9 @@ public class VariableReturnType { private static final BString JANE_DOE = new BmpStringValue("Jane Doe"); private static final BString SOFTWARE_ENGINEER = new BmpStringValue("Software Engineer"); + private VariableReturnType() { + } + public static Object echo(BValue value, BTypedesc td) { return value; } @@ -97,11 +100,11 @@ public static BStream getStream(BStream value, BTypedesc td) { return value; } - public static TableValue getTable(TableValue value, BTypedesc td) { + public static TableValue getTable(TableValue value, BTypedesc td) { return value; } - public static BFunctionPointer getFunction(BFunctionPointer fp, BTypedesc param, BTypedesc ret) { + public static BFunctionPointer getFunction(BFunctionPointer fp, BTypedesc param, BTypedesc ret) { return fp; } @@ -132,20 +135,20 @@ public static Object getObjectValue(ObjectValue objectValue, BTypedesc td) { return getValue(td.getDescribingType()); } - public static MapValue query(BString query, BTypedesc typedesc) { + public static MapValue query(BString query, BTypedesc typedesc) { Type type = typedesc.getDescribingType(); - MapValue map; + MapValue map; if (type.getTag() == INT_TAG) { - map = new MapValueImpl(new BMapType(type)); + map = new MapValueImpl<>(new BMapType(type)); map.put(new BmpStringValue("one"), 10); map.put(new BmpStringValue("two"), 20); } else if (type.getTag() == STRING_TAG) { - map = new MapValueImpl(new BMapType(type)); + map = new MapValueImpl<>(new BMapType(type)); map.put(NAME, new BmpStringValue("Pubudu")); map.put(CITY, new BmpStringValue("Panadura")); } else { - map = new MapValueImpl(new BMapType(PredefinedTypes.TYPE_ANY)); + map = new MapValueImpl<>(new BMapType(PredefinedTypes.TYPE_ANY)); } return map; @@ -191,9 +194,9 @@ public static ArrayValue getTupleWithRestDesc(BTypedesc td1, BTypedesc td2, BTyp return arr; } - public static MapValue getRecord(BTypedesc td) { + public static MapValue getRecord(BTypedesc td) { BRecordType recType = (BRecordType) td.getDescribingType(); - MapValueImpl person = new MapValueImpl(recType); + MapValueImpl person = new MapValueImpl<>(recType); if (recType.getName().equals("Person")) { person.put(NAME, JOHN_DOE); @@ -222,7 +225,7 @@ public static Object getVariedUnion(long x, BTypedesc td1, BTypedesc td2) { } } - MapValueImpl rec = new MapValueImpl(type2); + MapValueImpl rec = new MapValueImpl<>(type2); if (type2.getName().equals("Person")) { rec.put(NAME, JOHN_DOE); rec.put(AGE, 20); @@ -274,7 +277,7 @@ private static Object getValue(Type type) { return 32; case RECORD_TYPE_TAG: BRecordType recType = (BRecordType) type; - MapValueImpl person = new MapValueImpl(recType); + MapValueImpl person = new MapValueImpl<>(recType); if (recType.getName().equals("Person")) { person.put(NAME, JOHN_DOE); @@ -295,13 +298,11 @@ private static Object getValue(Type type) { public static Object get(ObjectValue objectValue, BTypedesc td) { Type describingType = td.getDescribingType(); - switch (describingType.getTag()) { - case INT_TAG: - return objectValue.getIntValue(StringUtils.fromString("a")); - case STRING_TAG: - return objectValue.getStringValue(StringUtils.fromString("b")); - } - return objectValue.get(StringUtils.fromString("c")); + return switch (describingType.getTag()) { + case INT_TAG -> objectValue.getIntValue(StringUtils.fromString("a")); + case STRING_TAG -> objectValue.getStringValue(StringUtils.fromString("b")); + default -> objectValue.get(StringUtils.fromString("c")); + }; } public static Object getIntFieldOrDefault(ObjectValue objectValue, BTypedesc td) { @@ -357,8 +358,8 @@ public static Object getAnnotationValue2(Object value, BTypedesc typedesc, BStri BMap annotations = ((AnnotatableType) describingType).getAnnotations(); if (annotations.containsKey(annotationName)) { Object annotValue = annotations.get(annotationName); - Long minValue = (Long) ((BMap) annotValue).get(StringUtils.fromString("minValue")); - Long maxValue = (Long) ((BMap) annotValue).get(StringUtils.fromString("maxValue")); + Long minValue = (Long) ((BMap) annotValue).get(StringUtils.fromString("minValue")); + Long maxValue = (Long) ((BMap) annotValue).get(StringUtils.fromString("maxValue")); if (minValue == min && maxValue == max) { return value; } @@ -393,7 +394,7 @@ public static Object getWithMultipleTypedescs(long i, BTypedesc j, BTypedesc k, return true; } - public static Object clientPost(BObject client, BTypedesc targetType, MapValue options) { + public static Object clientPost(BObject client, BTypedesc targetType, MapValue options) { BString mediaType = Optional.ofNullable(options.getStringValue(StringUtils.fromString("mediaType"))) .orElse(StringUtils.fromString("")); @@ -408,7 +409,7 @@ public static Object clientPost(BObject client, BTypedesc targetType, MapValue o return mediaType.length() + header.length(); } - public static Object calculate(BObject client, long i, BTypedesc targetType, MapValue options) { + public static Object calculate(BObject client, long i, BTypedesc targetType, MapValue options) { BString mediaType = Optional.ofNullable(options.getStringValue(StringUtils.fromString("mediaType"))) .orElse(StringUtils.fromString("")); @@ -516,7 +517,7 @@ public static Object getValueWithUnionReturnType(Object val, BTypedesc td) { return !((boolean) val); } - public static BFunctionPointer getFunctionWithAnyFunctionParamType(BFunctionPointer x, BTypedesc td) { + public static BFunctionPointer getFunctionWithAnyFunctionParamType(BFunctionPointer x, BTypedesc td) { Assert.assertEquals(td.getDescribingType().getTag(), INT_TAG); return x; } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/ParserTestRunner.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/ParserTestRunner.java index 315052a4f46c..34b1d65408c9 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/ParserTestRunner.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/ParserTestRunner.java @@ -25,6 +25,7 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashSet; +import java.util.stream.Stream; /** * Test running parser tests through compiler phases. @@ -58,9 +59,8 @@ public HashSet skipList() { @DataProvider(name = "parser-test-file-provider") public Object[][] dataProvider() { HashSet skippedTests = skipList(); - try { - return Files.walk(parserDir.resolve("src").resolve("test").resolve("resources")) - .filter(path -> { + try (Stream paths = Files.walk(parserDir.resolve("src").resolve("test").resolve("resources"))) { + return paths.filter(path -> { File file = path.toFile(); return file.isFile() && file.getName().endsWith(".bal") && !skippedTests.contains(file.getName()); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/annotations/AnnotationAttachmentTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/annotations/AnnotationAttachmentTest.java index 18c73eaa13ca..466fb2e4c2a9 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/annotations/AnnotationAttachmentTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/annotations/AnnotationAttachmentTest.java @@ -61,7 +61,6 @@ import java.util.List; import java.util.Objects; import java.util.Optional; -import java.util.stream.Collectors; /** * Class to test annotation attachments. @@ -459,7 +458,7 @@ public void testAnnotWithEmptyMapConstructorOnService() { .get().getAnnotationAttachments() .stream() .filter(ann -> !isServiceIntropAnnot((BLangAnnotationAttachment) ann)) - .collect(Collectors.toList()); + .toList(); validateEmptyMapConstructorExprInAnnot(attachments, "v20", "A", 1); } @@ -527,10 +526,10 @@ public void validateEmptyMapConstructorExprInAnnot(List getServiceClassAnnotations(String name) getServiceClassForServiceDecl(name).getAnnotationAttachments() .stream() .filter(ann -> !isServiceIntropAnnot((BLangAnnotationAttachment) ann)) - .collect(Collectors.toList()); + .toList(); } private ClassDefinition getServiceClassForServiceDecl(String name) { diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/annotations/AnnotationRuntimeTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/annotations/AnnotationRuntimeTest.java index eb336daa1b1b..3d5046e2917c 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/annotations/AnnotationRuntimeTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/annotations/AnnotationRuntimeTest.java @@ -138,7 +138,7 @@ public void testAnnotAvailabilty() { CompileResult resultFour = BCompileUtil.compile("test-src/annotations/annot_availability.bal"); Assert.assertEquals(resultFour.getErrorCount(), 0); Object obj = BRunUtil.invokeAndGetJVMResult(resultFour, "testStructureAnnots"); - Assert.assertEquals(TypeChecker.getType(obj).getTag(), io.ballerina.runtime.api.TypeTags.TUPLE_TAG); + Assert.assertEquals(TypeChecker.getType(obj).getTag(), TypeTags.TUPLE_TAG); TupleValueImpl tupleValue = (TupleValueImpl) obj; @@ -146,7 +146,7 @@ public void testAnnotAvailabilty() { Assert.assertEquals(annotatableType.getAnnotation(StringUtils.fromString("W")), true); Object fieldAnnots = annotatableType.getAnnotation(StringUtils.fromString("$field$.i")); - Assert.assertEquals(TypeChecker.getType(fieldAnnots).getTag(), io.ballerina.runtime.api.TypeTags.MAP_TAG); + Assert.assertEquals(TypeChecker.getType(fieldAnnots).getTag(), TypeTags.MAP_TAG); MapValueImpl fieldAnnotMap = (MapValueImpl) fieldAnnots; Object annotValue = fieldAnnotMap.get(StringUtils.fromString("Z")); @@ -154,7 +154,7 @@ public void testAnnotAvailabilty() { Assert.assertTrue((Boolean) annotValue); annotValue = fieldAnnotMap.get(StringUtils.fromString("X")); - Assert.assertEquals(TypeChecker.getType(annotValue).getTag(), io.ballerina.runtime.api.TypeTags.MAP_TAG); + Assert.assertEquals(TypeChecker.getType(annotValue).getTag(), TypeTags.MAP_TAG); MapValueImpl mapValue = (MapValueImpl) annotValue; Assert.assertEquals(mapValue.size(), 1); @@ -163,15 +163,15 @@ public void testAnnotAvailabilty() { annotatableType = (AnnotatableType) ((TypedescValue) tupleValue.get(1)).getDescribingType(); Assert.assertEquals(annotatableType.getAnnotation(StringUtils.fromString("W")), true); fieldAnnots = annotatableType.getAnnotation(StringUtils.fromString("$field$.j")); - Assert.assertEquals(TypeChecker.getType(fieldAnnots).getTag(), io.ballerina.runtime.api.TypeTags.MAP_TAG); + Assert.assertEquals(TypeChecker.getType(fieldAnnots).getTag(), TypeTags.MAP_TAG); fieldAnnotMap = (MapValueImpl) fieldAnnots; annotValue = fieldAnnotMap.get(StringUtils.fromString("Z")); - Assert.assertEquals(TypeChecker.getType(annotValue).getTag(), io.ballerina.runtime.api.TypeTags.BOOLEAN_TAG); + Assert.assertEquals(TypeChecker.getType(annotValue).getTag(), TypeTags.BOOLEAN_TAG); Assert.assertTrue((Boolean) annotValue); annotValue = fieldAnnotMap.get(StringUtils.fromString("Y")); - Assert.assertEquals(TypeChecker.getType(annotValue).getTag(), io.ballerina.runtime.api.TypeTags.MAP_TAG); + Assert.assertEquals(TypeChecker.getType(annotValue).getTag(), TypeTags.MAP_TAG); mapValue = (MapValueImpl) annotValue; Assert.assertEquals(mapValue.size(), 2); @@ -181,11 +181,11 @@ public void testAnnotAvailabilty() { annotatableType = (AnnotatableType) ((TypedescValue) tupleValue.get(2)).getDescribingType(); Assert.assertEquals(annotatableType.getAnnotation(StringUtils.fromString("W")), true); fieldAnnots = annotatableType.getAnnotation(StringUtils.fromString("$field$.j")); - Assert.assertEquals(TypeChecker.getType(fieldAnnots).getTag(), io.ballerina.runtime.api.TypeTags.MAP_TAG); + Assert.assertEquals(TypeChecker.getType(fieldAnnots).getTag(), TypeTags.MAP_TAG); fieldAnnotMap = (MapValueImpl) fieldAnnots; annotValue = fieldAnnotMap.get(StringUtils.fromString("Z")); - Assert.assertEquals(TypeChecker.getType(annotValue).getTag(), io.ballerina.runtime.api.TypeTags.BOOLEAN_TAG); + Assert.assertEquals(TypeChecker.getType(annotValue).getTag(), TypeTags.BOOLEAN_TAG); Assert.assertTrue((Boolean) annotValue); } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/annotations/AnonymousTupleAnnotationTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/annotations/AnonymousTupleAnnotationTest.java index 36b2699b6510..7fc60fc8b602 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/annotations/AnonymousTupleAnnotationTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/annotations/AnonymousTupleAnnotationTest.java @@ -62,8 +62,8 @@ public Object[] dataToTestAnnotationsOfLocalTuple() { }; } - public static BMap getAnonymousTupleAnnotations(TypedescValue typedescValue, BString annotName) { - return (BMap) TypeChecker.getAnnotValue(typedescValue, annotName); + public static BMap getAnonymousTupleAnnotations(TypedescValue typedescValue, BString annotName) { + return (BMap) TypeChecker.getAnnotValue(typedescValue, annotName); } @AfterClass diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/annotations/DisplayAnnotationTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/annotations/DisplayAnnotationTest.java index 155c2050b1a3..43c6ae0f08b3 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/annotations/DisplayAnnotationTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/annotations/DisplayAnnotationTest.java @@ -65,8 +65,8 @@ public void setup() { @Test public void testDisplayAnnotOnFunction() { - BLangFunction fooFunction = (BLangFunction) ((List) ((BLangPackage) result.getAST()).functions).get(0); - BLangAnnotationAttachment annot = (BLangAnnotationAttachment) ((List) fooFunction.annAttachments).get(0); + BLangFunction fooFunction = (BLangFunction) ((List) ((BLangPackage) result.getAST()).functions).get(0); + BLangAnnotationAttachment annot = (BLangAnnotationAttachment) ((List) fooFunction.annAttachments).get(0); Assert.assertEquals(getActualExpressionFromAnnotationAttachmentExpr(annot.expr).toString(), " {iconPath: fooIconPath.icon,label: Foo function}"); } @@ -127,7 +127,7 @@ public void testDisplayAnnotOnWorker() { @Test public void testDisplayAnnotOnExternalFunctionBody() { BLangExternalFunctionBody body = (BLangExternalFunctionBody) result.getAST().getFunctions().get(3).getBody(); - BLangAnnotationAttachment annot = (BLangAnnotationAttachment) ((List) body.annAttachments).get(0); + BLangAnnotationAttachment annot = (BLangAnnotationAttachment) ((List) body.annAttachments).get(0); Assert.assertEquals(getActualExpressionFromAnnotationAttachmentExpr(annot.expr).toString(), " {label: external,id: hash}"); } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/annotations/LocalRecordAnnotationTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/annotations/LocalRecordAnnotationTest.java index 15ead423fe3d..c8cec151469b 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/annotations/LocalRecordAnnotationTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/annotations/LocalRecordAnnotationTest.java @@ -64,8 +64,8 @@ public Object[] dataToTestAnnotationsOfLocalRecord() { }; } - public static BMap getLocalRecordAnnotations(TypedescValue typedescValue, BString annotName) { - return (BMap) TypeChecker.getAnnotValue(typedescValue, annotName); + public static BMap getLocalRecordAnnotations(TypedescValue typedescValue, BString annotName) { + return (BMap) TypeChecker.getAnnotValue(typedescValue, annotName); } @AfterClass diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/bala/object/ObjectIncludeOverrideBalaTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/bala/object/ObjectIncludeOverrideBalaTest.java index 32d353031348..710b80d02cb3 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/bala/object/ObjectIncludeOverrideBalaTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/bala/object/ObjectIncludeOverrideBalaTest.java @@ -85,7 +85,7 @@ public void testOverriddenFunctionInformation() { } @Test - public void testIsolationNegative() { + public void testInclusionNegative() { CompileResult negativeRes = BCompileUtil.compile("test-src/bala/test_bala/object/test_object_type_inclusion_negative.bal"); int index = 0; @@ -104,10 +104,12 @@ public void testIsolationNegative() { "a referenced type across modules cannot have non-public fields or methods", 42, 6); validateError(negativeRes, index++, "incompatible type reference 'foo:Employee5': " + "a referenced type across modules cannot have non-public fields or methods", 48, 6); - validateError(negativeRes, index++, "mismatched function signatures: expected 'public function " + - "execute(string, int)', found 'public function execute(int, int)'", 58, 5); - validateError(negativeRes, index++, "mismatched function signatures: expected 'public function " + - "execute(string, int)', found 'public function execute(string, int, int)'", 65, 5); + validateError(negativeRes, index++, "mismatched function signatures: expected 'remote function " + + "execute(string, int)', found 'remote function execute(int, int)'", 58, 5); + validateError(negativeRes, index++, "mismatched function signatures: expected 'remote function " + + "execute(string, int)', found 'remote function execute(string, int, int)'", 65, 5); + validateError(negativeRes, index++, "mismatched function signatures: expected 'remote function " + + "execute(string, int)', found 'public function execute(string, int)'", 72, 5); assertEquals(negativeRes.getErrorCount(), index); } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/bala/record/ClosedRecordTypeInclusionTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/bala/record/ClosedRecordTypeInclusionTest.java index 48ba6acd5de8..e06f506c8520 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/bala/record/ClosedRecordTypeInclusionTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/bala/record/ClosedRecordTypeInclusionTest.java @@ -90,7 +90,7 @@ public void negativeTests() { @Test(description = "Test case for type referencing all value-typed fields") public void testValRefType() { Object returns = BRunUtil.invoke(compileResult, "testValRefType"); - BMap foo1 = (BMap) returns; + BMap foo1 = (BMap) returns; assertEquals(foo1.get(StringUtils.fromString("a")), 10L); assertEquals(foo1.get(StringUtils.fromString("b")), 23.45); assertEquals(foo1.get(StringUtils.fromString("s")).toString(), "hello foo"); @@ -109,32 +109,26 @@ public void testValRefType() { @Test(description = "Test case for type referencing records with complex ref types") public void testRefTypes() { Object returns = BRunUtil.invoke(compileResult, "testRefTypes"); - BMap foo2 = (BMap) returns; + BMap foo2 = (BMap) returns; assertEquals(foo2.get(StringUtils.fromString("s")).toString(), "qwerty"); assertEquals(foo2.get(StringUtils.fromString("i")), 10L); - assertEquals(getType(foo2.get(StringUtils.fromString("rj"))).getTag(), - io.ballerina.runtime.api.TypeTags.MAP_TAG); + assertEquals(getType(foo2.get(StringUtils.fromString("rj"))).getTag(), TypeTags.MAP_TAG); assertEquals(foo2.get(StringUtils.fromString("rj")).toString(), "{\"name\":\"apple\",\"color\":\"red\",\"price\":40}"); - assertEquals(getType(foo2.get(StringUtils.fromString("rx"))).getTag(), - TypeTags.XML_ELEMENT_TAG); + assertEquals(getType(foo2.get(StringUtils.fromString("rx"))).getTag(), TypeTags.XML_ELEMENT_TAG); assertEquals(foo2.get(StringUtils.fromString("rx")).toString(), "Count of Monte Cristo"); - assertEquals(getType(foo2.get(StringUtils.fromString("rp"))).getTag(), - io.ballerina.runtime.api.TypeTags.OBJECT_TYPE_TAG); + assertEquals(getType(foo2.get(StringUtils.fromString("rp"))).getTag(), TypeTags.OBJECT_TYPE_TAG); assertEquals(((BObject) foo2.get(StringUtils.fromString("rp"))).get(StringUtils.fromString("name")).toString(), "John Doe"); - assertEquals(getType(foo2.get(StringUtils.fromString("ra"))).getTag(), - io.ballerina.runtime.api.TypeTags.RECORD_TYPE_TAG); + assertEquals(getType(foo2.get(StringUtils.fromString("ra"))).getTag(), TypeTags.RECORD_TYPE_TAG); assertEquals(foo2.get(StringUtils.fromString("ra")).toString(), "{\"city\":\"Colombo\",\"country\":\"Sri " + "Lanka\"}"); assertEquals(getType(foo2.get(StringUtils.fromString("crx"))).getTag(), TypeTags.XML_ELEMENT_TAG); assertEquals(foo2.get(StringUtils.fromString("crx")).toString(), "Count of Monte Cristo"); - assertEquals(getType(foo2.get(StringUtils.fromString("crj"))).getTag(), - io.ballerina.runtime.api.TypeTags.MAP_TAG); + assertEquals(getType(foo2.get(StringUtils.fromString("crj"))).getTag(), TypeTags.MAP_TAG); assertEquals(foo2.get(StringUtils.fromString("crj")).toString(), "{\"name\":\"apple\",\"color\":\"red\",\"price\":40}"); - assertEquals(getType(foo2.get(StringUtils.fromString("rp"))).getTag(), - io.ballerina.runtime.api.TypeTags.OBJECT_TYPE_TAG); + assertEquals(getType(foo2.get(StringUtils.fromString("rp"))).getTag(), TypeTags.OBJECT_TYPE_TAG); assertEquals(((BObject) foo2.get(StringUtils.fromString("crp"))).get(StringUtils.fromString("name")).toString(), "Jane Doe"); assertEquals(getType(foo2.get(StringUtils.fromString("cra"))).getTag(), TypeTags.RECORD_TYPE_TAG); @@ -145,7 +139,7 @@ public void testRefTypes() { @Test(description = "Test case for order of resolving") public void testOrdering() { Object returns = BRunUtil.invoke(compileResult, "testOrdering"); - BMap foo3 = (BMap) returns; + BMap foo3 = (BMap) returns; assertEquals(foo3.get(StringUtils.fromString("s")).toString(), "qwerty"); assertEquals(foo3.get(StringUtils.fromString("ri")), 10L); assertEquals(foo3.get(StringUtils.fromString("rs")).toString(), "asdf"); @@ -154,7 +148,7 @@ public void testOrdering() { @Test(description = "Test case for reference chains") public void testReferenceChains() { Object returns = BRunUtil.invoke(compileResult, "testReferenceChains"); - BMap foo4 = (BMap) returns; + BMap foo4 = (BMap) returns; assertEquals(foo4.get(StringUtils.fromString("s")).toString(), "qwerty"); assertEquals(foo4.get(StringUtils.fromString("abi")), 10L); assertEquals(foo4.get(StringUtils.fromString("efs")).toString(), "asdf"); @@ -164,7 +158,7 @@ public void testReferenceChains() { @Test(description = "Test case for type referencing in BALAs") public void testTypeReferencingInBALAs() { Object returns = BRunUtil.invoke(compileResult, "testTypeReferencingInBALAs"); - BMap manager = (BMap) returns; + BMap manager = (BMap) returns; assertEquals(manager.get(StringUtils.fromString("name")).toString(), "John Doe"); assertEquals(manager.get(StringUtils.fromString("age")), 25L); assertEquals(manager.get(StringUtils.fromString("adr")).toString(), "{\"city\":\"Colombo\",\"country\":\"Sri " + @@ -176,7 +170,7 @@ public void testTypeReferencingInBALAs() { @Test(description = "Test case for default value initializing in type referenced fields") public void testDefaultValueInit() { Object returns = BRunUtil.invoke(compileResult, "testDefaultValueInit"); - BMap manager = (BMap) returns; + BMap manager = (BMap) returns; assertEquals(manager.get(StringUtils.fromString("name")).toString(), "John Doe"); assertEquals(manager.get(StringUtils.fromString("age")), 25L); assertEquals(manager.get(StringUtils.fromString("adr")).toString(), "{\"city\":\"Colombo\",\"country\":\"Sri " + @@ -188,7 +182,7 @@ public void testDefaultValueInit() { @Test(description = "Test case for default value initializing in type referenced fields from a bala") public void testDefaultValueInitInBALAs() { Object returns = BRunUtil.invoke(compileResult, "testDefaultValueInitInBALAs"); - BMap manager = (BMap) returns; + BMap manager = (BMap) returns; assertEquals(manager.get(StringUtils.fromString("name")).toString(), "anonymous"); assertEquals(manager.get(StringUtils.fromString("age")), 0L); assertEquals(manager.get(StringUtils.fromString("adr")).toString(), "{\"city\":\"\",\"country\":\"\"}"); @@ -207,6 +201,7 @@ public Object[] testFunctions() { "testRestTypeOverriding", "testOutOfOrderFieldOverridingFieldFromTypeInclusion", "testTypeInclusionWithFiniteField", + "testDefaultValueFromInclusion" }; } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/bala/record/OpenRecordTypeInclusionTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/bala/record/OpenRecordTypeInclusionTest.java index 122965a4088d..f6122037f4f4 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/bala/record/OpenRecordTypeInclusionTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/bala/record/OpenRecordTypeInclusionTest.java @@ -82,7 +82,7 @@ public void negativeTests() { @Test(description = "Test case for type referencing all value-typed fields") public void testValRefType() { Object returns = BRunUtil.invoke(compileResult, "testValRefType"); - BMap foo1 = (BMap) returns; + BMap foo1 = (BMap) returns; assertEquals(foo1.get(StringUtils.fromString("a")), 10L); assertEquals(foo1.get(StringUtils.fromString("b")), 23.45); assertEquals(foo1.get(StringUtils.fromString("s")).toString(), "hello foo"); @@ -101,7 +101,7 @@ public void testValRefType() { @Test(description = "Test case for type referencing records with complex ref types") public void testRefTypes() { Object returns = BRunUtil.invoke(compileResult, "testRefTypes"); - BMap foo2 = (BMap) returns; + BMap foo2 = (BMap) returns; assertEquals(foo2.get(StringUtils.fromString("s")).toString(), "qwerty"); assertEquals(foo2.get(StringUtils.fromString("i")), 10L); assertEquals(getType(foo2.get(StringUtils.fromString("rj"))).getTag(), TypeTags.MAP_TAG); @@ -131,7 +131,7 @@ public void testRefTypes() { @Test(description = "Test case for order of resolving") public void testOrdering() { Object returns = BRunUtil.invoke(compileResult, "testOrdering"); - BMap foo3 = (BMap) returns; + BMap foo3 = (BMap) returns; assertEquals(foo3.get(StringUtils.fromString("s")).toString(), "qwerty"); assertEquals(foo3.get(StringUtils.fromString("ri")), 10L); assertEquals(foo3.get(StringUtils.fromString("rs")).toString(), "asdf"); @@ -140,7 +140,7 @@ public void testOrdering() { @Test(description = "Test case for reference chains") public void testReferenceChains() { Object returns = BRunUtil.invoke(compileResult, "testReferenceChains"); - BMap foo4 = (BMap) returns; + BMap foo4 = (BMap) returns; assertEquals(foo4.get(StringUtils.fromString("s")).toString(), "qwerty"); assertEquals(foo4.get(StringUtils.fromString("abi")), 10L); assertEquals(foo4.get(StringUtils.fromString("efs")).toString(), "asdf"); @@ -150,7 +150,7 @@ public void testReferenceChains() { @Test(description = "Test case for type referencing in BALAs") public void testTypeReferencingInBALAs() { Object returns = BRunUtil.invoke(compileResult, "testTypeReferencingInBALAs"); - BMap manager = (BMap) returns; + BMap manager = (BMap) returns; assertEquals(manager.get(StringUtils.fromString("name")).toString(), "John Doe"); assertEquals(manager.get(StringUtils.fromString("age")), 25L); assertEquals(manager.get(StringUtils.fromString("adr")).toString(), @@ -162,7 +162,7 @@ public void testTypeReferencingInBALAs() { @Test(description = "Test case for default value initializing in type referenced fields") public void testDefaultValueInit() { Object returns = BRunUtil.invoke(compileResult, "testDefaultValueInit"); - BMap manager = (BMap) returns; + BMap manager = (BMap) returns; assertEquals(manager.get(StringUtils.fromString("name")).toString(), "John Doe"); assertEquals(manager.get(StringUtils.fromString("age")), 25L); assertEquals(manager.get(StringUtils.fromString("adr")).toString(), @@ -174,7 +174,7 @@ public void testDefaultValueInit() { @Test(description = "Test case for default value initializing in type referenced fields from a bala") public void testDefaultValueInitInBALAs() { Object returns = BRunUtil.invoke(compileResult, "testDefaultValueInitInBALAs"); - BMap manager = (BMap) returns; + BMap manager = (BMap) returns; assertEquals(manager.get(StringUtils.fromString("name")).toString(), "anonymous"); assertEquals(manager.get(StringUtils.fromString("age")), 0L); assertEquals(manager.get(StringUtils.fromString("adr")).toString(), "{\"city\":\"\",\"country\":\"\"}"); @@ -193,7 +193,9 @@ public Object[] testFunctions() { "testCyclicRecord", "testOutOfOrderFieldOverridingFieldFromTypeInclusion", "testCreatingRecordWithOverriddenFields", - "testDefaultValuesOfRecordFieldsWithTypeInclusion" + "testDefaultValuesOfRecordFieldsWithTypeInclusion", + "testDefaultValueFromInclusion", + "testSpreadOverrideDefault" }; } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/bir/BirVariableOptimizationTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/bir/BirVariableOptimizationTest.java index 2fb1c893b690..df00cb7a9dc1 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/bir/BirVariableOptimizationTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/bir/BirVariableOptimizationTest.java @@ -79,11 +79,11 @@ private String readFile(String name) throws IOException { Path filePath = Paths.get("src", "test", "resources", "test-src", "bir", "bir-dump", name).toAbsolutePath(); if (Files.exists(filePath)) { StringBuilder contentBuilder = new StringBuilder(); + try (Stream stream = Files.lines(filePath, StandardCharsets.UTF_8)) { + stream.forEach(s -> contentBuilder.append(s).append("\n")); - Stream stream = Files.lines(filePath, StandardCharsets.UTF_8); - stream.forEach(s -> contentBuilder.append(s).append("\n")); - - return contentBuilder.toString().trim(); + return contentBuilder.toString().trim(); + } } return ""; } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/bir/RecordDesugarTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/bir/RecordDesugarTest.java index a291a3c84648..1704aaa73a3f 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/bir/RecordDesugarTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/bir/RecordDesugarTest.java @@ -76,9 +76,9 @@ private String readFile(String name) throws IOException { Path filePath = Paths.get("src", "test", "resources", "test-src", "bir", "bir-dump", name).toAbsolutePath(); if (Files.exists(filePath)) { StringBuilder contentBuilder = new StringBuilder(); - - Stream stream = Files.lines(filePath, StandardCharsets.UTF_8); - stream.forEach(s -> contentBuilder.append(s).append("\n")); + try (Stream stream = Files.lines(filePath, StandardCharsets.UTF_8)) { + stream.forEach(s -> contentBuilder.append(s).append("\n")); + } return contentBuilder.toString().trim(); } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/closures/VarMutabilityClosureTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/closures/VarMutabilityClosureTest.java index 48d26457dde8..0527814490c0 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/closures/VarMutabilityClosureTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/closures/VarMutabilityClosureTest.java @@ -102,15 +102,15 @@ public void testVarMutabilityWithArrays() { @Test(description = "Test variable mutability with maps") public void testVarMutabilityWithMaps() { Object returns = BRunUtil.invoke(compileResult, "test8"); - Assert.assertEquals(((BMap) returns).size(), 8); - Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("a")).toString(), "AAAA"); - Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("b")).toString(), "BB"); - Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("c")).toString(), "C"); - Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("d")).toString(), "D"); - Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("e")).toString(), "EE"); - Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("x")).toString(), "XXXX"); - Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("y")).toString(), "YY"); - Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("z")).toString(), "ZZ"); + Assert.assertEquals(((BMap) returns).size(), 8); + Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("a")).toString(), "AAAA"); + Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("b")).toString(), "BB"); + Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("c")).toString(), "C"); + Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("d")).toString(), "D"); + Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("e")).toString(), "EE"); + Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("x")).toString(), "XXXX"); + Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("y")).toString(), "YY"); + Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("z")).toString(), "ZZ"); } @@ -126,12 +126,12 @@ public void testVarMutabilityWithObjects() { public void testVarMutabilityWithRecords() { Object returns = BRunUtil.invoke(compileResult, "test10"); - BMap resMap = ((BMap) returns); + BMap resMap = ((BMap) returns); Assert.assertEquals(resMap.get(StringUtils.fromString("age")).toString(), "17"); Assert.assertEquals(resMap.get(StringUtils.fromString("name")).toString(), "Adam Page"); Assert.assertEquals(resMap.get(StringUtils.fromString("email")).toString(), "adamp@wso2.com"); - BMap gradesMap = (BMap) resMap.get(StringUtils.fromString("grades")); + BMap gradesMap = (BMap) resMap.get(StringUtils.fromString("grades")); Assert.assertEquals(gradesMap.get(StringUtils.fromString("bio")).toString(), "22"); Assert.assertEquals(gradesMap.get(StringUtils.fromString("maths")).toString(), "80"); Assert.assertEquals(gradesMap.get(StringUtils.fromString("physics")).toString(), "100"); @@ -141,12 +141,12 @@ public void testVarMutabilityWithRecords() { @Test(description = "Test variable mutability with json objects") public void testVarMutabilityWithJSONObjects() { Object returns = BRunUtil.invoke(compileResult, "test11"); - Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("f1")).toString(), "{\"name\":\"apple\"," + - "\"color\":\"red\",\"price\":12.48}"); - Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("f2")).toString(), "{\"name\":\"orange\"," + - "\"color\":\"orange\",\"price\":5.36}"); - Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("f3")).toString(), "{\"name\":\"cherry\"," + - "\"color\":\"red\",\"price\":5.36}"); + Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("f1")).toString(), + "{\"name\":\"apple\",\"color\":\"red\",\"price\":12.48}"); + Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("f2")).toString(), + "{\"name\":\"orange\",\"color\":\"orange\",\"price\":5.36}"); + Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("f3")).toString(), + "{\"name\":\"cherry\",\"color\":\"red\",\"price\":5.36}"); } @Test(description = "Test variable mutability with xml") diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/documentation/DeprecatedAnnotationTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/documentation/DeprecatedAnnotationTest.java index 83879169c249..192f1e02fa7b 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/documentation/DeprecatedAnnotationTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/documentation/DeprecatedAnnotationTest.java @@ -18,6 +18,7 @@ package org.ballerinalang.test.documentation; +import io.ballerina.projects.Project; import org.ballerinalang.docgen.docs.BallerinaDocGenerator; import org.ballerinalang.docgen.generator.model.Annotation; import org.ballerinalang.docgen.generator.model.BClass; @@ -52,7 +53,7 @@ public class DeprecatedAnnotationTest { public void setup() throws IOException { String sourceRoot = "test-src" + File.separator + "documentation" + File.separator + "deprecated_annotation_project"; - io.ballerina.projects.Project project = BCompileUtil.loadProject(sourceRoot); + Project project = BCompileUtil.loadProject(sourceRoot); Map moduleDocMap = BallerinaDocGenerator.generateModuleDocMap(project); List modulesList = BallerinaDocGenerator.getDocsGenModel(moduleDocMap, project.currentPackage() .packageOrg().toString(), project.currentPackage().packageVersion().toString()); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/documentation/DocModelTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/documentation/DocModelTest.java index 663bea205416..b1c2b26a2a2c 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/documentation/DocModelTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/documentation/DocModelTest.java @@ -15,6 +15,7 @@ */ package org.ballerinalang.test.documentation; +import io.ballerina.projects.Project; import org.ballerinalang.docgen.docs.BallerinaDocGenerator; import org.ballerinalang.docgen.generator.model.BClass; import org.ballerinalang.docgen.generator.model.BObjectType; @@ -47,7 +48,7 @@ public class DocModelTest { @BeforeClass public void setup() throws IOException { String sourceRoot = "test-src" + File.separator + "documentation" + File.separator + "docerina_project"; - io.ballerina.projects.Project project = BCompileUtil.loadProject(sourceRoot); + Project project = BCompileUtil.loadProject(sourceRoot); Map moduleDocMap = BallerinaDocGenerator.generateModuleDocMap(project); List modulesList = BallerinaDocGenerator.getDocsGenModel(moduleDocMap, project.currentPackage() .packageOrg().toString(), project.currentPackage().packageVersion().toString()); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/documentation/ErrorsTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/documentation/ErrorsTest.java index 4fa4e46aa342..83b51187196e 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/documentation/ErrorsTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/documentation/ErrorsTest.java @@ -18,6 +18,7 @@ package org.ballerinalang.test.documentation; +import io.ballerina.projects.Project; import org.ballerinalang.docgen.docs.BallerinaDocGenerator; import org.ballerinalang.docgen.generator.model.Module; import org.ballerinalang.docgen.generator.model.ModuleDoc; @@ -43,7 +44,7 @@ public class ErrorsTest { public void setup() throws IOException { String sourceRoot = "test-src" + File.separator + "documentation" + File.separator + "errors_project"; - io.ballerina.projects.Project project = BCompileUtil.loadProject(sourceRoot); + Project project = BCompileUtil.loadProject(sourceRoot); Map moduleDocMap = BallerinaDocGenerator.generateModuleDocMap(project); List modulesList = BallerinaDocGenerator.getDocsGenModel(moduleDocMap, project.currentPackage() .packageOrg().toString(), project.currentPackage().packageVersion().toString()); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/documentation/FieldLevelDocsTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/documentation/FieldLevelDocsTest.java index a1fce274783e..57aa93461015 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/documentation/FieldLevelDocsTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/documentation/FieldLevelDocsTest.java @@ -18,6 +18,7 @@ package org.ballerinalang.test.documentation; +import io.ballerina.projects.Project; import org.ballerinalang.docgen.docs.BallerinaDocGenerator; import org.ballerinalang.docgen.generator.model.BClass; import org.ballerinalang.docgen.generator.model.DefaultableVariable; @@ -56,7 +57,7 @@ public class FieldLevelDocsTest { public void setup() throws IOException { String sourceRoot = "test-src" + File.separator + "documentation" + File.separator + "record_object_fields_project"; - io.ballerina.projects.Project project = BCompileUtil.loadProject(sourceRoot); + Project project = BCompileUtil.loadProject(sourceRoot); Map moduleDocMap = BallerinaDocGenerator.generateModuleDocMap(project); List modulesList = BallerinaDocGenerator.getDocsGenModel(moduleDocMap, project.currentPackage() .packageOrg().toString(), project.currentPackage().packageVersion().toString()); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/documentation/MultilineDocsTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/documentation/MultilineDocsTest.java index 9ab12f4e092d..3d14e444cd0f 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/documentation/MultilineDocsTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/documentation/MultilineDocsTest.java @@ -18,6 +18,7 @@ package org.ballerinalang.test.documentation; +import io.ballerina.projects.Project; import org.ballerinalang.docgen.docs.BallerinaDocGenerator; import org.ballerinalang.docgen.generator.model.Function; import org.ballerinalang.docgen.generator.model.Module; @@ -67,7 +68,7 @@ public class MultilineDocsTest { public void setup() throws IOException { String sourceRoot = "test-src" + File.separator + "documentation" + File.separator + "multi_line_docs_project"; - io.ballerina.projects.Project project = BCompileUtil.loadProject(sourceRoot); + Project project = BCompileUtil.loadProject(sourceRoot); Map moduleDocMap = BallerinaDocGenerator.generateModuleDocMap(project); List modulesList = BallerinaDocGenerator.getDocsGenModel(moduleDocMap, project.currentPackage() .packageOrg().toString(), project.currentPackage().packageVersion().toString()); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/documentation/ObjectFieldDefaultValueTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/documentation/ObjectFieldDefaultValueTest.java index c1877123aa1d..0bdc041a4283 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/documentation/ObjectFieldDefaultValueTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/documentation/ObjectFieldDefaultValueTest.java @@ -18,6 +18,7 @@ package org.ballerinalang.test.documentation; +import io.ballerina.projects.Project; import org.ballerinalang.docgen.docs.BallerinaDocGenerator; import org.ballerinalang.docgen.generator.model.BClass; import org.ballerinalang.docgen.generator.model.DefaultableVariable; @@ -44,7 +45,7 @@ public class ObjectFieldDefaultValueTest { public void setup() throws IOException { String sourceRoot = "test-src" + File.separator + "documentation" + File.separator + "default_value_initialization"; - io.ballerina.projects.Project project = BCompileUtil.loadProject(sourceRoot); + Project project = BCompileUtil.loadProject(sourceRoot); Map moduleDocMap = BallerinaDocGenerator.generateModuleDocMap(project); List modulesList = BallerinaDocGenerator.getDocsGenModel(moduleDocMap, project.currentPackage() .packageOrg().toString(), project.currentPackage().packageVersion().toString()); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/documentation/TypeModelTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/documentation/TypeModelTest.java index d23e3a2503b7..22745197b4b6 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/documentation/TypeModelTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/documentation/TypeModelTest.java @@ -17,6 +17,7 @@ */ package org.ballerinalang.test.documentation; +import io.ballerina.projects.Project; import org.ballerinalang.docgen.docs.BallerinaDocGenerator; import org.ballerinalang.docgen.generator.model.BObjectType; import org.ballerinalang.docgen.generator.model.BType; @@ -46,7 +47,7 @@ public class TypeModelTest { @BeforeClass public void setup() throws IOException { String sourceRoot = "test-src" + File.separator + "documentation" + File.separator + "type_models_project"; - io.ballerina.projects.Project project = BCompileUtil.loadProject(sourceRoot); + Project project = BCompileUtil.loadProject(sourceRoot); Map moduleDocMap = BallerinaDocGenerator.generateModuleDocMap(project); List modulesList = BallerinaDocGenerator.getDocsGenModel(moduleDocMap, project.currentPackage() .packageOrg().toString(), project.currentPackage().packageVersion().toString()); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/error/ErrorTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/error/ErrorTest.java index bf302c0812c7..9e84dfc2ea18 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/error/ErrorTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/error/ErrorTest.java @@ -199,7 +199,7 @@ public void testErrorWithConstantAsReason(String testFunction) { Assert.assertTrue(returns instanceof BError); Assert.assertEquals(((BError) returns).getMessage(), CONST_ERROR_REASON); Assert.assertEquals( - ((BMap) ((BError) returns).getDetails()).get(StringUtils.fromString("message")).toString(), + ((BMap) ((BError) returns).getDetails()).get(StringUtils.fromString("message")).toString(), "error detail message"); } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/builtinoperations/CloneOperationTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/builtinoperations/CloneOperationTest.java index af5eb7abe633..ebe63a90b658 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/builtinoperations/CloneOperationTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/builtinoperations/CloneOperationTest.java @@ -75,23 +75,23 @@ public void testCloneCyclicRecord() { BArray results = (BArray) returns; Assert.assertNotNull(results); - BMap record = (BMap) results.get(0); - BMap fieldA = (BMap) record.get(StringUtils.fromString("a")); + BMap record = (BMap) results.get(0); + BMap fieldA = (BMap) record.get(StringUtils.fromString("a")); BArray arr = (BArray) fieldA.get(StringUtils.fromString("arr")); - BMap fieldB = (BMap) record.get(StringUtils.fromString("b")); - BMap fieldAOfB = (BMap) fieldB.get(StringUtils.fromString("aa")); + BMap fieldB = (BMap) record.get(StringUtils.fromString("b")); + BMap fieldAOfB = (BMap) fieldB.get(StringUtils.fromString("aa")); BArray arrOfAA = (BArray) fieldAOfB.get(StringUtils.fromString("arr")); Assert.assertEquals(arr.getInt(0), 10); Assert.assertEquals(arrOfAA.getInt(0), 10); - record = (BMap) results.get(1); - BMap fieldA1 = (BMap) record.get(StringUtils.fromString("a")); + record = (BMap) results.get(1); + BMap fieldA1 = (BMap) record.get(StringUtils.fromString("a")); arr = (BArray) fieldA1.get(StringUtils.fromString("arr")); - fieldB = (BMap) record.get(StringUtils.fromString("b")); - BMap fieldAOfB1 = (BMap) fieldB.get(StringUtils.fromString("aa")); + fieldB = (BMap) record.get(StringUtils.fromString("b")); + BMap fieldAOfB1 = (BMap) fieldB.get(StringUtils.fromString("aa")); arrOfAA = (BArray) fieldAOfB1.get(StringUtils.fromString("arr")); Assert.assertEquals(arr.getInt(0), 1); @@ -114,11 +114,11 @@ public void testCloneCyclicArray() { arr[0] = (BArray) results.get(0); arr[1] = (BArray) results.get(1); - BMap record1 = (BMap) arr[0].getRefValue(2); - BMap record2 = (BMap) arr[0].getRefValue(3); + BMap record1 = (BMap) arr[0].getRefValue(2); + BMap record2 = (BMap) arr[0].getRefValue(3); - BMap record3 = (BMap) arr[1].getRefValue(2); - BMap record4 = (BMap) arr[1].getRefValue(3); + BMap record3 = (BMap) arr[1].getRefValue(2); + BMap record4 = (BMap) arr[1].getRefValue(3); BArray intArr1 = (BArray) record1.get(StringUtils.fromString("arr")); BArray intArr2 = (BArray) record2.get(StringUtils.fromString("arr")); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/conversion/NativeConversionTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/conversion/NativeConversionTest.java index a961b3b89b5a..f40274f2c89a 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/conversion/NativeConversionTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/conversion/NativeConversionTest.java @@ -213,7 +213,7 @@ public void testStructToJson() { public void testAnyRecordToAnydataMap() { Object returns = BRunUtil.invoke(compileResult, "testAnyRecordToAnydataMap"); Assert.assertTrue(returns instanceof BMap); - Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("name")).toString(), "Waruna"); + Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("name")).toString(), "Waruna"); } @Test(description = "Test converting a map to json") diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/lambda/ArrowExprTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/lambda/ArrowExprTest.java index dc58f8f2d918..42c854d77270 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/lambda/ArrowExprTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/lambda/ArrowExprTest.java @@ -104,8 +104,8 @@ public void testClosureWithCasting() { @Test(description = "Test arrow expression with input parameter and return type record") public void testRecordTypeWithArrowExpr() { Object returns = BRunUtil.invoke(basic, "testRecordTypeWithArrowExpr"); - Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("name")).toString(), "John"); - Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("age")).toString(), "12"); + Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("name")).toString(), "John"); + Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("age")).toString(), "12"); } @Test(description = "Test arrow expression that takes one nillable input parameter") diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/lambda/IterableArrowExprTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/lambda/IterableArrowExprTest.java index 1190d94908f4..4617418796f8 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/lambda/IterableArrowExprTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/lambda/IterableArrowExprTest.java @@ -53,8 +53,8 @@ public void setup() { @Test(description = "Test arrow expression inside map() with return string collection") public void testMapIterable() { Object returns = BRunUtil.invoke(basic, "testMapIterable"); - Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("a")).toString(), "ANT"); - Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("b")).toString(), "BEAR"); + Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("a")).toString(), "ANT"); + Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("b")).toString(), "BEAR"); } @Test(description = "Test arrow expression inside filter() and then inside map() followed by average()") @@ -66,14 +66,14 @@ public void testFilterIterable() { @Test(description = "Test arrow expression inside map() followed by map()") public void testTwoLevelMapIterable() { Object returns = BRunUtil.invoke(basic, "testTwoLevelMapIterable"); - Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("a")).toString(), "ANT"); - Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("b")).toString(), "BEAR"); + Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("a")).toString(), "ANT"); + Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("b")).toString(), "BEAR"); } @Test(description = "Test arrow expression inside map() then filter() then map()") public void testTwoLevelMapIterableWithFilter() { Object returns = BRunUtil.invoke(basic, "testTwoLevelMapIterableWithFilter"); - Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("b")).toString(), "BEAR"); + Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("b")).toString(), "BEAR"); } @Test(description = "Test arrow expression with filter() first and then map") @@ -88,15 +88,15 @@ public void testFilterThenMap() { @Test(description = "Test arrow expression inside map() with return a single string") public void testFilterWithArityOne() { Object returns = BRunUtil.invoke(basic, "testFilterWithArityOne"); - Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("a")).toString(), "ANT"); - Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("c")).toString(), "TIGER"); + Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("a")).toString(), "ANT"); + Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("c")).toString(), "TIGER"); } @Test(description = "Test arrow expression inside map() which returns a lambda collection") public void testIterableReturnLambda() { Object returns = BRunUtil.invoke(basic, "testIterableReturnLambda"); Assert.assertNotNull(returns); - BMap res = (BMap) returns; + BMap res = (BMap) returns; Assert.assertTrue(res.get(StringUtils.fromString("a")) instanceof BFunctionPointer); Assert.assertTrue(res.get(StringUtils.fromString("b")) instanceof BFunctionPointer); Assert.assertTrue(res.get(StringUtils.fromString("c")) instanceof BFunctionPointer); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/literals/IdentifierLiteralPackageTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/literals/IdentifierLiteralPackageTest.java index 88556e8ea82b..fd883cd46979 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/literals/IdentifierLiteralPackageTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/literals/IdentifierLiteralPackageTest.java @@ -93,7 +93,7 @@ public void testGetNestedAnonymousRecordArray() { BArray returns = (BArray) arr; Assert.assertEquals(returns.size(), 1); Assert.assertTrue(returns.get(0) instanceof BMap); - BMap bmap = (BMap) returns.get(0); + BMap bmap = (BMap) returns.get(0); Assert.assertEquals(bmap.get(StringUtils.fromString("name")).toString(), "Waruna"); } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/stamp/AnydataStampInbuiltFunctionTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/stamp/AnydataStampInbuiltFunctionTest.java index 58080df41cb4..af90b284548c 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/stamp/AnydataStampInbuiltFunctionTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/stamp/AnydataStampInbuiltFunctionTest.java @@ -92,10 +92,11 @@ public void testStampAnydataToJSONV2() { Assert.assertTrue(((BMapType) getType(mapValue0)).getConstrainedType() instanceof BJsonType); Assert.assertEquals((mapValue0).size(), 5); - Assert.assertEquals(((LinkedHashMap) mapValue0).get(StringUtils.fromString("school")).toString(), + Assert.assertEquals(((LinkedHashMap) mapValue0).get(StringUtils.fromString("school")).toString(), "Hindu College"); Assert.assertTrue( - getType(((LinkedHashMap) mapValue0).get(StringUtils.fromString("school"))) instanceof BStringType); + getType(((LinkedHashMap) mapValue0).get(StringUtils.fromString("school"))) + instanceof BStringType); } @@ -118,10 +119,10 @@ public void testStampAnydataToMap() { Assert.assertEquals(mapValue.size(), 2); Assert.assertEquals(getType(mapValue.get(StringUtils.fromString("a"))).getName(), "Employee"); - Assert.assertEquals(((BMap) mapValue.get(StringUtils.fromString("a"))).size(), 5); + Assert.assertEquals(((BMap) mapValue.get(StringUtils.fromString("a"))).size(), 5); Assert.assertEquals(getType(mapValue.get(StringUtils.fromString("b"))).getName(), "Employee"); - Assert.assertEquals(((BMap) mapValue.get(StringUtils.fromString("b"))).size(), 5); + Assert.assertEquals(((BMap) mapValue.get(StringUtils.fromString("b"))).size(), 5); } @Test @@ -154,23 +155,28 @@ public void testStampAnydataToTuple() { Assert.assertTrue(getType(tupleValue2) instanceof BRecordType); Assert.assertEquals(getType(tupleValue2).getName(), "Teacher"); - Assert.assertEquals(((BMap) tupleValue2).size(), 5); + Assert.assertEquals(((BMap) tupleValue2).size(), 5); - Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("name")).toString(), "Raja"); - Assert.assertTrue(getType(((BMap) tupleValue2).get(StringUtils.fromString("name"))) instanceof BStringType); + Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("name")).toString(), "Raja"); + Assert.assertTrue(getType(((BMap) tupleValue2).get(StringUtils.fromString("name"))) + instanceof BStringType); - Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("age")).toString(), "25"); - Assert.assertEquals(getType(((BMap) tupleValue2).get(StringUtils.fromString("age"))).getTag(), + Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("age")).toString(), "25"); + Assert.assertEquals(getType(((BMap) tupleValue2).get(StringUtils.fromString("age"))).getTag(), TypeTags.INT_TAG); - Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("status")).toString(), "single"); - Assert.assertTrue(getType(((BMap) tupleValue2).get(StringUtils.fromString("status"))) instanceof BStringType); + Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("status")).toString(), "single"); + Assert.assertTrue(getType(((BMap) tupleValue2).get(StringUtils.fromString("status"))) + instanceof BStringType); - Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("batch")).toString(), "LK2014"); - Assert.assertTrue(getType(((BMap) tupleValue2).get(StringUtils.fromString("batch"))) instanceof BStringType); + Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("batch")).toString(), "LK2014"); + Assert.assertTrue(getType(((BMap) tupleValue2).get(StringUtils.fromString("batch"))) + instanceof BStringType); - Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("school")).toString(), "Hindu College"); - Assert.assertTrue(getType(((BMap) tupleValue2).get(StringUtils.fromString("school"))) instanceof BStringType); + Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("school")).toString(), + "Hindu College"); + Assert.assertTrue(getType(((BMap) tupleValue2).get(StringUtils.fromString("school"))) + instanceof BStringType); } @Test diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/stamp/ArrayStampInbuiltFunctionTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/stamp/ArrayStampInbuiltFunctionTest.java index 4f3251a18a56..d7ba05008d41 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/stamp/ArrayStampInbuiltFunctionTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/stamp/ArrayStampInbuiltFunctionTest.java @@ -137,17 +137,19 @@ public void testStampConstraintArrayToJSONArray() { Assert.assertEquals(getType(mapValue0).getClass(), BMapType.class); Assert.assertEquals(((BMapType) mapValue0.getType()).getConstrainedType().getClass(), BJsonType.class); Assert.assertEquals((mapValue0).size(), 4); - Assert.assertEquals(((LinkedHashMap) mapValue0).get(StringUtils.fromString("batch")).toString(), "LK2014"); + Assert.assertEquals(((LinkedHashMap) mapValue0).get(StringUtils.fromString("batch")).toString(), + "LK2014"); Assert.assertEquals( - getType(((LinkedHashMap) mapValue0).get(StringUtils.fromString("batch"))).getClass(), + getType(((LinkedHashMap) mapValue0).get(StringUtils.fromString("batch"))).getClass(), BStringType.class); Assert.assertEquals(getType(mapValue1).getClass(), BMapType.class); Assert.assertEquals(((BMapType) mapValue0.getType()).getConstrainedType().getClass(), BJsonType.class); Assert.assertEquals((mapValue1).size(), 4); - Assert.assertEquals(((LinkedHashMap) mapValue1).get(StringUtils.fromString("batch")).toString(), "LK2014"); + Assert.assertEquals(((LinkedHashMap) mapValue1).get(StringUtils.fromString("batch")).toString(), + "LK2014"); Assert.assertEquals( - getType(((LinkedHashMap) mapValue0).get(StringUtils.fromString("batch"))).getClass(), + getType(((LinkedHashMap) mapValue0).get(StringUtils.fromString("batch"))).getClass(), BStringType.class); } @@ -220,26 +222,28 @@ public void testStampArrayValueToTuple() { Assert.assertEquals(getType(tupleValue2).getClass(), BRecordType.class); Assert.assertEquals(getType(tupleValue2).getName(), "Student"); - Assert.assertEquals(((BMap) tupleValue2).size(), 4); + Assert.assertEquals(((BMap) tupleValue2).size(), 4); - Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("name")).toString(), "Raja"); - Assert.assertEquals(getType(((BMap) tupleValue2).get(StringUtils.fromString("name"))).getClass(), + Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("name")).toString(), "Raja"); + Assert.assertEquals(getType(((BMap) tupleValue2).get(StringUtils.fromString("name"))).getClass(), BStringType.class); - Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("status")).toString(), "single"); - Assert.assertEquals(getType(((BMap) tupleValue2).get(StringUtils.fromString("status"))).getClass(), + Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("status")).toString(), "single"); + Assert.assertEquals(getType(((BMap) tupleValue2).get(StringUtils.fromString("status"))).getClass(), BStringType.class); - Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("batch")).toString(), "LK2014"); - Assert.assertEquals(getType(((BMap) tupleValue2).get(StringUtils.fromString("batch"))).getClass(), + Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("batch")).toString(), "LK2014"); + Assert.assertEquals(getType(((BMap) tupleValue2).get(StringUtils.fromString("batch"))).getClass(), BStringType.class); - Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("school")).toString(), "Hindu College"); - Assert.assertEquals(getType(((BMap) tupleValue2).get(StringUtils.fromString("school"))).getClass(), + Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("school")).toString(), + "Hindu College"); + Assert.assertEquals(getType(((BMap) tupleValue2).get(StringUtils.fromString("school"))).getClass(), BStringType.class); - Assert.assertEquals(((BMap) tupleValue1).get(StringUtils.fromString("school")).toString(), "Royal College"); - Assert.assertEquals(getType(((BMap) tupleValue1).get(StringUtils.fromString("school"))).getClass(), + Assert.assertEquals(((BMap) tupleValue1).get(StringUtils.fromString("school")).toString(), + "Royal College"); + Assert.assertEquals(getType(((BMap) tupleValue1).get(StringUtils.fromString("school"))).getClass(), BStringType.class); } @@ -250,11 +254,11 @@ public void testStampJSONToBasicArray() { BArray valueArray = (BArray) results; Assert.assertEquals(valueArray.size(), 4); - Assert.assertEquals(((BArray) results).getElementType().getTag(), TypeTags.INT_TAG); - Assert.assertEquals(((BArray) results).getInt(0), 1); - Assert.assertEquals(((BArray) results).getInt(1), 2); - Assert.assertEquals(((BArray) results).getInt(2), 3); - Assert.assertEquals(((BArray) results).getInt(3), 4); + Assert.assertEquals(valueArray.getElementType().getTag(), TypeTags.INT_TAG); + Assert.assertEquals(valueArray.getInt(0), 1); + Assert.assertEquals(valueArray.getInt(1), 2); + Assert.assertEquals(valueArray.getInt(2), 3); + Assert.assertEquals(valueArray.getInt(3), 4); } @Test @@ -264,11 +268,11 @@ public void testStampAnydataToBasicArray() { BArray valueArray = (BArray) results; Assert.assertEquals(valueArray.size(), 4); - Assert.assertEquals(((BArray) results).getElementType().getTag(), TypeTags.INT_TAG); - Assert.assertEquals(((BArray) results).getInt(0), 1); - Assert.assertEquals(((BArray) results).getInt(1), 2); - Assert.assertEquals(((BArray) results).getInt(2), 3); - Assert.assertEquals(((BArray) results).getInt(3), 4); + Assert.assertEquals(valueArray.getElementType().getTag(), TypeTags.INT_TAG); + Assert.assertEquals(valueArray.getInt(0), 1); + Assert.assertEquals(valueArray.getInt(1), 2); + Assert.assertEquals(valueArray.getInt(2), 3); + Assert.assertEquals(valueArray.getInt(3), 4); } @Test @@ -278,11 +282,11 @@ public void testStampAnydataArrayToBasicArray() { BArray valueArray = (BArray) results; Assert.assertEquals(valueArray.size(), 4); - Assert.assertEquals(((BArray) results).getElementType().getTag(), TypeTags.INT_TAG); - Assert.assertEquals(((BArray) results).getInt(0), 1); - Assert.assertEquals(((BArray) results).getInt(1), 2); - Assert.assertEquals(((BArray) results).getInt(2), 3); - Assert.assertEquals(((BArray) results).getInt(3), 4); + Assert.assertEquals(valueArray.getElementType().getTag(), TypeTags.INT_TAG); + Assert.assertEquals(valueArray.getInt(0), 1); + Assert.assertEquals(valueArray.getInt(1), 2); + Assert.assertEquals(valueArray.getInt(2), 3); + Assert.assertEquals(valueArray.getInt(3), 4); } @Test @@ -292,11 +296,11 @@ public void testStampJSONArrayToBasicArray() { BArray valueArray = (BArray) results; Assert.assertEquals(valueArray.size(), 4); - Assert.assertEquals(((BArray) results).getElementType().getTag(), TypeTags.INT_TAG); - Assert.assertEquals(((BArray) results).getInt(0), 1); - Assert.assertEquals(((BArray) results).getInt(1), 2); - Assert.assertEquals(((BArray) results).getInt(2), 3); - Assert.assertEquals(((BArray) results).getInt(3), 4); + Assert.assertEquals(valueArray.getElementType().getTag(), TypeTags.INT_TAG); + Assert.assertEquals(valueArray.getInt(0), 1); + Assert.assertEquals(valueArray.getInt(1), 2); + Assert.assertEquals(valueArray.getInt(2), 3); + Assert.assertEquals(valueArray.getInt(3), 4); } @Test diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/stamp/JSONStampInbuiltFunctionTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/stamp/JSONStampInbuiltFunctionTest.java index b9ecd5af511a..65e05fe942b1 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/stamp/JSONStampInbuiltFunctionTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/stamp/JSONStampInbuiltFunctionTest.java @@ -95,9 +95,9 @@ public void testStampJSONToRecordV2() { Assert.assertEquals(mapValue0.getType().getName(), "Employee"); Assert.assertEquals((mapValue0).size(), 4); - Assert.assertEquals(((LinkedHashMap) mapValue0).get(StringUtils.fromString("school")).toString(), + Assert.assertEquals(((LinkedHashMap) mapValue0).get(StringUtils.fromString("school")).toString(), "Hindu College"); - Assert.assertEquals(getType(((LinkedHashMap) mapValue0).get(StringUtils.fromString("school"))).getClass(), + Assert.assertEquals(getType(((LinkedHashMap) mapValue0).get(StringUtils.fromString("school"))).getClass(), BStringType.class); } @@ -138,16 +138,18 @@ public void testStampJSONArrayToConstraintArray() { Assert.assertEquals(mapValue0.getType().getName(), "Student"); Assert.assertEquals((mapValue0).size(), 4); - Assert.assertEquals(((LinkedHashMap) mapValue0).get(StringUtils.fromString("batch")).toString(), "LK2014"); - Assert.assertEquals(getType(((LinkedHashMap) mapValue0).get(StringUtils.fromString("batch"))).getClass(), + Assert.assertEquals(((LinkedHashMap) mapValue0).get(StringUtils.fromString("batch")).toString(), + "LK2014"); + Assert.assertEquals(getType(((LinkedHashMap) mapValue0).get(StringUtils.fromString("batch"))).getClass(), BStringType.class); Assert.assertEquals(mapValue1.getType().getClass(), BRecordType.class); Assert.assertEquals(mapValue1.getType().getName(), "Student"); Assert.assertEquals((mapValue1).size(), 4); - Assert.assertEquals(((LinkedHashMap) mapValue1).get(StringUtils.fromString("batch")).toString(), "LK2014"); - Assert.assertEquals(getType(((LinkedHashMap) mapValue0).get(StringUtils.fromString("batch"))).getClass(), + Assert.assertEquals(((LinkedHashMap) mapValue1).get(StringUtils.fromString("batch")).toString(), + "LK2014"); + Assert.assertEquals(getType(((LinkedHashMap) mapValue0).get(StringUtils.fromString("batch"))).getClass(), BStringType.class); } @@ -164,7 +166,7 @@ public void testStampJSONArrayToAnydataTypeArray() { Assert.assertEquals(getType(results.get(1)).getTag(), TypeTags.BOOLEAN_TAG); Assert.assertEquals(results.get(2).toString(), "foo"); Assert.assertEquals(getType(results.get(2)).getClass(), BStringType.class); - Assert.assertEquals((((BMap) results.get(3))).size(), 2); + Assert.assertEquals((((BMap) results.get(3))).size(), 2); Assert.assertEquals(getType(results.get(3)).getClass(), BMapType.class); Assert.assertEquals(((BMapType) getType(results.get(3))).getConstrainedType().getClass(), BAnydataType.class); } @@ -197,7 +199,7 @@ public void testStampJSONArrayWithNullToAnydataArray() { Assert.assertEquals(results.get(2).toString(), "foo"); Assert.assertEquals(getType(results.get(2)).getClass(), BStringType.class); Assert.assertNull(results.get(3)); - Assert.assertEquals((((BMap) results.get(4))).size(), 2); + Assert.assertEquals((((BMap) results.get(4))).size(), 2); Assert.assertEquals(getType(results.get(4)).getClass(), BMapType.class); Assert.assertEquals(((BMapType) getType(results.get(4))).getConstrainedType().getClass(), BAnydataType.class); } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/stamp/MapStampInbuiltFunctionTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/stamp/MapStampInbuiltFunctionTest.java index ed29e7c02ea9..6a80f98f45ab 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/stamp/MapStampInbuiltFunctionTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/stamp/MapStampInbuiltFunctionTest.java @@ -256,18 +256,18 @@ public void testStampAnydataMapToSimilarOpenRecordMap() { Assert.assertEquals(mapValue.size(), 2); Assert.assertEquals(getType(mapValue.get(StringUtils.fromString("a"))).getName(), "Employee"); - Assert.assertEquals(getType(((BMap) mapValue.get(StringUtils.fromString("a"))).get( + Assert.assertEquals(getType(((BMap) mapValue.get(StringUtils.fromString("a"))).get( StringUtils.fromString("age"))).getTag(), TypeTags.INT_TAG); - Assert.assertEquals(getType(((BMap) mapValue.get(StringUtils.fromString("a"))).get( + Assert.assertEquals(getType(((BMap) mapValue.get(StringUtils.fromString("a"))).get( StringUtils.fromString("school"))). getClass(), BStringType.class); Assert.assertEquals(getType(mapValue.get(StringUtils.fromString("b"))).getName(), "Employee"); - Assert.assertEquals(getType(((BMap) mapValue.get(StringUtils.fromString("b"))).get( + Assert.assertEquals(getType(((BMap) mapValue.get(StringUtils.fromString("b"))).get( StringUtils.fromString("age"))).getTag(), TypeTags.INT_TAG); - Assert.assertEquals(getType(((BMap) mapValue.get(StringUtils.fromString("b"))).get( + Assert.assertEquals(getType(((BMap) mapValue.get(StringUtils.fromString("b"))).get( StringUtils.fromString("school"))). getClass(), BStringType.class); } @@ -291,9 +291,9 @@ public void testStampRecordMapToAnydataMap() { Assert.assertEquals(mapValue.size(), 2); Assert.assertEquals(getType(mapValue.get(StringUtils.fromString("a"))).getClass(), BMapType.class); - Assert.assertEquals(((BMap) mapValue.get(StringUtils.fromString("a"))).size(), 5); + Assert.assertEquals(((BMap) mapValue.get(StringUtils.fromString("a"))).size(), 5); Assert.assertEquals(getType(mapValue.get(StringUtils.fromString("b"))).getClass(), BMapType.class); - Assert.assertEquals(((BMap) mapValue.get(StringUtils.fromString("b"))).size(), 5); + Assert.assertEquals(((BMap) mapValue.get(StringUtils.fromString("b"))).size(), 5); } @Test @@ -306,18 +306,20 @@ public void testStampRecordMapToSimilarOpenRecordMap() { Assert.assertEquals(getType(mapValue.get(StringUtils.fromString("a"))).getName(), "Employee"); Assert.assertEquals( - getType(((BMap) mapValue.get(StringUtils.fromString("a"))).get(StringUtils.fromString("age"))).getTag(), + getType(((BMap) mapValue.get(StringUtils.fromString("a"))) + .get(StringUtils.fromString("age"))).getTag(), TypeTags.INT_TAG); Assert.assertEquals( - getType(((BMap) mapValue.get(StringUtils.fromString("a"))).get(StringUtils.fromString("school"))). + getType(((BMap) mapValue.get(StringUtils.fromString("a"))).get(StringUtils.fromString("school"))). getClass(), BStringType.class); Assert.assertEquals(getType(mapValue.get(StringUtils.fromString("b"))).getName(), "Employee"); Assert.assertEquals( - getType(((BMap) mapValue.get(StringUtils.fromString("b"))).get(StringUtils.fromString("age"))).getTag(), + getType(((BMap) mapValue.get(StringUtils.fromString("b"))) + .get(StringUtils.fromString("age"))).getTag(), TypeTags.INT_TAG); Assert.assertEquals( - getType(((BMap) mapValue.get(StringUtils.fromString("b"))).get(StringUtils.fromString("school"))). + getType(((BMap) mapValue.get(StringUtils.fromString("b"))).get(StringUtils.fromString("school"))). getClass(), BStringType.class); } @@ -346,10 +348,12 @@ public void testStampAnydataToIntMultiDimensionMap() { Assert.assertEquals(mapValue.size(), 2); Assert.assertEquals( - getType(((BMap) ((BMap) mapValue.get(StringUtils.fromString("a"))).get(StringUtils.fromString("aa"))) + getType(((BMap) ((BMap) mapValue.get(StringUtils.fromString("a"))) + .get(StringUtils.fromString("aa"))) .get(StringUtils.fromString("aa"))).getTag(), TypeTags.INT_TAG); Assert.assertEquals( - ((BMap) ((BMap) mapValue.get(StringUtils.fromString("a"))).get(StringUtils.fromString("aa"))) + ((BMap) ((BMap) mapValue.get(StringUtils.fromString("a"))) + .get(StringUtils.fromString("aa"))) .get(StringUtils.fromString("aa")).toString(), "11"); } @@ -362,11 +366,12 @@ public void testStampIntToAnydataMultiDimensionMap() { Assert.assertEquals(mapValue.size(), 2); Assert.assertEquals(mapValue.size(), 2); - Assert.assertEquals(getType(((BMap) ((BMap) mapValue.get(StringUtils.fromString("a"))).get( + Assert.assertEquals(getType(((BMap) ((BMap) mapValue.get(StringUtils.fromString("a"))).get( StringUtils.fromString("aa"))).get(StringUtils.fromString("aa"))).getTag(), TypeTags.INT_TAG); Assert.assertEquals( - ((BMap) ((BMap) mapValue.get(StringUtils.fromString("a"))).get(StringUtils.fromString("aa"))).get( + ((BMap) ((BMap) mapValue.get(StringUtils.fromString("a"))) + .get(StringUtils.fromString("aa"))).get( StringUtils.fromString("aa")).toString(), "11"); } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/stamp/RecordStampInbuiltFunctionTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/stamp/RecordStampInbuiltFunctionTest.java index 33f1d31aa76d..9b97ceb2ff6a 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/stamp/RecordStampInbuiltFunctionTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/stamp/RecordStampInbuiltFunctionTest.java @@ -127,9 +127,9 @@ public void testStampRecordToJSON() { Assert.assertEquals(((BMapType) mapValue0.getType()).getConstrainedType().getClass(), BJsonType.class); Assert.assertEquals((mapValue0).size(), 4); - Assert.assertEquals(((LinkedHashMap) mapValue0).get(StringUtils.fromString("school")).toString(), + Assert.assertEquals(((LinkedHashMap) mapValue0).get(StringUtils.fromString("school")).toString(), "Hindu College"); - Assert.assertEquals(getType(((LinkedHashMap) mapValue0).get(StringUtils.fromString("school"))).getClass(), + Assert.assertEquals(getType(((LinkedHashMap) mapValue0).get(StringUtils.fromString("school"))).getClass(), BStringType.class); } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/stamp/TupleTypeStampInbuiltFunctionTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/stamp/TupleTypeStampInbuiltFunctionTest.java index fd6642d6a4f2..02889199545b 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/stamp/TupleTypeStampInbuiltFunctionTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/stamp/TupleTypeStampInbuiltFunctionTest.java @@ -67,26 +67,27 @@ public void testStampTupleValueV1() { Assert.assertEquals(getType(tupleValue2).getClass(), BRecordType.class); Assert.assertEquals(getType(tupleValue2).getName(), "Teacher"); - Assert.assertEquals(((BMap) tupleValue2).size(), 5); + Assert.assertEquals(((BMap) tupleValue2).size(), 5); - Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("name")).toString(), "Raja"); - Assert.assertEquals(getType(((BMap) tupleValue2).get(StringUtils.fromString("name"))).getClass(), + Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("name")).toString(), "Raja"); + Assert.assertEquals(getType(((BMap) tupleValue2).get(StringUtils.fromString("name"))).getClass(), BStringType.class); - Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("age")).toString(), "25"); - Assert.assertEquals(getType(((BMap) tupleValue2).get(StringUtils.fromString("age"))).getTag(), + Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("age")).toString(), "25"); + Assert.assertEquals(getType(((BMap) tupleValue2).get(StringUtils.fromString("age"))).getTag(), TypeTags.INT_TAG); - Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("status")).toString(), "single"); - Assert.assertEquals(getType(((BMap) tupleValue2).get(StringUtils.fromString("status"))).getClass(), + Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("status")).toString(), "single"); + Assert.assertEquals(getType(((BMap) tupleValue2).get(StringUtils.fromString("status"))).getClass(), BStringType.class); - Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("batch")).toString(), "LK2014"); - Assert.assertEquals(getType(((BMap) tupleValue2).get(StringUtils.fromString("batch"))).getClass(), + Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("batch")).toString(), "LK2014"); + Assert.assertEquals(getType(((BMap) tupleValue2).get(StringUtils.fromString("batch"))).getClass(), BStringType.class); - Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("school")).toString(), "Hindu College"); - Assert.assertEquals(getType(((BMap) tupleValue2).get(StringUtils.fromString("school"))).getClass(), + Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("school")).toString(), + "Hindu College"); + Assert.assertEquals(getType(((BMap) tupleValue2).get(StringUtils.fromString("school"))).getClass(), BStringType.class); } @@ -106,26 +107,27 @@ public void testStampTupleValueV2() { Assert.assertEquals(getType(tupleValue2).getClass(), BRecordType.class); Assert.assertEquals(getType(tupleValue2).getName(), "Employee"); - Assert.assertEquals(((BMap) tupleValue2).size(), 5); + Assert.assertEquals(((BMap) tupleValue2).size(), 5); - Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("name")).toString(), "Raja"); - Assert.assertEquals(getType(((BMap) tupleValue2).get(StringUtils.fromString("name"))).getClass(), + Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("name")).toString(), "Raja"); + Assert.assertEquals(getType(((BMap) tupleValue2).get(StringUtils.fromString("name"))).getClass(), BStringType.class); - Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("age")).toString(), "25"); - Assert.assertEquals(getType(((BMap) tupleValue2).get(StringUtils.fromString("age"))).getTag(), + Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("age")).toString(), "25"); + Assert.assertEquals(getType(((BMap) tupleValue2).get(StringUtils.fromString("age"))).getTag(), TypeTags.INT_TAG); - Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("status")).toString(), "single"); - Assert.assertEquals(getType(((BMap) tupleValue2).get(StringUtils.fromString("status"))).getClass(), + Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("status")).toString(), "single"); + Assert.assertEquals(getType(((BMap) tupleValue2).get(StringUtils.fromString("status"))).getClass(), BStringType.class); - Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("batch")).toString(), "LK2014"); - Assert.assertEquals(getType(((BMap) tupleValue2).get(StringUtils.fromString("batch"))).getClass(), + Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("batch")).toString(), "LK2014"); + Assert.assertEquals(getType(((BMap) tupleValue2).get(StringUtils.fromString("batch"))).getClass(), BStringType.class); - Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("school")).toString(), "Hindu College"); - Assert.assertEquals(getType(((BMap) tupleValue2).get(StringUtils.fromString("school"))).getClass(), + Assert.assertEquals(((BMap) tupleValue2).get(StringUtils.fromString("school")).toString(), + "Hindu College"); + Assert.assertEquals(getType(((BMap) tupleValue2).get(StringUtils.fromString("school"))).getClass(), BStringType.class); } @@ -162,22 +164,23 @@ public void testStampTupleValueToArray() { Assert.assertEquals(getType(arrayValue2).getClass(), BRecordType.class); Assert.assertEquals(getType(arrayValue2).getName(), "Employee"); - Assert.assertEquals(((BMap) arrayValue2).size(), 4); + Assert.assertEquals(((BMap) arrayValue2).size(), 4); - Assert.assertEquals(((BMap) arrayValue2).get(StringUtils.fromString("name")).toString(), "Raja"); - Assert.assertEquals(getType(((BMap) arrayValue2).get(StringUtils.fromString("name"))).getClass(), + Assert.assertEquals(((BMap) arrayValue2).get(StringUtils.fromString("name")).toString(), "Raja"); + Assert.assertEquals(getType(((BMap) arrayValue2).get(StringUtils.fromString("name"))).getClass(), BStringType.class); - Assert.assertEquals(((BMap) arrayValue2).get(StringUtils.fromString("status")).toString(), "single"); - Assert.assertEquals(getType(((BMap) arrayValue2).get(StringUtils.fromString("status"))).getClass(), + Assert.assertEquals(((BMap) arrayValue2).get(StringUtils.fromString("status")).toString(), "single"); + Assert.assertEquals(getType(((BMap) arrayValue2).get(StringUtils.fromString("status"))).getClass(), BStringType.class); - Assert.assertEquals(((BMap) arrayValue2).get(StringUtils.fromString("batch")).toString(), "LK2014"); - Assert.assertEquals(getType(((BMap) arrayValue2).get(StringUtils.fromString("batch"))).getClass(), + Assert.assertEquals(((BMap) arrayValue2).get(StringUtils.fromString("batch")).toString(), "LK2014"); + Assert.assertEquals(getType(((BMap) arrayValue2).get(StringUtils.fromString("batch"))).getClass(), BStringType.class); - Assert.assertEquals(((BMap) arrayValue2).get(StringUtils.fromString("school")).toString(), "Hindu College"); - Assert.assertEquals(getType(((BMap) arrayValue2).get(StringUtils.fromString("school"))).getClass(), + Assert.assertEquals(((BMap) arrayValue2).get(StringUtils.fromString("school")).toString(), + "Hindu College"); + Assert.assertEquals(getType(((BMap) arrayValue2).get(StringUtils.fromString("school"))).getClass(), BStringType.class); } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/stamp/UnionTypeStampInbuiltFunctionTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/stamp/UnionTypeStampInbuiltFunctionTest.java index 23cd8658cdd6..09c8c5b4639f 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/stamp/UnionTypeStampInbuiltFunctionTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/stamp/UnionTypeStampInbuiltFunctionTest.java @@ -150,24 +150,24 @@ public void testStampUnionToConstraintMapToUnion() { Assert.assertEquals(constrainedType.getName(), "Teacher"); Assert.assertEquals(getType(employee0.get(StringUtils.fromString("a"))).getName(), "Teacher"); - Assert.assertEquals(getType(((BMap) employee0.get(StringUtils.fromString("a"))).get( + Assert.assertEquals(getType(((BMap) employee0.get(StringUtils.fromString("a"))).get( StringUtils.fromString("age"))).getTag(), TypeTags.INT_TAG); - Assert.assertEquals(getType(((BMap) employee0.get(StringUtils.fromString("a"))).get( + Assert.assertEquals(getType(((BMap) employee0.get(StringUtils.fromString("a"))).get( StringUtils.fromString("school"))).getClass(), BStringType.class); - Assert.assertEquals(getType(((BMap) employee0.get(StringUtils.fromString("a"))).get( + Assert.assertEquals(getType(((BMap) employee0.get(StringUtils.fromString("a"))).get( StringUtils.fromString("batch"))).getClass(), BStringType.class); Assert.assertEquals(getType(employee0.get(StringUtils.fromString("b"))).getName(), "Teacher"); - Assert.assertEquals(getType(((BMap) employee0.get(StringUtils.fromString("b"))).get( + Assert.assertEquals(getType(((BMap) employee0.get(StringUtils.fromString("b"))).get( StringUtils.fromString("age"))).getTag(), TypeTags.INT_TAG); - Assert.assertEquals(getType(((BMap) employee0.get(StringUtils.fromString("b"))).get( + Assert.assertEquals(getType(((BMap) employee0.get(StringUtils.fromString("b"))).get( StringUtils.fromString("school"))).getClass(), BStringType.class); - Assert.assertEquals(getType(((BMap) employee0.get(StringUtils.fromString("b"))).get( + Assert.assertEquals(getType(((BMap) employee0.get(StringUtils.fromString("b"))).get( StringUtils.fromString("batch"))).getClass(), BStringType.class); } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/typecast/TypeCastExprTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/typecast/TypeCastExprTest.java index d82a4b53fe26..1a1138915746 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/typecast/TypeCastExprTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/typecast/TypeCastExprTest.java @@ -88,7 +88,7 @@ public void testIncompatibleStringToFloat() { Object returns = BRunUtil.invoke(result, "stringtofloat", args); Assert.assertTrue(returns instanceof BError); BError error = (BError) returns; - String errorMsg = ((BMap) error.getDetails()).get(StringUtils.fromString("message")).toString(); + String errorMsg = ((BMap) error.getDetails()).get(StringUtils.fromString("message")).toString(); Assert.assertEquals(errorMsg, "'string' value '2222.333f' cannot be converted to 'float'"); } @@ -226,7 +226,7 @@ public void testIncompatibleJsonToInt() { Object returns = BRunUtil.invoke(result, "testIncompatibleJsonToInt"); Assert.assertTrue(returns instanceof BError); BError error = (BError) returns; - String errorMsg = ((BMap) error.getDetails()).get(StringUtils.fromString("message")).toString(); + String errorMsg = ((BMap) error.getDetails()).get(StringUtils.fromString("message")).toString(); Assert.assertEquals(errorMsg, "'string' value '\"hello\"' cannot be converted to 'int'"); } @@ -235,7 +235,7 @@ public void testIncompatibleJsonToFloat() { Object returns = BRunUtil.invoke(result, "testIncompatibleJsonToFloat"); Assert.assertTrue(returns instanceof BError); BError error = (BError) returns; - String errorMsg = ((BMap) error.getDetails()).get(StringUtils.fromString("message")).toString(); + String errorMsg = ((BMap) error.getDetails()).get(StringUtils.fromString("message")).toString(); Assert.assertEquals(errorMsg, "'string' value '\"hello\"' cannot be converted to 'float'"); } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/typecast/TypeCastExpressionsTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/typecast/TypeCastExpressionsTest.java index 2f7f9964d8e4..874bea5794fc 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/typecast/TypeCastExpressionsTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/typecast/TypeCastExpressionsTest.java @@ -207,16 +207,16 @@ public Object[][] stringAsStringTests() { public void testUntaintedWithoutType() { Object returns = BRunUtil.invoke(result, "testContexuallyExpectedType"); Assert.assertTrue(returns instanceof BMap); - Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("name")).toString(), "Em Zee"); - Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("id")).toString(), "1100"); + Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("name")).toString(), "Em Zee"); + Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("id")).toString(), "1100"); } @Test public void testUntaintedWithoutType2() { Object returns = BRunUtil.invoke(result, "testContexuallyExpectedTypeRecContext"); Assert.assertTrue(returns instanceof BMap); - Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("name")).toString(), "Em Zee"); - Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("id")).toString(), "1100"); + Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("name")).toString(), "Em Zee"); + Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("id")).toString(), "1100"); } @DataProvider diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/typecast/ValueTypeCastExprTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/typecast/ValueTypeCastExprTest.java index 4277549f1b13..8377e87f6348 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/typecast/ValueTypeCastExprTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/typecast/ValueTypeCastExprTest.java @@ -106,7 +106,7 @@ public void testIncompatibleStringToFloat() { Object returns = BRunUtil.invoke(result, "stringToFloat", args); Assert.assertTrue(returns instanceof BError); BError error = (BError) returns; - String errorMsg = ((BMap) error.getDetails()).get(StringUtils.fromString("message")).toString(); + String errorMsg = ((BMap) error.getDetails()).get(StringUtils.fromString("message")).toString(); Assert.assertEquals(errorMsg, "'string' value '2222.333f' cannot be converted to 'float'"); } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/varref/ErrorVariableReferenceTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/varref/ErrorVariableReferenceTest.java index 2c7745bfd306..622828d9fd7a 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/varref/ErrorVariableReferenceTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/varref/ErrorVariableReferenceTest.java @@ -57,11 +57,11 @@ public void testBasicErrorVariableWithMapDetails() { Assert.assertEquals(returns.get(1).toString(), "Error One"); Assert.assertEquals(returns.get(2).toString(), "Error Two"); Assert.assertEquals(returns.get(3).toString(), "Error Two"); - Assert.assertEquals(((BMap) returns.get(4)).get(StringUtils.fromString("message")).toString(), "Msg One"); + Assert.assertEquals(((BMap) returns.get(4)).get(StringUtils.fromString("message")).toString(), "Msg One"); Assert.assertEquals(returns.get(5).toString(), "Msg One"); Assert.assertEquals(returns.get(6).toString(), "Detail Msg"); - Assert.assertEquals(((BMap) returns.get(7)).get(StringUtils.fromString("message")).toString(), "Msg Two"); - Assert.assertTrue((Boolean) ((BMap) returns.get(7)).get(StringUtils.fromString("fatal"))); + Assert.assertEquals(((BMap) returns.get(7)).get(StringUtils.fromString("message")).toString(), "Msg Two"); + Assert.assertTrue((Boolean) ((BMap) returns.get(7)).get(StringUtils.fromString("fatal"))); Assert.assertEquals(returns.get(8).toString(), "Msg Two"); Assert.assertTrue((Boolean) returns.get(9)); } @@ -75,11 +75,13 @@ public void testBasicErrorVariableWithConstAndMap() { Assert.assertEquals(returns.get(1).toString(), "Some Error One"); Assert.assertEquals(returns.get(2).toString(), "Some Error Two"); Assert.assertEquals(returns.get(3).toString(), "Some Error Two"); - Assert.assertEquals(((BMap) returns.get(4)).get(StringUtils.fromString("message")).toString(), "Msg Three"); + Assert.assertEquals(((BMap) returns.get(4)).get(StringUtils.fromString("message")).toString(), + "Msg Three"); Assert.assertEquals(returns.get(5).toString(), "Msg Three"); Assert.assertEquals(returns.get(6).toString(), "Detail Msg"); - Assert.assertEquals(((BMap) returns.get(7)).get(StringUtils.fromString("message")).toString(), "Msg Four"); - Assert.assertTrue((Boolean) ((BMap) returns.get(7)).get(StringUtils.fromString("fatal"))); + Assert.assertEquals(((BMap) returns.get(7)).get(StringUtils.fromString("message")).toString(), + "Msg Four"); + Assert.assertTrue((Boolean) ((BMap) returns.get(7)).get(StringUtils.fromString("fatal"))); Assert.assertEquals(returns.get(8).toString(), "Msg Four"); Assert.assertTrue((Boolean) returns.get(9)); Assert.assertEquals(returns.get(10).toString(), @@ -95,7 +97,7 @@ public void testBasicErrorVariableWithRecordDetails() { Assert.assertEquals(returns.get(1).toString(), "Error One"); Assert.assertEquals(returns.get(2).toString(), "Something Wrong"); Assert.assertTrue((Boolean) returns.get(3)); - Assert.assertEquals(((BMap) returns.get(4)).get(StringUtils.fromString("message")).toString(), + Assert.assertEquals(((BMap) returns.get(4)).get(StringUtils.fromString("message")).toString(), "Something Wrong"); } @@ -159,7 +161,7 @@ public void testErrorInRecordWithDestructure2() { @Test(description = "Test simple error var def inside tuple with destructuring error") public void testErrorWithRestParam() { Object returns = BRunUtil.invoke(result, "testErrorWithRestParam"); - BMap results = (BMap) returns; + BMap results = (BMap) returns; Assert.assertEquals(results.get(StringUtils.fromString("fatal")).toString(), "true"); Assert.assertEquals(results.get(StringUtils.fromString("extra")).toString(), "extra"); } @@ -170,7 +172,7 @@ public void testErrorWithUnderscore() { BArray returns = (BArray) arr; Assert.assertEquals(returns.size(), 2); Assert.assertEquals(returns.get(0).toString(), "Error"); - BMap results = (BMap) returns.get(1); + BMap results = (BMap) returns.get(1); Assert.assertEquals(results.get(StringUtils.fromString("message")).toString(), "Fatal"); Assert.assertEquals(results.get(StringUtils.fromString("fatal")).toString(), "true"); } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/varref/RecordVariableReferenceTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/varref/RecordVariableReferenceTest.java index 365a24f33648..9a0438d701c3 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/varref/RecordVariableReferenceTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/varref/RecordVariableReferenceTest.java @@ -62,8 +62,8 @@ public void testRecVarRefInsideRecVarRefInsideRecVarRef() { Object arr = BRunUtil.invoke(result, "testRecVarRefInsideRecVarRefInsideRecVarRef"); BArray returns = (BArray) arr; Assert.assertEquals(returns.size(), 4); - Assert.assertEquals(((BMap) returns.get(0)).get(StringUtils.fromString("mKey1")), 1L); - Assert.assertEquals(((BMap) returns.get(0)).get(StringUtils.fromString("mKey2")), 2L); + Assert.assertEquals(((BMap) returns.get(0)).get(StringUtils.fromString("mKey1")), 1L); + Assert.assertEquals(((BMap) returns.get(0)).get(StringUtils.fromString("mKey2")), 2L); Assert.assertEquals(returns.get(1), 12L); Assert.assertEquals(returns.get(2).toString(), "SomeVar1"); Assert.assertNull(returns.get(3)); @@ -72,8 +72,8 @@ public void testRecVarRefInsideRecVarRefInsideRecVarRef() { @Test(description = "Test simple record variable definition") public void testRestParam() { Object returns = BRunUtil.invoke(result, "testRestParam"); - Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("var3")), 12L); - Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("var4")).toString(), "text"); + Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("var3")), 12L); + Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("var4")).toString(), "text"); } @Test(description = "Test simple record variable definition") @@ -81,11 +81,11 @@ public void testRecordTypeInRecordVarRef() { Object arr = BRunUtil.invoke(result, "testRecordTypeInRecordVarRef"); BArray returns = (BArray) arr; Assert.assertEquals(returns.size(), 3); - Assert.assertEquals(((BMap) returns.get(0)).get(StringUtils.fromString("mKey1")), 1L); - Assert.assertEquals(((BMap) returns.get(0)).get(StringUtils.fromString("mKey2")), 2L); + Assert.assertEquals(((BMap) returns.get(0)).get(StringUtils.fromString("mKey1")), 1L); + Assert.assertEquals(((BMap) returns.get(0)).get(StringUtils.fromString("mKey2")), 2L); Assert.assertEquals(returns.get(1), 12L); - Assert.assertEquals((((BMap) returns.get(2)).get(StringUtils.fromString("var1"))).toString(), "SomeVar1"); - Assert.assertNull(((BMap) returns.get(2)).get(StringUtils.fromString("var2"))); + Assert.assertEquals((((BMap) returns.get(2)).get(StringUtils.fromString("var1"))).toString(), "SomeVar1"); + Assert.assertNull(((BMap) returns.get(2)).get(StringUtils.fromString("var2"))); } @Test(description = "Test tuple var ref inside record var ref") @@ -112,11 +112,11 @@ public void testRecordInsideTupleInsideRecord() { Assert.assertEquals(((BArray) returns.get(0)).getString(0), "A"); Assert.assertEquals(((BArray) returns.get(0)).getString(1), "B"); Assert.assertEquals(returns.get(1).toString(), "A"); - BMap child = (BMap) ((BMap) returns.get(2)).get(StringUtils.fromString("child")); + BMap child = (BMap) ((BMap) returns.get(2)).get(StringUtils.fromString("child")); Assert.assertEquals(child.get(StringUtils.fromString("name")).toString(), "C"); Assert.assertEquals((((BArray) child.get(StringUtils.fromString("yearAndAge"))).getRefValue(0)), 1996L); - Assert.assertEquals(((BMap) ((BArray) child.get(StringUtils.fromString("yearAndAge"))).getRefValue(1)).get( - StringUtils.fromString("format")).toString(), + Assert.assertEquals(((BMap) ((BArray) child.get(StringUtils.fromString("yearAndAge"))) + .getRefValue(1)).get(StringUtils.fromString("format")).toString(), "Z"); } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/functions/FunctionSignatureTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/functions/FunctionSignatureTest.java index a25fcd086b9e..be7cbd55fec1 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/functions/FunctionSignatureTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/functions/FunctionSignatureTest.java @@ -448,9 +448,7 @@ public void defaultValueForObjectFunctionParam() { Assert.assertEquals(returns.get(1).toString(), "inner default world"); } - public static ArrayValue mockedNativeFuncWithOptionalParams(long a, double b, - io.ballerina.runtime.api.values.BString c, long d, - io.ballerina.runtime.api.values.BString e) { + public static ArrayValue mockedNativeFuncWithOptionalParams(long a, double b, BString c, long d, BString e) { BTupleType tupleType = new BTupleType( Arrays.asList(PredefinedTypes.TYPE_INT, PredefinedTypes.TYPE_FLOAT, PredefinedTypes.TYPE_STRING, PredefinedTypes.TYPE_INT, PredefinedTypes.TYPE_STRING)); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/functions/FunctionsWithDefaultableParametersTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/functions/FunctionsWithDefaultableParametersTest.java index 9c8418414f93..74e07bfaa501 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/functions/FunctionsWithDefaultableParametersTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/functions/FunctionsWithDefaultableParametersTest.java @@ -91,25 +91,25 @@ public void testRecordAsDefaultExpr() { Assert.assertTrue(returns.get(2) instanceof BMap); Assert.assertTrue(returns.get(3) instanceof BMap); - BMap bMap = (BMap) returns.get(0); + BMap bMap = (BMap) returns.get(0); Assert.assertEquals(bMap.get(StringUtils.fromString("a")).toString(), "default"); Assert.assertEquals(bMap.get(StringUtils.fromString("b")), 50L); Assert.assertFalse((Boolean) bMap.get(StringUtils.fromString("c"))); Assert.assertEquals(bMap.get(StringUtils.fromString("d")), 11.1); - bMap = (BMap) returns.get(1); + bMap = (BMap) returns.get(1); Assert.assertEquals(bMap.get(StringUtils.fromString("a")).toString(), "f2"); Assert.assertEquals(bMap.get(StringUtils.fromString("b")), 200L); Assert.assertFalse((Boolean) bMap.get(StringUtils.fromString("c"))); Assert.assertEquals(bMap.get(StringUtils.fromString("d")), 44.4); - bMap = (BMap) returns.get(2); + bMap = (BMap) returns.get(2); Assert.assertEquals(bMap.get(StringUtils.fromString("a")).toString(), "f1"); Assert.assertEquals(bMap.get(StringUtils.fromString("b")), 100L); Assert.assertTrue((Boolean) bMap.get(StringUtils.fromString("c"))); Assert.assertEquals(bMap.get(StringUtils.fromString("d")), 22.2); - bMap = (BMap) returns.get(3); + bMap = (BMap) returns.get(3); Assert.assertEquals(bMap.get(StringUtils.fromString("a")).toString(), "default2"); Assert.assertEquals(bMap.get(StringUtils.fromString("b")), 150L); Assert.assertTrue((Boolean) bMap.get(StringUtils.fromString("c"))); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/javainterop/DependentlyTypedFunctionsTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/javainterop/DependentlyTypedFunctionsTest.java index 71306004571c..983759523093 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/javainterop/DependentlyTypedFunctionsTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/javainterop/DependentlyTypedFunctionsTest.java @@ -179,6 +179,8 @@ public void testNegatives() { validateError(errors, indx++, "incompatible type for parameter 't' with inferred typedesc value: expected " + "'typedesc<(int|string)>', found 'typedesc'", 369, 17); validateError(errors, indx++, "incompatible types: expected 'TargetType', found 'typedesc'", 371, 64); + validateError(errors, indx++, "incompatible type for parameter 'td' with inferred typedesc value: expected " + + "'typedesc', found 'typedesc'", 383, 24); Assert.assertEquals(errors.getErrorCount(), indx); } @@ -237,7 +239,8 @@ public Object[][] getFuncNames() { {"testDependentlyTypedMethodCallOnObjectType"}, {"testDependentlyTypedMethodCallOnObjectTypeWithInferredArgument"}, {"testDependentlyTypedFunctionWithInferredArgForParamOfTypeReferenceType"}, - {"testDependentlyTypedResourceMethods"} + {"testDependentlyTypedResourceMethods"}, + {"testDependentlyTypedFunctionWithTypeReferenceType"} }; } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/javainterop/RefTypeNegativeTests.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/javainterop/RefTypeNegativeTests.java index fe06be1a0813..9a4fd0c88e24 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/javainterop/RefTypeNegativeTests.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/javainterop/RefTypeNegativeTests.java @@ -104,7 +104,7 @@ public static Object acceptAndReturnImmutableArray(ArrayValue a) { public static void acceptReadOnlyValue(long r) { } - public static BFuture returnReadOnlyValue(FPValue f) { + public static BFuture returnReadOnlyValue(FPValue f) { return new FutureValue(null, null, null); // OK since not used anywhere. } } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/javainterop/RefTypeTests.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/javainterop/RefTypeTests.java index bb5075ebc5e4..e19a04e4f30a 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/javainterop/RefTypeTests.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/javainterop/RefTypeTests.java @@ -85,7 +85,7 @@ public void testInteropWithRefTypesAndMapReturn() { Object returns = BRunUtil.invoke(result, "interopWithRefTypesAndMapReturn"); Assert.assertTrue(returns instanceof BMap); - BMap bMap = (BMap) returns; + BMap bMap = (BMap) returns; Assert.assertEquals(bMap.toString(), "{\"a\":object Person,\"b\":[5,\"hello\",object Person]," + "\"c\":{\"name\":\"sameera\"},\"e\":object Person,\"f\":83,\"g\":{\"name\":\"sample\"}}"); } @@ -306,7 +306,7 @@ public void testGetHandle() { Assert.assertTrue(returns instanceof HandleValue); HandleValue handle = (HandleValue) returns; Assert.assertTrue(handle.getValue() instanceof Map); - Map map = (Map) handle.getValue(); + Map map = (Map) handle.getValue(); Assert.assertEquals(map.size(), 1); Assert.assertEquals(map.get("name"), "John"); } @@ -360,7 +360,7 @@ public static XmlValue getXML() { return new XmlItem(new QName("hello")); } - public static io.ballerina.runtime.api.values.BString getStringFromXML(XmlValue x) { + public static BString getStringFromXML(XmlValue x) { return StringUtils.fromString(x.toString()); } @@ -392,15 +392,15 @@ public static Object acceptAny(Object x) { return x; } - public static int useFunctionPointer(FPValue fp) { + public static int useFunctionPointer(FPValue fp) { return ((Long) fp.call(new Object[]{Scheduler.getStrand(), 3, 4})).intValue(); } - public static FPValue getFunctionPointer(Object fp) { - return (FPValue) fp; + public static FPValue getFunctionPointer(Object fp) { + return (FPValue) fp; } - public static io.ballerina.runtime.api.values.BString useTypeDesc(TypedescValue type) { + public static BString useTypeDesc(TypedescValue type) { return StringUtils.fromString(type.stringValue(null)); } @@ -422,7 +422,7 @@ public static HandleValue getHandle() { return new HandleValue(m); } - public static io.ballerina.runtime.api.values.BString useHandle(HandleValue h) { + public static BString useHandle(HandleValue h) { Map m = (Map) h.getValue(); return StringUtils.fromString(m.get("name")); } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/javainterop/RefTypeWithBValueAPITests.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/javainterop/RefTypeWithBValueAPITests.java index abebb5ac2566..ff57370cd4fc 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/javainterop/RefTypeWithBValueAPITests.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/javainterop/RefTypeWithBValueAPITests.java @@ -24,8 +24,12 @@ import io.ballerina.runtime.api.utils.StringUtils; import io.ballerina.runtime.api.values.BArray; import io.ballerina.runtime.api.values.BError; +import io.ballerina.runtime.api.values.BFunctionPointer; +import io.ballerina.runtime.api.values.BFuture; import io.ballerina.runtime.api.values.BMap; +import io.ballerina.runtime.api.values.BObject; import io.ballerina.runtime.api.values.BString; +import io.ballerina.runtime.api.values.BTypedesc; import io.ballerina.runtime.api.values.BXml; import io.ballerina.runtime.internal.scheduling.Scheduler; import io.ballerina.runtime.internal.types.BArrayType; @@ -86,7 +90,7 @@ public void testInteropWithRefTypesAndMapReturn() { Object returns = BRunUtil.invoke(result, "interopWithRefTypesAndMapReturn"); Assert.assertTrue(returns instanceof BMap); - BMap bMap = (BMap) returns; + BMap bMap = (BMap) returns; Assert.assertEquals(bMap.toString(), "{\"a\":object Person,\"b\":[5,\"hello\",object Person]," + "\"c\":{\"name\":\"sameera\"},\"e\":object Person,\"f\":83,\"g\":{\"name\":\"sample\"}}"); } @@ -281,8 +285,7 @@ public void testGetFuture() { // static methods // This scenario is for map value to be passed to interop and return array value. - public static io.ballerina.runtime.api.values.BArray - getArrayValueFromMap(io.ballerina.runtime.api.values.BString key, io.ballerina.runtime.api.values.BMap mapValue) { + public static BArray getArrayValueFromMap(BString key, BMap mapValue) { BArray arrayValue = new ArrayValueImpl(new BArrayType(PredefinedTypes.TYPE_INT)); arrayValue.add(0, 1); long fromMap = (long) mapValue.get(key); @@ -290,12 +293,9 @@ public void testGetFuture() { return arrayValue; } - public static io.ballerina.runtime.api.values.BMap - acceptRefTypesAndReturnMap(io.ballerina.runtime.api.values.BObject a, - io.ballerina.runtime.api.values.BArray b, Object c, - BError d, Object e, Object f, - io.ballerina.runtime.api.values.BMap g) { - io.ballerina.runtime.api.values.BMap mapValue = new MapValueImpl(); + public static BMap acceptRefTypesAndReturnMap(BObject a, BArray b, Object c, BError d, Object e, Object f, + BMap g) { + BMap mapValue = new MapValueImpl<>(); mapValue.put("a", a); mapValue.put("b", b); mapValue.put("c", c); @@ -306,27 +306,20 @@ public void testGetFuture() { } public static Object acceptIntUnionReturn(int flag) { - switch (flag) { - case 1: - return 25; - case 2: - return StringUtils.fromString("sample value return"); - case 3: - return 54.88; - default: - return true; - } - } - - public static io.ballerina.runtime.api.values.BObject - acceptObjectAndObjectReturn(io.ballerina.runtime.api.values.BObject p, int newVal) { + return switch (flag) { + case 1 -> 25; + case 2 -> StringUtils.fromString("sample value return"); + case 3 -> 54.88; + default -> true; + }; + } + + public static BObject acceptObjectAndObjectReturn(BObject p, int newVal) { p.set(StringUtils.fromString("age"), newVal); return p; } - public static io.ballerina.runtime.api.values.BMap - acceptRecordAndRecordReturn(io.ballerina.runtime.api.values.BMap e, - io.ballerina.runtime.api.values.BString newVal) { + public static BMap acceptRecordAndRecordReturn(BMap e, BString newVal) { e.put(StringUtils.fromString("name"), newVal); return e; } @@ -335,35 +328,26 @@ public static int acceptIntReturnIntThrowsCheckedException(long a) throws JavaIn return (int) (a + 5); } - public static io.ballerina.runtime.api.values.BMap - acceptRecordAndRecordReturnWhichThrowsCheckedException(io.ballerina.runtime.api.values.BMap e, - io.ballerina.runtime.api.values.BString newVal) - throws JavaInteropTestCheckedException { + public static BMap acceptRecordAndRecordReturnWhichThrowsCheckedException( + BMap e, BString newVal) throws JavaInteropTestCheckedException { e.put("name", newVal); return e; } public static Object acceptIntUnionReturnWhichThrowsCheckedException(int flag) throws JavaInteropTestCheckedException { - switch (flag) { - case 1: - return 25; - case 2: - return "sample value return"; - case 3: - return 54.88; - default: - return true; - } - } - - public static io.ballerina.runtime.api.values.BMap - acceptRefTypesAndReturnMapWhichThrowsCheckedException(io.ballerina.runtime.api.values.BObject a, - io.ballerina.runtime.api.values.BArray b, Object c, - BError d, Object e, - Object f, io.ballerina.runtime.api.values.BMap g) + return switch (flag) { + case 1 -> 25; + case 2 -> "sample value return"; + case 3 -> 54.88; + default -> true; + }; + } + + public static BMap acceptRefTypesAndReturnMapWhichThrowsCheckedException( + BObject a, BArray b, Object c, BError d, Object e, Object f, BMap g) throws JavaInteropTestCheckedException { - io.ballerina.runtime.api.values.BMap mapValue = new MapValueImpl<>(); + BMap mapValue = new MapValueImpl<>(); mapValue.put("a", a); mapValue.put("b", b); mapValue.put("c", c); @@ -373,14 +357,12 @@ public static Object acceptIntUnionReturnWhichThrowsCheckedException(int flag) return mapValue; } - public static BError acceptStringErrorReturnWhichThrowsCheckedException( - io.ballerina.runtime.api.values.BString msg) + public static BError acceptStringErrorReturnWhichThrowsCheckedException(BString msg) throws JavaInteropTestCheckedException { return ErrorCreator.createError(msg, new MapValueImpl<>(PredefinedTypes.TYPE_ERROR_DETAIL)); } - public static BArray getArrayValueFromMapWhichThrowsCheckedException(io.ballerina.runtime.api.values.BString key, - io.ballerina.runtime.api.values.BMap mapValue) + public static BArray getArrayValueFromMapWhichThrowsCheckedException(BString key, BMap mapValue) throws JavaInteropTestCheckedException { BArray arrayValue = new ArrayValueImpl(new BArrayType(PredefinedTypes.TYPE_INT)); arrayValue.add(0, 1); @@ -389,32 +371,28 @@ public static BArray getArrayValueFromMapWhichThrowsCheckedException(io.ballerin return arrayValue; } - public static boolean acceptServiceObjectAndReturnBoolean(io.ballerina.runtime.api.values.BObject serviceObject) { + public static boolean acceptServiceObjectAndReturnBoolean(BObject serviceObject) { return TypeTags.SERVICE_TAG == getType(serviceObject).getTag(); } - public static BError acceptStringErrorReturn(io.ballerina.runtime.api.values.BString msg) { + public static BError acceptStringErrorReturn(BString msg) { return ErrorCreator.createError(msg); } public static Object getJson() { - MapValueImpl map = - new MapValueImpl<>(PredefinedTypes.TYPE_JSON); + MapValueImpl map = new MapValueImpl<>(PredefinedTypes.TYPE_JSON); map.put(StringUtils.fromString("name"), StringUtils.fromString("John")); return map; } - public static io.ballerina.runtime.api.values.BMap getJsonObject() { - io.ballerina.runtime.api.values.BMap - map = new MapValueImpl<>(PredefinedTypes.TYPE_JSON); + public static BMap getJsonObject() { + BMap map = new MapValueImpl<>(PredefinedTypes.TYPE_JSON); map.put(StringUtils.fromString("name"), StringUtils.fromString("Doe")); return map; } - public static io.ballerina.runtime.api.values.BArray getJsonArray() { - io.ballerina.runtime.api.values.BArray array = new ArrayValueImpl(new BArrayType(PredefinedTypes.TYPE_JSON)); + public static BArray getJsonArray() { + BArray array = new ArrayValueImpl(new BArrayType(PredefinedTypes.TYPE_JSON)); array.add(0, (Object) StringUtils.fromString("John")); return array; } @@ -439,7 +417,7 @@ public static BXml getXML() { return new XmlItem(new QName("hello")); } - public static io.ballerina.runtime.api.values.BString getStringFromXML(BXml x) { + public static BString getStringFromXML(BXml x) { return StringUtils.fromString(x.toString()); } @@ -471,28 +449,27 @@ public static Object acceptAny(Object x) { return x; } - public static int useFunctionPointer(io.ballerina.runtime.api.values.BFunctionPointer fp) { + public static int useFunctionPointer(BFunctionPointer fp) { return ((Long) fp.call(new Object[]{Scheduler.getStrand(), 3, 4})).intValue(); } - public static io.ballerina.runtime.api.values.BFunctionPointer getFunctionPointer(Object fp) { - return (FPValue) fp; + public static BFunctionPointer getFunctionPointer(Object fp) { + return (FPValue) fp; } - public static io.ballerina.runtime.api.values.BString useTypeDesc( - io.ballerina.runtime.api.values.BTypedesc type) { + public static BString useTypeDesc(BTypedesc type) { return StringUtils.fromString(type.stringValue(null)); } - public static io.ballerina.runtime.api.values.BTypedesc getTypeDesc() { + public static BTypedesc getTypeDesc() { return new TypedescValueImpl(PredefinedTypes.TYPE_XML); } - public static Object useFuture(io.ballerina.runtime.api.values.BFuture future) { + public static Object useFuture(BFuture future) { return future.getResult(); } - public static io.ballerina.runtime.api.values.BFuture getFuture(Object a) { + public static BFuture getFuture(Object a) { return (FutureValue) a; } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/javainterop/basic/InstanceMethodTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/javainterop/basic/InstanceMethodTest.java index b0ac3d99dbcf..75f109d224b0 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/javainterop/basic/InstanceMethodTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/javainterop/basic/InstanceMethodTest.java @@ -222,12 +222,13 @@ public void testErrorDetail() { Assert.assertEquals(getType(returns).getName(), "error"); Assert.assertEquals(((BError) returns).getMessage(), "org.ballerinalang.nativeimpl.jvm.tests.JavaInteropTestCheckedException"); - Assert.assertEquals(((BMap) ((BError) returns).getDetails()).get(StringUtils.fromString("message")).toString(), + Assert.assertEquals(((BMap) ((BError) returns).getDetails()).get(StringUtils.fromString("message")) + .toString(), "Custom error"); - BError cause = (BError) ((BMap) ((BError) returns).getDetails()).get(StringUtils.fromString("cause")); + BError cause = (BError) ((BMap) ((BError) returns).getDetails()).get(StringUtils.fromString("cause")); Assert.assertEquals(getType(cause).getName(), "error"); Assert.assertEquals(cause.getMessage(), "java.lang.Throwable"); - Assert.assertEquals(((BMap) cause.getDetails()).get(StringUtils.fromString("message")).toString(), + Assert.assertEquals(((BMap) cause.getDetails()).get(StringUtils.fromString("message")).toString(), "Interop Throwable"); } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/javainterop/overloading/pkg/SportsCar.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/javainterop/overloading/pkg/SportsCar.java index cf9447316bba..d1934e3ac594 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/javainterop/overloading/pkg/SportsCar.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/javainterop/overloading/pkg/SportsCar.java @@ -33,6 +33,7 @@ public String getDescription(String prefix) { return prefix + " seat count: " + seatCount; } + @Override public long getSeatCount() { return seatCount; } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/jvm/AnonymousFunctionsTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/jvm/AnonymousFunctionsTest.java index cf3f83b9ad76..8dab901535bc 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/jvm/AnonymousFunctionsTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/jvm/AnonymousFunctionsTest.java @@ -1,77 +1,77 @@ - /* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - package org.ballerinalang.test.jvm; +/* + * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ballerinalang.test.jvm; - import org.ballerinalang.test.BCompileUtil; - import org.ballerinalang.test.BRunUtil; - import org.ballerinalang.test.CompileResult; - import org.testng.Assert; - import org.testng.annotations.AfterClass; - import org.testng.annotations.BeforeClass; - import org.testng.annotations.Test; +import org.ballerinalang.test.BCompileUtil; +import org.ballerinalang.test.BRunUtil; +import org.ballerinalang.test.CompileResult; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; - /** - * Test cases to cover anonymous functions related tests on JBallerina. - * - * @since 0.995.0 - */ +/** + * Test cases to cover anonymous functions related tests on JBallerina. + * + * @since 0.995.0 + */ - public class AnonymousFunctionsTest { +public class AnonymousFunctionsTest { - private CompileResult compileResult; + private CompileResult compileResult; - @BeforeClass - public void setup() { - compileResult = BCompileUtil.compile("test-src/jvm/anon-funcs.bal"); - } + @BeforeClass + public void setup() { + compileResult = BCompileUtil.compile("test-src/jvm/anon-funcs.bal"); + } - @Test(description = "Test anon call") - public void testAnonCall() { - Object result = BRunUtil.invoke(compileResult, "testAnonFunc"); - Assert.assertEquals(result.toString(), "Hello World.!!!"); - } + @Test(description = "Test anon call") + public void testAnonCall() { + Object result = BRunUtil.invoke(compileResult, "testAnonFunc"); + Assert.assertEquals(result.toString(), "Hello World.!!!"); + } - @Test(description = "Test fp passing between methods") - public void testFPPassing() { - Object result = BRunUtil.invoke(compileResult, "testFPPassing"); - Assert.assertEquals(result.toString(), "200"); - } + @Test(description = "Test fp passing between methods") + public void testFPPassing() { + Object result = BRunUtil.invoke(compileResult, "testFPPassing"); + Assert.assertEquals(result.toString(), "200"); + } - @Test(description = "Test basic closures") - public void testBasicClosure() { - Object result = BRunUtil.invoke(compileResult, "testBasicClosure"); - Assert.assertEquals(result.toString(), "242"); - } + @Test(description = "Test basic closures") + public void testBasicClosure() { + Object result = BRunUtil.invoke(compileResult, "testBasicClosure"); + Assert.assertEquals(result.toString(), "242"); + } - @Test(description = "Test multilevel closures") - public void testMultilevelClosures() { - Object result = BRunUtil.invoke(compileResult, "testMultilevelClosure"); - Assert.assertEquals(result.toString(), "72"); - } + @Test(description = "Test multilevel closures") + public void testMultilevelClosures() { + Object result = BRunUtil.invoke(compileResult, "testMultilevelClosure"); + Assert.assertEquals(result.toString(), "72"); + } - @Test(description = "Test basic worker") - public void testWorkerBasic() { - Object result = BRunUtil.invoke(compileResult, "basicWorkerTest"); - Assert.assertEquals(result.toString(), "120"); - } + @Test(description = "Test basic worker") + public void testWorkerBasic() { + Object result = BRunUtil.invoke(compileResult, "basicWorkerTest"); + Assert.assertEquals(result.toString(), "120"); + } - @AfterClass - public void tearDown() { - compileResult = null; - } - } + @AfterClass + public void tearDown() { + compileResult = null; + } +} diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/jvm/BuiltinMethodTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/jvm/BuiltinMethodTest.java index 85dc3eeae24d..4b2e2fb74935 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/jvm/BuiltinMethodTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/jvm/BuiltinMethodTest.java @@ -45,7 +45,7 @@ public void setup() { public void testClone() { Object result = BRunUtil.invoke(compileResult, "testClone"); Assert.assertTrue(result instanceof BMap); - BMap bMap = (BMap) result; + BMap bMap = (BMap) result; Assert.assertEquals(bMap.get(StringUtils.fromString("test")).toString(), "sample"); } @@ -53,7 +53,7 @@ public void testClone() { public void testCloneAny() { Object result = BRunUtil.invoke(compileResult, "testCloneAny"); Assert.assertTrue(result instanceof BMap); - BMap bMap = (BMap) result; + BMap bMap = (BMap) result; Assert.assertEquals(bMap.get(StringUtils.fromString("test")).toString(), "sample"); } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/jvm/ErrorTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/jvm/ErrorTest.java index b6b9042712be..3b6cd1e264d1 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/jvm/ErrorTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/jvm/ErrorTest.java @@ -79,7 +79,7 @@ public void testSelfReferencingObject() { BRunUtil.invoke(compileResult, "testSelfReferencingError"); } - @Test(description = "Test runtime out of memory error", expectedExceptions = java.lang.RuntimeException.class, + @Test(description = "Test runtime out of memory error", expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = "error: \\{ballerina}OutOfMemoryError \\{\"message\":\"Java heap " + "space\"}.*") public void testRuntimeOOMError() { diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/jvm/TypesTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/jvm/TypesTest.java index 0e38e8e4c55e..f95075502a80 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/jvm/TypesTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/jvm/TypesTest.java @@ -162,6 +162,11 @@ public void testByteToIntCast() { Assert.assertEquals(intValue, input, "Invalid integer value returned."); } + @Test(description = "Test comparison between XML Sequence with one text member and xml:Text") + public void testXMLSequenceWithOneTextMemberToXMLTextCast() { + BRunUtil.invoke(compileResult, "testXMLSequenceWithOneTextMember"); + } + @Test(description = "Test integer to byte cast") public void testIntToByteCast() { int input = 123; @@ -592,7 +597,7 @@ public void testJsonArrayToJsonCasting() { expectedExceptionsMessageRegExp = "error: \\{ballerina\\}JSONOperationError \\{\"message\":\"JSON value " + "is not " + "a mapping\"\\}\n" + - "\tat types:testGetFromNull\\(types.bal:588\\)") + "\tat types:testGetFromNull\\(types.bal:595\\)") public void testGetFromNull() { BRunUtil.invoke(compileResult, "testGetFromNull"); } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/object/ObjectFunctionsWithDefaultableArguments.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/object/ObjectFunctionsWithDefaultableArguments.java index bbd6ff1deaff..738a4b58f61c 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/object/ObjectFunctionsWithDefaultableArguments.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/object/ObjectFunctionsWithDefaultableArguments.java @@ -57,7 +57,7 @@ public void testObjectInitWithDefaultValues() { Assert.assertEquals(bValueArray.getRefValue(2), 100L); Assert.assertEquals(bValueArray.getRefValue(3), 1.1); - BMap record = (BMap) bValueArray.getRefValue(4); + BMap record = (BMap) bValueArray.getRefValue(4); Assert.assertEquals(record.get(StringUtils.fromString("a")).toString(), "default"); Assert.assertEquals(record.get(StringUtils.fromString("b")), 50L); Assert.assertFalse((Boolean) record.get(StringUtils.fromString("c"))); @@ -73,7 +73,7 @@ public void testObjectInitWithDefaultValues() { Assert.assertEquals(bValueArray.getRefValue(2), 99L); Assert.assertEquals(bValueArray.getRefValue(3), 1.1); - record = (BMap) bValueArray.getRefValue(4); + record = (BMap) bValueArray.getRefValue(4); Assert.assertEquals(record.get(StringUtils.fromString("a")).toString(), "given2"); Assert.assertEquals(record.get(StringUtils.fromString("b")), 49L); Assert.assertTrue((Boolean) record.get(StringUtils.fromString("c"))); @@ -96,7 +96,7 @@ public void testObjectInitWithDefaultValues2() { Assert.assertEquals(bValueArray.getRefValue(1).toString(), "defdefault"); Assert.assertEquals(bValueArray.getRefValue(2), 101.1); - BMap record = (BMap) bValueArray.getRefValue(3); + BMap record = (BMap) bValueArray.getRefValue(3); Assert.assertEquals(record.get(StringUtils.fromString("a")).toString(), "default2"); Assert.assertEquals(record.get(StringUtils.fromString("b")), 150L); Assert.assertTrue((Boolean) record.get(StringUtils.fromString("c"))); @@ -107,7 +107,7 @@ public void testObjectInitWithDefaultValues2() { Assert.assertEquals(bValueArray.getRefValue(1).toString(), "defdefault"); Assert.assertEquals(bValueArray.getRefValue(2), 101.1); - record = (BMap) bValueArray.getRefValue(3); + record = (BMap) bValueArray.getRefValue(3); Assert.assertEquals(record.get(StringUtils.fromString("a")).toString(), "given"); Assert.assertEquals(record.get(StringUtils.fromString("b")), 49L); Assert.assertFalse((Boolean) record.get(StringUtils.fromString("c"))); @@ -125,7 +125,7 @@ public void testObjectAttachedFunction1() { Assert.assertEquals(bValueArray.getRefValue(0).toString(), "global"); Assert.assertEquals(bValueArray.getRefValue(1), 200L); - BMap record = (BMap) bValueArray.getRefValue(2); + BMap record = (BMap) bValueArray.getRefValue(2); Assert.assertEquals(record.get(StringUtils.fromString("a")).toString(), "default"); Assert.assertEquals(record.get(StringUtils.fromString("b")), 50L); Assert.assertFalse((Boolean) record.get(StringUtils.fromString("c"))); @@ -135,7 +135,7 @@ public void testObjectAttachedFunction1() { Assert.assertEquals(bValueArray.getRefValue(0).toString(), "given"); Assert.assertEquals(bValueArray.getRefValue(1), 200L); - record = (BMap) bValueArray.getRefValue(2); + record = (BMap) bValueArray.getRefValue(2); Assert.assertEquals(record.get(StringUtils.fromString("a")).toString(), "given2"); Assert.assertEquals(record.get(StringUtils.fromString("b")), 140L); Assert.assertTrue((Boolean) record.get(StringUtils.fromString("c"))); @@ -153,7 +153,7 @@ public void testObjectAttachedFunction2() { Assert.assertEquals(bValueArray.getRefValue(1).toString(), "defdefaultglobal"); Assert.assertEquals(bValueArray.getRefValue(2), 101.1); - BMap record = (BMap) bValueArray.getRefValue(3); + BMap record = (BMap) bValueArray.getRefValue(3); Assert.assertEquals(record.get(StringUtils.fromString("a")).toString(), "default2"); Assert.assertEquals(record.get(StringUtils.fromString("b")), 150L); Assert.assertTrue((Boolean) record.get(StringUtils.fromString("c"))); @@ -164,7 +164,7 @@ public void testObjectAttachedFunction2() { Assert.assertEquals(bValueArray.getRefValue(1).toString(), "given"); Assert.assertEquals(bValueArray.getRefValue(2), 101.1); - record = (BMap) bValueArray.getRefValue(3); + record = (BMap) bValueArray.getRefValue(3); Assert.assertEquals(record.get(StringUtils.fromString("a")).toString(), "given2"); Assert.assertEquals(record.get(StringUtils.fromString("b")), 140L); Assert.assertTrue((Boolean) record.get(StringUtils.fromString("c"))); @@ -181,7 +181,7 @@ public void testObjectAttachedFunction3() { Assert.assertEquals(bValueArray.getRefValue(0).toString(), "global"); Assert.assertEquals(bValueArray.getRefValue(1), 200L); - BMap record = (BMap) bValueArray.getRefValue(2); + BMap record = (BMap) bValueArray.getRefValue(2); Assert.assertEquals(record.get(StringUtils.fromString("a")).toString(), "default"); Assert.assertEquals(record.get(StringUtils.fromString("b")), 50L); Assert.assertFalse((Boolean) record.get(StringUtils.fromString("c"))); @@ -191,7 +191,7 @@ public void testObjectAttachedFunction3() { Assert.assertEquals(bValueArray.getRefValue(0).toString(), "given"); Assert.assertEquals(bValueArray.getRefValue(1), 200L); - record = (BMap) bValueArray.getRefValue(2); + record = (BMap) bValueArray.getRefValue(2); Assert.assertEquals(record.get(StringUtils.fromString("a")).toString(), "given2"); Assert.assertEquals(record.get(StringUtils.fromString("b")), 140L); Assert.assertTrue((Boolean) record.get(StringUtils.fromString("c"))); @@ -209,7 +209,7 @@ public void testObjectAttachedFunction4() { Assert.assertEquals(bValueArray.getRefValue(1).toString(), "defdefaultglobal"); Assert.assertEquals(bValueArray.getRefValue(2), 101.1); - BMap record = (BMap) bValueArray.getRefValue(3); + BMap record = (BMap) bValueArray.getRefValue(3); Assert.assertEquals(record.get(StringUtils.fromString("a")).toString(), "default2"); Assert.assertEquals((record.get(StringUtils.fromString("b"))), 150L); Assert.assertTrue((Boolean) record.get(StringUtils.fromString("c"))); @@ -220,7 +220,7 @@ public void testObjectAttachedFunction4() { Assert.assertEquals(bValueArray.getRefValue(1).toString(), "given"); Assert.assertEquals(bValueArray.getRefValue(2), 101.1); - record = (BMap) bValueArray.getRefValue(3); + record = (BMap) bValueArray.getRefValue(3); Assert.assertEquals(record.get(StringUtils.fromString("a")).toString(), "given2"); Assert.assertEquals(record.get(StringUtils.fromString("b")), 140L); Assert.assertTrue((Boolean) record.get(StringUtils.fromString("c"))); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/object/ObjectTypeReferenceTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/object/ObjectTypeReferenceTest.java index 631d931afc41..28b7681a9627 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/object/ObjectTypeReferenceTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/object/ObjectTypeReferenceTest.java @@ -347,6 +347,14 @@ public void testTypeReferencedFunctionImplementation() { "'InvalidReadOnlyClassWithMissingImpls'", 101, 1); BAssertUtil.validateError(result, index++, "no implementation found for the method 'toString' of class " + "'InvalidReadOnlyClassWithMissingImpls'", 101, 1); + BAssertUtil.validateError(result, index++, "mismatched function signatures: expected 'remote " + + "function execute(string, int)', found 'public function execute(string, int)'", 115, 5); + BAssertUtil.validateError(result, index++, "mismatched function signatures: expected 'public function pause" + + "(string, int)', found 'remote function pause(string, int)'", 118, 5); + BAssertUtil.validateError(result, index++, "mismatched function signatures: expected 'remote " + + "function execute(string, int)', found 'public function execute(string, int)'", 125, 5); + BAssertUtil.validateError(result, index++, "mismatched function signatures: expected 'public function pause" + + "(string, int)', found 'remote function pause(string, int)'", 127, 5); Assert.assertEquals(result.getErrorCount(), index); } @@ -391,4 +399,9 @@ public void testOverridingIncludedFieldInObjectTypeDescWithReadOnlyIntersection( public void testInclusionWithDifferentParamNames() { BRunUtil.invoke(compileResult, "testInclusionWithDifferentParamNames"); } + + @Test + public void testInclusionWithRemoteMethods() { + BRunUtil.invoke(compileResult, "testInclusionWithRemoteMethods"); + } } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/object/ReadonlyObjectTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/object/ReadonlyObjectTest.java index 6069ca34238e..496ce1def87a 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/object/ReadonlyObjectTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/object/ReadonlyObjectTest.java @@ -50,7 +50,8 @@ public Object[] readOnlyObjectTests() { "testReadOnlyServiceClass", "testReadOnlyClassIntersectionWithMismatchedQualifiersRuntimeNegative", "testReadOnlyClassIntersectionWithValidQualifiers", - "testRecursiveObjectArrayReadonlyClone" + "testRecursiveObjectArrayReadonlyClone", + "testReadonlyObjectMethodCall" }; } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/packaging/PathConverterIntegrationTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/packaging/PathConverterIntegrationTest.java index e2b7c4fffcae..a15c7e71edd9 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/packaging/PathConverterIntegrationTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/packaging/PathConverterIntegrationTest.java @@ -83,15 +83,16 @@ public void teardown() throws IOException { Files.delete(tempFile); Files.delete(tempSemVerFile); Files.delete(tempNonSourceFile); - Files.walk(tempDirectory) - .sorted(Comparator.reverseOrder()) - .filter(Files::isDirectory) - .forEach(path -> { - try { - Files.delete(path); - } catch (IOException e) { - Assert.fail(e.getMessage(), e); - } - }); + try (Stream paths = Files.walk(tempDirectory)) { + paths.sorted(Comparator.reverseOrder()) + .filter(Files::isDirectory) + .forEach(path -> { + try { + Files.delete(path); + } catch (IOException e) { + Assert.fail(e.getMessage(), e); + } + }); + } } } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/packaging/PattenTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/packaging/PattenTest.java index 54e6ccc37ed7..0b24d88e1237 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/packaging/PattenTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/packaging/PattenTest.java @@ -12,7 +12,6 @@ import java.util.List; import java.util.function.BiFunction; import java.util.function.Function; -import java.util.stream.Collectors; import java.util.stream.Stream; import static org.wso2.ballerinalang.compiler.packaging.Patten.path; @@ -67,7 +66,7 @@ public void testReduction() { null, null); Patten subject = new Patten(path("hello", "world")); - List strings = subject.convert(mock, null).collect(Collectors.toList()); + List strings = subject.convert(mock, null).toList(); Assert.assertEquals(strings, Collections.singletonList("root-dir > hello > world")); } @@ -82,7 +81,7 @@ public void testDirExpansion() { null, null); Patten subject = new Patten(Patten.LATEST_VERSION_DIR); - List strings = subject.convert(mock, null).collect(Collectors.toList()); + List strings = subject.convert(mock, null).toList(); Assert.assertEquals(strings, Arrays.asList("root-dir > cache1", "root-dir > cache2", @@ -117,7 +116,7 @@ public void testBalExpansion() { s + " > dir2 > dir3 > f.bal"), null); Patten subject = new Patten(Patten.WILDCARD_SOURCE); - List strings = subject.convert(mock, null).collect(Collectors.toList()); + List strings = subject.convert(mock, null).toList(); Assert.assertEquals(strings, Arrays.asList("project-dir > dir1 > x.bal", "project-dir > y.bal", @@ -157,7 +156,7 @@ public void testReductionAndExpansion() { q + " > dir2 > dir3 > f.bal"), null); Patten subject = new Patten(path("hello"), Patten.LATEST_VERSION_DIR, path("world"), Patten.WILDCARD_SOURCE); - List strings = subject.convert(mock, null).collect(Collectors.toList()); + List strings = subject.convert(mock, null).toList(); Assert.assertEquals(strings, Arrays.asList("my-dir > hello > cache1 > world > dir1 > x.bal", "my-dir > hello > cache1 > world > y.bal", diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/packaging/RepoTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/packaging/RepoTest.java index a3aa22b59753..1ce66292e7f9 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/packaging/RepoTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/packaging/RepoTest.java @@ -103,7 +103,7 @@ public void testBinaryRepo() { @Test public void testSystemOrgIsReserved() { PackageID pkg = newPackageID("ballerina", "any.pkg", "10.2.3"); - Repo subject = new NonSysRepo(null) { + Repo subject = new NonSysRepo<>(null) { @Override public Patten calculateNonSysPkg(PackageID pkg) { Assert.fail("Tried to calculate path for system packages"); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/packaging/URIConverterTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/packaging/URIConverterTest.java index c348b325ef32..ec78a1567929 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/packaging/URIConverterTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/packaging/URIConverterTest.java @@ -27,7 +27,6 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; -import java.util.stream.Collectors; import static org.wso2.ballerinalang.compiler.packaging.Patten.path; @@ -43,7 +42,7 @@ public void testURIConverter() { URIConverter subject = new URIConverter(baseURI, new HashMap<>()); List urls = patten.convert(subject, null) - .collect(Collectors.toList()); + .toList(); URI expected = URI.create("http://staging.central.ballerina.io:9090/modules/natasha/foo.bar/1.0.5/"); Assert.assertEquals(urls, Collections.singletonList(expected)); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/query/MultipleFromClauseTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/query/MultipleFromClauseTest.java index ef0b9124ba0e..4cfa846bc82a 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/query/MultipleFromClauseTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/query/MultipleFromClauseTest.java @@ -326,10 +326,10 @@ public void testQueryExprWithOpenRecords() { Assert.assertEquals(returnValues.size(), 4, "Expected events are not received"); - BMap section1 = (BMap) returnValues.get(0); - BMap section2 = (BMap) returnValues.get(1); - BMap section3 = (BMap) returnValues.get(2); - BMap section4 = (BMap) returnValues.get(3); + BMap section1 = (BMap) returnValues.get(0); + BMap section2 = (BMap) returnValues.get(1); + BMap section3 = (BMap) returnValues.get(2); + BMap section4 = (BMap) returnValues.get(3); Assert.assertTrue(section1.get(StringUtils.fromString("grades")) instanceof BMap); Assert.assertEquals(section1.get(StringUtils.fromString("grades")).toString(), @@ -366,10 +366,10 @@ public void testQueryExprRecordTypedBinding() { Assert.assertEquals(returnValues.size(), 4, "Expected events are not received"); - BMap person1 = (BMap) returnValues.get(0); - BMap person2 = (BMap) returnValues.get(1); - BMap person3 = (BMap) returnValues.get(2); - BMap person4 = (BMap) returnValues.get(3); + BMap person1 = (BMap) returnValues.get(0); + BMap person2 = (BMap) returnValues.get(1); + BMap person3 = (BMap) returnValues.get(2); + BMap person4 = (BMap) returnValues.get(3); Assert.assertTrue(person1.get(StringUtils.fromString("address")) instanceof BMap); Assert.assertEquals(person1.toString(), "{\"firstName\":\"Alex\",\"lastName\":\"George\"," + diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/query/QueryWithClosuresTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/query/QueryWithClosuresTest.java index dac74ba5952f..9f31317cfc2f 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/query/QueryWithClosuresTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/query/QueryWithClosuresTest.java @@ -52,7 +52,7 @@ public Object[] dataToTestQueryWithClosures() { "testClosuresInQueryInLet", "testClosuresInNestedQueryInSelect", "testClosuresInNestedQueryInSelect2", -// "testClosureInQueryActionInDo2" #39760 + "testClosureInQueryActionInDo2", "testClosureInQueryActionInDo3", "testClosureInQueryActionInDo4", "testClosureInQueryActionInDo5", diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/query/SimpleQueryExpressionWithDefinedTypeTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/query/SimpleQueryExpressionWithDefinedTypeTest.java index e38fd37d4269..f9c219606de7 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/query/SimpleQueryExpressionWithDefinedTypeTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/query/SimpleQueryExpressionWithDefinedTypeTest.java @@ -252,8 +252,8 @@ public void testOthersAssociatedWithRecordTypes() { Assert.assertNotNull(returnValues); Assert.assertEquals(returnValues.size(), 2, "Expected events are not received"); - BMap teacher1 = (BMap) returnValues.get(0); - BMap teacher2 = (BMap) returnValues.get(1); + BMap teacher1 = (BMap) returnValues.get(0); + BMap teacher2 = (BMap) returnValues.get(1); Assert.assertTrue(teacher1.get(StringUtils.fromString("classStudents")) instanceof BArray); Assert.assertTrue(teacher1.get(StringUtils.fromString("experience")) instanceof BMap); @@ -298,8 +298,8 @@ public void testQueryExprWithTypeConversion() { Assert.assertNotNull(returnValues); Assert.assertEquals(returnValues.size(), 2, "Expected events are not received"); - BMap person1 = (BMap) returnValues.get(0); - BMap person2 = (BMap) returnValues.get(1); + BMap person1 = (BMap) returnValues.get(0); + BMap person2 = (BMap) returnValues.get(1); Assert.assertEquals(person1.toString(), "{\"firstName\":\"Alex\",\"lastName\":\"George\"," + "\"deptAccess\":\"XYZ\",\"address\":{\"city\":\"New York\",\"country\":\"America\"}}"); @@ -312,7 +312,7 @@ public void testQueryExprWithStreamMapAndFilter() { BArray returnValues = (BArray) BRunUtil.invoke(result, "testQueryExprWithStreamMapAndFilter"); Assert.assertNotNull(returnValues); - BMap subscription = (BMap) returnValues.get(0); + BMap subscription = (BMap) returnValues.get(0); Assert.assertEquals(subscription.toString(), "{\"firstName\":\"Ranjan\",\"lastName\":\"Fonseka\",\"score\":90.6,\"" + @@ -332,8 +332,8 @@ public void testQueryWithRecordVarInLetClause() { BArray returnValues = (BArray) BRunUtil.invoke(result, "testQueryWithRecordVarInLetClause"); Assert.assertNotNull(returnValues); Assert.assertEquals(returnValues.size(), 2, "Expected events are not received"); - BMap person1 = (BMap) returnValues.get(0); - BMap person2 = (BMap) returnValues.get(1); + BMap person1 = (BMap) returnValues.get(0); + BMap person2 = (BMap) returnValues.get(1); Assert.assertEquals(person1.toString(), "{\"firstName\":\"Ranjan\",\"lastName\":\"Fonseka\"," + "\"deptAccess\":\"XYZ\",\"address\":{\"city\":\"Colombo\",\"country\":\"SL\"}}"); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/ClosedRecordEquivalencyTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/ClosedRecordEquivalencyTest.java index 40882f0b3307..c8e48a459c14 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/ClosedRecordEquivalencyTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/ClosedRecordEquivalencyTest.java @@ -105,7 +105,7 @@ public void testRuntimeEqPublicStructs1() { @Test(description = "Test case for record equivalence") public void testRecordEquivalence() { Object returns = BRunUtil.invoke(compileResult, "testRecordEquivalence"); - BMap foo = (BMap) returns; + BMap foo = (BMap) returns; Assert.assertEquals(foo.size(), 6); Assert.assertEquals(foo.get(StringUtils.fromString("a")).toString(), "A"); @@ -119,7 +119,7 @@ public void testRecordEquivalence() { @Test(description = "Test case for using records with unordered fields in a match") public void testUnorderedFieldRecordsInAMatch() { Object returns = BRunUtil.invoke(compileResult, "testUnorderedFieldRecordsInAMatch"); - BMap foo = (BMap) returns; + BMap foo = (BMap) returns; Assert.assertEquals(foo.size(), 6); Assert.assertEquals(foo.get(StringUtils.fromString("a")).toString(), "A"); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/ClosedRecordIterationTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/ClosedRecordIterationTest.java index 4419c8581223..021c5d2d63fb 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/ClosedRecordIterationTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/ClosedRecordIterationTest.java @@ -124,7 +124,7 @@ public void testForeachWithClosedRecords() { Assert.assertEquals(values.getRefValue(1), 25L); Assert.assertTrue(values.getRefValue(2) instanceof BMap); - BMap addressRecord = (BMap) values.getRefValue(2); + BMap addressRecord = (BMap) values.getRefValue(2); Assert.assertEquals(addressRecord.get(StringUtils.fromString("street")).toString(), "Palm Grove"); Assert.assertEquals(addressRecord.get(StringUtils.fromString("city")).toString(), "Colombo 3"); } @@ -137,7 +137,7 @@ public void testForeachWithOpenRecords2() { Assert.assertEquals(returns.get(1), 25L); Assert.assertTrue(returns.get(2) instanceof BMap); - BMap addressRecord = (BMap) returns.get(2); + BMap addressRecord = (BMap) returns.get(2); Assert.assertEquals(addressRecord.get(StringUtils.fromString("street")).toString(), "Palm Grove"); Assert.assertEquals(addressRecord.get(StringUtils.fromString("city")).toString(), "Colombo 3"); } @@ -150,7 +150,7 @@ public void testForeachOpWithClosedRecords() { Assert.assertEquals(returns.get(1), 25L); Assert.assertTrue(returns.get(2) instanceof BMap); - BMap addressRecord = (BMap) returns.get(2); + BMap addressRecord = (BMap) returns.get(2); Assert.assertEquals(addressRecord.get(StringUtils.fromString("street")).toString(), "Palm Grove"); Assert.assertEquals(addressRecord.get(StringUtils.fromString("city")).toString(), "Colombo 3"); } @@ -160,12 +160,12 @@ public void testMapOpWithClosedRecords() { String[] expectedFields = new String[]{"name", "age", "address"}; Object returns = BRunUtil.invoke(result, "testMapOpWithClosedRecords"); - BMap person = (BMap) returns; + BMap person = (BMap) returns; Assert.assertEquals(person.get(StringUtils.fromString(expectedFields[0])).toString(), "john doe"); Assert.assertEquals((person.get(StringUtils.fromString(expectedFields[1]))), 25L); Assert.assertTrue(person.get(StringUtils.fromString(expectedFields[2])) instanceof BMap); - BMap addressRecord = (BMap) person.get(StringUtils.fromString(expectedFields[2])); + BMap addressRecord = (BMap) person.get(StringUtils.fromString(expectedFields[2])); Assert.assertEquals(addressRecord.get(StringUtils.fromString("street")).toString(), "Palm Grove"); Assert.assertEquals(addressRecord.get(StringUtils.fromString("city")).toString(), "Colombo 3"); } @@ -175,7 +175,7 @@ public void testFilterOpWithClosedRecords() { String[] expectedFields = new String[]{"a", "b", "c", "d", "e"}; Object returns = BRunUtil.invoke(result, "testFilterOpWithClosedRecords"); - BMap person = (BMap) returns; + BMap person = (BMap) returns; Assert.assertEquals(person.get(StringUtils.fromString(expectedFields[0])).toString(), "A"); Assert.assertNull(person.get(StringUtils.fromString(expectedFields[1]))); Assert.assertNull(person.get(StringUtils.fromString(expectedFields[2]))); @@ -192,7 +192,7 @@ public void testReduceOpWithClosedRecords() { @Test(description = "Test case for chained iterable operations on closed records") public void testChainedOpsWithClosedRecords() { Object returns = BRunUtil.invoke(result, "testChainedOpsWithClosedRecords"); - BMap foo = (BMap) returns; + BMap foo = (BMap) returns; Assert.assertNull(foo.get(StringUtils.fromString("a"))); Assert.assertEquals(foo.get(StringUtils.fromString("b")).toString(), "bb"); @@ -205,7 +205,7 @@ public void testChainedOpsWithClosedRecords() { public void testMapWithAllStringClosedRecord() { Object returns = BRunUtil.invoke(result, "testMapWithAllStringClosedRecord"); - BMap foo = (BMap) returns; + BMap foo = (BMap) returns; Assert.assertEquals(foo.get(StringUtils.fromString("a")).toString(), "aa"); Assert.assertEquals(foo.get(StringUtils.fromString("b")).toString(), "bb"); Assert.assertEquals(foo.get(StringUtils.fromString("c")).toString(), "cc"); @@ -218,7 +218,7 @@ public void testMapWithAllIntClosedRecord() { Object[] args = new Object[]{(80), (75), (65)}; Object returns = BRunUtil.invoke(result, "testMapWithAllIntClosedRecord", args); - BMap gradesMap = (BMap) returns; + BMap gradesMap = (BMap) returns; Assert.assertEquals((gradesMap.get(StringUtils.fromString("maths"))), 90L); Assert.assertEquals((gradesMap.get(StringUtils.fromString("physics"))), 85L); Assert.assertEquals((gradesMap.get(StringUtils.fromString("chemistry"))), 75L); @@ -230,7 +230,7 @@ public void testMapWithAllFloatClosedRecord() { Object[] args = new Object[]{(a), (b), (c)}; Object returns = BRunUtil.invoke(result, "testMapWithAllFloatClosedRecord", args); - BMap gradesMap = (BMap) returns; + BMap gradesMap = (BMap) returns; Assert.assertEquals((gradesMap.get(StringUtils.fromString("x"))), a + 10); Assert.assertEquals((gradesMap.get(StringUtils.fromString("y"))), b + 10); Assert.assertEquals((gradesMap.get(StringUtils.fromString("z"))), c + 10); @@ -241,7 +241,7 @@ public void testFilterWithAllStringClosedRecord() { final String a = "AA", e = "EE"; Object returns = BRunUtil.invoke(result, "testFilterWithAllStringClosedRecord"); - BMap foo = (BMap) returns; + BMap foo = (BMap) returns; Assert.assertEquals(foo.get(StringUtils.fromString("a")).toString(), a); Assert.assertNull(foo.get(StringUtils.fromString("b"))); Assert.assertNull(foo.get(StringUtils.fromString("c"))); @@ -254,7 +254,7 @@ public void testFilterWithAllIntClosedRecord() { final long m = 80, p = 75; Object returns = BRunUtil.invoke(result, "testFilterWithAllIntClosedRecord"); - BMap gradesMap = (BMap) returns; + BMap gradesMap = (BMap) returns; Assert.assertEquals((gradesMap.get(StringUtils.fromString("maths"))), m); Assert.assertEquals((gradesMap.get(StringUtils.fromString("physics"))), p); Assert.assertNull(gradesMap.get(StringUtils.fromString("chemistry"))); @@ -266,7 +266,7 @@ public void testFilterWithAllFloatClosedRecord() { Object[] args = new Object[]{(a), (b), (c)}; Object returns = BRunUtil.invoke(result, "testFilterWithAllFloatClosedRecord", args); - BMap gradesMap = (BMap) returns; + BMap gradesMap = (BMap) returns; Assert.assertEquals((gradesMap.get(StringUtils.fromString("x"))), a); Assert.assertEquals((gradesMap.get(StringUtils.fromString("y"))), b); Assert.assertNull(gradesMap.get(StringUtils.fromString("z"))); @@ -302,7 +302,7 @@ public void testTerminalOpsOnAllIntClosedRecord2() { @Test(description = "Test case for chained iterable operations on closed records") public void testChainedOpsWithClosedRecords2() { Object returns = BRunUtil.invoke(result, "testChainedOpsWithClosedRecords2"); - BMap grades = (BMap) returns; + BMap grades = (BMap) returns; Assert.assertEquals((grades.get(StringUtils.fromString("maths"))), 4.2); Assert.assertEquals((grades.get(StringUtils.fromString("physics"))), 4.2); @@ -325,7 +325,7 @@ public void testOpChainsWithTerminalOps() { @Test(description = "Test case for checking whether iterable ops mutate the original record") public void testMutability() { Object returns = BRunUtil.invoke(result, "testMutability"); - BMap grades = (BMap) returns; + BMap grades = (BMap) returns; Assert.assertEquals(grades.size(), 3); Assert.assertEquals(grades.get(StringUtils.fromString("maths")), 80L); Assert.assertEquals(grades.get(StringUtils.fromString("physics")), 75L); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/ClosedRecordOptionalFieldsTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/ClosedRecordOptionalFieldsTest.java index da2f74175d23..de28957edf0b 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/ClosedRecordOptionalFieldsTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/ClosedRecordOptionalFieldsTest.java @@ -62,12 +62,12 @@ public void testNegatives() { public void testNonDefReqField() { Object returns = BRunUtil.invoke(compileResult, "testNonDefReqField"); - BMap person = (BMap) returns; + BMap person = (BMap) returns; Assert.assertEquals(person.get(StringUtils.fromString("fname")).toString(), "default"); Assert.assertNull(person.get(StringUtils.fromString("lname"))); Assert.assertNull(person.get(StringUtils.fromString("age"))); - BMap adrs = (BMap) person.get(StringUtils.fromString("adrs")); + BMap adrs = (BMap) person.get(StringUtils.fromString("adrs")); Assert.assertEquals(adrs.get(StringUtils.fromString("street")).toString(), ""); Assert.assertEquals(adrs.get(StringUtils.fromString("city")).toString(), ""); Assert.assertEquals(adrs.get(StringUtils.fromString("country")).toString(), "LK"); @@ -78,12 +78,12 @@ public void testNonDefReqField() { public void testNonDefReqField2() { Object returns = BRunUtil.invoke(compileResult, "testNonDefReqField2"); - BMap person = (BMap) returns; + BMap person = (BMap) returns; Assert.assertEquals(person.get(StringUtils.fromString("fname")).toString(), "John"); Assert.assertEquals(person.get(StringUtils.fromString("lname")).toString(), "Doe"); Assert.assertNull(person.get(StringUtils.fromString("age"))); - BMap adrs = (BMap) person.get(StringUtils.fromString("adrs")); + BMap adrs = (BMap) person.get(StringUtils.fromString("adrs")); Assert.assertEquals(adrs.get(StringUtils.fromString("street")).toString(), ""); Assert.assertEquals(adrs.get(StringUtils.fromString("city")).toString(), ""); Assert.assertEquals(adrs.get(StringUtils.fromString("country")).toString(), "LK"); @@ -93,12 +93,12 @@ public void testNonDefReqField2() { public void testDefaultableReqField() { Object returns = BRunUtil.invoke(compileResult, "testDefaultableReqField"); - BMap person = (BMap) returns; + BMap person = (BMap) returns; Assert.assertEquals(person.get(StringUtils.fromString("fname")).toString(), "default"); Assert.assertNull(person.get(StringUtils.fromString("lname"))); Assert.assertNull(person.get(StringUtils.fromString("age"))); - BMap adrs = (BMap) person.get(StringUtils.fromString("adrs")); + BMap adrs = (BMap) person.get(StringUtils.fromString("adrs")); Assert.assertEquals(adrs.get(StringUtils.fromString("street")).toString(), ""); Assert.assertEquals(adrs.get(StringUtils.fromString("city")).toString(), ""); Assert.assertEquals(adrs.get(StringUtils.fromString("country")).toString(), "LK"); @@ -107,7 +107,7 @@ public void testDefaultableReqField() { @Test(description = "Test non-defaultable user defined type as an optional field") public void testOptionalNonDefField() { Object returns = BRunUtil.invoke(compileResult, "testOptionalNonDefField"); - BMap person = (BMap) returns; + BMap person = (BMap) returns; Assert.assertEquals(person.get(StringUtils.fromString("fname")).toString(), "default"); Assert.assertNull(person.get(StringUtils.fromString("lname"))); Assert.assertNull(person.get(StringUtils.fromString("age"))); @@ -145,7 +145,7 @@ public void testOptionalNonDefField4() { public void testOptionalDefaultableField() { Object returns = BRunUtil.invoke(compileResult, "testOptionalDefaultableField"); - BMap person = (BMap) returns; + BMap person = (BMap) returns; Assert.assertEquals(person.get(StringUtils.fromString("fname")).toString(), "default"); Assert.assertNull(person.get(StringUtils.fromString("lname"))); Assert.assertNull(person.get(StringUtils.fromString("age"))); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/OpenRecordEquivalencyTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/OpenRecordEquivalencyTest.java index 38ae30ad861f..7dc142ababa2 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/OpenRecordEquivalencyTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/OpenRecordEquivalencyTest.java @@ -107,7 +107,7 @@ public void testRuntimeEqPublicStructs1() { @Test(description = "Test case for record equivalence") public void testRecordEquivalence() { Object returns = BRunUtil.invoke(compileResult, "testRecordEquivalence"); - BMap foo = (BMap) returns; + BMap foo = (BMap) returns; Assert.assertEquals(foo.size(), 7); Assert.assertEquals(foo.get(StringUtils.fromString("a")).toString(), "A"); @@ -122,7 +122,7 @@ public void testRecordEquivalence() { @Test(description = "Test case for using records with unordered fields in a match") public void testUnorderedFieldRecordsInAMatch() { Object returns = BRunUtil.invoke(compileResult, "testUnorderedFieldRecordsInAMatch"); - BMap foo = (BMap) returns; + BMap foo = (BMap) returns; Assert.assertEquals(foo.size(), 7); Assert.assertEquals(foo.get(StringUtils.fromString("a")).toString(), "A"); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/OpenRecordIterationTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/OpenRecordIterationTest.java index 14849707711c..6a12a62c6f50 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/OpenRecordIterationTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/OpenRecordIterationTest.java @@ -118,7 +118,7 @@ public void testForeachWithOpenRecords() { Assert.assertEquals((values.getRefValue(1)), 25L); Assert.assertTrue(values.getRefValue(2) instanceof BMap); - BMap addressRecord = (BMap) values.getRefValue(2); + BMap addressRecord = (BMap) values.getRefValue(2); Assert.assertEquals(addressRecord.get(StringUtils.fromString("street")).toString(), "Palm Grove"); Assert.assertEquals(addressRecord.get(StringUtils.fromString("city")).toString(), "Colombo 3"); } @@ -139,7 +139,7 @@ public void testForeachWithOpenRecords2() { Assert.assertTrue(values.getRefValue(2) instanceof BMap); Assert.assertEquals((values.getRefValue(3)), 5.9); - BMap addressRecord = (BMap) values.getRefValue(2); + BMap addressRecord = (BMap) values.getRefValue(2); Assert.assertEquals(addressRecord.get(StringUtils.fromString("street")).toString(), "Palm Grove"); Assert.assertEquals(addressRecord.get(StringUtils.fromString("city")).toString(), "Colombo 3"); } @@ -152,7 +152,7 @@ public void testForeachWithOpenRecords3() { Assert.assertEquals(returns.get(1), 25L); Assert.assertTrue(returns.get(2) instanceof BMap); - BMap addressRecord = (BMap) returns.get(2); + BMap addressRecord = (BMap) returns.get(2); Assert.assertEquals(addressRecord.get(StringUtils.fromString("street")).toString(), "Palm Grove"); Assert.assertEquals(addressRecord.get(StringUtils.fromString("city")).toString(), "Colombo 3"); } @@ -165,7 +165,7 @@ public void testForeachOpWithOpenRecords() { Assert.assertEquals(returns.get(1), 25L); Assert.assertTrue(returns.get(2) instanceof BMap); - BMap addressRecord = (BMap) returns.get(2); + BMap addressRecord = (BMap) returns.get(2); Assert.assertEquals(addressRecord.get(StringUtils.fromString("street")).toString(), "Palm Grove"); Assert.assertEquals(addressRecord.get(StringUtils.fromString("city")).toString(), "Colombo 3"); @@ -177,13 +177,13 @@ public void testMapOpWithOpenRecords() { String[] expectedFields = new String[]{"name", "age", "address", "profession"}; Object returns = BRunUtil.invoke(result, "testMapOpWithOpenRecords"); - BMap person = (BMap) returns; + BMap person = (BMap) returns; Assert.assertEquals(person.get(StringUtils.fromString(expectedFields[0])).toString(), "john doe"); Assert.assertEquals((person.get(StringUtils.fromString(expectedFields[1]))), 25L); Assert.assertTrue(person.get(StringUtils.fromString(expectedFields[2])) instanceof BMap); Assert.assertEquals(person.get(StringUtils.fromString(expectedFields[3])).toString(), "software engineer"); - BMap addressRecord = (BMap) person.get(StringUtils.fromString(expectedFields[2])); + BMap addressRecord = (BMap) person.get(StringUtils.fromString(expectedFields[2])); Assert.assertEquals(addressRecord.get(StringUtils.fromString("street")).toString(), "Palm Grove"); Assert.assertEquals(addressRecord.get(StringUtils.fromString("city")).toString(), "Colombo 3"); } @@ -191,7 +191,7 @@ public void testMapOpWithOpenRecords() { @Test(description = "Tests filter iterable operation on open records") public void testFilterOpWithOpenRecords() { Object returns = BRunUtil.invoke(result, "testFilterOpWithOpenRecords"); - BMap foo = (BMap) returns; + BMap foo = (BMap) returns; Assert.assertNull(foo.get(StringUtils.fromString("a"))); Assert.assertEquals(foo.get(StringUtils.fromString("b")).toString(), "B"); @@ -210,7 +210,7 @@ public void testCountOpWithOpenRecords() { @Test(description = "Test case for chained iterable operations on open records") public void testChainedOpsWithOpenRecords() { Object returns = BRunUtil.invoke(result, "testChainedOpsWithOpenRecords"); - BMap foo = (BMap) returns; + BMap foo = (BMap) returns; Assert.assertNull(foo.get(StringUtils.fromString("a"))); Assert.assertEquals(foo.get(StringUtils.fromString("b")).toString(), "bb"); @@ -224,7 +224,7 @@ public void testChainedOpsWithOpenRecords() { public void testMapWithAllStringOpenRecord() { Object returns = BRunUtil.invoke(result, "testMapWithAllStringOpenRecord"); - BMap foo = (BMap) returns; + BMap foo = (BMap) returns; Assert.assertEquals(foo.get(StringUtils.fromString("a")).toString(), "aa"); Assert.assertEquals(foo.get(StringUtils.fromString("b")).toString(), "bb"); Assert.assertEquals(foo.get(StringUtils.fromString("c")).toString(), "cc"); @@ -237,7 +237,7 @@ public void testMapWithAllIntOpenRecord() { Object[] args = new Object[]{(80), (75), (65), (78)}; Object returns = BRunUtil.invoke(result, "testMapWithAllIntOpenRecord", args); - BMap gradesMap = (BMap) returns; + BMap gradesMap = (BMap) returns; Assert.assertEquals((gradesMap.get(StringUtils.fromString("maths"))), 90L); Assert.assertEquals((gradesMap.get(StringUtils.fromString("physics"))), 85L); Assert.assertEquals((gradesMap.get(StringUtils.fromString("chemistry"))), 75L); @@ -250,7 +250,7 @@ public void testMapWithAllFloatOpenRecord() { Object[] args = new Object[]{(a), (b), (c)}; Object returns = BRunUtil.invoke(result, "testMapWithAllFloatOpenRecord", args); - BMap gradesMap = (BMap) returns; + BMap gradesMap = (BMap) returns; Assert.assertEquals((gradesMap.get(StringUtils.fromString("x"))), a + 10); Assert.assertEquals((gradesMap.get(StringUtils.fromString("y"))), b + 10); Assert.assertEquals((gradesMap.get(StringUtils.fromString("z"))), c + 10); @@ -262,7 +262,7 @@ public void testFilterWithAllStringOpenRecord() { final String a = "AA", e = "EE", f = "FF"; Object returns = BRunUtil.invoke(result, "testFilterWithAllStringOpenRecord"); - BMap foo = (BMap) returns; + BMap foo = (BMap) returns; Assert.assertEquals(foo.get(StringUtils.fromString("a")).toString(), a); Assert.assertNull(foo.get(StringUtils.fromString("b"))); Assert.assertNull(foo.get(StringUtils.fromString("c"))); @@ -276,7 +276,7 @@ public void testFilterWithAllIntOpenRecord() { final long m = 80, p = 75, e = 78; Object returns = BRunUtil.invoke(result, "testFilterWithAllIntOpenRecord"); - BMap gradesMap = (BMap) returns; + BMap gradesMap = (BMap) returns; Assert.assertEquals((gradesMap.get(StringUtils.fromString("maths"))), m); Assert.assertEquals((gradesMap.get(StringUtils.fromString("physics"))), p); Assert.assertNull(gradesMap.get(StringUtils.fromString("chemistry"))); @@ -289,7 +289,7 @@ public void testFilterWithAllFloatOpenRecord() { Object[] args = new Object[]{(a), (b), (c)}; Object returns = BRunUtil.invoke(result, "testFilterWithAllFloatOpenRecord", args); - BMap gradesMap = (BMap) returns; + BMap gradesMap = (BMap) returns; Assert.assertEquals((gradesMap.get(StringUtils.fromString("x"))), a); Assert.assertEquals((gradesMap.get(StringUtils.fromString("y"))), b); Assert.assertNull(gradesMap.get(StringUtils.fromString("z"))); @@ -313,7 +313,7 @@ public void testTerminalOpsOnAllIntOpenRecord() { @Test(description = "Test case for chained iterable operations on open records") public void testChainedOpsWithOpenRecords2() { Object returns = BRunUtil.invoke(result, "testChainedOpsWithOpenRecords2"); - BMap grades = (BMap) returns; + BMap grades = (BMap) returns; Assert.assertEquals((grades.get(StringUtils.fromString("maths"))), 4.2); Assert.assertEquals((grades.get(StringUtils.fromString("physics"))), 4.2); @@ -324,7 +324,7 @@ public void testChainedOpsWithOpenRecords2() { @Test(description = "Test case for chained iterable operations on open records") public void testChainedOpsWithOpenRecords3() { Object returns = BRunUtil.invoke(result, "testChainedOpsWithOpenRecords3"); - BMap grades = (BMap) returns; + BMap grades = (BMap) returns; Assert.assertEquals((grades.get(StringUtils.fromString("maths"))), 4.2); Assert.assertEquals((grades.get(StringUtils.fromString("physics"))), 4.2); @@ -363,7 +363,7 @@ public void testOpChainsWithTerminalOps() { @Test(description = "Test case for checking whether iterable ops mutate the original record") public void testMutability() { Object returns = BRunUtil.invoke(result, "testMutability"); - BMap grades = (BMap) returns; + BMap grades = (BMap) returns; Assert.assertEquals(grades.size(), 4); Assert.assertEquals(grades.get(StringUtils.fromString("maths")), 80L); Assert.assertEquals(grades.get(StringUtils.fromString("physics")), 75L); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/OpenRecordOptionalFieldsTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/OpenRecordOptionalFieldsTest.java index a242beaca77e..506cf5750a56 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/OpenRecordOptionalFieldsTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/OpenRecordOptionalFieldsTest.java @@ -64,12 +64,12 @@ public void testNegatives() { public void testNonDefReqField() { Object returns = BRunUtil.invoke(compileResult, "testNonDefReqField"); - BMap person = (BMap) returns; + BMap person = (BMap) returns; Assert.assertEquals(person.get(StringUtils.fromString("fname")).toString(), "default"); Assert.assertNull(person.get(StringUtils.fromString("lname"))); Assert.assertNull(person.get(StringUtils.fromString("age"))); - BMap adrs = (BMap) person.get(StringUtils.fromString("adrs")); + BMap adrs = (BMap) person.get(StringUtils.fromString("adrs")); Assert.assertEquals(adrs.get(StringUtils.fromString("street")).toString(), ""); Assert.assertEquals(adrs.get(StringUtils.fromString("city")).toString(), ""); Assert.assertEquals(adrs.get(StringUtils.fromString("country")).toString(), "LK"); @@ -80,12 +80,12 @@ public void testNonDefReqField() { public void testNonDefReqField2() { Object returns = BRunUtil.invoke(compileResult, "testNonDefReqField2"); - BMap person = (BMap) returns; + BMap person = (BMap) returns; Assert.assertEquals(person.get(StringUtils.fromString("fname")).toString(), "John"); Assert.assertEquals(person.get(StringUtils.fromString("lname")).toString(), "Doe"); Assert.assertNull(person.get(StringUtils.fromString("age"))); - BMap adrs = (BMap) person.get(StringUtils.fromString("adrs")); + BMap adrs = (BMap) person.get(StringUtils.fromString("adrs")); Assert.assertEquals(adrs.get(StringUtils.fromString("street")).toString(), ""); Assert.assertEquals(adrs.get(StringUtils.fromString("city")).toString(), ""); Assert.assertEquals(adrs.get(StringUtils.fromString("country")).toString(), "LK"); @@ -95,12 +95,12 @@ public void testNonDefReqField2() { public void testDefaultableReqField() { Object returns = BRunUtil.invoke(compileResult, "testDefaultableReqField"); - BMap person = (BMap) returns; + BMap person = (BMap) returns; Assert.assertEquals(person.get(StringUtils.fromString("fname")).toString(), "default"); Assert.assertNull(person.get(StringUtils.fromString("lname"))); Assert.assertNull(person.get(StringUtils.fromString("age"))); - BMap adrs = (BMap) person.get(StringUtils.fromString("adrs")); + BMap adrs = (BMap) person.get(StringUtils.fromString("adrs")); Assert.assertEquals(adrs.get(StringUtils.fromString("street")).toString(), ""); Assert.assertEquals(adrs.get(StringUtils.fromString("city")).toString(), ""); Assert.assertEquals(adrs.get(StringUtils.fromString("country")).toString(), "LK"); @@ -109,7 +109,7 @@ public void testDefaultableReqField() { @Test(description = "Test non-defaultable user defined type as an optional field") public void testOptionalNonDefField() { Object returns = BRunUtil.invoke(compileResult, "testOptionalNonDefField"); - BMap person = (BMap) returns; + BMap person = (BMap) returns; Assert.assertEquals(person.get(StringUtils.fromString("fname")).toString(), "default"); Assert.assertNull(person.get(StringUtils.fromString("lname"))); Assert.assertNull(person.get(StringUtils.fromString("age"))); @@ -148,7 +148,7 @@ public void testOptionalNonDefField4() { public void testOptionalDefaultableField() { Object returns = BRunUtil.invoke(compileResult, "testOptionalDefaultableField"); - BMap person = (BMap) returns; + BMap person = (BMap) returns; Assert.assertEquals(person.get(StringUtils.fromString("fname")).toString(), "default"); Assert.assertNull(person.get(StringUtils.fromString("lname"))); Assert.assertNull(person.get(StringUtils.fromString("age"))); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/OpenRecordTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/OpenRecordTest.java index 2e1e6d12187d..f44b0fc9511b 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/OpenRecordTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/OpenRecordTest.java @@ -179,7 +179,7 @@ public void testStructLiteralAttachedFunc() { public void testAdditionOfARestField() { Object returns = BRunUtil.invoke(compileResult, "testAdditionOfARestField"); - BMap person = (BMap) returns; + BMap person = (BMap) returns; Assert.assertTrue(person.get(StringUtils.fromString("mname")) instanceof BString); Assert.assertEquals(person.get(StringUtils.fromString("mname")).toString(), "Bar"); @@ -204,7 +204,7 @@ public void testAnydataOrErrorRestFieldRHSIndexAccess() { public void testStringRestField() { Object returns = BRunUtil.invoke(compileResult, "testStringRestField"); - BMap person = (BMap) returns; + BMap person = (BMap) returns; Assert.assertTrue(person.get(StringUtils.fromString("lname")) instanceof BString); Assert.assertEquals(person.get(StringUtils.fromString("lname")).toString(), "Bar"); @@ -227,7 +227,7 @@ public void testStringRestFieldRHSIndexAccess() { public void testIntRestField() { Object returns = BRunUtil.invoke(compileResult, "testIntRestField"); - BMap person = (BMap) returns; + BMap person = (BMap) returns; Assert.assertTrue(person.get(StringUtils.fromString("year")) instanceof Long); Assert.assertEquals((person.get(StringUtils.fromString("year"))), 3L); @@ -246,7 +246,7 @@ public void testIntRestFieldRHSIndexAccess() { public void testFloatRestField() { Object returns = BRunUtil.invoke(compileResult, "testFloatRestField"); - BMap person = (BMap) returns; + BMap person = (BMap) returns; Assert.assertTrue(person.get(StringUtils.fromString("height")) instanceof Double); Assert.assertEquals((person.get(StringUtils.fromString("height"))), 5.9D); @@ -265,7 +265,7 @@ public void testFloatRestFieldRHSIndexAccess() { public void testBooleanRestField() { Object returns = BRunUtil.invoke(compileResult, "testBooleanRestField"); - BMap person = (BMap) returns; + BMap person = (BMap) returns; Assert.assertTrue(person.get(StringUtils.fromString("isEmployed")) instanceof Boolean); Assert.assertTrue((Boolean) person.get(StringUtils.fromString("isEmployed"))); @@ -284,7 +284,7 @@ public void testBooleanRestFieldRHSIndexAccess() { public void testMapRestField() { Object returns = BRunUtil.invoke(compileResult, "testMapRestField"); - BMap person = (BMap) returns; + BMap person = (BMap) returns; Assert.assertTrue(person.get(StringUtils.fromString("misc")) instanceof BMap); Assert.assertEquals(person.get(StringUtils.fromString("misc")).toString(), "{\"lname\":\"Bar\",\"height\":5.9,\"isEmployed\":true}"); @@ -297,7 +297,7 @@ public void testMapRestField() { public void testMapRestFieldRHSIndexAccess() { BArray returns = (BArray) BRunUtil.invoke(compileResult, "testMapRestFieldRHSIndexAccess"); Assert.assertNotNull(returns.get(0)); - Assert.assertEquals(((BMap) returns.get(0)).size(), 0); + Assert.assertEquals(((BMap) returns.get(0)).size(), 0); Assert.assertNull(returns.get(1)); } @@ -305,7 +305,7 @@ public void testMapRestFieldRHSIndexAccess() { public void testUnionRestField() { Object returns = BRunUtil.invoke(compileResult, "testUnionRestField"); - BMap person = (BMap) returns; + BMap person = (BMap) returns; Assert.assertTrue(person.get(StringUtils.fromString("lname")) instanceof BString); Assert.assertTrue(person.get(StringUtils.fromString("height")) instanceof Double); Assert.assertTrue(person.get(StringUtils.fromString("isEmployed")) instanceof Boolean); @@ -326,7 +326,7 @@ public void testUnionRestFieldRHSIndexAccess() { public void testNilRestField() { Object returns = BRunUtil.invoke(compileResult, "testNilRestField"); - BMap person = (BMap) returns; + BMap person = (BMap) returns; Assert.assertNull(person.get(StringUtils.fromString("lname"))); Assert.assertEquals(person.toString(), "{\"name\":\"Foo\",\"age\":25,\"lname\":null}"); @@ -336,7 +336,7 @@ public void testNilRestField() { public void testRecordRestField() { Object returns = BRunUtil.invoke(compileResult, "testRecordRestField"); - BMap person = (BMap) returns; + BMap person = (BMap) returns; Assert.assertTrue(person.get(StringUtils.fromString("dpt")) instanceof BMap); Assert.assertEquals(person.get(StringUtils.fromString("dpt")).toString(), "{\"dptName\":\"Engineering\"," + "\"employees\":[]}"); @@ -356,7 +356,7 @@ public void testRecordRestFieldRHSIndexAccess() { public void testObjectRestField() { Object returns = BRunUtil.invoke(compileResult, "testObjectRestField"); - BMap person = (BMap) returns; + BMap person = (BMap) returns; Assert.assertTrue(person.get(StringUtils.fromString("pet")) instanceof BObject); Assert.assertEquals(person.get(StringUtils.fromString("pet")).toString(), "{kind:Cat, name:Miaw}"); @@ -377,7 +377,7 @@ public void testObjectRestFieldRHSIndexAccess() { public void testTupleRestField() { Object returns = BRunUtil.invoke(compileResult, "testTupleRestField"); - BMap person = (BMap) returns; + BMap person = (BMap) returns; BArray miscInfo = (BArray) person.get(StringUtils.fromString("misc")); Assert.assertTrue(person.get(StringUtils.fromString("misc")) instanceof BArray); @@ -406,7 +406,7 @@ public void testTupleRestFieldRHSIndexAccess() { public void testAnyRestField() { Object returns = BRunUtil.invoke(compileResult, "testAnyRestField"); - BMap person = (BMap) returns; + BMap person = (BMap) returns; BArray pets = (BArray) person.get(StringUtils.fromString("pets")); Assert.assertEquals(getType(pets).toString(), "Animal?[]"); Assert.assertEquals(person.toString(), @@ -434,7 +434,7 @@ public void testFuncPtrAsAField() { @Test(description = "Test case for default value initializing in type referenced fields") public void testDefaultValueInit() { Object returns = BRunUtil.invoke(compileResult, "testDefaultValueInit"); - BMap manager = (BMap) returns; + BMap manager = (BMap) returns; Assert.assertEquals(manager.get(StringUtils.fromString("name")).toString(), "John Doe"); Assert.assertEquals((manager.get(StringUtils.fromString("age"))), 25L); Assert.assertEquals(manager.get(StringUtils.fromString("adr")).toString(), "{\"city\":\"Colombo\"," + @@ -467,7 +467,7 @@ public void testExpressionsAsKeys() { @Test public void testLangFuncOnRecord() { Object returns = BRunUtil.invoke(compileResult, "testLangFuncOnRecord"); - Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("toJson")), 44L); + Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("toJson")), 44L); } @Test diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/RecordAccessWithIndexTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/RecordAccessWithIndexTest.java index 184f669cdf06..4ad56e7b0d5c 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/RecordAccessWithIndexTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/RecordAccessWithIndexTest.java @@ -53,7 +53,7 @@ public void testBasicStruct() { Assert.assertEquals(returns.get(0).toString(), "Jack"); Assert.assertTrue(returns.get(1) instanceof BMap); - BMap adrsMap = ((BMap) returns.get(1)); + BMap adrsMap = ((BMap) returns.get(1)); Assert.assertEquals(adrsMap.get(StringUtils.fromString("country")), StringUtils.fromString("USA")); Assert.assertEquals(adrsMap.get(StringUtils.fromString("state")), StringUtils.fromString("CA")); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/statements/arrays/ArrayFillTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/statements/arrays/ArrayFillTest.java index 5ce5e7dec4d1..06d8ea560c61 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/statements/arrays/ArrayFillTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/statements/arrays/ArrayFillTest.java @@ -25,6 +25,7 @@ import io.ballerina.runtime.api.utils.StringUtils; import io.ballerina.runtime.api.values.BArray; import io.ballerina.runtime.api.values.BMap; +import io.ballerina.runtime.api.values.BString; import org.ballerinalang.test.BCompileUtil; import org.ballerinalang.test.BRunUtil; import org.ballerinalang.test.CompileResult; @@ -201,19 +202,20 @@ public void testTupleSealedArrayFill() { @Test public void testMapArrayFill() { - BMap emptyMap = ValueCreator.createMapValue(TypeCreator.createMapType(PredefinedTypes.TYPE_ANY)); - BMap map = ValueCreator.createMapValue(TypeCreator.createMapType(PredefinedTypes.TYPE_ANY)); - map.put("1", 1); + BMap emptyMap = + ValueCreator.createMapValue(TypeCreator.createMapType(PredefinedTypes.TYPE_ANY)); + BMap map = ValueCreator.createMapValue(TypeCreator.createMapType(PredefinedTypes.TYPE_ANY)); + map.put(StringUtils.fromString("1"), 1); Object[] args = new Object[]{(index), map}; Object returns = BRunUtil.invoke(compileResult, "testMapArrayFill", args); BArray mapArr = (BArray) returns; assertEquals(mapArr.size(), index + 1); for (int i = 0; i < index; i++) { - validateMapValue((BMap) mapArr.get(i), emptyMap); + validateMapValue((BMap) mapArr.get(i), emptyMap); } - validateMapValue((BMap) mapArr.get(index), map); + validateMapValue((BMap) mapArr.get(index), map); } @Test @@ -534,10 +536,10 @@ public void testFiniteTypeUnionArrayFill() { BRunUtil.invoke(compileResult, "testFiniteTypeUnionArrayFill"); } - private void validateMapValue(BMap actual, BMap expected) { + private void validateMapValue(BMap actual, BMap expected) { assertEquals(actual.size(), expected.size()); - for (Map.Entry entry : expected.entrySet()) { + for (Map.Entry entry : expected.entrySet()) { assertEquals(actual.get(entry.getKey()), entry.getValue()); } } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/statements/arrays/ArrayInitializerExprTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/statements/arrays/ArrayInitializerExprTest.java index c98288c554dc..c1b7d83ec185 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/statements/arrays/ArrayInitializerExprTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/statements/arrays/ArrayInitializerExprTest.java @@ -122,21 +122,21 @@ public void testArrayOfMapsInit() { Object adrs1 = arrayValue.getRefValue(0); Assert.assertTrue(adrs1 instanceof BMap); - Object address = ((BMap) adrs1).get(StringUtils.fromString("address")); + Object address = ((BMap) adrs1).get(StringUtils.fromString("address")); Assert.assertTrue(address instanceof BMap); - Assert.assertEquals(((BMap) address).get(StringUtils.fromString("city")).toString(), "Colombo"); + Assert.assertEquals(((BMap) address).get(StringUtils.fromString("city")).toString(), "Colombo"); Object adrs2 = arrayValue.getRefValue(1); Assert.assertTrue(adrs2 instanceof BMap); - address = ((BMap) adrs2).get(StringUtils.fromString("address")); + address = ((BMap) adrs2).get(StringUtils.fromString("address")); Assert.assertTrue(address instanceof BMap); - Assert.assertEquals(((BMap) address).get(StringUtils.fromString("city")).toString(), "Kandy"); + Assert.assertEquals(((BMap) address).get(StringUtils.fromString("city")).toString(), "Kandy"); Object adrs3 = arrayValue.getRefValue(2); Assert.assertTrue(adrs3 instanceof BMap); - address = ((BMap) adrs3).get(StringUtils.fromString("address")); + address = ((BMap) adrs3).get(StringUtils.fromString("address")); Assert.assertTrue(address instanceof BMap); - Assert.assertEquals(((BMap) address).get(StringUtils.fromString("city")).toString(), "Galle"); + Assert.assertEquals(((BMap) address).get(StringUtils.fromString("city")).toString(), "Galle"); } @Test(description = "Test float array initialization with integer values") diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/statements/arrays/ArrayTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/statements/arrays/ArrayTest.java index 34e729fdeca7..580059fe58b0 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/statements/arrays/ArrayTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/statements/arrays/ArrayTest.java @@ -142,8 +142,7 @@ public void testArrayToString() { Assert.assertEquals(bBooleanArray.stringValue(null), "[true,true,false]"); BXml[] xmlArray = {XmlFactory.parse(" "), XmlFactory.parse("hello")}; - ArrayValue bXmlArray = new ArrayValueImpl(xmlArray, - new io.ballerina.runtime.internal.types.BArrayType(PredefinedTypes.TYPE_XML)); + ArrayValue bXmlArray = new ArrayValueImpl(xmlArray, new BArrayType(PredefinedTypes.TYPE_XML)); Assert.assertEquals(bXmlArray.stringValue(null), "[` `,`hello`]"); } @@ -158,7 +157,7 @@ public void testElementTypesWithoutImplicitInitVal() { @Test public void testArrayFieldInRecord() { Object retVals = BRunUtil.invoke(compileResult, "testArrayFieldInRecord"); - BMap barRec = (BMap) retVals; + BMap barRec = (BMap) retVals; BArray arr = (BArray) barRec.get(StringUtils.fromString("fArr")); Assert.assertEquals(((BArrayType) arr.getType()).getState().getValue(), BArrayState.CLOSED.getValue()); Assert.assertEquals(arr.toString(), "[1,2]"); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/statements/variabledef/ErrorVariableDefinitionTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/statements/variabledef/ErrorVariableDefinitionTest.java index f98d9063f1bd..d771a88a3a15 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/statements/variabledef/ErrorVariableDefinitionTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/statements/variabledef/ErrorVariableDefinitionTest.java @@ -55,8 +55,8 @@ public void testBasicErrorVariableWithMapDetails() { Assert.assertEquals(returns.get(3).toString(), "Error Two"); Assert.assertEquals(returns.get(4).toString(), "{\"detail\":\"Detail Msg\"}"); Assert.assertEquals(returns.get(5).toString(), "Msg One"); - Assert.assertEquals(((BMap) returns.get(6)).get(StringUtils.fromString("message")).toString(), "Msg Two"); - Assert.assertTrue((Boolean) ((BMap) returns.get(6)).get(StringUtils.fromString("fatal"))); + Assert.assertEquals(((BMap) returns.get(6)).get(StringUtils.fromString("message")).toString(), "Msg Two"); + Assert.assertTrue((Boolean) ((BMap) returns.get(6)).get(StringUtils.fromString("fatal"))); Assert.assertEquals(returns.get(7).toString(), "Msg Two"); } @@ -68,10 +68,12 @@ public void testBasicErrorVariableWithConstAndMap() { Assert.assertEquals(returns.get(1).toString(), "Some Error One"); Assert.assertEquals(returns.get(2).toString(), "Some Error Two"); Assert.assertEquals(returns.get(3).toString(), "Some Error Two"); - Assert.assertEquals(((BMap) returns.get(4)).get(StringUtils.fromString("message")).toString(), "Msg Three"); + Assert.assertEquals(((BMap) returns.get(4)).get(StringUtils.fromString("message")).toString(), + "Msg Three"); Assert.assertEquals(returns.get(5).toString(), "Msg Three"); - Assert.assertEquals(((BMap) returns.get(6)).get(StringUtils.fromString("message")).toString(), "Msg Four"); - Assert.assertTrue((Boolean) ((BMap) returns.get(6)).get(StringUtils.fromString("fatal"))); + Assert.assertEquals(((BMap) returns.get(6)).get(StringUtils.fromString("message")).toString(), + "Msg Four"); + Assert.assertTrue((Boolean) ((BMap) returns.get(6)).get(StringUtils.fromString("fatal"))); Assert.assertEquals(returns.get(7).toString(), "Msg Four"); } @@ -83,10 +85,10 @@ public void testVarBasicErrorVariableWithMapDetails() { Assert.assertEquals(returns.get(1).toString(), "Error One"); Assert.assertEquals(returns.get(2).toString(), "Error Two"); Assert.assertEquals(returns.get(3).toString(), "Error Two"); - Assert.assertEquals(((BMap) returns.get(4)).get(StringUtils.fromString("message")).toString(), "Msg One"); + Assert.assertEquals(((BMap) returns.get(4)).get(StringUtils.fromString("message")).toString(), "Msg One"); Assert.assertEquals(returns.get(5).toString(), "Msg One"); - Assert.assertEquals(((BMap) returns.get(6)).get(StringUtils.fromString("message")).toString(), "Msg Two"); - Assert.assertTrue((Boolean) ((BMap) returns.get(6)).get(StringUtils.fromString("fatal"))); + Assert.assertEquals(((BMap) returns.get(6)).get(StringUtils.fromString("message")).toString(), "Msg Two"); + Assert.assertTrue((Boolean) ((BMap) returns.get(6)).get(StringUtils.fromString("fatal"))); Assert.assertEquals(returns.get(7).toString(), "Msg Two"); } @@ -98,10 +100,12 @@ public void testVarBasicErrorVariableWithConstAndMap() { Assert.assertEquals(returns.get(1).toString(), "Some Error One"); Assert.assertEquals(returns.get(2).toString(), "Some Error Two"); Assert.assertEquals(returns.get(3).toString(), "Some Error Two"); - Assert.assertEquals(((BMap) returns.get(4)).get(StringUtils.fromString("message")).toString(), "Msg Three"); + Assert.assertEquals(((BMap) returns.get(4)).get(StringUtils.fromString("message")).toString(), + "Msg Three"); Assert.assertEquals(returns.get(5).toString(), "Msg Three"); - Assert.assertEquals(((BMap) returns.get(6)).get(StringUtils.fromString("message")).toString(), "Msg Four"); - Assert.assertTrue((Boolean) ((BMap) returns.get(6)).get(StringUtils.fromString("fatal"))); + Assert.assertEquals(((BMap) returns.get(6)).get(StringUtils.fromString("message")).toString(), + "Msg Four"); + Assert.assertTrue((Boolean) ((BMap) returns.get(6)).get(StringUtils.fromString("fatal"))); Assert.assertEquals(returns.get(7).toString(), "Msg Four"); } @@ -113,7 +117,7 @@ public void testBasicErrorVariableWithRecordDetails() { Assert.assertEquals(returns.get(1).toString(), "Error One"); Assert.assertEquals(returns.get(2).toString(), "Something Wrong"); Assert.assertTrue((Boolean) returns.get(3)); - Assert.assertEquals(((BMap) returns.get(4)).get(StringUtils.fromString("message")).toString(), + Assert.assertEquals(((BMap) returns.get(4)).get(StringUtils.fromString("message")).toString(), "Something Wrong"); } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/statements/variabledef/ForwardReferencingGlobalDefinitionTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/statements/variabledef/ForwardReferencingGlobalDefinitionTest.java index fcdd97caf597..aa729a01e4b6 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/statements/variabledef/ForwardReferencingGlobalDefinitionTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/statements/variabledef/ForwardReferencingGlobalDefinitionTest.java @@ -54,7 +54,7 @@ public void globalDefinitionsReOrdering() { Assert.assertEquals(diagnostics.length, 0); Object employee = BRunUtil.invoke(resultReOrdered, "getEmployee"); - String employeeName = ((BMap) employee).get(StringUtils.fromString("name")).toString(); + String employeeName = ((BMap) employee).get(StringUtils.fromString("name")).toString(); Assert.assertEquals(employeeName, "Sumedha"); } @@ -75,11 +75,11 @@ public void inFunctionGlobalReference() { compile("test-src/statements/variabledef/inFunctionGlobalRefProject"); Object employee = BRunUtil.invoke(resultReOrdered, "getEmployee"); - String employeeName = ((BMap) employee).get(StringUtils.fromString("name")).toString(); + String employeeName = ((BMap) employee).get(StringUtils.fromString("name")).toString(); Assert.assertEquals(employeeName, "Sumedha"); Object employee2 = BRunUtil.invoke(resultReOrdered, "getfromFuncA"); - String employee2Name = ((BMap) employee2).get(StringUtils.fromString("name")).toString(); + String employee2Name = ((BMap) employee2).get(StringUtils.fromString("name")).toString(); Assert.assertEquals(employee2Name, "Sumedha"); } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/statements/variabledef/RecordVariableDefinitionTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/statements/variabledef/RecordVariableDefinitionTest.java index 7096133c10e4..ba72e83832ba 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/statements/variabledef/RecordVariableDefinitionTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/statements/variabledef/RecordVariableDefinitionTest.java @@ -73,8 +73,8 @@ public void recordVarInRecordVar2() { BArray returns = (BArray) BRunUtil.invoke(result, "recordVarInRecordVar2"); Assert.assertEquals(returns.size(), 2); Assert.assertEquals(returns.get(0).toString(), "Peter"); - Assert.assertEquals((((BMap) returns.get(1)).get(StringUtils.fromString("age"))), 29L); - Assert.assertEquals(((BMap) returns.get(1)).get(StringUtils.fromString("format")).toString(), "Y"); + Assert.assertEquals((((BMap) returns.get(1)).get(StringUtils.fromString("age"))), 29L); + Assert.assertEquals(((BMap) returns.get(1)).get(StringUtils.fromString("format")).toString(), "Y"); } @Test(description = "Test record variable inside record variable inside record variable") @@ -121,13 +121,15 @@ public void nestedRecordVariableWithRHSInvocation() { public void testRestParameter() { Object returns = BRunUtil.invoke(result, "testRestParameter"); Assert.assertTrue(returns instanceof BMap); - BMap bMap = (BMap) returns; + BMap bMap = (BMap) returns; Assert.assertEquals(bMap.size(), 2); Assert.assertEquals(bMap.get(StringUtils.fromString("work")).toString(), "SE"); - Assert.assertEquals((((BMap) bMap.get(StringUtils.fromString("other"))).get(StringUtils.fromString("age"))), + Assert.assertEquals((((BMap) bMap.get(StringUtils.fromString("other"))) + .get(StringUtils.fromString("age"))), 99L); Assert.assertEquals( - ((BMap) bMap.get(StringUtils.fromString("other"))).get(StringUtils.fromString("format")).toString(), + ((BMap) bMap.get(StringUtils.fromString("other"))) + .get(StringUtils.fromString("format")).toString(), "MM"); } @@ -135,11 +137,11 @@ public void testRestParameter() { public void testNestedRestParameter() { BArray returns = (BArray) BRunUtil.invoke(result, "testNestedRestParameter"); Assert.assertTrue(returns.get(0) instanceof BMap); - BMap bMap = (BMap) returns.get(0); + BMap bMap = (BMap) returns.get(0); Assert.assertEquals(bMap.size(), 1); Assert.assertEquals((bMap.get(StringUtils.fromString("year"))), 1990L); - BMap bMap2 = (BMap) returns.get(1); + BMap bMap2 = (BMap) returns.get(1); Assert.assertEquals(bMap2.size(), 1); Assert.assertEquals(bMap2.get(StringUtils.fromString("work")).toString(), "SE"); } @@ -152,7 +154,7 @@ public void testVariableAssignment() { Assert.assertEquals(returns.get(1), 29L); Assert.assertEquals(returns.get(2).toString(), "Y"); Assert.assertTrue((Boolean) returns.get(3)); - Assert.assertEquals(((BMap) returns.get(4)).get(StringUtils.fromString("work")).toString(), "SE"); + Assert.assertEquals(((BMap) returns.get(4)).get(StringUtils.fromString("work")).toString(), "SE"); } @Test(description = "Test rest parameter in nested record variable") @@ -163,7 +165,7 @@ public void testVariableAssignment2() { Assert.assertEquals(returns.get(1), 30L); Assert.assertEquals(returns.get(2).toString(), "N"); Assert.assertFalse((Boolean) returns.get(3)); - Assert.assertEquals(((BMap) returns.get(4)).get(StringUtils.fromString("added")).toString(), "later"); + Assert.assertEquals(((BMap) returns.get(4)).get(StringUtils.fromString("added")).toString(), "later"); } @Test(description = "Test tuple var def inside record var def") @@ -188,10 +190,11 @@ public void testRecordInsideTupleInsideRecord() { Assert.assertEquals(((BArray) returns.get(0)).getString(0), "A"); Assert.assertEquals(((BArray) returns.get(0)).getString(1), "B"); Assert.assertEquals(returns.get(1).toString(), "A"); - BMap child = (BMap) ((BMap) returns.get(2)).get(StringUtils.fromString("child")); + BMap child = (BMap) ((BMap) returns.get(2)).get(StringUtils.fromString("child")); Assert.assertEquals(child.get(StringUtils.fromString("name")).toString(), "C"); Assert.assertEquals((((BArray) child.get(StringUtils.fromString("yearAndAge"))).getRefValue(0)), 1996L); - Assert.assertEquals(((BMap) ((BArray) child.get(StringUtils.fromString("yearAndAge"))).getRefValue(1)).get( + Assert.assertEquals(((BMap) ((BArray) child.get(StringUtils.fromString("yearAndAge"))) + .getRefValue(1)).get( StringUtils.fromString("format")).toString(), "Z"); } @@ -213,10 +216,11 @@ public void testRecordInsideTupleInsideRecordWithVar() { Assert.assertEquals(((BArray) returns.get(0)).getString(0), "A"); Assert.assertEquals(((BArray) returns.get(0)).getString(1), "B"); Assert.assertEquals(returns.get(1).toString(), "A"); - BMap child = (BMap) ((BMap) returns.get(2)).get(StringUtils.fromString("child")); + BMap child = (BMap) ((BMap) returns.get(2)).get(StringUtils.fromString("child")); Assert.assertEquals(child.get(StringUtils.fromString("name")).toString(), "C"); Assert.assertEquals((((BArray) child.get(StringUtils.fromString("yearAndAge"))).getRefValue(0)), 1996L); - Assert.assertEquals(((BMap) ((BArray) child.get(StringUtils.fromString("yearAndAge"))).getRefValue(1)).get( + Assert.assertEquals(((BMap) ((BArray) child.get(StringUtils.fromString("yearAndAge"))) + .getRefValue(1)).get( StringUtils.fromString("format")).toString(), "Z"); } @@ -238,7 +242,7 @@ public void testRecordVarWithUnionType() { Assert.assertEquals(returns.get(0), 50L); Assert.assertEquals(returns.get(1), 51.1); Assert.assertEquals(getType(returns.get(2)).getName(), "UnionOne"); - Assert.assertEquals(((BMap) returns.get(2)).get(StringUtils.fromString("restP1")).toString(), "stringP1"); + Assert.assertEquals(((BMap) returns.get(2)).get(StringUtils.fromString("restP1")).toString(), "stringP1"); } @Test(description = "Test record variable with Union Type") @@ -261,7 +265,7 @@ public void testIgnoreVariable() { @Test(description = "Test record variable with only a rest parameter") public void testRecordVariableWithOnlyRestParam() { - BMap returns = (BMap) BRunUtil.invoke(result, "testRecordVariableWithOnlyRestParam"); + BMap returns = (BMap) BRunUtil.invoke(result, "testRecordVariableWithOnlyRestParam"); Assert.assertEquals(returns.toString(), "{\"name\":\"John\",\"age\":{\"age\":30,\"format\":\"YY\",\"year\":1990},\"married\":true," + diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/structs/StructAccessWithIndexTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/structs/StructAccessWithIndexTest.java index ef24b09dab83..4ab133c1a1f4 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/structs/StructAccessWithIndexTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/structs/StructAccessWithIndexTest.java @@ -54,7 +54,7 @@ public void testBasicStruct() { Assert.assertEquals(returns.get(0).toString(), "Jack"); Assert.assertTrue(returns.get(1) instanceof BMap); - BMap adrsMap = ((BMap) returns.get(1)); + BMap adrsMap = ((BMap) returns.get(1)); Assert.assertEquals(adrsMap.get(StringUtils.fromString("country")), StringUtils.fromString("USA")); Assert.assertEquals(adrsMap.get(StringUtils.fromString("state")), StringUtils.fromString("CA")); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/structs/StructTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/structs/StructTest.java index 9bcd0e555a25..c0ef43033440 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/structs/StructTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/structs/StructTest.java @@ -49,7 +49,7 @@ public void testBasicStruct() { Assert.assertEquals(returns.get(0).toString(), "Jack"); Assert.assertTrue(returns.get(1) instanceof BMap); - BMap adrsMap = ((BMap) returns.get(1)); + BMap adrsMap = ((BMap) returns.get(1)); Assert.assertEquals(adrsMap.get(StringUtils.fromString("country")), StringUtils.fromString("USA")); Assert.assertEquals(adrsMap.get(StringUtils.fromString("state")), StringUtils.fromString("CA")); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/any/BAnyTypeNativeSuccessScenariosTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/any/BAnyTypeNativeSuccessScenariosTest.java index 1700be9c6858..ef0b950c4880 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/any/BAnyTypeNativeSuccessScenariosTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/any/BAnyTypeNativeSuccessScenariosTest.java @@ -56,54 +56,46 @@ public void testJsonInAnyCastToString() { @Test(description = "This tests the finding of best native function when there are no direct match for println") public void testAnyPrintln() throws IOException { - ByteArrayOutputStream outContent = new ByteArrayOutputStream(); - try { + try (ByteArrayOutputStream outContent = new ByteArrayOutputStream()) { System.setOut(new PrintStream(outContent)); BRunUtil.invoke(result, "printlnAnyVal", new Object[0]); Assert.assertEquals(outContent.toString().replace("\r", ""), "{\"PropertyName\":\"Value\"}\n", - "Invalid xml printed"); + "Invalid xml printed"); } finally { - outContent.close(); System.setOut(original); } } @Test(description = "This tests the finding of best native function when there are no direct match for print") public void testAnyPrint() throws IOException { - ByteArrayOutputStream outContent = new ByteArrayOutputStream(); - try { + try (ByteArrayOutputStream outContent = new ByteArrayOutputStream()) { System.setOut(new PrintStream(outContent)); BRunUtil.invoke(result, "printAnyVal", new Object[0]); Assert.assertEquals(outContent.toString().replace("\r", ""), "{\"PropertyName\":\"Value\"}", "Invalid xml printed"); } finally { - outContent.close(); System.setOut(original); } } @Test(description = "This tests the finding of best native function when there are no direct match for print int") public void testFindBestMatchForNativeFunctionPrintln() throws IOException { - ByteArrayOutputStream outContent = new ByteArrayOutputStream(); - try { + try (ByteArrayOutputStream outContent = new ByteArrayOutputStream()) { System.setOut(new PrintStream(outContent)); BRunUtil.invoke(result, "findBestNativeFunctionPrintln", new Object[0]); Assert.assertEquals(outContent.toString().replace("\r", ""), "8\n", "Invalid int value printed"); } finally { - outContent.close(); System.setOut(original); } } @Test(description = "This tests the finding of best native function when there are no direct match for println int") public void testFindBestMatchForNativeFunctionPrint() throws IOException { - ByteArrayOutputStream outContent = new ByteArrayOutputStream(); - try { + try (ByteArrayOutputStream outContent = new ByteArrayOutputStream()) { System.setOut(new PrintStream(outContent)); BRunUtil.invoke(result, "findBestNativeFunctionPrint", new Object[0]); Assert.assertEquals(outContent.toString().replace("\r", ""), "7", "Invalid int value printed"); } finally { - outContent.close(); System.setOut(original); } } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/anydata/AnydataTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/anydata/AnydataTest.java index 9fdd7bf63909..27b735c2c316 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/anydata/AnydataTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/anydata/AnydataTest.java @@ -74,11 +74,11 @@ public void testValueTypesAssignment() { public void testRecordAssignment() { BArray returns = (BArray) BRunUtil.invoke(result, "testRecordAssignment"); - BMap foo = (BMap) returns.get(0); + BMap foo = (BMap) returns.get(0); assertEquals(getType(foo).getName(), "Foo"); assertEquals((foo.get(StringUtils.fromString("a"))), 20L); - BMap closedFoo = (BMap) returns.get(1); + BMap closedFoo = (BMap) returns.get(1); assertEquals(getType(closedFoo).getName(), "ClosedFoo"); assertEquals((closedFoo.get(StringUtils.fromString("ca"))), 35L); } @@ -87,11 +87,12 @@ public void testRecordAssignment() { public void testCyclicRecordAssignment() { Object returns = BRunUtil.invoke(result, "testCyclicRecordAssignment"); Assert.assertTrue(returns instanceof BMap); - BMap bMap = (BMap) returns; + BMap bMap = (BMap) returns; Assert.assertEquals(bMap.get(StringUtils.fromString("name")).toString(), "Child"); Assert.assertEquals(bMap.get(StringUtils.fromString("age")), 25L); Assert.assertEquals( - ((BMap) bMap.get(StringUtils.fromString("parent"))).get(StringUtils.fromString("name")).toString(), + ((BMap) bMap.get(StringUtils.fromString("parent"))) + .get(StringUtils.fromString("name")).toString(), "Parent"); } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/json/JSONTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/json/JSONTest.java index 6d167995336e..8a2581da84b7 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/json/JSONTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/json/JSONTest.java @@ -156,7 +156,7 @@ public void testParseMalformedString() { Object returns = BRunUtil.invoke(compileResult, "testParse", args); Assert.assertTrue(returns instanceof BError); String errorMsg = - (((BMap) ((BError) returns).getDetails()).get(StringUtils.fromString("message"))).toString(); + (((BMap) ((BError) returns).getDetails()).get(StringUtils.fromString("message"))).toString(); Assert.assertEquals(errorMsg, "unrecognized token 'some' at line: 1 column: 6"); } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/map/BMapValueTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/map/BMapValueTest.java index dd2ad4b34119..5afc4a76ae5d 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/map/BMapValueTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/map/BMapValueTest.java @@ -20,6 +20,7 @@ import io.ballerina.runtime.api.creators.ValueCreator; import io.ballerina.runtime.api.utils.StringUtils; import io.ballerina.runtime.api.values.BMap; +import io.ballerina.runtime.api.values.BString; import io.ballerina.runtime.internal.XmlFactory; import io.ballerina.runtime.internal.values.MapValue; import io.ballerina.runtime.internal.values.MapValueImpl; @@ -43,7 +44,7 @@ public class BMapValueTest { @Test public void testBMap() { - BMap map = ValueCreator.createMapValue(); + BMap map = ValueCreator.createMapValue(); map.put(StringUtils.fromString("Chanaka"), 1L); map.put(StringUtils.fromString("Udaya"), 2L); map.put(StringUtils.fromString("Chanaka"), 1L); @@ -63,7 +64,7 @@ public void testBMap() { @Test public void testBMapClear() { - BMap map = ValueCreator.createMapValue(); + BMap map = ValueCreator.createMapValue(); map.put(StringUtils.fromString("IS"), 0L); map.put(StringUtils.fromString("ESB"), 1L); map.put(StringUtils.fromString("APIM"), 2L); @@ -74,7 +75,7 @@ public void testBMapClear() { @Test public void testBMapHasKey() { - BMap map = ValueCreator.createMapValue(); + BMap map = ValueCreator.createMapValue(); map.put(StringUtils.fromString("IS"), (0)); map.put(StringUtils.fromString("ESB"), (1)); map.put(StringUtils.fromString("APIM"), (2)); @@ -168,7 +169,7 @@ void testInvalidGrammar3() { @Test(description = "Testing convert map values to string") public void testBMapToString() { - MapValue map = new MapValueImpl<>(); + MapValue map = new MapValueImpl<>(); map.put(StringUtils.fromString("key1"), 1); map.put(StringUtils.fromString("key2"), StringUtils.fromString("foo")); map.put(StringUtils.fromString("key3"), XmlFactory.parse("hello")); @@ -178,7 +179,7 @@ public void testBMapToString() { @Test(dependsOnMethods = "testGrammar") public void testMapOrder() { Object returnVals = BRunUtil.invoke(programFile, "testMapOrder", new Object[0]); - BMap m = (BMap) returnVals; + BMap m = (BMap) returnVals; Object[] keys = m.getKeys(); int counter = 0; String[] values = {"Element 1", "Element 2", "Element 3"}; @@ -193,14 +194,14 @@ public void testMapOrder() { @Test(description = "Test string representations of a map with a nil value", dependsOnMethods = "testGrammar") public void testMapStringRepresentation() { Object returnVals = BRunUtil.invoke(programFile, "testMapStringRepresentation", new Object[0]); - BMap m = (BMap) returnVals; + BMap m = (BMap) returnVals; String mapString = m.toString(); Assert.assertEquals(mapString, "{\"key1\":\"Element 1\",\"key2\":\"Element 2\",\"key3\":null}"); } @Test public void testBMapOrder() { - BMap map = ValueCreator.createMapValue(); + BMap map = ValueCreator.createMapValue(); map.put(StringUtils.fromString("Entry1"), StringUtils.fromString("foo")); map.put(StringUtils.fromString("Entry2"), StringUtils.fromString("bar")); map.put(StringUtils.fromString("Entry3"), StringUtils.fromString("foobar")); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/map/MapAccessExprTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/map/MapAccessExprTest.java index a2781fa49824..29a3dc5bb778 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/map/MapAccessExprTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/map/MapAccessExprTest.java @@ -78,7 +78,7 @@ public void testArrayReturnValueTest() { Assert.assertTrue(returns instanceof BMap); - BMap mapValue = (BMap) returns; + BMap mapValue = (BMap) returns; Assert.assertEquals(mapValue.size(), 3); Assert.assertEquals(mapValue.get(StringUtils.fromString("fname")).toString(), "Chanaka"); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/map/MapInitializerExprTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/map/MapInitializerExprTest.java index 4c78b1a5ff65..92bf10ae7c5e 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/map/MapInitializerExprTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/map/MapInitializerExprTest.java @@ -103,21 +103,21 @@ public void testComplexMapInit() { Object adrs1 = addressArray.getRefValue(0); Assert.assertTrue(adrs1 instanceof BMap); - Object address = ((BMap) adrs1).get(StringUtils.fromString("address")); + Object address = ((BMap) adrs1).get(StringUtils.fromString("address")); Assert.assertTrue(address instanceof BMap); - Assert.assertEquals(((BMap) address).get(StringUtils.fromString("city")).toString(), "Colombo"); + Assert.assertEquals(((BMap) address).get(StringUtils.fromString("city")).toString(), "Colombo"); Object adrs2 = addressArray.getRefValue(1); Assert.assertTrue(adrs2 instanceof BMap); - address = ((BMap) adrs2).get(StringUtils.fromString("address")); + address = ((BMap) adrs2).get(StringUtils.fromString("address")); Assert.assertTrue(address instanceof BMap); - Assert.assertEquals(((BMap) address).get(StringUtils.fromString("city")).toString(), "Kandy"); + Assert.assertEquals(((BMap) address).get(StringUtils.fromString("city")).toString(), "Kandy"); Object adrs3 = addressArray.getRefValue(2); Assert.assertTrue(adrs3 instanceof BMap); - address = ((BMap) adrs3).get(StringUtils.fromString("address")); + address = ((BMap) adrs3).get(StringUtils.fromString("address")); Assert.assertTrue(address instanceof BMap); - Assert.assertEquals(((BMap) address).get(StringUtils.fromString("city")).toString(), "Galle"); + Assert.assertEquals(((BMap) address).get(StringUtils.fromString("city")).toString(), "Galle"); } @Test() @@ -162,7 +162,7 @@ public void testEmptyMap() { Object returns = BRunUtil.invoke(compileResult, "testEmptyMap", new Object[]{}); Assert.assertTrue(returns instanceof BMap, "empty map initialization with {}"); - Assert.assertEquals(((BMap) returns).size(), 0, "incorrect empty map size"); + Assert.assertEquals(((BMap) returns).size(), 0, "incorrect empty map size"); } @Test diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/readonly/ReadonlyArrayCreator.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/readonly/ReadonlyArrayCreator.java index 58ff8d646f23..386bbefdcfff 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/readonly/ReadonlyArrayCreator.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/readonly/ReadonlyArrayCreator.java @@ -28,7 +28,10 @@ /** * Interop functions for readonly array creation. */ -public class ReadonlyArrayCreator { +public final class ReadonlyArrayCreator { + + private ReadonlyArrayCreator() { + } public static BArray createIntArray() { long[] numbers = {1000, 2000, 3000}; @@ -55,7 +58,7 @@ public static BArray createStringArray() { return ValueCreator.createReadonlyArrayValue(numbers); } - public static BArray createArrayOfMaps(BMap map) { + public static BArray createArrayOfMaps(BMap map) { return ValueCreator.createArrayValue(TypeCreator.createArrayType(map.getType(), 0, true)); } } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/string/BStringAnnotationTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/string/BStringAnnotationTest.java index 8076d3630017..522b32fa97c7 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/string/BStringAnnotationTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/string/BStringAnnotationTest.java @@ -38,6 +38,7 @@ public void testAnnotation() { testAndAssert("testAnnotation", 8); } + @Override @AfterClass public void tearDown() { result = null; diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/string/BStringJsonTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/string/BStringJsonTest.java index 5e9cfacd51c1..8b9ed89f5e23 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/string/BStringJsonTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/string/BStringJsonTest.java @@ -43,6 +43,7 @@ public void testJsonOptionalAccess() { testAndAssert("testJsonOptionalAccess", 9); } + @Override @AfterClass public void tearDown() { result = null; diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/string/BStringMainTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/string/BStringMainTest.java index 29ef72d19801..7e1200dd5052 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/string/BStringMainTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/string/BStringMainTest.java @@ -43,6 +43,7 @@ public void testJsonOptionalAccess() { testAndAssert("testJsonOptionalAccess", 9); } + @Override @AfterClass public void tearDown() { result = null; diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/string/BStringObjectTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/string/BStringObjectTest.java index 1b8d6acc9f35..1ae21f7ef070 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/string/BStringObjectTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/string/BStringObjectTest.java @@ -48,6 +48,7 @@ public void testObjectSet() { testAndAssert("testObjectSet", 8); } + @Override @AfterClass public void tearDown() { result = null; diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/string/BStringTableValueTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/string/BStringTableValueTest.java index 4e66372f9962..ec78e19ce99a 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/string/BStringTableValueTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/string/BStringTableValueTest.java @@ -44,6 +44,7 @@ public void testTableWithArrayGeneration() { testAndAssert("testTableWithArrayGeneration", 55); } + @Override @AfterClass public void tearDown() { result = null; diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/string/BStringToStringTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/string/BStringToStringTest.java index 6a874c6a23d6..fbfce166f3fe 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/string/BStringToStringTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/string/BStringToStringTest.java @@ -90,6 +90,7 @@ public String[] toStringTestFunctions() { return new String[]{"testFutureValueToString", "testFutureValueToStringWithNilReturn"}; } + @Override @AfterClass public void tearDown() { result = null; diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/string/StringValueBasicsTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/string/StringValueBasicsTest.java index e667e357ea75..ae94910a4f9c 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/string/StringValueBasicsTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/string/StringValueBasicsTest.java @@ -81,6 +81,7 @@ public void testCastToString() { testAndAssert("anydataToStringCast", 6); } + @Override @AfterClass public void tearDown() { result = null; diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/string/StringValueXmlTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/string/StringValueXmlTest.java index 980ec9e9b9aa..227727dcbed1 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/string/StringValueXmlTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/string/StringValueXmlTest.java @@ -73,6 +73,7 @@ public void testXmlInterpolation() { testAndAssert("testXmlInterpolation", 249); } + @Override @AfterClass public void tearDown() { result = null; diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/xml/XMLAttributesTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/xml/XMLAttributesTest.java index b990c23dcc15..be07d061d7a8 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/xml/XMLAttributesTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/xml/XMLAttributesTest.java @@ -30,6 +30,7 @@ import org.testng.annotations.Test; import java.io.ByteArrayOutputStream; +import java.io.IOException; import java.io.PrintStream; /** @@ -267,21 +268,15 @@ public void testCharacterReferencesInXmlAttributeValue() { } @Test - public void testPrintAttribMap() { + public void testPrintAttribMap() throws IOException { PrintStream original = System.out; - ByteArrayOutputStream outContent = new ByteArrayOutputStream(); - try { + try (ByteArrayOutputStream outContent = new ByteArrayOutputStream()) { System.setOut(new PrintStream(outContent)); BRunUtil.invoke(xmlAttrProgFile, "testPrintAttribMap"); Assert.assertEquals(outContent.toString(), - "{\"{http://www.w3.org/2000/xmlns/}xmlns\":\"http://sample.com/wso2/c1\",\"name\":\"Foo\"}", - "Invalid attribute map printed"); + "{\"{http://www.w3.org/2000/xmlns/}xmlns\":\"http://sample.com/wso2/c1\",\"name\":\"Foo\"}", + "Invalid attribute map printed"); } finally { - try { - outContent.close(); - } catch (Throwable t) { - // ignore - } System.setOut(original); } } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/xml/XMLLiteralTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/xml/XMLLiteralTest.java index 67b2a38df455..f456d7503044 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/xml/XMLLiteralTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/xml/XMLLiteralTest.java @@ -353,7 +353,7 @@ public void testXMLLiteralWithEscapeSequence() { private String arrayToString(Object aReturn) { BArray ar = ((BArray) aReturn); StringBuilder builder = new StringBuilder(); - BIterator bIterator = ar.getIterator(); + BIterator bIterator = ar.getIterator(); while (bIterator.hasNext()) { String str = bIterator.next().toString(); builder.append(str); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/utils/BStringUtils.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/utils/BStringUtils.java index 0baae0f12e01..2d32fc706a15 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/utils/BStringUtils.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/utils/BStringUtils.java @@ -24,7 +24,10 @@ /** * A util class that is useful with bstring array related test operations. */ -public class BStringUtils { +public final class BStringUtils { + + private BStringUtils() { + } public static BString[] getBStringArray(String[] s) { BString[] bStringArray = new BString[s.length]; diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/utils/ByteArrayUtils.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/utils/ByteArrayUtils.java index 7a59a4bc54d3..593028dcf1a6 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/utils/ByteArrayUtils.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/utils/ByteArrayUtils.java @@ -26,7 +26,10 @@ /** * A util class that is useful with byte array related operations. */ -public class ByteArrayUtils { +public final class ByteArrayUtils { + + private ByteArrayUtils() { + } public static byte[] decodeBase64(String b64) { return Base64.getDecoder().decode(b64.getBytes(StandardCharsets.UTF_8)); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/utils/ResponseReader.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/utils/ResponseReader.java index 4f6160c90be0..55a77db8d489 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/utils/ResponseReader.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/utils/ResponseReader.java @@ -31,9 +31,13 @@ /** * Utility class for managing responses. */ -public class ResponseReader { +public final class ResponseReader { + private static final Logger LOG = LoggerFactory.getLogger(ResponseReader.class); + private ResponseReader() { + } + /** * Get the response value from input stream. * diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/utils/interop/Utils.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/utils/interop/Utils.java index 54ffa6f1e70b..24eca7db1cab 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/utils/interop/Utils.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/utils/interop/Utils.java @@ -31,12 +31,15 @@ * * @since 2.0.0 */ -public class Utils { +public final class Utils { private static final int CORE_THREAD_POOL_SIZE = 1; private static ScheduledExecutorService executor = Executors.newScheduledThreadPool(CORE_THREAD_POOL_SIZE); + private Utils() { + } + public static void sleep(Environment env, long delayMillis) { Future balFuture = env.markAsync(); executor.schedule(() -> balFuture.complete(null), delayMillis, TimeUnit.MILLISECONDS); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/worker/BasicWorkerTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/worker/BasicWorkerTest.java index 9b9fa572f6d0..be5eb8a82b66 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/worker/BasicWorkerTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/worker/BasicWorkerTest.java @@ -18,6 +18,7 @@ import io.ballerina.runtime.api.utils.StringUtils; import io.ballerina.runtime.api.values.BMap; +import io.ballerina.runtime.api.values.BString; import org.ballerinalang.test.BAssertUtil; import org.ballerinalang.test.BCompileUtil; import org.ballerinalang.test.BRunUtil; @@ -87,7 +88,7 @@ public void workerReturnTest() { @Test public void workerSameThreadSchedulingTest() { Object vals = BRunUtil.invoke(result, "workerSameThreadTest", new Object[0]); - BMap result = (BMap) vals; + BMap result = (BMap) vals; Assert.assertEquals(result.get(StringUtils.fromString("w")), result.get(StringUtils.fromString("w1"))); Assert.assertEquals(result.get(StringUtils.fromString("w")), result.get(StringUtils.fromString("w2"))); } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/worker/VarMutabilityWithWorkersTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/worker/VarMutabilityWithWorkersTest.java index c4ad9d2bfd4b..487801d0f9b3 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/worker/VarMutabilityWithWorkersTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/worker/VarMutabilityWithWorkersTest.java @@ -63,7 +63,7 @@ public void testWithTuples() { @Test(description = "Test variable mutability with maps") public void testWithMaps() { Object returns = BRunUtil.invoke(compileResult, "testWithMaps"); - BMap resMap = (BMap) returns; + BMap resMap = (BMap) returns; Assert.assertEquals(resMap.size(), 7); Assert.assertEquals(resMap.get(StringUtils.fromString("a")).toString(), "AAAA"); Assert.assertEquals(resMap.get(StringUtils.fromString("b")).toString(), "B"); @@ -80,7 +80,7 @@ public void complexWorkerTest() { Assert.assertEquals(returns.size(), 2); Assert.assertEquals(returns.get(0), 400L); - BMap resMap = (BMap) returns.get(1); + BMap resMap = (BMap) returns.get(1); Assert.assertEquals(resMap.size(), 6); Assert.assertEquals(resMap.get(StringUtils.fromString("a")).toString(), "AAAA"); Assert.assertEquals(resMap.get(StringUtils.fromString("b")).toString(), "BBBB"); @@ -93,7 +93,7 @@ public void complexWorkerTest() { @Test(description = "Test variable mutability with records") public void testWithRecords() { Object returns = BRunUtil.invoke(compileResult, "testWithRecords"); - Assert.assertEquals(((BMap) returns).size(), 3); + Assert.assertEquals(((BMap) returns).size(), 3); Assert.assertEquals(returns.toString(), "{\"name\":\"Adam Page\",\"age\":24,\"email\":\"adamp@wso2.com\"}"); } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/worker/WaitForAllActionsTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/worker/WaitForAllActionsTest.java index 95e5dbf55498..81b4d92ea046 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/worker/WaitForAllActionsTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/worker/WaitForAllActionsTest.java @@ -55,7 +55,7 @@ public void waitTest1() { expectedMap.put("f3", "hello foo"); expectedMap.put("f4", "true"); - Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); + Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); } @Test @@ -68,7 +68,7 @@ public void waitTest2() { expectedMap.put("f3", "150"); expectedMap.put("str2", "hello xyz"); - Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); + Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); } @Test @@ -80,7 +80,7 @@ public void waitTest3() { expectedMap.put("f3", "150"); expectedMap.put("f5", "hello bar"); - Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); + Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); } @Test @@ -92,7 +92,7 @@ public void waitTest4() { expectedMap.put("f4", "hello foo"); expectedMap.put("f2", "22"); - Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); + Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); } @Test @@ -103,7 +103,7 @@ public void waitTest5() { expectedMap.put("id", "66"); expectedMap.put("name", "hello foo"); - Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); + Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); } @Test @@ -114,7 +114,7 @@ public void waitTest6() { expectedMap.put("idField", "150"); expectedMap.put("stringField", "hello foo"); - Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); + Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); } @Test @@ -132,7 +132,7 @@ public void waitTest8() { expectedMap.put("id", "8"); expectedMap.put("name", "hello moo"); - Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); + Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); } @Test @@ -143,7 +143,7 @@ public void waitTest9() { expectedMap.put("f1", "20"); expectedMap.put("f5", "hello foo"); - Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); + Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); } @Test @@ -154,7 +154,7 @@ public void waitTest10() { expectedMap.put("f1", "30"); expectedMap.put("f5", "hello xyz"); - Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); + Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); } @Test @@ -165,7 +165,7 @@ public void waitTest11() { expectedMap.put("f1", "30"); expectedMap.put("field", "hello bar"); - Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); + Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); } @Test @@ -175,7 +175,7 @@ public void waitTest12() { Map expectedMap = new HashMap<>(); expectedMap.put("id", "86"); - Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); + Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); } @Test(expectedExceptions = {BLangTestException.class}, @@ -207,9 +207,9 @@ public void waitTest16() { public void waitTest17() { Object returns = BRunUtil.invoke(result, "waitTest17"); - Assert.assertEquals(((BMap) returns).values().size(), 2); - BMap val1 = (BMap) ((BMap) returns).get(StringUtils.fromString("f1")); - BMap val2 = (BMap) ((BMap) returns).get(StringUtils.fromString("f2")); + Assert.assertEquals(((BMap) returns).values().size(), 2); + BMap val1 = (BMap) ((BMap) returns).get(StringUtils.fromString("f1")); + BMap val2 = (BMap) ((BMap) returns).get(StringUtils.fromString("f2")); Assert.assertEquals(val1.get(StringUtils.fromString("f1")), 7L); Assert.assertEquals(val1.get(StringUtils.fromString("f2")), 150L); Assert.assertEquals(val2.get(StringUtils.fromString("name")).toString(), "hello foo"); @@ -224,7 +224,7 @@ public void waitTest18() { expectedMap.put("f5", "hello foo"); expectedMap.put("f1", "7"); - Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); + Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); } @Test @@ -235,7 +235,7 @@ public void waitTest19() { expectedMap.put("w1", "30"); expectedMap.put("w2", "16"); - Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); + Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); } @Test @@ -246,7 +246,7 @@ public void waitTest20() { expectedMap.put("w2", "hello world"); expectedMap.put("w3", "15"); - Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); + Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); } @Test @@ -257,7 +257,7 @@ public void waitTest21() { expectedMap.put("id", "7"); expectedMap.put("name", "hello foo"); - Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); + Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); } @Test @@ -269,7 +269,7 @@ public void waitTest22() { expectedMap.put("name", "hello foo"); expectedMap.put("status", "hello bar"); - Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); + Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); } @Test @@ -281,7 +281,7 @@ public void waitTest23() { expectedMap.put("name", "hello foo"); expectedMap.put("status", "20"); - Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); + Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); } @Test @@ -293,7 +293,7 @@ public void waitTest24() { expectedMap.put("name", "hello foo"); expectedMap.put("status", "hello bar"); - Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); + Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); } @Test @@ -303,7 +303,7 @@ public void waitTest25() { Map expectedMap = new HashMap<>(); expectedMap.put("id", "7"); expectedMap.put("name", "hello foo"); - Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); + Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); } @Test @@ -315,10 +315,10 @@ public void waitTest26() { expectedMap.put("name", "hello world"); expectedMap.put("status", "hello moo"); - Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap(((BMap) returns)))); + Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap(((BMap) returns)))); } - private Map getResultMap(BMap returns) { + private Map getResultMap(BMap returns) { Map resultMap = new HashMap<>(); for (Object key : returns.getKeys()) { resultMap.put(key.toString(), returns.get(key).toString()); @@ -335,7 +335,7 @@ public void waitTest27() { expectedMap.put("name", "hello mello"); expectedMap.put("greet", "hello sunshine"); - Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); + Assert.assertTrue(mapsAreEqual(expectedMap, getResultMap((BMap) returns))); } /** diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/worker/WorkerSyncSendTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/worker/WorkerSyncSendTest.java index ce0933ac4e90..8ad28505adb4 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/worker/WorkerSyncSendTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/worker/WorkerSyncSendTest.java @@ -171,7 +171,7 @@ public void errorResultWithMultipleWorkers() { public void testComplexTypeSend() { Object returns = BRunUtil.invoke(result, "testComplexType"); Assert.assertEquals(getType(returns).getName(), "Rec"); - Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("k")), 10L); + Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("k")), 10L); } @Test diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/worker/WorkerTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/worker/WorkerTest.java index ad54efc92529..7d7eee126d88 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/worker/WorkerTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/worker/WorkerTest.java @@ -278,7 +278,7 @@ public void testComplexTypeSend() { Object returns = BRunUtil.invoke(result, "testComplexType"); Assert.assertEquals(getType(returns).getName(), "Rec"); - Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("k")), 10L); + Assert.assertEquals(((BMap) returns).get(StringUtils.fromString("k")), 10L); } @Test @@ -296,7 +296,7 @@ public void waitInReturn() { Object returns = BRunUtil.invoke(result, "waitInReturn"); Assert.assertTrue(returns instanceof BMap); - BMap mapResult = (BMap) returns; + BMap mapResult = (BMap) returns; Assert.assertEquals(mapResult.get(StringUtils.fromString("w1")).toString(), "w1"); Assert.assertEquals(mapResult.get(StringUtils.fromString("w2")).toString(), "w2"); } diff --git a/tests/jballerina-unit-test/src/test/resources/test-src/bala/test_bala/object/test_object_type_inclusion_negative.bal b/tests/jballerina-unit-test/src/test/resources/test-src/bala/test_bala/object/test_object_type_inclusion_negative.bal index 3ae25a059e48..93501b816f82 100644 --- a/tests/jballerina-unit-test/src/test/resources/test-src/bala/test_bala/object/test_object_type_inclusion_negative.bal +++ b/tests/jballerina-unit-test/src/test/resources/test-src/bala/test_bala/object/test_object_type_inclusion_negative.bal @@ -65,3 +65,10 @@ readonly service class BarClass { isolated remote function execute(string cVar, int dVar, int eVar) { } } + +readonly service class BazClass { + *foo:FooObj; + + public isolated function execute(string aVar, int bVar) { + } +} diff --git a/tests/jballerina-unit-test/src/test/resources/test-src/expressions/binaryoperations/ref_equal_and_not_equal_operation.bal b/tests/jballerina-unit-test/src/test/resources/test-src/expressions/binaryoperations/ref_equal_and_not_equal_operation.bal index b598108f53b4..6e63ea100f3a 100644 --- a/tests/jballerina-unit-test/src/test/resources/test-src/expressions/binaryoperations/ref_equal_and_not_equal_operation.bal +++ b/tests/jballerina-unit-test/src/test/resources/test-src/expressions/binaryoperations/ref_equal_and_not_equal_operation.bal @@ -465,8 +465,11 @@ function testXMLSequenceRefEquality() { xml x1 = xml `b`; xml x2 = x + x1; xml x3 = x + x1; + xml x4 = xml:concat(x); + xml x5 = xml:concat(x); test:assertTrue(x2 === x3); + test:assertTrue(x4 === x5); xml a1 = xml ``; xml a2 = xml ``; diff --git a/tests/jballerina-unit-test/src/test/resources/test-src/javainterop/dependently_typed_functions_test.bal b/tests/jballerina-unit-test/src/test/resources/test-src/javainterop/dependently_typed_functions_test.bal index 70e14bc5b1d4..49817c076771 100644 --- a/tests/jballerina-unit-test/src/test/resources/test-src/javainterop/dependently_typed_functions_test.bal +++ b/tests/jballerina-unit-test/src/test/resources/test-src/javainterop/dependently_typed_functions_test.bal @@ -326,6 +326,12 @@ function getArray(typedesc td) returns td[] = @java:Method { paramTypes: ["io.ballerina.runtime.api.values.BTypedesc"] } external; +function getArrayInferred(typedesc td = <>) returns td[] = @java:Method { + 'class: "org.ballerinalang.nativeimpl.jvm.tests.VariableReturnType", + name: "getArray", + paramTypes: ["io.ballerina.runtime.api.values.BTypedesc"] +} external; + function getInvalidValue(typedesc td1, typedesc td2) returns td1 = @java:Method { 'class: "org.ballerinalang.nativeimpl.jvm.tests.VariableReturnType", name: "getInvalidValue", @@ -973,6 +979,11 @@ function testDependentlyTypedResourceMethods() { assert(0, checkpanic c); } +function testDependentlyTypedFunctionWithTypeReferenceType() returns error? { + IntArray arr = check getArrayInferred(); + assert([10, 20, 30], arr); +} + // Util functions function assert(anydata expected, anydata actual) { if (expected != actual) { diff --git a/tests/jballerina-unit-test/src/test/resources/test-src/javainterop/dependently_typed_functions_test_negative.bal b/tests/jballerina-unit-test/src/test/resources/test-src/javainterop/dependently_typed_functions_test_negative.bal index d6e8c880139d..5e571b2a5d4b 100644 --- a/tests/jballerina-unit-test/src/test/resources/test-src/javainterop/dependently_typed_functions_test_negative.bal +++ b/tests/jballerina-unit-test/src/test/resources/test-src/javainterop/dependently_typed_functions_test_negative.bal @@ -370,3 +370,15 @@ function testDependentlyTypedFunctionWithInferredArgForParamOfTypeReferenceTypeN var _ = functionWithInferredArgForParamOfTypeReferenceType(boolean); } + +function getArrayInferred(typedesc td = <>) returns td[] = @java:Method { + 'class: "org.ballerinalang.nativeimpl.jvm.tests.VariableReturnType", + name: "getArray", + paramTypes: ["io.ballerina.runtime.api.values.BTypedesc"] +} external; + +type AnyArray any[]; + +function testDependentlyTypedFunctionWithTypeReferenceTypeNegative() returns error? { + AnyArray _ = check getArrayInferred(); +} diff --git a/tests/jballerina-unit-test/src/test/resources/test-src/jvm/types.bal b/tests/jballerina-unit-test/src/test/resources/test-src/jvm/types.bal index 25cef3d454fa..16ead37beef1 100644 --- a/tests/jballerina-unit-test/src/test/resources/test-src/jvm/types.bal +++ b/tests/jballerina-unit-test/src/test/resources/test-src/jvm/types.bal @@ -90,6 +90,13 @@ function testIntToByteExplicitCast(int b) returns byte|error { return a; } +function testXMLSequenceWithOneTextMember() { + xml text1 = xml `abcdef`; + xml text2 = xml:map(xml:elements(text1), y => y.getChildren()); + xml:Text text3 = xml `abcdef`; + assertEquality(text2 == text3, true); +} + function testByteArray() returns byte[] { byte[] ba = [12, 24, 7]; return ba; diff --git a/tests/jballerina-unit-test/src/test/resources/test-src/object/object-type-reference.bal b/tests/jballerina-unit-test/src/test/resources/test-src/object/object-type-reference.bal index 690e63fdc070..7d42e70805a7 100644 --- a/tests/jballerina-unit-test/src/test/resources/test-src/object/object-type-reference.bal +++ b/tests/jballerina-unit-test/src/test/resources/test-src/object/object-type-reference.bal @@ -395,6 +395,30 @@ function testInclusionWithDifferentParamNames() { assertEquality(6, subClass.subtract(8, 2)); } +public type ClientObject client object { + isolated remote function execute(string aVar, int bVar) returns int|error; +}; + +client class ClientClass { + *ClientObject; + + isolated remote function execute(string aVar, int bVar) returns int|error { + return check int:fromString(aVar) + bVar; + } +} + +function testInclusionWithRemoteMethods() { + ClientObject cOb = new ClientClass(); + int|error r1 = cOb->execute("10", 5); + assertEquality(15, r1); + + int|error r2 = cOb->execute("10s", 5); + assertEquality(true, r2 is error); + error err = r2; + assertEquality("{ballerina/lang.int}NumberParsingError", err.message()); + assertEquality("'string' value '10s' cannot be converted to 'int'", err.detail()["message"]); +} + const ASSERTION_ERROR_REASON = "AssertionError"; function assertEquality(any|error expected, any|error actual) { diff --git a/tests/jballerina-unit-test/src/test/resources/test-src/object/object_func_reference_neg.bal b/tests/jballerina-unit-test/src/test/resources/test-src/object/object_func_reference_neg.bal index a529ece0c93d..846fe321454c 100644 --- a/tests/jballerina-unit-test/src/test/resources/test-src/object/object_func_reference_neg.bal +++ b/tests/jballerina-unit-test/src/test/resources/test-src/object/object_func_reference_neg.bal @@ -103,3 +103,26 @@ readonly class InvalidReadOnlyClassWithMissingImpls { public function toInt() returns int => 0; } + +public type FooObj client object { + isolated remote function execute(string aVar, int bVar); + public function pause(string aVar, int bVar); +}; + +client class BarClass { + *FooObj; + + public isolated function execute(string aVar, int bVar) { + } + + remote function pause(string aVar, int bVar) { + } +} + +type BazObj client object { + *FooObj; + + public isolated function execute(string aVar, int bVar); + + remote function pause(string aVar, int bVar); +}; diff --git a/tests/jballerina-unit-test/src/test/resources/test-src/object/readonly_objects.bal b/tests/jballerina-unit-test/src/test/resources/test-src/object/readonly_objects.bal index 05a83a338408..862992621617 100644 --- a/tests/jballerina-unit-test/src/test/resources/test-src/object/readonly_objects.bal +++ b/tests/jballerina-unit-test/src/test/resources/test-src/object/readonly_objects.bal @@ -315,6 +315,21 @@ public function testRecursiveObjectArrayReadonlyClone() { assertTrue(x is readonly & Obj[]); } +public function testReadonlyObjectMethodCall() { + File file = new VirtualFile(); + string filename = file.filename(); + assertEquality("File Name", filename); +} + +public type File readonly & object { + public function filename() returns string; +}; + +public readonly class VirtualFile { + *File; + public function filename() returns string => "File Name"; +} + const ASSERTION_ERROR_REASON = "AssertionError"; function assertTrue(any|error actual) { diff --git a/tests/jballerina-unit-test/src/test/resources/test-src/query/query_with_closures.bal b/tests/jballerina-unit-test/src/test/resources/test-src/query/query_with_closures.bal index b7864e02c118..370c751116b2 100644 --- a/tests/jballerina-unit-test/src/test/resources/test-src/query/query_with_closures.bal +++ b/tests/jballerina-unit-test/src/test/resources/test-src/query/query_with_closures.bal @@ -166,10 +166,15 @@ function testClosureInQueryActionInDo2() { do { from var k in 5 ... 7 do { - var x = from var i in 1 ... 2 select (from var t in 3 ... 4 where t == k select t); + var x = from var i in 1 ... 2 + select (from var t in 5 ... 7 + where t == k + select t); + arr.push(...x[0]); + arr.push(...x[1]); }; }; - assertEquality([6, 7, 8, 7, 8, 9, 8, 9, 10, 9, 10, 11, 10, 11, 12], arr); + assertEquality([5, 5, 6, 6, 7, 7, 5, 5, 6, 6, 7, 7, 5, 5, 6, 6, 7, 7, 5, 5, 6, 6, 7, 7, 5, 5, 6, 6, 7, 7], arr); } class EvenNumberGenerator { diff --git a/tests/jballerina-unit-test/src/test/resources/test-src/record/closed_record_type_inclusion.bal b/tests/jballerina-unit-test/src/test/resources/test-src/record/closed_record_type_inclusion.bal index 04e896c57eee..ec43cd156b5a 100644 --- a/tests/jballerina-unit-test/src/test/resources/test-src/record/closed_record_type_inclusion.bal +++ b/tests/jballerina-unit-test/src/test/resources/test-src/record/closed_record_type_inclusion.bal @@ -291,9 +291,111 @@ function testTypeInclusionWithFiniteField() { assertEquality(true, expr is UnaryExpr); } +isolated int count1 = 0; +isolated int count2 = 0; + +isolated function getDefaultVal1() returns Val1 { + lock { + count1 = count1 + 1; + } + return {val: 10}; +} + +isolated function getDefaultVal2() returns Val2 { + lock { + count2 = count2 + 1; + } + return {val: 3.3}; +} + +type Val1 record {| + int val; +|}; + +type Val2 record {| + float val; +|}; + +type Base1 record {| + Val1 val1 = getDefaultVal1(); +|}; + +type BO1 record {| + Val1 val1?; +|}; + +type Base2 record {| + Val2 val2 = getDefaultVal2(); +|}; + +type BO2 record {| + Val2 val2?; +|}; + +type Derived record {| + *Base1; + *Base2; +|}; + +isolated function testDefaultValueFromInclusion() { + BO1 bo1 = {}; + BO2 bo2 = {}; + Derived d = {...bo1, ...bo2}; + assertEquality(10, d.val1.val); + assertEquality(3.3, d.val2.val); + lock { + assertEquality(1, count1); + } + lock { + assertEquality(1, count2); + } + + BO1 bo3 = {val1: {val: 20}}; + Derived d1 = {...bo3, ...bo2}; + assertEquality(20, d1.val1.val); + assertEquality(3.3, d1.val2.val); + lock { + assertEquality(1, count1); + } + lock { + assertEquality(2, count2); + } + + BO2 bo4 = {val2: {val: 30.3}}; + Derived d2 = {...bo3, ...bo4}; + assertEquality(20, d2.val1.val); + assertEquality(30.3, d2.val2.val); + lock { + assertEquality(1, count1); + } + lock { + assertEquality(2, count2); + } + + Derived d3 = {}; + assertEquality(10, d3.val1.val); + assertEquality(3.3, d3.val2.val); + lock { + assertEquality(2, count1); + } + lock { + assertEquality(3, count2); + } + + Derived d4 = {val1: {val: 40}, val2: {val: 50.5}}; + assertEquality(40, d4.val1.val); + assertEquality(50.5, d4.val2.val); + lock { + assertEquality(2, count1); + } + lock { + assertEquality(3, count2); + } +} + const ASSERTION_ERROR_REASON = "AssertionError"; -function assertEquality(any|error expected, any|error actual) { +isolated function assertEquality(any|error expected, any|error actual) { if expected is anydata && actual is anydata && expected == actual { return; } diff --git a/tests/jballerina-unit-test/src/test/resources/test-src/record/open_record_type_inclusion.bal b/tests/jballerina-unit-test/src/test/resources/test-src/record/open_record_type_inclusion.bal index dc96e34252e2..2c093b73eb54 100644 --- a/tests/jballerina-unit-test/src/test/resources/test-src/record/open_record_type_inclusion.bal +++ b/tests/jballerina-unit-test/src/test/resources/test-src/record/open_record_type_inclusion.bal @@ -289,9 +289,158 @@ function testDefaultValuesOfRecordFieldsWithTypeInclusion() { assertEquality(30, info1.age); } +type Inner record {| + int foo; +|}; + +type Outer record {| + Inner inner?; +|}; + +isolated int count = 0; + +isolated function getDefaultInner() returns Inner { + lock { + count += 1; + } + return {foo: 10}; +} + +type OuterXBase record { + Inner inner = getDefaultInner(); +}; + +type OuterX record {| + *OuterXBase; +|}; + +type OuterXOpenRecord record {| + *OuterXBase; + Inner...; +|}; + +type InnerOpenRec record {| + Inner...; +|}; + +type OuterXAlsoClosed record {| + *OuterXBase; + never...; +|}; + +type EffectivelyCloseRecord record {| + *OuterXBase; + record {| + never bar; + |}...; +|}; + +isolated function testDefaultValueFromInclusion() { + Outer o = {}; + OuterX ox = {...o}; + assertEquality(ox.inner.foo, 10); + lock { + assertEquality(1, count); + } + Outer o1 = {inner: {foo: 20}}; + OuterX ox1 = {...o1}; + assertEquality(20, ox1.inner.foo); + lock { + assertEquality(1, count); + } + map innerMap = {}; + OuterX ox2 = {...innerMap}; + assertEquality(10, ox2.inner.foo); + lock { + assertEquality(2, count); + } + + map innerMap1 = {inner: {foo: 20}}; + OuterX ox3 = {...innerMap1}; + assertEquality(20, ox3.inner.foo); + lock { + assertEquality(2, count); + } + + InnerOpenRec innerMap2 = {"inner": {foo: 20}}; + + OuterX ox4 = {...innerMap2}; + assertEquality(20, ox4.inner.foo); + lock { + assertEquality(2, count); + } + + OuterXOpenRecord ox5 = {...innerMap2}; + assertEquality(20, ox5.inner.foo); + lock { + assertEquality(2, count); + } + + OuterXOpenRecord ox6 = {...o}; + assertEquality(10, ox6.inner.foo); + lock { + assertEquality(3, count); + } + + OuterXAlsoClosed oxx = {...o}; + assertEquality(oxx.inner.foo, 10); + lock { + assertEquality(4, count); + } + OuterXAlsoClosed oxx1 = {...o1}; + assertEquality(20, oxx1.inner.foo); + lock { + assertEquality(4, count); + } + + OuterX ox7 = {}; + assertEquality(ox7.inner.foo, 10); + lock { + assertEquality(5, count); + } + + OuterX ox8 = {inner: {foo: 20}}; + assertEquality(ox8.inner.foo, 20); + lock { + assertEquality(5, count); + } + + EffectivelyCloseRecord ecr = {...o}; + assertEquality(ecr.inner.foo, 10); + lock { + assertEquality(6, count); + } + + EffectivelyCloseRecord ecr1 = {...o1}; + assertEquality(ecr1.inner.foo, 20); + lock { + assertEquality(6, count); + } +} + +type Data record { + string id = fn(); + string name; +}; + +type OpenData record {| + string name; + string...; +|}; + +isolated function fn() returns string { + panic error("shouldn't be called"); +} + +public function testSpreadOverrideDefault() { + OpenData or = {name: "May", "id": "A1234"}; + Data emp = {...or}; + assertEquality("A1234", emp.id); +} + const ASSERTION_ERROR_REASON = "AssertionError"; -function assertEquality(any|error expected, any|error actual) { +isolated function assertEquality(any|error expected, any|error actual) { if expected is anydata && actual is anydata && expected == actual { return; } diff --git a/tests/language-server-integration-tests/src/test/java/org/ballerinalang/langserver/test/codeaction/CompilerPluginCodeActionTests.java b/tests/language-server-integration-tests/src/test/java/org/ballerinalang/langserver/test/codeaction/CompilerPluginCodeActionTests.java index 38423b115d24..43d7abc39a4d 100644 --- a/tests/language-server-integration-tests/src/test/java/org/ballerinalang/langserver/test/codeaction/CompilerPluginCodeActionTests.java +++ b/tests/language-server-integration-tests/src/test/java/org/ballerinalang/langserver/test/codeaction/CompilerPluginCodeActionTests.java @@ -34,6 +34,7 @@ public void compilePlugins() { BCompileUtil.compileAndCacheBala("compiler_plugin_tests/package_comp_plugin_with_codeactions"); } + @Override @Test(dataProvider = "codeaction-data-provider") public void test(String config) throws IOException, WorkspaceDocumentException { super.test(config); diff --git a/tests/language-server-integration-tests/src/test/java/org/ballerinalang/langserver/test/hover/ApiDocsUrlTest.java b/tests/language-server-integration-tests/src/test/java/org/ballerinalang/langserver/test/hover/ApiDocsUrlTest.java index 7e9646ce6288..abaf5da2df0d 100644 --- a/tests/language-server-integration-tests/src/test/java/org/ballerinalang/langserver/test/hover/ApiDocsUrlTest.java +++ b/tests/language-server-integration-tests/src/test/java/org/ballerinalang/langserver/test/hover/ApiDocsUrlTest.java @@ -40,7 +40,7 @@ public void test(String orgName, String moduleName, String version, String const connection.connect(); int code = connection.getResponseCode(); connection.disconnect(); - Assert.assertEquals(code, 200, "API Docs URL is not valid: " + urlString + "received code: " + code); + Assert.assertEquals(code, 200, "API Docs URL is not valid: " + urlString + " received code: " + code); } @DataProvider(name = "data-provider") diff --git a/tests/testerina-integration-test/src/test/java/org/ballerinalang/testerina/test/BaseTestCase.java b/tests/testerina-integration-test/src/test/java/org/ballerinalang/testerina/test/BaseTestCase.java index 876ed489448b..7979e245e3a1 100644 --- a/tests/testerina-integration-test/src/test/java/org/ballerinalang/testerina/test/BaseTestCase.java +++ b/tests/testerina-integration-test/src/test/java/org/ballerinalang/testerina/test/BaseTestCase.java @@ -68,10 +68,8 @@ public void destroy() { @AfterSuite public void copyBallerinaExecFiles() { List packageDirs; - try { - packageDirs = Files.walk(projectBasedTestsPath, 1) - .filter(Files::isDirectory) - .toList(); + try (Stream paths = Files.walk(projectBasedTestsPath, 1)) { + packageDirs = paths.filter(Files::isDirectory).toList(); for (Path dir : packageDirs) { try { FileUtils.copyBallerinaExec(dir, ""); diff --git a/tests/testerina-integration-test/src/test/java/org/ballerinalang/testerina/test/CodeCoverageReportTest.java b/tests/testerina-integration-test/src/test/java/org/ballerinalang/testerina/test/CodeCoverageReportTest.java index 31f54c1458ed..1a5ad77320d2 100644 --- a/tests/testerina-integration-test/src/test/java/org/ballerinalang/testerina/test/CodeCoverageReportTest.java +++ b/tests/testerina-integration-test/src/test/java/org/ballerinalang/testerina/test/CodeCoverageReportTest.java @@ -149,6 +149,20 @@ public void multipleModulePkgCoverageTest() throws BallerinaTestException { "testerina_report/foo&0046bar/0/constants", "test-report-tests/modules/bar", "testerina_report/foo$test/0/creators", + "testerina_report/foo&0046annot$test/0/constants", + "testerina_report/foo&0046annot/0/creators", + "testerina_report/foo&0046annot/0/annotations", + "testerina_report/foo&0046annot/0/types", + "testerina_report/foo&0046annot/0", + "testerina_report/foo&0046annot/0/constants", + "testerina_report/foo&0046annot/0/functions", + "testerina_report/foo&0046annot/0/lambdas", + "testerina_report/foo&0046annot$test/0/annotations", + "testerina_report/foo&0046annot$test/0/creators", + "testerina_report/foo&0046annot$test/0/types", + "testerina_report/foo&0046annot$test/0", + "test-report-tests/modules/annot", + "test-report-tests/modules/annot/lambdas", "testerina_report/foo/0/functions", "testerina_report/foo/0/lambdas" ); @@ -193,6 +207,9 @@ private HashMap> getExpectedCoverageClasses() { "/modules/math/divide", multiModuleTestRoot + "/modules/math/foo$$$math")); coverageClassMap.put(multiModuleTestRoot + "/modules/bar.tests", List.of(multiModuleTestRoot + "/modules/bar.tests/foo$$$bar$$$tests")); + coverageClassMap.put(multiModuleTestRoot + "modules/annot", + Arrays.asList(multiModuleTestRoot + "/modules/annot/main", + multiModuleTestRoot + "/modules/annot/$value$ZeroDiffAnnot")); return coverageClassMap; } diff --git a/tests/testerina-integration-test/src/test/java/org/ballerinalang/testerina/test/TestReportTest.java b/tests/testerina-integration-test/src/test/java/org/ballerinalang/testerina/test/TestReportTest.java index 30e798b8b463..4dd14939d477 100644 --- a/tests/testerina-integration-test/src/test/java/org/ballerinalang/testerina/test/TestReportTest.java +++ b/tests/testerina-integration-test/src/test/java/org/ballerinalang/testerina/test/TestReportTest.java @@ -97,12 +97,14 @@ public void testWithCoverage() throws BallerinaTestException { int mathTotal = 2, mathPassed = 2, mathFailed = 0, mathSkipped = 0; int fooTotal = 3, fooPassed = 1, fooFailed = 1, fooSkipped = 1; int bartestTotal = 1, bartestPassed = 1, bartestFailed = 0, bartestSkipped = 0; + int annotTotal = 1, annotPassed = 1, annotFailed = 0, annotSkipped = 0; int[] mathStatus = {mathTotal, mathPassed, mathFailed, mathSkipped}; int[] fooStatus = {fooTotal, fooPassed, fooFailed, fooSkipped}; int[] bartestStatus = {bartestTotal, bartestPassed, bartestFailed, bartestSkipped}; + int[] annotStatus = {annotTotal, annotPassed, annotFailed, annotSkipped}; - validateStatuses(mathStatus, fooStatus, bartestStatus); + validateStatuses(mathStatus, fooStatus, bartestStatus, annotStatus); validateCoverage(); } @@ -114,12 +116,14 @@ public void testWithoutCoverage() throws BallerinaTestException { int mathTotal = 2, mathPassed = 2, mathFailed = 0, mathSkipped = 0; int fooTotal = 2, fooPassed = 0, fooFailed = 1, fooSkipped = 1; int bartestTotal = 1, bartestPassed = 1, bartestFailed = 0, bartestSkipped = 0; + int annotTotal = 1, annotPassed = 1, annotFailed = 0, annotSkipped = 0; int[] mathStatus = {mathTotal, mathPassed, mathFailed, mathSkipped}; int[] fooStatus = {fooTotal, fooPassed, fooFailed, fooSkipped}; int[] bartestStatus = {bartestTotal, bartestPassed, bartestFailed, bartestSkipped}; + int[] annotStatus = {annotTotal, annotPassed, annotFailed, annotSkipped}; - validateStatuses(mathStatus, fooStatus, bartestStatus); + validateStatuses(mathStatus, fooStatus, bartestStatus, annotStatus); Assert.assertEquals(resultObj.get("moduleCoverage").getAsJsonArray().size(), 0); } @@ -131,12 +135,14 @@ public void testModuleWiseCoverage() throws BallerinaTestException { int mathTotal = 2, mathPassed = 2, mathFailed = 0, mathSkipped = 0; int fooTotal = 0, fooPassed = 0, fooFailed = 0, fooSkipped = 0; int bartestTotal = 0, bartestPassed = 0, bartestFailed = 0, bartestSkipped = 0; + int annotTotal = 0, annotPassed = 0, annotFailed = 0, annotSkipped = 0; int[] mathStatus = {mathTotal, mathPassed, mathFailed, mathSkipped}; int[] fooStatus = {fooTotal, fooPassed, fooFailed, fooSkipped}; int[] bartestStatus = {bartestTotal, bartestPassed, bartestFailed, bartestSkipped}; + int[] annotStatus = {annotTotal, annotPassed, annotFailed, annotSkipped}; - validateStatuses(mathStatus, fooStatus, bartestStatus); + validateStatuses(mathStatus, fooStatus, bartestStatus, annotStatus); validateModuleWiseCoverage(); } @@ -153,16 +159,18 @@ private void runCommand(String[] args) throws BallerinaTestException { } - private void validateStatuses(int[] mathStatus, int[] fooStatus, int[] bartestStatus) { + private void validateStatuses(int[] mathStatus, int[] fooStatus, int[] bartestStatus, int[] annotStatus) { validateModuleStatus(mathStatus, "foo.math"); validateModuleStatus(fooStatus, "foo"); validateModuleStatus(bartestStatus, "foo.bar.tests"); + validateModuleStatus(annotStatus, "foo.annot"); int[] overallStatus = { - mathStatus[TOTAL_TESTS] + fooStatus[TOTAL_TESTS] + bartestStatus[TOTAL_TESTS], - mathStatus[PASSED] + fooStatus[PASSED] + bartestStatus[PASSED], - mathStatus[FAILED] + fooStatus[FAILED] + bartestStatus[FAILED], - mathStatus[SKIPPED] + fooStatus[SKIPPED] + bartestStatus[SKIPPED] + mathStatus[TOTAL_TESTS] + fooStatus[TOTAL_TESTS] + bartestStatus[TOTAL_TESTS] + + annotStatus[TOTAL_TESTS], + mathStatus[PASSED] + fooStatus[PASSED] + bartestStatus[PASSED] + annotStatus[PASSED], + mathStatus[FAILED] + fooStatus[FAILED] + bartestStatus[FAILED] + annotStatus[FAILED], + mathStatus[SKIPPED] + fooStatus[SKIPPED] + bartestStatus[SKIPPED] + annotStatus[SKIPPED] }; validateProjectLevelStatus(overallStatus, resultObj); @@ -194,7 +202,6 @@ private void validateStatus(int[] status, JsonObject obj, String msg) { } private void validateCoverage() { - JsonParser parser = new JsonParser(); //math module int[] mathAddCovered = new int[] {22, 23, 24, 26, 29, 31, 32}, mathAddMissed = new int[] {27}; float mathAddPercentageVal = @@ -232,9 +239,18 @@ private void validateCoverage() { int barCovered = barMainCovered.length, barMissed = barMainMissed.length; + //annot module + int[] annotMainCovered = new int[]{22, 26, 33, 34, 38, 41, 42, 43, 44, 48, 49, 50, 51, 55, 59, 61, 79, 80, 82, + 83, 84, 85, 86, 87, 88, 92, 93, 94, 107, 109, 110}, + annotMainMissed = new int[]{46, 63, 64, 65, 66, 67, 96, 98, 100, 101, 102, 104, 105}; + float annotMainPercentageVal = + (float) (annotMainCovered.length) / (annotMainMissed.length + annotMainCovered.length) * 100; + float annotMainPercentage = (float) (Math.round(annotMainPercentageVal * 100.0) / 100.0); + int annotCovered = annotMainCovered.length, annotMissed = annotMainMissed.length; + // project - int totalCovered = mathCovered + barCovered + fooCovered; - int totalMissed = mathMissed + barMissed + fooMissed; + int totalCovered = mathCovered + barCovered + fooCovered + annotCovered; + int totalMissed = mathMissed + barMissed + fooMissed + annotMissed; float coveragePercentageVal = (float) (totalCovered) / (totalCovered + totalMissed) * 100; float coveragePercentage = (float) (Math.round(coveragePercentageVal * 100.0) / 100.0); @@ -247,16 +263,16 @@ private void validateCoverage() { for (JsonElement element1 : moduleObj.get("sourceFiles").getAsJsonArray()) { JsonObject fileObj = (JsonObject) element1; if ("add.bal".equals(fileObj.get("name").getAsString())) { - Assert.assertEquals(parser.parse(Arrays.toString(mathAddCovered)), - parser.parse(fileObj.get("coveredLines").getAsJsonArray().toString())); - Assert.assertEquals(parser.parse(Arrays.toString(mathAddMissed)), - parser.parse(fileObj.get("missedLines").getAsJsonArray().toString())); + Assert.assertEquals(JsonParser.parseString(Arrays.toString(mathAddCovered)), + JsonParser.parseString(fileObj.get("coveredLines").getAsJsonArray().toString())); + Assert.assertEquals(JsonParser.parseString(Arrays.toString(mathAddMissed)), + JsonParser.parseString(fileObj.get("missedLines").getAsJsonArray().toString())); Assert.assertEquals(mathAddPercentage, fileObj.get("coveragePercentage").getAsFloat()); } else if ("divide.bal".equals(fileObj.get("name").getAsString())) { - Assert.assertEquals(parser.parse(Arrays.toString(mathDivideCovered)), - parser.parse(fileObj.get("coveredLines").getAsJsonArray().toString())); - Assert.assertEquals(parser.parse(Arrays.toString(mathDivideMissed)), - parser.parse(fileObj.get("missedLines").getAsJsonArray().toString())); + Assert.assertEquals(JsonParser.parseString(Arrays.toString(mathDivideCovered)), + JsonParser.parseString(fileObj.get("coveredLines").getAsJsonArray().toString())); + Assert.assertEquals(JsonParser.parseString(Arrays.toString(mathDivideMissed)), + JsonParser.parseString(fileObj.get("missedLines").getAsJsonArray().toString())); Assert.assertEquals(mathDividePercentage, fileObj.get("coveragePercentage").getAsFloat()); } else { Assert.fail("unrecognized file: " + fileObj.get( @@ -273,10 +289,10 @@ private void validateCoverage() { // Verify coverage of source file JsonObject fileObj = (JsonObject) moduleObj.get("sourceFiles").getAsJsonArray().get(0); Assert.assertEquals("main.bal", fileObj.get("name").getAsString()); - Assert.assertEquals(parser.parse(Arrays.toString(fooMainCovered)), - parser.parse(fileObj.get("coveredLines").getAsJsonArray().toString())); - Assert.assertEquals(parser.parse(Arrays.toString(fooMainMissed)), - parser.parse(fileObj.get("missedLines").getAsJsonArray().toString())); + Assert.assertEquals(JsonParser.parseString(Arrays.toString(fooMainCovered)), + JsonParser.parseString(fileObj.get("coveredLines").getAsJsonArray().toString())); + Assert.assertEquals(JsonParser.parseString(Arrays.toString(fooMainMissed)), + JsonParser.parseString(fileObj.get("missedLines").getAsJsonArray().toString())); Assert.assertEquals(fooMainPercentage, fileObj.get("coveragePercentage").getAsFloat()); // Verify coverage of module @@ -286,10 +302,10 @@ private void validateCoverage() { } else if ("foo.bar".equals(moduleObj.get("name").getAsString())) { JsonObject fileObj = (JsonObject) moduleObj.get("sourceFiles").getAsJsonArray().get(0); Assert.assertEquals("main.bal", fileObj.get("name").getAsString()); - Assert.assertEquals(parser.parse(Arrays.toString(barMainCovered)), - parser.parse(fileObj.get("coveredLines").getAsJsonArray().toString())); - Assert.assertEquals(parser.parse(Arrays.toString(barMainMissed)), - parser.parse(fileObj.get("missedLines").getAsJsonArray().toString())); + Assert.assertEquals(JsonParser.parseString(Arrays.toString(barMainCovered)), + JsonParser.parseString(fileObj.get("coveredLines").getAsJsonArray().toString())); + Assert.assertEquals(JsonParser.parseString(Arrays.toString(barMainMissed)), + JsonParser.parseString(fileObj.get("missedLines").getAsJsonArray().toString())); Assert.assertEquals(barMainPercentage, fileObj.get("coveragePercentage").getAsFloat()); // Verify coverage of module @@ -298,6 +314,19 @@ private void validateCoverage() { Assert.assertEquals(barMainPercentage, moduleObj.get("coveragePercentage").getAsFloat()); } else if ("foo.bar.tests".equals(moduleObj.get("name").getAsString())) { // No module coverage for bar_tests + } else if ("foo.annot".equals(moduleObj.get("name").getAsString())) { + JsonObject fileObj = (JsonObject) moduleObj.get("sourceFiles").getAsJsonArray().get(0); + Assert.assertEquals("main.bal", fileObj.get("name").getAsString()); + Assert.assertEquals(JsonParser.parseString(Arrays.toString(annotMainCovered)), + JsonParser.parseString(fileObj.get("coveredLines").getAsJsonArray().toString())); + Assert.assertEquals(JsonParser.parseString(Arrays.toString(annotMainMissed)), + JsonParser.parseString(fileObj.get("missedLines").getAsJsonArray().toString())); + Assert.assertEquals(annotMainPercentage, fileObj.get("coveragePercentage").getAsFloat()); + + // Verify coverage of module + Assert.assertEquals(annotCovered, moduleObj.get("coveredLines").getAsInt()); + Assert.assertEquals(annotMissed, moduleObj.get("missedLines").getAsInt()); + Assert.assertEquals(annotMainPercentage, moduleObj.get("coveragePercentage").getAsFloat()); } else { Assert.fail("unrecognized module: " + moduleObj.get("name").getAsString()); } @@ -310,7 +339,6 @@ private void validateCoverage() { } private void validateModuleWiseCoverage() { - JsonParser parser = new JsonParser(); //math module int[] mathAddCovered = new int[]{22, 23, 24, 26, 29, 31, 32}, mathAddMissed = new int[]{27}; float mathAddPercentageVal = @@ -345,9 +373,18 @@ private void validateModuleWiseCoverage() { int barCovered = barMainCovered.length, barMissed = barMainMissed.length; + //annot module + int[] annotMainCovered = new int[]{22, 26, 33, 34, 38, 41, 42, 43, 44, 48, 49, 50, 51, 55, 59, 61, 79, 80, 82, + 83, 84, 85, 86, 87, 88, 92, 93, 94, 107}, + annotMainMissed = new int[]{46, 63, 64, 65, 66, 67, 96, 98, 100, 101, 102, 104, 105, 109, 110}; + float annotMainPercentageVal = + (float) (annotMainCovered.length) / (annotMainMissed.length + annotMainCovered.length) * 100; + float annotMainPercentage = (float) (Math.round(annotMainPercentageVal * 100.0) / 100.0); + int annotCovered = annotMainCovered.length, annotMissed = annotMainMissed.length; + // project - int totalCovered = mathCovered + barCovered + fooCovered; - int totalMissed = mathMissed + barMissed + fooMissed; + int totalCovered = mathCovered + barCovered + fooCovered + annotCovered; + int totalMissed = mathMissed + barMissed + fooMissed + annotMissed; float coveragePercentageVal = (float) (totalCovered) / (totalCovered + totalMissed) * 100; float coveragePercentage = (float) (Math.round(coveragePercentageVal * 100.0) / 100.0); @@ -360,16 +397,16 @@ private void validateModuleWiseCoverage() { for (JsonElement element1 : moduleObj.get("sourceFiles").getAsJsonArray()) { JsonObject fileObj = (JsonObject) element1; if ("add.bal".equals(fileObj.get("name").getAsString())) { - Assert.assertEquals(parser.parse(Arrays.toString(mathAddCovered)), - parser.parse(fileObj.get("coveredLines").getAsJsonArray().toString())); - Assert.assertEquals(parser.parse(Arrays.toString(mathAddMissed)), - parser.parse(fileObj.get("missedLines").getAsJsonArray().toString())); + Assert.assertEquals(JsonParser.parseString(Arrays.toString(mathAddCovered)), + JsonParser.parseString(fileObj.get("coveredLines").getAsJsonArray().toString())); + Assert.assertEquals(JsonParser.parseString(Arrays.toString(mathAddMissed)), + JsonParser.parseString(fileObj.get("missedLines").getAsJsonArray().toString())); Assert.assertEquals(mathAddPercentage, fileObj.get("coveragePercentage").getAsFloat()); } else if ("divide.bal".equals(fileObj.get("name").getAsString())) { - Assert.assertEquals(parser.parse(Arrays.toString(mathDivideCovered)), - parser.parse(fileObj.get("coveredLines").getAsJsonArray().toString())); - Assert.assertEquals(parser.parse(Arrays.toString(mathDivideMissed)), - parser.parse(fileObj.get("missedLines").getAsJsonArray().toString())); + Assert.assertEquals(JsonParser.parseString(Arrays.toString(mathDivideCovered)), + JsonParser.parseString(fileObj.get("coveredLines").getAsJsonArray().toString())); + Assert.assertEquals(JsonParser.parseString(Arrays.toString(mathDivideMissed)), + JsonParser.parseString(fileObj.get("missedLines").getAsJsonArray().toString())); Assert.assertEquals(mathDividePercentage, fileObj.get("coveragePercentage").getAsFloat()); } else { Assert.fail("unrecognized file: " + fileObj.get( @@ -386,10 +423,10 @@ private void validateModuleWiseCoverage() { // Verify coverage of source file JsonObject fileObj = (JsonObject) moduleObj.get("sourceFiles").getAsJsonArray().get(0); Assert.assertEquals("main.bal", fileObj.get("name").getAsString()); - Assert.assertEquals(parser.parse(Arrays.toString(fooMainCovered)), - parser.parse(fileObj.get("coveredLines").getAsJsonArray().toString())); - Assert.assertEquals(parser.parse(Arrays.toString(fooMainMissed)), - parser.parse(fileObj.get("missedLines").getAsJsonArray().toString())); + Assert.assertEquals(JsonParser.parseString(Arrays.toString(fooMainCovered)), + JsonParser.parseString(fileObj.get("coveredLines").getAsJsonArray().toString())); + Assert.assertEquals(JsonParser.parseString(Arrays.toString(fooMainMissed)), + JsonParser.parseString(fileObj.get("missedLines").getAsJsonArray().toString())); Assert.assertEquals(fooMainPercentage, fileObj.get("coveragePercentage").getAsFloat()); // Verify coverage of module @@ -399,10 +436,10 @@ private void validateModuleWiseCoverage() { } else if ("foo.bar".equals(moduleObj.get("name").getAsString())) { JsonObject fileObj = (JsonObject) moduleObj.get("sourceFiles").getAsJsonArray().get(0); Assert.assertEquals("main.bal", fileObj.get("name").getAsString()); - Assert.assertEquals(parser.parse(Arrays.toString(barMainCovered)), - parser.parse(fileObj.get("coveredLines").getAsJsonArray().toString())); - Assert.assertEquals(parser.parse(Arrays.toString(barMainMissed)), - parser.parse(fileObj.get("missedLines").getAsJsonArray().toString())); + Assert.assertEquals(JsonParser.parseString(Arrays.toString(barMainCovered)), + JsonParser.parseString(fileObj.get("coveredLines").getAsJsonArray().toString())); + Assert.assertEquals(JsonParser.parseString(Arrays.toString(barMainMissed)), + JsonParser.parseString(fileObj.get("missedLines").getAsJsonArray().toString())); Assert.assertEquals(barMainPercentage, fileObj.get("coveragePercentage").getAsFloat()); // Verify coverage of module @@ -411,6 +448,19 @@ private void validateModuleWiseCoverage() { Assert.assertEquals(barMainPercentage, moduleObj.get("coveragePercentage").getAsFloat()); } else if ("foo.bar.tests".equals(moduleObj.get("name").getAsString())) { // No module coverage for bar_tests + } else if ("foo.annot".equals(moduleObj.get("name").getAsString())) { + JsonObject fileObj = (JsonObject) moduleObj.get("sourceFiles").getAsJsonArray().get(0); + Assert.assertEquals("main.bal", fileObj.get("name").getAsString()); + Assert.assertEquals(JsonParser.parseString(Arrays.toString(annotMainCovered)), + JsonParser.parseString(fileObj.get("coveredLines").getAsJsonArray().toString())); + Assert.assertEquals(JsonParser.parseString(Arrays.toString(annotMainMissed)), + JsonParser.parseString(fileObj.get("missedLines").getAsJsonArray().toString())); + Assert.assertEquals(annotMainPercentage, fileObj.get("coveragePercentage").getAsFloat()); + + // Verify coverage of module + Assert.assertEquals(annotCovered, moduleObj.get("coveredLines").getAsInt()); + Assert.assertEquals(annotMissed, moduleObj.get("missedLines").getAsInt()); + Assert.assertEquals(annotMainPercentage, moduleObj.get("coveragePercentage").getAsFloat()); } else { Assert.fail("unrecognized module: " + moduleObj.get("name").getAsString()); } diff --git a/tests/testerina-integration-test/src/test/java/org/ballerinalang/testerina/test/utils/AssertionUtils.java b/tests/testerina-integration-test/src/test/java/org/ballerinalang/testerina/test/utils/AssertionUtils.java index 484856c16ac3..a84ae8d020f0 100644 --- a/tests/testerina-integration-test/src/test/java/org/ballerinalang/testerina/test/utils/AssertionUtils.java +++ b/tests/testerina-integration-test/src/test/java/org/ballerinalang/testerina/test/utils/AssertionUtils.java @@ -30,13 +30,17 @@ * * @since 2.0.0 */ -public class AssertionUtils { +public final class AssertionUtils { + private static final Boolean isWindows = System.getProperty("os.name").toLowerCase(Locale.getDefault()) .contains("win"); private static final Path commandOutputsDir = Paths .get("src", "test", "resources", "command-outputs"); + private AssertionUtils() { + } + public static void assertForTestFailures(String programOutput, String errMessage) { if (programOutput.contains("error: there are test failures")) { Assert.fail("Test failed due to " + errMessage + " in test framework"); diff --git a/tests/testerina-integration-test/src/test/java/org/ballerinalang/testerina/test/utils/CommonUtils.java b/tests/testerina-integration-test/src/test/java/org/ballerinalang/testerina/test/utils/CommonUtils.java index 12888a7e6a91..41e0fac50d06 100644 --- a/tests/testerina-integration-test/src/test/java/org/ballerinalang/testerina/test/utils/CommonUtils.java +++ b/tests/testerina-integration-test/src/test/java/org/ballerinalang/testerina/test/utils/CommonUtils.java @@ -23,7 +23,7 @@ * Common utility functions to handle integration test outputs . * */ -public class CommonUtils { +public final class CommonUtils { private CommonUtils() { } diff --git a/tests/testerina-integration-test/src/test/java/org/ballerinalang/testerina/test/utils/FileUtils.java b/tests/testerina-integration-test/src/test/java/org/ballerinalang/testerina/test/utils/FileUtils.java index 79e507329a5b..f66d07a2e51f 100644 --- a/tests/testerina-integration-test/src/test/java/org/ballerinalang/testerina/test/utils/FileUtils.java +++ b/tests/testerina-integration-test/src/test/java/org/ballerinalang/testerina/test/utils/FileUtils.java @@ -21,13 +21,17 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.stream.Stream; import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; /** * Util class for file operations. */ -public class FileUtils { +public final class FileUtils { + + private FileUtils() { + } /** * Recursively copy a directory from a source to destination. @@ -37,7 +41,9 @@ public class FileUtils { * @throws IOException thrown when as error occurs when copying from src to dest */ public static void copyFolder(Path src, Path dest) throws IOException { - Files.walk(src).forEach(source -> copy(source, dest.resolve(src.relativize(source)))); + try (Stream paths = Files.walk(src)) { + paths.forEach(source -> copy(source, dest.resolve(src.relativize(source)))); + } } private static void copy(Path source, Path dest) { diff --git a/tests/testerina-integration-test/src/test/java/org/ballerinalang/testerina/utils/ObjectMockTestInterop.java b/tests/testerina-integration-test/src/test/java/org/ballerinalang/testerina/utils/ObjectMockTestInterop.java index 2b16c35c92c1..a4b1313f0bb7 100644 --- a/tests/testerina-integration-test/src/test/java/org/ballerinalang/testerina/utils/ObjectMockTestInterop.java +++ b/tests/testerina-integration-test/src/test/java/org/ballerinalang/testerina/utils/ObjectMockTestInterop.java @@ -27,7 +27,10 @@ * * @since 2.0.0 */ -public class ObjectMockTestInterop { +public final class ObjectMockTestInterop { + + private ObjectMockTestInterop() { + } public static Object getValue(ObjectValue objectValue, BString param1, BTypedesc td) { BString newFname = objectValue.getStringValue(new BmpStringValue("fname")) diff --git a/tests/testerina-integration-test/src/test/java/org/ballerinalang/testerina/utils/RuntimeApi.java b/tests/testerina-integration-test/src/test/java/org/ballerinalang/testerina/utils/RuntimeApi.java index b0cd8f947900..48ae9bfe7ad9 100644 --- a/tests/testerina-integration-test/src/test/java/org/ballerinalang/testerina/utils/RuntimeApi.java +++ b/tests/testerina-integration-test/src/test/java/org/ballerinalang/testerina/utils/RuntimeApi.java @@ -38,12 +38,15 @@ * * @since 2201.1.0 */ -public class RuntimeApi { +public final class RuntimeApi { private static final Module objectModule = new Module("testorg", "runtime_api", "1"); private static final Module recordModule = new Module("testorg", "runtime_api", "1"); private static Module errorModule = new Module("testorg", "runtime_api", "1"); + private RuntimeApi() { + } + public static BMap getRecord(BString recordName) { HashMap address = new HashMap<>(); diff --git a/tests/testerina-integration-test/src/test/resources/command-outputs/unix/TestReportTest-testWarningForCoverageFormatFlag.txt b/tests/testerina-integration-test/src/test/resources/command-outputs/unix/TestReportTest-testWarningForCoverageFormatFlag.txt index 99cc6a5014a2..ac562777c968 100644 --- a/tests/testerina-integration-test/src/test/resources/command-outputs/unix/TestReportTest-testWarningForCoverageFormatFlag.txt +++ b/tests/testerina-integration-test/src/test/resources/command-outputs/unix/TestReportTest-testWarningForCoverageFormatFlag.txt @@ -46,5 +46,15 @@ Running Tests 0 failing 0 skipped + Test execution time :*****s + + foo.annot + [pass] testFunc + + + 1 passing + 0 failing + 0 skipped + Test execution time :*****s error: there are test failures \ No newline at end of file diff --git a/tests/testerina-integration-test/src/test/resources/command-outputs/unix/TestReportTest-testWarningForReportTools.txt b/tests/testerina-integration-test/src/test/resources/command-outputs/unix/TestReportTest-testWarningForReportTools.txt index 40b924d70612..4afe55bf693b 100644 --- a/tests/testerina-integration-test/src/test/resources/command-outputs/unix/TestReportTest-testWarningForReportTools.txt +++ b/tests/testerina-integration-test/src/test/resources/command-outputs/unix/TestReportTest-testWarningForReportTools.txt @@ -47,6 +47,16 @@ Running Tests with Coverage Test execution time :*****s + foo.annot + [pass] testFunc + + + 1 passing + 0 failing + 0 skipped + + Test execution time :*****s + Generating Test Report*****project-based-tests/test-report-tests/target/report/test_results.json warning: Could not find the required HTML report tools for code coverage at /lib/tools/coverage/report.zip diff --git a/tests/testerina-integration-test/src/test/resources/command-outputs/windows/TestReportTest-testWarningForCoverageFormatFlag.txt b/tests/testerina-integration-test/src/test/resources/command-outputs/windows/TestReportTest-testWarningForCoverageFormatFlag.txt index fc1daee66f65..bac3317c3501 100644 --- a/tests/testerina-integration-test/src/test/resources/command-outputs/windows/TestReportTest-testWarningForCoverageFormatFlag.txt +++ b/tests/testerina-integration-test/src/test/resources/command-outputs/windows/TestReportTest-testWarningForCoverageFormatFlag.txt @@ -46,5 +46,15 @@ Running Tests 0 failing 0 skipped + Test execution time :*****s + + foo.annot + [pass] testFunc + + + 1 passing + 0 failing + 0 skipped + Test execution time :*****s error: there are test failures diff --git a/tests/testerina-integration-test/src/test/resources/command-outputs/windows/TestReportTest-testWarningForReportTools.txt b/tests/testerina-integration-test/src/test/resources/command-outputs/windows/TestReportTest-testWarningForReportTools.txt index 2a632515749e..1acd0b834868 100644 --- a/tests/testerina-integration-test/src/test/resources/command-outputs/windows/TestReportTest-testWarningForReportTools.txt +++ b/tests/testerina-integration-test/src/test/resources/command-outputs/windows/TestReportTest-testWarningForReportTools.txt @@ -47,6 +47,16 @@ Running Tests with Coverage Test execution time :*****s + foo.annot + [pass] testFunc + + + 1 passing + 0 failing + 0 skipped + + Test execution time :*****s + Generating Test Report*****project-based-tests\test-report-tests\target\report\test_results.json warning: Could not find the required HTML report tools for code coverage at \lib\tools\coverage\report.zip diff --git a/tests/testerina-integration-test/src/test/resources/project-based-tests/test-report-tests/modules/annot/main.bal b/tests/testerina-integration-test/src/test/resources/project-based-tests/test-report-tests/modules/annot/main.bal new file mode 100644 index 000000000000..2fcbef73cd9f --- /dev/null +++ b/tests/testerina-integration-test/src/test/resources/project-based-tests/test-report-tests/modules/annot/main.bal @@ -0,0 +1,110 @@ +// Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). +// +// WSO2 Inc. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +annotation MyAnnot on parameter, function, class, field, service, type, return; +annotation YourAnnot on function, parameter, field, return; + +public type Person record { + string name; + @MyAnnot + int age = add(10, 20); +}; + +@MyAnnot +public type Student record { + Person person; + string school; +}; + +public isolated function add(int a, int b) returns int { + return a + b; +} + +Person p = {name: "John"}; + +@MyAnnot +type INT int; + +@MyAnnot +@divAnnot { + value: "ZeroDiv", + out: zeroDiv(10) +} +service class Review { + int id; + @MyAnnot + @divAnnot { + out: zeroDiv(10), + value: "ZeroDiv" + } + string content; + int groupId; + @YourAnnot + float rating; + + function init( + @MyAnnot + int id, string content, + @YourAnnot int groupId, + float rating) { + self.id = id; + self.content = content; + self.groupId = groupId; + self.rating = rating; + } +} + +type ZeroDiffAnnot record { + string value; + boolean out; +}; + +annotation ZeroDiffAnnot zeroDivAnnot on function,return; +annotation ZeroDiffAnnot divAnnot on function,return, field, class; + +function zeroDiv(int n) returns boolean { + return n / 10 == 0; +} + +@zeroDivAnnot { + value: "ZeroDiv", + out: zeroDiv(10) +} +@divAnnot { + value: "ZeroDiv", + out: zeroDiv(10) +} +function foo(int n) + returns + @zeroDivAnnot { + value: "ZeroDiv", + out: zeroDiv(10) + } + int { + var _ = + @MyAnnot + service object { + resource function get .() returns string { + return "Hello, World!"; + } + }; + return n; +} + +@MyAnnot +function bar() returns int { + return 1; +} diff --git a/tests/testerina-integration-test/src/test/resources/project-based-tests/test-report-tests/modules/annot/tests/test_main.bal b/tests/testerina-integration-test/src/test/resources/project-based-tests/test-report-tests/modules/annot/tests/test_main.bal new file mode 100644 index 000000000000..c816ed14c38b --- /dev/null +++ b/tests/testerina-integration-test/src/test/resources/project-based-tests/test-report-tests/modules/annot/tests/test_main.bal @@ -0,0 +1,22 @@ +// Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). +// +// WSO2 Inc. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +import ballerina/test; + +@test:Config +function testFunc() { + test:assertEquals(bar(), 1); +}