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 b2970e598c45..f056abddc30d 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 @@ -263,8 +263,7 @@ public static boolean isJSONObject(Object json) { MapValueImpl map = new MapValueImpl<>(mapType); Type mapConstraint = TypeUtils.getImpliedType(mapType.getConstrainedType()); - if (mapConstraint == null || mapConstraint.getTag() == TypeTags.ANY_TAG || - mapConstraint.getTag() == TypeTags.JSON_TAG) { + if (mapConstraint.getTag() == TypeTags.ANY_TAG || mapConstraint.getTag() == TypeTags.JSON_TAG) { ((MapValueImpl) json).forEach(map::put); return map; diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/MathUtils.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/MathUtils.java index 8908919cd75d..1c0d1b21b77d 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/MathUtils.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/MathUtils.java @@ -56,12 +56,7 @@ public static long remainder(long numerator, long denominator) { try { return numerator % denominator; } catch (ArithmeticException e) { - if (denominator == 0) { - throw ErrorCreator.createError(ErrorReasons.DIVISION_BY_ZERO_ERROR, DIVIDE_BY_ZERO_ERROR); - } else { - throw ErrorCreator.createError(ErrorReasons.ARITHMETIC_OPERATION_ERROR, - StringUtils.fromString(e.getMessage())); - } + throw ErrorCreator.createError(ErrorReasons.DIVISION_BY_ZERO_ERROR, DIVIDE_BY_ZERO_ERROR); } } 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 86d401f8a7bc..0178af2e19b5 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 @@ -19,21 +19,24 @@ import io.ballerina.runtime.api.TypeTags; import io.ballerina.runtime.api.creators.ErrorCreator; +import io.ballerina.runtime.api.types.Field; import io.ballerina.runtime.api.types.Type; import io.ballerina.runtime.api.utils.StringUtils; import io.ballerina.runtime.api.utils.TypeUtils; import io.ballerina.runtime.api.values.BArray; import io.ballerina.runtime.api.values.BMap; import io.ballerina.runtime.api.values.BString; -import io.ballerina.runtime.internal.types.BField; import io.ballerina.runtime.internal.types.BStructureType; import io.ballerina.runtime.internal.values.DecimalValue; import io.ballerina.runtime.internal.values.IteratorValue; +import io.ballerina.runtime.internal.values.MapValue; import io.ballerina.runtime.internal.values.MapValueImpl; -import io.ballerina.runtime.internal.values.TableValueImpl; +import io.ballerina.runtime.internal.values.TableValue; import io.ballerina.runtime.internal.values.TupleValueImpl; import org.apache.axiom.om.ds.AbstractPushOMDataSource; +import java.util.Collection; + import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; @@ -51,11 +54,11 @@ public class TableOmDataSource extends AbstractPushOMDataSource { private static final String DEFAULT_ROOT_WRAPPER = "results"; private static final String DEFAULT_ROW_WRAPPER = "result"; - private final TableValueImpl table; + private final TableValue table; private final String rootWrapper; private final String rowWrapper; - public TableOmDataSource(TableValueImpl table, String rootWrapper, String rowWrapper) { + public TableOmDataSource(TableValue table, String rootWrapper, String rowWrapper) { this.table = table; this.rootWrapper = rootWrapper != null ? rootWrapper : DEFAULT_ROOT_WRAPPER; this.rowWrapper = rowWrapper != null ? rowWrapper : DEFAULT_ROW_WRAPPER; @@ -67,22 +70,15 @@ public void serialize(XMLStreamWriter xmlStreamWriter) throws XMLStreamException IteratorValue itr = this.table.getIterator(); while (itr.hasNext()) { - table.getIterator().next(); xmlStreamWriter.writeStartElement("", this.rowWrapper, ""); TupleValueImpl tupleValue = (TupleValueImpl) itr.next(); - MapValueImpl record = ((MapValueImpl) tupleValue.get(0)); + MapValue record = ((MapValue) tupleValue.get(0)); BStructureType structType = (BStructureType) record.getType(); - BField[] structFields = null; if (structType != null) { - structFields = structType.getFields().values().toArray(new BField[0]); - } - for (int i = 0; i < structFields.length; i++) { - BField internalStructField = structFields[i]; - int type = TypeUtils.getImpliedType(internalStructField.getFieldType()).getTag(); - String fieldName = internalStructField.getFieldName(); - - writeElement(record, xmlStreamWriter, fieldName, type, i, structFields); + for (Field internalStructField : structType.getFields().values()) { + writeElement(record, xmlStreamWriter, internalStructField); + } } xmlStreamWriter.writeEndElement(); } @@ -90,9 +86,10 @@ public void serialize(XMLStreamWriter xmlStreamWriter) throws XMLStreamException xmlStreamWriter.flush(); } - private void writeElement(MapValueImpl record, - XMLStreamWriter xmlStreamWriter, String name, int type, int index, - BField[] structFields) throws XMLStreamException { + private void writeElement(MapValue record, XMLStreamWriter xmlStreamWriter, + Field structField) throws XMLStreamException { + int type = TypeUtils.getImpliedType(structField.getFieldType()).getTag(); + String name = structField.getFieldName(); boolean isArray = false; xmlStreamWriter.writeStartElement("", name, ""); BString key = StringUtils.fromString(name); @@ -122,13 +119,8 @@ private void writeElement(MapValueImpl record, case TypeTags.OBJECT_TYPE_TAG: case TypeTags.RECORD_TYPE_TAG: isArray = true; - if (structFields == null) { - BArray structData = record.getArrayValue(key); - processArray(xmlStreamWriter, structData); - } else { - BMap structData = record.getMapValue(key); - processStruct(xmlStreamWriter, structData, structFields, index); - } + BMap structData = record.getMapValue(key); + processStruct(xmlStreamWriter, structData, structField); break; default: value = String.valueOf(record.getStringValue(key)); @@ -146,42 +138,36 @@ private void writeElement(MapValueImpl record, } private void processArray(XMLStreamWriter xmlStreamWriter, BArray array) throws XMLStreamException { - if (array != null) { - for (int i = 0; i < array.size(); i++) { - xmlStreamWriter.writeStartElement("", ARRAY_ELEMENT_NAME, ""); - xmlStreamWriter.writeCharacters(String.valueOf(array.get(i))); - xmlStreamWriter.writeEndElement(); - } + if (array == null) { + return; + } + for (int i = 0; i < array.size(); i++) { + xmlStreamWriter.writeStartElement("", ARRAY_ELEMENT_NAME, ""); + xmlStreamWriter.writeCharacters(String.valueOf(array.get(i))); + xmlStreamWriter.writeEndElement(); } } - private void processStruct(XMLStreamWriter xmlStreamWriter, BMap structData, - BField[] structFields, int index) throws XMLStreamException { - boolean structError = true; - Type internalType = TypeUtils.getImpliedType(structFields[index].getFieldType()); - if (internalType.getTag() == TypeTags.OBJECT_TYPE_TAG - || internalType.getTag() == TypeTags.RECORD_TYPE_TAG) { - BField[] internalStructFields = ((BStructureType) internalType).getFields() - .values().toArray(new BField[0]); - if (internalStructFields != null) { - for (int i = 0; i < internalStructFields.length; i++) { - BString internalKeyName = StringUtils.fromString(internalStructFields[i].getFieldName()); - Object val = structData.get(internalKeyName); - xmlStreamWriter.writeStartElement("", internalStructFields[i].getFieldName(), ""); - if (val instanceof MapValueImpl mapValue) { - processStruct(xmlStreamWriter, mapValue, internalStructFields, i); - } else { - xmlStreamWriter.writeCharacters(val.toString()); - } - xmlStreamWriter.writeEndElement(); - } - structError = false; - } - } - if (structError) { + private void processStruct(XMLStreamWriter xmlStreamWriter, BMap structData, Field structField) + throws XMLStreamException { + Type internalType = TypeUtils.getImpliedType(structField.getFieldType()); + if (internalType.getTag() != TypeTags.OBJECT_TYPE_TAG && internalType.getTag() != TypeTags.RECORD_TYPE_TAG) { throw ErrorCreator.createError(StringUtils.fromString( "error in constructing the xml element from struct type data")); } + + Collection internalStructFields = ((BStructureType) internalType).getFields().values(); + for (Field internalStructField : internalStructFields) { + BString internalKeyName = StringUtils.fromString(internalStructField.getFieldName()); + Object val = structData.get(internalKeyName); + xmlStreamWriter.writeStartElement("", internalStructField.getFieldName(), ""); + if (val instanceof MapValueImpl mapValue) { + processStruct(xmlStreamWriter, mapValue, internalStructField); + } else { + xmlStreamWriter.writeCharacters(val.toString()); + } + xmlStreamWriter.writeEndElement(); + } } @Override 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 908c590b9fe5..cc3e8e8fdc1c 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 @@ -1744,9 +1744,7 @@ private static boolean checkObjectSubTypeForMethods(List unresolvedTyp } MethodType rhsFunc = rhsFunction.get(); - if (rhsFunc == null || - !isInSameVisibilityRegion(targetTypeModule, sourceTypeModule, lhsFunc.getFlags(), - rhsFunc.getFlags())) { + if (!isInSameVisibilityRegion(targetTypeModule, sourceTypeModule, lhsFunc.getFlags(), rhsFunc.getFlags())) { return false; } if (SymbolFlags.isFlagOn(lhsFunc.getFlags(), SymbolFlags.REMOTE) != SymbolFlags @@ -1803,7 +1801,7 @@ private static Optional getMatchingInvokableType(List rh return matchingFunction; } - if ((lhsFuncIsResource && !matchingFuncIsResource) || (matchingFuncIsResource && !lhsFuncIsResource)) { + if (!lhsFuncIsResource || !matchingFuncIsResource) { return Optional.empty(); } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/Strand.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/Strand.java index 0e9e972752a4..f107be50f6e8 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/Strand.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/scheduling/Strand.java @@ -500,8 +500,7 @@ private void getInfoFromYieldedState(StringBuilder strandInfo, String closingBra strandInfo.append(RUNNABLE).append(closingBracketWithNewLines); return; } - if (!this.isYielded() || noPickedYieldStatus) { - // if frames have got empty, noPickedYieldStatus is true, then the state has changed to runnable + if (!this.isYielded()) { strandInfo.append(RUNNABLE).append(closingBracketWithNewLines); return; } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/util/CompatibilityChecker.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/util/CompatibilityChecker.java index e5ed38a11e16..f0f1507122bc 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/util/CompatibilityChecker.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/util/CompatibilityChecker.java @@ -62,7 +62,7 @@ public static void verifyJavaCompatibility(String compiledVersion) { } // if both have only major versions, then stop checking further. - if (compiledVersionParts.length == 1 && compiledVersionParts.length == 1) { + if (compiledVersionParts.length == 1 && runtimeVersionParts.length == 1) { return; } diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/XmlSequence.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/XmlSequence.java index cca632cf9dd2..f024b023c122 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/XmlSequence.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/internal/values/XmlSequence.java @@ -309,11 +309,8 @@ public void addChildren(BXml xmlItem) { // If sequence contains children of same type // the sequence type should be changed to that corresponding xml type boolean isSameType = true; - Type tempExprType = null; - if (!children.isEmpty()) { - tempExprType = children.get(0).getType(); - } + Type tempExprType = children.get(0).getType(); for (int i = 1; i < children.size(); i++) { if (tempExprType != children.get(i).getType()) { diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/metrics/StatisticConfig.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/metrics/StatisticConfig.java index 8d311ca39de9..7242e0fe2a2e 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/metrics/StatisticConfig.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/observability/metrics/StatisticConfig.java @@ -62,7 +62,7 @@ private StatisticConfig() { * @see Builder#percentiles(double...) */ public double[] getPercentiles() { - return percentiles != null ? Arrays.copyOf(percentiles, percentiles.length) : percentiles; + return percentiles != null ? Arrays.copyOf(percentiles, percentiles.length) : null; } /** diff --git a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/transactions/TransactionResourceManager.java b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/transactions/TransactionResourceManager.java index 35eec8a9c1c9..aaa870d8298e 100644 --- a/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/transactions/TransactionResourceManager.java +++ b/bvm/ballerina-runtime/src/main/java/io/ballerina/runtime/transactions/TransactionResourceManager.java @@ -136,27 +136,25 @@ public static TransactionResourceManager getInstance() { */ private void setLogProperties() { final Path projectRoot = Path.of(RuntimeUtils.USER_DIR); - if (projectRoot != null) { - String logDir = getTransactionLogDirectory(); - Path logDirPath = Path.of(logDir); - Path transactionLogDirectory; - if (!logDirPath.isAbsolute()) { - logDir = projectRoot.toAbsolutePath().toString() + File.separatorChar + logDir; - transactionLogDirectory = Path.of(logDir); - } else { - transactionLogDirectory = logDirPath; - } - if (!Files.exists(transactionLogDirectory)) { - try { - Files.createDirectory(transactionLogDirectory); - } catch (IOException e) { - STDERR.println("error: failed to create transaction log directory in " + logDir); - } + String logDir = getTransactionLogDirectory(); + Path logDirPath = Path.of(logDir); + Path transactionLogDirectory; + if (!logDirPath.isAbsolute()) { + logDir = projectRoot.toAbsolutePath().toString() + File.separatorChar + logDir; + transactionLogDirectory = Path.of(logDir); + } else { + transactionLogDirectory = logDirPath; + } + if (!Files.exists(transactionLogDirectory)) { + try { + Files.createDirectory(transactionLogDirectory); + } catch (IOException e) { + STDERR.println("error: failed to create transaction log directory in " + logDir); } - System.setProperty(ATOMIKOS_LOG_BASE_PROPERTY, logDir); - System.setProperty(ATOMIKOS_LOG_NAME_PROPERTY, "transaction_recovery"); - System.setProperty(ATOMIKOS_REGISTERED_PROPERTY, "not-registered"); } + System.setProperty(ATOMIKOS_LOG_BASE_PROPERTY, logDir); + System.setProperty(ATOMIKOS_LOG_NAME_PROPERTY, "transaction_recovery"); + System.setProperty(ATOMIKOS_REGISTERED_PROPERTY, "not-registered"); } /** diff --git a/cli/ballerina-cli/src/main/java/io/ballerina/cli/cmd/PushCommand.java b/cli/ballerina-cli/src/main/java/io/ballerina/cli/cmd/PushCommand.java index b0bb908418c2..e1c14d6cf94c 100644 --- a/cli/ballerina-cli/src/main/java/io/ballerina/cli/cmd/PushCommand.java +++ b/cli/ballerina-cli/src/main/java/io/ballerina/cli/cmd/PushCommand.java @@ -207,9 +207,9 @@ public void execute() { Proxy proxy = settings.getProxy(); mvnClient.setProxy(proxy.host(), proxy.port(), proxy.username(), proxy.password()); - if (balaPath == null && isCustomRepository) { + if (balaPath == null) { pushPackage(project, mvnClient); - } else if (isCustomRepository) { + } else { if (!balaPath.toFile().exists()) { throw new ProjectException("path provided for the bala file does not exist: " + balaPath + "."); } diff --git a/cli/ballerina-cli/src/main/java/io/ballerina/cli/task/RunNativeImageTestTask.java b/cli/ballerina-cli/src/main/java/io/ballerina/cli/task/RunNativeImageTestTask.java index d9501a3d51f0..7940325eb374 100644 --- a/cli/ballerina-cli/src/main/java/io/ballerina/cli/task/RunNativeImageTestTask.java +++ b/cli/ballerina-cli/src/main/java/io/ballerina/cli/task/RunNativeImageTestTask.java @@ -252,40 +252,38 @@ public void execute(Project project) { //Write the testsuite to the disk TestUtils.writeToTestSuiteJson(testSuiteMap, testsCachePath); - if (hasTests) { - int testResult = 1; - try { - String warnings = GraalVMCompatibilityUtils.getAllWarnings( - project.currentPackage(), jBallerinaBackend.targetPlatform().code(), true); - if (!warnings.isEmpty()) { - out.println(warnings); - } - testResult = runTestSuiteWithNativeImage(project.currentPackage(), target, testSuiteMap); - if (testResult != 0) { - accumulatedTestResult = testResult; - } - if (report) { - for (Map.Entry testSuiteEntry : testSuiteMap.entrySet()) { - String moduleName = testSuiteEntry.getKey(); - ModuleStatus moduleStatus = TestUtils.loadModuleStatusFromFile( - testsCachePath.resolve(moduleName).resolve(TesterinaConstants.STATUS_FILE)); - if (moduleStatus == null) { - continue; - } - - if (!moduleName.equals(project.currentPackage().packageName().toString())) { - moduleName = ModuleName.from(project.currentPackage().packageName(), - moduleName).toString(); - } - testReport.addModuleStatus(moduleName, moduleStatus); + int testResult; + try { + String warnings = GraalVMCompatibilityUtils.getAllWarnings( + project.currentPackage(), jBallerinaBackend.targetPlatform().code(), true); + if (!warnings.isEmpty()) { + out.println(warnings); + } + testResult = runTestSuiteWithNativeImage(project.currentPackage(), target, testSuiteMap); + if (testResult != 0) { + accumulatedTestResult = testResult; + } + if (report) { + for (Map.Entry testSuiteEntry : testSuiteMap.entrySet()) { + String moduleName = testSuiteEntry.getKey(); + ModuleStatus moduleStatus = TestUtils.loadModuleStatusFromFile( + testsCachePath.resolve(moduleName).resolve(TesterinaConstants.STATUS_FILE)); + if (moduleStatus == null) { + continue; } + + if (!moduleName.equals(project.currentPackage().packageName().toString())) { + moduleName = ModuleName.from(project.currentPackage().packageName(), + moduleName).toString(); + } + testReport.addModuleStatus(moduleName, moduleStatus); } - } catch (IOException e) { - TestUtils.cleanTempCache(project, cachesRoot); - throw createLauncherException("error occurred while running tests: ", e); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); } + } catch (IOException e) { + TestUtils.cleanTempCache(project, cachesRoot); + throw createLauncherException("error occurred while running tests: ", e); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); } } if (report && hasTests) { diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/JBallerinaBackend.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/JBallerinaBackend.java index 7f9931d5e2e3..8f70836d10e2 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/JBallerinaBackend.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/JBallerinaBackend.java @@ -215,10 +215,10 @@ public DiagnosticResult diagnosticResult() { } public EmitResult emit(OutputType outputType, Path filePath) { - Path generatedArtifact = null; + Path generatedArtifact; if (diagnosticResult.hasErrors()) { - return new EmitResult(false, new DefaultDiagnosticResult(new ArrayList<>()), generatedArtifact); + return new EmitResult(false, new DefaultDiagnosticResult(new ArrayList<>()), null); } List emitResultDiagnostics = new ArrayList<>(); diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/ManifestBuilder.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/ManifestBuilder.java index 368c9ed635b6..adb0c4068395 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/ManifestBuilder.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/ManifestBuilder.java @@ -592,7 +592,6 @@ private PackageManifest.Platform getDependencyPlatform(TopLevelNode dependencyNo } private PackageManifest.Platform getGraalvmCompatibilityPlatform(TopLevelNode graalvmCompatibleNode) { - PackageManifest.Platform platform = null; if (graalvmCompatibleNode.kind() == TomlType.KEY_VALUE) { TomlKeyValueNode keyValueNode = ((TomlKeyValueNode) graalvmCompatibleNode); if (keyValueNode.value().kind() == TomlType.BOOLEAN) { @@ -601,7 +600,7 @@ private PackageManifest.Platform getGraalvmCompatibilityPlatform(TopLevelNode gr graalvmCompatible); } } - return platform; + return null; } private List getLocalRepoDependencies() { diff --git a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/ProjectFiles.java b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/ProjectFiles.java index b76b2fdcb02d..088ea516029d 100644 --- a/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/ProjectFiles.java +++ b/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/ProjectFiles.java @@ -384,16 +384,14 @@ public static void validateSingleFileProjectFilePath(Path filePath) { Path projectRoot = ProjectUtils.findProjectRoot(filePath); if (null != projectRoot) { Path absFilePath = filePath.toAbsolutePath(); - if (projectRoot.equals(Optional.of(absFilePath.getParent()).get())) { + if (projectRoot.equals(absFilePath.getParent())) { throw new ProjectException("The source file '" + filePath + "' belongs to a Ballerina package."); } // Check if it is inside a module Path modulesRoot = projectRoot.resolve(ProjectConstants.MODULES_ROOT); Path parent = absFilePath.getParent(); - if (parent != null) { - if (modulesRoot.equals(Optional.of(parent.getParent()).get())) { - throw new ProjectException("The source file '" + filePath + "' belongs to a Ballerina package."); - } + if (parent != null && modulesRoot.equals(parent.getParent())) { + throw new ProjectException("The source file '" + filePath + "' belongs to a Ballerina package."); } } checkReadPermission(filePath); diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/BIRPackageSymbolEnter.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/BIRPackageSymbolEnter.java index 0dd00444e14f..97e943698e19 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/BIRPackageSymbolEnter.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/BIRPackageSymbolEnter.java @@ -145,8 +145,6 @@ public class BIRPackageSymbolEnter { private BStructureTypeSymbol currentStructure = null; private final LinkedList compositeStack = new LinkedList<>(); - private static final int SERVICE_TYPE_TAG = 54; - private static final CompilerContext.Key COMPILED_PACKAGE_SYMBOL_ENTER_KEY = new CompilerContext.Key<>(); @@ -1696,8 +1694,6 @@ public BType readType(int cpI) throws IOException { case TypeTags.FUNCTION_POINTER: // TODO fix break; - case SERVICE_TYPE_TAG: - throw new AssertionError(); case TypeTags.SIGNED32_INT: return symTable.signed32IntType; case TypeTags.SIGNED16_INT: 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 817db44b9bb8..79b4af59f064 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 @@ -360,9 +360,7 @@ private void addIntrospectionInfoAnnotation(BLangClassDefinition serviceClass, S if (fieldSymbol instanceof BVarSymbol bVarSymbol) { descriptorKeyValue.key.fieldSymbol = bVarSymbol; } - if (valueLiteral != null) { - descriptorKeyValue.valueExpr = valueLiteral; - } + descriptorKeyValue.valueExpr = valueLiteral; symResolver.populateAnnotationAttachmentSymbol(annoAttachment, env, constantValueResolver); @@ -786,9 +784,7 @@ private void addVarArgsAnnotation(BLangFunction mainFunc, SymbolEnv env) { if (fieldSymbol instanceof BVarSymbol bVarSymbol) { descriptorKeyValue.key.fieldSymbol = bVarSymbol; } - if (valueLiteral != null) { - descriptorKeyValue.valueExpr = valueLiteral; - } + descriptorKeyValue.valueExpr = valueLiteral; symResolver.populateAnnotationAttachmentSymbol(annoAttachment, env, constantValueResolver); ((List) mainFunc.symbol.getAnnotations()).add( diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/ClassClosureDesugar.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/ClassClosureDesugar.java index 6728becea920..08d64bea1b74 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/ClassClosureDesugar.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/ClassClosureDesugar.java @@ -949,9 +949,8 @@ public void visit(BLangSimpleVarRef.BLangLocalVarRef localVarRef) { return; } - BVarSymbol mapSym = null; //createMapSymbolIfAbsent(symbolEnv.node, symbolEnv.envCount); - updateClosureVars(localVarRef, mapSym); + updateClosureVars(localVarRef, null); } @Override @@ -1417,7 +1416,7 @@ private void updateFields(BLangClassDefinition classDef) { private BLangNode getNextPossibleNode(SymbolEnv envArg) { SymbolEnv localEnv = envArg; BLangNode node = localEnv.node; - while (localEnv != null) { + while (true) { NodeKind kind = node.getKind(); if (kind == NodeKind.PACKAGE) { break; diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/ClosureDesugar.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/ClosureDesugar.java index 98f38d9c9d85..36c7f958a3b5 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/ClosureDesugar.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/ClosureDesugar.java @@ -418,7 +418,7 @@ private BVarSymbol addFunctionMapMapToClassDefinition(BLangClassDefinition class private BLangNode getNextPossibleNode(SymbolEnv envArg) { SymbolEnv localEnv = envArg; BLangNode node = localEnv.node; - while (localEnv != null) { + while (true) { NodeKind kind = node.getKind(); if (kind == NodeKind.PACKAGE) { break; diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/Desugar.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/Desugar.java index 683de4d78266..b3542dff2c94 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/Desugar.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/Desugar.java @@ -3341,7 +3341,7 @@ public void visit(BLangRetryTransaction retryTransaction) { retryTransaction.transaction.pos = null; retryTransaction.transaction.transactionBody.pos = null; - BLangBlockStmt retryBody = ASTBuilderUtil.createBlockStmt(retryTransaction.pos); + BLangBlockStmt retryBody = ASTBuilderUtil.createBlockStmt(null); retryBody.stmts.add(retryTransaction.transaction); BLangRetry retry = (BLangRetry) TreeBuilder.createRetryNode(); @@ -6328,9 +6328,9 @@ public void visit(BLangSimpleVarRef varRefExpr) { return; } - // If the the variable is not used in lhs, then add a conversion if required. + // If the variable is not used in lhs, then add a conversion if required. // This is done to make the types compatible for narrowed types. - genVarRefExpr.isLValue = varRefExpr.isLValue; + genVarRefExpr.isLValue = false; BType targetType = genVarRefExpr.getBType(); genVarRefExpr.setBType(genVarRefExpr.symbol.type); BLangExpression expression = types.addConversionExprIfRequired(genVarRefExpr, targetType); @@ -7790,12 +7790,12 @@ private void createTypeCastExprForRelationalExpr(BLangBinaryExpr binaryExpr, int return; } - if (isLhsIntegerType && !isRhsIntegerType) { + if (isLhsIntegerType) { addTypeCastForBinaryExprB(binaryExpr, symTable.intType, rhsExprType); return; } - if (!isLhsIntegerType && isRhsIntegerType) { + if (isRhsIntegerType) { addTypeCastForBinaryExprA(binaryExpr, symTable.intType, lhsExprType); return; } @@ -7819,12 +7819,12 @@ private void createTypeCastExprForRelationalExpr(BLangBinaryExpr binaryExpr, int return; } - if (isLhsStringType && !isRhsStringType) { + if (isLhsStringType) { addTypeCastForBinaryExprB(binaryExpr, symTable.stringType, rhsExprType); return; } - if (!isLhsStringType && isRhsStringType) { + if (isRhsStringType) { addTypeCastForBinaryExprA(binaryExpr, symTable.stringType, lhsExprType); } } diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/packaging/converters/URIConverter.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/packaging/converters/URIConverter.java index 9f341d7f7d3a..ed17e3edbef3 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/packaging/converters/URIConverter.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/packaging/converters/URIConverter.java @@ -120,36 +120,12 @@ public Stream finalize(URI remoteURI, PackageID moduleID) { String supportedVersionRange = ""; boolean nightlyBuild = RepoUtils.getBallerinaVersion().contains("SNAPSHOT"); for (String supportedPlatform : SUPPORTED_PLATFORMS) { - String errorMessage = ""; - - if (!errorMessage.isEmpty()) { - // removing the error stack - if (errorMessage.contains("\n\tat")) { - errorMessage = errorMessage.substring(0, errorMessage.indexOf("\n\tat")); - } - - // if module already exists in home repository - if (errorMessage.contains("module already exists in the home repository") && this.isBuild) { - // Need to update the version of moduleID that was resolved by remote. But since the version - // cannot be returned by the call done to module_pull.bal file we need to set the version from - // the downloaded bala file. - Patten patten = this.homeBalaRepo.calculate(moduleID); - return patten.convertToSources(this.homeBalaRepo.getConverterInstance(), moduleID); - } - - // check if the message is empty or not. Empty means module not found. Else some other error. - // Log if it is some other error. - if (!"".equals(errorMessage.replace("error: \t", "").trim())) { - this.errStream.println(errorMessage.trim()); - return Stream.of(); - } - } else { - // Need to update the version of moduleID that was resolved by remote. But since the version cannot - // be returned by the call done to module_pull.bal file we need to set the version from the - // downloaded bala file. - Patten patten = this.homeBalaRepo.calculate(moduleID); - return patten.convertToSources(this.homeBalaRepo.getConverterInstance(), moduleID); - } + + // Need to update the version of moduleID that was resolved by remote. But since the version cannot + // be returned by the call done to module_pull.bal file we need to set the version from the + // downloaded bala file. + Patten patten = this.homeBalaRepo.calculate(moduleID); + return patten.convertToSources(this.homeBalaRepo.getConverterInstance(), moduleID); } return Stream.of(); } 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 0fa8aec2d8f7..6acdf0aaf800 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 @@ -724,8 +724,6 @@ public BLangNode transform(ImportDeclarationNode importDeclaration) { orgName = orgNameNode.orgName(); } - String version = null; - List pkgNameComps = new ArrayList<>(); NodeList names = importDeclaration.moduleName(); Location position = getPosition(importDeclaration); @@ -735,7 +733,7 @@ public BLangNode transform(ImportDeclarationNode importDeclaration) { importDcl.pos = position; importDcl.pkgNameComps = pkgNameComps; importDcl.orgName = this.createIdentifier(getPosition(orgNameNode), orgName); - importDcl.version = this.createIdentifier(null, version); + importDcl.version = this.createIdentifier(null, (String) null); if (prefixNode.isEmpty()) { importDcl.alias = pkgNameComps.get(pkgNameComps.size() - 1); diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/ConstantValueResolver.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/ConstantValueResolver.java index 64bbf364dd51..b929c95ad4fe 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/ConstantValueResolver.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/ConstantValueResolver.java @@ -584,7 +584,7 @@ BLangConstantValue constructBLangConstantValueWithExactType(BLangExpression expr constantSymbol.value = value; if (value == null) { - return value; + return null; } this.anonTypeNameSuffixes = anonTypeNameSuffixes; diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/DataflowAnalyzer.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/DataflowAnalyzer.java index b539f07c5f4f..61f0b0af8994 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/DataflowAnalyzer.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/DataflowAnalyzer.java @@ -1366,7 +1366,7 @@ public Integer hash(Node node) { } } else if (node.getKind() == NodeKind.RECORD_LITERAL_KEY_VALUE) { BLangRecordLiteral.BLangRecordKeyValueField field = (BLangRecordLiteral.BLangRecordKeyValueField) node; - result = 31 * result + hash(field.key.expr) + hash(field.valueExpr); + result = hash(field.key.expr) + hash(field.valueExpr); } else if (node.getKind() == NodeKind.ARRAY_LITERAL_EXPR) { BLangListConstructorExpr.BLangArrayLiteral arrayLiteral = (BLangListConstructorExpr.BLangArrayLiteral) node; @@ -1378,25 +1378,25 @@ public Integer hash(Node node) { result = Objects.hash(literal.value); } else if (node.getKind() == NodeKind.XML_TEXT_LITERAL) { BLangXMLTextLiteral literal = (BLangXMLTextLiteral) node; - result = 31 * result + hash(literal.concatExpr); + result = hash(literal.concatExpr); for (BLangExpression expr : literal.textFragments) { result = result * 31 + hash(expr); } } else if (node.getKind() == NodeKind.XML_ATTRIBUTE) { BLangXMLAttribute attribute = (BLangXMLAttribute) node; - result = 31 * result + hash(attribute.name) + hash(attribute.value); + result = hash(attribute.name) + hash(attribute.value); } else if (node.getKind() == NodeKind.XML_QNAME) { BLangXMLQName xmlqName = (BLangXMLQName) node; - result = 31 * result + hash(xmlqName.localname) + hash(xmlqName.prefix); + result = hash(xmlqName.localname) + hash(xmlqName.prefix); } else if (node.getKind() == NodeKind.XML_COMMENT_LITERAL) { BLangXMLCommentLiteral literal = (BLangXMLCommentLiteral) node; - result = 31 * result + hash(literal.concatExpr); + result = hash(literal.concatExpr); for (BLangExpression expr : literal.textFragments) { result = result * 31 + hash(expr); } } else if (node.getKind() == NodeKind.XML_ELEMENT_LITERAL) { BLangXMLElementLiteral literal = (BLangXMLElementLiteral) node; - result = 31 * result + hash(literal.startTagName) + hash(literal.endTagName); + result = hash(literal.startTagName) + hash(literal.endTagName); for (BLangExpression expr : literal.attributes) { result = 31 * result + hash(expr); } @@ -1405,16 +1405,16 @@ public Integer hash(Node node) { } } else if (node.getKind() == NodeKind.XML_QUOTED_STRING) { BLangXMLQuotedString literal = (BLangXMLQuotedString) node; - result = 31 * result + hash(literal.concatExpr); + result = hash(literal.concatExpr); for (BLangExpression expr : literal.textFragments) { result = result * 31 + hash(expr); } } else if (node.getKind() == NodeKind.XMLNS) { BLangXMLNS xmlns = (BLangXMLNS) node; - result = result * 31 + hash(xmlns.prefix) + hash(xmlns.namespaceURI); + result = hash(xmlns.prefix) + hash(xmlns.namespaceURI); } else if (node.getKind() == NodeKind.XML_PI_LITERAL) { BLangXMLProcInsLiteral literal = (BLangXMLProcInsLiteral) node; - result = 31 * result + hash(literal.target) + hash(literal.dataConcatExpr); + result = hash(literal.target) + hash(literal.dataConcatExpr); for (BLangExpression expr : literal.dataFragments) { result = result * 31 + hash(expr); } @@ -1447,25 +1447,24 @@ public Integer hash(Node node) { } } else if (node.getKind() == NodeKind.TYPE_CONVERSION_EXPR) { BLangTypeConversionExpr typeConversionExpr = (BLangTypeConversionExpr) node; - result = 31 * result + hash(typeConversionExpr.expr); + result = hash(typeConversionExpr.expr); } else if (node.getKind() == NodeKind.BINARY_EXPR) { BLangBinaryExpr binaryExpr = (BLangBinaryExpr) node; - result = 31 * result + hash(binaryExpr.lhsExpr) + hash(binaryExpr.rhsExpr); + result = hash(binaryExpr.lhsExpr) + hash(binaryExpr.rhsExpr); } else if (node.getKind() == NodeKind.UNARY_EXPR) { BLangUnaryExpr unaryExpr = (BLangUnaryExpr) node; - result = 31 * result + hash(unaryExpr.expr); + result = hash(unaryExpr.expr); } else if (node.getKind() == NodeKind.TYPE_TEST_EXPR) { BLangTypeTestExpr typeTestExpr = (BLangTypeTestExpr) node; - result = 31 * result + hash(typeTestExpr.expr); + result = hash(typeTestExpr.expr); } else if (node.getKind() == NodeKind.TERNARY_EXPR) { BLangTernaryExpr ternaryExpr = (BLangTernaryExpr) node; - result = 31 * result + hash(ternaryExpr.expr) + hash(ternaryExpr.thenExpr) + hash(ternaryExpr.elseExpr); + result = hash(ternaryExpr.expr) + hash(ternaryExpr.thenExpr) + hash(ternaryExpr.elseExpr); } else if (node.getKind() == NodeKind.GROUP_EXPR) { BLangGroupExpr groupExpr = (BLangGroupExpr) node; - result = 31 * result + hash(groupExpr.expression); + result = hash(groupExpr.expression); } else if (node.getKind() == NodeKind.REG_EXP_TEMPLATE_LITERAL) { - result = 31 * result + - generateHashForRegExp(((BLangRegExpTemplateLiteral) node).reDisjunction.sequenceList); + result = generateHashForRegExp(((BLangRegExpTemplateLiteral) node).reDisjunction.sequenceList); } else { dlog.error(((BLangExpression) node).pos, DiagnosticErrorCode.EXPRESSION_IS_NOT_A_CONSTANT_EXPRESSION); } @@ -1707,10 +1706,10 @@ public void visit(BLangInvocation invocationExpr) { if (symbol != symTable.notFoundSymbol) { addDependency(invokableOwnerSymbol, symbol); } - } else if (symbol != null && symbol.kind == SymbolKind.FUNCTION) { + } else if (symbol.kind == SymbolKind.FUNCTION) { BInvokableSymbol invokableProviderSymbol = (BInvokableSymbol) symbol; BSymbol curDependent = this.currDependentSymbolDeque.peek(); - if (curDependent != null && isGlobalVarSymbol(curDependent)) { + if (isGlobalVarSymbol(curDependent)) { addDependency(curDependent, invokableProviderSymbol); } } 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 c1105d69a974..298891dc56c8 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 @@ -2984,10 +2984,6 @@ private boolean isIsolatedExpression(BLangExpression expression, boolean logErro case TYPE_INIT_EXPR: BLangTypeInit typeInitExpr = (BLangTypeInit) expression; - if (typeInitExpr == null) { - return true; - } - expression = typeInitExpr.initInvocation; break; case OBJECT_CTOR_EXPRESSION: diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/SemanticAnalyzer.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/SemanticAnalyzer.java index 84e687632a15..5b8566b99307 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/SemanticAnalyzer.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/SemanticAnalyzer.java @@ -4111,7 +4111,7 @@ private void inferServiceTypeFromListeners(BLangService serviceNode, AnalyzerDat private BTypeIdSet getTypeIds(BType type) { type = Types.getImpliedType(type); int tag = type.tag; - if (tag == TypeTags.SERVICE || tag == TypeTags.OBJECT) { + if (tag == TypeTags.OBJECT) { return ((BObjectType) type).typeIdSet; } return BTypeIdSet.emptySet(); 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 650f86031181..cef5cdbdf1a3 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 @@ -810,12 +810,6 @@ public BType getTypeOfDecimalFloatingPointLiteral(BLangLiteral literalExpr, Obje } } return literalExpr.getBType(); - } else if (expectedType.tag == TypeTags.FLOAT) { - if (!types.validateFloatLiteral(literalExpr.pos, numericLiteral)) { - data.resultType = symTable.semanticError; - return symTable.semanticError; - } - return symTable.floatType; } else if (expectedType.tag == TypeTags.UNION) { BUnionType unionType = (BUnionType) expectedType; for (int tag = TypeTags.FLOAT; tag <= TypeTags.DECIMAL; tag++) { @@ -6786,15 +6780,13 @@ private void checkFunctionInvocationExpr(BLangInvocation iExpr, AnalyzerData dat if (pkgSymbol == symTable.notFoundSymbol) { dlog.error(iExpr.pos, DiagnosticErrorCode.UNDEFINED_MODULE, pkgAlias); } else { - if (funcSymbol == symTable.notFoundSymbol) { - BSymbol symbol = symResolver.lookupMainSpaceSymbolInPackage(iExpr.pos, data.env, pkgAlias, funcName); - if ((symbol.tag & SymTag.VARIABLE) == SymTag.VARIABLE) { - funcSymbol = symbol; - } - if (symTable.rootPkgSymbol.pkgID.equals(symbol.pkgID) && - (symbol.tag & SymTag.VARIABLE_NAME) == SymTag.VARIABLE_NAME) { - funcSymbol = symbol; - } + BSymbol symbol = symResolver.lookupMainSpaceSymbolInPackage(iExpr.pos, data.env, pkgAlias, funcName); + if ((symbol.tag & SymTag.VARIABLE) == SymTag.VARIABLE) { + funcSymbol = symbol; + } + if (symTable.rootPkgSymbol.pkgID.equals(symbol.pkgID) && + (symbol.tag & SymTag.VARIABLE_NAME) == SymTag.VARIABLE_NAME) { + funcSymbol = symbol; } if (funcSymbol == symTable.notFoundSymbol || ((funcSymbol.tag & SymTag.TYPE) == SymTag.TYPE)) { BSymbol ctor = 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 d2e43b2155ad..de443d69b5be 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 @@ -3589,7 +3589,7 @@ private Optional getMatchingInvokableType(List(tsymbol.params); invokableSymbol.restParam = tsymbol.restParam; invokableSymbol.retType = tsymbol.returnType; - invokableSymbol.flags = tsymbol.flags; + invokableSymbol.flags = invokableSymbol.flags | tsymbol.flags; } else if (fieldType == symTable.semanticError) { // Can only happen for records. fieldSymbol = new BVarSymbol(origField.symbol.flags | flag | Flags.OPTIONAL, diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/TypeTags.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/TypeTags.java index 8858b5e58aea..4653617c5314 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/TypeTags.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/TypeTags.java @@ -58,7 +58,6 @@ public final class TypeTags { public static final int FUTURE = TUPLE + 1; public static final int FINITE = FUTURE + 1; public static final int OBJECT = FINITE + 1; - public static final int SERVICE = OBJECT; public static final int BYTE_ARRAY = OBJECT + 1; public static final int FUNCTION_POINTER = BYTE_ARRAY + 1; public static final int HANDLE = FUNCTION_POINTER + 1; diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/Unifier.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/Unifier.java index 598d04640cae..51225b103c49 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/Unifier.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/util/Unifier.java @@ -332,16 +332,16 @@ public BType visit(BTableType originalType, BType expType) { } if (isSameType(newConstraint, originalType.constraint) && - isSameType(newKeyTypeConstraint, originalType.keyTypeConstraint)) { + isSameType(null, originalType.keyTypeConstraint)) { return originalType; } - if (isSemanticErrorInInvocation(newConstraint) || isSemanticErrorInInvocation(newKeyTypeConstraint)) { + if (isSemanticErrorInInvocation(newConstraint) || isSemanticErrorInInvocation(null)) { return symbolTable.semanticError; } BTableType newTableType = new BTableType(TypeTags.TABLE, newConstraint, null); - newTableType.keyTypeConstraint = newKeyTypeConstraint; + newTableType.keyTypeConstraint = null; newTableType.fieldNameList = originalType.fieldNameList; newTableType.constraintPos = originalType.constraintPos; newTableType.isTypeInlineDefined = originalType.isTypeInlineDefined; diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/BallerinaParser.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/BallerinaParser.java index dacf28c591c7..9b6c6d6cf7e5 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/BallerinaParser.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/BallerinaParser.java @@ -2309,7 +2309,7 @@ private STNode parseAfterParamType(SyntaxKind prevParamKind, STNode annots, STNo } recover(token, ParserRuleContext.AFTER_PARAMETER_TYPE); - return parseAfterParamType(prevParamKind, annots, inclusionSymbol, type, isParamNameOptional); + return parseAfterParamType(prevParamKind, annots, inclusionSymbol, type, false); } /** @@ -2596,7 +2596,7 @@ private STNode parseComplexTypeDescriptorInternal(STNode typeDesc, ParserRuleCon } STNode arrayTypeDesc = parseArrayTypeDescriptor(typeDesc); - return parseComplexTypeDescriptorInternal(arrayTypeDesc, context, isTypedBindingPattern, precedence); + return parseComplexTypeDescriptorInternal(arrayTypeDesc, context, false, precedence); case PIPE_TOKEN: if (precedence.isHigherThanOrEqual(TypePrecedence.UNION)) { return typeDesc; @@ -4676,7 +4676,7 @@ private STNode createMissingSimpleVarDecl(STNode metadata, STNode publicQualifie STNode typedBindingPattern = STNodeFactory.createTypedBindingPatternNode(simpleNameRef, captureBP); if (isModuleVar) { - List varDeclQuals = extractVarDeclQualifiers(qualifiers, isModuleVar); + List varDeclQuals = extractVarDeclQualifiers(qualifiers, true); typedBindingPattern = modifyNodeWithInvalidTokenList(qualifiers, typedBindingPattern); if (isSyntaxKindInList(varDeclQuals, SyntaxKind.CONFIGURABLE_KEYWORD)) { @@ -15869,8 +15869,7 @@ private boolean isAmbiguous(STNode node) { return true; case BINARY_EXPRESSION: STBinaryExpressionNode binaryExpr = (STBinaryExpressionNode) node; - if (binaryExpr.operator.kind != SyntaxKind.PIPE_TOKEN || - binaryExpr.operator.kind == SyntaxKind.BITWISE_AND_TOKEN) { + if (binaryExpr.operator.kind != SyntaxKind.PIPE_TOKEN) { return false; } return isAmbiguous(binaryExpr.lhsExpr) && isAmbiguous(binaryExpr.rhsExpr); @@ -15909,8 +15908,7 @@ private boolean isAllBasicLiterals(STNode node) { return true; case BINARY_EXPRESSION: STBinaryExpressionNode binaryExpr = (STBinaryExpressionNode) node; - if (binaryExpr.operator.kind != SyntaxKind.PIPE_TOKEN || - binaryExpr.operator.kind == SyntaxKind.BITWISE_AND_TOKEN) { + if (binaryExpr.operator.kind != SyntaxKind.PIPE_TOKEN) { return false; } return isAmbiguous(binaryExpr.lhsExpr) && isAmbiguous(binaryExpr.rhsExpr); @@ -17611,7 +17609,7 @@ private STNode parseTupleTypeDescOrListConstructorRhs(STNode openBracket, List(), typedBindingPattern, false); @@ -18943,7 +18941,7 @@ private STNode getBindingPattern(STNode ambiguousNode, boolean isListBP) { DiagnosticCode errorCode = DiagnosticErrorCode.ERROR_INVALID_BINDING_PATTERN; if (isEmpty(ambiguousNode)) { - return ambiguousNode; + return null; } switch (ambiguousNode.kind) { diff --git a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/Node.java b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/Node.java index ab44596c6ccf..a6bb8d87d05d 100644 --- a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/Node.java +++ b/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/Node.java @@ -75,7 +75,7 @@ public Optional ancestor(Predicate filter) { parent = parent.parent(); } - return Optional.ofNullable(parent); + return Optional.empty(); } public List ancestors() { diff --git a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/CreateElement.java b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/CreateElement.java index b487ea95eaeb..e369bd98d4a2 100644 --- a/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/CreateElement.java +++ b/langlib/lang.xml/src/main/java/org/ballerinalang/langlib/xml/CreateElement.java @@ -59,8 +59,7 @@ public static BXml createElement(BString name, BMap attributes } else { xmlqName = ValueCreator.createXmlQName(name, prefix); } - String temp = null; - BXml xmlElement = XmlFactory.createXMLElement(xmlqName, temp); + BXml xmlElement = XmlFactory.createXMLElement(xmlqName, (String) null); xmlElement.setAttributes(attributes); xmlElement.setChildren(getChildren(children)); return xmlElement; diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/CreateTypeCodeAction.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/CreateTypeCodeAction.java index 6415b6dc6436..6ee479f567fc 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/CreateTypeCodeAction.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/codeaction/providers/CreateTypeCodeAction.java @@ -68,7 +68,7 @@ public List getCodeActions(Diagnostic diagnostic, Range diagRange = PathUtil.getRange(diagnostic.location()); Optional node = context.currentSyntaxTree() .map(syntaxTree -> CommonUtil.findNode(diagRange, syntaxTree)); - if (node == null || node.isEmpty() || name.isEmpty()) { + if (node.isEmpty() || name.isEmpty()) { return Collections.emptyList(); } @@ -88,16 +88,11 @@ public List getCodeActions(Diagnostic diagnostic, // Here, we create a closed record if the unknown type is in the return type descriptor. // This is to be aligned with the open-by-default principle where we become conservative // on what we send (return) - StringBuilder sb = new StringBuilder(); - sb.append("type ").append(name.get()) - .append(" record {").append(isReturnType ? "|" : "") - .append(CommonUtil.LINE_SEPARATOR); - sb.append(paddingStr).append(CommonUtil.LINE_SEPARATOR); - sb.append(isReturnType ? "|" : "").append("};").append(CommonUtil.LINE_SEPARATOR); - sb.append(CommonUtil.LINE_SEPARATOR); + String closedRecord = "type %s record {%s%n%s%n%s};%n%n" + .formatted(name.get(), isReturnType ? "|" : "", paddingStr, isReturnType ? "|" : ""); String title = String.format("Create record '%s'", name.get()); - CodeAction codeAction = CodeActionUtil.createCodeAction(title, List.of(new TextEdit(range, sb.toString())), + CodeAction codeAction = CodeActionUtil.createCodeAction(title, List.of(new TextEdit(range, closedRecord)), context.fileUri(), CodeActionKind.QuickFix); return List.of(codeAction); } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/AnnotationUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/AnnotationUtil.java index 06afea2db52c..aeb1ad694352 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/AnnotationUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/AnnotationUtil.java @@ -189,20 +189,20 @@ private static String getAnnotationInsertText(@Nonnull String aliasComponent, An } if (annotationSymbol.typeDescriptor().isPresent()) { annotationStart.append(annotationSymbol.getName().get()); - Optional attachedType - = Optional.ofNullable(CommonUtil.getRawType(annotationSymbol.typeDescriptor().get())); - Optional resultType; - if (attachedType.isPresent() && attachedType.get().typeKind() == TypeDescKind.ARRAY) { - resultType = Optional.of(((ArrayTypeSymbol) attachedType.get()).memberTypeDescriptor()); + TypeSymbol attachedType + = CommonUtil.getRawType(annotationSymbol.typeDescriptor().get()); + TypeSymbol resultType; + if (attachedType.typeKind() == TypeDescKind.ARRAY) { + resultType = ((ArrayTypeSymbol) attachedType).memberTypeDescriptor(); } else { resultType = attachedType; } - if (resultType.isPresent() && (resultType.get().typeKind() == TypeDescKind.RECORD - || resultType.get().typeKind() == TypeDescKind.MAP)) { + if ((resultType.typeKind() == TypeDescKind.RECORD + || resultType.typeKind() == TypeDescKind.MAP)) { List requiredFields = new ArrayList<>(); - if (resultType.get().typeKind() == TypeDescKind.RECORD) { + if (resultType.typeKind() == TypeDescKind.RECORD) { requiredFields.addAll(RecordUtil.getMandatoryRecordFields((RecordTypeSymbol) - resultType.get())); + resultType)); } if (!requiredFields.isEmpty()) { annotationStart.append(" ").append(OPEN_BRACE_KEY).append(LINE_SEPARATOR); diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/CommonUtil.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/CommonUtil.java index ef7080b4e0b2..ada3125d1115 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/CommonUtil.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/common/utils/CommonUtil.java @@ -552,10 +552,8 @@ public static List getQualifiersOfNode(BallerinaCompletionContext context break; case MODULE_PART: List qualsAtCursor = getQualifiersAtCursor(context); - Set foundQuals = qualifiers.stream().map(Node::kind).collect(Collectors.toSet()); context.getNodeAtCursor().leadingInvalidTokens().stream() .filter(token -> QUALIFIER_KINDS.contains(token.kind())) - .filter(token -> !foundQuals.contains(token.kind())) .forEach(qualifiers::add); // Avoid duplicating the token at cursor. qualsAtCursor.stream() diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/util/RegexpCompletionProvider.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/util/RegexpCompletionProvider.java index 461cb2454eb1..2a3af47512c2 100644 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/util/RegexpCompletionProvider.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/completions/providers/context/util/RegexpCompletionProvider.java @@ -163,14 +163,14 @@ public static List getRegexCompletions(NonTerminalNode nodeAtC completionItems.add(new SnippetCompletionItem(ctx, new SnippetBlock(",", snippet + ",", snippet + ",", ItemResolverConstants.VALUE_TYPE, SnippetBlock.Kind.VALUE))); - addAssertionEndCompletion(nodeAtCursor, ctx, nodeFinder, completionItems, resolvedWord); + addAssertionEndCompletion(nodeAtCursor, ctx, nodeFinder, completionItems, null); return completionItems; } if (isReQuantifier(nodeAtCursor)) { completionItems.add(new SnippetCompletionItem(ctx, new SnippetBlock("?", "?", "?", ItemResolverConstants.VALUE_TYPE, SnippetBlock.Kind.VALUE))); - addAssertionEndCompletion(nodeAtCursor, ctx, nodeFinder, completionItems, resolvedWord); + addAssertionEndCompletion(nodeAtCursor, ctx, nodeFinder, completionItems, null); return completionItems; } @@ -178,7 +178,7 @@ public static List getRegexCompletions(NonTerminalNode nodeAtC && nodeAtCursor.textRange().endOffset() == ctx.getCursorPositionInTree()) { completionItems.add(new SnippetCompletionItem(ctx, new SnippetBlock("?", "?", "?", ItemResolverConstants.VALUE_TYPE, SnippetBlock.Kind.VALUE))); - addAssertionEndCompletion(nodeAtCursor, ctx, nodeFinder, completionItems, resolvedWord); + addAssertionEndCompletion(nodeAtCursor, ctx, nodeFinder, completionItems, null); return completionItems; } @@ -214,7 +214,7 @@ public static List getRegexCompletions(NonTerminalNode nodeAtC Snippet.DEF_SQUARE_BRACKET.get())); completionItems.add(new SnippetCompletionItem(ctx, RegexpCompletionProvider.RegexSnippet.DEF_ASSERTION_START.get())); - addAssertionEndCompletion(nodeAtCursor, ctx, nodeFinder, completionItems, resolvedWord); + addAssertionEndCompletion(nodeAtCursor, ctx, nodeFinder, completionItems, null); return completionItems; } diff --git a/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/utils/BindgenNodeFactory.java b/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/utils/BindgenNodeFactory.java index 333d8e50bc59..d16dc9a228c6 100644 --- a/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/utils/BindgenNodeFactory.java +++ b/misc/ballerina-bindgen/src/main/java/org/ballerinalang/bindgen/utils/BindgenNodeFactory.java @@ -304,7 +304,7 @@ private static String documentationParamDescription(BFunction.BFunctionKind func private static String documentationReturnDescription(BFunction bFunction) { String paramDescription = null; if (bFunction.getReturnType() == null && bFunction.getErrorType() == null) { - return paramDescription; + return null; } if (bFunction.getKind() == BFunction.BFunctionKind.CONSTRUCTOR) { if (bFunction.getErrorType() != null) { diff --git a/misc/compiler-plugins/modules/configurable-schema-generator/src/main/java/org/ballerinalang/config/schema/generator/ConfigSchemaGenTask.java b/misc/compiler-plugins/modules/configurable-schema-generator/src/main/java/org/ballerinalang/config/schema/generator/ConfigSchemaGenTask.java index 5d49f203999e..be8ac49ef48e 100644 --- a/misc/compiler-plugins/modules/configurable-schema-generator/src/main/java/org/ballerinalang/config/schema/generator/ConfigSchemaGenTask.java +++ b/misc/compiler-plugins/modules/configurable-schema-generator/src/main/java/org/ballerinalang/config/schema/generator/ConfigSchemaGenTask.java @@ -62,7 +62,7 @@ private void writeConfigJSONSchema(String schema, Project project) { } else { path = project.targetDir().resolve(ProjectConstants.BIN_DIR_NAME); } - if (path != null && !schema.isEmpty()) { + if (!schema.isEmpty()) { Path configSchemaFile = path.resolve(CONFIG_SCHEMA); createIfNotExists(configSchemaFile); writeContent(configSchemaFile, schema); 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 d0043efada68..9d0b8b935ad2 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 @@ -45,12 +45,12 @@ import java.util.ArrayList; import java.util.Comparator; -import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; @@ -68,7 +68,7 @@ public class BreakpointProcessor { private final ExecutionContext context; private final JDIEventProcessor jdiEventProcessor; - private final Map> userBreakpoints = new HashMap<>(); + private final Map> userBreakpoints = new ConcurrentHashMap<>(); private static final Logger LOGGER = LoggerFactory.getLogger(BreakpointProcessor.class); public BreakpointProcessor(ExecutionContext context, JDIEventProcessor jdiEventProcessor) { @@ -77,7 +77,7 @@ public BreakpointProcessor(ExecutionContext context, JDIEventProcessor jdiEventP } public Map> getUserBreakpoints() { - return Map.copyOf(userBreakpoints); + return userBreakpoints; } /** @@ -250,8 +250,10 @@ void activateDynamicBreakPoints(int threadId, DynamicBreakpointMode mode) { } } catch (JdiProxyException e) { LOGGER.error(e.getMessage()); - int stepType = ((StepRequest) jdiEventProcessor.getStepRequests().get(0)).depth(); - jdiEventProcessor.sendStepRequest(threadId, stepType); + if (!jdiEventProcessor.getStepRequests().isEmpty()) { + int stepType = ((StepRequest) jdiEventProcessor.getStepRequests().get(0)).depth(); + jdiEventProcessor.sendStepRequest(threadId, stepType); + } } } 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 6c4bcdb776b3..b6d854e42bf6 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 @@ -224,19 +224,27 @@ public CompletableFuture setBreakpoints(SetBreakpointsAr breakpointsMap.put(bp.getLine(), bp); } - SetBreakpointsResponse breakpointsResponse = new SetBreakpointsResponse(); + SetBreakpointsResponse bpResponse = new SetBreakpointsResponse(); String sourcePathUri = args.getSource().getPath(); Optional qualifiedClassName = getQualifiedClassName(context, sourcePathUri); - qualifiedClassName.ifPresent(className -> { - eventProcessor.enableBreakpoints(className, breakpointsMap); - BreakpointProcessor breakpointProcessor = eventProcessor.getBreakpointProcessor(); - Breakpoint[] breakpoints = breakpointProcessor.getUserBreakpoints().get(qualifiedClassName.get()) - .values().stream() - .map(BalBreakpoint::getAsDAPBreakpoint) - .toArray(Breakpoint[]::new); - breakpointsResponse.setBreakpoints(breakpoints); - }); - return breakpointsResponse; + if (qualifiedClassName.isEmpty()) { + LOGGER.warn("Failed to set breakpoints. Source path is not a valid Ballerina source: " + sourcePathUri); + return bpResponse; + } + + eventProcessor.enableBreakpoints(qualifiedClassName.get(), breakpointsMap); + BreakpointProcessor bpProcessor = eventProcessor.getBreakpointProcessor(); + Map userBpMap = bpProcessor.getUserBreakpoints().get(qualifiedClassName.get()); + if (userBpMap == null) { + LOGGER.warn("Failed to set breakpoints for source: " + sourcePathUri); + return bpResponse; + } + + Breakpoint[] breakpoints = userBpMap.values().stream() + .map(BalBreakpoint::getAsDAPBreakpoint) + .toArray(Breakpoint[]::new); + bpResponse.setBreakpoints(breakpoints); + return bpResponse; }); } 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 93722428b10b..37b8a123888a 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 @@ -42,6 +42,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CopyOnWriteArrayList; import static org.ballerinalang.debugadapter.BreakpointProcessor.DynamicBreakpointMode; import static org.ballerinalang.debugadapter.JBallerinaDebugServer.isBalStackFrame; @@ -55,7 +56,7 @@ public class JDIEventProcessor { private final ExecutionContext context; private final BreakpointProcessor breakpointProcessor; private boolean isRemoteVmAttached = false; - private final List stepRequests = new ArrayList<>(); + private final List stepRequests = new CopyOnWriteArrayList<>(); private static final Logger LOGGER = LoggerFactory.getLogger(JDIEventProcessor.class); JDIEventProcessor(ExecutionContext context) { diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java index 3b5ae46f603f..206307d1099a 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java @@ -3834,7 +3834,7 @@ public Token transform(Token token) { private T formatNode(T node, int trailingWS, int trailingNL, Boolean preserveIndentation) { try { if (node == null) { - return node; + return null; } if (!isInlineRange(node, lineRange)) { @@ -3900,7 +3900,7 @@ private T formatNode(T node, int trailingWS, int trailingNL) { private T formatToken(T token, int trailingWS, int trailingNL, Boolean preserveIndentation) { try { if (token == null) { - return token; + return null; } if (!isInlineRange(token, lineRange)) { @@ -4674,10 +4674,10 @@ private void setIndentation(int value) { private void preserveIndentation(boolean value) { if (value) { if (env.trailingNL < 1) { - env.preserveIndentation = value; + env.preserveIndentation = true; } } else { - env.preserveIndentation = value; + env.preserveIndentation = false; } } diff --git a/misc/identifier-util/src/main/java/io/ballerina/identifier/Utils.java b/misc/identifier-util/src/main/java/io/ballerina/identifier/Utils.java index 0e87690aa193..f050ed7adc72 100644 --- a/misc/identifier-util/src/main/java/io/ballerina/identifier/Utils.java +++ b/misc/identifier-util/src/main/java/io/ballerina/identifier/Utils.java @@ -139,7 +139,7 @@ private static String getFormattedStringForJvmReservedSet(char c) { */ public static String decodeIdentifier(String encodedIdentifier) { if (encodedIdentifier == null) { - return encodedIdentifier; + return null; } StringBuilder sb = new StringBuilder(); int index = 0; diff --git a/misc/maven-resolver/src/main/java/org/ballerinalang/maven/bala/client/MavenResolverClient.java b/misc/maven-resolver/src/main/java/org/ballerinalang/maven/bala/client/MavenResolverClient.java index 0f5fb2b49351..36d6e4ee6342 100644 --- a/misc/maven-resolver/src/main/java/org/ballerinalang/maven/bala/client/MavenResolverClient.java +++ b/misc/maven-resolver/src/main/java/org/ballerinalang/maven/bala/client/MavenResolverClient.java @@ -19,7 +19,6 @@ import org.apache.maven.model.Model; import org.apache.maven.model.io.xpp3.MavenXpp3Writer; import org.apache.maven.repository.internal.MavenRepositorySystemUtils; -import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.WriterFactory; import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.RepositorySystem; @@ -197,8 +196,6 @@ private File generatePomFile(String groupId, String artifactId, String version) Writer fw = WriterFactory.newXmlWriter(tempFile); new MavenXpp3Writer().write(fw, model); fw.close(); - fw = null; - IOUtil.close(fw); return tempFile; } } 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 98542b9ee40c..ca3a75f25614 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 @@ -391,7 +391,7 @@ private static String cleanupClassName(String className) { public static String decodeIdentifier(String encodedIdentifier) { if (encodedIdentifier == null) { - return encodedIdentifier; + return null; } StringBuilder sb = new StringBuilder(); int index = 0; diff --git a/misc/toml-parser/src/main/java/io/ballerina/toml/syntax/tree/Node.java b/misc/toml-parser/src/main/java/io/ballerina/toml/syntax/tree/Node.java index 664bf942d037..184bef84eeba 100644 --- a/misc/toml-parser/src/main/java/io/ballerina/toml/syntax/tree/Node.java +++ b/misc/toml-parser/src/main/java/io/ballerina/toml/syntax/tree/Node.java @@ -75,7 +75,7 @@ public Optional ancestor(Predicate filter) { parent = parent.parent(); } - return Optional.ofNullable(parent); + return Optional.empty(); } public List ancestors() { diff --git a/semtypes/src/test/java/io/ballerina/semtype/SemTypeTest.java b/semtypes/src/test/java/io/ballerina/semtype/SemTypeTest.java index e3d1907df1a9..a4a16c8e6031 100644 --- a/semtypes/src/test/java/io/ballerina/semtype/SemTypeTest.java +++ b/semtypes/src/test/java/io/ballerina/semtype/SemTypeTest.java @@ -26,6 +26,7 @@ */ public class SemTypeTest { + @SuppressWarnings("ConstantValue") @Test public void testSemType() { SemTypeMock s1 = new UniformTypeBitSetMock(0x00); diff --git a/settings.gradle b/settings.gradle index 5fd19c3897df..db9cab84d223 100644 --- a/settings.gradle +++ b/settings.gradle @@ -4,7 +4,7 @@ pluginManagement { } plugins { - id "com.gradle.enterprise" version "3.13.2" + id "com.gradle.develocity" version "3.17.5" } rootProject.name = 'ballerina-parent' @@ -294,9 +294,9 @@ buildCache { } } -gradleEnterprise { +develocity { buildScan { - termsOfServiceUrl = 'https://gradle.com/terms-of-service' - termsOfServiceAgree = 'yes' + termsOfUseUrl = 'https://gradle.com/help/legal-terms-of-use' + termsOfUseAgree = 'yes' } } diff --git a/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/context/BServerInstance.java b/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/context/BServerInstance.java index 7959b3d709c2..dcc709041ed0 100644 --- a/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/context/BServerInstance.java +++ b/tests/ballerina-test-utils/src/main/java/org/ballerinalang/test/context/BServerInstance.java @@ -89,7 +89,7 @@ private void initialize() throws BallerinaTestException { private void configureAgentArgs() throws BallerinaTestException { String balAgent = Path.of(System.getProperty(BALLERINA_AGENT_PATH)).toString(); - if (balAgent == null || balAgent.isEmpty()) { + if (balAgent.isEmpty()) { throw new BallerinaTestException("Cannot start server, Ballerina agent not provided"); } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/binaryoperations/BinaryExprTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/binaryoperations/BinaryExprTest.java index 1cd6eb317e5b..e5f6991826ca 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/binaryoperations/BinaryExprTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/binaryoperations/BinaryExprTest.java @@ -29,6 +29,7 @@ /** * Class to test functionality of binary expressions. */ +@SuppressWarnings("ConstantValue") public class BinaryExprTest { CompileResult result; diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/binaryoperations/OperatorPrecedenceTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/binaryoperations/OperatorPrecedenceTest.java index 4930ab7dfc72..50a4f7e4d30a 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/binaryoperations/OperatorPrecedenceTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/binaryoperations/OperatorPrecedenceTest.java @@ -216,6 +216,7 @@ public void testMultiplicationPrecedence() { Assert.assertEquals(actualResult, expectedResult, "The results of multiplication operation differ"); } + @SuppressWarnings("ConstantValue") @Test(description = "Test if division takes precedence over addition and subtraction") public void testDivisionPrecedence() { @@ -240,6 +241,7 @@ public void testDivisionPrecedence() { } + @SuppressWarnings("ConstantValue") @Test(description = "Test if division and multiplication takes same precedence over addition and subtraction") public void testDivisionAndMultiplicationPrecedence() { diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/ReadonlyRecordFieldTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/ReadonlyRecordFieldTest.java index 2f8ce30afd2d..6acfa020b0d0 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/ReadonlyRecordFieldTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/record/ReadonlyRecordFieldTest.java @@ -40,6 +40,15 @@ public void testReadonlyRecordFields(String testFunction) { BRunUtil.invoke(result, testFunction); } + @Test + public void testReadonlyInheritanceForInvokableTypeRecordField() { + BCompileUtil.compileAndCacheBala( + "test-src/record/cloned_record_field_flag_inheritance/imported_module_with_readonly_records"); + CompileResult result = BCompileUtil.compile( + "test-src/record/cloned_record_field_flag_inheritance/module_with_field_access_for_readonly_record"); + assertEquals(result.getErrorCount(), 0); + } + @DataProvider(name = "readonlyRecordFieldTestFunctions") public Object[][] readonlyRecordFieldTestFunctions() { return new Object[][]{ diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/bytetype/BByteValueTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/bytetype/BByteValueTest.java index 3ce79c4ec482..bb0dd4f27c81 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/bytetype/BByteValueTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/bytetype/BByteValueTest.java @@ -39,6 +39,7 @@ * @since 0.980 */ +@SuppressWarnings("ConstantValue") public class BByteValueTest { private CompileResult result; diff --git a/tests/jballerina-unit-test/src/test/resources/test-src/record/cloned_record_field_flag_inheritance/imported_module_with_readonly_records/Ballerina.toml b/tests/jballerina-unit-test/src/test/resources/test-src/record/cloned_record_field_flag_inheritance/imported_module_with_readonly_records/Ballerina.toml new file mode 100644 index 000000000000..a606d18f8e35 --- /dev/null +++ b/tests/jballerina-unit-test/src/test/resources/test-src/record/cloned_record_field_flag_inheritance/imported_module_with_readonly_records/Ballerina.toml @@ -0,0 +1,4 @@ +[package] +org = "test_org" +name = "ReadonlyRecord" +version = "0.1.0" diff --git a/tests/jballerina-unit-test/src/test/resources/test-src/record/cloned_record_field_flag_inheritance/imported_module_with_readonly_records/util.bal b/tests/jballerina-unit-test/src/test/resources/test-src/record/cloned_record_field_flag_inheritance/imported_module_with_readonly_records/util.bal new file mode 100644 index 000000000000..8f113cffdf16 --- /dev/null +++ b/tests/jballerina-unit-test/src/test/resources/test-src/record/cloned_record_field_flag_inheritance/imported_module_with_readonly_records/util.bal @@ -0,0 +1,25 @@ +// Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +public type InvokableTypeDef function (int) returns int; + +public type RecA record {| + readonly & InvokableTypeDef preProcessor?; +|}; + +public type RecB record {| + readonly RecA[] recArr; +|}; diff --git a/tests/jballerina-unit-test/src/test/resources/test-src/record/cloned_record_field_flag_inheritance/module_with_field_access_for_readonly_record/Ballerina.toml b/tests/jballerina-unit-test/src/test/resources/test-src/record/cloned_record_field_flag_inheritance/module_with_field_access_for_readonly_record/Ballerina.toml new file mode 100644 index 000000000000..99f212727cb3 --- /dev/null +++ b/tests/jballerina-unit-test/src/test/resources/test-src/record/cloned_record_field_flag_inheritance/module_with_field_access_for_readonly_record/Ballerina.toml @@ -0,0 +1,10 @@ +[package] +org = "test_org" +name = "LocalPkgUsage" +version = "0.1.0" + +[[dependency]] +org = "test_org" +name = "ReadonlyRecord" +version = "0.1.0" +repository="local" diff --git a/tests/jballerina-unit-test/src/test/resources/test-src/record/cloned_record_field_flag_inheritance/module_with_field_access_for_readonly_record/main.bal b/tests/jballerina-unit-test/src/test/resources/test-src/record/cloned_record_field_flag_inheritance/module_with_field_access_for_readonly_record/main.bal new file mode 100644 index 000000000000..53a9534447c3 --- /dev/null +++ b/tests/jballerina-unit-test/src/test/resources/test-src/record/cloned_record_field_flag_inheritance/module_with_field_access_for_readonly_record/main.bal @@ -0,0 +1,25 @@ +// Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +import test_org/ReadonlyRecord; + +ReadonlyRecord:RecB rec = { + recArr: [] +}; + +public function main() { + ReadonlyRecord:RecA[] & readonly ops = rec.recArr; +}