From 37424b25dafec9404aee118a7e1ebcdb8a2652b6 Mon Sep 17 00:00:00 2001 From: Felix Schnabel Date: Mon, 10 Jun 2024 14:02:15 +0200 Subject: [PATCH] Use pattern matching variable instead of cast --- .../shell/invoker/ShellSnippetsInvoker.java | 4 +- .../invoker/classload/ClassLoadInvoker.java | 14 +- .../classload/GlobalVariableSymbol.java | 8 +- .../shell/parser/SerialTreeParser.java | 4 +- .../parser/trials/ModuleMemberTrial.java | 4 +- .../snippet/factory/BasicSnippetFactory.java | 26 +- .../types/ModuleMemberDeclarationSnippet.java | 27 +- .../io/ballerina/shell/utils/StringUtils.java | 4 +- .../runtime/api/creators/ErrorCreator.java | 4 +- .../runtime/api/types/Parameter.java | 3 +- .../runtime/internal/AnnotationUtils.java | 7 +- .../runtime/internal/CloneUtils.java | 6 +- .../runtime/internal/ErrorUtils.java | 4 +- .../runtime/internal/JsonGenerator.java | 4 +- .../runtime/internal/JsonInternalUtils.java | 50 ++-- .../runtime/internal/TableOmDataSource.java | 4 +- .../runtime/internal/TableUtils.java | 7 +- .../runtime/internal/TypeChecker.java | 48 ++-- .../runtime/internal/TypeConverter.java | 257 +++++++++--------- .../runtime/internal/ValueUtils.java | 4 +- .../internal/commons/TypeValuePair.java | 3 +- .../providers/toml/TomlConfigValue.java | 4 +- .../runtime/internal/errors/ErrorHelper.java | 4 +- .../internal/regexp/RegExpFactory.java | 25 +- .../runtime/internal/types/BArrayType.java | 3 +- .../runtime/internal/types/BErrorType.java | 3 +- .../runtime/internal/types/BFiniteType.java | 3 +- .../runtime/internal/types/BFunctionType.java | 8 +- .../runtime/internal/types/BFutureType.java | 3 +- .../internal/types/BIntersectionType.java | 3 +- .../runtime/internal/types/BMapType.java | 4 +- .../internal/types/BParameterizedType.java | 4 +- .../runtime/internal/types/BStreamType.java | 3 +- .../runtime/internal/types/BTableType.java | 3 +- .../runtime/internal/types/BTupleType.java | 3 +- .../runtime/internal/types/BType.java | 3 +- .../runtime/internal/types/BTypeIdSet.java | 3 +- .../internal/types/BTypeReferenceType.java | 4 +- .../runtime/internal/types/BTypedescType.java | 4 +- .../runtime/internal/types/BUnionType.java | 16 +- .../runtime/internal/types/BXmlType.java | 3 +- .../runtime/internal/util/RuntimeUtils.java | 8 +- .../internal/values/ArrayValueImpl.java | 8 +- .../internal/values/ChannelDetails.java | 2 +- .../runtime/internal/values/ErrorValue.java | 6 +- .../runtime/internal/values/MapValueImpl.java | 8 +- .../internal/values/RegExpAtomQuantifier.java | 4 +- .../internal/values/RegExpCharSet.java | 4 +- .../internal/values/RegExpDisjunction.java | 4 +- .../runtime/internal/values/StringValue.java | 4 +- .../internal/values/TupleValueImpl.java | 12 +- .../runtime/internal/values/XmlItem.java | 3 +- .../runtime/internal/values/XmlText.java | 4 +- .../runtime/internal/values/XmlValue.java | 4 +- .../ballerina/cli/launcher/LauncherUtils.java | 4 +- .../api/impl/BallerinaSemanticModel.java | 7 +- .../compiler/api/impl/ExpectedTypeFinder.java | 58 ++-- .../compiler/api/impl/NodeFinder.java | 5 +- .../compiler/api/impl/SymbolFactory.java | 51 ++-- .../compiler/api/impl/SymbolFinder.java | 9 +- .../impl/symbols/BallerinaConstantSymbol.java | 12 +- .../api/impl/symbols/BallerinaModule.java | 3 +- .../symbols/BallerinaObjectTypeSymbol.java | 3 +- .../BallerinaResourceMethodSymbol.java | 4 +- .../BallerinaServiceDeclarationSymbol.java | 3 +- .../api/impl/symbols/BallerinaSymbol.java | 3 +- .../api/impl/symbols/TypesFactory.java | 16 +- .../builders/BallerinaArrayTypeBuilder.java | 4 +- .../BallerinaFunctionTypeBuilder.java | 19 +- .../builders/BallerinaFutureTypeBuilder.java | 4 +- .../builders/BallerinaObjectTypeBuilder.java | 16 +- .../builders/BallerinaRecordTypeBuilder.java | 4 +- .../BallerinaSingletonTypeBuilder.java | 4 +- .../builders/BallerinaStreamTypeBuilder.java | 8 +- .../builders/BallerinaTableTypeBuilder.java | 27 +- .../builders/BallerinaTupleTypeBuilder.java | 6 +- .../BallerinaTypeDescTypeBuilder.java | 4 +- .../builders/BallerinaUnionTypeBuilder.java | 8 +- .../impl/values/BallerinaConstantValue.java | 3 +- .../io/ballerina/projects/ConfigReader.java | 8 +- .../internal/configschema/TypeConverter.java | 56 ++-- .../ballerinalang/toml/model/Dependency.java | 3 +- .../toml/model/LockFileImport.java | 3 +- .../ballerinalang/toml/model/Manifest.java | 7 +- .../toml/parser/ManifestProcessor.java | 8 +- .../bir/codegen/JvmTerminatorGen.java | 10 +- .../compiler/bir/codegen/JvmValueGen.java | 4 +- .../bir/codegen/interop/AnnotationProc.java | 14 +- .../codegen/interop/ExternalMethodGen.java | 8 +- .../compiler/bir/model/BIRNode.java | 4 +- .../compiler/bir/model/BIRNonTerminator.java | 6 +- .../compiler/bir/model/BIROperand.java | 4 +- .../compiler/bir/writer/BIRTypeWriter.java | 8 +- .../compiler/desugar/AnnotationDesugar.java | 16 +- .../desugar/DeclarativeAuthDesugar.java | 3 +- .../compiler/desugar/QueryDesugar.java | 4 +- .../compiler/diagnostic/BLangDiagnostic.java | 3 +- .../diagnostic/BLangDiagnosticLocation.java | 3 +- .../diagnostic/BLangDiagnosticLog.java | 19 +- .../properties/BCollectionProperty.java | 3 +- .../properties/BNumericProperty.java | 3 +- .../properties/BStringProperty.java | 3 +- .../diagnostic/properties/NonCatProperty.java | 3 +- .../compiler/parser/BLangNodeBuilder.java | 33 +-- .../compiler/parser/NodeCloner.java | 4 +- .../semantics/analyzer/CodeAnalyzer.java | 6 +- .../analyzer/ConstantTypeChecker.java | 4 +- .../semantics/analyzer/IsolationAnalyzer.java | 13 +- .../semantics/analyzer/SymbolEnter.java | 7 +- .../semantics/analyzer/TypeChecker.java | 32 +-- .../semantics/analyzer/TypeParamAnalyzer.java | 3 +- .../compiler/semantics/analyzer/Types.java | 6 +- .../model/symbols/BInvokableSymbol.java | 4 +- .../semantics/model/types/BInvokableType.java | 7 +- .../semantics/model/types/BTupleType.java | 12 +- .../semantics/model/types/BTypeIdSet.java | 6 +- .../semantics/model/types/BUnionType.java | 24 +- .../compiler/tree/BLangConstantValue.java | 3 +- .../tree/expressions/BLangXMLQName.java | 3 +- .../util/diagnotic/DiagnosticPos.java | 3 +- .../compiler/syntax/tree/NonTerminalNode.java | 3 +- .../tools/diagnostics/DiagnosticInfo.java | 3 +- .../ballerinalang/birspec/BIRTestUtils.java | 6 +- .../langlib/regexp/RegexUtil.java | 4 +- .../langlib/value/IsReadOnly.java | 2 +- .../org/ballerinalang/langlib/xml/Concat.java | 8 +- .../ballerinalang/langlib/xml/Elements.java | 4 +- .../langserver/BallerinaWorkspaceService.java | 3 +- .../ExtendedClientCapabilityBuilder.java | 3 +- .../langserver/LangExtensionDelegator.java | 3 +- .../codeaction/CodeActionNodeAnalyzer.java | 4 +- .../codeaction/CodeActionProvidersHolder.java | 6 +- .../IgnoreUnusedVariableCodeAction.java | 4 +- .../ChangeVariableTypeCodeAction.java | 4 +- .../command/docs/DocumentationGenerator.java | 4 +- .../langserver/common/RecordField.java | 3 +- .../langserver/common/utils/ModuleUtil.java | 5 +- .../providers/AbstractCompletionProvider.java | 2 +- .../util/FieldAccessCompletionResolver.java | 3 +- .../langserver/config/CodeLensConfig.java | 3 +- .../connector/BallerinaConnectorService.java | 4 +- .../DocumentComponentTransformer.java | 4 +- .../symbol/BallerinaSymbolService.java | 10 +- .../langserver/hover/HoverObjectResolver.java | 7 +- .../langserver/hover/HoverUtil.java | 7 +- .../langserver/rename/RenameUtil.java | 4 +- .../semantictokens/SemanticTokensVisitor.java | 14 +- .../debugadapter/BreakpointProcessor.java | 3 +- .../debugadapter/JBallerinaDebugServer.java | 32 +-- .../debugadapter/JDIEventProcessor.java | 17 +- .../FieldAccessCompletionResolver.java | 3 +- .../completion/util/QNameReferenceUtil.java | 4 +- .../config/ClientConfigHolder.java | 11 +- .../config/ClientLaunchConfigHolder.java | 24 +- .../engine/EvaluationTypeResolver.java | 4 +- .../engine/ModuleLevelDefinitionFinder.java | 12 +- .../engine/NodeBasedTypeResolver.java | 7 +- .../MemberAccessExpressionEvaluator.java | 32 +-- .../MethodCallExpressionEvaluator.java | 8 +- .../expression/StringTemplateEvaluator.java | 4 +- .../XMLTemplateExpressionEvaluator.java | 3 +- .../invokable/RuntimeInstanceMethod.java | 4 +- .../engine/invokable/RuntimeStaticMethod.java | 4 +- .../evaluation/utils/EvaluationUtils.java | 20 +- .../jdi/LocalVariableProxyImpl.java | 3 +- .../jdi/ObjectReferenceProxyImpl.java | 4 +- .../debugadapter/jdi/StackFrameProxyImpl.java | 3 +- .../jdi/VirtualMachineProxyImpl.java | 12 +- .../debugadapter/variable/VariableUtils.java | 8 +- .../debugadapter/variable/types/BArray.java | 6 +- .../debugadapter/variable/types/BByte.java | 4 +- .../debugadapter/variable/types/BObject.java | 6 +- .../debugadapter/variable/types/BTuple.java | 9 +- .../debugadapter/variable/types/BUnknown.java | 3 +- .../variable/types/BXmlSequence.java | 12 +- .../debugadapter/runtime/DebuggerRuntime.java | 8 +- .../debugadapter/runtime/VariableUtils.java | 6 +- .../diagramutil/SyntaxTreeMapGenerator.java | 40 ++- .../generator/ConnectorGenerator.java | 5 +- .../connector/generator/GeneratorUtils.java | 23 +- .../connector/models/connector/Type.java | 55 ++-- .../org/ballerinalang/docgen/Generator.java | 66 ++--- .../docgen/generator/model/Type.java | 113 +++----- .../core/options/FormattingOptions.java | 30 +- .../jsonmapper/util/ConverterUtils.java | 14 +- .../converters/JsonToRecordConverter.java | 6 +- .../converters/util/SchemaGenerator.java | 7 +- .../PerformanceAnalyzerNodeVisitor.java | 3 +- .../java/io/ballerina/utils/ParserUtil.java | 29 +- .../semver/checker/util/DiffUtils.java | 50 ++-- .../formatter/VariableFormatter.java | 7 +- .../segment/factories/NodeSegmentFactory.java | 8 +- .../compiler/TesterinaCodeAnalyzer.java | 10 +- .../testerina/core/TestProcessor.java | 12 +- .../testerina/natives/CommonUtils.java | 4 +- .../testerina/natives/mock/ObjectMock.java | 29 +- .../test/runtime/util/TesterinaUtils.java | 4 +- .../toml/syntax/tree/NonTerminalNode.java | 3 +- .../util/ConverterUtils.java | 18 +- .../projects/test/PackageResolutionTests.java | 6 +- .../semantic/api/test/SymbolBIRTest.java | 3 +- .../semantic/api/test/TypedescriptorTest.java | 4 +- .../java/org/ballerinalang/test/BRunUtil.java | 17 +- .../test/agent/server/WebServer.java | 3 +- .../test/util/client/ResponseHandler.java | 4 +- .../ProcessStreamConnectionProvider.java | 3 +- .../SocketStreamConnectionProvider.java | 3 +- .../stamp/ArrayStampInbuiltFunctionTest.java | 40 +-- 208 files changed, 1056 insertions(+), 1293 deletions(-) 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..79ee781ead36 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 @@ -435,9 +435,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) { 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..54f5ff96fc49 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."); 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/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..142de7e2cbb3 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 @@ -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/snippet/factory/BasicSnippetFactory.java b/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/snippet/factory/BasicSnippetFactory.java index 371d7b7b51e8..8cd89ff843d6 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); } 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/StringUtils.java b/ballerina-shell/modules/shell-core/src/main/java/io/ballerina/shell/utils/StringUtils.java index f6799730d4d4..63c1ae24b5a4 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 @@ -159,8 +159,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/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..8115a47604ac 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 @@ -138,8 +138,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/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/internal/AnnotationUtils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/AnnotationUtils.java index 2615a721150d..00a2208122dc 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 @@ -47,12 +47,10 @@ public class AnnotationUtils { * @param bType The type for which annotations need to be set */ public static void processAnnotations(MapValue globalAnnotMap, Type bType) { - if (!(bType instanceof BAnnotatableType)) { + 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)); @@ -94,8 +92,7 @@ public static void processObjectCtorAnnotations(BObjectType bType, MapValue glob for (MethodType attachedFunction : bType.getMethods()) { processObjectMethodLambdaAnnotation(globalAnnotMap, strand, attachedFunction); } - if (bType instanceof BServiceType) { - var serviceType = (BServiceType) bType; + if (bType instanceof BServiceType serviceType) { for (var resourceFunction : serviceType.getResourceMethods()) { processObjectMethodLambdaAnnotation(globalAnnotMap, strand, resourceFunction); } 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..8819601cd30c 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 @@ -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..dba2cd0f203a 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 @@ -84,8 +84,8 @@ public static ErrorValue createInteropError(Throwable e) { } 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/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..f7e4129a63c7 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 @@ -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; } @@ -507,13 +507,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); @@ -567,12 +566,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 +581,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 +601,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 +624,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 +831,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/TableOmDataSource.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/TableOmDataSource.java index 0dce761f0d0b..9c61b0c6bb73 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 @@ -167,8 +167,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..8ef5402f4459 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 @@ -57,7 +57,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,7 +66,6 @@ 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; @@ -100,8 +99,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..16dd93abc3ac 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 @@ -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(); @@ -469,8 +469,8 @@ public static boolean isReferenceEqual(Object lhsValue, Object rhsValue) { 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<>()); + if (lhsValue instanceof RegExpValue lhsRegExpValue && rhsValue instanceof RegExpValue) { + return lhsRegExpValue.equals(rhsValue, new HashSet<>()); } return false; } @@ -525,8 +525,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 +540,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); } /** @@ -2540,10 +2540,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 +2552,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 +2605,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 +2619,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 +2686,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 +2709,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 +2721,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 +2766,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; @@ -3008,8 +3006,8 @@ private static boolean checkValueEquals(Object lhsValue, Object rhsValue, Set unresolvedValues, List errors, boolean allowNumericConversion) { - if (!(sourceValue instanceof MapValueImpl)) { + if (!(sourceValue instanceof MapValueImpl sourceMapValueImpl)) { return false; } @@ -468,7 +468,6 @@ private static boolean isConvertibleToRecordType(Object sourceValue, BRecordType targetFieldTypes.put(field.getKey(), field.getValue().getFieldType()); } - MapValueImpl sourceMapValueImpl = (MapValueImpl) sourceValue; for (Map.Entry targetTypeEntry : targetFieldTypes.entrySet()) { String fieldName = targetTypeEntry.getKey().toString(); String fieldNameLong = getLongFieldName(varName, fieldName); @@ -640,10 +639,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 +687,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 +747,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 +769,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 +798,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 +820,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(); } @@ -1040,19 +1037,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 +1059,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 +1076,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 +1096,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 +1136,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/ValueUtils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/ValueUtils.java index f2438efb18c1..48f007de31c2 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 @@ -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/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/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/errors/ErrorHelper.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/errors/ErrorHelper.java index ae1fa77d9947..ddf6863b926d 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 @@ -97,10 +97,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/regexp/RegExpFactory.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/regexp/RegExpFactory.java index 7198f608b69c..52335599517c 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 @@ -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/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/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/RuntimeUtils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/util/RuntimeUtils.java index 11d4dc9d767f..90339567e95a 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 @@ -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/values/ArrayValueImpl.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/ArrayValueImpl.java index e57cf695a662..57caec7201e2 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 @@ -896,8 +896,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; } @@ -1066,8 +1066,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(); } } } 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..022fe54fa4b4 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 @@ -46,6 +46,6 @@ public int hashCode() { @Override public boolean equals(Object o) { - return (o instanceof ChannelDetails) && (((ChannelDetails) o).name.equals(this.name)); + return (o instanceof ChannelDetails channelDetails) && (channelDetails.name.equals(this.name)); } } 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..d9e08a3cb031 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 @@ -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/MapValueImpl.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/MapValueImpl.java index 699747cf318d..0a9bf6613af9 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; } @@ -590,8 +590,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; 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/StringValue.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/StringValue.java index a00c1c0e0575..82378396f109 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 @@ -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/TupleValueImpl.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/TupleValueImpl.java index 2bdc52b627bb..02c8e5a57d50 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; } @@ -518,8 +518,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; } @@ -605,8 +605,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; 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..33089731f705 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 @@ -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()) { 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..492b6ec38f73 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 @@ -130,8 +130,8 @@ public boolean equals(Object o, Set visitedValues) { if (o instanceof XmlText rhsXMLText) { return this.getTextValue().equals(rhsXMLText.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 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/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 11441741882b..5a5b900ef6ac 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 @@ -82,8 +82,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 { message = cause.toString(); } 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..a0a16524bcf9 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 @@ -227,9 +227,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 +304,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 +364,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 +390,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 +513,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 +559,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 +574,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 +694,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 +744,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 +790,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 +869,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 +948,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; 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/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..dd857e2bbb63 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 @@ -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/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..64e5f1d98ff1 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: 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..98c7dfdde8c7 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 @@ -113,8 +113,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/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/projects/ConfigReader.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/ConfigReader.java index 79d94c92c050..96841a2dfbbf 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 @@ -196,8 +196,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 +240,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); } } } 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..7b9608ea07b1 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()); } } } 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..fabef5d0a000 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 @@ -64,10 +64,9 @@ public List getDependencies() { 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/wso2/ballerinalang/compiler/bir/codegen/JvmTerminatorGen.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/bir/codegen/JvmTerminatorGen.java index 1b033239aea5..5a7c5a461630 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 19d6954f8851..fd069305332d 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..29671469e10d 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 @@ -135,13 +135,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..2e5921b1f95b 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 @@ -54,8 +54,8 @@ public static void genJMethodForBExternalFunc(BIRFunction birFunc, ClassWriter c 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/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/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/desugar/AnnotationDesugar.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/AnnotationDesugar.java index e1573d5e91a1..314ac9b8e999 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 @@ -310,8 +310,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 +356,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; @@ -731,8 +731,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 +786,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; 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/QueryDesugar.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/QueryDesugar.java index ae4463de4fde..c292edb3a4c1 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 @@ -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/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 848ef33dffcf..f8ee31916053 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 @@ -62,8 +62,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..e9c936836485 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 @@ -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/parser/BLangNodeBuilder.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/parser/BLangNodeBuilder.java index 58d576a52fb0..7db70532e28b 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 @@ -1314,7 +1314,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); } @@ -2698,8 +2698,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 +3911,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; @@ -4929,9 +4927,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 +5215,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); @@ -6124,10 +6118,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 +6304,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()) { @@ -6908,8 +6901,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 585e9fbfef3e..93e250e7ee5a 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 @@ -3838,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) { @@ -3879,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)) { 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..e2060205f45f 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 @@ -1500,8 +1500,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; } 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..9b63f21d67f0 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 @@ -3158,12 +3158,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 +3372,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 +3401,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); } @@ -3493,11 +3489,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/SymbolEnter.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/SymbolEnter.java index 33e50ebf1252..75d22594de7b 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 @@ -621,8 +621,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; }; @@ -5219,8 +5219,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); 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 3f17308d704e..4e8d4af5cd3e 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 @@ -639,8 +639,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 +1033,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 +1041,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; @@ -3537,9 +3537,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; } @@ -3672,9 +3672,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; } 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..38b59b69378f 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 @@ -1112,8 +1112,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/Types.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/Types.java index b6f80c1f19cf..66b6c735777f 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 @@ -3693,8 +3693,7 @@ private boolean isAssignableToUnionType(BType source, BType target, Set 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/types/BInvokableType.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/types/BInvokableType.java index 79bde4b69a0b..796d98926d69 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,11 +129,11 @@ 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; 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/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/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/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/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-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..7472d0f412a3 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 @@ -92,8 +92,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-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/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..37099fc938e5 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 @@ -649,13 +649,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()); 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..27964b05f28c 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 @@ -60,8 +60,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]; } 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..2c1cef1201de 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 @@ -28,6 +28,6 @@ public class 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.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..18f1109b4bf3 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 @@ -39,7 +39,7 @@ public static BXml concat(Object... arrayValue) { BXml lastItem = null; for (int i = 0; i < arrayValue.length; i++) { Object refValue = arrayValue[i]; - if (refValue instanceof BString) { + 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 +48,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/Elements.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/Elements.java index 6f29af4efe82..74d7ee0bf50e 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 @@ -44,8 +44,8 @@ public class 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) { 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..5bdf0ab3234d 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 @@ -71,10 +71,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 { 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..c00483275431 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 @@ -56,10 +56,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/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..baf75b31adb7 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 @@ -729,9 +729,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..076961c93eee 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 @@ -74,14 +74,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); } } 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/changetype/ChangeVariableTypeCodeAction.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/changetype/ChangeVariableTypeCodeAction.java index 0e399abe993c..5322a58683a0 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 @@ -190,9 +190,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(); } 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 ced084a1491a..f90d1f4b593c 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 @@ -324,11 +324,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/common/RecordField.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/RecordField.java index da6fa9ef2919..1bb7e09d02fd 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/RecordField.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/RecordField.java @@ -75,10 +75,9 @@ public boolean equals(Object obj) { if (this == obj) { return true; } - if (!(obj instanceof RecordFieldIdentifier)) { + if (!(obj instanceof RecordFieldIdentifier other)) { return false; } - RecordFieldIdentifier other = (RecordFieldIdentifier) obj; return other.name.equals(this.name) && other.typeSymbol.signature().equals(this.typeSymbol.signature()); } 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..496c5cf7b3d9 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 @@ -137,8 +137,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/completions/providers/AbstractCompletionProvider.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/AbstractCompletionProvider.java index 8a98748024a5..96ee9206dce4 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); 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..5e27881d4510 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 @@ -316,8 +316,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/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/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/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/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/hover/HoverObjectResolver.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/hover/HoverObjectResolver.java index a97d4d80d51b..aa1adc7e525f 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 @@ -94,8 +94,8 @@ public Hover getHoverObjectForSymbol(Symbol symbol) { case PARAMETER: return getHoverObjectForSymbol((ParameterSymbol) symbol); case TYPE: - if (symbol instanceof TypeReferenceTypeSymbol) { - return getHoverObjectForSymbol(((TypeReferenceTypeSymbol) symbol).definition()); + if (symbol instanceof TypeReferenceTypeSymbol refTypeSymbol) { + return getHoverObjectForSymbol(refTypeSymbol.definition()); } return HoverUtil.getHoverObject(); default: @@ -381,8 +381,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..0eb44efb4a3f 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 @@ -178,8 +178,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 +200,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/rename/RenameUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/rename/RenameUtil.java index 463b87b8e231..4769a6b1d89a 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 @@ -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/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/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/resolver/FieldAccessCompletionResolver.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/completion/resolver/FieldAccessCompletionResolver.java index ac5d700ac01f..18a466c9735b 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); 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..c1c2396074e8 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 @@ -88,10 +88,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(); 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/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/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/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..2cea9b28605d 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 @@ -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; @@ -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/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..95dffeb21e92 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 @@ -122,13 +122,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/VirtualMachineProxyImpl.java b/misc/debug-adapter/modules/debug-adapter-core/src/main/java/org/ballerinalang/debugadapter/jdi/VirtualMachineProxyImpl.java index f5f3de33cfbe..4f12095a2ecb 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); } 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..a5f784a54202 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 @@ -470,10 +470,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..2f9bb7ef7660 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 @@ -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"; } 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..22991fd91e14 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 @@ -39,16 +39,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/SyntaxTreeMapGenerator.java b/misc/diagram-util/src/main/java/org/ballerinalang/diagramutil/SyntaxTreeMapGenerator.java index 072e1627a826..b4fe5ff2ff48 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 @@ -271,8 +271,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 +296,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 +584,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 +601,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 io.ballerina.compiler.api.symbols.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 +634,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..35844e246c50 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 @@ -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..9b79a4564ebf 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 @@ -80,11 +80,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 +139,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 +172,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/docerina/src/main/java/org/ballerinalang/docgen/Generator.java b/misc/docerina/src/main/java/org/ballerinalang/docgen/Generator.java index 688420e79956..3164f817ab36 100644 --- a/misc/docerina/src/main/java/org/ballerinalang/docgen/Generator.java +++ b/misc/docerina/src/main/java/org/ballerinalang/docgen/Generator.java @@ -135,10 +135,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); } @@ -603,8 +603,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)) { @@ -653,8 +652,8 @@ 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)); } } @@ -768,8 +767,7 @@ public static List getDefaultableVariableList(NodeList node 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()) { @@ -784,8 +782,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()) { @@ -809,8 +806,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(); @@ -830,15 +826,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); @@ -847,8 +841,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); @@ -856,8 +849,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); @@ -942,16 +934,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; } @@ -972,18 +963,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 { @@ -1008,9 +997,8 @@ private static List getDescSectionsDocFromMetaDataList(Optional symbol = Optional.empty(); @@ -154,8 +153,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); @@ -163,8 +162,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(); @@ -177,8 +175,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); @@ -204,20 +202,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.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) { @@ -226,18 +221,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); @@ -253,8 +245,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(); @@ -265,10 +256,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()) { @@ -284,19 +274,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(); @@ -310,30 +297,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 { @@ -348,8 +329,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, @@ -358,13 +338,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); } } @@ -373,8 +353,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() ? @@ -398,8 +377,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) -> { @@ -468,42 +446,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; @@ -513,8 +486,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; @@ -538,8 +510,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) { @@ -547,13 +518,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/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..8fa23bb9ee8e 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 @@ -187,25 +187,33 @@ 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 configs)) { continue; } - Map configs = (Map) value; String key = entry.getKey(); FormatSection section = FormatSection.fromString(key); switch (section) { - case INDENT -> indentFormattingOptions = IndentFormattingOptions.builder().build(configs); - case WRAPPING -> wrappingFormattingOptions = WrappingFormattingOptions.builder().build(configs); - case BRACES -> braceFormattingOptions = BraceFormattingOptions.builder().build(configs); + case INDENT -> indentFormattingOptions = IndentFormattingOptions.builder().build( + (Map) configs); + case WRAPPING -> wrappingFormattingOptions = WrappingFormattingOptions.builder().build( + (Map) configs); + case BRACES -> braceFormattingOptions = BraceFormattingOptions.builder().build( + (Map) configs); case FUNCTION_DEFINITION -> - functionDefFormattingOptions = FunctionDefFormattingOptions.builder().build(configs); + functionDefFormattingOptions = FunctionDefFormattingOptions.builder().build( + (Map) configs); case FUNCTION_CALL -> - functionCallFormattingOptions = FunctionCallFormattingOptions.builder().build(configs); + functionCallFormattingOptions = FunctionCallFormattingOptions.builder().build( + (Map) configs); case IF_STATEMENT -> - ifStatementFormattingOptions = IfStatementFormattingOptions.builder().build(configs); - case QUERY -> queryFormattingOptions = QueryFormattingOptions.builder().build(configs); - case SPACING -> spacingFormattingOptions = SpacingFormattingOptions.builder().build(configs); - case IMPORT -> importFormattingOptions = ImportFormattingOptions.builder().build(configs); + ifStatementFormattingOptions = IfStatementFormattingOptions.builder().build( + (Map) configs); + case QUERY -> queryFormattingOptions = QueryFormattingOptions.builder().build( + (Map) configs); + case SPACING -> spacingFormattingOptions = SpacingFormattingOptions.builder().build( + (Map) configs); + case IMPORT -> importFormattingOptions = ImportFormattingOptions.builder().build( + (Map) configs); } } return build(); 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..681c09398ae5 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 @@ -200,10 +200,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)); @@ -282,15 +282,15 @@ public static 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/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..4d854352d534 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 @@ -227,8 +227,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 = @@ -325,8 +324,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/SchemaGenerator.java b/misc/ls-extensions/modules/json-to-record-converter/src/main/java/io/ballerina/converters/util/SchemaGenerator.java index 801eea99e68c..7b850cf90514 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 @@ -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/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..d15b3464b449 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 @@ -81,11 +81,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 +104,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 +123,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 +140,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 +162,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 +175,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 +183,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/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..e1d31b31b7e5 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 @@ -139,10 +139,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)) @@ -261,24 +261,24 @@ private static String getDiffVerb(Diff diff) { } 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 diff1) { + return getPackageName(diff1); + } else if (diff instanceof ModuleDiff diff1) { + return getModuleName(diff1); + } else if (diff instanceof FunctionDiff diff1) { + return getFunctionName(diff1); + } else if (diff instanceof ServiceDiff diff1) { + return getServiceName(diff1); + } else if (diff instanceof ModuleVarDiff diff1) { + return getModuleVariableName(diff1); + } else if (diff instanceof ModuleConstantDiff diff1) { + return getModuleConstantName(diff1); + } else if (diff instanceof ClassDiff diff1) { + return getModuleClassName(diff1); + } else if (diff instanceof TypeDefinitionDiff diff1) { + return getModuleTypeDefName(diff1); + } else if (diff instanceof EnumDiff diff1) { + return getModuleEnumName(diff1); } else { return UNKNOWN; } @@ -302,8 +302,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 +336,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/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..eec46652a630 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 @@ -51,9 +51,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); } @@ -130,8 +130,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/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/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-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..95dec40fe1bc 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 @@ -62,11 +62,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/mock/ObjectMock.java b/misc/testerina/modules/testerina-core/src/main/java/org/ballerinalang/testerina/natives/mock/ObjectMock.java index b4825504ba52..045bdbb4d066 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 @@ -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) { @@ -325,10 +325,10 @@ public static BError validateArguments(BObject caseObj) { int i = 0; 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; @@ -402,10 +402,10 @@ public static BError validatePathArgs(BObject caseObj) { 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; @@ -483,10 +483,10 @@ public static BError validateResourceArguments(BObject caseObj) { "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; @@ -899,8 +899,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 +910,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/util/TesterinaUtils.java b/misc/testerina/modules/testerina-runtime/src/main/java/org/ballerinalang/test/runtime/util/TesterinaUtils.java index 3cfc160eedd8..ed133f112fdb 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 @@ -127,9 +127,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); } } 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..1ced0ca46f42 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 @@ -91,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 DocumentNode) { - DocumentNode modulePartNode = (DocumentNode) this; + this instanceof DocumentNode modulePartNode) { return modulePartNode.eofToken(); } 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..56e6be02caf2 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 @@ -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)); @@ -170,22 +170,22 @@ public static 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/project-api/project-api-test/src/test/java/io/ballerina/projects/test/PackageResolutionTests.java b/project-api/project-api-test/src/test/java/io/ballerina/projects/test/PackageResolutionTests.java index d28ea923615d..d3e4d329bd97 100644 --- a/project-api/project-api-test/src/test/java/io/ballerina/projects/test/PackageResolutionTests.java +++ b/project-api/project-api-test/src/test/java/io/ballerina/projects/test/PackageResolutionTests.java @@ -566,8 +566,7 @@ public void testProjectWithManyDependencies() { OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean(); long initialOpenCount = 0; - if (os instanceof UnixOperatingSystemMXBean) { - UnixOperatingSystemMXBean unixOperatingSystemMXBean = (UnixOperatingSystemMXBean) os; + if (os instanceof UnixOperatingSystemMXBean unixOperatingSystemMXBean) { initialOpenCount = unixOperatingSystemMXBean.getOpenFileDescriptorCount(); } Project project = BCompileUtil.loadProject( @@ -580,8 +579,7 @@ public void testProjectWithManyDependencies() { diagnosticResult.errors().forEach(OUT::println); Assert.assertEquals(diagnosticResult.diagnosticCount(), 0, "Unexpected compilation diagnostics"); - if (os instanceof UnixOperatingSystemMXBean) { - UnixOperatingSystemMXBean unixOperatingSystemMXBean = (UnixOperatingSystemMXBean) os; + if (os instanceof UnixOperatingSystemMXBean unixOperatingSystemMXBean) { Assert.assertEquals(initialOpenCount, unixOperatingSystemMXBean.getOpenFileDescriptorCount()); } 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..4f70e4d0b272 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 @@ -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/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-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..90c587488099 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 @@ -190,9 +190,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 io.ballerina.runtime.api.values.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: " + @@ -391,9 +391,8 @@ private static void directRun(Class initClazz, String functionName, Class[] p 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 +429,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 +444,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/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/util/client/ResponseHandler.java b/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/util/client/ResponseHandler.java index 07efe812c91c..30bf1ba6fa44 100644 --- a/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/util/client/ResponseHandler.java +++ b/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/util/client/ResponseHandler.java @@ -37,8 +37,8 @@ public class ResponseHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { - if (msg instanceof FullHttpResponse) { - this.fullHttpResponses.add((FullHttpResponse) msg); + if (msg instanceof FullHttpResponse httpResponse) { + this.fullHttpResponses.add(httpResponse); if (latch != null) { latch.countDown(); } 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-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..6fd626db11ba 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 @@ -250,11 +250,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 +264,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 +278,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 +292,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