From 56be443caeb16032613c0c4997d92b74fc2e28e7 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Tue, 2 May 2023 07:53:53 +0200 Subject: [PATCH 001/136] [maven-release-plugin] prepare for next development iteration --- javaparser-core-generators/pom.xml | 2 +- javaparser-core-metamodel-generator/pom.xml | 2 +- javaparser-core-serialization/pom.xml | 2 +- javaparser-core-testing-bdd/pom.xml | 2 +- javaparser-core-testing/pom.xml | 2 +- javaparser-core/pom.xml | 2 +- javaparser-symbol-solver-core/pom.xml | 2 +- javaparser-symbol-solver-testing/pom.xml | 2 +- pom.xml | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) diff --git a/javaparser-core-generators/pom.xml b/javaparser-core-generators/pom.xml index 5026710358..0057ccddd4 100644 --- a/javaparser-core-generators/pom.xml +++ b/javaparser-core-generators/pom.xml @@ -3,7 +3,7 @@ javaparser-parent com.github.javaparser - 3.25.3 + 3.25.4-SNAPSHOT 4.0.0 diff --git a/javaparser-core-metamodel-generator/pom.xml b/javaparser-core-metamodel-generator/pom.xml index 192c0d5df4..5f3dfeee92 100644 --- a/javaparser-core-metamodel-generator/pom.xml +++ b/javaparser-core-metamodel-generator/pom.xml @@ -3,7 +3,7 @@ javaparser-parent com.github.javaparser - 3.25.3 + 3.25.4-SNAPSHOT 4.0.0 diff --git a/javaparser-core-serialization/pom.xml b/javaparser-core-serialization/pom.xml index b240d7489b..11a67d5ef4 100644 --- a/javaparser-core-serialization/pom.xml +++ b/javaparser-core-serialization/pom.xml @@ -2,7 +2,7 @@ javaparser-parent com.github.javaparser - 3.25.3 + 3.25.4-SNAPSHOT 4.0.0 diff --git a/javaparser-core-testing-bdd/pom.xml b/javaparser-core-testing-bdd/pom.xml index beaea91e21..d87055a56e 100644 --- a/javaparser-core-testing-bdd/pom.xml +++ b/javaparser-core-testing-bdd/pom.xml @@ -2,7 +2,7 @@ javaparser-parent com.github.javaparser - 3.25.3 + 3.25.4-SNAPSHOT 4.0.0 diff --git a/javaparser-core-testing/pom.xml b/javaparser-core-testing/pom.xml index 3a053e7da7..d622aefa95 100644 --- a/javaparser-core-testing/pom.xml +++ b/javaparser-core-testing/pom.xml @@ -2,7 +2,7 @@ javaparser-parent com.github.javaparser - 3.25.3 + 3.25.4-SNAPSHOT 4.0.0 diff --git a/javaparser-core/pom.xml b/javaparser-core/pom.xml index be4c95f99a..24f9735110 100644 --- a/javaparser-core/pom.xml +++ b/javaparser-core/pom.xml @@ -2,7 +2,7 @@ javaparser-parent com.github.javaparser - 3.25.3 + 3.25.4-SNAPSHOT 4.0.0 diff --git a/javaparser-symbol-solver-core/pom.xml b/javaparser-symbol-solver-core/pom.xml index 115bbe127d..77a9a1be5a 100644 --- a/javaparser-symbol-solver-core/pom.xml +++ b/javaparser-symbol-solver-core/pom.xml @@ -3,7 +3,7 @@ javaparser-parent com.github.javaparser - 3.25.3 + 3.25.4-SNAPSHOT 4.0.0 diff --git a/javaparser-symbol-solver-testing/pom.xml b/javaparser-symbol-solver-testing/pom.xml index 6f6d327605..2a507b1b9a 100644 --- a/javaparser-symbol-solver-testing/pom.xml +++ b/javaparser-symbol-solver-testing/pom.xml @@ -3,7 +3,7 @@ javaparser-parent com.github.javaparser - 3.25.3 + 3.25.4-SNAPSHOT 4.0.0 diff --git a/pom.xml b/pom.xml index 475dc1f5e0..5a0bdf7551 100644 --- a/pom.xml +++ b/pom.xml @@ -14,7 +14,7 @@ com.github.javaparser javaparser-parent pom - 3.25.3 + 3.25.4-SNAPSHOT javaparser-parent https://github.com/javaparser From c4c7296d87dcdbfd9816439a67b89db26aa85dc9 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Tue, 2 May 2023 08:03:10 +0200 Subject: [PATCH 002/136] Update readme --- readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/readme.md b/readme.md index 95b6776a30..ae326ae271 100644 --- a/readme.md +++ b/readme.md @@ -14,7 +14,7 @@ [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.2667378.svg)](https://doi.org/10.5281/zenodo.2667378) -This project contains a set of libraries implementing a Java 1.0 - Java 15 Parser with advanced analysis functionalities. This includes preview features to Java 13, with Java 14 preview features work-in-progress. +This project contains a set of libraries implementing a Java 1.0 - Java 17 Parser with advanced analysis functionalities. Our main site is at [JavaParser.org](http://javaparser.org) @@ -121,7 +121,7 @@ Make sure that `javaparser-core` at least compiles before you run these. ## More information -#### [JavaParser.org](https://javaparser.org) is the main information site. +#### [JavaParser.org](https://javaparser.org) is the main information site or see the wiki page https://github.com/javaparser/javaparser/wiki. ## License From 4392681e1c4e57364616fea4eb805db685ed4ada Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sat, 6 May 2023 07:37:47 +0000 Subject: [PATCH 003/136] chore(deps): update dependency org.apache.maven.plugins:maven-gpg-plugin to v3.1.0 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 5a0bdf7551..cc0c7f72ad 100644 --- a/pom.xml +++ b/pom.xml @@ -210,7 +210,7 @@ org.apache.maven.plugins maven-gpg-plugin - 3.0.1 + 3.1.0 org.apache.maven.plugins @@ -500,7 +500,7 @@ org.apache.maven.plugins maven-gpg-plugin - 3.0.1 + 3.1.0 sign-artifacts From 8732631bc8731b7ace7a371af7534c8bedb3dcd6 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 10 May 2023 08:39:59 +0000 Subject: [PATCH 004/136] chore(deps): update dependency com.puppycrawl.tools:checkstyle to v10.11.0 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index cc0c7f72ad..936b6c6b88 100644 --- a/pom.xml +++ b/pom.xml @@ -352,7 +352,7 @@ com.puppycrawl.tools checkstyle - 10.10.0 + 10.11.0 From 3e8ee9c4a5e0e6e1325a8da3c81ceeb4356cbee6 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Thu, 11 May 2023 08:08:12 +0000 Subject: [PATCH 005/136] chore(deps): update dependency maven to v3.9.2 --- .mvn/wrapper/maven-wrapper.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties index d8b2495a1e..3c6fda8c6e 100644 --- a/.mvn/wrapper/maven-wrapper.properties +++ b/.mvn/wrapper/maven-wrapper.properties @@ -14,5 +14,5 @@ # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.1/apache-maven-3.9.1-bin.zip +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.2/apache-maven-3.9.2-bin.zip wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar From e37942234d0fe9ad2cc7eb7745e85ce12c68de7a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 11 May 2023 23:56:46 +0000 Subject: [PATCH 006/136] chore(deps): bump build-helper-maven-plugin from 3.3.0 to 3.4.0 Bumps [build-helper-maven-plugin](https://github.com/mojohaus/build-helper-maven-plugin) from 3.3.0 to 3.4.0. - [Release notes](https://github.com/mojohaus/build-helper-maven-plugin/releases) - [Commits](https://github.com/mojohaus/build-helper-maven-plugin/compare/build-helper-maven-plugin-3.3.0...3.4.0) --- updated-dependencies: - dependency-name: org.codehaus.mojo:build-helper-maven-plugin dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 936b6c6b88..5e470a66cb 100644 --- a/pom.xml +++ b/pom.xml @@ -319,7 +319,7 @@ org.codehaus.mojo build-helper-maven-plugin - 3.3.0 + 3.4.0 org.codehaus.mojo From beba13cc730ce0076496567669b18ddf4cb96a7a Mon Sep 17 00:00:00 2001 From: Valery Yatsynovich Date: Fri, 12 May 2023 14:37:01 +0300 Subject: [PATCH 007/136] BDD tests: migarte to JBehave 5 --- javaparser-core-testing-bdd/pom.xml | 8 ++++---- .../test/java/com/github/javaparser/BasicJBehaveTest.java | 4 ++-- .../java/com/github/javaparser/CommentParsingTest.java | 4 ++-- .../test/java/com/github/javaparser/ComparingTest.java | 4 ++-- .../test/java/com/github/javaparser/ManipulationTest.java | 4 ++-- .../src/test/java/com/github/javaparser/ParsingTest.java | 4 ++-- .../java/com/github/javaparser/PositionRangeTest.java | 4 ++-- .../java/com/github/javaparser/PrettyPrintingTest.java | 4 ++-- .../src/test/java/com/github/javaparser/VisitorTest.java | 4 ++-- .../github/javaparser/comment_attribution_scenarios.story | 4 ++-- 10 files changed, 22 insertions(+), 22 deletions(-) diff --git a/javaparser-core-testing-bdd/pom.xml b/javaparser-core-testing-bdd/pom.xml index d87055a56e..a1b76668b5 100644 --- a/javaparser-core-testing-bdd/pom.xml +++ b/javaparser-core-testing-bdd/pom.xml @@ -119,13 +119,13 @@ org.jbehave jbehave-core - 4.8.3 + 5.1.1 test - com.github.valfirst - jbehave-junit-runner - 2.3.2 + org.hamcrest + hamcrest + 2.2 test diff --git a/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/BasicJBehaveTest.java b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/BasicJBehaveTest.java index 73a32da063..eb91df2479 100644 --- a/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/BasicJBehaveTest.java +++ b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/BasicJBehaveTest.java @@ -22,12 +22,12 @@ package com.github.javaparser; -import com.github.valfirst.jbehave.junit.monitoring.JUnitReportingRunner; import org.jbehave.core.configuration.Configuration; import org.jbehave.core.configuration.MostUsefulConfiguration; import org.jbehave.core.failures.FailingUponPendingStep; import org.jbehave.core.io.LoadFromClasspath; import org.jbehave.core.io.StoryFinder; +import org.jbehave.core.junit.JUnit4StoryRunner; import org.jbehave.core.junit.JUnitStories; import org.jbehave.core.reporters.Format; import org.jbehave.core.reporters.StoryReporterBuilder; @@ -42,7 +42,7 @@ abstract class BasicJBehaveTest extends JUnitStories { BasicJBehaveTest(String storiesPath) { this.storiesPath = storiesPath; - JUnitReportingRunner.recommendedControls(configuredEmbedder()); + JUnit4StoryRunner.recommendedControls(configuredEmbedder()); } @Override diff --git a/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/CommentParsingTest.java b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/CommentParsingTest.java index 737f56e57f..9a1a54b3e7 100644 --- a/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/CommentParsingTest.java +++ b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/CommentParsingTest.java @@ -22,12 +22,12 @@ package com.github.javaparser; import com.github.javaparser.steps.CommentParsingSteps; -import com.github.valfirst.jbehave.junit.monitoring.JUnitReportingRunner; +import org.jbehave.core.junit.JUnit4StoryRunner; import org.jbehave.core.steps.InjectableStepsFactory; import org.jbehave.core.steps.InstanceStepsFactory; import org.junit.runner.RunWith; -@RunWith(JUnitReportingRunner.class) +@RunWith(JUnit4StoryRunner.class) public class CommentParsingTest extends BasicJBehaveTest { @Override diff --git a/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/ComparingTest.java b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/ComparingTest.java index 37d4f83cf0..49b9067a3c 100644 --- a/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/ComparingTest.java +++ b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/ComparingTest.java @@ -23,7 +23,7 @@ import com.github.javaparser.steps.ComparingSteps; import com.github.javaparser.steps.SharedSteps; -import com.github.valfirst.jbehave.junit.monitoring.JUnitReportingRunner; +import org.jbehave.core.junit.JUnit4StoryRunner; import org.jbehave.core.steps.InjectableStepsFactory; import org.jbehave.core.steps.InstanceStepsFactory; import org.junit.runner.RunWith; @@ -31,7 +31,7 @@ import java.util.HashMap; import java.util.Map; -@RunWith(JUnitReportingRunner.class) +@RunWith(JUnit4StoryRunner.class) public class ComparingTest extends BasicJBehaveTest { @Override diff --git a/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/ManipulationTest.java b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/ManipulationTest.java index 7d00606718..b9637fa05d 100644 --- a/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/ManipulationTest.java +++ b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/ManipulationTest.java @@ -23,7 +23,7 @@ import com.github.javaparser.steps.ManipulationSteps; import com.github.javaparser.steps.SharedSteps; -import com.github.valfirst.jbehave.junit.monitoring.JUnitReportingRunner; +import org.jbehave.core.junit.JUnit4StoryRunner; import org.jbehave.core.steps.InjectableStepsFactory; import org.jbehave.core.steps.InstanceStepsFactory; import org.junit.runner.RunWith; @@ -31,7 +31,7 @@ import java.util.HashMap; import java.util.Map; -@RunWith(JUnitReportingRunner.class) +@RunWith(JUnit4StoryRunner.class) public class ManipulationTest extends BasicJBehaveTest { @Override diff --git a/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/ParsingTest.java b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/ParsingTest.java index 044c9fd93d..6cd778dc49 100644 --- a/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/ParsingTest.java +++ b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/ParsingTest.java @@ -23,7 +23,7 @@ import com.github.javaparser.steps.ParsingSteps; import com.github.javaparser.steps.SharedSteps; -import com.github.valfirst.jbehave.junit.monitoring.JUnitReportingRunner; +import org.jbehave.core.junit.JUnit4StoryRunner; import org.jbehave.core.steps.InjectableStepsFactory; import org.jbehave.core.steps.InstanceStepsFactory; import org.junit.runner.RunWith; @@ -31,7 +31,7 @@ import java.util.HashMap; import java.util.Map; -@RunWith(JUnitReportingRunner.class) +@RunWith(JUnit4StoryRunner.class) public class ParsingTest extends BasicJBehaveTest { @Override diff --git a/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/PositionRangeTest.java b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/PositionRangeTest.java index 32753e6f4e..abd183069d 100644 --- a/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/PositionRangeTest.java +++ b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/PositionRangeTest.java @@ -23,7 +23,7 @@ import com.github.javaparser.steps.PositionRangeSteps; import com.github.javaparser.steps.SharedSteps; -import com.github.valfirst.jbehave.junit.monitoring.JUnitReportingRunner; +import org.jbehave.core.junit.JUnit4StoryRunner; import org.jbehave.core.steps.InjectableStepsFactory; import org.jbehave.core.steps.InstanceStepsFactory; import org.junit.runner.RunWith; @@ -31,7 +31,7 @@ import java.util.HashMap; import java.util.Map; -@RunWith(JUnitReportingRunner.class) +@RunWith(JUnit4StoryRunner.class) public class PositionRangeTest extends BasicJBehaveTest { @Override diff --git a/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/PrettyPrintingTest.java b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/PrettyPrintingTest.java index 2968185abe..a2e9101d12 100644 --- a/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/PrettyPrintingTest.java +++ b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/PrettyPrintingTest.java @@ -22,12 +22,12 @@ package com.github.javaparser; import com.github.javaparser.steps.PrettyPrintingSteps; -import com.github.valfirst.jbehave.junit.monitoring.JUnitReportingRunner; +import org.jbehave.core.junit.JUnit4StoryRunner; import org.jbehave.core.steps.InjectableStepsFactory; import org.jbehave.core.steps.InstanceStepsFactory; import org.junit.runner.RunWith; -@RunWith(JUnitReportingRunner.class) +@RunWith(JUnit4StoryRunner.class) public class PrettyPrintingTest extends BasicJBehaveTest { @Override diff --git a/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/VisitorTest.java b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/VisitorTest.java index aee1441f6e..6d3c03887e 100644 --- a/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/VisitorTest.java +++ b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/VisitorTest.java @@ -23,7 +23,7 @@ import com.github.javaparser.steps.SharedSteps; import com.github.javaparser.steps.VisitorSteps; -import com.github.valfirst.jbehave.junit.monitoring.JUnitReportingRunner; +import org.jbehave.core.junit.JUnit4StoryRunner; import org.jbehave.core.steps.InjectableStepsFactory; import org.jbehave.core.steps.InstanceStepsFactory; import org.junit.runner.RunWith; @@ -31,7 +31,7 @@ import java.util.HashMap; import java.util.Map; -@RunWith(JUnitReportingRunner.class) +@RunWith(JUnit4StoryRunner.class) public class VisitorTest extends BasicJBehaveTest { @Override diff --git a/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/comment_attribution_scenarios.story b/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/comment_attribution_scenarios.story index a55d6af5fe..c3724cedea 100644 --- a/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/comment_attribution_scenarios.story +++ b/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/comment_attribution_scenarios.story @@ -158,7 +158,7 @@ Then class 1 has 4 total contained comments Then class 1 has 1 orphan comment Then class 1 orphan comment 1 is "Case 1" Then field 1 in class 1 contains 0 comments -!--Then field 2 in class 1 contains 0 comments +!-- Then field 2 in class 1 contains 0 comments Then field 1 in class 1 is commented "field1" Then field 2 in class 1 is commented "Case 2" Then variable 1 value of field 2 in class 1 is commented "field2" @@ -180,7 +180,7 @@ When the class is parsed by the Java parser Then the compilation unit has 2 contained comments Then class 1 has 2 total contained comments Then field 1 in class 1 contains 0 comments -!--Then field 2 in class 1 contains 0 comments +!-- Then field 2 in class 1 contains 0 comments Then field 1 in class 1 is commented "field1" Then variable 1 value of field 2 in class 1 is commented "field2" From 976dff84a8f44ef28c39f50168acf0d993b5c121 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 15 May 2023 23:56:51 +0000 Subject: [PATCH 008/136] chore(deps): bump codecov/codecov-action from 3.1.3 to 3.1.4 Bumps [codecov/codecov-action](https://github.com/codecov/codecov-action) from 3.1.3 to 3.1.4. - [Release notes](https://github.com/codecov/codecov-action/releases) - [Changelog](https://github.com/codecov/codecov-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/codecov/codecov-action/compare/v3.1.3...v3.1.4) --- updated-dependencies: - dependency-name: codecov/codecov-action dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .github/workflows/maven_tests.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/maven_tests.yml b/.github/workflows/maven_tests.yml index 063520079a..902722e951 100644 --- a/.github/workflows/maven_tests.yml +++ b/.github/workflows/maven_tests.yml @@ -84,7 +84,7 @@ jobs: - name: CodeCov - JavaParser Core - uses: codecov/codecov-action@v3.1.3 + uses: codecov/codecov-action@v3.1.4 timeout-minutes: 10 with: files: javaparser-core-testing/target/site/jacoco/jacoco.xml,javaparser-core-testing-bdd/target/site/jacoco/jacoco.xml @@ -94,7 +94,7 @@ jobs: env_vars: OS,JDK - name: CodeCov - JavaParser Symbol Solver - uses: codecov/codecov-action@v3.1.3 + uses: codecov/codecov-action@v3.1.4 timeout-minutes: 10 with: file: javaparser-symbol-solver-testing/target/site/jacoco/jacoco.xml From 52903b96f6ae9845cf89bd22c2f9d3216a9ecc6b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 18 May 2023 23:56:52 +0000 Subject: [PATCH 009/136] chore(deps): bump maven-scm-plugin from 2.0.0 to 2.0.1 Bumps [maven-scm-plugin](https://github.com/apache/maven-scm) from 2.0.0 to 2.0.1. - [Commits](https://github.com/apache/maven-scm/compare/maven-scm-2.0.0...maven-scm-2.0.1) --- updated-dependencies: - dependency-name: org.apache.maven.plugins:maven-scm-plugin dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 5e470a66cb..f3d82fbd5e 100644 --- a/pom.xml +++ b/pom.xml @@ -248,7 +248,7 @@ org.apache.maven.plugins maven-scm-plugin - 2.0.0 + 2.0.1 org.apache.maven.plugins From 8d76ec7db5c791fb7e74536c0f70208eaf2f877c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 22 May 2023 23:56:47 +0000 Subject: [PATCH 010/136] chore(deps): bump maven-checkstyle-plugin from 3.2.2 to 3.3.0 Bumps [maven-checkstyle-plugin](https://github.com/apache/maven-checkstyle-plugin) from 3.2.2 to 3.3.0. - [Commits](https://github.com/apache/maven-checkstyle-plugin/compare/maven-checkstyle-plugin-3.2.2...maven-checkstyle-plugin-3.3.0) --- updated-dependencies: - dependency-name: org.apache.maven.plugins:maven-checkstyle-plugin dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index f3d82fbd5e..50038e8bda 100644 --- a/pom.xml +++ b/pom.xml @@ -342,7 +342,7 @@ org.apache.maven.plugins maven-checkstyle-plugin - 3.2.2 + 3.3.0 dev-files/JavaParser-CheckStyle.xml true From 3285a04f0405777f9c60cf1a4b34159ac0e005c5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 22 May 2023 23:56:52 +0000 Subject: [PATCH 011/136] chore(deps): bump maven-source-plugin from 3.2.1 to 3.3.0 Bumps [maven-source-plugin](https://github.com/apache/maven-source-plugin) from 3.2.1 to 3.3.0. - [Commits](https://github.com/apache/maven-source-plugin/compare/maven-source-plugin-3.2.1...maven-source-plugin-3.3.0) --- updated-dependencies: - dependency-name: org.apache.maven.plugins:maven-source-plugin dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index f3d82fbd5e..f15d7a588a 100644 --- a/pom.xml +++ b/pom.xml @@ -253,7 +253,7 @@ org.apache.maven.plugins maven-source-plugin - 3.2.1 + 3.3.0 org.eluder.coveralls From af2d81a08e82c502c22a26f7e5ffb85f5cb48fb0 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 23 May 2023 23:56:48 +0000 Subject: [PATCH 012/136] chore(deps): bump maven-dependency-plugin from 3.5.0 to 3.6.0 Bumps [maven-dependency-plugin](https://github.com/apache/maven-dependency-plugin) from 3.5.0 to 3.6.0. - [Commits](https://github.com/apache/maven-dependency-plugin/compare/maven-dependency-plugin-3.5.0...maven-dependency-plugin-3.6.0) --- updated-dependencies: - dependency-name: org.apache.maven.plugins:maven-dependency-plugin dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 992d404c7d..29a2d42be2 100644 --- a/pom.xml +++ b/pom.xml @@ -329,7 +329,7 @@ org.apache.maven.plugins maven-dependency-plugin - 3.5.0 + 3.6.0 org.codehaus.mojo From 4e14ef5b270647ce745c4613d76b6651c080e149 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Thu, 25 May 2023 10:00:45 +0200 Subject: [PATCH 013/136] Fix: issue 4016 Failed to parse variable with name 'sealed' or 'permits' --- .../body/ClassOrInterfaceDeclarationTest.java | 48 ++++++++++++++++--- .../Java17Validator.java | 8 ++++ javaparser-core/src/main/javacc/java.jj | 2 +- 3 files changed, 50 insertions(+), 8 deletions(-) diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/ClassOrInterfaceDeclarationTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/ClassOrInterfaceDeclarationTest.java index a1bed1c52a..89da70cefb 100644 --- a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/ClassOrInterfaceDeclarationTest.java +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/ClassOrInterfaceDeclarationTest.java @@ -21,17 +21,19 @@ package com.github.javaparser.ast.body; +import static com.github.javaparser.StaticJavaParser.parse; +import static com.github.javaparser.StaticJavaParser.parseBodyDeclaration; +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.opentest4j.AssertionFailedError; + import com.github.javaparser.ParserConfiguration; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.Modifier; import com.github.javaparser.utils.TestParser; -import org.junit.jupiter.api.Test; - -import static com.github.javaparser.StaticJavaParser.parse; -import static com.github.javaparser.StaticJavaParser.parseBodyDeclaration; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; class ClassOrInterfaceDeclarationTest { @Test @@ -109,4 +111,36 @@ void nonSealedClass() { assertTrue(x.hasModifier(Modifier.Keyword.NON_SEALED)); } + @ParameterizedTest + @EnumSource(value = ParserConfiguration.LanguageLevel.class, names = {"JAVA_8","JAVA_9","JAVA_10","JAVA_11","JAVA_12","JAVA_13","JAVA_14", "JAVA_15", "JAVA_16"}) + void sealedFieldNamePermitted(ParserConfiguration.LanguageLevel languageLevel) { + assertDoesNotThrow(() -> { + TestParser.parseVariableDeclarationExpr(languageLevel, "boolean sealed"); + }); + } + + @ParameterizedTest + @EnumSource(value = ParserConfiguration.LanguageLevel.class, names = {"JAVA_17"}) + void sealedFieldNameNotPermitted(ParserConfiguration.LanguageLevel languageLevel) { + assertThrows(AssertionFailedError.class, () -> { + TestParser.parseVariableDeclarationExpr(languageLevel, "boolean sealed"); + }); + } + + @ParameterizedTest + @EnumSource(value = ParserConfiguration.LanguageLevel.class, names = {"JAVA_8","JAVA_9","JAVA_10","JAVA_11","JAVA_12","JAVA_13","JAVA_14", "JAVA_15", "JAVA_16"}) + void permitsFieldNamePermitted(ParserConfiguration.LanguageLevel languageLevel) { + assertDoesNotThrow(() -> { + TestParser.parseVariableDeclarationExpr(languageLevel, "boolean permits"); + }); + } + + @ParameterizedTest + @EnumSource(value = ParserConfiguration.LanguageLevel.class, names = {"JAVA_17"}) + void permitsFieldNameNotPermitted(ParserConfiguration.LanguageLevel languageLevel) { + assertThrows(AssertionFailedError.class, () -> { + TestParser.parseVariableDeclarationExpr(languageLevel, "boolean permits"); + }); + } + } diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java17Validator.java b/javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java17Validator.java index 256d49c1dc..f131ed3b11 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java17Validator.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java17Validator.java @@ -20,6 +20,9 @@ */ package com.github.javaparser.ast.validator.language_level_validations; +import com.github.javaparser.ast.validator.ReservedKeywordValidator; +import com.github.javaparser.ast.validator.Validator; + /** * This validator validates according to Java 17 syntax rules. * @@ -27,10 +30,15 @@ */ public class Java17Validator extends Java16Validator { + final Validator sealedNotAllowedAsIdentifier = new ReservedKeywordValidator("sealed"); + final Validator permitsNotAllowedAsIdentifier = new ReservedKeywordValidator("permits"); + public Java17Validator() { super(); // Released Language Features // Sealed Classes - https://openjdk.java.net/jeps/409 + add(sealedNotAllowedAsIdentifier); + add(permitsNotAllowedAsIdentifier); remove(noSealedClasses); remove(noPermitsListInClasses); } diff --git a/javaparser-core/src/main/javacc/java.jj b/javaparser-core/src/main/javacc/java.jj index cbde7422ba..c224875129 100644 --- a/javaparser-core/src/main/javacc/java.jj +++ b/javaparser-core/src/main/javacc/java.jj @@ -2984,7 +2984,7 @@ String Identifier(): // Make sure the module info keywords don't interfere with normal Java parsing by matching them as normal identifiers. | | | | | | | | | | // Make sure older Java versions parse - | | | | + | | | | | | // An actual plain old identifier ) { ret = token.image; setTokenKind(IDENTIFIER);} From ddc72f3674d50a4feb456ba48ea301145ffeb782 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Thu, 25 May 2023 10:24:53 +0200 Subject: [PATCH 014/136] Fix errors in unit tests whose assertions are based on the error message generated by the parser --- .../com/github/javaparser/JavaParserTest.java | 33 ++++++++++--------- .../javaparser/ast/ParseResultTest.java | 15 +++++---- 2 files changed, 25 insertions(+), 23 deletions(-) diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/JavaParserTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/JavaParserTest.java index 7c43f42436..0d7fc9fb97 100644 --- a/javaparser-core-testing/src/test/java/com/github/javaparser/JavaParserTest.java +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/JavaParserTest.java @@ -21,6 +21,22 @@ package com.github.javaparser; +import static com.github.javaparser.ParseStart.COMPILATION_UNIT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.BLEEDING_EDGE; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.CURRENT; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.Range.range; +import static com.github.javaparser.StaticJavaParser.*; +import static com.github.javaparser.utils.TestUtils.assertInstanceOf; +import static com.github.javaparser.utils.Utils.SYSTEM_EOL; +import static org.junit.jupiter.api.Assertions.*; + +import java.util.Optional; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.NodeList; import com.github.javaparser.ast.body.AnnotationMemberDeclaration; @@ -34,21 +50,6 @@ import com.github.javaparser.ast.type.IntersectionType; import com.github.javaparser.ast.type.Type; import com.github.javaparser.printer.YamlPrinter; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.util.Optional; - -import static com.github.javaparser.ParseStart.COMPILATION_UNIT; -import static com.github.javaparser.ParserConfiguration.LanguageLevel.BLEEDING_EDGE; -import static com.github.javaparser.ParserConfiguration.LanguageLevel.CURRENT; -import static com.github.javaparser.Providers.provider; -import static com.github.javaparser.Range.range; -import static com.github.javaparser.StaticJavaParser.*; -import static com.github.javaparser.utils.TestUtils.assertInstanceOf; -import static com.github.javaparser.utils.Utils.SYSTEM_EOL; -import static org.junit.jupiter.api.Assertions.*; class JavaParserTest { @@ -142,7 +143,7 @@ void parseErrorContainsLocation() { Problem problem = result.getProblem(0); assertEquals(range(1, 9, 1, 17), problem.getLocation().get().toRange().get()); - assertEquals("Parse error. Found , expected one of \";\" \"<\" \"@\" \"abstract\" \"boolean\" \"byte\" \"char\" \"class\" \"default\" \"double\" \"enum\" \"exports\" \"final\" \"float\" \"int\" \"interface\" \"long\" \"module\" \"native\" \"non-sealed\" \"open\" \"opens\" \"private\" \"protected\" \"provides\" \"public\" \"record\" \"requires\" \"sealed\" \"short\" \"static\" \"strictfp\" \"synchronized\" \"to\" \"transient\" \"transitive\" \"uses\" \"void\" \"volatile\" \"with\" \"yield\" \"{\" \"}\" ", problem.getMessage()); + assertEquals("Parse error. Found , expected one of \";\" \"<\" \"@\" \"abstract\" \"boolean\" \"byte\" \"char\" \"class\" \"default\" \"double\" \"enum\" \"exports\" \"final\" \"float\" \"int\" \"interface\" \"long\" \"module\" \"native\" \"non-sealed\" \"open\" \"opens\" \"permits\" \"private\" \"protected\" \"provides\" \"public\" \"record\" \"requires\" \"sealed\" \"short\" \"static\" \"strictfp\" \"synchronized\" \"to\" \"transient\" \"transitive\" \"uses\" \"void\" \"volatile\" \"with\" \"yield\" \"{\" \"}\" ", problem.getMessage()); assertInstanceOf(ParseException.class, problem.getCause().get()); } diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/ParseResultTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/ParseResultTest.java index c6f2e309bf..ebc08dae01 100644 --- a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/ParseResultTest.java +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/ParseResultTest.java @@ -21,12 +21,6 @@ package com.github.javaparser.ast; -import com.github.javaparser.JavaParser; -import com.github.javaparser.ParseResult; -import com.github.javaparser.ParserConfiguration; -import com.github.javaparser.Problem; -import org.junit.jupiter.api.Test; - import static com.github.javaparser.ParseStart.COMPILATION_UNIT; import static com.github.javaparser.Providers.provider; import static com.github.javaparser.ast.Node.Parsedness.PARSED; @@ -34,6 +28,13 @@ import static com.github.javaparser.utils.Utils.SYSTEM_EOL; import static org.assertj.core.api.Assertions.assertThat; +import org.junit.jupiter.api.Test; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.Problem; + class ParseResultTest { private final JavaParser javaParser = new JavaParser(new ParserConfiguration()); @@ -57,7 +58,7 @@ void whenParsingFailsThenWeGetProblemsAndABadResult() { assertThat(result.getProblems().size()).isEqualTo(1); Problem problem = result.getProblem(0); - assertThat(problem.getMessage()).isEqualTo("Parse error. Found \"{\", expected one of \"enum\" \"exports\" \"module\" \"open\" \"opens\" \"provides\" \"record\" \"requires\" \"strictfp\" \"to\" \"transitive\" \"uses\" \"with\" \"yield\" "); + assertThat(problem.getMessage()).isEqualTo("Parse error. Found \"{\", expected one of \"enum\" \"exports\" \"module\" \"open\" \"opens\" \"permits\" \"provides\" \"record\" \"requires\" \"sealed\" \"strictfp\" \"to\" \"transitive\" \"uses\" \"with\" \"yield\" "); assertThat(result.toString()).startsWith("Parsing failed:" + SYSTEM_EOL + "(line 1,col 1) Parse error."); } From 78b4e5695398502f320c68240b8cb8d9fe06e18e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 26 May 2023 23:57:45 +0000 Subject: [PATCH 015/136] chore(deps): bump guava from 31.1-jre to 32.0.0-jre Bumps [guava](https://github.com/google/guava) from 31.1-jre to 32.0.0-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production ... Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 29a2d42be2..ad8ef00f66 100644 --- a/pom.xml +++ b/pom.xml @@ -371,7 +371,7 @@ com.google.guava guava - 31.1-jre + 32.0.0-jre junit From 12b25233dfe3395abfd8270e6c2c62fee7ae8580 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sun, 28 May 2023 11:34:47 +0000 Subject: [PATCH 016/136] chore(deps): update dependency com.puppycrawl.tools:checkstyle to v10.12.0 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index ad8ef00f66..4a7da395ba 100644 --- a/pom.xml +++ b/pom.xml @@ -352,7 +352,7 @@ com.puppycrawl.tools checkstyle - 10.11.0 + 10.12.0 From fa02315cb4ed3c46280f39755cb735c803063890 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Sun, 28 May 2023 23:40:11 +0200 Subject: [PATCH 017/136] Add PR 'add Java 17 sealed/non-sealed classes' in changelog --- changelog.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/changelog.md b/changelog.md index 701343bd05..43d280e121 100644 --- a/changelog.md +++ b/changelog.md @@ -15,6 +15,11 @@ Version 3.25.3 -------------- [issues resolved](https://github.com/javaparser/javaparser/milestone/199?closed=1) + +### Added + +* add Java 17 sealed/non-sealed classes (PR [#3997](https://github.com/javaparser/javaparser/pull/3997) by [@kris-scheibe](https://github.com/kris-scheibe)) + ### Changed * Minor simplification of the Difference class (PR [#4008](https://github.com/javaparser/javaparser/pull/4008) by [@jlerbsc](https://github.com/jlerbsc)) From 60b600e72b70c63d18a06a265ebc6212c046aabb Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Tue, 30 May 2023 16:52:21 +0200 Subject: [PATCH 018/136] Fix: issue 4037 ArrayIndexOutOfBoundsException throws when method param is variadic --- .../javaparsermodel/TypeExtractor.java | 9 ++++++++- .../contexts/MethodReferenceExprContext.java | 16 +++++++++++----- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/TypeExtractor.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/TypeExtractor.java index 9a999dc0fc..6689cb276e 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/TypeExtractor.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/TypeExtractor.java @@ -635,7 +635,14 @@ public ResolvedType visit(MethodReferenceExpr node, Boolean solveLambdas) { return result; } - return refMethod.getCorrespondingDeclaration().getParam(pos).getType(); + // Since variable parameters are represented by an array, in case we deal with + // the variadic parameter we have to take into account the base type of the + // array. + ResolvedMethodDeclaration rmd = refMethod.getCorrespondingDeclaration(); + if (rmd.hasVariadicParameter() && pos >= rmd.getNumberOfParams() - 1) { + return rmd.getLastParam().getType().asArrayType().getComponentType(); + } + return rmd.getParam(pos).getType(); } throw new UnsupportedOperationException("The type of a method reference expr depends on the position and its return value"); } diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/MethodReferenceExprContext.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/MethodReferenceExprContext.java index b2d81b3a6a..dad80fd1bb 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/MethodReferenceExprContext.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/MethodReferenceExprContext.java @@ -21,6 +21,10 @@ package com.github.javaparser.symbolsolver.javaparsermodel.contexts; +import static com.github.javaparser.resolution.Navigator.demandParentNode; + +import java.util.*; + import com.github.javaparser.ast.body.MethodDeclaration; import com.github.javaparser.ast.body.VariableDeclarator; import com.github.javaparser.ast.expr.Expression; @@ -41,10 +45,6 @@ import com.github.javaparser.resolution.types.ResolvedType; import com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade; -import java.util.*; - -import static com.github.javaparser.resolution.Navigator.demandParentNode; - public class MethodReferenceExprContext extends AbstractJavaParserContext { /// @@ -103,7 +103,13 @@ private List inferArgumentTypes() { MethodCallExpr methodCallExpr = (MethodCallExpr) demandParentNode(wrappedNode); MethodUsage methodUsage = JavaParserFacade.get(typeSolver).solveMethodAsUsage(methodCallExpr); int pos = pos(methodCallExpr, wrappedNode); - ResolvedType lambdaType = methodUsage.getParamTypes().get(pos); + ResolvedMethodDeclaration rmd = methodUsage.getDeclaration(); + // Since variable parameters are represented by an array, in case we deal with + // the variadic parameter we have to take into account the base type of the + // array. + ResolvedType lambdaType = (rmd.hasVariadicParameter() && pos >= rmd.getNumberOfParams() - 1) ? + rmd.getLastParam().getType().asArrayType().getComponentType(): + methodUsage.getParamType(pos); // Get the functional method in order for us to resolve it's type arguments properly Optional functionalMethodOpt = FunctionalInterfaceLogic.getFunctionalMethod(lambdaType); From e7e7751b28ad8df1ee30689eb15dfc0d63ecb25e Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Tue, 30 May 2023 17:01:39 +0200 Subject: [PATCH 019/136] Add a unit test --- .../symbolsolver/Issue4037Test.java | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100755 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue4037Test.java diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue4037Test.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue4037Test.java new file mode 100755 index 0000000000..338a85d2fb --- /dev/null +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue4037Test.java @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2013-2023 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.symbolsolver; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import java.util.List; + +import org.junit.jupiter.api.Test; + +import com.github.javaparser.JavaParserAdapter; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.expr.MethodReferenceExpr; +import com.github.javaparser.symbolsolver.resolution.AbstractResolutionTest; + +public class Issue4037Test extends AbstractResolutionTest { + + @Test + void test() { + + String code = + "public class Test1 {\n" + + " public static Integer getD2() { return null; }\n" + + " public static Integer getD1() { return null; }\n" + + " public void m(java.util.function.Supplier... rs) { }\n" + + "\n" + + " public void test() {\n" + + " new Test1().m(Test1::getD1, Test1::getD2); // exception throws\n" + + " }\n" + + " }"; + + JavaParserAdapter parser = JavaParserAdapter.of(createParserWithResolver(defaultTypeSolver())); + CompilationUnit cu = parser.parse(code); + + List exprs = cu.findAll(MethodReferenceExpr .class); + + exprs.forEach(expr -> { + assertDoesNotThrow(() -> expr.resolve()); + }); + } +} From c09efcfc5937ff33058e0a3f674422e774068785 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Tue, 30 May 2023 18:52:35 +0200 Subject: [PATCH 020/136] Add unrelated commit to unlock PR validation --- .../github/javaparser/symbolsolver/JavaSymbolSolver.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/JavaSymbolSolver.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/JavaSymbolSolver.java index 7130e10807..95598959db 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/JavaSymbolSolver.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/JavaSymbolSolver.java @@ -21,6 +21,8 @@ package com.github.javaparser.symbolsolver; +import static com.github.javaparser.resolution.Navigator.demandParentNode; + import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.Node; import com.github.javaparser.ast.body.*; @@ -39,8 +41,6 @@ import com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade; import com.github.javaparser.symbolsolver.javaparsermodel.declarations.*; -import static com.github.javaparser.resolution.Navigator.demandParentNode; - /** * This implementation of the SymbolResolver wraps the functionality of the library to make them easily usable * from JavaParser nodes. @@ -293,7 +293,7 @@ public T toResolvedType(Type javaparserType, Class resultClass) { public ResolvedType calculateType(Expression expression) { return JavaParserFacade.get(typeSolver).getType(expression); } - + @Override public ResolvedReferenceTypeDeclaration toTypeDeclaration(Node node) { if (node instanceof ClassOrInterfaceDeclaration) { @@ -312,7 +312,7 @@ public ResolvedReferenceTypeDeclaration toTypeDeclaration(Node node) { return new JavaParserAnnotationDeclaration((AnnotationDeclaration) node, typeSolver); } if (node instanceof EnumConstantDeclaration) { - return new JavaParserEnumDeclaration((EnumDeclaration) demandParentNode((EnumConstantDeclaration) node), typeSolver); + return new JavaParserEnumDeclaration((EnumDeclaration) demandParentNode(node), typeSolver); } throw new IllegalArgumentException("Cannot get a reference type declaration from " + node.getClass().getCanonicalName()); } From 5a87afffb98f9366f8575e5135c93322fac9a604 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 6 Jun 2023 23:56:50 +0000 Subject: [PATCH 021/136] chore(deps): bump versions-maven-plugin from 2.15.0 to 2.16.0 Bumps [versions-maven-plugin](https://github.com/mojohaus/versions) from 2.15.0 to 2.16.0. - [Release notes](https://github.com/mojohaus/versions/releases) - [Changelog](https://github.com/mojohaus/versions/blob/master/ReleaseNotes.md) - [Commits](https://github.com/mojohaus/versions/compare/2.15.0...2.16.0) --- updated-dependencies: - dependency-name: org.codehaus.mojo:versions-maven-plugin dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 4a7da395ba..c5b9459000 100644 --- a/pom.xml +++ b/pom.xml @@ -334,7 +334,7 @@ org.codehaus.mojo versions-maven-plugin - 2.15.0 + 2.16.0 false From 3e192b41989243d3d8654b48306120a0010f45e8 Mon Sep 17 00:00:00 2001 From: Marc Etter Date: Wed, 7 Jun 2023 19:19:32 +0200 Subject: [PATCH 022/136] Fix #4056 --- .../ast/body/FieldDeclarationTest.java | 30 +++++++++++++++++-- .../javaparser/ast/body/FieldDeclaration.java | 8 +++-- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/FieldDeclarationTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/FieldDeclarationTest.java index d2c2369ca8..6137d4425a 100644 --- a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/FieldDeclarationTest.java +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/FieldDeclarationTest.java @@ -21,6 +21,7 @@ package com.github.javaparser.ast.body; +import com.github.javaparser.StaticJavaParser; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.Modifier; import com.github.javaparser.ast.Modifier.Keyword; @@ -30,8 +31,9 @@ import static com.github.javaparser.StaticJavaParser.parse; import static com.github.javaparser.StaticJavaParser.parseBodyDeclaration; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasSize; +import static org.junit.jupiter.api.Assertions.*; class FieldDeclarationTest { @Test @@ -100,4 +102,28 @@ void interfaceFieldTest() { } } + /** + * Regression test for issue #4056. + */ + @Test + void testEnumWithPrivateFieldInsideInterface() { + String source = "interface Outer {\n" + + " enum Numbers {\n" + + " ONE(1),\n" + + " TWO(2),\n" + + " THREE(3);\n" + + "\n" + + " Numbers(int i) {\n" + + " this.i = i;\n" + + " }\n" + + "\n" + + " private int i;\n" + + " }\n" + + "}"; + CompilationUnit cu = StaticJavaParser.parse(source); + FieldDeclaration i = cu.getTypes().get(0).asClassOrInterfaceDeclaration() + .getMembers().get(0).asEnumDeclaration() + .getFields().get(0); + assertFalse(i.isPublic()); + } } diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/body/FieldDeclaration.java b/javaparser-core/src/main/java/com/github/javaparser/ast/body/FieldDeclaration.java index 3c7cf1c49c..31b583b350 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/body/FieldDeclaration.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/body/FieldDeclaration.java @@ -267,8 +267,12 @@ public boolean isPublic() { * Returns true if the field is declared in an interface */ private boolean isDeclaredInInterface() { - Optional parentClass = findAncestor(ClassOrInterfaceDeclaration.class); - return parentClass.map(parent -> parent.isInterface()).orElse(false); + Optional parentType = findAncestor(TypeDeclaration.class); + return parentType + .filter(BodyDeclaration::isClassOrInterfaceDeclaration) + .map(BodyDeclaration::asClassOrInterfaceDeclaration) + .map(ClassOrInterfaceDeclaration::isInterface) + .orElse(false); } @Override From 49933b4507be197dc1562656389381e2a77c78d4 Mon Sep 17 00:00:00 2001 From: Marc Etter Date: Wed, 7 Jun 2023 19:30:38 +0200 Subject: [PATCH 023/136] add assertions for isStatic() and isFinal() --- .../github/javaparser/ast/body/FieldDeclarationTest.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/FieldDeclarationTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/FieldDeclarationTest.java index 6137d4425a..96e9d8e63f 100644 --- a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/FieldDeclarationTest.java +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/FieldDeclarationTest.java @@ -31,8 +31,6 @@ import static com.github.javaparser.StaticJavaParser.parse; import static com.github.javaparser.StaticJavaParser.parseBodyDeclaration; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasSize; import static org.junit.jupiter.api.Assertions.*; class FieldDeclarationTest { @@ -124,6 +122,10 @@ void testEnumWithPrivateFieldInsideInterface() { FieldDeclaration i = cu.getTypes().get(0).asClassOrInterfaceDeclaration() .getMembers().get(0).asEnumDeclaration() .getFields().get(0); - assertFalse(i.isPublic()); + assertAll( + () -> assertFalse(i.isPublic()), + () -> assertFalse(i.isStatic()), + () -> assertFalse(i.isFinal()) + ); } } From 715d318ae45623c813cc24fb788a2bcb3abccdf6 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 9 Jun 2023 15:09:36 +0000 Subject: [PATCH 024/136] chore(deps): update actions/checkout action to v3.5.3 --- .github/workflows/create_github_release.yml | 2 +- .github/workflows/maven_tests.yml | 4 ++-- .github/workflows/prepare_release_changelog.yml | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/create_github_release.yml b/.github/workflows/create_github_release.yml index a7a531948d..0f4d2b94ad 100644 --- a/.github/workflows/create_github_release.yml +++ b/.github/workflows/create_github_release.yml @@ -13,7 +13,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout code - uses: actions/checkout@v3.5.2 + uses: actions/checkout@v3.5.3 - name: Create Release id: create_release diff --git a/.github/workflows/maven_tests.yml b/.github/workflows/maven_tests.yml index 902722e951..15d6aecb86 100644 --- a/.github/workflows/maven_tests.yml +++ b/.github/workflows/maven_tests.yml @@ -45,7 +45,7 @@ jobs: steps: ## Checkout the current version of the code from the repo. - name: Checkout latest code - uses: actions/checkout@v3.5.2 + uses: actions/checkout@v3.5.3 with: fetch-depth: "0" @@ -109,7 +109,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout latest code - uses: actions/checkout@v3.5.2 + uses: actions/checkout@v3.5.3 with: fetch-depth: "0" - name: Set up JDK 11 diff --git a/.github/workflows/prepare_release_changelog.yml b/.github/workflows/prepare_release_changelog.yml index 03da6ca7ab..4dcdc0fd46 100644 --- a/.github/workflows/prepare_release_changelog.yml +++ b/.github/workflows/prepare_release_changelog.yml @@ -15,7 +15,7 @@ jobs: # Check out current repository - name: Fetch Sources - uses: actions/checkout@v3.5.2 + uses: actions/checkout@v3.5.3 # Setup Java 11 environment for the next steps - name: Setup Java From 0c170348b913833cee180832177d29479887305a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 13 Jun 2023 13:17:44 +0000 Subject: [PATCH 025/136] chore(deps): bump maven-release-plugin from 3.0.0 to 3.0.1 Bumps [maven-release-plugin](https://github.com/apache/maven-release) from 3.0.0 to 3.0.1. - [Release notes](https://github.com/apache/maven-release/releases) - [Commits](https://github.com/apache/maven-release/compare/maven-release-3.0.0...maven-release-3.0.1) --- updated-dependencies: - dependency-name: org.apache.maven.plugins:maven-release-plugin dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index c5b9459000..fdb7183735 100644 --- a/pom.xml +++ b/pom.xml @@ -228,7 +228,7 @@ org.apache.maven.plugins maven-release-plugin - 3.0.0 + 3.0.1 true From f72f9ae846012e86578906fd064f0422153dc06d Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 13 Jun 2023 15:25:37 +0000 Subject: [PATCH 026/136] chore(deps): update dependency org.apache.maven.plugins:maven-surefire-plugin to v3.1.2 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index fdb7183735..faf6cd9d08 100644 --- a/pom.xml +++ b/pom.xml @@ -304,7 +304,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.0.0 + 3.1.2 org.codehaus.mojo From 3540a8729abcb000dde26cc97b545ee550807a94 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 20 Jun 2023 10:19:26 +0000 Subject: [PATCH 027/136] chore(deps): update dependency org.apache.maven.plugins:maven-clean-plugin to v3.3.1 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index faf6cd9d08..992d0c5089 100644 --- a/pom.xml +++ b/pom.xml @@ -200,7 +200,7 @@ org.apache.maven.plugins maven-clean-plugin - 3.2.0 + 3.3.1 org.apache.maven.plugins From 7dc71a0719dd0b7ee8d39b843e8b920a34573f73 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Tue, 20 Jun 2023 17:03:20 +0200 Subject: [PATCH 028/136] Fix: issue 3978 typesolver can't parse in parallel --- .../javaparser/symbolsolver/cache/InMemoryCache.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/cache/InMemoryCache.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/cache/InMemoryCache.java index d20727ea32..4ef77a1b59 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/cache/InMemoryCache.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/cache/InMemoryCache.java @@ -21,6 +21,7 @@ package com.github.javaparser.symbolsolver.cache; +import java.util.Collections; import java.util.Map; import java.util.Optional; import java.util.WeakHashMap; @@ -47,7 +48,11 @@ public static InMemoryCache create( return new InMemoryCache<>(); } - private final Map mappedValues = new WeakHashMap<>(); + private final Map mappedValues; + + private InMemoryCache() { + mappedValues = Collections.synchronizedMap(new WeakHashMap<>()); + } @Override public void put(K key, V value) { From 4d6f7b18b265078e1bee0c335c42265c51f1dd52 Mon Sep 17 00:00:00 2001 From: Udo Borkowski Date: Mon, 26 Jun 2023 23:05:54 +0200 Subject: [PATCH 029/136] fix line separators of selected test files to resolve https://github.com/javaparser/javaparser/issues/4077 --- .../com/github/javaparser/utils/Bla.java | 4 +- .../github/javaparser/utils/module-info.java | 4 +- .../issue2615/with_module_info/demo/Main.java | 92 +++++++++---------- .../with_module_info/demo/module-info.java | 4 +- .../with_module_info_in_root/demo/Main.java | 92 +++++++++---------- .../with_module_info_in_root/module-info.java | 4 +- .../without_module_info/demo/Main.java | 92 +++++++++---------- 7 files changed, 146 insertions(+), 146 deletions(-) diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/utils/Bla.java b/javaparser-core-testing/src/test/resources/com/github/javaparser/utils/Bla.java index a81184b5c1..eeeb6f19e7 100644 --- a/javaparser-core-testing/src/test/resources/com/github/javaparser/utils/Bla.java +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/utils/Bla.java @@ -1,2 +1,2 @@ -class X { -} +class X { +} diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/utils/module-info.java b/javaparser-core-testing/src/test/resources/com/github/javaparser/utils/module-info.java index 119be4ee19..a4a0ddbf86 100644 --- a/javaparser-core-testing/src/test/resources/com/github/javaparser/utils/module-info.java +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/utils/module-info.java @@ -1,2 +1,2 @@ -module M.N { -} +module M.N { +} diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/utils/projectroot/issue2615/with_module_info/demo/Main.java b/javaparser-core-testing/src/test/resources/com/github/javaparser/utils/projectroot/issue2615/with_module_info/demo/Main.java index c8db09696b..60dca7d294 100644 --- a/javaparser-core-testing/src/test/resources/com/github/javaparser/utils/projectroot/issue2615/with_module_info/demo/Main.java +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/utils/projectroot/issue2615/with_module_info/demo/Main.java @@ -1,46 +1,46 @@ -package demo; - -import com.github.javaparser.ParseResult; -import com.github.javaparser.ast.CompilationUnit; -import com.github.javaparser.utils.ParserCollectionStrategy; -import com.github.javaparser.utils.ProjectRoot; -import com.github.javaparser.utils.SourceRoot; -import java.io.IOException; -import java.nio.file.Path; -import java.nio.file.Paths; - -/* If there is a module declaration in the root directory, JavaParser doesn't find any .java files. */ -public class Main { - - public static void main(String[] args) { - if (args.length < 1) { - System.err.println("Usage: provide one or more directory names to process"); - System.exit(1); - } - for (String dir : args) { - process(dir); - } - } - - private static void process(String dir) { - Path root = Paths.get(dir); - Callback cb = new Callback(); - ProjectRoot projectRoot = new ParserCollectionStrategy().collect(root); - projectRoot.getSourceRoots().forEach(sourceRoot -> { - try { - sourceRoot.parse("", cb); - } catch (IOException e) { - System.err.println("IOException: " + e); - } - }); - } - - private static class Callback implements SourceRoot.Callback { - - @Override - public Result process(Path localPath, Path absolutePath, ParseResult result) { - System.out.printf("Found %s%n", absolutePath); - return Result.SAVE; - } - } -} +package demo; + +import com.github.javaparser.ParseResult; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.utils.ParserCollectionStrategy; +import com.github.javaparser.utils.ProjectRoot; +import com.github.javaparser.utils.SourceRoot; +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; + +/* If there is a module declaration in the root directory, JavaParser doesn't find any .java files. */ +public class Main { + + public static void main(String[] args) { + if (args.length < 1) { + System.err.println("Usage: provide one or more directory names to process"); + System.exit(1); + } + for (String dir : args) { + process(dir); + } + } + + private static void process(String dir) { + Path root = Paths.get(dir); + Callback cb = new Callback(); + ProjectRoot projectRoot = new ParserCollectionStrategy().collect(root); + projectRoot.getSourceRoots().forEach(sourceRoot -> { + try { + sourceRoot.parse("", cb); + } catch (IOException e) { + System.err.println("IOException: " + e); + } + }); + } + + private static class Callback implements SourceRoot.Callback { + + @Override + public Result process(Path localPath, Path absolutePath, ParseResult result) { + System.out.printf("Found %s%n", absolutePath); + return Result.SAVE; + } + } +} diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/utils/projectroot/issue2615/with_module_info/demo/module-info.java b/javaparser-core-testing/src/test/resources/com/github/javaparser/utils/projectroot/issue2615/with_module_info/demo/module-info.java index abd7417e79..38c78e1d38 100644 --- a/javaparser-core-testing/src/test/resources/com/github/javaparser/utils/projectroot/issue2615/with_module_info/demo/module-info.java +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/utils/projectroot/issue2615/with_module_info/demo/module-info.java @@ -1,2 +1,2 @@ -module demo { -} +module demo { +} diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/utils/projectroot/issue2615/with_module_info_in_root/demo/Main.java b/javaparser-core-testing/src/test/resources/com/github/javaparser/utils/projectroot/issue2615/with_module_info_in_root/demo/Main.java index c8db09696b..60dca7d294 100644 --- a/javaparser-core-testing/src/test/resources/com/github/javaparser/utils/projectroot/issue2615/with_module_info_in_root/demo/Main.java +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/utils/projectroot/issue2615/with_module_info_in_root/demo/Main.java @@ -1,46 +1,46 @@ -package demo; - -import com.github.javaparser.ParseResult; -import com.github.javaparser.ast.CompilationUnit; -import com.github.javaparser.utils.ParserCollectionStrategy; -import com.github.javaparser.utils.ProjectRoot; -import com.github.javaparser.utils.SourceRoot; -import java.io.IOException; -import java.nio.file.Path; -import java.nio.file.Paths; - -/* If there is a module declaration in the root directory, JavaParser doesn't find any .java files. */ -public class Main { - - public static void main(String[] args) { - if (args.length < 1) { - System.err.println("Usage: provide one or more directory names to process"); - System.exit(1); - } - for (String dir : args) { - process(dir); - } - } - - private static void process(String dir) { - Path root = Paths.get(dir); - Callback cb = new Callback(); - ProjectRoot projectRoot = new ParserCollectionStrategy().collect(root); - projectRoot.getSourceRoots().forEach(sourceRoot -> { - try { - sourceRoot.parse("", cb); - } catch (IOException e) { - System.err.println("IOException: " + e); - } - }); - } - - private static class Callback implements SourceRoot.Callback { - - @Override - public Result process(Path localPath, Path absolutePath, ParseResult result) { - System.out.printf("Found %s%n", absolutePath); - return Result.SAVE; - } - } -} +package demo; + +import com.github.javaparser.ParseResult; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.utils.ParserCollectionStrategy; +import com.github.javaparser.utils.ProjectRoot; +import com.github.javaparser.utils.SourceRoot; +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; + +/* If there is a module declaration in the root directory, JavaParser doesn't find any .java files. */ +public class Main { + + public static void main(String[] args) { + if (args.length < 1) { + System.err.println("Usage: provide one or more directory names to process"); + System.exit(1); + } + for (String dir : args) { + process(dir); + } + } + + private static void process(String dir) { + Path root = Paths.get(dir); + Callback cb = new Callback(); + ProjectRoot projectRoot = new ParserCollectionStrategy().collect(root); + projectRoot.getSourceRoots().forEach(sourceRoot -> { + try { + sourceRoot.parse("", cb); + } catch (IOException e) { + System.err.println("IOException: " + e); + } + }); + } + + private static class Callback implements SourceRoot.Callback { + + @Override + public Result process(Path localPath, Path absolutePath, ParseResult result) { + System.out.printf("Found %s%n", absolutePath); + return Result.SAVE; + } + } +} diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/utils/projectroot/issue2615/with_module_info_in_root/module-info.java b/javaparser-core-testing/src/test/resources/com/github/javaparser/utils/projectroot/issue2615/with_module_info_in_root/module-info.java index abd7417e79..38c78e1d38 100644 --- a/javaparser-core-testing/src/test/resources/com/github/javaparser/utils/projectroot/issue2615/with_module_info_in_root/module-info.java +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/utils/projectroot/issue2615/with_module_info_in_root/module-info.java @@ -1,2 +1,2 @@ -module demo { -} +module demo { +} diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/utils/projectroot/issue2615/without_module_info/demo/Main.java b/javaparser-core-testing/src/test/resources/com/github/javaparser/utils/projectroot/issue2615/without_module_info/demo/Main.java index c8db09696b..60dca7d294 100644 --- a/javaparser-core-testing/src/test/resources/com/github/javaparser/utils/projectroot/issue2615/without_module_info/demo/Main.java +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/utils/projectroot/issue2615/without_module_info/demo/Main.java @@ -1,46 +1,46 @@ -package demo; - -import com.github.javaparser.ParseResult; -import com.github.javaparser.ast.CompilationUnit; -import com.github.javaparser.utils.ParserCollectionStrategy; -import com.github.javaparser.utils.ProjectRoot; -import com.github.javaparser.utils.SourceRoot; -import java.io.IOException; -import java.nio.file.Path; -import java.nio.file.Paths; - -/* If there is a module declaration in the root directory, JavaParser doesn't find any .java files. */ -public class Main { - - public static void main(String[] args) { - if (args.length < 1) { - System.err.println("Usage: provide one or more directory names to process"); - System.exit(1); - } - for (String dir : args) { - process(dir); - } - } - - private static void process(String dir) { - Path root = Paths.get(dir); - Callback cb = new Callback(); - ProjectRoot projectRoot = new ParserCollectionStrategy().collect(root); - projectRoot.getSourceRoots().forEach(sourceRoot -> { - try { - sourceRoot.parse("", cb); - } catch (IOException e) { - System.err.println("IOException: " + e); - } - }); - } - - private static class Callback implements SourceRoot.Callback { - - @Override - public Result process(Path localPath, Path absolutePath, ParseResult result) { - System.out.printf("Found %s%n", absolutePath); - return Result.SAVE; - } - } -} +package demo; + +import com.github.javaparser.ParseResult; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.utils.ParserCollectionStrategy; +import com.github.javaparser.utils.ProjectRoot; +import com.github.javaparser.utils.SourceRoot; +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; + +/* If there is a module declaration in the root directory, JavaParser doesn't find any .java files. */ +public class Main { + + public static void main(String[] args) { + if (args.length < 1) { + System.err.println("Usage: provide one or more directory names to process"); + System.exit(1); + } + for (String dir : args) { + process(dir); + } + } + + private static void process(String dir) { + Path root = Paths.get(dir); + Callback cb = new Callback(); + ProjectRoot projectRoot = new ParserCollectionStrategy().collect(root); + projectRoot.getSourceRoots().forEach(sourceRoot -> { + try { + sourceRoot.parse("", cb); + } catch (IOException e) { + System.err.println("IOException: " + e); + } + }); + } + + private static class Callback implements SourceRoot.Callback { + + @Override + public Result process(Path localPath, Path absolutePath, ParseResult result) { + System.out.printf("Found %s%n", absolutePath); + return Result.SAVE; + } + } +} From 8825869d33fc28838f2dd1f5fc5cca7ac7293112 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 26 Jun 2023 23:56:52 +0000 Subject: [PATCH 030/136] chore(deps): bump checkstyle from 10.12.0 to 10.12.1 Bumps [checkstyle](https://github.com/checkstyle/checkstyle) from 10.12.0 to 10.12.1. - [Release notes](https://github.com/checkstyle/checkstyle/releases) - [Commits](https://github.com/checkstyle/checkstyle/compare/checkstyle-10.12.0...checkstyle-10.12.1) --- updated-dependencies: - dependency-name: com.puppycrawl.tools:checkstyle dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 992d0c5089..35963aa7ab 100644 --- a/pom.xml +++ b/pom.xml @@ -352,7 +352,7 @@ com.puppycrawl.tools checkstyle - 10.12.0 + 10.12.1 From c799dc06493e006896f28d5368fef1abcb360e6d Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Wed, 28 Jun 2023 08:45:59 +0200 Subject: [PATCH 031/136] Nested 'if' statements should be simplified --- .../generator/core/utils/CodeUtils.java | 7 +- .../NoCommentHashCodeVisitorGenerator.java | 4 +- .../com/github/javaparser/JavadocParser.java | 18 ++-- .../LineEndingProcessingProvider.java | 15 ++- .../UnicodeEscapeProcessingProvider.java | 23 ++--- .../javaparser/ast/CompilationUnit.java | 8 +- .../java/com/github/javaparser/ast/Node.java | 16 ++-- .../com/github/javaparser/ast/NodeList.java | 3 +- .../javaparser/ast/comments/Comment.java | 8 +- .../javaparser/ast/expr/InstanceOfExpr.java | 3 +- .../ast/expr/IntegerLiteralExpr.java | 10 +- .../javaparser/ast/expr/LambdaExpr.java | 3 +- .../javaparser/ast/expr/LongLiteralExpr.java | 9 +- .../ast/nodeTypes/NodeWithModifiers.java | 3 +- .../ast/observer/ObservableProperty.java | 22 ++--- .../github/javaparser/ast/type/VarType.java | 3 +- .../javaparser/ast/visitor/EqualsVisitor.java | 3 +- .../printer/lexicalpreservation/Added.java | 6 +- .../lexicalpreservation/Difference.java | 3 +- .../DifferenceElementCalculator.java | 45 +++++---- .../LexicalPreservingPrinter.java | 8 +- .../lexicalpreservation/PhantomNodeLogic.java | 13 ++- .../lexicalpreservation/RemovedGroup.java | 12 +-- .../TextElementIteratorsFactory.java | 6 +- .../changes/ListAdditionChange.java | 3 +- .../changes/ListRemovalChange.java | 3 +- .../changes/ListReplacementChange.java | 3 +- .../javaparser/resolution/MethodUsage.java | 3 +- .../javaparser/resolution/TypeSolver.java | 6 +- .../ResolvedMethodLikeDeclaration.java | 3 +- .../ResolvedParameterDeclaration.java | 3 +- .../ResolvedReferenceTypeDeclaration.java | 6 +- .../logic/ConstructorResolutionLogic.java | 14 ++- .../logic/FunctionalInterfaceLogic.java | 3 +- .../resolution/logic/InferenceContext.java | 48 ++++++---- .../logic/InferenceVariableType.java | 12 +-- .../logic/MethodResolutionLogic.java | 18 ++-- .../resolution/types/ResolvedArrayType.java | 3 +- .../types/ResolvedIntersectionType.java | 3 +- .../types/ResolvedPrimitiveType.java | 14 +-- .../types/ResolvedReferenceType.java | 6 +- .../resolution/types/ResolvedType.java | 3 +- .../types/ResolvedTypeVariable.java | 6 +- .../resolution/types/ResolvedWildcard.java | 24 ++--- .../ResolvedTypeParameterValueProvider.java | 3 +- .../ResolvedTypeParametersMap.java | 6 +- .../javaparser/utils/CodeGenerationUtils.java | 12 ++- .../javaparser/utils/CollectionStrategy.java | 11 +-- .../javaparser/utils/LineSeparator.java | 18 ++-- .../javaparser/utils/PositionUtils.java | 29 +++--- .../github/javaparser/utils/SourceRoot.java | 3 +- .../symbolsolver/SourceFileInfoExtractor.java | 3 +- .../javaparsermodel/JavaParserFacade.java | 31 +++---- .../javaparsermodel/JavaParserFactory.java | 91 ++++++++++++------- .../javaparsermodel/TypeExtractor.java | 39 ++++---- .../contexts/AbstractJavaParserContext.java | 26 +++--- .../AbstractMethodLikeDeclarationContext.java | 3 +- .../contexts/CompilationUnitContext.java | 31 +++---- .../contexts/ContextHelper.java | 3 +- .../contexts/FieldAccessContext.java | 9 +- .../contexts/ForEachStatementContext.java | 8 +- .../contexts/ForStatementContext.java | 3 +- .../JavaParserTypeDeclarationAdapter.java | 12 +-- .../contexts/LambdaExprContext.java | 24 +++-- .../contexts/MethodCallExprContext.java | 42 ++++----- .../contexts/MethodReferenceExprContext.java | 27 +++--- .../contexts/StatementContext.java | 19 ++-- .../contexts/TryWithResourceContext.java | 6 +- .../declarations/AstResolutionUtils.java | 21 ++--- .../JavaParserAnnotationDeclaration.java | 3 +- .../JavaParserAnonymousClassDeclaration.java | 6 +- .../JavaParserClassDeclaration.java | 9 +- .../JavaParserInterfaceDeclaration.java | 5 +- .../JavaParserSymbolDeclaration.java | 3 +- .../declarations/JavaParserTypeAdapter.java | 33 ++++--- .../declarations/JavaParserTypeParameter.java | 15 +-- .../JavaParserTypeVariableDeclaration.java | 12 +-- .../JavassistAnnotationDeclaration.java | 3 +- .../javassistmodel/JavassistFactory.java | 38 ++++---- .../JavassistTypeDeclarationAdapter.java | 13 +-- .../JavassistTypeParameter.java | 3 +- .../javassistmodel/JavassistUtils.java | 38 ++++---- .../ReflectionAnnotationDeclaration.java | 5 +- .../reflectionmodel/ReflectionFactory.java | 48 +++++----- .../ReflectionMethodDeclaration.java | 3 +- .../ReflectionTypeParameter.java | 6 +- .../symbolsolver/resolution/SymbolSolver.java | 3 +- .../resolution/naming/NameLogic.java | 48 +++++----- .../NumericConditionalExprHandler.java | 6 +- .../resolution/typeinference/Bound.java | 6 +- .../typeinference/ControlFlowLogic.java | 7 +- .../resolution/typeinference/TypeHelper.java | 17 +--- .../typeinference/TypeInference.java | 3 +- .../ExpressionCompatibleWithType.java | 3 +- .../TypeCompatibleWithType.java | 3 +- .../constraintformulas/TypeSameAsType.java | 3 +- .../constraintformulas/TypeSubtypeOfType.java | 3 +- .../typesolvers/ClassLoaderTypeSolver.java | 14 ++- .../typesolvers/CombinedTypeSolver.java | 3 +- .../resolution/typesolvers/JarTypeSolver.java | 3 +- .../typesolvers/MemoryTypeSolver.java | 3 +- 101 files changed, 603 insertions(+), 680 deletions(-) diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/utils/CodeUtils.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/utils/CodeUtils.java index 7f002d241e..a9d537c215 100644 --- a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/utils/CodeUtils.java +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/utils/CodeUtils.java @@ -49,10 +49,9 @@ private CodeUtils() { public static String castValue(String value, Type requiredType, String valueType) { String requiredTypeName = requiredType.asString(); - if (requiredTypeName.equals(valueType)) - return value; - else - return String.format("(%s) %s", requiredTypeName, value); + if (requiredTypeName.equals(valueType)) + return value; + return String.format("(%s) %s", requiredTypeName, value); } } diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/NoCommentHashCodeVisitorGenerator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/NoCommentHashCodeVisitorGenerator.java index 8c75799f1a..9169b3b755 100644 --- a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/NoCommentHashCodeVisitorGenerator.java +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/NoCommentHashCodeVisitorGenerator.java @@ -62,8 +62,8 @@ protected void generateVisitMethodBody(BaseNodeMetaModel node, MethodDeclaration if (propertyMetaModels.size() == 1) { builder.append("0"); break; - } else - continue; + } + continue; } // Is this field another AST node? Visit it. if (field.getNodeReference().isPresent()) { diff --git a/javaparser-core/src/main/java/com/github/javaparser/JavadocParser.java b/javaparser-core/src/main/java/com/github/javaparser/JavadocParser.java index f3ae005dba..b3a4b33035 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/JavadocParser.java +++ b/javaparser-core/src/main/java/com/github/javaparser/JavadocParser.java @@ -97,17 +97,14 @@ private static List cleanLines(String content) { int asteriskIndex = startsWithAsterisk(l); if (asteriskIndex == -1) { return l; - } else { - // if a line starts with space followed by an asterisk drop to the asterisk - // if there is a space immediately after the asterisk drop it also - if (l.length() > (asteriskIndex + 1)) { + } + if (l.length() > (asteriskIndex + 1)) { char c = l.charAt(asteriskIndex + 1); if (c == ' ' || c == '\t') { return l.substring(asteriskIndex + 2); } } - return l.substring(asteriskIndex + 1); - } + return l.substring(asteriskIndex + 1); }).collect(Collectors.toList()); // lines containing only whitespace are normalized to empty lines cleanedLines = cleanedLines.stream().map(l -> l.trim().isEmpty() ? "" : l).collect(Collectors.toList()); @@ -129,15 +126,14 @@ private static List cleanLines(String content) { static int startsWithAsterisk(String line) { if (line.startsWith("*")) { return 0; - } else if ((line.startsWith(" ") || line.startsWith("\t")) && line.length() > 1) { + } + if ((line.startsWith(" ") || line.startsWith("\t")) && line.length() > 1) { int res = startsWithAsterisk(line.substring(1)); if (res == -1) { return -1; - } else { - return 1 + res; } - } else { - return -1; + return 1 + res; } + return -1; } } diff --git a/javaparser-core/src/main/java/com/github/javaparser/LineEndingProcessingProvider.java b/javaparser-core/src/main/java/com/github/javaparser/LineEndingProcessingProvider.java index a9d4c3763a..9be75cdf30 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/LineEndingProcessingProvider.java +++ b/javaparser-core/src/main/java/com/github/javaparser/LineEndingProcessingProvider.java @@ -115,13 +115,12 @@ public int read(char[] buffer, final int offset, int len) throws IOException { if (pos == offset) { // Nothing read yet, this is the end of the stream. return EOF; - } else { - break; } - } else { - String str = String.valueOf((char) ch); - Optional lookup = LineSeparator.lookup(str); - if (lookup.isPresent()) { + break; + } + String str = String.valueOf((char) ch); + Optional lookup = LineSeparator.lookup(str); + if (lookup.isPresent()) { LineSeparator lineSeparator = lookup.get(); // Track the number of times this character is found.. eolCounts.putIfAbsent(lineSeparator, 0); @@ -140,9 +139,7 @@ public int read(char[] buffer, final int offset, int len) throws IOException { // If "this" (current) char is not a line separator, set the next loop's "previous" to null previousLineSeparator = null; } - // Move to next character - buffer[pos++] = (char) ch; - } + buffer[pos++] = (char) ch; } return pos - offset; } diff --git a/javaparser-core/src/main/java/com/github/javaparser/UnicodeEscapeProcessingProvider.java b/javaparser-core/src/main/java/com/github/javaparser/UnicodeEscapeProcessingProvider.java index de5be427cf..c6dd55f7f7 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/UnicodeEscapeProcessingProvider.java +++ b/javaparser-core/src/main/java/com/github/javaparser/UnicodeEscapeProcessingProvider.java @@ -99,13 +99,11 @@ public int read(char[] buffer, final int offset, int len) throws IOException { if (pos == offset) { // Nothing read yet, this is the end of the stream. return EOF; - } else { - break; } - } else { - _mappingBuilder.update(); - buffer[pos++] = (char) ch; + break; } + _mappingBuilder.update(); + buffer[pos++] = (char) ch; } return pos - offset; } @@ -129,9 +127,8 @@ private int nextOutputChar() throws IOException { { if (_backslashSeen) { return clearBackSlashSeen(next); - } else { - return backSlashSeen(); } + return backSlashSeen(); } default: { @@ -348,17 +345,13 @@ public PositionUpdate lookup(Position position) { int result = Collections.binarySearch(_deltas, position); if (result >= 0) { return _deltas.get(result); - } else { - int insertIndex = -result - 1; - if (insertIndex == 0) { + } + int insertIndex = -result - 1; + if (insertIndex == 0) { // Before the first delta info, identity mapping. return PositionUpdate.NONE; - } else { - // The relevant update is the one with the position smaller - // than the requested position. - return _deltas.get(insertIndex - 1); } - } + return _deltas.get(insertIndex - 1); } /** diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/CompilationUnit.java b/javaparser-core/src/main/java/com/github/javaparser/ast/CompilationUnit.java index 7f2a18dc03..18bcb081d1 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/CompilationUnit.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/CompilationUnit.java @@ -302,10 +302,8 @@ private boolean isImplicitImport(ImportDeclaration importDeclaration) { return currentPackageName.equals(importPackageName.get()); } return false; - } else { - // imports of unnamed package are not allowed - return true; } + return true; } private static Optional getImportPackageName(ImportDeclaration importDeclaration) { @@ -397,9 +395,9 @@ public CompilationUnit addImport(Class clazz) { if (clazz.isArray()) { return addImport(clazz.getComponentType()); } - if (ClassUtils.isPrimitiveOrWrapper(clazz) || JAVA_LANG.equals(clazz.getPackage().getName())) + if (ClassUtils.isPrimitiveOrWrapper(clazz) || JAVA_LANG.equals(clazz.getPackage().getName())) return this; - else if (clazz.isAnonymousClass() || clazz.isLocalClass()) + if (clazz.isAnonymousClass() || clazz.isLocalClass()) throw new IllegalArgumentException(clazz.getName() + " is an anonymous or local class therefore it can't be added with addImport"); return addImport(clazz.getCanonicalName()); } diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/Node.java b/javaparser-core/src/main/java/com/github/javaparser/ast/Node.java index d13fbc7fcc..9f4dfcae0f 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/Node.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/Node.java @@ -793,9 +793,8 @@ public SymbolResolver getSymbolResolver() { return findCompilationUnit().map(cu -> { if (cu.containsData(SYMBOL_RESOLVER_KEY)) { return cu.getData(SYMBOL_RESOLVER_KEY); - } else { - throw new IllegalStateException("Symbol resolution not configured: to configure consider setting a SymbolResolver in the ParserConfiguration"); } + throw new IllegalStateException("Symbol resolution not configured: to configure consider setting a SymbolResolver in the ParserConfiguration"); }).orElseThrow(() -> new IllegalStateException("The node is not inserted in a CompilationUnit")); } @@ -1116,15 +1115,14 @@ public Node next() { Node node = nodes.get(cursor); fillStackToLeaf(node); return nextFromLevel(); - } else { - nodesStack.pop(); - cursorStack.pop(); - hasNext = !nodesStack.empty(); - if (hasNext) { + } + nodesStack.pop(); + cursorStack.pop(); + hasNext = !nodesStack.empty(); + if (hasNext) { return nextFromLevel(); } - return root; - } + return root; } private Node nextFromLevel() { diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/NodeList.java b/javaparser-core/src/main/java/com/github/javaparser/ast/NodeList.java index 46c7b2b376..d78ed2ad5c 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/NodeList.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/NodeList.java @@ -319,9 +319,8 @@ public T[] toArray(T[] a) { public boolean remove(Object o) { if (o instanceof Node) { return remove((Node) o); - } else { - return false; } + return false; } /** diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/comments/Comment.java b/javaparser-core/src/main/java/com/github/javaparser/ast/comments/Comment.java index 04e36db6a1..c91424de4c 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/comments/Comment.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/comments/Comment.java @@ -143,15 +143,15 @@ public Node setComment(final Comment comment) { @Override public boolean remove() { - // the other are orphan comments and remove should work with them + if (this.commentedNode != null) { this.commentedNode.setComment(null); return true; - } else if (this.getParentNode().isPresent()) { + } + if (this.getParentNode().isPresent()) { return this.getParentNode().get().removeOrphanComment(this); - } else { - return false; } + return false; } @Override diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/expr/InstanceOfExpr.java b/javaparser-core/src/main/java/com/github/javaparser/ast/expr/InstanceOfExpr.java index c8f9d8129f..2428dc468e 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/expr/InstanceOfExpr.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/expr/InstanceOfExpr.java @@ -141,9 +141,8 @@ public InstanceOfExpr(TokenRange tokenRange, Expression expression, ReferenceTyp public Optional getName() { if (pattern == null) { return Optional.empty(); - } else { - return Optional.of(pattern.getName()); } + return Optional.of(pattern.getName()); } @Override diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/expr/IntegerLiteralExpr.java b/javaparser-core/src/main/java/com/github/javaparser/ast/expr/IntegerLiteralExpr.java index 0180b24d5e..d86f6b2ab8 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/expr/IntegerLiteralExpr.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/expr/IntegerLiteralExpr.java @@ -128,17 +128,11 @@ public int asInt() { * @return the literal value as a number while respecting different number representations */ public Number asNumber() { - /* - * we need to handle the special case for the literal 2147483648, which is used to - * represent Integer.MIN_VALUE (-2147483648) as a combination of a UnaryExpr and an - * IntegerLiteralExpr. However 2147483648 cannot be represented in an integer, so we - * need to return a long - */ + if (Objects.equals(value, MAX_31_BIT_UNSIGNED_VALUE_AS_STRING) && hasUnaryMinusAsParent(this)) { return MAX_31_BIT_UNSIGNED_VALUE_AS_LONG; - } else { - return asInt(); } + return asInt(); } /** diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/expr/LambdaExpr.java b/javaparser-core/src/main/java/com/github/javaparser/ast/expr/LambdaExpr.java index 2413d74e45..95d46f00a5 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/expr/LambdaExpr.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/expr/LambdaExpr.java @@ -208,9 +208,8 @@ public boolean remove(Node node) { public Optional getExpressionBody() { if (body.isExpressionStmt()) { return Optional.of(body.asExpressionStmt().getExpression()); - } else { - return Optional.empty(); } + return Optional.empty(); } @Override diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/expr/LongLiteralExpr.java b/javaparser-core/src/main/java/com/github/javaparser/ast/expr/LongLiteralExpr.java index 223b7f441c..c39062cc37 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/expr/LongLiteralExpr.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/expr/LongLiteralExpr.java @@ -135,16 +135,11 @@ public long asLong() { * @return the literal value as a number while respecting different number representations */ public Number asNumber() { - /* we need to handle the special case for the literal 9223372036854775808L, which is used to - * represent Integer.MIN_VALUE (-9223372036854775808L) as a combination of a UnaryExpr and a - * LongLiteralExpr. However 9223372036854775808L cannot be represented in a long, so we need - * to return a BigInteger - */ + if (Objects.equals(value, MAX_63_BIT_UNSIGNED_VALUE_AS_STRING) && hasUnaryMinusAsParent(this)) { return MAX_63_BIT_UNSIGNED_VALUE_AS_BIG_INTEGER; - } else { - return asLong(); } + return asLong(); } /** diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithModifiers.java b/javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithModifiers.java index 35fdc68cfe..c178f0b558 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithModifiers.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithModifiers.java @@ -72,9 +72,8 @@ default N removeModifier(Modifier.Keyword... modifiersToRemove) { default N setModifier(Modifier.Keyword m, boolean set) { if (set) { return addModifier(m); - } else { - return removeModifier(m); } + return removeModifier(m); } /** diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/observer/ObservableProperty.java b/javaparser-core/src/main/java/com/github/javaparser/ast/observer/ObservableProperty.java index ac5bbeb3b9..b183b58aea 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/observer/ObservableProperty.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/observer/ObservableProperty.java @@ -158,9 +158,8 @@ public static ObservableProperty fromCamelCaseName(String camelCaseName) { Optional observableProperty = Arrays.stream(values()).filter(v -> v.camelCaseName().equals(camelCaseName)).findFirst(); if (observableProperty.isPresent()) { return observableProperty.get(); - } else { - throw new IllegalArgumentException("No property found with the given camel case name: " + camelCaseName); } + throw new IllegalArgumentException("No property found with the given camel case name: " + camelCaseName); } ObservableProperty(Type type) { @@ -206,16 +205,15 @@ public Node getValueAsSingleReference(Node node) { try { if (rawValue instanceof Node) { return (Node) rawValue; - } else if (rawValue instanceof Optional) { + } + if (rawValue instanceof Optional) { Optional opt = (Optional) rawValue; if (opt.isPresent()) { return opt.get(); - } else { - return null; } - } else { - throw new RuntimeException(String.format("Property %s returned %s (%s)", this.name(), rawValue.toString(), rawValue.getClass().getCanonicalName())); + return null; } + throw new RuntimeException(String.format("Property %s returned %s (%s)", this.name(), rawValue.toString(), rawValue.getClass().getCanonicalName())); } catch (ClassCastException e) { throw new RuntimeException(e); } @@ -238,14 +236,12 @@ public NodeList getValueAsMultipleReference(Node node) { } if (rawValue instanceof NodeList) { return (NodeList) rawValue; - } else { - Optional opt = (Optional) rawValue; - if (opt.isPresent()) { + } + Optional opt = (Optional) rawValue; + if (opt.isPresent()) { return opt.get(); - } else { - return null; } - } + return null; } catch (ClassCastException e) { throw new RuntimeException("Unable to get list value for " + this.name() + " from " + node + " (class: " + node.getClass().getSimpleName() + ")", e); } diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/type/VarType.java b/javaparser-core/src/main/java/com/github/javaparser/ast/type/VarType.java index e3038dff55..6e36e68d67 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/type/VarType.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/type/VarType.java @@ -183,8 +183,7 @@ private Optional forEachStmtWithVariableDeclarator( node = node.get().getParentNode(); if (!node.isPresent() || !(node.get() instanceof ForEachStmt)) { return Optional.empty(); - } else { - return Optional.of((ForEachStmt)node.get()); } + return Optional.of((ForEachStmt)node.get()); } } diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/visitor/EqualsVisitor.java b/javaparser-core/src/main/java/com/github/javaparser/ast/visitor/EqualsVisitor.java index 97ef09b3de..ef54c23d95 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/visitor/EqualsVisitor.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/visitor/EqualsVisitor.java @@ -64,7 +64,8 @@ private boolean commonNodeEquality(Node n, Node n2) { private boolean nodesEquals(final List nodes1, final List nodes2) { if (nodes1 == null) { return nodes2 == null; - } else if (nodes2 == null) { + } + if (nodes2 == null) { return false; } if (nodes1.size() != nodes2.size()) { diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Added.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Added.java index e9769b58ee..8cbe083c0c 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Added.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Added.java @@ -88,11 +88,11 @@ private boolean isToken() { public TextElement toTextElement() { if (element instanceof LexicalDifferenceCalculator.CsmChild) { return new ChildTextElement(((LexicalDifferenceCalculator.CsmChild) element).getChild()); - } else if (element instanceof CsmToken) { + } + if (element instanceof CsmToken) { return new TokenTextElement(((CsmToken) element).getTokenType(), ((CsmToken) element).getContent(null)); - } else { - throw new UnsupportedOperationException(element.getClass().getSimpleName()); } + throw new UnsupportedOperationException(element.getClass().getSimpleName()); } /* diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java index 045d43d85e..82a9e621cb 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java @@ -935,9 +935,8 @@ private int rewindSpace(int index) { } if (nodeText.getTextElement(index).isWhiteSpace()) { return rewindSpace(index - 1); - } else { - return index; } + return index; } private boolean nextIsRightBrace(int index) { diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/DifferenceElementCalculator.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/DifferenceElementCalculator.java index 200f9ecee4..b9481df29c 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/DifferenceElementCalculator.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/DifferenceElementCalculator.java @@ -74,16 +74,19 @@ static boolean matching(CsmElement a, CsmElement b) { CsmChild childA = (CsmChild) a; CsmChild childB = (CsmChild) b; return childA.getChild().equals(childB.getChild()); - } else if (b instanceof CsmToken) { + } + if (b instanceof CsmToken) { return false; - } else if (b instanceof CsmIndent) { + } + if (b instanceof CsmIndent) { return false; - } else if (b instanceof CsmUnindent) { + } + if (b instanceof CsmUnindent) { return false; - } else { - throw new UnsupportedOperationException(a.getClass().getSimpleName() + " " + b.getClass().getSimpleName()); } - } else if (a instanceof CsmToken) { + throw new UnsupportedOperationException(a.getClass().getSimpleName() + " " + b.getClass().getSimpleName()); + } + if (a instanceof CsmToken) { if (b instanceof CsmToken) { // fix #2382: // Tokens are described by their type AND their content @@ -92,18 +95,22 @@ static boolean matching(CsmElement a, CsmElement b) { CsmToken childA = (CsmToken) a; CsmToken childB = (CsmToken) b; return childA.equals(childB); - } else if (b instanceof CsmChild) { + } + if (b instanceof CsmChild) { return false; - } else if (b instanceof CsmIndent) { + } + if (b instanceof CsmIndent) { return false; - } else if (b instanceof CsmUnindent) { + } + if (b instanceof CsmUnindent) { return false; - } else { - throw new UnsupportedOperationException(a.getClass().getSimpleName() + " " + b.getClass().getSimpleName()); } - } else if (a instanceof CsmIndent) { + throw new UnsupportedOperationException(a.getClass().getSimpleName() + " " + b.getClass().getSimpleName()); + } + if (a instanceof CsmIndent) { return b instanceof CsmIndent; - } else if (a instanceof CsmUnindent) { + } + if (a instanceof CsmUnindent) { return b instanceof CsmUnindent; } throw new UnsupportedOperationException(a.getClass().getSimpleName() + " " + b.getClass().getSimpleName()); @@ -118,17 +125,19 @@ private static boolean replacement(CsmElement a, CsmElement b) { CsmChild childA = (CsmChild) a; CsmChild childB = (CsmChild) b; return childA.getChild().getClass().equals(childB.getChild().getClass()); - } else if (b instanceof CsmToken) { + } + if (b instanceof CsmToken) { return false; - } else { - throw new UnsupportedOperationException(a.getClass().getSimpleName() + " " + b.getClass().getSimpleName()); } - } else if (a instanceof CsmToken) { + throw new UnsupportedOperationException(a.getClass().getSimpleName() + " " + b.getClass().getSimpleName()); + } + if (a instanceof CsmToken) { if (b instanceof CsmToken) { CsmToken childA = (CsmToken) a; CsmToken childB = (CsmToken) b; return childA.getTokenType() == childB.getTokenType(); - } else if (b instanceof CsmChild) { + } + if (b instanceof CsmChild) { return false; } } diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinter.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinter.java index 75e8812192..9edf9a9fb7 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinter.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinter.java @@ -489,11 +489,8 @@ private static Iterator tokensPreceeding(final Node node) { if (index == NodeText.NOT_FOUND) { if (node.getParentNode().get() instanceof VariableDeclarator) { return tokensPreceeding(node.getParentNode().get()); - } else { - // comment node can be removed at this stage. - return new TextElementIteratorsFactory.EmptyIterator(); -// throw new IllegalArgumentException(String.format("I could not find child '%s' in parent '%s'. parentNodeText: %s", node, node.getParentNode().get(), parentNodeText)); } + return new TextElementIteratorsFactory.EmptyIterator(); } return new TextElementIteratorsFactory.CascadingIterator<>(TextElementIteratorsFactory.partialReverseIterator(parentNodeText, index - 1), () -> tokensPreceeding(node.getParentNode().get())); } @@ -656,9 +653,8 @@ static List findIndentation(Node node) { TokenTextElement tte = it.next(); if (tte.getTokenKind() == SINGLE_LINE_COMMENT || tte.isNewline()) { break; - } else { - followingNewlines.add(tte); } + followingNewlines.add(tte); } Collections.reverse(followingNewlines); for (int i = 0; i < followingNewlines.size(); i++) { diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/PhantomNodeLogic.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/PhantomNodeLogic.java index 1b813a703f..88895bbfc3 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/PhantomNodeLogic.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/PhantomNodeLogic.java @@ -52,15 +52,14 @@ public void parentChange(Node observedNode, Node previousParent, Node newParent) static boolean isPhantomNode(Node node) { if (isPhantomNodeCache.containsKey(node)) { return isPhantomNodeCache.get(node); - } else { - if (node instanceof UnknownType) { + } + if (node instanceof UnknownType) { return true; } - boolean res = (node.getParentNode().isPresent() && node.getParentNode().get().hasRange() && node.hasRange() && !node.getParentNode().get().getRange().get().contains(node.getRange().get()) || inPhantomNode(node, LEVELS_TO_EXPLORE)); - isPhantomNodeCache.put(node, res); - node.register(cacheCleaner); - return res; - } + boolean res = (node.getParentNode().isPresent() && node.getParentNode().get().hasRange() && node.hasRange() && !node.getParentNode().get().getRange().get().contains(node.getRange().get()) || inPhantomNode(node, LEVELS_TO_EXPLORE)); + isPhantomNodeCache.put(node, res); + node.register(cacheCleaner); + return res; } /** diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/RemovedGroup.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/RemovedGroup.java index 2c6b3c6cf5..f676c44b2e 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/RemovedGroup.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/RemovedGroup.java @@ -179,11 +179,11 @@ private boolean hasOnlyWhiteSpaceForTokenFunction(JavaToken token, Function getIndentation() { if (previousToken.isPresent()) { if (TokenTypes.isEndOfLineToken(previousToken.get().getKind())) { return Optional.of(Integer.valueOf(indentation)); - } else { - return Optional.empty(); } - } else { - return Optional.of(Integer.valueOf(indentation)); + return Optional.empty(); } + return Optional.of(Integer.valueOf(indentation)); } } } diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/TextElementIteratorsFactory.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/TextElementIteratorsFactory.java index 44a8f57d7a..1f46839a97 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/TextElementIteratorsFactory.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/TextElementIteratorsFactory.java @@ -174,13 +174,13 @@ public void remove() { nodeText.removeElement(index); } }; - } else if (textElement instanceof ChildTextElement) { + } + if (textElement instanceof ChildTextElement) { ChildTextElement childTextElement = (ChildTextElement) textElement; NodeText textForChild = childTextElement.getNodeTextForWrappedNode(); return reverseIterator(textForChild); - } else { - throw new IllegalArgumentException(); } + throw new IllegalArgumentException(); } public static Iterator reverseIterator(NodeText nodeText) { diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/changes/ListAdditionChange.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/changes/ListAdditionChange.java index 029cd0de84..5ca5e74a24 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/changes/ListAdditionChange.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/changes/ListAdditionChange.java @@ -62,9 +62,8 @@ public Object getValue(ObservableProperty property, Node node) { // Perform modification -- add to the list newNodeList.add(index, nodeAdded); return newNodeList; - } else { - return new NoChange().getValue(property, node); } + return new NoChange().getValue(property, node); } @Override diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/changes/ListRemovalChange.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/changes/ListRemovalChange.java index 888770b62e..047f2f5823 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/changes/ListRemovalChange.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/changes/ListRemovalChange.java @@ -60,9 +60,8 @@ public Object getValue(ObservableProperty property, Node node) { // Perform modification -- remove an item from the list newNodeList.remove(index); return newNodeList; - } else { - return new NoChange().getValue(property, node); } + return new NoChange().getValue(property, node); } @Override diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/changes/ListReplacementChange.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/changes/ListReplacementChange.java index a63a7b5124..c405206c70 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/changes/ListReplacementChange.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/changes/ListReplacementChange.java @@ -62,9 +62,8 @@ public Object getValue(ObservableProperty property, Node node) { // Perform modification -- replace an item in the list newNodeList.set(index, newValue); return newNodeList; - } else { - return new NoChange().getValue(property, node); } + return new NoChange().getValue(property, node); } @Override diff --git a/javaparser-core/src/main/java/com/github/javaparser/resolution/MethodUsage.java b/javaparser-core/src/main/java/com/github/javaparser/resolution/MethodUsage.java index 5040b6f913..c598796cf0 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/resolution/MethodUsage.java +++ b/javaparser-core/src/main/java/com/github/javaparser/resolution/MethodUsage.java @@ -123,9 +123,8 @@ public MethodUsage replaceExceptionType(int i, ResolvedType replaced) { public MethodUsage replaceReturnType(ResolvedType returnType) { if (returnType == this.returnType) { return this; - } else { - return new MethodUsage(declaration, paramTypes, returnType, exceptionTypes, typeParametersMap); } + return new MethodUsage(declaration, paramTypes, returnType, exceptionTypes, typeParametersMap); } /** diff --git a/javaparser-core/src/main/java/com/github/javaparser/resolution/TypeSolver.java b/javaparser-core/src/main/java/com/github/javaparser/resolution/TypeSolver.java index d7bf5eb49d..9691331156 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/resolution/TypeSolver.java +++ b/javaparser-core/src/main/java/com/github/javaparser/resolution/TypeSolver.java @@ -40,9 +40,8 @@ public interface TypeSolver { default TypeSolver getRoot() { if (getParent() == null) { return this; - } else { - return getParent().getRoot(); } + return getParent().getRoot(); } /** @@ -68,9 +67,8 @@ default ResolvedReferenceTypeDeclaration solveType(String name) throws UnsolvedS SymbolReference ref = tryToSolveType(name); if (ref.isSolved()) { return ref.getCorrespondingDeclaration(); - } else { - throw new UnsolvedSymbolException(name, this.toString()); } + throw new UnsolvedSymbolException(name, this.toString()); } /** diff --git a/javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedMethodLikeDeclaration.java b/javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedMethodLikeDeclaration.java index 1b71161116..dee38cce75 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedMethodLikeDeclaration.java +++ b/javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedMethodLikeDeclaration.java @@ -129,9 +129,8 @@ default List formalParameterTypes() { default boolean hasVariadicParameter() { if (getNumberOfParams() == 0) { return false; - } else { - return getParam(getNumberOfParams() - 1).isVariadic(); } + return getParam(getNumberOfParams() - 1).isVariadic(); } @Override diff --git a/javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedParameterDeclaration.java b/javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedParameterDeclaration.java index e8183cf957..077e1bc8c0 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedParameterDeclaration.java +++ b/javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedParameterDeclaration.java @@ -56,8 +56,7 @@ default ResolvedParameterDeclaration asParameter() { default String describeType() { if (isVariadic()) { return getType().asArrayType().getComponentType().describe() + "..."; - } else { - return getType().describe(); } + return getType().describe(); } } diff --git a/javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedReferenceTypeDeclaration.java b/javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedReferenceTypeDeclaration.java index 4e397f9f55..dd17402924 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedReferenceTypeDeclaration.java +++ b/javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedReferenceTypeDeclaration.java @@ -175,9 +175,8 @@ default ResolvedFieldDeclaration getField(String name) { Optional field = this.getAllFields().stream().filter(f -> f.getName().equals(name)).findFirst(); if (field.isPresent()) { return field.get(); - } else { - throw new UnsolvedSymbolException("Field not found: " + name); } + throw new UnsolvedSymbolException("Field not found: " + name); } /** @@ -187,9 +186,8 @@ default ResolvedFieldDeclaration getVisibleField(String name) { Optional field = getVisibleFields().stream().filter(f -> f.getName().equals(name)).findFirst(); if (field.isPresent()) { return field.get(); - } else { - throw new IllegalArgumentException(); } + throw new IllegalArgumentException(); } /** diff --git a/javaparser-core/src/main/java/com/github/javaparser/resolution/logic/ConstructorResolutionLogic.java b/javaparser-core/src/main/java/com/github/javaparser/resolution/logic/ConstructorResolutionLogic.java index 35346ced9c..d1437da5a9 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/resolution/logic/ConstructorResolutionLogic.java +++ b/javaparser-core/src/main/java/com/github/javaparser/resolution/logic/ConstructorResolutionLogic.java @@ -168,11 +168,11 @@ public static SymbolReference findMostApplicable } if (applicableConstructors.size() == 1) { return SymbolReference.solved(applicableConstructors.get(0)); - } else { - ResolvedConstructorDeclaration winningCandidate = applicableConstructors.get(0); - ResolvedConstructorDeclaration other = null; - boolean possibleAmbiguity = false; - for (int i = 1; i < applicableConstructors.size(); i++) { + } + ResolvedConstructorDeclaration winningCandidate = applicableConstructors.get(0); + ResolvedConstructorDeclaration other = null; + boolean possibleAmbiguity = false; + for (int i = 1; i < applicableConstructors.size(); i++) { other = applicableConstructors.get(i); if (isMoreSpecific(winningCandidate, other, typeSolver)) { possibleAmbiguity = false; @@ -198,9 +198,7 @@ public static SymbolReference findMostApplicable } } } - - return SymbolReference.solved(winningCandidate); - } + return SymbolReference.solved(winningCandidate); } private static boolean isMoreSpecific(ResolvedConstructorDeclaration constructorA, diff --git a/javaparser-core/src/main/java/com/github/javaparser/resolution/logic/FunctionalInterfaceLogic.java b/javaparser-core/src/main/java/com/github/javaparser/resolution/logic/FunctionalInterfaceLogic.java index c0579982d2..5718978ac7 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/resolution/logic/FunctionalInterfaceLogic.java +++ b/javaparser-core/src/main/java/com/github/javaparser/resolution/logic/FunctionalInterfaceLogic.java @@ -54,9 +54,8 @@ public static Optional getFunctionalMethod(ResolvedType type) { ResolvedReferenceTypeDeclaration typeDeclaration = optionalTypeDeclaration.get(); if (type.isReferenceType() && typeDeclaration.isInterface()) { return getFunctionalMethod(typeDeclaration); - } else { - return Optional.empty(); } + return Optional.empty(); } /** diff --git a/javaparser-core/src/main/java/com/github/javaparser/resolution/logic/InferenceContext.java b/javaparser-core/src/main/java/com/github/javaparser/resolution/logic/InferenceContext.java index cc0f76c6ee..d9563f2667 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/resolution/logic/InferenceContext.java +++ b/javaparser-core/src/main/java/com/github/javaparser/resolution/logic/InferenceContext.java @@ -192,48 +192,56 @@ private ResolvedType placeInferenceVariables(ResolvedType type) { if (type.isWildcard()) { if (type.asWildcard().isExtends()) { return ResolvedWildcard.extendsBound(placeInferenceVariables(type.asWildcard().getBoundedType())); - } else if (type.asWildcard().isSuper()) { + } + if (type.asWildcard().isSuper()) { return ResolvedWildcard.superBound(placeInferenceVariables(type.asWildcard().getBoundedType())); - } else { - return type; } - } else if (type.isTypeVariable()) { + return type; + } + if (type.isTypeVariable()) { return inferenceVariableTypeForTp(type.asTypeParameter()); - } else if (type.isReferenceType()) { + } + if (type.isReferenceType()) { return type.asReferenceType().transformTypeParameters(tp -> placeInferenceVariables(tp)); - } else if (type.isArray()) { + } + if (type.isArray()) { return new ResolvedArrayType(placeInferenceVariables(type.asArrayType().getComponentType())); - } else if (type.isNull() || type.isPrimitive() || type.isVoid()) { + } + if (type.isNull() || type.isPrimitive() || type.isVoid()) { return type; - } else if (type.isConstraint()) { + } + if (type.isConstraint()) { return ResolvedLambdaConstraintType.bound(placeInferenceVariables(type.asConstraintType().getBound())); - } else if (type instanceof InferenceVariableType) { + } + if (type instanceof InferenceVariableType) { return type; - } else { - throw new UnsupportedOperationException(type.describe()); } + throw new UnsupportedOperationException(type.describe()); } public ResolvedType resolve(ResolvedType type) { if (type instanceof InferenceVariableType) { InferenceVariableType inferenceVariableType = (InferenceVariableType) type; return inferenceVariableType.equivalentType(); - } else if (type.isReferenceType()) { + } + if (type.isReferenceType()) { return type.asReferenceType().transformTypeParameters(tp -> resolve(tp)); - } else if (type.isNull() || type.isPrimitive() || type.isVoid()) { + } + if (type.isNull() || type.isPrimitive() || type.isVoid()) { return type; - } else if (type.isArray()) { + } + if (type.isArray()) { return new ResolvedArrayType(resolve(type.asArrayType().getComponentType())); - } else if (type.isWildcard()) { + } + if (type.isWildcard()) { if (type.asWildcard().isExtends()) { return ResolvedWildcard.extendsBound(resolve(type.asWildcard().getBoundedType())); - } else if (type.asWildcard().isSuper()) { + } + if (type.asWildcard().isSuper()) { return ResolvedWildcard.superBound(resolve(type.asWildcard().getBoundedType())); - } else { - return type; } - } else { - throw new UnsupportedOperationException(type.describe()); + return type; } + throw new UnsupportedOperationException(type.describe()); } } diff --git a/javaparser-core/src/main/java/com/github/javaparser/resolution/logic/InferenceVariableType.java b/javaparser-core/src/main/java/com/github/javaparser/resolution/logic/InferenceVariableType.java index 8fc6c55173..1659c6c796 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/resolution/logic/InferenceVariableType.java +++ b/javaparser-core/src/main/java/com/github/javaparser/resolution/logic/InferenceVariableType.java @@ -111,9 +111,8 @@ public ResolvedType equivalentType() { if (concreteEquivalent.isEmpty()) { if (correspondingTp == null) { return new ReferenceTypeImpl(typeSolver.getSolvedJavaLangObject()); - } else { - return new ResolvedTypeVariable(correspondingTp); } + return new ResolvedTypeVariable(correspondingTp); } if (concreteEquivalent.size() == 1) { return concreteEquivalent.iterator().next(); @@ -123,15 +122,14 @@ public ResolvedType equivalentType() { .collect(Collectors.toSet()); if (notTypeVariables.size() == 1) { return notTypeVariables.iterator().next(); - } else if (notTypeVariables.size() == 0 && !superTypes.isEmpty()) { + } + if (notTypeVariables.size() == 0 && !superTypes.isEmpty()) { if (superTypes.size() == 1) { return superTypes.iterator().next(); - } else { - throw new IllegalStateException("Super types are: " + superTypes); } - } else { - throw new IllegalStateException("Equivalent types are: " + equivalentTypes); + throw new IllegalStateException("Super types are: " + superTypes); } + throw new IllegalStateException("Equivalent types are: " + equivalentTypes); } private boolean hasInferenceVariables(ResolvedType type){ diff --git a/javaparser-core/src/main/java/com/github/javaparser/resolution/logic/MethodResolutionLogic.java b/javaparser-core/src/main/java/com/github/javaparser/resolution/logic/MethodResolutionLogic.java index 9b68c78bf3..91aa72e61f 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/resolution/logic/MethodResolutionLogic.java +++ b/javaparser-core/src/main/java/com/github/javaparser/resolution/logic/MethodResolutionLogic.java @@ -337,15 +337,15 @@ private static boolean isAssignableMatchTypeParametersMatchingQName(ResolvedRefe if (!expectedParam.equals(actualParam)) { return false; } - } else if (expectedParam.isWildcard()) { + } + if (expectedParam.isWildcard()) { if (expectedParam.asWildcard().isExtends()) { return isAssignableMatchTypeParameters(expectedParam.asWildcard().getBoundedType(), actual, matchedParameters); } // TODO verify super bound return true; - } else { - throw new UnsupportedOperationException(expectedParam.describe()); } + throw new UnsupportedOperationException(expectedParam.describe()); } return true; } @@ -356,7 +356,8 @@ private static boolean matchTypeVariable(ResolvedTypeVariable typeVariable, Reso ResolvedType matchedParameter = matchedParameters.get(typeParameterName); if (matchedParameter.isAssignableBy(type)) { return true; - } else if (type.isAssignableBy(matchedParameter)) { + } + if (type.isAssignableBy(matchedParameter)) { // update matchedParameters to contain the more general type matchedParameters.put(typeParameterName, type); return true; @@ -823,9 +824,9 @@ public static Optional findMostApplicableUsage(List me } if (applicableMethods.size() == 1) { return Optional.of(applicableMethods.get(0)); - } else { - MethodUsage winningCandidate = applicableMethods.get(0); - for (int i = 1; i < applicableMethods.size(); i++) { + } + MethodUsage winningCandidate = applicableMethods.get(0); + for (int i = 1; i < applicableMethods.size(); i++) { MethodUsage other = applicableMethods.get(i); if (isMoreSpecific(winningCandidate, other)) { // nothing to do @@ -842,8 +843,7 @@ public static Optional findMostApplicableUsage(List me } } } - return Optional.of(winningCandidate); - } + return Optional.of(winningCandidate); } private static boolean areOverride(MethodUsage winningCandidate, MethodUsage other) { diff --git a/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedArrayType.java b/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedArrayType.java index 4150fd7f16..83c635298b 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedArrayType.java +++ b/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedArrayType.java @@ -112,9 +112,8 @@ public ResolvedType replaceTypeVariables(ResolvedTypeParameterDeclaration tpToRe ResolvedType baseTypeReplaced = baseType.replaceTypeVariables(tpToReplace, replaced, inferredTypes); if (baseTypeReplaced == baseType) { return this; - } else { - return new ResolvedArrayType(baseTypeReplaced); } + return new ResolvedArrayType(baseTypeReplaced); } // / diff --git a/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedIntersectionType.java b/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedIntersectionType.java index 9c101b44c9..5fb4e1aa62 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedIntersectionType.java +++ b/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedIntersectionType.java @@ -71,8 +71,7 @@ public ResolvedType replaceTypeVariables(ResolvedTypeParameterDeclaration tp, Re List elementsReplaced = elements.stream().map(e -> e.replaceTypeVariables(tp, replaced, inferredTypes)).collect(Collectors.toList()); if (elementsReplaced.equals(elements)) { return this; - } else { - return new ResolvedIntersectionType(elementsReplaced); } + return new ResolvedIntersectionType(elementsReplaced); } } diff --git a/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedPrimitiveType.java b/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedPrimitiveType.java index d29e58fbde..3121c92bd4 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedPrimitiveType.java +++ b/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedPrimitiveType.java @@ -140,7 +140,8 @@ public boolean isTypeVariable() { public boolean isAssignableBy(ResolvedType other) { if (other.isPrimitive()) { return this == other || promotionTypes.contains(other); - } else if (other.isReferenceType()) { + } + if (other.isReferenceType()) { if (other.asReferenceType().getQualifiedName().equals(getBoxTypeQName())) { return true; } @@ -150,9 +151,8 @@ public boolean isAssignableBy(ResolvedType other) { } } return false; - } else { - return other.isConstraint() && this.isAssignableBy(other.asConstraintType().getBound()); } + return other.isConstraint() && this.isAssignableBy(other.asConstraintType().getBound()); } public String getBoxTypeQName() { @@ -182,14 +182,16 @@ public boolean isBoolean() { * If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8). */ public ResolvedPrimitiveType bnp(ResolvedPrimitiveType other) { - // If either operand is of type double, the other is converted to double. + if (this == ResolvedPrimitiveType.DOUBLE || other == ResolvedPrimitiveType.DOUBLE) { return ResolvedPrimitiveType.DOUBLE; // Otherwise, if either operand is of type float, the other is converted to float. - } else if (this == ResolvedPrimitiveType.FLOAT || other == ResolvedPrimitiveType.FLOAT) { + } + if (this == ResolvedPrimitiveType.FLOAT || other == ResolvedPrimitiveType.FLOAT) { return ResolvedPrimitiveType.FLOAT; // Otherwise, if either operand is of type long, the other is converted to long. - } else if (this == ResolvedPrimitiveType.LONG || other == ResolvedPrimitiveType.LONG) { + } + if (this == ResolvedPrimitiveType.LONG || other == ResolvedPrimitiveType.LONG) { return ResolvedPrimitiveType.LONG; } // Otherwise, both operands are converted to type int. diff --git a/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedReferenceType.java b/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedReferenceType.java index 4763c71eeb..d7538b0421 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedReferenceType.java +++ b/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedReferenceType.java @@ -470,9 +470,11 @@ protected boolean compareConsideringTypeParameters(ResolvedReferenceType other) List thisBounds = thisParam.asTypeVariable().asTypeParameter().getBounds().stream().map(ResolvedTypeParameterDeclaration.Bound::getType).collect(Collectors.toList()); List otherBounds = otherParam.asTypeVariable().asTypeParameter().getBounds().stream().map(ResolvedTypeParameterDeclaration.Bound::getType).collect(Collectors.toList()); return thisBounds.size() == otherBounds.size() && otherBounds.containsAll(thisBounds); - } else if (!(thisParam instanceof ResolvedTypeVariable) && otherParam instanceof ResolvedTypeVariable) { + } + if (!(thisParam instanceof ResolvedTypeVariable) && otherParam instanceof ResolvedTypeVariable) { return compareConsideringVariableTypeParameters(thisParam, (ResolvedTypeVariable) otherParam); - } else if (thisParam instanceof ResolvedTypeVariable && !(otherParam instanceof ResolvedTypeVariable)) { + } + if (thisParam instanceof ResolvedTypeVariable && !(otherParam instanceof ResolvedTypeVariable)) { return compareConsideringVariableTypeParameters(otherParam, (ResolvedTypeVariable) thisParam); } return false; diff --git a/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedType.java b/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedType.java index 1c319dce78..f6ab1721ab 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedType.java +++ b/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedType.java @@ -67,9 +67,8 @@ default boolean isArray() { default int arrayLevel() { if (isArray()) { return 1 + this.asArrayType().getComponentType().arrayLevel(); - } else { - return 0; } + return 0; } /** diff --git a/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedTypeVariable.java b/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedTypeVariable.java index e3c3d1d0d0..eb149825b5 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedTypeVariable.java +++ b/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedTypeVariable.java @@ -80,9 +80,8 @@ public ResolvedType replaceTypeVariables(ResolvedTypeParameterDeclaration tpToBe if (tpToBeReplaced.getName().equals(this.typeParameter.getName())) { inferredTypes.put(this.asTypeParameter(), replaced); return replaced; - } else { - return this; } + return this; } @Override @@ -114,9 +113,8 @@ public boolean isTypeVariable() { public boolean isAssignableBy(ResolvedType other) { if (other.isTypeVariable()) { return describe().equals(other.describe()); - } else { - return true; } + return true; } @Override diff --git a/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedWildcard.java b/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedWildcard.java index 37b7ef4e76..3054a899bb 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedWildcard.java +++ b/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedWildcard.java @@ -102,13 +102,14 @@ public int hashCode() { public String describe() { if (type == null) { return "?"; - } else if (type == BoundType.SUPER) { + } + if (type == BoundType.SUPER) { return "? super " + boundedType.describe(); - } else if (type == BoundType.EXTENDS) { + } + if (type == BoundType.EXTENDS) { return "? extends " + boundedType.describe(); - } else { - throw new UnsupportedOperationException(); } + throw new UnsupportedOperationException(); } public boolean isSuper() { @@ -135,13 +136,14 @@ public boolean isAssignableBy(ResolvedType other) { if (boundedType == null) { // return other.isReferenceType() && other.asReferenceType().getQualifiedName().equals(Object.class.getCanonicalName()); return false; - } else if (type == BoundType.SUPER) { + } + if (type == BoundType.SUPER) { return boundedType.isAssignableBy(other); - } else if (type == BoundType.EXTENDS) { + } + if (type == BoundType.EXTENDS) { return false; - } else { - throw new RuntimeException(); } + throw new RuntimeException(); } @Override @@ -158,9 +160,8 @@ public ResolvedType replaceTypeVariables(ResolvedTypeParameterDeclaration tpToRe } if (boundedTypeReplaced != boundedType) { return new ResolvedWildcard(type, boundedTypeReplaced); - } else { - return this; } + return this; } @Override @@ -190,9 +191,8 @@ public ResolvedType solveGenericTypes(Context context) { ResolvedType boundResolved = getBoundedType().solveGenericTypes(context); if (isExtends()) { return ResolvedWildcard.extendsBound(boundResolved); - } else { - return ResolvedWildcard.superBound(boundResolved); } + return ResolvedWildcard.superBound(boundResolved); } return this; } diff --git a/javaparser-core/src/main/java/com/github/javaparser/resolution/types/parametrization/ResolvedTypeParameterValueProvider.java b/javaparser-core/src/main/java/com/github/javaparser/resolution/types/parametrization/ResolvedTypeParameterValueProvider.java index 14d2f88849..d3a5f27f71 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/resolution/types/parametrization/ResolvedTypeParameterValueProvider.java +++ b/javaparser-core/src/main/java/com/github/javaparser/resolution/types/parametrization/ResolvedTypeParameterValueProvider.java @@ -54,9 +54,8 @@ default ResolvedType useThisTypeParametersOnTheGivenType(ResolvedType type) { if (type.isWildcard() && type.asWildcard().isBounded()) { if (type.asWildcard().isExtends()) { return ResolvedWildcard.extendsBound(useThisTypeParametersOnTheGivenType(type.asWildcard().getBoundedType())); - } else { - return ResolvedWildcard.superBound(useThisTypeParametersOnTheGivenType(type.asWildcard().getBoundedType())); } + return ResolvedWildcard.superBound(useThisTypeParametersOnTheGivenType(type.asWildcard().getBoundedType())); } if (type.isReferenceType()) { type = type.asReferenceType().transformTypeParameters(this::useThisTypeParametersOnTheGivenType); diff --git a/javaparser-core/src/main/java/com/github/javaparser/resolution/types/parametrization/ResolvedTypeParametersMap.java b/javaparser-core/src/main/java/com/github/javaparser/resolution/types/parametrization/ResolvedTypeParametersMap.java index b7e03bd9a2..4ef48be77a 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/resolution/types/parametrization/ResolvedTypeParametersMap.java +++ b/javaparser-core/src/main/java/com/github/javaparser/resolution/types/parametrization/ResolvedTypeParametersMap.java @@ -103,17 +103,15 @@ public ResolvedType getValue(ResolvedTypeParameterDeclaration typeParameter) { String qualifiedName = typeParameter.getQualifiedName(); if (nameToValue.containsKey(qualifiedName)) { return nameToValue.get(qualifiedName); - } else { - return new ResolvedTypeVariable(typeParameter); } + return new ResolvedTypeVariable(typeParameter); } public Optional getValueBySignature(String signature) { if (nameToValue.containsKey(signature)) { return Optional.of(nameToValue.get(signature)); - } else { - return Optional.empty(); } + return Optional.empty(); } public List getNames() { diff --git a/javaparser-core/src/main/java/com/github/javaparser/utils/CodeGenerationUtils.java b/javaparser-core/src/main/java/com/github/javaparser/utils/CodeGenerationUtils.java index bc4ca155a8..500891cf89 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/utils/CodeGenerationUtils.java +++ b/javaparser-core/src/main/java/com/github/javaparser/utils/CodeGenerationUtils.java @@ -39,7 +39,8 @@ private CodeGenerationUtils() { public static String getterName(Class type, String name) { if (name.startsWith("is") && boolean.class.equals(type)) { return name; - } else if (Boolean.TYPE.equals(type)) { + } + if (Boolean.TYPE.equals(type)) { return "is" + capitalize(name); } return "get" + capitalize(name); @@ -48,9 +49,11 @@ public static String getterName(Class type, String name) { public static String getterToPropertyName(String getterName) { if (getterName.startsWith("is")) { return decapitalize(getterName.substring("is".length())); - } else if (getterName.startsWith("get")) { + } + if (getterName.startsWith("get")) { return decapitalize(getterName.substring("get".length())); - } else if (getterName.startsWith("has")) { + } + if (getterName.startsWith("has")) { return decapitalize(getterName.substring("has".length())); } throw new IllegalArgumentException("Unexpected getterName '" + getterName + "'"); @@ -66,9 +69,8 @@ public static String setterName(String fieldName) { public static String optionalOf(String text, boolean isOptional) { if (isOptional) { return f("Optional.of(%s)", text); - } else { - return "Optional.empty()"; } + return "Optional.empty()"; } /** diff --git a/javaparser-core/src/main/java/com/github/javaparser/utils/CollectionStrategy.java b/javaparser-core/src/main/java/com/github/javaparser/utils/CollectionStrategy.java index 1a48126ef9..d41947bc1a 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/utils/CollectionStrategy.java +++ b/javaparser-core/src/main/java/com/github/javaparser/utils/CollectionStrategy.java @@ -55,16 +55,13 @@ default Optional getRoot(Path file) { return Optional.empty(); } return storage.map(CompilationUnit.Storage::getSourceRoot); - } else { - Log.info("Storage information not present -- an issue with providing a string rather than file reference?"); } - } else { - Log.info("Parse result not present"); + Log.info("Storage information not present -- an issue with providing a string rather than file reference?"); } - } else { - Log.info("Parsing was not successful."); - Log.info("There were (%d) problems parsing file: %s", () -> parseResult.getProblems().size(), parseResult::getProblems); + Log.info("Parse result not present"); } + Log.info("Parsing was not successful."); + Log.info("There were (%d) problems parsing file: %s", () -> parseResult.getProblems().size(), parseResult::getProblems); } catch (ParseProblemException e) { Log.info("Problem parsing file %s : %s", () -> file, () -> e.getLocalizedMessage()); } catch (RuntimeException e) { diff --git a/javaparser-core/src/main/java/com/github/javaparser/utils/LineSeparator.java b/javaparser-core/src/main/java/com/github/javaparser/utils/LineSeparator.java index 41fa775fa6..a27aa8aa11 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/utils/LineSeparator.java +++ b/javaparser-core/src/main/java/com/github/javaparser/utils/LineSeparator.java @@ -122,25 +122,27 @@ public static LineSeparator getLineEnding(int countCr, int countLf, int countCrL public static Optional lookup(String ending) { if (CR.asRawString().equals(ending)) { return Optional.of(CR); - } else if (LF.asRawString().equals(ending)) { + } + if (LF.asRawString().equals(ending)) { return Optional.of(LF); - } else if (CRLF.asRawString().equals(ending)) { + } + if (CRLF.asRawString().equals(ending)) { return Optional.of(CRLF); - } else { - return Optional.empty(); } + return Optional.empty(); } public static Optional lookupEscaped(String ending) { if (CR.asEscapedString().equals(ending)) { return Optional.of(CR); - } else if (LF.asEscapedString().equals(ending)) { + } + if (LF.asEscapedString().equals(ending)) { return Optional.of(LF); - } else if (CRLF.asEscapedString().equals(ending)) { + } + if (CRLF.asEscapedString().equals(ending)) { return Optional.of(CRLF); - } else { - return Optional.empty(); } + return Optional.empty(); } public String describe() { diff --git a/javaparser-core/src/main/java/com/github/javaparser/utils/PositionUtils.java b/javaparser-core/src/main/java/com/github/javaparser/utils/PositionUtils.java index b2bdb6840d..88ccd0722d 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/utils/PositionUtils.java +++ b/javaparser-core/src/main/java/com/github/javaparser/utils/PositionUtils.java @@ -76,18 +76,16 @@ private static int compare(Node a, Node b, boolean ignoringAnnotations) { int signLine = signum(beginLineWithoutConsideringAnnotation(a) - beginLineWithoutConsideringAnnotation(b)); if (signLine == 0) { return signum(beginColumnWithoutConsideringAnnotation(a) - beginColumnWithoutConsideringAnnotation(b)); - } else { - return signLine; } + return signLine; } Position aBegin = a.getBegin().get(); Position bBegin = b.getBegin().get(); int signLine = signum(aBegin.line - bBegin.line); if (signLine == 0) { return signum(aBegin.column - bBegin.column); - } else { - return signLine; } + return signLine; } public static AnnotationExpr getLastAnnotation(Node node) { @@ -98,9 +96,8 @@ public static AnnotationExpr getLastAnnotation(Node node) { } sortByBeginPosition(annotations); return annotations.get(annotations.size() - 1); - } else { - return null; } + return null; } private static int beginLineWithoutConsideringAnnotation(Node node) { @@ -112,37 +109,35 @@ private static int beginColumnWithoutConsideringAnnotation(Node node) { } private static Node firstNonAnnotationNode(Node node) { - // TODO: Consider the remaining "types" of thing that annotations can target ( https://docs.oracle.com/javase/8/docs/api/java/lang/annotation/ElementType.html ) + if (node instanceof ClassOrInterfaceDeclaration) { // Modifiers appear before the class name -- ClassOrInterfaceDeclaration casted = (ClassOrInterfaceDeclaration) node; Modifier earliestModifier = casted.getModifiers().stream().filter(modifier -> modifier.hasRange()).min(Comparator.comparing(o -> o.getRange().get().begin)).orElse(null); if (earliestModifier == null) { return casted.getName(); - } else { - return earliestModifier; } - } else if (node instanceof MethodDeclaration) { + return earliestModifier; + } + if (node instanceof MethodDeclaration) { // Modifiers appear before the class name -- MethodDeclaration casted = (MethodDeclaration) node; Modifier earliestModifier = casted.getModifiers().stream().filter(modifier -> modifier.hasRange()).min(Comparator.comparing(o -> o.getRange().get().begin)).orElse(null); if (earliestModifier == null) { return casted.getType(); - } else { - return earliestModifier; } - } else if (node instanceof FieldDeclaration) { + return earliestModifier; + } + if (node instanceof FieldDeclaration) { // Modifiers appear before the class name -- FieldDeclaration casted = (FieldDeclaration) node; Modifier earliestModifier = casted.getModifiers().stream().filter(modifier -> modifier.hasRange()).min(Comparator.comparing(o -> o.getRange().get().begin)).orElse(null); if (earliestModifier == null) { return casted.getVariable(0).getType(); - } else { - return earliestModifier; } - } else { - return node; + return earliestModifier; } + return node; } /** diff --git a/javaparser-core/src/main/java/com/github/javaparser/utils/SourceRoot.java b/javaparser-core/src/main/java/com/github/javaparser/utils/SourceRoot.java index 0d128592f2..af8058d160 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/utils/SourceRoot.java +++ b/javaparser-core/src/main/java/com/github/javaparser/utils/SourceRoot.java @@ -595,9 +595,8 @@ public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) th w.fork(); walks.add(w); return SKIP_SUBTREE; - } else { - return CONTINUE; } + return CONTINUE; } @Override diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/SourceFileInfoExtractor.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/SourceFileInfoExtractor.java index 82527a7911..22e86f6576 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/SourceFileInfoExtractor.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/SourceFileInfoExtractor.java @@ -173,9 +173,8 @@ private String toString(MethodCallExpr node) { private String toString(SymbolReference methodDeclarationSymbolReference) { if (methodDeclarationSymbolReference.isSolved()) { return methodDeclarationSymbolReference.getCorrespondingDeclaration().getQualifiedSignature(); - } else { - return "UNSOLVED"; } + return "UNSOLVED"; } private List collectAllNodes(Node node) { diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/JavaParserFacade.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/JavaParserFacade.java index 014fc34be6..3c80746e73 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/JavaParserFacade.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/JavaParserFacade.java @@ -292,9 +292,8 @@ public SymbolReference solve(AnnotationExpr annot if (typeDeclarationSymbolReference.isSolved()) { ResolvedAnnotationDeclaration annotationDeclaration = (ResolvedAnnotationDeclaration) typeDeclarationSymbolReference.getCorrespondingDeclaration(); return solved(annotationDeclaration); - } else { - return unsolved(); } + return unsolved(); } public SymbolReference solve(FieldAccessExpr fieldAccessExpr) { @@ -370,21 +369,20 @@ public ResolvedType getType(Node node, boolean solveLambdas) { Log.trace("getType on %s -> %s", () -> node, () -> res); } return node.getData(TYPE_WITH_LAMBDAS_RESOLVED); - } else { - Optional res = find(TYPE_WITH_LAMBDAS_RESOLVED, node); - if (res.isPresent()) { + } + Optional res = find(TYPE_WITH_LAMBDAS_RESOLVED, node); + if (res.isPresent()) { return res.get(); } - res = find(TYPE_WITHOUT_LAMBDAS_RESOLVED, node); - if (!res.isPresent()) { + res = find(TYPE_WITHOUT_LAMBDAS_RESOLVED, node); + if (!res.isPresent()) { ResolvedType resType = getTypeConcrete(node, solveLambdas); node.setData(TYPE_WITHOUT_LAMBDAS_RESOLVED, resType); Optional finalRes = res; Log.trace("getType on %s (no solveLambdas) -> %s", () -> node, () -> finalRes); return resType; } - return res.get(); - } + return res.get(); } private Optional find(DataKey dataKey, Node node) { @@ -560,10 +558,10 @@ protected Node findContainingTypeDeclOrObjectCreationExpr(Node node) { if (parent instanceof BodyDeclaration) { if (parent instanceof TypeDeclaration) { return parent; - } else { - detachFlag = true; } - } else if (parent instanceof ObjectCreationExpr) { + detachFlag = true; + } + if (parent instanceof ObjectCreationExpr) { if (detachFlag) { return parent; } @@ -583,10 +581,10 @@ protected Node findContainingTypeDeclOrObjectCreationExpr(Node node, String clas if (parent instanceof BodyDeclaration) { if (parent instanceof TypeDeclaration && ((TypeDeclaration) parent).getFullyQualifiedName().get().endsWith(className)) { return parent; - } else { - detachFlag = true; } - } else if (parent instanceof ObjectCreationExpr && ((ObjectCreationExpr) parent).getType().getName().asString().equals(className)) { + detachFlag = true; + } + if (parent instanceof ObjectCreationExpr && ((ObjectCreationExpr) parent).getType().getName().asString().equals(className)) { if (detachFlag) { return parent; } @@ -629,9 +627,8 @@ private Optional forEachStmtWithVariableDeclarator( node = node.get().getParentNode(); if (!node.isPresent() || !(node.get() instanceof ForEachStmt)) { return Optional.empty(); - } else { - return Optional.of((ForEachStmt)node.get()); } + return Optional.of((ForEachStmt)node.get()); } public ResolvedType convert(Type type, Node node) { diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/JavaParserFactory.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/JavaParserFactory.java index 9c5eaafcc0..de9b56759b 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/JavaParserFactory.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/JavaParserFactory.java @@ -45,64 +45,90 @@ public static Context getContext(Node node, TypeSolver typeSolver) { throw new NullPointerException("Node should not be null"); } - // TODO: Is order important here? + if (node instanceof ArrayAccessExpr) { return new ArrayAccessExprContext((ArrayAccessExpr) node, typeSolver); - } else if (node instanceof AnnotationDeclaration) { + } + if (node instanceof AnnotationDeclaration) { return new AnnotationDeclarationContext((AnnotationDeclaration) node, typeSolver); - } else if (node instanceof BinaryExpr) { + } + if (node instanceof BinaryExpr) { return new BinaryExprContext((BinaryExpr) node, typeSolver); - } else if (node instanceof BlockStmt) { + } + if (node instanceof BlockStmt) { return new BlockStmtContext((BlockStmt) node, typeSolver); - } else if (node instanceof CompilationUnit) { + } + if (node instanceof CompilationUnit) { return new CompilationUnitContext((CompilationUnit) node, typeSolver); - } else if (node instanceof EnclosedExpr) { + } + if (node instanceof EnclosedExpr) { return new EnclosedExprContext((EnclosedExpr) node, typeSolver); - } else if (node instanceof ForEachStmt) { + } + if (node instanceof ForEachStmt) { return new ForEachStatementContext((ForEachStmt) node, typeSolver); - } else if (node instanceof ForStmt) { + } + if (node instanceof ForStmt) { return new ForStatementContext((ForStmt) node, typeSolver); - } else if (node instanceof IfStmt) { + } + if (node instanceof IfStmt) { return new IfStatementContext((IfStmt) node, typeSolver); - } else if (node instanceof InstanceOfExpr) { + } + if (node instanceof InstanceOfExpr) { return new InstanceOfExprContext((InstanceOfExpr) node, typeSolver); - } else if (node instanceof LambdaExpr) { + } + if (node instanceof LambdaExpr) { return new LambdaExprContext((LambdaExpr) node, typeSolver); - } else if (node instanceof MethodDeclaration) { + } + if (node instanceof MethodDeclaration) { return new MethodContext((MethodDeclaration) node, typeSolver); - } else if (node instanceof ConstructorDeclaration) { + } + if (node instanceof ConstructorDeclaration) { return new ConstructorContext((ConstructorDeclaration) node, typeSolver); - } else if (node instanceof ClassOrInterfaceDeclaration) { + } + if (node instanceof ClassOrInterfaceDeclaration) { return new ClassOrInterfaceDeclarationContext((ClassOrInterfaceDeclaration) node, typeSolver); - } else if (node instanceof MethodCallExpr) { + } + if (node instanceof MethodCallExpr) { return new MethodCallExprContext((MethodCallExpr) node, typeSolver); - } else if (node instanceof MethodReferenceExpr) { + } + if (node instanceof MethodReferenceExpr) { return new MethodReferenceExprContext((MethodReferenceExpr) node, typeSolver); - } else if (node instanceof EnumDeclaration) { + } + if (node instanceof EnumDeclaration) { return new EnumDeclarationContext((EnumDeclaration) node, typeSolver); - } else if (node instanceof FieldAccessExpr) { + } + if (node instanceof FieldAccessExpr) { return new FieldAccessContext((FieldAccessExpr) node, typeSolver); - } else if (node instanceof SwitchEntry) { + } + if (node instanceof SwitchEntry) { return new SwitchEntryContext((SwitchEntry) node, typeSolver); - } else if (node instanceof TryStmt) { + } + if (node instanceof TryStmt) { return new TryWithResourceContext((TryStmt) node, typeSolver); - } else if (node instanceof Statement) { + } + if (node instanceof Statement) { return new StatementContext<>((Statement) node, typeSolver); - } else if (node instanceof CatchClause) { + } + if (node instanceof CatchClause) { return new CatchClauseContext((CatchClause) node, typeSolver); - } else if (node instanceof UnaryExpr) { + } + if (node instanceof UnaryExpr) { return new UnaryExprContext((UnaryExpr) node, typeSolver); - } else if (node instanceof VariableDeclarator) { + } + if (node instanceof VariableDeclarator) { return new VariableDeclaratorContext((VariableDeclarator) node, typeSolver); - } else if (node instanceof VariableDeclarationExpr) { + } + if (node instanceof VariableDeclarationExpr) { return new VariableDeclarationExprContext((VariableDeclarationExpr) node, typeSolver); - } else if (node instanceof ObjectCreationExpr && + } + if (node instanceof ObjectCreationExpr && ((ObjectCreationExpr) node).getAnonymousClassBody().isPresent()) { return new AnonymousClassDeclarationContext((ObjectCreationExpr) node, typeSolver); - } else if (node instanceof ObjectCreationExpr) { + } + if (node instanceof ObjectCreationExpr) { return new ObjectCreationContext((ObjectCreationExpr)node, typeSolver); - } else { - if (node instanceof NameExpr) { + } + if (node instanceof NameExpr) { // to resolve a name when in a fieldAccess context, we can go up until we get a node other than FieldAccessExpr, // in order to prevent a infinite loop if the name is the same as the field (ie x.x, x.y.x, or x.y.z.x) if (node.getParentNode().isPresent() && node.getParentNode().get() instanceof FieldAccessExpr) { @@ -119,8 +145,8 @@ public static Context getContext(Node node, TypeSolver typeSolver) { return getContext(node.getParentNode().get().getParentNode().get(), typeSolver); } } - final Node parentNode = demandParentNode(node); - if (node instanceof ClassOrInterfaceType && parentNode instanceof ClassOrInterfaceDeclaration) { + final Node parentNode = demandParentNode(node); + if (node instanceof ClassOrInterfaceType && parentNode instanceof ClassOrInterfaceDeclaration) { ClassOrInterfaceDeclaration parentDeclaration = (ClassOrInterfaceDeclaration) parentNode; if (parentDeclaration.getImplementedTypes().contains(node) || parentDeclaration.getExtendedTypes().contains(node)) { @@ -129,8 +155,7 @@ public static Context getContext(Node node, TypeSolver typeSolver) { return new ClassOrInterfaceDeclarationExtendsContext(parentDeclaration, typeSolver); } } - return getContext(parentNode, typeSolver); - } + return getContext(parentNode, typeSolver); } public static SymbolDeclarator getSymbolDeclarator(Node node, TypeSolver typeSolver) { diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/TypeExtractor.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/TypeExtractor.java index 6689cb276e..54528547dc 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/TypeExtractor.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/TypeExtractor.java @@ -83,7 +83,8 @@ public TypeExtractor(TypeSolver typeSolver, JavaParserFacade facade) { public ResolvedType visit(VariableDeclarator node, Boolean solveLambdas) { if (demandParentNode(node) instanceof FieldDeclaration) { return facade.convertToUsage(node.getType()); - } else if (demandParentNode(node) instanceof VariableDeclarationExpr) { + } + if (demandParentNode(node) instanceof VariableDeclarationExpr) { return facade.convertToUsage(node.getType()); } throw new UnsupportedOperationException(demandParentNode(node).getClass().getCanonicalName()); @@ -213,16 +214,17 @@ public ResolvedType visit(EnclosedExpr node, Boolean solveLambdas) { */ private ResolvedType solveDotExpressionType(ResolvedReferenceTypeDeclaration parentType, FieldAccessExpr node) { // Fields and internal type declarations cannot have the same name. - // Thus, these checks will always be mutually exclusive. + if (parentType.isEnum() && parentType.asEnum().hasEnumConstant(node.getName().getId())) { return parentType.asEnum().getEnumConstant(node.getName().getId()).getType(); - } else if (parentType.hasField(node.getName().getId())) { + } + if (parentType.hasField(node.getName().getId())) { return parentType.getField(node.getName().getId()).getType(); - } else if (parentType.hasInternalType(node.getName().getId())) { + } + if (parentType.hasInternalType(node.getName().getId())) { return new ReferenceTypeImpl(parentType.getInternalType(node.getName().getId())); - } else { - throw new UnsolvedSymbolException(node.getName().getId()); } + throw new UnsolvedSymbolException(node.getName().getId()); } @Override @@ -333,9 +335,8 @@ public ResolvedType visit(NameExpr node, Boolean solveLambdas) { Optional value = createSolver().solveSymbolAsValue(node.getName().getId(), node); if (!value.isPresent()) { throw new UnsolvedSymbolException("Solving " + node, node.getName().getId()); - } else { - return value.get().getType(); } + return value.get().getType(); } @Override @@ -404,24 +405,22 @@ public ResolvedType visit(SuperExpr node, Boolean solveLambdas) { ResolvedTypeDeclaration resolvedTypeName = resolvedTypeNameRef.getCorrespondingDeclaration(); if (resolvedTypeName.isInterface()) { return new ReferenceTypeImpl(resolvedTypeName.asInterface()); - } else if (resolvedTypeName.isClass()) { + } + if (resolvedTypeName.isClass()) { // TODO: Maybe include a presence check? e.g. in the case of `java.lang.Object` there will be no superclass. return resolvedTypeName.asClass().getSuperClass().orElseThrow(() -> new RuntimeException("super class unexpectedly empty")); - } else { - throw new UnsupportedOperationException(node.getClass().getCanonicalName()); } - } else { - throw new UnsolvedSymbolException(className); + throw new UnsupportedOperationException(node.getClass().getCanonicalName()); } + throw new UnsolvedSymbolException(className); } ResolvedTypeDeclaration typeOfNode = facade.getTypeDeclaration(facade.findContainingTypeDeclOrObjectCreationExpr(node)); if (typeOfNode instanceof ResolvedClassDeclaration) { // TODO: Maybe include a presence check? e.g. in the case of `java.lang.Object` there will be no superclass. return ((ResolvedClassDeclaration) typeOfNode).getSuperClass().orElseThrow(() -> new RuntimeException("super class unexpectedly empty")); - } else { - throw new UnsupportedOperationException(node.getClass().getCanonicalName()); } + throw new UnsupportedOperationException(node.getClass().getCanonicalName()); } @Override @@ -496,8 +495,8 @@ public ResolvedType visit(LambdaExpr node, Boolean solveLambdas) { result = resolveLambda(node, result); } return result; - } else if (demandParentNode(node) instanceof VariableDeclarator) - { + } + if (demandParentNode(node) instanceof VariableDeclarator) { VariableDeclarator decExpr = (VariableDeclarator) demandParentNode(node); ResolvedType result = decExpr.getType().resolve(); @@ -505,7 +504,8 @@ public ResolvedType visit(LambdaExpr node, Boolean solveLambdas) { result = resolveLambda(node, result); } return result; - } else if (demandParentNode(node) instanceof AssignExpr) { + } + if (demandParentNode(node) instanceof AssignExpr) { AssignExpr assExpr = (AssignExpr) demandParentNode(node); ResolvedType result = assExpr.calculateResolvedType(); @@ -513,9 +513,8 @@ public ResolvedType visit(LambdaExpr node, Boolean solveLambdas) { result = resolveLambda(node, result); } return result; - } else { - throw new UnsupportedOperationException("The type of a lambda expr depends on the position and its return value"); } + throw new UnsupportedOperationException("The type of a lambda expr depends on the position and its return value"); } private ResolvedType resolveLambda(LambdaExpr node, ResolvedType result) { diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/AbstractJavaParserContext.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/AbstractJavaParserContext.java index 6f6c60fe16..fc00797b6b 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/AbstractJavaParserContext.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/AbstractJavaParserContext.java @@ -157,10 +157,11 @@ public SymbolReference solveSymbolInParentCo .findFirst(); if (localResolutionResults.isPresent()) { - if(patternExprs.size() == 1) { + if (patternExprs.size() == 1) { JavaParserPatternDeclaration decl = JavaParserSymbolDeclaration.patternVar(localResolutionResults.get(), typeSolver); return SymbolReference.solved(decl); - } else if(patternExprs.size() > 1) { + } + if(patternExprs.size() > 1) { throw new IllegalStateException("Unexpectedly more than one reference in scope"); } } @@ -217,13 +218,14 @@ protected Collection findTypeDeclarations(Opti .getTypeDeclaration() .orElseThrow(() -> new RuntimeException("TypeDeclaration unexpectedly empty.")) ); - } else { - return singletonList(typeSolver.getSolvedJavaLangObject()); } - } else if (typeOfScope.isArray()) { + return singletonList(typeSolver.getSolvedJavaLangObject()); + } + if (typeOfScope.isArray()) { // method call on array are Object methods return singletonList(typeSolver.getSolvedJavaLangObject()); - } else if (typeOfScope.isTypeVariable()) { + } + if (typeOfScope.isTypeVariable()) { Collection result = new ArrayList<>(); for (ResolvedTypeParameterDeclaration.Bound bound : typeOfScope.asTypeParameter().getBounds()) { // TODO: Figure out if it is appropriate to remove the orElseThrow() -- if so, how... @@ -235,7 +237,8 @@ protected Collection findTypeDeclarations(Opti ); } return result; - } else if (typeOfScope.isConstraint()) { + } + if (typeOfScope.isConstraint()) { // TODO: Figure out if it is appropriate to remove the orElseThrow() -- if so, how... ResolvedType type = typeOfScope.asConstraintType().getBound(); if (type.isReferenceType()) { @@ -243,10 +246,10 @@ protected Collection findTypeDeclarations(Opti type.asReferenceType().getTypeDeclaration() .orElseThrow(() -> new RuntimeException("TypeDeclaration unexpectedly empty.")) ); - } else { - throw new UnsupportedOperationException("The type declaration cannot be found on constraint "+ type.describe()); } - } else if (typeOfScope.isUnionType()) { + throw new UnsupportedOperationException("The type declaration cannot be found on constraint "+ type.describe()); + } + if (typeOfScope.isUnionType()) { return typeOfScope.asUnionType().getCommonAncestor() .flatMap(ResolvedReferenceType::getTypeDeclaration) .map(Collections::singletonList) @@ -289,9 +292,8 @@ public Optional solveMethodAsUsage(String name, List MethodUsage methodUsage = ((TypeVariableResolutionCapability) methodDeclaration).resolveTypeVariables(this, argumentsTypes); return Optional.of(methodUsage); - } else { - return Optional.empty(); } + return Optional.empty(); } @Override diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/AbstractMethodLikeDeclarationContext.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/AbstractMethodLikeDeclarationContext.java index bfa3509ded..cce4dd8357 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/AbstractMethodLikeDeclarationContext.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/AbstractMethodLikeDeclarationContext.java @@ -113,7 +113,8 @@ public final SymbolReference solveType(String name, Lis if (localType.getName().getId().equals(name)) { return SymbolReference.solved(JavaParserFacade.get(typeSolver) .getTypeDeclaration(localType)); - } else if (name.startsWith(String.format("%s.", localType.getName()))) { + } + if (name.startsWith(String.format("%s.", localType.getName()))) { return JavaParserFactory.getContext(localType, typeSolver) .solveType(name.substring(localType.getName().getId().length() + 1)); } diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/CompilationUnitContext.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/CompilationUnitContext.java index 61112b45fe..8a7be56cb2 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/CompilationUnitContext.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/CompilationUnitContext.java @@ -81,9 +81,8 @@ public SymbolReference solveSymbol(String na SymbolReference type = this.solveType(typeName); if (type.isSolved()) { return new SymbolSolver(typeSolver).solveSymbolInType(type.getCorrespondingDeclaration(), memberName); - } else { - itName = typeName; } + itName = typeName; } // Look among statically imported values @@ -129,13 +128,16 @@ public SymbolReference solveType(String name, List qualified.equals(name)).orElse(false)) { if (type instanceof ClassOrInterfaceDeclaration) { return SymbolReference.solved(JavaParserFacade.get(typeSolver).getTypeDeclaration((ClassOrInterfaceDeclaration) type)); - } else if (type instanceof AnnotationDeclaration) { + } + + if (type instanceof AnnotationDeclaration) { return SymbolReference.solved(new JavaParserAnnotationDeclaration((AnnotationDeclaration) type, typeSolver)); - } else if (type instanceof EnumDeclaration) { + } + + if (type instanceof EnumDeclaration) { return SymbolReference.solved(new JavaParserEnumDeclaration((EnumDeclaration) type, typeSolver)); - } else { - throw new UnsupportedOperationException(type.getClass().getCanonicalName()); } + throw new UnsupportedOperationException(type.getClass().getCanonicalName()); } } @@ -223,28 +225,25 @@ public SymbolReference solveType(String name, List solveMethod(String name, List< SymbolReference method = MethodResolutionLogic.solveMethodInType(ref, name, argumentsTypes, true); if (method.isSolved()) { return method; - } else { - return SymbolReference.unsolved(); } + return SymbolReference.unsolved(); } } } diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/ContextHelper.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/ContextHelper.java index 215ced0724..6d82865846 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/ContextHelper.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/ContextHelper.java @@ -46,8 +46,7 @@ public static Optional solveMethodAsUsage(ResolvedTypeDeclaration t if (typeDeclaration instanceof MethodUsageResolutionCapability) { return ((MethodUsageResolutionCapability) typeDeclaration) .solveMethodAsUsage(name, argumentsTypes, invokationContext, typeParameters); - } else { - throw new UnsupportedOperationException(typeDeclaration.toString()); } + throw new UnsupportedOperationException(typeDeclaration.toString()); } } diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/FieldAccessContext.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/FieldAccessContext.java index 4c804ad50d..54eed28196 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/FieldAccessContext.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/FieldAccessContext.java @@ -88,14 +88,13 @@ public Optional solveSymbolAsValue(String name) { } if (typeOfScope.isReferenceType()) { return solveSymbolAsValue(name, typeOfScope.asReferenceType()); - } else if (typeOfScope.isConstraint()) { + } + if (typeOfScope.isConstraint()) { return solveSymbolAsValue(name, typeOfScope.asConstraintType().getBound().asReferenceType()); - } else { - return Optional.empty(); } - } else { - return solveSymbolAsValueInParentContext(name); + return Optional.empty(); } + return solveSymbolAsValueInParentContext(name); } /* diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/ForEachStatementContext.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/ForEachStatementContext.java index cdb5feb315..378500f75e 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/ForEachStatementContext.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/ForEachStatementContext.java @@ -51,13 +51,11 @@ public SymbolReference solveSymbol(String na VariableDeclarator variableDeclarator = wrappedNode.getVariable().getVariables().get(0); if (variableDeclarator.getName().getId().equals(name)) { return SymbolReference.solved(JavaParserSymbolDeclaration.localVar(variableDeclarator, typeSolver)); - } else { - if (demandParentNode(wrappedNode) instanceof BlockStmt) { + } + if (demandParentNode(wrappedNode) instanceof BlockStmt) { return StatementContext.solveInBlock(name, typeSolver, wrappedNode); - } else { - return solveSymbolInParentContext(name); } - } + return solveSymbolInParentContext(name); } @Override diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/ForStatementContext.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/ForStatementContext.java index 0e48055874..206074f635 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/ForStatementContext.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/ForStatementContext.java @@ -61,9 +61,8 @@ public SymbolReference solveSymbol(String na if (demandParentNode(wrappedNode) instanceof NodeWithStatements) { return StatementContext.solveInBlock(name, typeSolver, wrappedNode); - } else { - return solveSymbolInParentContext(name); } + return solveSymbolInParentContext(name); } @Override diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/JavaParserTypeDeclarationAdapter.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/JavaParserTypeDeclarationAdapter.java index 0a99cd6950..8d7dce32e4 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/JavaParserTypeDeclarationAdapter.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/JavaParserTypeDeclarationAdapter.java @@ -86,9 +86,11 @@ public SymbolReference solveType(String name, List internalType = member.asTypeDeclaration(); if (internalType.getName().getId().equals(name) && compareTypeParameters(internalType, typeArguments)) { return SymbolReference.solved(JavaParserFacade.get(typeSolver).getTypeDeclaration(internalType)); - } else if (name.startsWith(wrappedNode.getName().getId() + "." + internalType.getName().getId())) { + } + if (name.startsWith(wrappedNode.getName().getId() + "." + internalType.getName().getId())) { return JavaParserFactory.getContext(internalType, typeSolver).solveType(name.substring(wrappedNode.getName().getId().length() + 1), typeArguments); - } else if (name.startsWith(internalType.getName().getId() + ".")) { + } + if (name.startsWith(internalType.getName().getId() + ".")) { return JavaParserFactory.getContext(internalType, typeSolver).solveType(name.substring(internalType.getName().getId().length() + 1), typeArguments); } } @@ -185,9 +187,8 @@ private > boolean compareTypeParameters(T ty private boolean compareTypeParameters(TypeDeclaration typeDeclaration, List resolvedTypeArguments) { if (typeDeclaration instanceof NodeWithTypeParameters) { return compareTypeParameters((NodeWithTypeParameters) typeDeclaration, resolvedTypeArguments); - } else { - return true; } + return true; } /** @@ -215,9 +216,8 @@ private ResolvedTypeDeclaration checkAncestorsForType(String name, ResolvedRefer if (internalTypeDeclaration.getName().equals(name)) { if (visible) { return internalTypeDeclaration; - } else { - return null; // FIXME -- Avoid returning null. } + return null; } } diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/LambdaExprContext.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/LambdaExprContext.java index 5e9c133646..46841127a3 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/LambdaExprContext.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/LambdaExprContext.java @@ -77,7 +77,7 @@ public Optional solveSymbolAsValue(String name) { // Get the functional method in order for us to resolve it's type arguments properly Optional functionalMethodOpt = FunctionalInterfaceLogic.getFunctionalMethod(lambdaType); - if (functionalMethodOpt.isPresent()){ + if (functionalMethodOpt.isPresent()) { MethodUsage functionalMethod = functionalMethodOpt.get(); InferenceContext inferenceContext = new InferenceContext(typeSolver); @@ -112,10 +112,10 @@ public Optional solveSymbolAsValue(String name) { } Value value = new Value(conType, name); return Optional.of(value); - } else{ - return Optional.empty(); } - } else if (parentNode instanceof VariableDeclarator) { + return Optional.empty(); + } + if (parentNode instanceof VariableDeclarator) { VariableDeclarator variableDeclarator = (VariableDeclarator) parentNode; ResolvedType t = JavaParserFacade.get(typeSolver).convertToUsage(variableDeclarator.getType()); Optional functionalMethod = FunctionalInterfaceLogic.getFunctionalMethod(t); @@ -137,10 +137,10 @@ public Optional solveSymbolAsValue(String name) { Value value = new Value(lambdaType, name); return Optional.of(value); - } else { - throw new UnsupportedOperationException(); } - } else if (parentNode instanceof ReturnStmt) { + throw new UnsupportedOperationException(); + } + if (parentNode instanceof ReturnStmt) { ReturnStmt returnStmt = (ReturnStmt) parentNode; Optional optDeclaration = returnStmt.findAncestor(MethodDeclaration.class); if (optDeclaration.isPresent()) { @@ -165,11 +165,11 @@ public Optional solveSymbolAsValue(String name) { Value value = new Value(lambdaType, name); return Optional.of(value); - } else { - throw new UnsupportedOperationException(); } + throw new UnsupportedOperationException(); } - } else if (parentNode instanceof CastExpr) { + } + if (parentNode instanceof CastExpr) { CastExpr castExpr = (CastExpr) parentNode; ResolvedType t = JavaParserFacade.get(typeSolver).convertToUsage(castExpr.getType()); Optional functionalMethod = FunctionalInterfaceLogic.getFunctionalMethod(t); @@ -192,12 +192,10 @@ public Optional solveSymbolAsValue(String name) { Value value = new Value(lambdaType, name); return Optional.of(value); - } else { - throw new UnsupportedOperationException(); } - } else { throw new UnsupportedOperationException(); } + throw new UnsupportedOperationException(); } } } diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/MethodCallExprContext.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/MethodCallExprContext.java index 4909fbee3b..08d8266856 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/MethodCallExprContext.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/MethodCallExprContext.java @@ -90,10 +90,9 @@ public Optional solveMethodAsUsage(String name, List methodUsage = resolveMethodTypeParametersFromExplicitList(typeSolver, methodUsage); methodUsage = resolveMethodTypeParameters(methodUsage, argumentsTypes); return Optional.of(methodUsage); - } else { - throw new UnsolvedSymbolException(ref.getCorrespondingDeclaration().toString(), - "Method '" + name + "' with parameterTypes " + argumentsTypes); } + throw new UnsolvedSymbolException(ref.getCorrespondingDeclaration().toString(), + "Method '" + name + "' with parameterTypes " + argumentsTypes); } } @@ -229,9 +228,8 @@ private Optional solveMethodAsUsage(ResolvedReferenceType refType, methodUsage = methodUsage.replaceParamType(i, replaced); } return Optional.of(methodUsage); - } else { - return ref; } + return ref; } private void inferTypes(ResolvedType source, ResolvedType target, Map mappings) { @@ -491,35 +489,39 @@ private Optional solveMethodAsUsage(ResolvedTypeVariable tp, String private Optional solveMethodAsUsage(ResolvedType type, String name, List argumentsTypes, Context invokationContext) { if (type instanceof ResolvedReferenceType) { return solveMethodAsUsage((ResolvedReferenceType) type, name, argumentsTypes, invokationContext); - } else if (type instanceof LazyType) { + } + if (type instanceof LazyType) { return solveMethodAsUsage(type.asReferenceType(), name, argumentsTypes, invokationContext); - } else if (type instanceof ResolvedTypeVariable) { + } + if (type instanceof ResolvedTypeVariable) { return solveMethodAsUsage((ResolvedTypeVariable) type, name, argumentsTypes, invokationContext); - } else if (type instanceof ResolvedWildcard) { + } + if (type instanceof ResolvedWildcard) { ResolvedWildcard wildcardUsage = (ResolvedWildcard) type; if (wildcardUsage.isSuper()) { return solveMethodAsUsage(wildcardUsage.getBoundedType(), name, argumentsTypes, invokationContext); - } else if (wildcardUsage.isExtends()) { + } + if (wildcardUsage.isExtends()) { return solveMethodAsUsage(wildcardUsage.getBoundedType(), name, argumentsTypes, invokationContext); - } else { - return solveMethodAsUsage(new ReferenceTypeImpl(typeSolver.getSolvedJavaLangObject()), name, argumentsTypes, invokationContext); } - } else if (type instanceof ResolvedLambdaConstraintType){ + return solveMethodAsUsage(new ReferenceTypeImpl(typeSolver.getSolvedJavaLangObject()), name, argumentsTypes, invokationContext); + } + if (type instanceof ResolvedLambdaConstraintType){ ResolvedLambdaConstraintType constraintType = (ResolvedLambdaConstraintType) type; return solveMethodAsUsage(constraintType.getBound(), name, argumentsTypes, invokationContext); - } else if (type instanceof ResolvedArrayType) { + } + if (type instanceof ResolvedArrayType) { // An array inherits methods from Object not from it's component type return solveMethodAsUsage(new ReferenceTypeImpl(typeSolver.getSolvedJavaLangObject()), name, argumentsTypes, invokationContext); - } else if (type instanceof ResolvedUnionType) { + } + if (type instanceof ResolvedUnionType) { Optional commonAncestor = type.asUnionType().getCommonAncestor(); if (commonAncestor.isPresent()) { return solveMethodAsUsage(commonAncestor.get(), name, argumentsTypes, invokationContext); - } else { - throw new UnsupportedOperationException("no common ancestor available for " + type.describe()); } - } else { - throw new UnsupportedOperationException("type usage: " + type.getClass().getCanonicalName()); + throw new UnsupportedOperationException("no common ancestor available for " + type.describe()); } + throw new UnsupportedOperationException("type usage: " + type.getClass().getCanonicalName()); } private ResolvedType usingParameterTypesFromScope(ResolvedType scope, ResolvedType type, Map inferredTypes) { @@ -529,10 +531,8 @@ private ResolvedType usingParameterTypesFromScope(ResolvedType scope, ResolvedTy type = type.replaceTypeVariables(entry.a, scope.asReferenceType().getGenericParameterByName(entry.a.getName()).get(), inferredTypes); } } - return type; - } else { - return type; } + return type; } private ResolvedType applyInferredTypes(ResolvedType type, Map inferredTypes) { diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/MethodReferenceExprContext.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/MethodReferenceExprContext.java index dad80fd1bb..36c84f804a 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/MethodReferenceExprContext.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/MethodReferenceExprContext.java @@ -81,14 +81,11 @@ public SymbolReference solveMethod(String name, List< SymbolReference firstResAttempt = MethodResolutionLogic.solveMethodInType(rrtd, name, argumentsTypes, false); if (firstResAttempt.isSolved()) { return firstResAttempt; - } else { - // If has not already been solved above then will be solved here if single argument type same as - // (or subclass of) rrtd, as call is actually performed on the argument itself with zero params - SymbolReference secondResAttempt = MethodResolutionLogic.solveMethodInType(rrtd, name, Collections.emptyList(), false); - if (secondResAttempt.isSolved()) { + } + SymbolReference secondResAttempt = MethodResolutionLogic.solveMethodInType(rrtd, name, Collections.emptyList(), false); + if (secondResAttempt.isSolved()) { return secondResAttempt; } - } } return SymbolReference.unsolved(); @@ -139,10 +136,10 @@ private List inferArgumentTypes() { } return resolvedTypes; - } else { - throw new UnsupportedOperationException(); } - } else if (demandParentNode(wrappedNode) instanceof VariableDeclarator) { + throw new UnsupportedOperationException(); + } + if (demandParentNode(wrappedNode) instanceof VariableDeclarator) { VariableDeclarator variableDeclarator = (VariableDeclarator) demandParentNode(wrappedNode); ResolvedType t = JavaParserFacade.get(typeSolver).convertToUsage(variableDeclarator.getType()); Optional functionalMethod = FunctionalInterfaceLogic.getFunctionalMethod(t); @@ -165,10 +162,10 @@ private List inferArgumentTypes() { } return resolvedTypes; - } else { - throw new UnsupportedOperationException(); } - } else if (demandParentNode(wrappedNode) instanceof ReturnStmt) { + throw new UnsupportedOperationException(); + } + if (demandParentNode(wrappedNode) instanceof ReturnStmt) { ReturnStmt returnStmt = (ReturnStmt) demandParentNode(wrappedNode); Optional optDeclaration = returnStmt.findAncestor(MethodDeclaration.class); if (optDeclaration.isPresent()) { @@ -193,14 +190,12 @@ private List inferArgumentTypes() { } return resolvedTypes; - } else { - throw new UnsupportedOperationException(); } + throw new UnsupportedOperationException(); } throw new UnsupportedOperationException(); - } else { - throw new UnsupportedOperationException(); } + throw new UnsupportedOperationException(); } private int pos(MethodCallExpr callExpr, Expression param) { diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/StatementContext.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/StatementContext.java index 58abcb62e3..fbc6bc85cb 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/StatementContext.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/StatementContext.java @@ -142,12 +142,14 @@ public Optional solveSymbolAsValue(String name) { Node parentOfWrappedNode = optionalParentNode.get(); - // we should look in all the statements preceding, treating them as SymbolDeclarators + if (parentOfWrappedNode instanceof MethodDeclaration) { return parentContext.solveSymbolAsValue(name); - }else if (parentOfWrappedNode instanceof LambdaExpr) { + } + if (parentOfWrappedNode instanceof LambdaExpr) { return parentContext.solveSymbolAsValue(name); - } else if (!(parentOfWrappedNode instanceof NodeWithStatements)) { + } + if (!(parentOfWrappedNode instanceof NodeWithStatements)) { return parentContext.solveSymbolAsValue(name); } @@ -230,14 +232,17 @@ private SymbolReference solveSymbol(String n Node parentOfWrappedNode = optionalParentNode.get(); - // we should look in all the statements preceding, treating them as SymbolDeclarators + if (parentOfWrappedNode instanceof MethodDeclaration) { return solveSymbolInParentContext(name); - } else if (parentOfWrappedNode instanceof ConstructorDeclaration) { + } + if (parentOfWrappedNode instanceof ConstructorDeclaration) { return solveSymbolInParentContext(name); - } else if (parentOfWrappedNode instanceof LambdaExpr) { + } + if (parentOfWrappedNode instanceof LambdaExpr) { return solveSymbolInParentContext(name); - } else if (parentOfWrappedNode instanceof NodeWithStatements) { + } + if (parentOfWrappedNode instanceof NodeWithStatements) { // If we choose to not solve adjacent statements abort the solution process here. // In the calling context (the context that calls this) we will attempt to // resolve all prior adjacent statements, and then the common parent as the fallback. diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/TryWithResourceContext.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/TryWithResourceContext.java index bc0e67e4a7..b4b4a1886c 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/TryWithResourceContext.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/TryWithResourceContext.java @@ -65,9 +65,8 @@ public Optional solveSymbolAsValue(String name) { if (demandParentNode(wrappedNode) instanceof BlockStmt) { return StatementContext.solveInBlockAsValue(name, typeSolver, wrappedNode); - } else { - return solveSymbolAsValueInParentContext(name); } + return solveSymbolAsValueInParentContext(name); } @Override @@ -84,9 +83,8 @@ public SymbolReference solveSymbol(String na if (demandParentNode(wrappedNode) instanceof BlockStmt) { return StatementContext.solveInBlock(name, typeSolver, wrappedNode); - } else { - return solveSymbolInParentContext(name); } + return solveSymbolInParentContext(name); } @Override diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/AstResolutionUtils.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/AstResolutionUtils.java index d4e6b9ffae..ffa27592c1 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/AstResolutionUtils.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/AstResolutionUtils.java @@ -71,26 +71,26 @@ static String getClassName(String base, Node container) { String cn = ((com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) container).getName().getId(); if (b.isEmpty()) { return cn; - } else { - return b + "." + cn; } - } else if (container instanceof com.github.javaparser.ast.body.EnumDeclaration) { + return b + "." + cn; + } + if (container instanceof com.github.javaparser.ast.body.EnumDeclaration) { String b = getClassName(base, container.getParentNode().orElse(null)); String cn = ((com.github.javaparser.ast.body.EnumDeclaration) container).getName().getId(); if (b.isEmpty()) { return cn; - } else { - return b + "." + cn; } - } else if (container instanceof com.github.javaparser.ast.body.AnnotationDeclaration) { + return b + "." + cn; + } + if (container instanceof com.github.javaparser.ast.body.AnnotationDeclaration) { String b = getClassName(base, container.getParentNode().orElse(null)); String cn = ((com.github.javaparser.ast.body.AnnotationDeclaration) container).getName().getId(); if (b.isEmpty()) { return cn; - } else { - return b + "." + cn; } - } else if (container != null) { + return b + "." + cn; + } + if (container != null) { return getClassName(base, container.getParentNode().orElse(null)); } return base; @@ -122,8 +122,7 @@ static List(container)); - } else { - return declared; } + return declared; } } diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserAnnotationDeclaration.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserAnnotationDeclaration.java index 405bac13ff..7df40f47a5 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserAnnotationDeclaration.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserAnnotationDeclaration.java @@ -115,9 +115,8 @@ public String getQualifiedName() { String containerName = AstResolutionUtils.containerName(wrappedNode.getParentNode().orElse(null)); if (containerName.isEmpty()) { return wrappedNode.getName().getId(); - } else { - return containerName + "." + wrappedNode.getName(); } + return containerName + "." + wrappedNode.getName(); } @Override diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserAnonymousClassDeclaration.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserAnonymousClassDeclaration.java index 18b497aee1..7910da6373 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserAnonymousClassDeclaration.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserAnonymousClassDeclaration.java @@ -86,9 +86,8 @@ public List findMembersOfKind(final Class memberClass) { .filter(node -> memberClass.isAssignableFrom(node.getClass())) .map(memberClass::cast) .collect(Collectors.toList()); - } else { - return Collections.emptyList(); } + return Collections.emptyList(); } public Context getContext() { @@ -233,9 +232,8 @@ public String getQualifiedName() { String containerName = AstResolutionUtils.containerName(wrappedNode.getParentNode().orElse(null)); if (containerName.isEmpty()) { return getName(); - } else { - return containerName + "." + getName(); } + return containerName + "." + getName(); } @Override diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserClassDeclaration.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserClassDeclaration.java index c73ab84457..f65179f5da 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserClassDeclaration.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserClassDeclaration.java @@ -189,16 +189,15 @@ public String getName() { @Override public Optional getSuperClass() { - if(isJavaLangObject()) { + if (isJavaLangObject()) { // If this is java.lang.Object, it has no super class. return Optional.empty(); - } else if (wrappedNode.getExtendedTypes().isEmpty()) { + } + if (wrappedNode.getExtendedTypes().isEmpty()) { // All objects implicitly extend java.lang.Object -- inject it here (only when this isn't java.lang.Object) return Optional.of(object()); - } else { - // Otherwise, return the first ancestor (n.b.: we know it's not empty due to check above). - return Optional.of(toReferenceType(wrappedNode.getExtendedTypes().getFirst().get())); } + return Optional.of(toReferenceType(wrappedNode.getExtendedTypes().getFirst().get())); } @Override diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserInterfaceDeclaration.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserInterfaceDeclaration.java index 5264281b72..2aaf9170d1 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserInterfaceDeclaration.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserInterfaceDeclaration.java @@ -341,11 +341,10 @@ public List getAncestors(boolean acceptIncompleteList) { public List getTypeParameters() { if (this.wrappedNode.getTypeParameters() == null) { return Collections.emptyList(); - } else { - return this.wrappedNode.getTypeParameters().stream().map( + } + return this.wrappedNode.getTypeParameters().stream().map( (tp) -> new JavaParserTypeParameter(tp, typeSolver) ).collect(Collectors.toList()); - } } /** diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserSymbolDeclaration.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserSymbolDeclaration.java index 34bec36db4..c75e3b0c8b 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserSymbolDeclaration.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserSymbolDeclaration.java @@ -59,7 +59,8 @@ public static int getParamPos(Parameter parameter) { for (Node node : demandParentNode(parameter).getChildNodes()) { if (node == parameter) { return pos; - } else if (node instanceof Parameter) { + } + if (node instanceof Parameter) { pos++; } } diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserTypeAdapter.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserTypeAdapter.java index 5733080a7d..4480ae19eb 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserTypeAdapter.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserTypeAdapter.java @@ -69,9 +69,8 @@ public String getQualifiedName() { String containerName = AstResolutionUtils.containerName(wrappedNode.getParentNode().orElse(null)); if (containerName.isEmpty()) { return wrappedNode.getName().getId(); - } else { - return containerName + "." + wrappedNode.getName().getId(); } + return containerName + "." + wrappedNode.getName().getId(); } public boolean isAssignableBy(ResolvedReferenceTypeDeclaration other) { @@ -92,9 +91,8 @@ public boolean isAssignableBy(ResolvedType type) { if (type.isReferenceType()) { ResolvedReferenceTypeDeclaration other = typeSolver.solveType(type.describe()); return isAssignableBy(other); - } else { - throw new UnsupportedOperationException(); } + throw new UnsupportedOperationException(); } /** @@ -125,30 +123,31 @@ public SymbolReference solveType(String name) { if (internalType instanceof ClassOrInterfaceDeclaration) { if (((ClassOrInterfaceDeclaration) internalType).isInterface()) { return SymbolReference.solved(new JavaParserInterfaceDeclaration((com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) internalType, typeSolver)); - } else { - return SymbolReference.solved(new JavaParserClassDeclaration((com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) internalType, typeSolver)); } - } else if (internalType instanceof EnumDeclaration) { + return SymbolReference.solved(new JavaParserClassDeclaration((com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) internalType, typeSolver)); + } + if (internalType instanceof EnumDeclaration) { return SymbolReference.solved(new JavaParserEnumDeclaration((com.github.javaparser.ast.body.EnumDeclaration) internalType, typeSolver)); - } else if (internalType instanceof AnnotationDeclaration) { + } + if (internalType instanceof AnnotationDeclaration) { return SymbolReference.solved(new JavaParserAnnotationDeclaration((com.github.javaparser.ast.body.AnnotationDeclaration) internalType, typeSolver)); - } else { - throw new UnsupportedOperationException(); } - } else if (name.startsWith(prefix) && name.length() > prefix.length()) { + throw new UnsupportedOperationException(); + } + if (name.startsWith(prefix) && name.length() > prefix.length()) { if (internalType instanceof ClassOrInterfaceDeclaration) { if (((ClassOrInterfaceDeclaration) internalType).isInterface()) { return new JavaParserInterfaceDeclaration((com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) internalType, typeSolver).solveType(name.substring(prefix.length())); - } else { - return new JavaParserClassDeclaration((com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) internalType, typeSolver).solveType(name.substring(prefix.length())); } - } else if (internalType instanceof EnumDeclaration) { + return new JavaParserClassDeclaration((com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) internalType, typeSolver).solveType(name.substring(prefix.length())); + } + if (internalType instanceof EnumDeclaration) { return new SymbolSolver(typeSolver).solveTypeInType(new JavaParserEnumDeclaration((com.github.javaparser.ast.body.EnumDeclaration) internalType, typeSolver), name.substring(prefix.length())); - } else if (internalType instanceof AnnotationDeclaration) { + } + if (internalType instanceof AnnotationDeclaration) { return SymbolReference.solved(new JavaParserAnnotationDeclaration((com.github.javaparser.ast.body.AnnotationDeclaration) internalType, typeSolver)); - } else { - throw new UnsupportedOperationException(); } + throw new UnsupportedOperationException(); } } } diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserTypeParameter.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserTypeParameter.java index ec36ebcad6..693ef20c5b 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserTypeParameter.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserTypeParameter.java @@ -96,11 +96,11 @@ public String getContainerQualifiedName() { ResolvedTypeParametrizable container = getContainer(); if (container instanceof ResolvedReferenceTypeDeclaration) { return ((ResolvedReferenceTypeDeclaration) container).getQualifiedName(); - } else if (container instanceof JavaParserConstructorDeclaration) { + } + if (container instanceof JavaParserConstructorDeclaration) { return ((JavaParserConstructorDeclaration) container).getQualifiedSignature(); - } else { - return ((JavaParserMethodDeclaration) container).getQualifiedSignature(); } + return ((JavaParserMethodDeclaration) container).getQualifiedSignature(); } @Override @@ -108,11 +108,11 @@ public String getContainerId() { ResolvedTypeParametrizable container = getContainer(); if (container instanceof ResolvedReferenceTypeDeclaration) { return ((ResolvedReferenceTypeDeclaration) container).getId(); - } else if (container instanceof JavaParserConstructorDeclaration) { + } + if (container instanceof JavaParserConstructorDeclaration) { return ((JavaParserConstructorDeclaration) container).getQualifiedSignature(); - } else { - return ((JavaParserMethodDeclaration) container).getQualifiedSignature(); } + return ((JavaParserMethodDeclaration) container).getQualifiedSignature(); } @Override @@ -121,7 +121,8 @@ public ResolvedTypeParametrizable getContainer() { if (parentNode instanceof com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) { com.github.javaparser.ast.body.ClassOrInterfaceDeclaration jpTypeDeclaration = (com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) parentNode; return JavaParserFacade.get(typeSolver).getTypeDeclaration(jpTypeDeclaration); - } else if (parentNode instanceof com.github.javaparser.ast.body.ConstructorDeclaration){ + } + if (parentNode instanceof com.github.javaparser.ast.body.ConstructorDeclaration){ com.github.javaparser.ast.body.ConstructorDeclaration jpConstructorDeclaration = (com.github.javaparser.ast.body.ConstructorDeclaration) parentNode; Optional jpTypeDeclaration = jpConstructorDeclaration.findAncestor(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration.class); if (jpTypeDeclaration.isPresent()) { diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserTypeVariableDeclaration.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserTypeVariableDeclaration.java index 3f1e1b88e9..1f74833c73 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserTypeVariableDeclaration.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserTypeVariableDeclaration.java @@ -93,9 +93,8 @@ public ResolvedType getUsage(Node node) { public boolean isAssignableBy(ResolvedType type) { if (type.isTypeVariable()) { throw new UnsupportedOperationException("Is this type variable declaration assignable by " + type.describe()); - } else { - throw new UnsupportedOperationException("Is this type variable declaration assignable by " + type); } + throw new UnsupportedOperationException("Is this type variable declaration assignable by " + type); } @Override @@ -125,9 +124,9 @@ public List getAncestors(boolean acceptIncompleteList) { // If no bound is declared for a type variable, Object is assumed. // https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.4 return Collections.singletonList(new ReferenceTypeImpl(typeSolver.getSolvedJavaLangObject())); - } else { - List ancestors = new ArrayList<>(); - for (ClassOrInterfaceType type : wrappedNode.getTypeBound()) { + } + List ancestors = new ArrayList<>(); + for (ClassOrInterfaceType type : wrappedNode.getTypeBound()) { try { ResolvedType resolvedType = JavaParserFacade.get(typeSolver).convertToUsage(type); ancestors.add(resolvedType.asReferenceType()); @@ -138,8 +137,7 @@ public List getAncestors(boolean acceptIncompleteList) { } } } - return ancestors; - } + return ancestors; } @Override diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistAnnotationDeclaration.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistAnnotationDeclaration.java index 765ac44b69..a51bb497fc 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistAnnotationDeclaration.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistAnnotationDeclaration.java @@ -72,9 +72,8 @@ public String getClassName() { String qualifiedName = getQualifiedName(); if (qualifiedName.contains(".")) { return qualifiedName.substring(qualifiedName.lastIndexOf(".") + 1, qualifiedName.length()); - } else { - return qualifiedName; } + return qualifiedName; } @Override diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistFactory.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistFactory.java index 875e13b725..0a88c7e65f 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistFactory.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistFactory.java @@ -43,21 +43,20 @@ public static ResolvedType typeUsageFor(CtClass ctClazz, TypeSolver typeSolver) try { if (ctClazz.isArray()) { return new ResolvedArrayType(typeUsageFor(ctClazz.getComponentType(), typeSolver)); - } else if (ctClazz.isPrimitive()) { + } + if (ctClazz.isPrimitive()) { if (ctClazz.getName().equals("void")) { return ResolvedVoidType.INSTANCE; - } else { - return ResolvedPrimitiveType.byName(ctClazz.getName()); } - } else { - if (ctClazz.isInterface()) { + return ResolvedPrimitiveType.byName(ctClazz.getName()); + } + if (ctClazz.isInterface()) { return new ReferenceTypeImpl(new JavassistInterfaceDeclaration(ctClazz, typeSolver)); - } else if (ctClazz.isEnum()) { + } + if (ctClazz.isEnum()) { return new ReferenceTypeImpl(new JavassistEnumDeclaration(ctClazz, typeSolver)); - } else { - return new ReferenceTypeImpl(new JavassistClassDeclaration(ctClazz, typeSolver)); } - } + return new ReferenceTypeImpl(new JavassistClassDeclaration(ctClazz, typeSolver)); } catch (NotFoundException e) { throw new RuntimeException(e); } @@ -66,27 +65,30 @@ public static ResolvedType typeUsageFor(CtClass ctClazz, TypeSolver typeSolver) public static ResolvedReferenceTypeDeclaration toTypeDeclaration(CtClass ctClazz, TypeSolver typeSolver) { if (ctClazz.isAnnotation()) { return new JavassistAnnotationDeclaration(ctClazz, typeSolver); - } else if (ctClazz.isInterface()) { + } + if (ctClazz.isInterface()) { return new JavassistInterfaceDeclaration(ctClazz, typeSolver); - } else if (ctClazz.isEnum()) { + } + if (ctClazz.isEnum()) { return new JavassistEnumDeclaration(ctClazz, typeSolver); - } else if (ctClazz.isArray()) { + } + if (ctClazz.isArray()) { throw new IllegalArgumentException("This method should not be called passing an array"); - } else { - return new JavassistClassDeclaration(ctClazz, typeSolver); } + return new JavassistClassDeclaration(ctClazz, typeSolver); } static AccessSpecifier modifiersToAccessLevel(final int modifiers) { if (Modifier.isPublic(modifiers)) { return AccessSpecifier.PUBLIC; - } else if (Modifier.isProtected(modifiers)) { + } + if (Modifier.isProtected(modifiers)) { return AccessSpecifier.PROTECTED; - } else if (Modifier.isPrivate(modifiers)) { + } + if (Modifier.isPrivate(modifiers)) { return AccessSpecifier.PRIVATE; - } else { - return AccessSpecifier.NONE; } + return AccessSpecifier.NONE; } } diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistTypeDeclarationAdapter.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistTypeDeclarationAdapter.java index ebbd8e82ec..d6e2d0c699 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistTypeDeclarationAdapter.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistTypeDeclarationAdapter.java @@ -84,17 +84,15 @@ public Optional getSuperClass() { return Optional.of(new ReferenceTypeImpl( typeSolver.solveType(JavassistUtils.internalNameToCanonicalName(ctClass.getClassFile().getSuperclass())) )); - } else { - // If there is a generic signature present, solve the types and return it. - SignatureAttribute.ClassSignature classSignature = SignatureAttribute.toClassSignature(ctClass.getGenericSignature()); - return Optional.ofNullable( + } + SignatureAttribute.ClassSignature classSignature = SignatureAttribute.toClassSignature(ctClass.getGenericSignature()); + return Optional.ofNullable( JavassistUtils.signatureTypeToType( classSignature.getSuperClass(), typeSolver, typeDeclaration ).asReferenceType() ); - } } catch (BadBytecode e) { throw new RuntimeException(e); } @@ -215,8 +213,8 @@ private String getAnnotationType(Object annotation) { public List getTypeParameters() { if (null == ctClass.getGenericSignature()) { return Collections.emptyList(); - } else { - try { + } + try { SignatureAttribute.ClassSignature classSignature = SignatureAttribute.toClassSignature(ctClass.getGenericSignature()); return Arrays.stream(classSignature.getParameters()) @@ -225,7 +223,6 @@ public List getTypeParameters() { } catch (BadBytecode badBytecode) { throw new RuntimeException(badBytecode); } - } } public Optional containerType() { diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistTypeParameter.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistTypeParameter.java index d1be24a2c4..22ef611492 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistTypeParameter.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistTypeParameter.java @@ -91,7 +91,8 @@ public String getName() { public String getContainerQualifiedName() { if (this.container instanceof ResolvedReferenceTypeDeclaration) { return ((ResolvedReferenceTypeDeclaration) this.container).getQualifiedName(); - } else if (this.container instanceof ResolvedMethodLikeDeclaration) { + } + if (this.container instanceof ResolvedMethodLikeDeclaration) { return ((ResolvedMethodLikeDeclaration) this.container).getQualifiedName(); } throw new UnsupportedOperationException(); diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistUtils.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistUtils.java index ff6cad8142..4c7b722f81 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistUtils.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistUtils.java @@ -131,7 +131,8 @@ static ResolvedType signatureTypeToType(SignatureAttribute.Type signatureType, T ResolvedReferenceTypeDeclaration typeDeclaration = typeSolver.solveType( removeTypeArguments(internalNameToCanonicalName(getTypeName(classType)))); return new ReferenceTypeImpl(typeDeclaration, typeArguments); - } else if (signatureType instanceof SignatureAttribute.TypeVariable) { + } + if (signatureType instanceof SignatureAttribute.TypeVariable) { SignatureAttribute.TypeVariable typeVariableSignature = (SignatureAttribute.TypeVariable) signatureType; Optional typeParameterDeclarationOpt = typeParametrizable.findTypeParameter(typeVariableSignature.getName()); if (!typeParameterDeclarationOpt.isPresent()) { @@ -139,20 +140,20 @@ static ResolvedType signatureTypeToType(SignatureAttribute.Type signatureType, T } ResolvedTypeParameterDeclaration typeParameterDeclaration = typeParameterDeclarationOpt.get(); return new ResolvedTypeVariable(typeParameterDeclaration); - } else if (signatureType instanceof SignatureAttribute.ArrayType) { + } + if (signatureType instanceof SignatureAttribute.ArrayType) { SignatureAttribute.ArrayType arrayType = (SignatureAttribute.ArrayType) signatureType; ResolvedType baseType = signatureTypeToType(arrayType.getComponentType(), typeSolver, typeParametrizable); return getArrayType(baseType, arrayType.getDimension()); - } else if (signatureType instanceof SignatureAttribute.BaseType) { + } + if (signatureType instanceof SignatureAttribute.BaseType) { SignatureAttribute.BaseType baseType = (SignatureAttribute.BaseType) signatureType; if (baseType.toString().equals("void")) { return ResolvedVoidType.INSTANCE; - } else { - return ResolvedPrimitiveType.byName(baseType.toString()); } - } else { - throw new RuntimeException(signatureType.getClass().getCanonicalName()); + return ResolvedPrimitiveType.byName(baseType.toString()); } + throw new RuntimeException(signatureType.getClass().getCanonicalName()); } /* * Manage dimension of an array @@ -170,9 +171,8 @@ private static String getTypeName(SignatureAttribute.ClassType classType) { private static String removeTypeArguments(String typeName) { if (typeName.contains("<")) { return typeName.substring(0, typeName.indexOf('<')); - } else { - return typeName; } + return typeName; } static String internalNameToCanonicalName(String typeName) { @@ -182,12 +182,12 @@ static String internalNameToCanonicalName(String typeName) { private static ResolvedType objectTypeArgumentToType(SignatureAttribute.ObjectType typeArgument, TypeSolver typeSolver, ResolvedTypeParametrizable typeParametrizable) { if (typeArgument instanceof SignatureAttribute.ClassType) { return signatureTypeToType(typeArgument, typeSolver, typeParametrizable); - } else if (typeArgument instanceof SignatureAttribute.ArrayType) { + } + if (typeArgument instanceof SignatureAttribute.ArrayType) { return new ResolvedArrayType(signatureTypeToType(((SignatureAttribute.ArrayType) typeArgument).getComponentType(), typeSolver, typeParametrizable)); - } else { - String typeName = typeArgument.jvmTypeName(); - return getGenericParameterByName(typeName, typeParametrizable, typeSolver); } + String typeName = typeArgument.jvmTypeName(); + return getGenericParameterByName(typeName, typeParametrizable, typeSolver); } private static ResolvedType getGenericParameterByName(String typeName, ResolvedTypeParametrizable typeParametrizable, TypeSolver typeSolver) { @@ -200,16 +200,16 @@ private static ResolvedType typeArgumentToType(SignatureAttribute.TypeArgument t if (typeArgument.isWildcard()) { if (typeArgument.getType() == null) { return ResolvedWildcard.UNBOUNDED; - } else if (typeArgument.getKind() == '+') { + } + if (typeArgument.getKind() == '+') { return ResolvedWildcard.extendsBound(objectTypeArgumentToType(typeArgument.getType(), typeSolver, typeParametrizable)); - } else if (typeArgument.getKind() == '-') { + } + if (typeArgument.getKind() == '-') { return ResolvedWildcard.superBound(objectTypeArgumentToType(typeArgument.getType(), typeSolver, typeParametrizable)); - } else { - throw new UnsupportedOperationException(); } - } else { - return objectTypeArgumentToType(typeArgument.getType(), typeSolver, typeParametrizable); + throw new UnsupportedOperationException(); } + return objectTypeArgumentToType(typeArgument.getType(), typeSolver, typeParametrizable); } /** diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionAnnotationDeclaration.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionAnnotationDeclaration.java index 5ee4aa678b..b59281efd0 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionAnnotationDeclaration.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionAnnotationDeclaration.java @@ -83,11 +83,10 @@ public String getPackageName() { @Override public String getClassName() { String qualifiedName = getQualifiedName(); - if(qualifiedName.contains(".")) { + if (qualifiedName.contains(".")) { return qualifiedName.substring(qualifiedName.lastIndexOf(".") + 1); - } else { - return qualifiedName; } + return qualifiedName; } @Override diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionFactory.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionFactory.java index 2077f8b12f..51bbfd12e9 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionFactory.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionFactory.java @@ -46,17 +46,20 @@ public class ReflectionFactory { public static ResolvedReferenceTypeDeclaration typeDeclarationFor(Class clazz, TypeSolver typeSolver) { if (clazz.isArray()) { throw new IllegalArgumentException("No type declaration available for an Array"); - } else if (clazz.isPrimitive()) { + } + if (clazz.isPrimitive()) { throw new IllegalArgumentException(); - } else if (clazz.isAnnotation()) { + } + if (clazz.isAnnotation()) { return new ReflectionAnnotationDeclaration(clazz, typeSolver); - } else if (clazz.isInterface()) { + } + if (clazz.isInterface()) { return new ReflectionInterfaceDeclaration(clazz, typeSolver); - } else if (clazz.isEnum()) { + } + if (clazz.isEnum()) { return new ReflectionEnumDeclaration(clazz, typeSolver); - } else { - return new ReflectionClassDeclaration(clazz, typeSolver); } + return new ReflectionClassDeclaration(clazz, typeSolver); } public static ResolvedType typeUsageFor(java.lang.reflect.Type type, TypeSolver typeSolver) { @@ -65,7 +68,8 @@ public static ResolvedType typeUsageFor(java.lang.reflect.Type type, TypeSolver boolean declaredOnClass = tv.getGenericDeclaration() instanceof java.lang.reflect.Type; ResolvedTypeParameterDeclaration typeParameter = new ReflectionTypeParameter(tv, declaredOnClass, typeSolver); return new ResolvedTypeVariable(typeParameter); - } else if (type instanceof ParameterizedType) { + } + if (type instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) type; ResolvedReferenceType rawType = typeUsageFor(pt.getRawType(), typeSolver).asReferenceType(); List actualTypes = new ArrayList<>(); @@ -73,23 +77,25 @@ public static ResolvedType typeUsageFor(java.lang.reflect.Type type, TypeSolver // we consume the actual types rawType = rawType.transformTypeParameters(tp -> typeUsageFor(actualTypes.remove(0), typeSolver)).asReferenceType(); return rawType; - } else if (type instanceof Class) { + } + if (type instanceof Class) { Class c = (Class) type; if (c.isPrimitive()) { if (c.getName().equals(Void.TYPE.getName())) { return ResolvedVoidType.INSTANCE; - } else { - return ResolvedPrimitiveType.byName(c.getName()); } - } else if (c.isArray()) { + return ResolvedPrimitiveType.byName(c.getName()); + } + if (c.isArray()) { return new ResolvedArrayType(typeUsageFor(c.getComponentType(), typeSolver)); - } else { - return new ReferenceTypeImpl(typeDeclarationFor(c, typeSolver)); } - } else if (type instanceof GenericArrayType) { + return new ReferenceTypeImpl(typeDeclarationFor(c, typeSolver)); + } + if (type instanceof GenericArrayType) { GenericArrayType genericArrayType = (GenericArrayType) type; return new ResolvedArrayType(typeUsageFor(genericArrayType.getGenericComponentType(), typeSolver)); - } else if (type instanceof WildcardType) { + } + if (type instanceof WildcardType) { WildcardType wildcardType = (WildcardType) type; if (wildcardType.getLowerBounds().length > 0 && wildcardType.getUpperBounds().length > 0) { if (wildcardType.getUpperBounds().length == 1 && wildcardType.getUpperBounds()[0].getTypeName().equals(JAVA_LANG_OBJECT)) { @@ -109,20 +115,20 @@ public static ResolvedType typeUsageFor(java.lang.reflect.Type type, TypeSolver return ResolvedWildcard.extendsBound(typeUsageFor(wildcardType.getUpperBounds()[0], typeSolver)); } return ResolvedWildcard.UNBOUNDED; - } else { - throw new UnsupportedOperationException(type.getClass().getCanonicalName() + " " + type); } + throw new UnsupportedOperationException(type.getClass().getCanonicalName() + " " + type); } static AccessSpecifier modifiersToAccessLevel(final int modifiers) { if (Modifier.isPublic(modifiers)) { return AccessSpecifier.PUBLIC; - } else if (Modifier.isProtected(modifiers)) { + } + if (Modifier.isProtected(modifiers)) { return AccessSpecifier.PROTECTED; - } else if (Modifier.isPrivate(modifiers)) { + } + if (Modifier.isPrivate(modifiers)) { return AccessSpecifier.PRIVATE; - } else { - return AccessSpecifier.NONE; } + return AccessSpecifier.NONE; } } diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionMethodDeclaration.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionMethodDeclaration.java index 6795800104..67e59ca33f 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionMethodDeclaration.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionMethodDeclaration.java @@ -90,9 +90,8 @@ public ResolvedReferenceTypeDeclaration declaringType() { } if (method.getDeclaringClass().isEnum()) { return new ReflectionEnumDeclaration(method.getDeclaringClass(), typeSolver); - } else { - return new ReflectionClassDeclaration(method.getDeclaringClass(), typeSolver); } + return new ReflectionClassDeclaration(method.getDeclaringClass(), typeSolver); } @Override diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionTypeParameter.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionTypeParameter.java index d1657addfb..a5e0806038 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionTypeParameter.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionTypeParameter.java @@ -96,18 +96,16 @@ public String getName() { public String getContainerQualifiedName() { if (container instanceof ResolvedReferenceTypeDeclaration) { return ((ResolvedReferenceTypeDeclaration) container).getQualifiedName(); - } else { - return ((ResolvedMethodLikeDeclaration) container).getQualifiedSignature(); } + return ((ResolvedMethodLikeDeclaration) container).getQualifiedSignature(); } @Override public String getContainerId() { if (container instanceof ResolvedReferenceTypeDeclaration) { return ((ResolvedReferenceTypeDeclaration) container).getId(); - } else { - return ((ResolvedMethodLikeDeclaration) container).getQualifiedSignature(); } + return ((ResolvedMethodLikeDeclaration) container).getQualifiedSignature(); } @Override diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/SymbolSolver.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/SymbolSolver.java index fe2aa018c9..3e458f286b 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/SymbolSolver.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/SymbolSolver.java @@ -118,9 +118,8 @@ public ResolvedTypeDeclaration solveType(Type type) { throw new UnsolvedSymbolException(JavaParserFactory.getContext(type, typeSolver).toString(), name); } return ref.getCorrespondingDeclaration(); - } else { - throw new UnsupportedOperationException(type.getClass().getCanonicalName()); } + throw new UnsupportedOperationException(type.getClass().getCanonicalName()); } @Override diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/naming/NameLogic.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/naming/NameLogic.java index 01fd7549f6..4ab7d5057e 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/naming/NameLogic.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/naming/NameLogic.java @@ -78,12 +78,11 @@ public static boolean isAName(Node node) { if (node instanceof FieldAccessExpr) { FieldAccessExpr fieldAccessExpr = (FieldAccessExpr) node; return isAName(fieldAccessExpr.getScope()); - } else { - return node instanceof SimpleName || + } + return node instanceof SimpleName || node instanceof Name || node instanceof ClassOrInterfaceType || node instanceof NameExpr; - } } private static Node getQualifier(Node node) { @@ -322,14 +321,13 @@ public static NameCategory classifyReference(Node name, TypeSolver typeSolver) { NameCategory first = syntacticClassificationAccordingToContext(name); // Second, a name that is initially classified by its context as an AmbiguousName or as a PackageOrTypeName is - // then reclassified to be a PackageName, TypeName, or ExpressionName. + if (first.isNeedingDisambiguation()) { NameCategory second = reclassificationOfContextuallyAmbiguousNames(name, first, typeSolver); assert !second.isNeedingDisambiguation(); return second; - } else { - return first; } + return first; } /** @@ -364,9 +362,8 @@ private static NameCategory reclassificationOfContextuallyAmbiguousPackageOrType if (isSimpleName(name)) { if (JavaParserFactory.getContext(name, typeSolver).solveType(nameAsString(name)).isSolved()) { return NameCategory.TYPE_NAME; - } else { - return NameCategory.PACKAGE_NAME; } + return NameCategory.PACKAGE_NAME; } // 6.5.4.2. Qualified PackageOrTypeNames @@ -381,9 +378,8 @@ private static NameCategory reclassificationOfContextuallyAmbiguousPackageOrType if (isQualifiedName(name)) { if (JavaParserFactory.getContext(name, typeSolver).solveType(nameAsString(name)).isSolved()) { return NameCategory.TYPE_NAME; - } else { - return NameCategory.PACKAGE_NAME; } + return NameCategory.PACKAGE_NAME; } throw new UnsupportedOperationException("This is unexpected: the name is neither simple or qualified"); @@ -410,9 +406,8 @@ private static NameCategory reclassificationOfContextuallyAmbiguousQualifiedAmbi if (leftNameCategory == NameCategory.PACKAGE_NAME) { if (typeSolver.hasType(nameAsString(nameNode))) { return NameCategory.TYPE_NAME; - } else { - return NameCategory.PACKAGE_NAME; } + return NameCategory.PACKAGE_NAME; } // * If the name to the left of the "." is reclassified as a TypeName, then: @@ -442,12 +437,10 @@ private static NameCategory reclassificationOfContextuallyAmbiguousQualifiedAmbi return NameCategory.TYPE_NAME; } return NameCategory.COMPILATION_ERROR; - } else { - throw new UnsupportedOperationException("The name is a type but it has been resolved to something that is not a reference type"); } - } else { - throw new UnsolvedSymbolException("Unable to solve context type: " + NameLogic.nameAsString(leftName)); + throw new UnsupportedOperationException("The name is a type but it has been resolved to something that is not a reference type"); } + throw new UnsolvedSymbolException("Unable to solve context type: " + NameLogic.nameAsString(leftName)); } // * If the name to the left of the "." is reclassified as an ExpressionName, then this AmbiguousName is @@ -983,23 +976,25 @@ public static String nameAsString(Node name) { } if (name instanceof Name) { return ((Name) name).asString(); - } else if (name instanceof SimpleName) { + } + if (name instanceof SimpleName) { return ((SimpleName) name).getIdentifier(); - } else if (name instanceof ClassOrInterfaceType) { + } + if (name instanceof ClassOrInterfaceType) { return ((ClassOrInterfaceType) name).asString(); - } else if (name instanceof FieldAccessExpr) { + } + if (name instanceof FieldAccessExpr) { FieldAccessExpr fieldAccessExpr = (FieldAccessExpr) name; if (isAName(fieldAccessExpr.getScope())) { return nameAsString(fieldAccessExpr.getScope()) + "." + nameAsString(fieldAccessExpr.getName()); - } else { - throw new IllegalArgumentException(); } - } else if (name instanceof NameExpr) { + throw new IllegalArgumentException(); + } + if (name instanceof NameExpr) { return ((NameExpr) name).getNameAsString(); - } else { - throw new UnsupportedOperationException("Unknown type of name found: " + name + " (" - + name.getClass().getCanonicalName() + ")"); } + throw new UnsupportedOperationException("Unknown type of name found: " + name + " (" + + name.getClass().getCanonicalName() + ")"); } private interface PredicateOnParentAndChild

{ @@ -1017,9 +1012,8 @@ private static

boolean whenParentIs( if (child.getParentNode().isPresent()) { Node parent = child.getParentNode().get(); return parentClass.isInstance(parent) && predicate.isSatisfied(parentClass.cast(parent), child); - } else { - return false; } + return false; } } diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/promotion/NumericConditionalExprHandler.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/promotion/NumericConditionalExprHandler.java index aa18918164..fe6f68995a 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/promotion/NumericConditionalExprHandler.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/promotion/NumericConditionalExprHandler.java @@ -108,7 +108,8 @@ public ResolvedType resolveType() { if (((ResolvedPrimitiveType)thenExpr).in(resolvedPrimitiveTypeSubList) && ((ResolvedPrimitiveType)elseExpr).equals(ResolvedPrimitiveType.INT)) { return thenExpr; - } else if (((ResolvedPrimitiveType)elseExpr).in(resolvedPrimitiveTypeSubList) + } + if (((ResolvedPrimitiveType)elseExpr).in(resolvedPrimitiveTypeSubList) && ((ResolvedPrimitiveType)thenExpr).equals(ResolvedPrimitiveType.INT)) { return elseExpr; } @@ -125,7 +126,8 @@ public ResolvedType resolveType() { && thenExpr.asReferenceType().toUnboxedType().get().in(resolvedPrimitiveTypeSubList) && ((ResolvedPrimitiveType)elseExpr).equals(ResolvedPrimitiveType.INT)) { return thenExpr.asReferenceType().toUnboxedType().get(); - } else if (elseExpr.isReference() && thenExpr.isPrimitive() + } + if (elseExpr.isReference() && thenExpr.isPrimitive() && elseExpr.asReferenceType().isUnboxable() && elseExpr.asReferenceType().toUnboxedType().get().in(resolvedPrimitiveTypeSubList) && ((ResolvedPrimitiveType)thenExpr).equals(ResolvedPrimitiveType.INT)) { diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/Bound.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/Bound.java index c432124dca..2849ed7257 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/Bound.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/Bound.java @@ -93,18 +93,16 @@ Optional isProperLowerBoundFor(InferenceVariable inferenceVari Optional partial = isProperLowerBound(); if (partial.isPresent() && partial.get().getInferenceVariable().equals(inferenceVariable)) { return partial; - } else { - return Optional.empty(); } + return Optional.empty(); } Optional isProperUpperBoundFor(InferenceVariable inferenceVariable) { Optional partial = isProperUpperBound(); if (partial.isPresent() && partial.get().getInferenceVariable().equals(inferenceVariable)) { return partial; - } else { - return Optional.empty(); } + return Optional.empty(); } /** diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/ControlFlowLogic.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/ControlFlowLogic.java index 5bce7af578..1519504a1b 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/ControlFlowLogic.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/ControlFlowLogic.java @@ -110,9 +110,8 @@ private List containedTryStmts(Statement statement) { private

boolean parentIs(Node node, Class

parentClass) { if (node.getParentNode().isPresent()) { return parentClass.isInstance(node.getParentNode().get()); - } else { - return false; } + return false; } // See JLS 14.21 @@ -167,10 +166,8 @@ public Boolean visit(IfStmt n, Void arg) { // An if-then-else statement can complete normally iff the then-statement can // complete normally or the else-statement can complete normally. return canCompleteNormally(n.getThenStmt()) || canCompleteNormally(n.getElseStmt().get()); - } else { - // An if-then statement can complete normally iff it is reachable. - return isReachable(n); } + return isReachable(n); } @Override diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/TypeHelper.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/TypeHelper.java index f9a67a80fb..4b7e654ff9 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/TypeHelper.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/TypeHelper.java @@ -66,9 +66,8 @@ public static boolean isProperType(ResolvedType type) { ResolvedWildcard wildcard = (ResolvedWildcard)type; if (wildcard.isBounded()) { return isProperType(wildcard.getBoundedType()); - } else { - return true; } + return true; } if (type.isPrimitive()) { return true; @@ -181,9 +180,8 @@ public static boolean areCompatibleThroughWideningReferenceConversion(ResolvedTy public static boolean areCompatibleThroughWideningPrimitiveConversion(ResolvedType s, ResolvedType t) { if (s.isPrimitive() && t.isPrimitive()) { return s.isAssignableBy(t); - } else { - return false; } + return false; } public static Set usedInferenceVariables(ResolvedType type) { @@ -229,13 +227,7 @@ public static Pair groundTargetTypeOfLambda(LambdaExpr la used18_5_3 = true; throw new UnsupportedOperationException(); } - - // - If T is a wildcard-parameterized functional interface type and the lambda expression is implicitly typed, - // then the ground target type is the non-wildcard parameterization (§9.9) of T. - - else { - return new Pair<>(nonWildcardParameterizationOf(T.asReferenceType(), typeSolver), used18_5_3); - } + return new Pair<>(nonWildcardParameterizationOf(T.asReferenceType(), typeSolver), used18_5_3); } // - Otherwise, the ground target type is T. @@ -314,9 +306,8 @@ public static MethodType getFunctionType(ResolvedType type) { Optional mu = FunctionalInterfaceLogic.getFunctionalMethod(type); if (mu.isPresent()) { return MethodType.fromMethodUsage(mu.get()); - } else { - throw new IllegalArgumentException(); } + throw new IllegalArgumentException(); } /** diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/TypeInference.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/TypeInference.java index 97dcdacdcd..6f6e72481a 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/TypeInference.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/TypeInference.java @@ -66,9 +66,8 @@ public static MethodUsage toMethodUsage(MethodCallExpr call, ResolvedMethodDecla Optional instantiationSetOpt = typeInference.instantiationInference(call, methodDeclaration); if (instantiationSetOpt.isPresent()) { return instantiationSetToMethodUsage(methodDeclaration, instantiationSetOpt.get()); - } else { - throw new IllegalArgumentException(); } + throw new IllegalArgumentException(); } /// diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/constraintformulas/ExpressionCompatibleWithType.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/constraintformulas/ExpressionCompatibleWithType.java index 7803ee241d..9a93b0f7d2 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/constraintformulas/ExpressionCompatibleWithType.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/constraintformulas/ExpressionCompatibleWithType.java @@ -68,9 +68,8 @@ public ReductionResult reduce(BoundSet currentBoundSet) { if (isProperType(T)) { if (isCompatibleInALooseInvocationContext(typeSolver, expression, T)) { return ReductionResult.trueResult(); - } else { - return ReductionResult.falseResult(); } + return ReductionResult.falseResult(); } // Otherwise, if the expression is a standalone expression (§15.2) of type S, the constraint reduces diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/constraintformulas/TypeCompatibleWithType.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/constraintformulas/TypeCompatibleWithType.java index 5249bc9479..ce61e031a7 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/constraintformulas/TypeCompatibleWithType.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/constraintformulas/TypeCompatibleWithType.java @@ -56,9 +56,8 @@ public ReductionResult reduce(BoundSet currentBoundSet) { if (isProperType(s) && isProperType(t)) { if (isCompatibleInALooseInvocationContext(s, t)) { return ReductionResult.trueResult(); - } else { - return ReductionResult.falseResult(); } + return ReductionResult.falseResult(); } // 2. Otherwise, if S is a primitive type, let S' be the result of applying boxing conversion (§5.1.7) to S. Then the constraint reduces to ‹S' → T›. diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/constraintformulas/TypeSameAsType.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/constraintformulas/TypeSameAsType.java index cf688d4ef6..5329edad74 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/constraintformulas/TypeSameAsType.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/constraintformulas/TypeSameAsType.java @@ -56,9 +56,8 @@ public ReductionResult reduce(BoundSet currentBoundSet) { if (isProperType(S) && isProperType(T)) { if (S.equals(T)) { return ReductionResult.trueResult(); - } else { - return ReductionResult.falseResult(); } + return ReductionResult.falseResult(); } // - Otherwise, if S or T is the null type, the constraint reduces to false. diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/constraintformulas/TypeSubtypeOfType.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/constraintformulas/TypeSubtypeOfType.java index e36511306d..3dc672f4bb 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/constraintformulas/TypeSubtypeOfType.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/constraintformulas/TypeSubtypeOfType.java @@ -56,9 +56,8 @@ public ReductionResult reduce(BoundSet currentBoundSet) { if (isProperType(S) && isProperType(T)) { if (T.isAssignableBy(S)) { return ReductionResult.trueResult(); - } else { - return ReductionResult.falseResult(); } + return ReductionResult.falseResult(); } // - Otherwise, if S is the null type, the constraint reduces to true. diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typesolvers/ClassLoaderTypeSolver.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typesolvers/ClassLoaderTypeSolver.java index cb0c6fe018..d9c70a4e31 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typesolvers/ClassLoaderTypeSolver.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typesolvers/ClassLoaderTypeSolver.java @@ -92,20 +92,18 @@ public SymbolReference tryToSolveType(String n int lastDot = name.lastIndexOf('.'); if (lastDot == -1) { return SymbolReference.unsolved(); - } else { - String parentName = name.substring(0, lastDot); - String childName = name.substring(lastDot + 1); - SymbolReference parent = tryToSolveType(parentName); - if (parent.isSolved()) { + } + String parentName = name.substring(0, lastDot); + String childName = name.substring(lastDot + 1); + SymbolReference parent = tryToSolveType(parentName); + if (parent.isSolved()) { Optional innerClass = parent.getCorrespondingDeclaration() .internalTypes() .stream().filter(it -> it.getName().equals(childName)).findFirst(); return innerClass.map(SymbolReference::solved) .orElseGet(() -> SymbolReference.unsolved()); - } else { - return SymbolReference.unsolved(); } - } + return SymbolReference.unsolved(); } } else { return SymbolReference.unsolved(); diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typesolvers/CombinedTypeSolver.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typesolvers/CombinedTypeSolver.java index 20950ffb19..124264178a 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typesolvers/CombinedTypeSolver.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typesolvers/CombinedTypeSolver.java @@ -181,9 +181,8 @@ public ResolvedReferenceTypeDeclaration solveType(String name) throws UnsolvedSy SymbolReference res = tryToSolveType(name); if (res.isSolved()) { return res.getCorrespondingDeclaration(); - } else { - throw new UnsolvedSymbolException(name); } + throw new UnsolvedSymbolException(name); } /** diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typesolvers/JarTypeSolver.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typesolvers/JarTypeSolver.java index 03948ccbd6..ff4aec107f 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typesolvers/JarTypeSolver.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typesolvers/JarTypeSolver.java @@ -278,9 +278,8 @@ public ResolvedReferenceTypeDeclaration solveType(String name) throws UnsolvedSy SymbolReference ref = tryToSolveType(name); if (ref.isSolved()) { return ref.getCorrespondingDeclaration(); - } else { - throw new UnsolvedSymbolException(name); } + throw new UnsolvedSymbolException(name); } } diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typesolvers/MemoryTypeSolver.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typesolvers/MemoryTypeSolver.java index 7a37222a7e..28f73d83d1 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typesolvers/MemoryTypeSolver.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typesolvers/MemoryTypeSolver.java @@ -91,9 +91,8 @@ public void addDeclaration(String name, ResolvedReferenceTypeDeclaration typeDec public SymbolReference tryToSolveType(String name) { if (declarationMap.containsKey(name)) { return SymbolReference.solved(declarationMap.get(name)); - } else { - return SymbolReference.unsolved(); } + return SymbolReference.unsolved(); } } From 6b264f9f61d53e855538f589eba03d7a0b61b5dd Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Thu, 29 Jun 2023 10:47:27 +0200 Subject: [PATCH 032/136] Fix: issue 4077 After building JavaParser (with tests) on MacOS multiple committed files are modified --- .../javaparser/utils/SourceRootTest.java | 28 +++++++++++++------ 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/utils/SourceRootTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/utils/SourceRootTest.java index c8a7f60301..6d47658418 100644 --- a/javaparser-core-testing/src/test/java/com/github/javaparser/utils/SourceRootTest.java +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/utils/SourceRootTest.java @@ -21,14 +21,7 @@ package com.github.javaparser.utils; -import com.github.javaparser.ParseProblemException; -import com.github.javaparser.ParseResult; -import com.github.javaparser.ParserConfiguration; -import com.github.javaparser.ast.CompilationUnit; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.MockedStatic; -import org.mockito.Mockito; +import static org.junit.jupiter.api.Assertions.*; import java.io.IOException; import java.nio.file.Files; @@ -36,15 +29,30 @@ import java.nio.file.Paths; import java.util.List; -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.mockito.Mockito; + +import com.github.javaparser.ParseProblemException; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.printer.DefaultPrettyPrinter; +import com.github.javaparser.printer.Printer; +import com.github.javaparser.printer.configuration.DefaultConfigurationOption; +import com.github.javaparser.printer.configuration.DefaultPrinterConfiguration.ConfigOption; class SourceRootTest { private final Path root = CodeGenerationUtils.mavenModuleRoot(SourceRootTest.class).resolve("src/test/resources/com/github/javaparser/utils/"); private final SourceRoot sourceRoot = new SourceRoot(root); + private Printer printer; @BeforeEach void before() { sourceRoot.getParserConfiguration().setLanguageLevel(ParserConfiguration.LanguageLevel.BLEEDING_EDGE); + printer = new DefaultPrettyPrinter(); + sourceRoot.setPrinter(printer::print); } @Test @@ -59,11 +67,13 @@ void parseTestDirectory() throws IOException { @Test void saveInCallback() throws IOException { + printer.getConfiguration().addOption(new DefaultConfigurationOption(ConfigOption.END_OF_LINE_CHARACTER, LineSeparator.LF.asRawString())); sourceRoot.parse("", sourceRoot.getParserConfiguration(), (localPath, absolutePath, result) -> SourceRoot.Callback.Result.SAVE); } @Test void saveInCallbackParallelized() { + printer.getConfiguration().addOption(new DefaultConfigurationOption(ConfigOption.END_OF_LINE_CHARACTER, LineSeparator.LF.asRawString())); sourceRoot.parseParallelized("", sourceRoot.getParserConfiguration(), ((localPath, absolutePath, result) -> SourceRoot.Callback.Result.SAVE)); } From 8b358698318380d9b9b15c510a8e8cbe89a4c648 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 29 Jun 2023 23:55:48 +0000 Subject: [PATCH 033/136] chore(deps): bump guava from 32.0.0-jre to 32.1.0-jre Bumps [guava](https://github.com/google/guava) from 32.0.0-jre to 32.1.0-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 35963aa7ab..b20cc563c1 100644 --- a/pom.xml +++ b/pom.xml @@ -371,7 +371,7 @@ com.google.guava guava - 32.0.0-jre + 32.1.0-jre junit From 3e574764131a426d47f2891c755bb8c7d1f5be68 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 30 Jun 2023 23:39:33 +0000 Subject: [PATCH 034/136] chore(deps): bump guava from 32.1.0-jre to 32.1.1-jre Bumps [guava](https://github.com/google/guava) from 32.1.0-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index b20cc563c1..942a7b653c 100644 --- a/pom.xml +++ b/pom.xml @@ -371,7 +371,7 @@ com.google.guava guava - 32.1.0-jre + 32.1.1-jre junit From 73086c46aa0c75377cc5d8dd332e8830373c2a47 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Sat, 1 Jul 2023 16:39:10 +0200 Subject: [PATCH 035/136] Update changelog --- changelog.md | 47 +++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 45 insertions(+), 2 deletions(-) diff --git a/changelog.md b/changelog.md index 43d280e121..012a69ed02 100644 --- a/changelog.md +++ b/changelog.md @@ -1,7 +1,7 @@ -Next Release (Version 3.25.4-snapshot) +Next Release (Version 3.25.5-snapshot) -------------------------------------- -[issues resolved](https://github.com/javaparser/javaparser/milestone/200?closed=1) +[issues resolved](https://github.com/javaparser/javaparser/milestone/201?closed=1) ### Added ### Changed @@ -11,6 +11,49 @@ Next Release (Version 3.25.4-snapshot) ### Security +Version 3.25.4 +-------------- +[issues resolved](https://github.com/javaparser/javaparser/milestone/200?closed=1) + +### Changed + +* Nested 'if' statements should be simplified (PR [#4085](https://github.com/javaparser/javaparser/pull/4085) by [@jlerbsc](https://github.com/jlerbsc)) +* BDD tests: migarte to JBehave 5 (PR [#4028](https://github.com/javaparser/javaparser/pull/4028) by [@valfirst](https://github.com/valfirst)) + +### Fixed + +* Fix: issue 4077 After building JavaParser (with tests) on MacOS multi… (PR [#4086](https://github.com/javaparser/javaparser/pull/4086) by [@jlerbsc](https://github.com/jlerbsc)) +* fix line separators of selected test files (PR [#4083](https://github.com/javaparser/javaparser/pull/4083) by [@abego](https://github.com/abego)) +* Fix: issue 3978 typesolver can't parse in parallel (PR [#4073](https://github.com/javaparser/javaparser/pull/4073) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix #4056 isDeclaredInInterface() returns true for fields declared inside enumerations contained in an interface (PR [#4057](https://github.com/javaparser/javaparser/pull/4057) by [@Elewyth](https://github.com/Elewyth)) +* Fix: issue 4037 ArrayIndexOutOfBoundsException throws when method param is variadic (PR [#4046](https://github.com/javaparser/javaparser/pull/4046) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: issue 4016 Failed to parse variable with name 'sealed' or 'permits' (PR [#4039](https://github.com/javaparser/javaparser/pull/4039) by [@jlerbsc](https://github.com/jlerbsc)) + +### Developer Changes + +* chore(deps): bump guava from 32.1.0-jre to 32.1.1-jre (PR [#4089](https://github.com/javaparser/javaparser/pull/4089) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): bump guava from 32.0.0-jre to 32.1.0-jre (PR [#4087](https://github.com/javaparser/javaparser/pull/4087) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): bump checkstyle from 10.12.0 to 10.12.1 (PR [#4084](https://github.com/javaparser/javaparser/pull/4084) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): bump versions-maven-plugin from 2.15.0 to 2.16.0 (PR [#4055](https://github.com/javaparser/javaparser/pull/4055) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): bump maven-release-plugin from 3.0.0 to 3.0.1 (PR [#4053](https://github.com/javaparser/javaparser/pull/4053) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): bump guava from 31.1-jre to 32.0.0-jre (PR [#4042](https://github.com/javaparser/javaparser/pull/4042) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): bump maven-dependency-plugin from 3.5.0 to 3.6.0 (PR [#4035](https://github.com/javaparser/javaparser/pull/4035) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): bump maven-checkstyle-plugin from 3.2.2 to 3.3.0 (PR [#4033](https://github.com/javaparser/javaparser/pull/4033) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): bump maven-scm-plugin from 2.0.0 to 2.0.1 (PR [#4031](https://github.com/javaparser/javaparser/pull/4031) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): bump codecov/codecov-action from 3.1.3 to 3.1.4 (PR [#4030](https://github.com/javaparser/javaparser/pull/4030) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): bump build-helper-maven-plugin from 3.3.0 to 3.4.0 (PR [#4026](https://github.com/javaparser/javaparser/pull/4026) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): update dependency maven to v3.9.2 (PR [#4024](https://github.com/javaparser/javaparser/pull/4024) by [@renovate[bot]](https://github.com/apps/renovate)) + +### :heart: Contributors + +Thank You to all contributors who worked on this release! + +* [@valfirst](https://github.com/valfirst) +* [@abego](https://github.com/abego) +* [@Elewyth](https://github.com/Elewyth) +* [@jlerbsc](https://github.com/jlerbsc) + + Version 3.25.3 -------------- [issues resolved](https://github.com/javaparser/javaparser/milestone/199?closed=1) From 964f1549268b9a7766c409c722dc9c98e3230555 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Sat, 1 Jul 2023 16:40:18 +0200 Subject: [PATCH 036/136] update readme --- readme.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/readme.md b/readme.md index ae326ae271..0c52074f6f 100644 --- a/readme.md +++ b/readme.md @@ -37,14 +37,14 @@ Just add the following to your maven configuration or tailor to your own depende com.github.javaparser javaparser-symbol-solver-core - 3.25.3 + 3.25.4 ``` **Gradle**: ``` -implementation 'com.github.javaparser:javaparser-symbol-solver-core:3.25.3' +implementation 'com.github.javaparser:javaparser-symbol-solver-core:3.25.4' ``` Since Version 3.5.10, the JavaParser project includes the JavaSymbolSolver. @@ -59,14 +59,14 @@ Using the dependency above will add both JavaParser and JavaSymbolSolver to your com.github.javaparser javaparser-core - 3.25.3 + 3.25.4 ``` **Gradle**: ``` -implementation 'com.github.javaparser:javaparser-core:3.25.3' +implementation 'com.github.javaparser:javaparser-core:3.25.4' ``` Since version 3.6.17 the AST can be serialized to JSON. @@ -78,14 +78,14 @@ There is a separate module for this: com.github.javaparser javaparser-core-serialization - 3.25.3 + 3.25.4 ``` **Gradle**: ``` -implementation 'com.github.javaparser:javaparser-core-serialization:3.25.3' +implementation 'com.github.javaparser:javaparser-core-serialization:3.25.4' ``` ## How To Compile Sources From 67dcf3c505438a9bb41be0089ed4a546822274da Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Sat, 1 Jul 2023 16:41:19 +0200 Subject: [PATCH 037/136] [maven-release-plugin] prepare release javaparser-parent-3.25.4 --- javaparser-core-generators/pom.xml | 2 +- javaparser-core-metamodel-generator/pom.xml | 2 +- javaparser-core-serialization/pom.xml | 2 +- javaparser-core-testing-bdd/pom.xml | 2 +- javaparser-core-testing/pom.xml | 2 +- javaparser-core/pom.xml | 2 +- javaparser-symbol-solver-core/pom.xml | 2 +- javaparser-symbol-solver-testing/pom.xml | 2 +- pom.xml | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) diff --git a/javaparser-core-generators/pom.xml b/javaparser-core-generators/pom.xml index 0057ccddd4..a646f592ce 100644 --- a/javaparser-core-generators/pom.xml +++ b/javaparser-core-generators/pom.xml @@ -3,7 +3,7 @@ javaparser-parent com.github.javaparser - 3.25.4-SNAPSHOT + 3.25.4 4.0.0 diff --git a/javaparser-core-metamodel-generator/pom.xml b/javaparser-core-metamodel-generator/pom.xml index 5f3dfeee92..e6b01acfd7 100644 --- a/javaparser-core-metamodel-generator/pom.xml +++ b/javaparser-core-metamodel-generator/pom.xml @@ -3,7 +3,7 @@ javaparser-parent com.github.javaparser - 3.25.4-SNAPSHOT + 3.25.4 4.0.0 diff --git a/javaparser-core-serialization/pom.xml b/javaparser-core-serialization/pom.xml index 11a67d5ef4..4cb7b8c1bf 100644 --- a/javaparser-core-serialization/pom.xml +++ b/javaparser-core-serialization/pom.xml @@ -2,7 +2,7 @@ javaparser-parent com.github.javaparser - 3.25.4-SNAPSHOT + 3.25.4 4.0.0 diff --git a/javaparser-core-testing-bdd/pom.xml b/javaparser-core-testing-bdd/pom.xml index a1b76668b5..9a3a4348c3 100644 --- a/javaparser-core-testing-bdd/pom.xml +++ b/javaparser-core-testing-bdd/pom.xml @@ -2,7 +2,7 @@ javaparser-parent com.github.javaparser - 3.25.4-SNAPSHOT + 3.25.4 4.0.0 diff --git a/javaparser-core-testing/pom.xml b/javaparser-core-testing/pom.xml index d622aefa95..f0cfaa134d 100644 --- a/javaparser-core-testing/pom.xml +++ b/javaparser-core-testing/pom.xml @@ -2,7 +2,7 @@ javaparser-parent com.github.javaparser - 3.25.4-SNAPSHOT + 3.25.4 4.0.0 diff --git a/javaparser-core/pom.xml b/javaparser-core/pom.xml index 24f9735110..46ac9a7352 100644 --- a/javaparser-core/pom.xml +++ b/javaparser-core/pom.xml @@ -2,7 +2,7 @@ javaparser-parent com.github.javaparser - 3.25.4-SNAPSHOT + 3.25.4 4.0.0 diff --git a/javaparser-symbol-solver-core/pom.xml b/javaparser-symbol-solver-core/pom.xml index 77a9a1be5a..a5bc9be95a 100644 --- a/javaparser-symbol-solver-core/pom.xml +++ b/javaparser-symbol-solver-core/pom.xml @@ -3,7 +3,7 @@ javaparser-parent com.github.javaparser - 3.25.4-SNAPSHOT + 3.25.4 4.0.0 diff --git a/javaparser-symbol-solver-testing/pom.xml b/javaparser-symbol-solver-testing/pom.xml index 2a507b1b9a..0a2d99d06d 100644 --- a/javaparser-symbol-solver-testing/pom.xml +++ b/javaparser-symbol-solver-testing/pom.xml @@ -3,7 +3,7 @@ javaparser-parent com.github.javaparser - 3.25.4-SNAPSHOT + 3.25.4 4.0.0 diff --git a/pom.xml b/pom.xml index 942a7b653c..a4faa9a5f5 100644 --- a/pom.xml +++ b/pom.xml @@ -14,7 +14,7 @@ com.github.javaparser javaparser-parent pom - 3.25.4-SNAPSHOT + 3.25.4 javaparser-parent https://github.com/javaparser From d65ebb9f3b3a33c366d492dab732a95d624df29f Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Sat, 1 Jul 2023 16:52:23 +0200 Subject: [PATCH 038/136] [maven-release-plugin] prepare for next development iteration --- javaparser-core-generators/pom.xml | 2 +- javaparser-core-metamodel-generator/pom.xml | 2 +- javaparser-core-serialization/pom.xml | 2 +- javaparser-core-testing-bdd/pom.xml | 2 +- javaparser-core-testing/pom.xml | 2 +- javaparser-core/pom.xml | 2 +- javaparser-symbol-solver-core/pom.xml | 2 +- javaparser-symbol-solver-testing/pom.xml | 2 +- pom.xml | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) diff --git a/javaparser-core-generators/pom.xml b/javaparser-core-generators/pom.xml index a646f592ce..86e802971b 100644 --- a/javaparser-core-generators/pom.xml +++ b/javaparser-core-generators/pom.xml @@ -3,7 +3,7 @@ javaparser-parent com.github.javaparser - 3.25.4 + 3.25.5-SNAPSHOT 4.0.0 diff --git a/javaparser-core-metamodel-generator/pom.xml b/javaparser-core-metamodel-generator/pom.xml index e6b01acfd7..593c4d4886 100644 --- a/javaparser-core-metamodel-generator/pom.xml +++ b/javaparser-core-metamodel-generator/pom.xml @@ -3,7 +3,7 @@ javaparser-parent com.github.javaparser - 3.25.4 + 3.25.5-SNAPSHOT 4.0.0 diff --git a/javaparser-core-serialization/pom.xml b/javaparser-core-serialization/pom.xml index 4cb7b8c1bf..1afd575554 100644 --- a/javaparser-core-serialization/pom.xml +++ b/javaparser-core-serialization/pom.xml @@ -2,7 +2,7 @@ javaparser-parent com.github.javaparser - 3.25.4 + 3.25.5-SNAPSHOT 4.0.0 diff --git a/javaparser-core-testing-bdd/pom.xml b/javaparser-core-testing-bdd/pom.xml index 9a3a4348c3..4620af8408 100644 --- a/javaparser-core-testing-bdd/pom.xml +++ b/javaparser-core-testing-bdd/pom.xml @@ -2,7 +2,7 @@ javaparser-parent com.github.javaparser - 3.25.4 + 3.25.5-SNAPSHOT 4.0.0 diff --git a/javaparser-core-testing/pom.xml b/javaparser-core-testing/pom.xml index f0cfaa134d..767208eb79 100644 --- a/javaparser-core-testing/pom.xml +++ b/javaparser-core-testing/pom.xml @@ -2,7 +2,7 @@ javaparser-parent com.github.javaparser - 3.25.4 + 3.25.5-SNAPSHOT 4.0.0 diff --git a/javaparser-core/pom.xml b/javaparser-core/pom.xml index 46ac9a7352..6a45c1bfcd 100644 --- a/javaparser-core/pom.xml +++ b/javaparser-core/pom.xml @@ -2,7 +2,7 @@ javaparser-parent com.github.javaparser - 3.25.4 + 3.25.5-SNAPSHOT 4.0.0 diff --git a/javaparser-symbol-solver-core/pom.xml b/javaparser-symbol-solver-core/pom.xml index a5bc9be95a..70ee8c8a79 100644 --- a/javaparser-symbol-solver-core/pom.xml +++ b/javaparser-symbol-solver-core/pom.xml @@ -3,7 +3,7 @@ javaparser-parent com.github.javaparser - 3.25.4 + 3.25.5-SNAPSHOT 4.0.0 diff --git a/javaparser-symbol-solver-testing/pom.xml b/javaparser-symbol-solver-testing/pom.xml index 0a2d99d06d..a83b511855 100644 --- a/javaparser-symbol-solver-testing/pom.xml +++ b/javaparser-symbol-solver-testing/pom.xml @@ -3,7 +3,7 @@ javaparser-parent com.github.javaparser - 3.25.4 + 3.25.5-SNAPSHOT 4.0.0 diff --git a/pom.xml b/pom.xml index a4faa9a5f5..0486794c35 100644 --- a/pom.xml +++ b/pom.xml @@ -14,7 +14,7 @@ com.github.javaparser javaparser-parent pom - 3.25.4 + 3.25.5-SNAPSHOT javaparser-parent https://github.com/javaparser From 19e055943858d8a6436111bc22178fc2dd0d3514 Mon Sep 17 00:00:00 2001 From: Alessandro Autiero Date: Sun, 2 Jul 2023 23:16:03 +0200 Subject: [PATCH 039/136] Fixed missing permits in pretty printer --- .../printer/DefaultPrettyPrinterVisitor.java | 10 ++++++++++ .../github/javaparser/printer/PrettyPrintVisitor.java | 10 ++++++++++ 2 files changed, 20 insertions(+) diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/DefaultPrettyPrinterVisitor.java b/javaparser-core/src/main/java/com/github/javaparser/printer/DefaultPrettyPrinterVisitor.java index 7b8b9b5c78..0e3728cb8c 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/DefaultPrettyPrinterVisitor.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/DefaultPrettyPrinterVisitor.java @@ -297,6 +297,16 @@ public void visit(final ClassOrInterfaceDeclaration n, final Void arg) { } } } + if(!n.getPermittedTypes().isEmpty()){ + printer.print(" permits "); + for (final Iterator i = n.getPermittedTypes().iterator(); i.hasNext(); ) { + final ClassOrInterfaceType c = i.next(); + c.accept(this, arg); + if (i.hasNext()) { + printer.print(", "); + } + } + } printer.println(" {"); printer.indent(); if (!isNullOrEmpty(n.getMembers())) { diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/PrettyPrintVisitor.java b/javaparser-core/src/main/java/com/github/javaparser/printer/PrettyPrintVisitor.java index d73712b741..599e767323 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/PrettyPrintVisitor.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/PrettyPrintVisitor.java @@ -305,6 +305,16 @@ public void visit(final ClassOrInterfaceDeclaration n, final Void arg) { } } } + if(!n.getPermittedTypes().isEmpty()){ + printer.print(" permits "); + for (final Iterator i = n.getPermittedTypes().iterator(); i.hasNext(); ) { + final ClassOrInterfaceType c = i.next(); + c.accept(this, arg); + if (i.hasNext()) { + printer.print(", "); + } + } + } printer.println(" {"); printer.indent(); if (!isNullOrEmpty(n.getMembers())) { From a210dab7edff41dfb54f854c9820c7456da0006e Mon Sep 17 00:00:00 2001 From: Alessandro Autiero Date: Sun, 2 Jul 2023 23:18:43 +0200 Subject: [PATCH 040/136] Added sealedModifier and nonSealedModifier named constructors to Modifier --- .../src/main/java/com/github/javaparser/ast/Modifier.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/Modifier.java b/javaparser-core/src/main/java/com/github/javaparser/ast/Modifier.java index fc788cd916..21441ab9d6 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/Modifier.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/Modifier.java @@ -86,6 +86,14 @@ public static Modifier transitiveModifier() { return new Modifier(Keyword.TRANSITIVE); } + public static Modifier sealedModifier() { + return new Modifier(Keyword.SEALED); + } + + public static Modifier nonSealedModifier() { + return new Modifier(Keyword.NON_SEALED); + } + /** * The Java modifier keywords. */ From 75ad60c2ec0a1db299bf24839fa3f93900e61290 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sun, 23 Jul 2023 15:23:10 +0000 Subject: [PATCH 041/136] chore(deps): update junit5 monorepo to v5.10.0 --- pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index 0486794c35..776d3b9e18 100644 --- a/pom.xml +++ b/pom.xml @@ -388,19 +388,19 @@ org.junit.jupiter junit-jupiter-engine - 5.9.3 + 5.10.0 test org.junit.jupiter junit-jupiter-params - 5.9.3 + 5.10.0 test org.junit.vintage junit-vintage-engine - 5.9.3 + 5.10.0 test From 5ec633df2dbbf8b36507f72614d7b576831ee44a Mon Sep 17 00:00:00 2001 From: freya02 <41875020+freya022@users.noreply.github.com> Date: Sun, 23 Jul 2023 22:11:44 +0200 Subject: [PATCH 042/136] Fix typo --- .../ReflectionAnnotationMemberDeclaration.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionAnnotationMemberDeclaration.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionAnnotationMemberDeclaration.java index 82418c2db2..a29099aeaf 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionAnnotationMemberDeclaration.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionAnnotationMemberDeclaration.java @@ -40,14 +40,14 @@ */ public class ReflectionAnnotationMemberDeclaration implements ResolvedAnnotationMemberDeclaration { - private static Map, Function> valueAsExressionConverter = new HashMap<>(); + private static Map, Function> valueAsExpressionConverters = new HashMap<>(); static { - valueAsExressionConverter.put(Boolean.class, (value) -> new BooleanLiteralExpr(Boolean.class.cast(value))); - valueAsExressionConverter.put(Character.class, (value) -> new CharLiteralExpr(Character.class.cast(value))); - valueAsExressionConverter.put(Double.class, (value) -> new DoubleLiteralExpr(Double.class.cast(value))); - valueAsExressionConverter.put(Integer.class, (value) -> new IntegerLiteralExpr(Integer.class.cast(value))); - valueAsExressionConverter.put(Long.class, (value) -> new LongLiteralExpr(Long.class.cast(value))); - valueAsExressionConverter.put(String.class, (value) -> new StringLiteralExpr(String.class.cast(value))); + valueAsExpressionConverters.put(Boolean.class, (value) -> new BooleanLiteralExpr((Boolean) value)); + valueAsExpressionConverters.put(Character.class, (value) -> new CharLiteralExpr((Character) value)); + valueAsExpressionConverters.put(Double.class, (value) -> new DoubleLiteralExpr((Double) value)); + valueAsExpressionConverters.put(Integer.class, (value) -> new IntegerLiteralExpr((Integer) value)); + valueAsExpressionConverters.put(Long.class, (value) -> new LongLiteralExpr((Long) value)); + valueAsExpressionConverters.put(String.class, (value) -> new StringLiteralExpr((String) value)); } private Method annotationMember; @@ -61,7 +61,7 @@ public ReflectionAnnotationMemberDeclaration(Method annotationMember, TypeSolver @Override public Expression getDefaultValue() { Object value = annotationMember.getDefaultValue(); - Function fn = valueAsExressionConverter.get(value.getClass()); + Function fn = valueAsExpressionConverters.get(value.getClass()); if (fn == null) throw new UnsupportedOperationException(String.format("Obtaining the type of the annotation member %s is not supported yet.", annotationMember.getName())); return fn.apply(value); } From f8000d94d39e3b39091ab232e568dc9d8700a8db Mon Sep 17 00:00:00 2001 From: freya02 <41875020+freya022@users.noreply.github.com> Date: Sun, 23 Jul 2023 22:55:49 +0200 Subject: [PATCH 043/136] Add support for Class, enums, nested annotations, and arrays when getting the default value of an annotation --- ...ReflectionAnnotationMemberDeclaration.java | 45 ++++++++++++++++- .../resolution/AnnotationsResolutionTest.java | 48 ++++++++++++++++++- .../testingclasses/TargetType.java | 25 ++++++++++ .../src/test/resources/Annotations.java.txt | 5 ++ 4 files changed, 121 insertions(+), 2 deletions(-) create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/testingclasses/TargetType.java diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionAnnotationMemberDeclaration.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionAnnotationMemberDeclaration.java index a29099aeaf..2e38f82c1b 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionAnnotationMemberDeclaration.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionAnnotationMemberDeclaration.java @@ -21,7 +21,9 @@ package com.github.javaparser.symbolsolver.reflectionmodel; +import com.github.javaparser.ast.NodeList; import com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.type.ClassOrInterfaceType; import com.github.javaparser.resolution.TypeSolver; import com.github.javaparser.resolution.declarations.ResolvedAnnotationMemberDeclaration; import com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration; @@ -30,7 +32,9 @@ import com.github.javaparser.resolution.types.ResolvedPrimitiveType; import com.github.javaparser.resolution.types.ResolvedType; +import java.lang.annotation.Annotation; import java.lang.reflect.Method; +import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.function.Function; @@ -48,6 +52,10 @@ public class ReflectionAnnotationMemberDeclaration implements ResolvedAnnotation valueAsExpressionConverters.put(Integer.class, (value) -> new IntegerLiteralExpr((Integer) value)); valueAsExpressionConverters.put(Long.class, (value) -> new LongLiteralExpr((Long) value)); valueAsExpressionConverters.put(String.class, (value) -> new StringLiteralExpr((String) value)); + valueAsExpressionConverters.put(Class.class, (value) -> { + final ClassOrInterfaceType type = new ClassOrInterfaceType(null, ((Class) value).getSimpleName()); + return new ClassExpr(type); + }); } private Method annotationMember; @@ -61,8 +69,43 @@ public ReflectionAnnotationMemberDeclaration(Method annotationMember, TypeSolver @Override public Expression getDefaultValue() { Object value = annotationMember.getDefaultValue(); + if (value == null) return null; + + if (value.getClass().isArray()) { + Object[] values = (Object[]) value; + final NodeList expressions = Arrays.stream(values) + .map(this::transformDefaultValue) + .collect(NodeList.toNodeList()); + return new ArrayInitializerExpr(expressions); + } + + return transformDefaultValue(value); + } + + private Expression transformDefaultValue(Object value) { + if (value instanceof Enum) { + final Class declaringClass = ((Enum) value).getDeclaringClass(); + final String name = ((Enum) value).name(); + return new FieldAccessExpr(new NameExpr(declaringClass.getSimpleName()), name); + } else if (value instanceof Annotation) { + final Class annotationType = ((Annotation) value).annotationType(); + final Method[] declaredMethods = annotationType.getDeclaredMethods(); + final NodeList pairs = Arrays.stream(declaredMethods) + .map(m -> { + final ReflectionAnnotationMemberDeclaration nestedMemberDeclaration = new ReflectionAnnotationMemberDeclaration(m, typeSolver); + return new MemberValuePair(m.getName(), nestedMemberDeclaration.getDefaultValue()); + }) + .collect(NodeList.toNodeList()); + + return new NormalAnnotationExpr(new Name(annotationType.getSimpleName()), pairs); + } + Function fn = valueAsExpressionConverters.get(value.getClass()); - if (fn == null) throw new UnsupportedOperationException(String.format("Obtaining the type of the annotation member %s is not supported yet.", annotationMember.getName())); + if (fn == null) + throw new UnsupportedOperationException( + String.format("Obtaining the default value of the annotation member %s (of type %s) is not supported yet.", + annotationMember.getName(), value.getClass().getSimpleName()) + ); return fn.apply(value); } diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/AnnotationsResolutionTest.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/AnnotationsResolutionTest.java index 947f689130..e0b05ae2b1 100644 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/AnnotationsResolutionTest.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/AnnotationsResolutionTest.java @@ -23,8 +23,10 @@ import com.github.javaparser.StaticJavaParser; import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.NodeList; import com.github.javaparser.ast.body.*; import com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.type.ClassOrInterfaceType; import com.github.javaparser.resolution.Navigator; import com.github.javaparser.resolution.declarations.ResolvedAnnotationDeclaration; import com.github.javaparser.resolution.declarations.ResolvedAnnotationMemberDeclaration; @@ -57,7 +59,7 @@ class AnnotationsResolutionTest extends AbstractResolutionTest { void configureSymbolSolver() throws IOException { // configure symbol solver before parsing CombinedTypeSolver typeSolver = new CombinedTypeSolver(); - typeSolver.add(new ReflectionTypeSolver()); + typeSolver.add(new ReflectionTypeSolver(false)); typeSolver.add(new JarTypeSolver(adaptPath("src/test/resources/junit-4.8.1.jar"))); StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(typeSolver)); } @@ -359,4 +361,48 @@ void solveInnerClassAnnotationMember() throws IOException { assertEquals(am.getType().asReferenceType().getQualifiedName(), "foo.bar.MyAnnotationWithInnerClass.MyInnerClass"); } + @Test + void solveReflectionMarkerAnnotationWithDefaultValues() throws IOException { + // parse compilation unit and get annotation expression + CompilationUnit cu = parseSample("Annotations"); + ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "CI"); + + MarkerAnnotationExpr annotationExpr = clazz.getAnnotation(0).asMarkerAnnotationExpr(); + + // resolve annotation expression + ResolvedAnnotationDeclaration resolved = annotationExpr.resolve(); + // get default values + // Class[] - {} + Expression arrayExpr = findAnnotationMemberByName(resolved, "packagesOf").getDefaultValue(); + assertInstanceOf(ArrayInitializerExpr.class, arrayExpr); + final NodeList values = ((ArrayInitializerExpr) arrayExpr).getValues(); + assertTrue(values.isNonEmpty()); + assertTrue(values.get(0).isClassExpr()); + assertEquals("MethodHandle", values.get(0).asClassExpr().getType().asString()); + + // Class - LambdaMetafactory.class + ClassExpr classExpr = assertInstanceOf(ClassExpr.class, findAnnotationMemberByName(resolved, "clazz").getDefaultValue()); + final ClassOrInterfaceType type = assertInstanceOf(ClassOrInterfaceType.class, classExpr.getType()); + assertEquals("LambdaMetafactory", type.getNameAsString()); + + // TimeUnit - TimeUnit.HOURS + Expression enumExpr = findAnnotationMemberByName(resolved, "unit").getDefaultValue(); + final FieldAccessExpr fieldAccessExpr = assertInstanceOf(FieldAccessExpr.class, enumExpr); + final NameExpr scopeNameExpr = assertInstanceOf(NameExpr.class, fieldAccessExpr.getScope()); + assertEquals("TimeUnit", scopeNameExpr.asNameExpr().getNameAsString()); + assertEquals("HOURS", fieldAccessExpr.getNameAsString()); + + // NestedAnnotation - @NestedAnnotation + Expression nestedExpr = findAnnotationMemberByName(resolved, "nestedAnnotation").getDefaultValue(); + assertInstanceOf(NormalAnnotationExpr.class, nestedExpr); + assertEquals("NestedAnnotation", nestedExpr.asNormalAnnotationExpr().getNameAsString()); + } + + private ResolvedAnnotationMemberDeclaration findAnnotationMemberByName(ResolvedAnnotationDeclaration resolved, String memberName) { + return resolved.getAnnotationMembers().stream() + .filter(a -> memberName.equals(a.getName())) + .findAny() + .orElseThrow(() -> new IllegalArgumentException(String.format("Could not find annotation member %s in %s", + memberName, resolved.getName()))); + } } diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/testingclasses/TargetType.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/testingclasses/TargetType.java new file mode 100644 index 0000000000..058404db94 --- /dev/null +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/testingclasses/TargetType.java @@ -0,0 +1,25 @@ +package com.github.javaparser.symbolsolver.testingclasses; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.lang.invoke.LambdaMetafactory; +import java.lang.invoke.MethodHandle; +import java.util.concurrent.TimeUnit; + +@interface NestedAnnotation { + +} + +@Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR}) +@Retention(RetentionPolicy.SOURCE) +public @interface TargetType { + Class[] packagesOf() default {MethodHandle.class}; + + Class clazz() default LambdaMetafactory.class; + + TimeUnit unit() default TimeUnit.HOURS; + + NestedAnnotation nestedAnnotation() default @NestedAnnotation; +} \ No newline at end of file diff --git a/javaparser-symbol-solver-testing/src/test/resources/Annotations.java.txt b/javaparser-symbol-solver-testing/src/test/resources/Annotations.java.txt index 0f8e7d5bae..5377d7a66d 100644 --- a/javaparser-symbol-solver-testing/src/test/resources/Annotations.java.txt +++ b/javaparser-symbol-solver-testing/src/test/resources/Annotations.java.txt @@ -3,6 +3,7 @@ package foo.bar; import java.lang.annotation.*; import java.beans.*; import org.junit.*; +import com.github.javaparser.symbolsolver.testingclasses.TargetType; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @@ -76,6 +77,10 @@ class CH { @Transient public String field; } +@TargetType +class CI { +} + @Inherited public @interface InheritedAnnotation { } From e0413ed30da8f241ea2abb7da77f12fed8c84de1 Mon Sep 17 00:00:00 2001 From: freya02 <41875020+freya022@users.noreply.github.com> Date: Mon, 24 Jul 2023 17:51:38 +0200 Subject: [PATCH 044/136] Separate tests --- .../resolution/AnnotationsResolutionTest.java | 40 ++++++++++++++++++- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/AnnotationsResolutionTest.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/AnnotationsResolutionTest.java index e0b05ae2b1..33dca095da 100644 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/AnnotationsResolutionTest.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/AnnotationsResolutionTest.java @@ -362,7 +362,7 @@ void solveInnerClassAnnotationMember() throws IOException { } @Test - void solveReflectionMarkerAnnotationWithDefaultValues() throws IOException { + void solveReflectionMarkerAnnotationWithDefaultArrayValue() throws IOException { // parse compilation unit and get annotation expression CompilationUnit cu = parseSample("Annotations"); ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "CI"); @@ -371,7 +371,7 @@ void solveReflectionMarkerAnnotationWithDefaultValues() throws IOException { // resolve annotation expression ResolvedAnnotationDeclaration resolved = annotationExpr.resolve(); - // get default values + // Class[] - {} Expression arrayExpr = findAnnotationMemberByName(resolved, "packagesOf").getDefaultValue(); assertInstanceOf(ArrayInitializerExpr.class, arrayExpr); @@ -379,11 +379,35 @@ void solveReflectionMarkerAnnotationWithDefaultValues() throws IOException { assertTrue(values.isNonEmpty()); assertTrue(values.get(0).isClassExpr()); assertEquals("MethodHandle", values.get(0).asClassExpr().getType().asString()); + } + + @Test + void solveReflectionMarkerAnnotationWithDefaultClassValue() throws IOException { + // parse compilation unit and get annotation expression + CompilationUnit cu = parseSample("Annotations"); + ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "CI"); + + MarkerAnnotationExpr annotationExpr = clazz.getAnnotation(0).asMarkerAnnotationExpr(); + + // resolve annotation expression + ResolvedAnnotationDeclaration resolved = annotationExpr.resolve(); // Class - LambdaMetafactory.class ClassExpr classExpr = assertInstanceOf(ClassExpr.class, findAnnotationMemberByName(resolved, "clazz").getDefaultValue()); final ClassOrInterfaceType type = assertInstanceOf(ClassOrInterfaceType.class, classExpr.getType()); assertEquals("LambdaMetafactory", type.getNameAsString()); + } + + @Test + void solveReflectionMarkerAnnotationWithDefaultEnumValue() throws IOException { + // parse compilation unit and get annotation expression + CompilationUnit cu = parseSample("Annotations"); + ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "CI"); + + MarkerAnnotationExpr annotationExpr = clazz.getAnnotation(0).asMarkerAnnotationExpr(); + + // resolve annotation expression + ResolvedAnnotationDeclaration resolved = annotationExpr.resolve(); // TimeUnit - TimeUnit.HOURS Expression enumExpr = findAnnotationMemberByName(resolved, "unit").getDefaultValue(); @@ -391,6 +415,18 @@ void solveReflectionMarkerAnnotationWithDefaultValues() throws IOException { final NameExpr scopeNameExpr = assertInstanceOf(NameExpr.class, fieldAccessExpr.getScope()); assertEquals("TimeUnit", scopeNameExpr.asNameExpr().getNameAsString()); assertEquals("HOURS", fieldAccessExpr.getNameAsString()); + } + + @Test + void solveReflectionMarkerAnnotationWithDefaultNestedAnnotationValue() throws IOException { + // parse compilation unit and get annotation expression + CompilationUnit cu = parseSample("Annotations"); + ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "CI"); + + MarkerAnnotationExpr annotationExpr = clazz.getAnnotation(0).asMarkerAnnotationExpr(); + + // resolve annotation expression + ResolvedAnnotationDeclaration resolved = annotationExpr.resolve(); // NestedAnnotation - @NestedAnnotation Expression nestedExpr = findAnnotationMemberByName(resolved, "nestedAnnotation").getDefaultValue(); From e8c325aa51c2b7ff08e36d327be1e73b4c46cedc Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Thu, 27 Jul 2023 15:48:41 +0200 Subject: [PATCH 045/136] Fix: issue 4104 LPP doesn't handle new switch entries well --- .../lexicalpreservation/Issue4104Test.java | 81 +++++++++++++++++++ .../lexicalpreservation/Difference.java | 3 + 2 files changed, 84 insertions(+) create mode 100755 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue4104Test.java diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue4104Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue4104Test.java new file mode 100755 index 0000000000..4498b777e0 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue4104Test.java @@ -0,0 +1,81 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2023 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.printer.lexicalpreservation; + +import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol; + +import org.junit.jupiter.api.Test; + +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.expr.IntegerLiteralExpr; +import com.github.javaparser.ast.stmt.BreakStmt; +import com.github.javaparser.ast.stmt.SwitchEntry; +import com.github.javaparser.ast.stmt.SwitchStmt; + +public class Issue4104Test extends AbstractLexicalPreservingTest { + + @Test + void test() { + considerCode( + "class Foo {\n" + + " void foo() {\n" + + " switch(bar) {\n" + + " default:\n" + + " break;\n" + + " }\n" + + " }\n" + + "}"); + // should be this +// String expected = +// "class Foo {\n" +// + " void foo() {\n" +// + " switch(bar) {\n" +// + " default:\n" +// + " break;\n" +// + " case 0:\n" +// + " break;\n" +// + " }\n" +// + " }\n" +// + "}"; + + String expected = + "class Foo {\n" + + " void foo() {\n" + + " switch(bar) {\n" + + " default:\n" + + " break;\n" + + " case 0:\n" + + " break;\n" + + " }\n" + + " }\n" + + "}"; + + SwitchStmt switchStmt = cu.findAll(SwitchStmt.class).stream().findFirst().get(); + + SwitchEntry newEntry = new SwitchEntry(); + newEntry.setLabels(NodeList.nodeList(new IntegerLiteralExpr(0))); + newEntry.setStatements(NodeList.nodeList(new BreakStmt())); + switchStmt.getEntries().addLast(newEntry); + + assertEqualsStringIgnoringEol(expected, LexicalPreservingPrinter.print(cu)); + } +} diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java index 82a9e621cb..4ee2c17162 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java @@ -1049,6 +1049,9 @@ private void applyAddedDiffElement(Added added) { if (!isPreviousElementNewline && !isFirstElement && !previousIsWhiteSpace) { // Insert after the new line originalIndex++; + // We want to adjust the indentation while considering the new element that we + // added + originalIndex = adjustIndentation(indentation, nodeText, originalIndex, false); } nodeText.addElement(originalIndex, addedTextElement); originalIndex++; From b27ac6fa0cc513f6bd0ac0bfb370a69a73b19a44 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sun, 30 Jul 2023 18:48:48 +0000 Subject: [PATCH 046/136] chore(deps): update dependency com.puppycrawl.tools:checkstyle to v10.12.2 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 776d3b9e18..6d3bd763e1 100644 --- a/pom.xml +++ b/pom.xml @@ -352,7 +352,7 @@ com.puppycrawl.tools checkstyle - 10.12.1 + 10.12.2 From dccb701f872ee075d205e4a53cd46019cb71a12c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 31 Jul 2023 23:29:06 +0000 Subject: [PATCH 047/136] chore(deps): bump com.google.guava:guava from 32.1.1-jre to 32.1.2-jre Bumps [com.google.guava:guava](https://github.com/google/guava) from 32.1.1-jre to 32.1.2-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 6d3bd763e1..448a14f6f0 100644 --- a/pom.xml +++ b/pom.xml @@ -371,7 +371,7 @@ com.google.guava guava - 32.1.1-jre + 32.1.2-jre junit From c215f4513828dd359a7519829833ee5aa3276952 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 31 Jul 2023 23:29:22 +0000 Subject: [PATCH 048/136] fix(deps): update dependency com.google.guava:guava to v32.1.2-jre --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 6d3bd763e1..448a14f6f0 100644 --- a/pom.xml +++ b/pom.xml @@ -371,7 +371,7 @@ com.google.guava guava - 32.1.1-jre + 32.1.2-jre junit From 2a156ba2f477b17745c2da33d9f12d3ce2562a03 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Mon, 7 Aug 2023 16:09:22 +0200 Subject: [PATCH 049/136] resolved merge conflicts --- .../javaparser/printer/lexicalpreservation/Difference.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java index 4ee2c17162..95f7516a8b 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java @@ -80,7 +80,7 @@ public class Difference { /* * Returns the indentation used after the last line break */ - private List processIndentation(List indentation, List prevElements) { + List processIndentation(List indentation, List prevElements) { int eolIndex = lastIndexOfEol(prevElements); // Return "indentation" as is if no EOL element was found if (eolIndex < 0) @@ -215,7 +215,7 @@ private boolean isAfterLBrace(NodeText nodeText, int nodeTextIndex) { * [ ][ ]void[ ]m{} * } */ - private int considerEnforcingIndentation(NodeText nodeText, int nodeTextIndex) { + int considerEnforcingIndentation(NodeText nodeText, int nodeTextIndex) { return considerIndentation(nodeText, nodeTextIndex, indentation.size()); } @@ -316,7 +316,7 @@ private EnforcingIndentationContext defineEnforcingIndentationContext(NodeText n } } // compute space after the deleted element - if (isSpaceOrTabElement(nodeText, startIndex)) { + if (startIndex < nodeText.numberOfElements() && isSpaceOrTabElement(nodeText, startIndex)) { // int startingFromIndex = startIndex == 0 ? startIndex : startIndex + 1; for (int i = startIndex; i >= 0 && i < nodeText.numberOfElements(); i++) { if (nodeText.getTextElement(i).isNewline()) { From 7fcf05b12e24ac852d56378ef1a141a0f4f53d9b Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Thu, 10 Aug 2023 14:42:16 +0200 Subject: [PATCH 050/136] Added comments and minor refactoring --- .../LexicalPreservingPrinter.java | 134 +++++++++--------- 1 file changed, 66 insertions(+), 68 deletions(-) diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinter.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinter.java index 9edf9a9fb7..2a78af3407 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinter.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinter.java @@ -20,20 +20,7 @@ */ package com.github.javaparser.printer.lexicalpreservation; -import static com.github.javaparser.GeneratedJavaParserConstants.BOOLEAN; -import static com.github.javaparser.GeneratedJavaParserConstants.BYTE; -import static com.github.javaparser.GeneratedJavaParserConstants.CHAR; -import static com.github.javaparser.GeneratedJavaParserConstants.DOUBLE; -import static com.github.javaparser.GeneratedJavaParserConstants.FLOAT; -import static com.github.javaparser.GeneratedJavaParserConstants.INT; -import static com.github.javaparser.GeneratedJavaParserConstants.JAVADOC_COMMENT; -import static com.github.javaparser.GeneratedJavaParserConstants.LBRACKET; -import static com.github.javaparser.GeneratedJavaParserConstants.LONG; -import static com.github.javaparser.GeneratedJavaParserConstants.MULTI_LINE_COMMENT; -import static com.github.javaparser.GeneratedJavaParserConstants.RBRACKET; -import static com.github.javaparser.GeneratedJavaParserConstants.SHORT; -import static com.github.javaparser.GeneratedJavaParserConstants.SINGLE_LINE_COMMENT; -import static com.github.javaparser.GeneratedJavaParserConstants.SPACE; +import static com.github.javaparser.GeneratedJavaParserConstants.*; import static com.github.javaparser.TokenTypes.eolTokenKind; import static com.github.javaparser.utils.Utils.assertNotNull; import static com.github.javaparser.utils.Utils.decapitalize; @@ -43,15 +30,7 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; -import java.util.ArrayList; -import java.util.Collections; -import java.util.IdentityHashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.ListIterator; -import java.util.Map; -import java.util.Optional; +import java.util.*; import com.github.javaparser.JavaToken; import com.github.javaparser.Range; @@ -71,11 +50,7 @@ import com.github.javaparser.ast.type.PrimitiveType; import com.github.javaparser.ast.visitor.TreeVisitor; import com.github.javaparser.printer.ConcreteSyntaxModel; -import com.github.javaparser.printer.concretesyntaxmodel.CsmElement; -import com.github.javaparser.printer.concretesyntaxmodel.CsmIndent; -import com.github.javaparser.printer.concretesyntaxmodel.CsmMix; -import com.github.javaparser.printer.concretesyntaxmodel.CsmToken; -import com.github.javaparser.printer.concretesyntaxmodel.CsmUnindent; +import com.github.javaparser.printer.concretesyntaxmodel.*; import com.github.javaparser.printer.lexicalpreservation.LexicalDifferenceCalculator.CsmChild; import com.github.javaparser.utils.LineSeparator; import com.github.javaparser.utils.Pair; @@ -101,9 +76,9 @@ public class LexicalPreservingPrinter { private static final LexicalDifferenceCalculator LEXICAL_DIFFERENCE_CALCULATOR = new LexicalDifferenceCalculator(); - // + // // Factory methods - // + // /** * Prepares the node so it can be used in the print methods. * The correct order is: @@ -130,7 +105,7 @@ public static N setup(N node) { }); return node; } - + /* * Returns true if the lexical preserving printer is initialized on the node */ @@ -138,9 +113,9 @@ public static boolean isAvailableOn(Node node) { return node.containsData(NODE_TEXT_DATA); } - // + // // Constructor and setup - // + // private static AstObserver createObserver() { return new LexicalPreservingPrinter.Observer(); } @@ -162,13 +137,33 @@ public void concretePropertyChange(Node observedNode, ObservableProperty propert orElse(getOrCreateNodeText(observedNode)); if (oldValue == null) { // this case corresponds to the addition of a comment int index = parentNode.isPresent() ? // Find the position of the comment node and put in front of it the [...] - nodeText.findChild(observedNode) : // + nodeText.findChild(observedNode) : // 0; - // Add the same indent depth of the comment to the following node - fixIndentOfMovedNode(nodeText, index); + /* Add the same indentation to the comment as the previous node + * for example if we want to add a comment on the body of the method declaration : + * Actual code + * {@code + * public class Foo { + * void visit(final UnknownType n, final Void arg) + * { + * } + * } + * } + * Expected result + * {@code + * public class Foo { + * void visit(final UnknownType n, final Void arg) + * //added comment <-- we should insert indentation before the comment + * { + * } + * } + * } + */ + fixIndentOfAddedNode(nodeText, index - 1); LineSeparator lineSeparator = observedNode.getLineEndingStyleOrDefault(LineSeparator.SYSTEM); - nodeText.addElement(index, makeCommentToken((Comment) newValue)); - nodeText.addToken(index + 1, eolTokenKind(lineSeparator), lineSeparator.asRawString()); + nodeText.addElement(index++, makeCommentToken((Comment) newValue)); + nodeText.addToken(index, eolTokenKind(lineSeparator), lineSeparator.asRawString()); + // code indentation after inserting an eol token may be wrong } else if (newValue == null) { // this case corresponds to a deletion of a comment if (oldValue instanceof Comment) { if (((Comment) oldValue).isOrphan()) { @@ -188,6 +183,7 @@ public void concretePropertyChange(Node observedNode, ObservableProperty propert throw new UnsupportedOperationException("Trying to remove something that is not a comment!"); } } else { + // this is a replacement of a comment List matchingTokens = findTokenTextElementForComment((Comment) oldValue, nodeText); if (matchingTokens.size() != 1) { throw new IllegalStateException("The matching comment to be replaced could not be found"); @@ -203,12 +199,12 @@ public void concretePropertyChange(Node observedNode, ObservableProperty propert } LEXICAL_DIFFERENCE_CALCULATOR.calculatePropertyChange(nodeText, observedNode, property, oldValue, newValue); } - + private boolean isCompleteLine(List elements , int index) { if (index <= 0 || index >= elements.size()) return false; boolean isCompleteLine=true; ListIterator iterator = elements.listIterator(index); - // verify if elements after the index are only spaces or tabs + // verify if elements after the index are only spaces or tabs while(iterator.hasNext()) { TextElement textElement = iterator.next(); if (textElement.isNewline()) break; @@ -216,7 +212,7 @@ private boolean isCompleteLine(List elements , int index) { isCompleteLine=false; break; } - // verify if elements before the index are only spaces or tabs + // verify if elements before the index are only spaces or tabs iterator = elements.listIterator(index); while(iterator.hasPrevious() && isCompleteLine) { TextElement textElement = iterator.previous(); @@ -224,10 +220,10 @@ private boolean isCompleteLine(List elements , int index) { if (textElement.isSpaceOrTab()) continue; isCompleteLine=false; } - + return isCompleteLine; } - + private void removeAllExtraCharacters(List elements , int index) { if (index < 0 || index >= elements.size()) return; removeAllExtraCharactersStartingFrom(elements.listIterator(index)); @@ -264,7 +260,7 @@ private void removeAllExtraCharactersStartingFrom(ListIterator iter break; } } - + private TokenTextElement makeCommentToken(Comment newComment) { if (newComment.isJavadocComment()) { return new TokenTextElement(JAVADOC_COMMENT, newComment.getHeader() + newComment.getContent() + newComment.getFooter()); @@ -302,7 +298,7 @@ private List findChildTextElementForComment(Comment oldValue, } return matchingChildElements; } - + private List selectMatchingChildElements(Comment oldValue, NodeText nodeText) { List result = new ArrayList<>(); List childTextElements = nodeText.getElements().stream().filter(e -> e.isChild()) @@ -322,7 +318,7 @@ private List selectMatchingChildElements(Comment oldValue, Nod } return result; } - + private boolean isSameComment(Comment childValue, Comment oldValue) { return childValue.getContent().equals(oldValue.getContent()); } @@ -350,27 +346,29 @@ private boolean isEqualRange(Optional range1, Optional range2) { return false; } - /** - * This method inserts new space tokens at the given {@code index}. If a new comment is added to the node - * at the position of {@code index}, the new comment and the node will have the same indent. - * - * @param nodeText The text of the node - * @param index The position where a new comment will be added to - */ - private void fixIndentOfMovedNode(NodeText nodeText, int index) { + /** + * This method inserts new space tokens at the given {@code index}. If a new + * comment is added to the token list at the position following {@code index}, + * the new comment and the node will have the same indent. + * + * @param nodeText The text of the node + * @param index The position at which the analysis should start + */ + private void fixIndentOfAddedNode(NodeText nodeText, int index) { if (index <= 0) { return; } TextElement currentSpaceCandidate = null; - for (int i = index - 1; i >= 0; i--) { + for (int i = index; i >= 0; i--) { TextElement spaceCandidate = nodeText.getTextElement(i); if (spaceCandidate.isSpaceOrTab()) { // save the current indentation char currentSpaceCandidate = nodeText.getTextElement(i); } if (!spaceCandidate.isSpaceOrTab()) { - if (spaceCandidate.isNewline() && i != index - 1) { - for (int j = 0; j < (index - 1) - i; j++) { + if (spaceCandidate.isNewline() && i != index) { + int numberOfIndentationCharacters = index - i; + for (int j = 0; j < numberOfIndentationCharacters; j++) { if (currentSpaceCandidate != null) { // use the current (or last) indentation character nodeText.addElement(index, new TokenTextElement(JavaToken.Kind.SPACE.getKind(), currentSpaceCandidate.expand())); @@ -435,7 +433,7 @@ public void process(Node node) { }.visitBreadthFirst(root); }); } - + private static Optional findNodeForToken(Node node, Range tokenRange) { if (node.isPhantom()) { return Optional.empty(); @@ -475,9 +473,9 @@ private static void storeInitialTextForOneNode(Node node, List nodeTo node.setData(NODE_TEXT_DATA, new NodeText(elements.stream().map(p -> p.b).collect(toList()))); } - // + // // Iterators - // + // private static Iterator tokensPreceeding(final Node node) { if (!node.getParentNode().isPresent()) { return new TextElementIteratorsFactory.EmptyIterator<>(); @@ -495,9 +493,9 @@ private static Iterator tokensPreceeding(final Node node) { return new TextElementIteratorsFactory.CascadingIterator<>(TextElementIteratorsFactory.partialReverseIterator(parentNodeText, index - 1), () -> tokensPreceeding(node.getParentNode().get())); } - // + // // Printing methods - // + // /** * Print a Node into a String, preserving the lexical information. */ @@ -506,12 +504,12 @@ public static String print(Node node) { final NodeText nodeText = getOrCreateNodeText(node); nodeText.getElements().forEach(element -> element.accept(visitor)); return visitor.toString(); - + } - // + // // Methods to handle transformations - // + // private static void prettyPrintingTextNode(Node node, NodeText nodeText) { if (node instanceof PrimitiveType) { PrimitiveType primitiveType = (PrimitiveType) node; @@ -577,7 +575,7 @@ private static NodeText interpret(Node node, CsmElement csm, NodeText nodeText) boolean pendingIndentation = false; // Add a comment and line separator if necessary node.getComment().ifPresent(comment -> { - // new comment has no range so in this case we want to force the comment before the node + // new comment has no range so in this case we want to force the comment before the node if (!comment.hasRange()) { LineSeparator lineSeparator = node.getLineEndingStyleOrDefault(LineSeparator.SYSTEM); calculatedSyntaxModel.elements.add(0,new CsmToken(eolTokenKind(lineSeparator), lineSeparator.asRawString())); @@ -665,9 +663,9 @@ static List findIndentation(Node node) { return followingNewlines; } - // + // // Helper methods - // + // private static boolean isReturningOptionalNodeList(Method m) { if (!m.getReturnType().getCanonicalName().equals(JAVA_UTIL_OPTIONAL)) { return false; From dd96c06b3623a03b71cdaa860cef3ae9ea55e528 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Thu, 10 Aug 2023 14:43:31 +0200 Subject: [PATCH 051/136] Fix: issue 4113 Orphan comment added when using lexical preservation is not printed --- .../LexicalPreservingPrinterTest.java | 142 ++++++++++++++---- .../java/com/github/javaparser/ast/Node.java | 1 + 2 files changed, 112 insertions(+), 31 deletions(-) diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinterTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinterTest.java index d120eeb91c..48366704b3 100644 --- a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinterTest.java +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinterTest.java @@ -21,11 +21,24 @@ package com.github.javaparser.printer.lexicalpreservation; +import static com.github.javaparser.StaticJavaParser.parseClassOrInterfaceType; +import static com.github.javaparser.ast.Modifier.Keyword.PUBLIC; +import static com.github.javaparser.printer.lexicalpreservation.LexicalPreservingPrinter.NODE_TEXT_DATA; +import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol; +import static com.github.javaparser.utils.Utils.SYSTEM_EOL; +import static org.junit.jupiter.api.Assertions.*; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import org.junit.jupiter.api.Test; + import com.github.javaparser.GeneratedJavaParserConstants; import com.github.javaparser.JavaParser; import com.github.javaparser.ParserConfiguration; import com.github.javaparser.StaticJavaParser; -import com.github.javaparser.ParserConfiguration.LanguageLevel; import com.github.javaparser.ast.*; import com.github.javaparser.ast.body.*; import com.github.javaparser.ast.comments.LineComment; @@ -37,19 +50,6 @@ import com.github.javaparser.ast.visitor.ModifierVisitor; import com.github.javaparser.ast.visitor.Visitable; import com.github.javaparser.utils.TestUtils; -import org.junit.jupiter.api.Test; - -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static com.github.javaparser.StaticJavaParser.parseClassOrInterfaceType; -import static com.github.javaparser.ast.Modifier.Keyword.PUBLIC; -import static com.github.javaparser.printer.lexicalpreservation.LexicalPreservingPrinter.NODE_TEXT_DATA; -import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol; -import static com.github.javaparser.utils.Utils.SYSTEM_EOL; -import static org.junit.jupiter.api.Assertions.*; class LexicalPreservingPrinterTest extends AbstractLexicalPreservingTest { private NodeText getTextForNode(Node node) { @@ -1401,10 +1401,10 @@ public void testReplaceTextBlockLiteral() { final String actual = LexicalPreservingPrinter.print(b); assertEquals(expected, actual); } - + @Test void testTextBlockSupport() { - String code = + String code = "String html = \"\"\"\n" + " \n" + " \n" + @@ -1556,7 +1556,7 @@ void testArrayPreservation_WithMultipleBracketWithoutSpace() { "}"; assertTransformedToString(expectedCode, cu); } - + @Test void testClassOrInterfacePreservationWithFullyQualifiedName_SingleType() { // Given @@ -1577,7 +1577,7 @@ void testClassOrInterfacePreservationWithFullyQualifiedName_SingleType() { assertTransformedToString(expectedCode, cu); } - + @Test void testClassOrInterfacePreservationWithFullyQualifiedName_ArrayType() { // Given @@ -1598,7 +1598,7 @@ void testClassOrInterfacePreservationWithFullyQualifiedName_ArrayType() { assertTransformedToString(expectedCode, cu); } - + @Test void testClassOrInterfacePreservationWithFullyQualifiedName_MultipleVariablesDeclarationWithSameType() { // Given @@ -1619,7 +1619,7 @@ void testClassOrInterfacePreservationWithFullyQualifiedName_MultipleVariablesDec assertTransformedToString(expectedCode, cu); } - + @Test void testClassOrInterfacePreservationWithFullyQualifiedName_MultipleVariablesDeclarationwithDifferentType() { // Given @@ -1640,8 +1640,8 @@ void testClassOrInterfacePreservationWithFullyQualifiedName_MultipleVariablesDec assertTransformedToString(expectedCode, cu); } - - // issue 3588 Modifier is removed when removing an annotation. + + // issue 3588 Modifier is removed when removing an annotation. @Test void testRemovingInlinedAnnotation() { // Given @@ -1662,8 +1662,8 @@ void testRemovingInlinedAnnotation() { assertTransformedToString(expectedCode, cu); } - - // issue 3588 Modifier is removed when removing an annotation. + + // issue 3588 Modifier is removed when removing an annotation. @Test void testRemovingInlinedAnnotation_alternate_case() { // Given @@ -1684,7 +1684,7 @@ void testRemovingInlinedAnnotation_alternate_case() { assertTransformedToString(expectedCode, cu); } - + // issue 3216 LexicalPreservingPrinter add Wrong indentation when removing comments @Test void removedIndentationLineCommentsPrinted() { @@ -1694,14 +1694,14 @@ void removedIndentationLineCommentsPrinted() { " }\n" + "}"); String expected = - "public class Foo {\n" + + "public class Foo {\n" + " void mymethod() {\n" + " }\n" + "}"; cu.getAllContainedComments().get(0).remove(); assertEqualsStringIgnoringEol(expected, LexicalPreservingPrinter.print(cu)); } - + // issue 3216 LexicalPreservingPrinter add Wrong indentation when removing comments @Test void removedIndentationBlockCommentsPrinted() { @@ -1718,10 +1718,10 @@ void removedIndentationBlockCommentsPrinted() { " }\n" + "}"; cu.getAllContainedComments().get(0).remove(); - + assertEqualsStringIgnoringEol(expected, LexicalPreservingPrinter.print(cu)); } - + // issue 3216 LexicalPreservingPrinter add Wrong indentation when removing comments @Test void removedIndentationJavaDocCommentsPrinted() { @@ -1741,7 +1741,87 @@ void removedIndentationJavaDocCommentsPrinted() { assertEqualsStringIgnoringEol(expected, LexicalPreservingPrinter.print(cu)); } - + + @Test + void addingOrphanCommentToType() { + String actual = + "public class Foo {\n" + + "}" ; + + String expected = + "//added comment\n" + + "public class Foo {\n" + + "}"; + + considerCode(actual); + cu.getTypes().get(0).addOrphanComment(new LineComment("added comment")); + assertEqualsStringIgnoringEol(expected, LexicalPreservingPrinter.print(cu)); + } + + @Test + void addingOrphanCommentToBlock() { + String actual = + "public class Foo {\n" + + "}" ; + + String expected = + "//added comment\n" + + "public class Foo {\n" + + "}"; + + considerCode(actual); + cu.getTypes().get(0).getChildNodes().get(0).addOrphanComment(new LineComment("added comment")); + assertEqualsStringIgnoringEol(expected, LexicalPreservingPrinter.print(cu)); + } + + @Test + void addingOrphanCommentToBlockInMethodDeclaration() { + String actual = + "public class Foo {\n" + + " boolean m() {\n" + + " return true;\n" + + " }\n" + + "}" ; + + // that's probably not what we want, + // but this is what is implemented in LexicalPreservingPrinter.Observer.concretePropertyChange(..) + String expected = + "public class Foo {\n" + + " boolean m() //added comment\n" + + "{\n" + + " return true;\n" + + " }\n" + + "}"; + + considerCode(actual); + cu.findAll(BlockStmt.class).get(0).addOrphanComment(new LineComment("added comment")); + assertEqualsStringIgnoringEol(expected, LexicalPreservingPrinter.print(cu)); + } + + @Test + void addingOrphanCommentToBlockInMethodDeclaration2() { + String actual = + "public class Foo {\n" + + " boolean m() \n" + + " {\n" + + " return true;\n" + + " }\n" + + "}" ; + + String expected = + "public class Foo {\n" + + " boolean m() \n" + + " //added comment\n" + + " {\n" + + " return true;\n" + + " }\n" + + "}"; + + considerCode(actual); + cu.findAll(BlockStmt.class).get(0).addOrphanComment(new LineComment("added comment")); + assertEqualsStringIgnoringEol(expected, LexicalPreservingPrinter.print(cu)); + } + // issue 3800 determine whether active @Test void checkLPPIsAvailableOnNode() { @@ -1749,7 +1829,7 @@ void checkLPPIsAvailableOnNode() { CompilationUnit cu = StaticJavaParser.parse(code); MethodDeclaration md = cu.findFirst(MethodDeclaration.class).get(); LexicalPreservingPrinter.setup(md); - + assertTrue(LexicalPreservingPrinter.isAvailableOn(md)); assertFalse(LexicalPreservingPrinter.isAvailableOn(cu)); } diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/Node.java b/javaparser-core/src/main/java/com/github/javaparser/ast/Node.java index 9f4dfcae0f..b4fdaa020f 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/Node.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/Node.java @@ -366,6 +366,7 @@ public List getChildNodes() { } public void addOrphanComment(Comment comment) { + notifyPropertyChange(ObservableProperty.COMMENT, null, comment); orphanComments.add(comment); comment.setParentNode(this); } From fe5046cfa51f75ee56f15e06374db330a8693b5e Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Thu, 10 Aug 2023 13:07:22 +0000 Subject: [PATCH 052/136] chore(deps): update dependency maven to v3.9.4 --- .mvn/wrapper/maven-wrapper.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties index 3c6fda8c6e..ac184013fc 100644 --- a/.mvn/wrapper/maven-wrapper.properties +++ b/.mvn/wrapper/maven-wrapper.properties @@ -14,5 +14,5 @@ # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.2/apache-maven-3.9.2-bin.zip +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.4/apache-maven-3.9.4-bin.zip wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar From 0c38be2e28851e783c8ad53ea8e2e366061d8025 Mon Sep 17 00:00:00 2001 From: volodya-lombrozo Date: Fri, 11 Aug 2023 19:21:42 +0300 Subject: [PATCH 053/136] feat(#4075): Add clear guidance for validator messages --- .../Java1_0Validator.java | 62 ++++++++++++------- 1 file changed, 39 insertions(+), 23 deletions(-) diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java1_0Validator.java b/javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java1_0Validator.java index a4da2f79fe..8ae95ee6e4 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java1_0Validator.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java1_0Validator.java @@ -20,6 +20,7 @@ */ package com.github.javaparser.ast.validator.language_level_validations; +import com.github.javaparser.ParserConfiguration; import com.github.javaparser.ast.ImportDeclaration; import com.github.javaparser.ast.Modifier; import com.github.javaparser.ast.Node; @@ -43,73 +44,73 @@ public class Java1_0Validator extends Validators { final Validator modifiersWithoutStrictfpAndDefaultAndStaticInterfaceMethodsAndPrivateInterfaceMethods = new ModifierValidator(false, false, false); - final Validator noAssertKeyword = new SimpleValidator<>(AssertStmt.class, n -> true, (n, reporter) -> reporter.report(n, "'assert' keyword is not supported.")); + final Validator noAssertKeyword = new SimpleValidator<>(AssertStmt.class, n -> true, (n, reporter) -> reporter.report(n, Java1_0Validator.message("'assert' keyword is not supported.", ParserConfiguration.LanguageLevel.JAVA_1_4))); - final Validator noInnerClasses = new SimpleValidator<>(ClassOrInterfaceDeclaration.class, n -> !n.isTopLevelType(), (n, reporter) -> reporter.report(n, "inner classes or interfaces are not supported.")); + final Validator noInnerClasses = new SimpleValidator<>(ClassOrInterfaceDeclaration.class, n -> !n.isTopLevelType(), (n, reporter) -> reporter.report(n, Java1_0Validator.message("inner classes or interfaces are not supported.", ParserConfiguration.LanguageLevel.JAVA_1_1))); - final Validator noReflection = new SimpleValidator<>(ClassExpr.class, n -> true, (n, reporter) -> reporter.report(n, "Reflection is not supported.")); + final Validator noReflection = new SimpleValidator<>(ClassExpr.class, n -> true, (n, reporter) -> reporter.report(n, Java1_0Validator.message("Reflection is not supported.", ParserConfiguration.LanguageLevel.JAVA_1_1))); final Validator noGenerics = new TreeVisitorValidator((node, reporter) -> { if (node instanceof NodeWithTypeArguments) { if (((NodeWithTypeArguments) node).getTypeArguments().isPresent()) { - reporter.report(node, "Generics are not supported."); + reporter.report(node, Java1_0Validator.message("Generics are not supported.", ParserConfiguration.LanguageLevel.JAVA_5)); } } if (node instanceof NodeWithTypeParameters) { if (((NodeWithTypeParameters) node).getTypeParameters().isNonEmpty()) { - reporter.report(node, "Generics are not supported."); + reporter.report(node, Java1_0Validator.message("Generics are not supported.", ParserConfiguration.LanguageLevel.JAVA_5)); } } }); final SingleNodeTypeValidator tryWithoutResources = new SingleNodeTypeValidator<>(TryStmt.class, (n, reporter) -> { if (n.getCatchClauses().isEmpty() && !n.getFinallyBlock().isPresent()) { - reporter.report(n, "Try has no finally and no catch."); + reporter.report(n, Java1_0Validator.message("Try has no finally and no catch.", ParserConfiguration.LanguageLevel.JAVA_7)); } if (n.getResources().isNonEmpty()) { - reporter.report(n, "Catch with resource is not supported."); + reporter.report(n, Java1_0Validator.message("Catch with resource is not supported.", ParserConfiguration.LanguageLevel.JAVA_7)); } }); final Validator noAnnotations = new TreeVisitorValidator((node, reporter) -> { if (node instanceof AnnotationExpr || node instanceof AnnotationDeclaration) { - reporter.report(node, "Annotations are not supported."); + reporter.report(node, Java1_0Validator.message("Annotations are not supported.", ParserConfiguration.LanguageLevel.JAVA_5)); } }); - final Validator noEnums = new SimpleValidator<>(EnumDeclaration.class, n -> true, (n, reporter) -> reporter.report(n, "Enumerations are not supported.")); + final Validator noEnums = new SimpleValidator<>(EnumDeclaration.class, n -> true, (n, reporter) -> reporter.report(n, Java1_0Validator.message("Enumerations are not supported.", ParserConfiguration.LanguageLevel.JAVA_5))); - final Validator noVarargs = new SimpleValidator<>(Parameter.class, Parameter::isVarArgs, (n, reporter) -> reporter.report(n, "Varargs are not supported.")); + final Validator noVarargs = new SimpleValidator<>(Parameter.class, Parameter::isVarArgs, (n, reporter) -> reporter.report(n, Java1_0Validator.message("Varargs are not supported.", ParserConfiguration.LanguageLevel.JAVA_5))); - final Validator noForEach = new SimpleValidator<>(ForEachStmt.class, n -> true, (n, reporter) -> reporter.report(n, "For-each loops are not supported.")); + final Validator noForEach = new SimpleValidator<>(ForEachStmt.class, n -> true, (n, reporter) -> reporter.report(n, Java1_0Validator.message("For-each loops are not supported.", ParserConfiguration.LanguageLevel.JAVA_5))); - final Validator noStaticImports = new SimpleValidator<>(ImportDeclaration.class, ImportDeclaration::isStatic, (n, reporter) -> reporter.report(n, "Static imports are not supported.")); + final Validator noStaticImports = new SimpleValidator<>(ImportDeclaration.class, ImportDeclaration::isStatic, (n, reporter) -> reporter.report(n, Java1_0Validator.message("Static imports are not supported.", ParserConfiguration.LanguageLevel.JAVA_5))); - final Validator onlyOneLabelInSwitchCase = new SimpleValidator<>(SwitchEntry.class, n -> n.getLabels().size() > 1, (n, reporter) -> reporter.report(n.getLabels().getParentNode().get(), "Only one label allowed in a switch-case.")); + final Validator onlyOneLabelInSwitchCase = new SimpleValidator<>(SwitchEntry.class, n -> n.getLabels().size() > 1, (n, reporter) -> reporter.report(n.getLabels().getParentNode().get(), Java1_0Validator.message("Only one label allowed in a switch-case.", ParserConfiguration.LanguageLevel.JAVA_7))); - final Validator noYield = new SimpleValidator<>(YieldStmt.class, n -> true, (n, reporter) -> reporter.report(n, "Only labels allowed in break statements.")); + final Validator noYield = new SimpleValidator<>(YieldStmt.class, n -> true, (n, reporter) -> reporter.report(n, Java1_0Validator.message("Only labels allowed in break statements.", ParserConfiguration.LanguageLevel.JAVA_13))); final Validator noBinaryIntegerLiterals = new NoBinaryIntegerLiteralsValidator(); final Validator noUnderscoresInIntegerLiterals = new NoUnderscoresInIntegerLiteralsValidator(); - final Validator noMultiCatch = new SimpleValidator<>(UnionType.class, n -> true, (n, reporter) -> reporter.report(n, "Multi-catch is not supported.")); + final Validator noMultiCatch = new SimpleValidator<>(UnionType.class, n -> true, (n, reporter) -> reporter.report(n, Java1_0Validator.message("Multi-catch is not supported.", ParserConfiguration.LanguageLevel.JAVA_7))); - final Validator noLambdas = new SimpleValidator<>(LambdaExpr.class, n -> true, (n, reporter) -> reporter.report(n, "Lambdas are not supported.")); + final Validator noLambdas = new SimpleValidator<>(LambdaExpr.class, n -> true, (n, reporter) -> reporter.report(n, Java1_0Validator.message("Lambdas are not supported.", ParserConfiguration.LanguageLevel.JAVA_8))); - final Validator noModules = new SimpleValidator<>(ModuleDeclaration.class, n -> true, (n, reporter) -> reporter.report(n, "Modules are not supported.")); + final Validator noModules = new SimpleValidator<>(ModuleDeclaration.class, n -> true, (n, reporter) -> reporter.report(n, Java1_0Validator.message("Modules are not supported.", ParserConfiguration.LanguageLevel.JAVA_9))); - final Validator noSwitchExpressions = new SimpleValidator<>(SwitchExpr.class, n -> true, (n, reporter) -> reporter.report(n, "Switch expressions are not supported.")); + final Validator noSwitchExpressions = new SimpleValidator<>(SwitchExpr.class, n -> true, (n, reporter) -> reporter.report(n, Java1_0Validator.message("Switch expressions are not supported.", ParserConfiguration.LanguageLevel.JAVA_12))); - final Validator noPatternMatchingInstanceOf = new SimpleValidator<>(InstanceOfExpr.class, n -> n.getPattern().isPresent(), (n, reporter) -> reporter.report(n, "Use of patterns with instanceof is not supported.")); + final Validator noPatternMatchingInstanceOf = new SimpleValidator<>(InstanceOfExpr.class, n -> n.getPattern().isPresent(), (n, reporter) -> reporter.report(n, Java1_0Validator.message("Use of patterns with instanceof is not supported.", ParserConfiguration.LanguageLevel.JAVA_14))); - final Validator noTextBlockLiteral = new SimpleValidator<>(TextBlockLiteralExpr.class, n -> true, (n, reporter) -> reporter.report(n, "Text Block Literals are not supported.")); + final Validator noTextBlockLiteral = new SimpleValidator<>(TextBlockLiteralExpr.class, n -> true, (n, reporter) -> reporter.report(n, Java1_0Validator.message("Text Block Literals are not supported.", ParserConfiguration.LanguageLevel.JAVA_15))); - final Validator noRecordDeclaration = new SimpleValidator<>(RecordDeclaration.class, n -> true, (n, reporter) -> reporter.report(n, "Record Declarations are not supported.")); + final Validator noRecordDeclaration = new SimpleValidator<>(RecordDeclaration.class, n -> true, (n, reporter) -> reporter.report(n, Java1_0Validator.message("Record Declarations are not supported.", ParserConfiguration.LanguageLevel.JAVA_14))); - final Validator noSealedClasses = new SimpleValidator<>(ClassOrInterfaceDeclaration.class, n -> n.hasModifier(Modifier.Keyword.SEALED) || n.hasModifier(Modifier.Keyword.NON_SEALED), (n, reporter) -> reporter.report(n, "Sealed classes are not supported.")); + final Validator noSealedClasses = new SimpleValidator<>(ClassOrInterfaceDeclaration.class, n -> n.hasModifier(Modifier.Keyword.SEALED) || n.hasModifier(Modifier.Keyword.NON_SEALED), (n, reporter) -> reporter.report(n, Java1_0Validator.message("Sealed classes are not supported.", ParserConfiguration.LanguageLevel.JAVA_15))); - final Validator noPermitsListInClasses = new SimpleValidator<>(ClassOrInterfaceDeclaration.class, n -> n.getPermittedTypes().isNonEmpty(), (n, reporter) -> reporter.report(n, "Permitted sub-classes are not supported.")); + final Validator noPermitsListInClasses = new SimpleValidator<>(ClassOrInterfaceDeclaration.class, n -> n.getPermittedTypes().isNonEmpty(), (n, reporter) -> reporter.report(n, Java1_0Validator.message("Permitted sub-classes are not supported.", ParserConfiguration.LanguageLevel.JAVA_17))); public Java1_0Validator() { super(new CommonValidators()); @@ -138,4 +139,19 @@ public Java1_0Validator() { add(noSealedClasses); add(noPermitsListInClasses); } + + /** + * Compose a validator message with suggestion to enable a feature. + * @param cause Original message - cause of the error. + * @param level Language level to enable. + * @return Composed message. + */ + private static String message(final String cause, final ParserConfiguration.LanguageLevel level){ + return String.format( + "%s To enable this feature, add this line before parsing the Java file: StaticJavaParser.getParserConfiguration().setLanguageLevel(%s).", + cause, + level.toString() + ); + } + } From c0edc2244158c70800108bb369fff763bce96d65 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Fri, 18 Aug 2023 10:55:52 +0200 Subject: [PATCH 054/136] Fix: issue 3673 isAssignableBy method StackOverflowError --- .../JavassistClassDeclaration.java | 41 +++++++++---------- .../JavassistInterfaceDeclaration.java | 40 ++++++++++++++++-- .../JavassistTypeDeclarationAdapter.java | 32 ++++++++++++--- .../JavassistClassDeclarationTest.java | 6 ++- .../JavassistInterfaceDeclarationTest.java | 4 +- 5 files changed, 88 insertions(+), 35 deletions(-) diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistClassDeclaration.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistClassDeclaration.java index c56fd027c6..946aeaaf8d 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistClassDeclaration.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistClassDeclaration.java @@ -92,7 +92,7 @@ public Set getDeclaredMethods() { @Override public boolean isAssignableBy(ResolvedReferenceTypeDeclaration other) { - return isAssignableBy(new ReferenceTypeImpl(other)); + return javassistTypeDeclarationAdapter.isAssignableBy(other); } @Override @@ -194,30 +194,24 @@ public ResolvedType getUsage(Node node) { } @Override - public boolean isAssignableBy(ResolvedType type) { - if (type.isNull()) { - return true; - } - - if (type instanceof LambdaArgumentTypePlaceholder) { + public boolean canBeAssignedTo(ResolvedReferenceTypeDeclaration other) { + if (other instanceof LambdaArgumentTypePlaceholder) { return isFunctionalInterface(); } - - // TODO look into generics - if (type.describe().equals(this.getQualifiedName())) { + if (other.getQualifiedName().equals(getQualifiedName())) { return true; } - - Optional superClassOpt = getSuperClass(); - if (superClassOpt.isPresent()) { - ResolvedReferenceType superClass = superClassOpt.get(); - if (superClass.isAssignableBy(type)) { - return true; - } - } - - for (ResolvedReferenceType interfaceType : getInterfaces()) { - if (interfaceType.isAssignableBy(type)) { + Optional oSuperClass = javassistTypeDeclarationAdapter.getSuperClass(); + if (oSuperClass.isPresent()) { + ResolvedReferenceType superClass = oSuperClass.get(); + Optional oDecl = superClass.getTypeDeclaration(); + if (oDecl.isPresent() && oDecl.get().canBeAssignedTo(other)) { + return true; + } + } + + for (ResolvedReferenceType interfaze : javassistTypeDeclarationAdapter.getInterfaces()) { + if (interfaze.getTypeDeclaration().isPresent() && interfaze.getTypeDeclaration().get().canBeAssignedTo(other)) { return true; } } @@ -225,6 +219,11 @@ public boolean isAssignableBy(ResolvedType type) { return false; } + @Override + public boolean isAssignableBy(ResolvedType type) { + return javassistTypeDeclarationAdapter.isAssignableBy(type); + } + @Override public boolean isTypeParameter() { return false; diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistInterfaceDeclaration.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistInterfaceDeclaration.java index 76ba87101d..d8459286ca 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistInterfaceDeclaration.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistInterfaceDeclaration.java @@ -31,6 +31,7 @@ import com.github.javaparser.resolution.UnsolvedSymbolException; import com.github.javaparser.resolution.declarations.*; import com.github.javaparser.resolution.logic.MethodResolutionCapability; +import com.github.javaparser.resolution.model.LambdaArgumentTypePlaceholder; import com.github.javaparser.resolution.model.SymbolReference; import com.github.javaparser.resolution.types.ResolvedReferenceType; import com.github.javaparser.resolution.types.ResolvedType; @@ -108,13 +109,13 @@ public SymbolReference solveMethod(String name, List< } @Override - public boolean isAssignableBy(ResolvedType type) { - return javassistTypeDeclarationAdapter.isAssignableBy(type); + public List getAllFields() { + return javassistTypeDeclarationAdapter.getDeclaredFields(); } @Override - public List getAllFields() { - return javassistTypeDeclarationAdapter.getDeclaredFields(); + public boolean isAssignableBy(ResolvedType type) { + return javassistTypeDeclarationAdapter.isAssignableBy(type); } @Override @@ -122,6 +123,37 @@ public boolean isAssignableBy(ResolvedReferenceTypeDeclaration other) { return javassistTypeDeclarationAdapter.isAssignableBy(other); } + @Override + public boolean canBeAssignedTo(ResolvedReferenceTypeDeclaration other) { + if (other.isJavaLangObject()) { + // Everything can be assigned to {@code java.lang.Object} + return true; + } + + if (other instanceof LambdaArgumentTypePlaceholder) { + return isFunctionalInterface(); + } + if (other.getQualifiedName().equals(getQualifiedName())) { + return true; + } + Optional oSuperClass = javassistTypeDeclarationAdapter.getSuperClass(); + if (oSuperClass.isPresent()) { + ResolvedReferenceType superClass = oSuperClass.get(); + Optional oDecl = superClass.getTypeDeclaration(); + if (oDecl.isPresent() && oDecl.get().canBeAssignedTo(other)) { + return true; + } + } + for (ResolvedReferenceType interfaze : javassistTypeDeclarationAdapter.getInterfaces()) { + if (interfaze.getTypeDeclaration().isPresent() + && interfaze.getTypeDeclaration().get().canBeAssignedTo(other)) { + return true; + } + } + + return false; + } + @Override public List getAncestors(boolean acceptIncompleteList) { return javassistTypeDeclarationAdapter.getAncestors(acceptIncompleteList); diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistTypeDeclarationAdapter.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistTypeDeclarationAdapter.java index d6e2d0c699..4972032c8b 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistTypeDeclarationAdapter.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistTypeDeclarationAdapter.java @@ -30,7 +30,9 @@ import com.github.javaparser.resolution.TypeSolver; import com.github.javaparser.resolution.UnsolvedSymbolException; import com.github.javaparser.resolution.declarations.*; +import com.github.javaparser.resolution.logic.FunctionalInterfaceLogic; import com.github.javaparser.resolution.model.LambdaArgumentTypePlaceholder; +import com.github.javaparser.resolution.model.typesystem.NullType; import com.github.javaparser.resolution.model.typesystem.ReferenceTypeImpl; import com.github.javaparser.resolution.types.ResolvedReferenceType; import com.github.javaparser.resolution.types.ResolvedType; @@ -235,23 +237,41 @@ public Optional containerType() { } } - public boolean isAssignableBy(ResolvedType other) { + public boolean isAssignableBy(ResolvedType type) { - if (other.isNull()) { + if (type instanceof NullType) { return true; } - - if (other instanceof LambdaArgumentTypePlaceholder) { - return typeDeclaration.isFunctionalInterface(); + if (type instanceof LambdaArgumentTypePlaceholder) { + return isFunctionalInterface(); + } + if (type.isArray()) { + return false; + } + if (type.isPrimitive()) { + return false; + } + if (type.describe().equals(typeDeclaration.getQualifiedName())) { + return true; + } + if (type instanceof ReferenceTypeImpl) { + ReferenceTypeImpl otherTypeDeclaration = (ReferenceTypeImpl) type; + if(otherTypeDeclaration.getTypeDeclaration().isPresent()) { + return otherTypeDeclaration.getTypeDeclaration().get().canBeAssignedTo(typeDeclaration); + } } - return other.isAssignableBy(new ReferenceTypeImpl(typeDeclaration)); + return false; } public boolean isAssignableBy(ResolvedReferenceTypeDeclaration other) { return isAssignableBy(new ReferenceTypeImpl(other)); } + private final boolean isFunctionalInterface() { + return FunctionalInterfaceLogic.getFunctionalMethod(typeDeclaration).isPresent(); + } + /** * Get the nested classes. *
diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistClassDeclarationTest.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistClassDeclarationTest.java index cb0eee4079..1b167ca664 100644 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistClassDeclarationTest.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistClassDeclarationTest.java @@ -539,7 +539,8 @@ void whenEqualTypeIsProvided() { void whenSuperClassIsProvided() { ResolvedReferenceTypeDeclaration node = newTypeSolver.solveType("com.github.javaparser.ast.Node"); JavassistClassDeclaration cu = (JavassistClassDeclaration) newTypeSolver.solveType("com.github.javaparser.ast.CompilationUnit"); - assertTrue(cu.isAssignableBy(node)); + assertFalse(cu.isAssignableBy(node)); + assertTrue(node.isAssignableBy(cu)); } @Test @@ -548,7 +549,8 @@ void whenInterfaceIsProvided() { "com.github.javaparser.ast.nodeTypes.NodeWithImplements"); JavassistClassDeclaration classDeclaration = (JavassistClassDeclaration) newTypeSolver.solveType( "com.github.javaparser.ast.body.ClassOrInterfaceDeclaration"); - assertTrue(classDeclaration.isAssignableBy(nodeWithImplements)); + assertFalse(classDeclaration.isAssignableBy(nodeWithImplements)); + assertTrue(nodeWithImplements.isAssignableBy(classDeclaration)); } } diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistInterfaceDeclarationTest.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistInterfaceDeclarationTest.java index 6cffe3c671..d19abdbcde 100644 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistInterfaceDeclarationTest.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistInterfaceDeclarationTest.java @@ -225,8 +225,8 @@ void whenInterfaceIsProvided() { memoryTypeSolver.addDeclaration("B", declarationB); // Knowing that B extends A we expect: - assertFalse(declarationA.isAssignableBy(declarationB), "This should not be allowed: B variable = new A()"); - assertTrue(declarationB.isAssignableBy(declarationA), "This should be allowed: A variable = new B()"); + assertTrue(declarationA.isAssignableBy(declarationB), "This should not be allowed: A variable = new B()"); + assertFalse(declarationB.isAssignableBy(declarationA), "This should be allowed: B variable = new A()"); } } From 01c34a94a6b3e92510922235dba8d0b167cfe2e4 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Fri, 18 Aug 2023 12:26:23 +0200 Subject: [PATCH 055/136] feat: issue 4115 ResolvedUnionType should give access to a list of resolved types --- .../resolution/types/ResolvedIntersectionType.java | 11 +++++++++-- .../resolution/types/ResolvedUnionType.java | 11 +++++++++-- .../resolution/JavaParserFacadeResolutionTest.java | 1 + 3 files changed, 19 insertions(+), 4 deletions(-) diff --git a/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedIntersectionType.java b/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedIntersectionType.java index 5fb4e1aa62..f590920622 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedIntersectionType.java +++ b/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedIntersectionType.java @@ -20,11 +20,11 @@ */ package com.github.javaparser.resolution.types; -import com.github.javaparser.resolution.declarations.ResolvedTypeParameterDeclaration; - import java.util.*; import java.util.stream.Collectors; +import com.github.javaparser.resolution.declarations.ResolvedTypeParameterDeclaration; + /** * An intersection type is defined in java as list of types separates by ampersands. * @@ -74,4 +74,11 @@ public ResolvedType replaceTypeVariables(ResolvedTypeParameterDeclaration tp, Re } return new ResolvedIntersectionType(elementsReplaced); } + + /* + * Returns the list of the resolved types + */ + public List getElements() { + return elements; + } } diff --git a/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedUnionType.java b/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedUnionType.java index b238be965a..44feaddfe8 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedUnionType.java +++ b/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedUnionType.java @@ -20,11 +20,11 @@ */ package com.github.javaparser.resolution.types; -import com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration; - import java.util.*; import java.util.stream.Collectors; +import com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration; + /** * A union type is defined in java as list of types separates by pipes. * @@ -87,4 +87,11 @@ public boolean isUnionType() { public ResolvedUnionType asUnionType() { return this; } + + /* + * Returns the list of the resolved types + */ + public List getElements() { + return elements; + } } diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/JavaParserFacadeResolutionTest.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/JavaParserFacadeResolutionTest.java index 8cac015477..8fb93be7f9 100644 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/JavaParserFacadeResolutionTest.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/JavaParserFacadeResolutionTest.java @@ -169,6 +169,7 @@ void solveMultiCatchType() { Type jpType = catchClause.getParameter().getType(); ResolvedType jssType = jpType.resolve(); assertTrue(jssType instanceof ResolvedUnionType); + assertTrue(jssType.asUnionType().getElements().size()==2); } @Test From 0e003e5e2eefed540d4dd51320ce9687f064f07a Mon Sep 17 00:00:00 2001 From: volodya-lombrozo Date: Fri, 18 Aug 2023 15:20:54 +0300 Subject: [PATCH 056/136] feat(#4075): Add UpgradeJavaMessage class --- .../ast/validator/ProblemReporter.java | 15 ++++- .../Java1_0Validator.java | 61 +++++++---------- .../Java1_1Validator.java | 3 +- .../Java5Validator.java | 3 +- .../UpgradeJavaMessage.java | 65 +++++++++++++++++++ 5 files changed, 104 insertions(+), 43 deletions(-) create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/UpgradeJavaMessage.java diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/validator/ProblemReporter.java b/javaparser-core/src/main/java/com/github/javaparser/ast/validator/ProblemReporter.java index 52dd5d0d07..6d0da4e3bc 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/validator/ProblemReporter.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/validator/ProblemReporter.java @@ -23,9 +23,8 @@ import com.github.javaparser.Problem; import com.github.javaparser.TokenRange; import com.github.javaparser.ast.nodeTypes.NodeWithTokenRange; - +import com.github.javaparser.ast.validator.language_level_validations.UpgradeJavaMessage; import java.util.function.Consumer; - import static com.github.javaparser.utils.CodeGenerationUtils.f; /** @@ -39,6 +38,16 @@ public ProblemReporter(Consumer problemConsumer) { this.problemConsumer = problemConsumer; } + /** + * Report a problem. + * + * @param message description of the problem + * @param node the node in which the problem occurred, used to find the Range of the problem. + */ + public void report(final NodeWithTokenRange node, final UpgradeJavaMessage message, final Object... args) { + this.report(node.getTokenRange().orElse(null), message.toString(), args); + } + /** * Report a problem. * @@ -46,7 +55,7 @@ public ProblemReporter(Consumer problemConsumer) { * @param node the node in which the problem occurred, used to find the Range of the problem. */ public void report(NodeWithTokenRange node, String message, Object... args) { - report(node.getTokenRange().orElse(null), message, args); + this.report(node.getTokenRange().orElse(null), message, args); } public void report(TokenRange range, String message, Object... args) { diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java1_0Validator.java b/javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java1_0Validator.java index 8ae95ee6e4..1291ac7cc4 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java1_0Validator.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java1_0Validator.java @@ -44,73 +44,73 @@ public class Java1_0Validator extends Validators { final Validator modifiersWithoutStrictfpAndDefaultAndStaticInterfaceMethodsAndPrivateInterfaceMethods = new ModifierValidator(false, false, false); - final Validator noAssertKeyword = new SimpleValidator<>(AssertStmt.class, n -> true, (n, reporter) -> reporter.report(n, Java1_0Validator.message("'assert' keyword is not supported.", ParserConfiguration.LanguageLevel.JAVA_1_4))); + final Validator noAssertKeyword = new SimpleValidator<>(AssertStmt.class, n -> true, (n, reporter) -> reporter.report(n, new UpgradeJavaMessage("'assert' keyword is not supported.", ParserConfiguration.LanguageLevel.JAVA_1_4))); - final Validator noInnerClasses = new SimpleValidator<>(ClassOrInterfaceDeclaration.class, n -> !n.isTopLevelType(), (n, reporter) -> reporter.report(n, Java1_0Validator.message("inner classes or interfaces are not supported.", ParserConfiguration.LanguageLevel.JAVA_1_1))); + final Validator noInnerClasses = new SimpleValidator<>(ClassOrInterfaceDeclaration.class, n -> !n.isTopLevelType(), (n, reporter) -> reporter.report(n, new UpgradeJavaMessage("inner classes or interfaces are not supported.", ParserConfiguration.LanguageLevel.JAVA_1_1))); - final Validator noReflection = new SimpleValidator<>(ClassExpr.class, n -> true, (n, reporter) -> reporter.report(n, Java1_0Validator.message("Reflection is not supported.", ParserConfiguration.LanguageLevel.JAVA_1_1))); + final Validator noReflection = new SimpleValidator<>(ClassExpr.class, n -> true, (n, reporter) -> reporter.report(n, new UpgradeJavaMessage("Reflection is not supported.", ParserConfiguration.LanguageLevel.JAVA_1_1))); final Validator noGenerics = new TreeVisitorValidator((node, reporter) -> { if (node instanceof NodeWithTypeArguments) { if (((NodeWithTypeArguments) node).getTypeArguments().isPresent()) { - reporter.report(node, Java1_0Validator.message("Generics are not supported.", ParserConfiguration.LanguageLevel.JAVA_5)); + reporter.report(node, new UpgradeJavaMessage("Generics are not supported.", ParserConfiguration.LanguageLevel.JAVA_5)); } } if (node instanceof NodeWithTypeParameters) { if (((NodeWithTypeParameters) node).getTypeParameters().isNonEmpty()) { - reporter.report(node, Java1_0Validator.message("Generics are not supported.", ParserConfiguration.LanguageLevel.JAVA_5)); + reporter.report(node, new UpgradeJavaMessage("Generics are not supported.", ParserConfiguration.LanguageLevel.JAVA_5)); } } }); final SingleNodeTypeValidator tryWithoutResources = new SingleNodeTypeValidator<>(TryStmt.class, (n, reporter) -> { if (n.getCatchClauses().isEmpty() && !n.getFinallyBlock().isPresent()) { - reporter.report(n, Java1_0Validator.message("Try has no finally and no catch.", ParserConfiguration.LanguageLevel.JAVA_7)); + reporter.report(n, new UpgradeJavaMessage("Try has no finally and no catch.", ParserConfiguration.LanguageLevel.JAVA_7)); } if (n.getResources().isNonEmpty()) { - reporter.report(n, Java1_0Validator.message("Catch with resource is not supported.", ParserConfiguration.LanguageLevel.JAVA_7)); + reporter.report(n, new UpgradeJavaMessage("Catch with resource is not supported.", ParserConfiguration.LanguageLevel.JAVA_7)); } }); final Validator noAnnotations = new TreeVisitorValidator((node, reporter) -> { if (node instanceof AnnotationExpr || node instanceof AnnotationDeclaration) { - reporter.report(node, Java1_0Validator.message("Annotations are not supported.", ParserConfiguration.LanguageLevel.JAVA_5)); + reporter.report(node, new UpgradeJavaMessage("Annotations are not supported.", ParserConfiguration.LanguageLevel.JAVA_5)); } }); - final Validator noEnums = new SimpleValidator<>(EnumDeclaration.class, n -> true, (n, reporter) -> reporter.report(n, Java1_0Validator.message("Enumerations are not supported.", ParserConfiguration.LanguageLevel.JAVA_5))); + final Validator noEnums = new SimpleValidator<>(EnumDeclaration.class, n -> true, (n, reporter) -> reporter.report(n, new UpgradeJavaMessage("Enumerations are not supported.", ParserConfiguration.LanguageLevel.JAVA_5))); - final Validator noVarargs = new SimpleValidator<>(Parameter.class, Parameter::isVarArgs, (n, reporter) -> reporter.report(n, Java1_0Validator.message("Varargs are not supported.", ParserConfiguration.LanguageLevel.JAVA_5))); + final Validator noVarargs = new SimpleValidator<>(Parameter.class, Parameter::isVarArgs, (n, reporter) -> reporter.report(n, new UpgradeJavaMessage("Varargs are not supported.", ParserConfiguration.LanguageLevel.JAVA_5))); - final Validator noForEach = new SimpleValidator<>(ForEachStmt.class, n -> true, (n, reporter) -> reporter.report(n, Java1_0Validator.message("For-each loops are not supported.", ParserConfiguration.LanguageLevel.JAVA_5))); + final Validator noForEach = new SimpleValidator<>(ForEachStmt.class, n -> true, (n, reporter) -> reporter.report(n, new UpgradeJavaMessage("For-each loops are not supported.", ParserConfiguration.LanguageLevel.JAVA_5))); - final Validator noStaticImports = new SimpleValidator<>(ImportDeclaration.class, ImportDeclaration::isStatic, (n, reporter) -> reporter.report(n, Java1_0Validator.message("Static imports are not supported.", ParserConfiguration.LanguageLevel.JAVA_5))); + final Validator noStaticImports = new SimpleValidator<>(ImportDeclaration.class, ImportDeclaration::isStatic, (n, reporter) -> reporter.report(n, new UpgradeJavaMessage("Static imports are not supported.", ParserConfiguration.LanguageLevel.JAVA_5))); - final Validator onlyOneLabelInSwitchCase = new SimpleValidator<>(SwitchEntry.class, n -> n.getLabels().size() > 1, (n, reporter) -> reporter.report(n.getLabels().getParentNode().get(), Java1_0Validator.message("Only one label allowed in a switch-case.", ParserConfiguration.LanguageLevel.JAVA_7))); + final Validator onlyOneLabelInSwitchCase = new SimpleValidator<>(SwitchEntry.class, n -> n.getLabels().size() > 1, (n, reporter) -> reporter.report(n.getLabels().getParentNode().get(), new UpgradeJavaMessage("Only one label allowed in a switch-case.", ParserConfiguration.LanguageLevel.JAVA_7))); - final Validator noYield = new SimpleValidator<>(YieldStmt.class, n -> true, (n, reporter) -> reporter.report(n, Java1_0Validator.message("Only labels allowed in break statements.", ParserConfiguration.LanguageLevel.JAVA_13))); + final Validator noYield = new SimpleValidator<>(YieldStmt.class, n -> true, (n, reporter) -> reporter.report(n, new UpgradeJavaMessage("Only labels allowed in break statements.", ParserConfiguration.LanguageLevel.JAVA_13))); final Validator noBinaryIntegerLiterals = new NoBinaryIntegerLiteralsValidator(); final Validator noUnderscoresInIntegerLiterals = new NoUnderscoresInIntegerLiteralsValidator(); - final Validator noMultiCatch = new SimpleValidator<>(UnionType.class, n -> true, (n, reporter) -> reporter.report(n, Java1_0Validator.message("Multi-catch is not supported.", ParserConfiguration.LanguageLevel.JAVA_7))); + final Validator noMultiCatch = new SimpleValidator<>(UnionType.class, n -> true, (n, reporter) -> reporter.report(n, new UpgradeJavaMessage("Multi-catch is not supported.", ParserConfiguration.LanguageLevel.JAVA_7))); - final Validator noLambdas = new SimpleValidator<>(LambdaExpr.class, n -> true, (n, reporter) -> reporter.report(n, Java1_0Validator.message("Lambdas are not supported.", ParserConfiguration.LanguageLevel.JAVA_8))); + final Validator noLambdas = new SimpleValidator<>(LambdaExpr.class, n -> true, (n, reporter) -> reporter.report(n, new UpgradeJavaMessage("Lambdas are not supported.", ParserConfiguration.LanguageLevel.JAVA_8))); - final Validator noModules = new SimpleValidator<>(ModuleDeclaration.class, n -> true, (n, reporter) -> reporter.report(n, Java1_0Validator.message("Modules are not supported.", ParserConfiguration.LanguageLevel.JAVA_9))); + final Validator noModules = new SimpleValidator<>(ModuleDeclaration.class, n -> true, (n, reporter) -> reporter.report(n, new UpgradeJavaMessage("Modules are not supported.", ParserConfiguration.LanguageLevel.JAVA_9))); - final Validator noSwitchExpressions = new SimpleValidator<>(SwitchExpr.class, n -> true, (n, reporter) -> reporter.report(n, Java1_0Validator.message("Switch expressions are not supported.", ParserConfiguration.LanguageLevel.JAVA_12))); + final Validator noSwitchExpressions = new SimpleValidator<>(SwitchExpr.class, n -> true, (n, reporter) -> reporter.report(n, new UpgradeJavaMessage("Switch expressions are not supported.", ParserConfiguration.LanguageLevel.JAVA_12))); - final Validator noPatternMatchingInstanceOf = new SimpleValidator<>(InstanceOfExpr.class, n -> n.getPattern().isPresent(), (n, reporter) -> reporter.report(n, Java1_0Validator.message("Use of patterns with instanceof is not supported.", ParserConfiguration.LanguageLevel.JAVA_14))); + final Validator noPatternMatchingInstanceOf = new SimpleValidator<>(InstanceOfExpr.class, n -> n.getPattern().isPresent(), (n, reporter) -> reporter.report(n, new UpgradeJavaMessage("Use of patterns with instanceof is not supported.", ParserConfiguration.LanguageLevel.JAVA_14))); - final Validator noTextBlockLiteral = new SimpleValidator<>(TextBlockLiteralExpr.class, n -> true, (n, reporter) -> reporter.report(n, Java1_0Validator.message("Text Block Literals are not supported.", ParserConfiguration.LanguageLevel.JAVA_15))); + final Validator noTextBlockLiteral = new SimpleValidator<>(TextBlockLiteralExpr.class, n -> true, (n, reporter) -> reporter.report(n, new UpgradeJavaMessage("Text Block Literals are not supported.", ParserConfiguration.LanguageLevel.JAVA_15))); - final Validator noRecordDeclaration = new SimpleValidator<>(RecordDeclaration.class, n -> true, (n, reporter) -> reporter.report(n, Java1_0Validator.message("Record Declarations are not supported.", ParserConfiguration.LanguageLevel.JAVA_14))); + final Validator noRecordDeclaration = new SimpleValidator<>(RecordDeclaration.class, n -> true, (n, reporter) -> reporter.report(n, new UpgradeJavaMessage("Record Declarations are not supported.", ParserConfiguration.LanguageLevel.JAVA_14))); - final Validator noSealedClasses = new SimpleValidator<>(ClassOrInterfaceDeclaration.class, n -> n.hasModifier(Modifier.Keyword.SEALED) || n.hasModifier(Modifier.Keyword.NON_SEALED), (n, reporter) -> reporter.report(n, Java1_0Validator.message("Sealed classes are not supported.", ParserConfiguration.LanguageLevel.JAVA_15))); + final Validator noSealedClasses = new SimpleValidator<>(ClassOrInterfaceDeclaration.class, n -> n.hasModifier(Modifier.Keyword.SEALED) || n.hasModifier(Modifier.Keyword.NON_SEALED), (n, reporter) -> reporter.report(n, new UpgradeJavaMessage("Sealed classes are not supported.", ParserConfiguration.LanguageLevel.JAVA_15))); - final Validator noPermitsListInClasses = new SimpleValidator<>(ClassOrInterfaceDeclaration.class, n -> n.getPermittedTypes().isNonEmpty(), (n, reporter) -> reporter.report(n, Java1_0Validator.message("Permitted sub-classes are not supported.", ParserConfiguration.LanguageLevel.JAVA_17))); + final Validator noPermitsListInClasses = new SimpleValidator<>(ClassOrInterfaceDeclaration.class, n -> n.getPermittedTypes().isNonEmpty(), (n, reporter) -> reporter.report(n, new UpgradeJavaMessage("Permitted sub-classes are not supported.", ParserConfiguration.LanguageLevel.JAVA_17))); public Java1_0Validator() { super(new CommonValidators()); @@ -139,19 +139,4 @@ public Java1_0Validator() { add(noSealedClasses); add(noPermitsListInClasses); } - - /** - * Compose a validator message with suggestion to enable a feature. - * @param cause Original message - cause of the error. - * @param level Language level to enable. - * @return Composed message. - */ - private static String message(final String cause, final ParserConfiguration.LanguageLevel level){ - return String.format( - "%s To enable this feature, add this line before parsing the Java file: StaticJavaParser.getParserConfiguration().setLanguageLevel(%s).", - cause, - level.toString() - ); - } - } diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java1_1Validator.java b/javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java1_1Validator.java index 98be6b327f..7ea1b92806 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java1_1Validator.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java1_1Validator.java @@ -20,6 +20,7 @@ */ package com.github.javaparser.ast.validator.language_level_validations; +import com.github.javaparser.ParserConfiguration; import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; import com.github.javaparser.ast.stmt.LocalClassDeclarationStmt; import com.github.javaparser.ast.validator.SingleNodeTypeValidator; @@ -32,7 +33,7 @@ public class Java1_1Validator extends Java1_0Validator { final Validator innerClasses = new SingleNodeTypeValidator<>(ClassOrInterfaceDeclaration.class, (n, reporter) -> n.getParentNode().ifPresent(p -> { if (p instanceof LocalClassDeclarationStmt && n.isInterface()) - reporter.report(n, "There is no such thing as a local interface."); + reporter.report(n, new UpgradeJavaMessage("There is no such thing as a local interface.", ParserConfiguration.LanguageLevel.JAVA_16)); })); public Java1_1Validator() { diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java5Validator.java b/javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java5Validator.java index 13bbf917f2..5373d5206b 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java5Validator.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java5Validator.java @@ -20,6 +20,7 @@ */ package com.github.javaparser.ast.validator.language_level_validations; +import com.github.javaparser.ParserConfiguration; import com.github.javaparser.ast.Node; import com.github.javaparser.ast.NodeList; import com.github.javaparser.ast.expr.VariableDeclarationExpr; @@ -43,7 +44,7 @@ public class Java5Validator extends Java1_4Validator { if (node instanceof NodeWithTypeArguments) { Optional> typeArguments = ((NodeWithTypeArguments) node).getTypeArguments(); if (typeArguments.isPresent() && typeArguments.get().isEmpty()) { - reporter.report(node, "The diamond operator is not supported."); + reporter.report(node, new UpgradeJavaMessage("The diamond operator is not supported.", ParserConfiguration.LanguageLevel.JAVA_7)); } } }); diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/UpgradeJavaMessage.java b/javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/UpgradeJavaMessage.java new file mode 100644 index 0000000000..b0bd363ad6 --- /dev/null +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/UpgradeJavaMessage.java @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2023 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ +package com.github.javaparser.ast.validator.language_level_validations; + +import com.github.javaparser.ParserConfiguration; + +/** + * Suggestion to upgrade the Java language level. + * A message that can be used to tell the user that a feature is + * not available in the configured language level. + * + * @since 3.24.5 + */ +public final class UpgradeJavaMessage { + + /** + * The reason why the language level must be upgraded. + */ + private final String reason; + + /** + * The language level that must be configured. + */ + private final ParserConfiguration.LanguageLevel level; + + /** + * Contructor. + * @param reason The reason why the language level must be upgraded. + * @param level The language level that must be configured. + */ + UpgradeJavaMessage( + final String reason, + final ParserConfiguration.LanguageLevel level + ) { + this.reason = reason; + this.level = level; + } + + @Override + public String toString() { + return String.format( + "%s Pay attention that this feature is supported starting from '%s' language level. If you need that feature the language level must be configured in the configuration before parsing the source files.", + this.reason, + this.level.toString() + ); + } +} From f96288a74cde0d0ba4f616619f690ed957481198 Mon Sep 17 00:00:00 2001 From: Mahesh Hegde <46179734+mahesh-hegde@users.noreply.github.com> Date: Sun, 20 Aug 2023 14:41:42 +0530 Subject: [PATCH 057/136] Fix failing test on JDK 17 --- .../typeinference/LeastUpperBoundTest.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/typeinference/LeastUpperBoundTest.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/typeinference/LeastUpperBoundTest.java index ae68290387..a323664aac 100755 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/typeinference/LeastUpperBoundTest.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/typeinference/LeastUpperBoundTest.java @@ -2,11 +2,11 @@ import static org.junit.jupiter.api.Assertions.*; +import java.io.FileNotFoundException; import java.io.IOError; import java.io.IOException; import java.io.Serializable; -import java.rmi.AlreadyBoundException; -import java.rmi.activation.UnknownGroupException; +import java.net.URISyntaxException; import java.util.*; import java.util.stream.Collectors; @@ -145,11 +145,11 @@ public void lub_approximation_inheritance_and_multiple_bounds() { @Test public void lub_approximation_with_complexe_inheritance() { ResolvedType expected = type(Exception.class.getCanonicalName()); - // java.lang.Object/java.lang.Throwable/java.lang.Exception/java.rmi.AlreadyBoundException - ResolvedType alreadyBoundException = type(AlreadyBoundException.class.getCanonicalName()); - // java.lang.Object//java.lang.Throwable/java.lang.Exception/java.rmi.activation.ActivationException/java.rmi.activation.UnknownGroupException - ResolvedType unknownGroupException = type(UnknownGroupException.class.getCanonicalName()); - ResolvedType lub = leastUpperBound(alreadyBoundException, unknownGroupException); + // java.lang.Object/java.lang.Throwable/java.lang.Exception/java.net.URISyntaxException + ResolvedType uriSyntaxException = type(URISyntaxException.class.getCanonicalName()); + // java.lang.Object//java.lang.Throwable/java.lang.Exception/java.io.IOException/java.io.FileNotFoundException + ResolvedType fileNotFoundException = type(FileNotFoundException.class.getCanonicalName()); + ResolvedType lub = leastUpperBound(uriSyntaxException, fileNotFoundException); assertEquals(expected, lub); } From 9ad247c24318232904c3307f1446fb67e82ed916 Mon Sep 17 00:00:00 2001 From: 70825 Date: Sun, 20 Aug 2023 20:04:47 +0900 Subject: [PATCH 058/136] Replace deprecated command with environment file --- .github/workflows/prepare_release_changelog.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/prepare_release_changelog.yml b/.github/workflows/prepare_release_changelog.yml index 4dcdc0fd46..911a0a0112 100644 --- a/.github/workflows/prepare_release_changelog.yml +++ b/.github/workflows/prepare_release_changelog.yml @@ -39,11 +39,11 @@ jobs: RELEASE_TITLE="SNAPSHOT - $SHA_SHORT" RELEASE_TAG_NAME="v_snapshot_$SHA_SHORT" - echo "::set-output name=sha_long::$SHA_LONG" - echo "::set-output name=sha_short::$SHA_SHORT" - echo "::set-output name=changelog::$CHANGELOG" - echo "::set-output name=release_title::$RELEASE_TITLE" - echo "::set-output name=release_tag_name::$RELEASE_TAG_NAME" + echo "sha_long=$SHA_LONG" >> $GITHUB_OUTPUT + echo "sha_short=$SHA_SHORT" >> $GITHUB_OUTPUT + echo "changelog=$CHANGELOG" >> $GITHUB_OUTPUT + echo "release_title=$RELEASE_TITLE" >> $GITHUB_OUTPUT + echo "release_tag_name=$RELEASE_TAG_NAME" >> $GITHUB_OUTPUT - name: Output variables From cc159998ac7c83234e2665cbc479f85dcc27f5d0 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Mon, 21 Aug 2023 16:34:39 +0200 Subject: [PATCH 059/136] Fix: issue 4051 Switched upperBounds and lowerBounds on ResolvedTypeParameterDeclaration --- .../ResolvedTypeParameterDeclaration.java | 8 +- .../resolution/types/ResolvedWildcard.java | 4 +- .../model/typesystem/ReferenceTypeTest.java | 102 +++++++++++------- 3 files changed, 72 insertions(+), 42 deletions(-) diff --git a/javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedTypeParameterDeclaration.java b/javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedTypeParameterDeclaration.java index 4044488f68..643ef83da5 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedTypeParameterDeclaration.java +++ b/javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedTypeParameterDeclaration.java @@ -192,7 +192,7 @@ default boolean hasBound() { */ default boolean hasLowerBound() { for (Bound b : getBounds()) { - if (b.isExtends()) { + if (b.isSuper()) { return true; } } @@ -204,7 +204,7 @@ default boolean hasLowerBound() { */ default boolean hasUpperBound() { for (Bound b : getBounds()) { - if (b.isSuper()) { + if (b.isExtends()) { return true; } } @@ -218,7 +218,7 @@ default boolean hasUpperBound() { */ default ResolvedType getLowerBound() { for (Bound b : getBounds()) { - if (b.isExtends()) { + if (b.isSuper()) { return b.getType(); } } @@ -232,7 +232,7 @@ default ResolvedType getLowerBound() { */ default ResolvedType getUpperBound() { for (Bound b : getBounds()) { - if (b.isSuper()) { + if (b.isExtends()) { return b.getType(); } } diff --git a/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedWildcard.java b/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedWildcard.java index 3054a899bb..f89faacf65 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedWildcard.java +++ b/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedWildcard.java @@ -170,11 +170,11 @@ public boolean mention(List typeParameters) { } public boolean isUpperBounded() { - return isSuper(); + return isExtends(); } public boolean isLowerBounded() { - return isExtends(); + return isSuper(); } public enum BoundType { diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/model/typesystem/ReferenceTypeTest.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/model/typesystem/ReferenceTypeTest.java index def3dcac88..452a4ddab0 100644 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/model/typesystem/ReferenceTypeTest.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/model/typesystem/ReferenceTypeTest.java @@ -21,6 +21,24 @@ package com.github.javaparser.symbolsolver.model.typesystem; +import static org.hamcrest.CoreMatchers.*; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; +import static org.junit.jupiter.api.Assertions.*; + +import java.io.IOException; +import java.io.Serializable; +import java.net.ProtocolException; +import java.nio.Buffer; +import java.nio.CharBuffer; +import java.nio.file.FileSystemException; +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import com.github.javaparser.*; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; @@ -37,23 +55,6 @@ import com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.io.IOException; -import java.io.Serializable; -import java.net.ProtocolException; -import java.nio.Buffer; -import java.nio.CharBuffer; -import java.nio.file.FileSystemException; -import java.util.*; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import static org.hamcrest.CoreMatchers.*; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; -import static org.junit.jupiter.api.Assertions.*; class ReferenceTypeTest extends AbstractSymbolResolutionTest { @@ -102,7 +103,7 @@ void setup() { new ReferenceTypeImpl(new ReflectionClassDeclaration(ClassCastException.class, typeSolver)), new ReferenceTypeImpl(new ReflectionClassDeclaration(AssertionError.class, typeSolver)) )); - + // minimal initialization of JavaParser ParserConfiguration configuration = new ParserConfiguration() .setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); @@ -267,7 +268,8 @@ public ResolvedReferenceTypeTester(ResolvedReferenceTypeDeclaration typeDeclarat super(typeDeclaration); } - public boolean isCorrespondingBoxingType(String name) { + @Override + public boolean isCorrespondingBoxingType(String name) { return super.isCorrespondingBoxingType(name); } @@ -335,7 +337,7 @@ void testIsAssignableByGenericsInheritance() { assertEquals(false, linkedListOfString.isAssignableBy(listOfStrings)); assertEquals(true, linkedListOfString.isAssignableBy(linkedListOfString)); } - + @Test void testIsAssignableByUnionType() { assertEquals(true, ioException.isAssignableBy(unionWithIOExceptionAsCommonAncestor)); @@ -852,7 +854,7 @@ void testGetAllFieldsVisibleToInheritors() { assertTrue(rtB.getAllFieldsVisibleToInheritors().stream().anyMatch(f -> f.getName().equals("l"))); assertTrue(rtB.getAllFieldsVisibleToInheritors().stream().anyMatch(f -> f.getName().equals("b"))); } - + @Test void erasure_non_generic_type() { List types = declaredTypes( @@ -860,7 +862,7 @@ void erasure_non_generic_type() { ResolvedType expected = types.get(0); assertEquals(expected, types.get(0).erasure()); } - + @Test // The erasure of a parameterized type void erasure_rawtype() { @@ -882,7 +884,7 @@ void erasure_arraytype() { String expected = "java.util.List[]"; assertEquals(expected, genericList.erasure().describe()); } - + @Test // The erasure of an array type T[] is |T|[]. void erasure_arraytype_with_bound() { @@ -892,7 +894,7 @@ void erasure_arraytype_with_bound() { String expected = "java.util.List[]"; assertEquals(expected, genericList.erasure().describe()); } - + @Test // The erasure of a type variable (§4.4) is the erasure of its leftmost bound. void erasure_type_variable() { @@ -902,7 +904,7 @@ void erasure_type_variable() { String expected = "A"; assertEquals(expected, rt.erasure().describe()); } - + @Test // The erasure of a nested type T.C is |T|.C. void erasure_nested_type() { @@ -926,17 +928,31 @@ void erasure_nested_type() { // assertEquals(expectedErasedAType, typeA.erasure()); assertEquals(expectedErasedCType, typeC.erasure()); } - + + @Test + void extend_type() { + ResolvedTypeVariable variable = parametrizedType("java.util.List", "java.lang.String"); + assertTrue(variable.asTypeParameter().hasUpperBound()); + assertFalse(variable.asTypeParameter().hasLowerBound()); + } + + @Test + void super_type() { + ResolvedTypeVariable variable = parametrizedTypeLowerBounded("java.util.List", "java.lang.String"); + assertTrue(variable.asTypeParameter().hasLowerBound()); + assertFalse(variable.asTypeParameter().hasUpperBound()); + } + // return a generic type with type arguments (arguments can be bounded) private ResolvedType genericType(String type, ResolvedType... parameterTypes) { return type(type, toList(parameterTypes)); } - + // return a generic type with type arguments private ResolvedType genericType(String type, String... parameterTypes) { return new ReferenceTypeImpl(typeSolver.solveType(type), types(parameterTypes)); } - + // return a list of types private List types(String... types) { return Arrays.stream(types).map(type -> type(type)).collect(Collectors.toList()); @@ -946,36 +962,50 @@ private List types(String... types) { private ResolvedType type(String type) { return type(type, new ArrayList<>()); } - + private ResolvedType type(String type, List typeArguments) { return new ReferenceTypeImpl(typeSolver.solveType(type), typeArguments); } - + // return a type parameter private ResolvedTypeVariable parametrizedType(String type, String parameterType) { + return parametrizedTypeUpperBounded(type, parameterType); + } + + private ResolvedTypeVariable parametrizedTypeUpperBounded(String type, String parameterType) { return new ResolvedTypeVariable(ResolvedTypeParameterDeclaration.onType(parameterType, type + "." + parameterType, Arrays.asList((extendBound(parameterType))))); } - // rturn an extend bound + private ResolvedTypeVariable parametrizedTypeLowerBounded(String type, String parameterType) { + return new ResolvedTypeVariable(ResolvedTypeParameterDeclaration.onType(parameterType, type + "." + parameterType, + Arrays.asList((superBound(parameterType))))); + } + + // return an extend bound private Bound extendBound(String type) { return Bound.extendsBound(type(type)); } + // return a super bound + private Bound superBound(String type) { + return Bound.superBound(type(type)); + } + private Set toSet(ResolvedType... resolvedTypes) { return new HashSet<>(toList(resolvedTypes)); } - + private List toList(ResolvedType... resolvedTypes) { return Arrays.asList(resolvedTypes); } - + // return an array type from the base type private ResolvedType array(ResolvedType baseType) { return new ResolvedArrayType(baseType); } - - // return a list of types from the declared types (using a static parser) + + // return a list of types from the declared types (using a static parser) private List declaredTypes(String... lines) { CompilationUnit tree = treeOf(lines); List results = Lists.newLinkedList(); @@ -992,5 +1022,5 @@ private CompilationUnit treeOf(String... lines) { } return StaticJavaParser.parse(builder.toString()); } - + } From 6cb48c3eaffb0a105118b822746b49e6507c2c68 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Thu, 24 Aug 2023 09:02:50 +0200 Subject: [PATCH 060/136] Fix: issue 4124 UnsupportedOperationException: 'T' is thrown in MethodCallExpr resolve --- .../logic/MethodResolutionLogic.java | 3 + .../symbolsolver/Issue4124Test.java | 71 +++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100755 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue4124Test.java diff --git a/javaparser-core/src/main/java/com/github/javaparser/resolution/logic/MethodResolutionLogic.java b/javaparser-core/src/main/java/com/github/javaparser/resolution/logic/MethodResolutionLogic.java index 91aa72e61f..9d51840ebf 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/resolution/logic/MethodResolutionLogic.java +++ b/javaparser-core/src/main/java/com/github/javaparser/resolution/logic/MethodResolutionLogic.java @@ -330,6 +330,9 @@ private static boolean isAssignableMatchTypeParametersMatchingQName(ResolvedRefe if (!actualParam.isTypeVariable() || !actualParam.asTypeParameter().getName().equals(expectedParamName)) { return matchTypeVariable(expectedParam.asTypeVariable(), actualParam, matchedParameters); } + // actualParam is a TypeVariable and actualParam has the same name as expectedParamName + // We should definitely consider that types are assignable + return true; } else if (expectedParam.isReferenceType()) { if (actualParam.isTypeVariable()) { return matchTypeVariable(actualParam.asTypeVariable(), expectedParam, matchedParameters); diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue4124Test.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue4124Test.java new file mode 100755 index 0000000000..1534531831 --- /dev/null +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue4124Test.java @@ -0,0 +1,71 @@ +/* + * Copyright (C) 2013-2023 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.symbolsolver; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +import com.github.javaparser.JavaParserAdapter; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.expr.MethodCallExpr; +import com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration; +import com.github.javaparser.symbolsolver.resolution.AbstractResolutionTest; + +public class Issue4124Test extends AbstractResolutionTest { + + @Test + void issue4124_withDifferentTypeParameterName() { + + String code = + "import java.util.Collections;\n" + + "import java.util.List;\n" + + "public class Foo {\n" + + " public void test(List ls){\n" + + " Collections.synchronizedList(ls);\n" + + " }\n" + + "}\n"; + + CompilationUnit cu = JavaParserAdapter.of(createParserWithResolver(defaultTypeSolver())).parse(code); + + MethodCallExpr m = cu.findFirst(MethodCallExpr.class).get(); + ResolvedMethodDeclaration rmd = m.resolve(); + assertEquals("java.util.Collections.synchronizedList(java.util.List)", rmd.getQualifiedSignature()); + } + + @Test + void issue4124_withSameTypeParameterName() { + String code = + "import java.util.Collections;\n" + + "import java.util.List;\n" + + "public class Foo {\n" + + " public void test(List ls){\n" + + " Collections.synchronizedList(ls);\n" + + " }\n" + + "}\n"; + + CompilationUnit cu = JavaParserAdapter.of(createParserWithResolver(defaultTypeSolver())).parse(code); + + MethodCallExpr m = cu.findFirst(MethodCallExpr.class).get(); + ResolvedMethodDeclaration rmd = m.resolve(); + assertEquals("java.util.Collections.synchronizedList(java.util.List)", rmd.getQualifiedSignature()); + } +} From c808ebfa8325091c8f7a10524492cf4469227176 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Thu, 24 Aug 2023 11:41:25 +0200 Subject: [PATCH 061/136] Add unit test for PR 4091 Fixed missing permits in pretty printer --- .../printer/PrettyPrintVisitorTest.java | 31 ++++++++++++++----- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/PrettyPrintVisitorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/PrettyPrintVisitorTest.java index 1c57a9f405..c478786b2a 100644 --- a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/PrettyPrintVisitorTest.java +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/PrettyPrintVisitorTest.java @@ -21,6 +21,15 @@ package com.github.javaparser.printer; +import static com.github.javaparser.StaticJavaParser.parse; +import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol; +import static com.github.javaparser.utils.Utils.SYSTEM_EOL; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Optional; + +import org.junit.jupiter.api.Test; + import com.github.javaparser.ParserConfiguration; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.Node; @@ -38,14 +47,6 @@ import com.github.javaparser.printer.configuration.DefaultPrinterConfiguration.ConfigOption; import com.github.javaparser.printer.configuration.PrinterConfiguration; import com.github.javaparser.utils.TestParser; -import org.junit.jupiter.api.Test; - -import java.util.Optional; - -import static com.github.javaparser.StaticJavaParser.parse; -import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol; -import static com.github.javaparser.utils.Utils.SYSTEM_EOL; -import static org.junit.jupiter.api.Assertions.assertEquals; class PrettyPrintVisitorTest extends TestParser { @@ -521,4 +522,18 @@ void innerClassWithConstructorReceiverParameterTest() { CompilationUnit cu = parseCompilationUnit(innerClassWithConstructorReceiverParam); assertEqualsStringIgnoringEol(innerClassWithConstructorReceiverParam, print(cu)); } + + @Test + void printPermitsKeyworld() { + CompilationUnit cu = parseCompilationUnit( + ParserConfiguration.LanguageLevel.JAVA_17, + "public sealed interface I1 permits I2, C, D {}" + ); + String expected = + "public sealed interface I1 permits I2, C, D {\n" + + "}\n"; + + + assertEqualsStringIgnoringEol(expected, cu.toString()); + } } From 065e80bbbf3f45f06781a68dcc4156d5da173c4e Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Thu, 24 Aug 2023 14:44:05 +0000 Subject: [PATCH 062/136] chore(deps): update actions/checkout action to v3.6.0 --- .github/workflows/create_github_release.yml | 2 +- .github/workflows/maven_tests.yml | 4 ++-- .github/workflows/prepare_release_changelog.yml | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/create_github_release.yml b/.github/workflows/create_github_release.yml index 0f4d2b94ad..12a4e0cf2c 100644 --- a/.github/workflows/create_github_release.yml +++ b/.github/workflows/create_github_release.yml @@ -13,7 +13,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout code - uses: actions/checkout@v3.5.3 + uses: actions/checkout@v3.6.0 - name: Create Release id: create_release diff --git a/.github/workflows/maven_tests.yml b/.github/workflows/maven_tests.yml index 15d6aecb86..fe83eddbc0 100644 --- a/.github/workflows/maven_tests.yml +++ b/.github/workflows/maven_tests.yml @@ -45,7 +45,7 @@ jobs: steps: ## Checkout the current version of the code from the repo. - name: Checkout latest code - uses: actions/checkout@v3.5.3 + uses: actions/checkout@v3.6.0 with: fetch-depth: "0" @@ -109,7 +109,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout latest code - uses: actions/checkout@v3.5.3 + uses: actions/checkout@v3.6.0 with: fetch-depth: "0" - name: Set up JDK 11 diff --git a/.github/workflows/prepare_release_changelog.yml b/.github/workflows/prepare_release_changelog.yml index 911a0a0112..2d121bbf7a 100644 --- a/.github/workflows/prepare_release_changelog.yml +++ b/.github/workflows/prepare_release_changelog.yml @@ -15,7 +15,7 @@ jobs: # Check out current repository - name: Fetch Sources - uses: actions/checkout@v3.5.3 + uses: actions/checkout@v3.6.0 # Setup Java 11 environment for the next steps - name: Setup Java From bbc711c1c84f0899edb45eeb63221ea4cf3cad59 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Sat, 26 Aug 2023 18:13:28 +0200 Subject: [PATCH 063/136] Fix: issue 3976 Issue resolving implicit generic types --- .../contexts/MethodCallExprContext.java | 74 +++++++++++++++++++ .../symbolsolver/Issue3976Test.java | 33 +++++++++ 2 files changed, 107 insertions(+) create mode 100755 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3976Test.java diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/MethodCallExprContext.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/MethodCallExprContext.java index 08d8266856..21b0a608c6 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/MethodCallExprContext.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/MethodCallExprContext.java @@ -22,6 +22,7 @@ package com.github.javaparser.symbolsolver.javaparsermodel.contexts; import java.util.*; +import java.util.stream.Collectors; import com.github.javaparser.ast.expr.Expression; import com.github.javaparser.ast.expr.MethodCallExpr; @@ -38,6 +39,7 @@ import com.github.javaparser.resolution.model.typesystem.ReferenceTypeImpl; import com.github.javaparser.resolution.types.*; import com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade; +import com.github.javaparser.symbolsolver.resolution.typeinference.LeastUpperBoundLogic; import com.github.javaparser.utils.Pair; public class MethodCallExprContext extends AbstractJavaParserContext { @@ -408,14 +410,86 @@ private MethodUsage resolveMethodTypeParameters(MethodUsage methodUsage, List matchedTypeParameters) { + // first group all resolved types by type variable + Map> resolvedTypesByTypeVariable = groupResolvedTypeByTypeVariable(matchedTypeParameters); + // then reduce the list of resolved types with the least upper bound logic + Map reducedResolvedTypesByTypeVariable = reduceResolvedTypesByTypeVariable(resolvedTypesByTypeVariable); + // then replace resolved type by the reduced type for each type variable + convertTypesParameters(matchedTypeParameters, reducedResolvedTypesByTypeVariable); + // finally replace type parameters for (ResolvedTypeParameterDeclaration tp : matchedTypeParameters.keySet()) { methodUsage = methodUsage.replaceTypeParameter(tp, matchedTypeParameters.get(tp)); } return methodUsage; } + /* + * Update the matchedTypeParameters map from the types in reducedResolvedTypesByTypeVariable map. + */ + private void convertTypesParameters( + Map matchedTypeParameters, + Map reducedResolvedTypesByTypeVariable) { + for (ResolvedTypeParameterDeclaration tp : matchedTypeParameters.keySet()) { + String typeParameterName = tp.getName(); + boolean replacement = reducedResolvedTypesByTypeVariable.keySet().contains(typeParameterName); + if (replacement) { + matchedTypeParameters.put(tp, reducedResolvedTypesByTypeVariable.get(typeParameterName)); + } + } + } + + /* + * Group resolved type by the variable type. For example in Map.of("k0", 0, "k1", + * 1D) which is solved as static Map of(K k1, V v1, K k2, V v2) + * the type variable named V that represents the type of the first and fourth parameter + * must reference v1 (Integer type) and v2 (Double type). + */ + private Map> groupResolvedTypeByTypeVariable(Map typeParameters) { + Map> resolvedTypesByTypeVariable = new HashMap<>(); + for (ResolvedTypeParameterDeclaration tp : typeParameters.keySet()) { + String typeParameterName = tp.getName(); + boolean alreadyCollected = resolvedTypesByTypeVariable.keySet().contains(typeParameterName); + if (!alreadyCollected) { + Set resolvedTypes = findResolvedTypesByTypeVariable(typeParameterName, typeParameters); + resolvedTypesByTypeVariable.put(typeParameterName, resolvedTypes); + } + } + return resolvedTypesByTypeVariable; + } + + /* + * Collect all resolved type from a type variable name + */ + private Set findResolvedTypesByTypeVariable(String typeVariableName, Map typeParameters) { + return typeParameters.keySet().stream() + .filter(resolvedTypeParameterDeclaration -> resolvedTypeParameterDeclaration.getName().equals(typeVariableName)) + .map(resolvedTypeParameterDeclaration -> typeParameters.get(resolvedTypeParameterDeclaration)) + .collect(Collectors.toSet()); + } + + /* + * Reduce all set of resolved type with LUB + */ + private Map reduceResolvedTypesByTypeVariable(Map> typeParameters) { + Map reducedResolvedTypesList = new HashMap<>(); + for (String typeParameterName : typeParameters.keySet()) { + ResolvedType type = reduceResolvedTypesWithLub(typeParameters.get(typeParameterName)); + reducedResolvedTypesList.put(typeParameterName, type); + } + return reducedResolvedTypesList; + } + + private ResolvedType reduceResolvedTypesWithLub(Set resolvedTypes) { + return LeastUpperBoundLogic.of().lub(resolvedTypes); + } + private void matchTypeParameters(ResolvedType expectedType, ResolvedType actualType, Map matchedTypeParameters) { if (expectedType.isTypeVariable()) { ResolvedType type = actualType; diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3976Test.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3976Test.java new file mode 100755 index 0000000000..be3833f340 --- /dev/null +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3976Test.java @@ -0,0 +1,33 @@ +package com.github.javaparser.symbolsolver; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +import com.github.javaparser.JavaParserAdapter; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.expr.MethodCallExpr; +import com.github.javaparser.resolution.types.ResolvedType; +import com.github.javaparser.symbolsolver.resolution.AbstractResolutionTest; + +public class Issue3976Test extends AbstractResolutionTest { + + @Test + void test() { + String testCase = + "import java.util.Map;\n" + + "public class Foo{\n" + + " public Object m() {\n" + + " return Map.of(\"k0\", 0, \"k1\", 1D);\n" + + " }\n" + + "}\n" + + ""; + + CompilationUnit cu = JavaParserAdapter.of(createParserWithResolver(defaultTypeSolver())).parse(testCase); + + MethodCallExpr methodCallExpr = cu.findFirst(MethodCallExpr.class).get(); + + ResolvedType rt = methodCallExpr.calculateResolvedType(); + assertEquals("java.util.Map", rt.describe()); + } +} From b4b7eb20e0001e2303744fa088094b9357a2f1d0 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Sat, 26 Aug 2023 19:49:36 +0200 Subject: [PATCH 064/136] Test method is only enabled for a specific range of Java RuntimeEnvironment (JRE) versions from java 9 --- .../javaparser/symbolsolver/Issue3976Test.java | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3976Test.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3976Test.java index be3833f340..899adec21e 100755 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3976Test.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3976Test.java @@ -3,6 +3,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledForJreRange; +import org.junit.jupiter.api.condition.JRE; import com.github.javaparser.JavaParserAdapter; import com.github.javaparser.ast.CompilationUnit; @@ -13,15 +15,15 @@ public class Issue3976Test extends AbstractResolutionTest { @Test + @EnabledForJreRange(min = JRE.JAVA_9) void test() { String testCase = "import java.util.Map;\n" - + "public class Foo{\n" - + " public Object m() {\n" - + " return Map.of(\"k0\", 0, \"k1\", 1D);\n" - + " }\n" - + "}\n" - + ""; + + "public class Foo {\n" + + " public Object m() {\n" + + " return Map.of(\"k0\", 0, \"k1\", 1D);\n" + + " }\n" + + "}"; CompilationUnit cu = JavaParserAdapter.of(createParserWithResolver(defaultTypeSolver())).parse(testCase); From 63ba04b2736e8f4e0fc853dd9878e71a40798efc Mon Sep 17 00:00:00 2001 From: 70825 Date: Sun, 27 Aug 2023 23:33:03 +0900 Subject: [PATCH 065/136] Fix multiline strings --- .github/workflows/prepare_release_changelog.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/prepare_release_changelog.yml b/.github/workflows/prepare_release_changelog.yml index 2d121bbf7a..59029b9a7a 100644 --- a/.github/workflows/prepare_release_changelog.yml +++ b/.github/workflows/prepare_release_changelog.yml @@ -41,7 +41,9 @@ jobs: echo "sha_long=$SHA_LONG" >> $GITHUB_OUTPUT echo "sha_short=$SHA_SHORT" >> $GITHUB_OUTPUT - echo "changelog=$CHANGELOG" >> $GITHUB_OUTPUT + echo "changelog<> $GITHUB_OUTPUT + echo "$CHANGELOG" >> $GITHUB_OUTPUT + echo "EOF" >> $GITHUB_OUTPUT echo "release_title=$RELEASE_TITLE" >> $GITHUB_OUTPUT echo "release_tag_name=$RELEASE_TAG_NAME" >> $GITHUB_OUTPUT From 7f85786bb02dd19bd90e39becdbc66654405fdb4 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 28 Aug 2023 05:00:10 +0000 Subject: [PATCH 066/136] chore(deps): update dependency com.puppycrawl.tools:checkstyle to v10.12.3 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 448a14f6f0..8050baf784 100644 --- a/pom.xml +++ b/pom.xml @@ -352,7 +352,7 @@ com.puppycrawl.tools checkstyle - 10.12.2 + 10.12.3 From 864ed44007ff53e9302d2ea95950f4f710c79d16 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Tue, 29 Aug 2023 17:04:17 +0200 Subject: [PATCH 067/136] Minor refactoring (renaming ReadOnlyListIterator ato ArrayIterator) --- .../lexicalpreservation/Difference.java | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java index 95f7516a8b..4b5eac7849 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java @@ -123,7 +123,7 @@ int lastIndexOfEol(List source) { private int posOfNextComment(int fromIndex, List elements) { if (!isValidIndex(fromIndex, elements)) return -1; - ReadOnlyListIterator iterator = new ReadOnlyListIterator(elements, fromIndex); + ArrayIterator iterator = new ArrayIterator(elements, fromIndex); // search for the next consecutive space characters while (iterator.hasNext()) { TextElement element = iterator.next(); @@ -1092,12 +1092,12 @@ private String tokenDescription(int kind) { private Map getCorrespondanceBetweenNextOrderAndPreviousOrder(CsmMix elementsFromPreviousOrder, CsmMix elementsFromNextOrder) { Map correspondanceBetweenNextOrderAndPreviousOrder = new HashMap<>(); - ReadOnlyListIterator previousOrderElementsIterator = new ReadOnlyListIterator( + ArrayIterator previousOrderElementsIterator = new ArrayIterator( elementsFromPreviousOrder.getElements()); int syncNextIndex = 0; while (previousOrderElementsIterator.hasNext()) { CsmElement pe = previousOrderElementsIterator.next(); - ReadOnlyListIterator nextOrderElementsIterator = new ReadOnlyListIterator( + ArrayIterator nextOrderElementsIterator = new ArrayIterator( elementsFromNextOrder.getElements(), syncNextIndex); while (nextOrderElementsIterator.hasNext()) { CsmElement ne = nextOrderElementsIterator.next(); @@ -1118,51 +1118,51 @@ private Map getCorrespondanceBetweenNextOrderAndPreviousOrder( * A list iterator which does not allow to modify the list * and which provides a method to know the current positioning */ - private class ReadOnlyListIterator implements ListIterator { - ListIterator elements; - public ReadOnlyListIterator(List elements) { + private class ArrayIterator implements ListIterator { + ListIterator iterator; + public ArrayIterator(List elements) { this(elements, 0); } - public ReadOnlyListIterator(List elements, int index) { - this.elements = elements.listIterator(index); + public ArrayIterator(List elements, int index) { + this.iterator = elements.listIterator(index); } @Override public boolean hasNext() { - return elements.hasNext(); + return iterator.hasNext(); } @Override public T next() { - return elements.next(); + return iterator.next(); } @Override public boolean hasPrevious() { - return elements.hasPrevious(); + return iterator.hasPrevious(); } @Override public T previous() { - return elements.previous(); + return iterator.previous(); } @Override public int nextIndex() { - return elements.nextIndex(); + return iterator.nextIndex(); } @Override public int previousIndex() { - return elements.previousIndex(); + return iterator.previousIndex(); } /* * Returns the current index in the underlying list */ public int index() { - return elements.nextIndex() - 1; + return iterator.nextIndex() - 1; } @Override From 9eaa832126711aed86a083d319f31d782001d462 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Wed, 30 Aug 2023 12:12:13 +0200 Subject: [PATCH 068/136] Extract reshuffled difference elements logic in a proper class --- .../lexicalpreservation/Difference.java | 234 +---------------- .../ReshuffledDiffElementExtractor.java | 245 ++++++++++++++++++ 2 files changed, 254 insertions(+), 225 deletions(-) create mode 100755 javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/ReshuffledDiffElementExtractor.java diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java index 4b5eac7849..fc95a8f6c4 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java @@ -37,7 +37,9 @@ import com.github.javaparser.ast.type.ArrayType; import com.github.javaparser.ast.type.ClassOrInterfaceType; import com.github.javaparser.ast.type.Type; -import com.github.javaparser.printer.concretesyntaxmodel.*; +import com.github.javaparser.printer.concretesyntaxmodel.CsmElement; +import com.github.javaparser.printer.concretesyntaxmodel.CsmIndent; +import com.github.javaparser.printer.concretesyntaxmodel.CsmUnindent; import com.github.javaparser.printer.lexicalpreservation.LexicalDifferenceCalculator.CsmChild; /** @@ -344,7 +346,7 @@ private boolean isSpaceOrTabElement(NodeText nodeText, int i) { * to the difference (adding and removing the elements provided). */ void apply() { - extractReshuffledDiffElements(diffElements); + ReshuffledDiffElementExtractor.of(nodeText, node).extract(diffElements); Map removedGroups = combineRemovedElementsToRemovedGroups(); do { boolean isLeftOverDiffElement = applyLeftOverDiffElements(); @@ -404,90 +406,6 @@ private boolean applyLeftOverDiffElements() { return isLeftOverElement; } - private void extractReshuffledDiffElements(List diffElements) { - for (int index = 0; index < diffElements.size(); index++) { - DifferenceElement diffElement = diffElements.get(index); - if (diffElement instanceof Reshuffled) { - Reshuffled reshuffled = (Reshuffled) diffElement; - // First, let's see how many tokens we need to attribute to the previous version of the of the CsmMix - CsmMix elementsFromPreviousOrder = reshuffled.getPreviousOrder(); - CsmMix elementsFromNextOrder = reshuffled.getNextOrder(); - // This contains indexes from elementsFromNextOrder to indexes from elementsFromPreviousOrder - Map correspondanceBetweenNextOrderAndPreviousOrder = getCorrespondanceBetweenNextOrderAndPreviousOrder(elementsFromPreviousOrder, elementsFromNextOrder); - // We now find out which Node Text elements corresponds to the elements in the original CSM - List nodeTextIndexOfPreviousElements = findIndexOfCorrespondingNodeTextElement(elementsFromPreviousOrder.getElements(), nodeText, originalIndex, node); - Map nodeTextIndexToPreviousCSMIndex = new HashMap<>(); - for (int i = 0; i < nodeTextIndexOfPreviousElements.size(); i++) { - int value = nodeTextIndexOfPreviousElements.get(i); - if (value != -1) { - nodeTextIndexToPreviousCSMIndex.put(value, i); - } - } - int lastNodeTextIndex = nodeTextIndexOfPreviousElements.stream().max(Integer::compareTo).orElse(-1); - // Elements to be added at the end - List elementsToBeAddedAtTheEnd = new LinkedList<>(); - List nextOrderElements = elementsFromNextOrder.getElements(); - Map> elementsToAddBeforeGivenOriginalCSMElement = new HashMap<>(); - for (int ni = 0; ni < nextOrderElements.size(); ni++) { - // If it has a mapping, then it is kept - if (!correspondanceBetweenNextOrderAndPreviousOrder.containsKey(ni)) { - // Ok, it is something new. Where to put it? Let's see what is the first following - // element that has a mapping - int originalCsmIndex = -1; - for (int nj = ni + 1; nj < nextOrderElements.size() && originalCsmIndex == -1; nj++) { - if (correspondanceBetweenNextOrderAndPreviousOrder.containsKey(nj)) { - originalCsmIndex = correspondanceBetweenNextOrderAndPreviousOrder.get(nj); - if (!elementsToAddBeforeGivenOriginalCSMElement.containsKey(originalCsmIndex)) { - elementsToAddBeforeGivenOriginalCSMElement.put(originalCsmIndex, new LinkedList<>()); - } - elementsToAddBeforeGivenOriginalCSMElement.get(originalCsmIndex).add(nextOrderElements.get(ni)); - } - } - // it does not preceed anything, so it goes at the end - if (originalCsmIndex == -1) { - elementsToBeAddedAtTheEnd.add(nextOrderElements.get(ni)); - } - } - } - // We go over the original node text elements, in the order they appear in the NodeText. - // Considering an original node text element (ONE) - // * we verify if it corresponds to a CSM element. If it does not we just move on, otherwise - // we find the correspond OCE (Original CSM Element) - // * we first add new elements that are marked to be added before OCE - // * if OCE is marked to be present also in the "after" CSM we add a kept element, - // otherwise we add a removed element - // Remove the whole Reshuffled element - diffElements.remove(index); - int diffElIterator = index; - if (lastNodeTextIndex != -1) { - for (int ntIndex = originalIndex; ntIndex <= lastNodeTextIndex; ntIndex++) { - if (nodeTextIndexToPreviousCSMIndex.containsKey(ntIndex)) { - int indexOfOriginalCSMElement = nodeTextIndexToPreviousCSMIndex.get(ntIndex); - if (elementsToAddBeforeGivenOriginalCSMElement.containsKey(indexOfOriginalCSMElement)) { - for (CsmElement elementToAdd : elementsToAddBeforeGivenOriginalCSMElement.get(indexOfOriginalCSMElement)) { - diffElements.add(diffElIterator++, new Added(elementToAdd)); - } - } - CsmElement originalCSMElement = elementsFromPreviousOrder.getElements().get(indexOfOriginalCSMElement); - boolean toBeKept = correspondanceBetweenNextOrderAndPreviousOrder.containsValue(indexOfOriginalCSMElement); - if (toBeKept) { - diffElements.add(diffElIterator++, new Kept(originalCSMElement)); - } else { - diffElements.add(diffElIterator++, new Removed(originalCSMElement)); - } - } - // else we have a simple node text element, without associated csm element, just keep ignore it - } - } - // Finally we look for the remaining new elements that were not yet added and - // add all of them - for (CsmElement elementToAdd : elementsToBeAddedAtTheEnd) { - diffElements.add(diffElIterator++, new Added(elementToAdd)); - } - } - } - } - /** * Maps all Removed elements as keys to their corresponding RemovedGroup. * A RemovedGroup contains all consecutive Removed elements. @@ -1075,50 +993,10 @@ private String tokenDescription(int kind) { return GeneratedJavaParserConstants.tokenImage[kind]; } - /* - * Considering that the lists of elements are ordered, We can find the common - * elements by starting with the list before the modifications and, for each - * element, by going through the list of elements containing the modifications. - * - * We can find the common elements by starting with the list before the - * modifications (L1) and, for each element, by going through the list of elements - * containing the modifications (L2). - * - * If element A in list L1 is not found in list L2, it is a deleted element. - * If element A of list L1 is found in list L2, it is a kept element. In this - * case the search for the next element of the list L1 must start from the - * position of the last element kept {@code syncNextIndex}. - */ - private Map getCorrespondanceBetweenNextOrderAndPreviousOrder(CsmMix elementsFromPreviousOrder, - CsmMix elementsFromNextOrder) { - Map correspondanceBetweenNextOrderAndPreviousOrder = new HashMap<>(); - ArrayIterator previousOrderElementsIterator = new ArrayIterator( - elementsFromPreviousOrder.getElements()); - int syncNextIndex = 0; - while (previousOrderElementsIterator.hasNext()) { - CsmElement pe = previousOrderElementsIterator.next(); - ArrayIterator nextOrderElementsIterator = new ArrayIterator( - elementsFromNextOrder.getElements(), syncNextIndex); - while (nextOrderElementsIterator.hasNext()) { - CsmElement ne = nextOrderElementsIterator.next(); - if (!correspondanceBetweenNextOrderAndPreviousOrder.values().contains(previousOrderElementsIterator.index()) - && DifferenceElementCalculator.matching(ne, pe)) { - correspondanceBetweenNextOrderAndPreviousOrder.put(nextOrderElementsIterator.index(), - previousOrderElementsIterator.index()); - // set the position to start on the next {@code nextOrderElementsIterator} iteration - syncNextIndex = nextOrderElementsIterator.index(); - break; - } - } - } - return correspondanceBetweenNextOrderAndPreviousOrder; - } - /* - * A list iterator which does not allow to modify the list - * and which provides a method to know the current positioning + * A list iterator which provides a method to know the current positioning */ - private class ArrayIterator implements ListIterator { + public static class ArrayIterator implements ListIterator { ListIterator iterator; public ArrayIterator(List elements) { this(elements, 0); @@ -1167,17 +1045,17 @@ public int index() { @Override public void remove() { - throw new UnsupportedOperationException(); + iterator.remove();; } @Override public void set(T e) { - throw new UnsupportedOperationException(); + iterator.set(e); } @Override public void add(T e) { - throw new UnsupportedOperationException(); + iterator.add(e);; } } @@ -1190,100 +1068,6 @@ private boolean isFollowedByUnindent(List diffElements, int d return (nextIndexValue) < diffElements.size() && diffElements.get(nextIndexValue).isAdded() && diffElements.get(nextIndexValue).getElement() instanceof CsmUnindent; } - private List findIndexOfCorrespondingNodeTextElement(List elements, NodeText nodeText, int startIndex, Node node) { - List correspondingIndices = new ArrayList<>(); - for (ListIterator csmElementListIterator = elements.listIterator(); csmElementListIterator.hasNext(); ) { - int previousCsmElementIndex = csmElementListIterator.previousIndex(); - CsmElement csmElement = csmElementListIterator.next(); - int nextCsmElementIndex = csmElementListIterator.nextIndex(); - Map potentialMatches = new EnumMap<>(MatchClassification.class); - for (int i = startIndex; i < nodeText.numberOfElements(); i++) { - if (!correspondingIndices.contains(i)) { - TextElement textElement = nodeText.getTextElement(i); - boolean isCorresponding = isCorrespondingElement(textElement, csmElement, node); - if (isCorresponding) { - boolean hasSamePreviousElement = false; - if (i > 0 && previousCsmElementIndex > -1) { - TextElement previousTextElement = nodeText.getTextElement(i - 1); - hasSamePreviousElement = isCorrespondingElement(previousTextElement, elements.get(previousCsmElementIndex), node); - } - boolean hasSameNextElement = false; - if (i < nodeText.numberOfElements() - 1 && nextCsmElementIndex < elements.size()) { - TextElement nextTextElement = nodeText.getTextElement(i + 1); - hasSameNextElement = isCorrespondingElement(nextTextElement, elements.get(nextCsmElementIndex), node); - } - if (hasSamePreviousElement && hasSameNextElement) { - potentialMatches.putIfAbsent(MatchClassification.ALL, i); - } else if (hasSamePreviousElement) { - potentialMatches.putIfAbsent(MatchClassification.PREVIOUS_AND_SAME, i); - } else if (hasSameNextElement) { - potentialMatches.putIfAbsent(MatchClassification.NEXT_AND_SAME, i); - } else { - potentialMatches.putIfAbsent(MatchClassification.SAME_ONLY, i); - } - } else if (isAlmostCorrespondingElement(textElement, csmElement, node)) { - potentialMatches.putIfAbsent(MatchClassification.ALMOST, i); - } - } - } - // Prioritize the matches from best to worst - Optional bestMatchKey = potentialMatches.keySet().stream().min(Comparator.comparing(MatchClassification::getPriority)); - if (bestMatchKey.isPresent()) { - correspondingIndices.add(potentialMatches.get(bestMatchKey.get())); - } else { - correspondingIndices.add(-1); - } - } - return correspondingIndices; - } - - private enum MatchClassification { - - ALL(1), PREVIOUS_AND_SAME(2), NEXT_AND_SAME(3), SAME_ONLY(4), ALMOST(5); - - private final int priority; - - MatchClassification(int priority) { - this.priority = priority; - } - - int getPriority() { - return priority; - } - } - - private boolean isCorrespondingElement(TextElement textElement, CsmElement csmElement, Node node) { - if (csmElement instanceof CsmToken) { - CsmToken csmToken = (CsmToken) csmElement; - if (textElement instanceof TokenTextElement) { - TokenTextElement tokenTextElement = (TokenTextElement) textElement; - return tokenTextElement.getTokenKind() == csmToken.getTokenType() && tokenTextElement.getText().equals(csmToken.getContent(node)); - } - } else if (csmElement instanceof CsmChild) { - CsmChild csmChild = (CsmChild) csmElement; - if (textElement instanceof ChildTextElement) { - ChildTextElement childTextElement = (ChildTextElement) textElement; - return childTextElement.getChild() == csmChild.getChild(); - } - } else if (csmElement instanceof CsmIndent) { - CsmIndent csmIndent = (CsmIndent) csmElement; - if (textElement instanceof TokenTextElement) { - TokenTextElement tokenTextElement = (TokenTextElement) textElement; - return tokenTextElement.isSpaceOrTab(); - } - } else { - throw new UnsupportedOperationException(); - } - return false; - } - - private boolean isAlmostCorrespondingElement(TextElement textElement, CsmElement csmElement, Node node) { - if (isCorrespondingElement(textElement, csmElement, node)) { - return false; - } - return textElement.isWhiteSpace() && csmElement instanceof CsmToken && ((CsmToken) csmElement).isWhiteSpace(); - } - private int adjustIndentation(List indentation, NodeText nodeText, int nodeTextIndex, boolean followedByUnindent) { List indentationAdj = processIndentation(indentation, nodeText.getElements().subList(0, nodeTextIndex - 1)); if (nodeTextIndex < nodeText.numberOfElements() && nodeText.getTextElement(nodeTextIndex).isToken(RBRACE)) { diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/ReshuffledDiffElementExtractor.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/ReshuffledDiffElementExtractor.java new file mode 100755 index 0000000000..7ffa2afeb5 --- /dev/null +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/ReshuffledDiffElementExtractor.java @@ -0,0 +1,245 @@ +package com.github.javaparser.printer.lexicalpreservation; + +import java.util.*; + +import com.github.javaparser.ast.Node; +import com.github.javaparser.printer.concretesyntaxmodel.CsmElement; +import com.github.javaparser.printer.concretesyntaxmodel.CsmIndent; +import com.github.javaparser.printer.concretesyntaxmodel.CsmMix; +import com.github.javaparser.printer.concretesyntaxmodel.CsmToken; +import com.github.javaparser.printer.lexicalpreservation.Difference.ArrayIterator; +import com.github.javaparser.printer.lexicalpreservation.LexicalDifferenceCalculator.CsmChild; + +public class ReshuffledDiffElementExtractor { + + private final NodeText nodeText; + + private final Node node; + + private enum MatchClassification { + + ALL(1), PREVIOUS_AND_SAME(2), NEXT_AND_SAME(3), SAME_ONLY(4), ALMOST(5); + + private final int priority; + + MatchClassification(int priority) { + this.priority = priority; + } + + int getPriority() { + return priority; + } + } + + static ReshuffledDiffElementExtractor of(NodeText nodeText, Node node) { + return new ReshuffledDiffElementExtractor(nodeText, node); + } + + private ReshuffledDiffElementExtractor(NodeText nodeText, Node node) { + this.nodeText = nodeText; + this.node = node; + } + + public void extract(List diffElements) { + int originalIndex = 0; + ArrayIterator iterator = new ArrayIterator(diffElements); + while (iterator.hasNext()) { + DifferenceElement diffElement = iterator.next(); + if (diffElement instanceof Reshuffled) { + Reshuffled reshuffled = (Reshuffled) diffElement; + // First, let's see how many tokens we need to attribute to the previous version of the of the CsmMix + CsmMix elementsFromPreviousOrder = reshuffled.getPreviousOrder(); + CsmMix elementsFromNextOrder = reshuffled.getNextOrder(); + // This contains indexes from elementsFromNextOrder to indexes from elementsFromPreviousOrder + Map correspondanceBetweenNextOrderAndPreviousOrder = getCorrespondanceBetweenNextOrderAndPreviousOrder(elementsFromPreviousOrder, elementsFromNextOrder); + // We now find out which Node Text elements corresponds to the elements in the original CSM + List nodeTextIndexOfPreviousElements = findIndexOfCorrespondingNodeTextElement(elementsFromPreviousOrder.getElements(), nodeText, originalIndex, node); + Map nodeTextIndexToPreviousCSMIndex = new HashMap<>(); + for (int i = 0; i < nodeTextIndexOfPreviousElements.size(); i++) { + int value = nodeTextIndexOfPreviousElements.get(i); + if (value != -1) { + nodeTextIndexToPreviousCSMIndex.put(value, i); + } + } + int lastNodeTextIndex = nodeTextIndexOfPreviousElements.stream().max(Integer::compareTo).orElse(-1); + // Elements to be added at the end + List elementsToBeAddedAtTheEnd = new LinkedList<>(); + List nextOrderElements = elementsFromNextOrder.getElements(); + Map> elementsToAddBeforeGivenOriginalCSMElement = new HashMap<>(); + for (int ni = 0; ni < nextOrderElements.size(); ni++) { + // If it has a mapping, then it is kept + if (!correspondanceBetweenNextOrderAndPreviousOrder.containsKey(ni)) { + // Ok, it is something new. Where to put it? Let's see what is the first following + // element that has a mapping + int originalCsmIndex = -1; + for (int nj = ni + 1; nj < nextOrderElements.size() && originalCsmIndex == -1; nj++) { + if (correspondanceBetweenNextOrderAndPreviousOrder.containsKey(nj)) { + originalCsmIndex = correspondanceBetweenNextOrderAndPreviousOrder.get(nj); + if (!elementsToAddBeforeGivenOriginalCSMElement.containsKey(originalCsmIndex)) { + elementsToAddBeforeGivenOriginalCSMElement.put(originalCsmIndex, new LinkedList<>()); + } + elementsToAddBeforeGivenOriginalCSMElement.get(originalCsmIndex).add(nextOrderElements.get(ni)); + } + } + // it does not preceed anything, so it goes at the end + if (originalCsmIndex == -1) { + elementsToBeAddedAtTheEnd.add(nextOrderElements.get(ni)); + } + } + } + // We go over the original node text elements, in the order they appear in the NodeText. + // Considering an original node text element (ONE) + // * we verify if it corresponds to a CSM element. If it does not we just move on, otherwise + // we find the correspond OCE (Original CSM Element) + // * we first add new elements that are marked to be added before OCE + // * if OCE is marked to be present also in the "after" CSM we add a kept element, + // otherwise we add a removed element + // Remove the whole Reshuffled element + iterator.remove(); + if (lastNodeTextIndex != -1) { + for (int ntIndex = originalIndex; ntIndex <= lastNodeTextIndex; ntIndex++) { + if (nodeTextIndexToPreviousCSMIndex.containsKey(ntIndex)) { + int indexOfOriginalCSMElement = nodeTextIndexToPreviousCSMIndex.get(ntIndex); + if (elementsToAddBeforeGivenOriginalCSMElement.containsKey(indexOfOriginalCSMElement)) { + for (CsmElement elementToAdd : elementsToAddBeforeGivenOriginalCSMElement.get(indexOfOriginalCSMElement)) { + iterator.add(new Added(elementToAdd)); + } + } + CsmElement originalCSMElement = elementsFromPreviousOrder.getElements().get(indexOfOriginalCSMElement); + boolean toBeKept = correspondanceBetweenNextOrderAndPreviousOrder.containsValue(indexOfOriginalCSMElement); + if (toBeKept) { + iterator.add(new Kept(originalCSMElement)); + } else { + iterator.add(new Removed(originalCSMElement)); + } + } + // else we have a simple node text element, without associated csm element, just keep ignore it + } + } + // Finally we look for the remaining new elements that were not yet added and + // add all of them + for (CsmElement elementToAdd : elementsToBeAddedAtTheEnd) { + iterator.add(new Added(elementToAdd)); + } + } + } + } + + /* + * Considering that the lists of elements are ordered, We can find the common + * elements by starting with the list before the modifications and, for each + * element, by going through the list of elements containing the modifications. + * + * We can find the common elements by starting with the list before the + * modifications (L1) and, for each element, by going through the list of elements + * containing the modifications (L2). + * + * If element A in list L1 is not found in list L2, it is a deleted element. + * If element A of list L1 is found in list L2, it is a kept element. In this + * case the search for the next element of the list L1 must start from the + * position of the last element kept {@code syncNextIndex}. + */ + private Map getCorrespondanceBetweenNextOrderAndPreviousOrder(CsmMix elementsFromPreviousOrder, + CsmMix elementsFromNextOrder) { + Map correspondanceBetweenNextOrderAndPreviousOrder = new HashMap<>(); + ArrayIterator previousOrderElementsIterator = new ArrayIterator<>( + elementsFromPreviousOrder.getElements()); + int syncNextIndex = 0; + while (previousOrderElementsIterator.hasNext()) { + CsmElement pe = previousOrderElementsIterator.next(); + ArrayIterator nextOrderElementsIterator = new ArrayIterator<>( + elementsFromNextOrder.getElements(), syncNextIndex); + while (nextOrderElementsIterator.hasNext()) { + CsmElement ne = nextOrderElementsIterator.next(); + if (!correspondanceBetweenNextOrderAndPreviousOrder.values().contains(previousOrderElementsIterator.index()) + && DifferenceElementCalculator.matching(ne, pe)) { + correspondanceBetweenNextOrderAndPreviousOrder.put(nextOrderElementsIterator.index(), + previousOrderElementsIterator.index()); + // set the position to start on the next {@code nextOrderElementsIterator} iteration + syncNextIndex = nextOrderElementsIterator.index(); + break; + } + } + } + return correspondanceBetweenNextOrderAndPreviousOrder; + } + + private List findIndexOfCorrespondingNodeTextElement(List elements, NodeText nodeText, int startIndex, Node node) { + List correspondingIndices = new ArrayList<>(); + for (ListIterator csmElementListIterator = elements.listIterator(); csmElementListIterator.hasNext(); ) { + int previousCsmElementIndex = csmElementListIterator.previousIndex(); + CsmElement csmElement = csmElementListIterator.next(); + int nextCsmElementIndex = csmElementListIterator.nextIndex(); + Map potentialMatches = new EnumMap<>(MatchClassification.class); + for (int i = startIndex; i < nodeText.numberOfElements(); i++) { + if (!correspondingIndices.contains(i)) { + TextElement textElement = nodeText.getTextElement(i); + boolean isCorresponding = isCorrespondingElement(textElement, csmElement, node); + if (isCorresponding) { + boolean hasSamePreviousElement = false; + if (i > 0 && previousCsmElementIndex > -1) { + TextElement previousTextElement = nodeText.getTextElement(i - 1); + hasSamePreviousElement = isCorrespondingElement(previousTextElement, elements.get(previousCsmElementIndex), node); + } + boolean hasSameNextElement = false; + if (i < nodeText.numberOfElements() - 1 && nextCsmElementIndex < elements.size()) { + TextElement nextTextElement = nodeText.getTextElement(i + 1); + hasSameNextElement = isCorrespondingElement(nextTextElement, elements.get(nextCsmElementIndex), node); + } + if (hasSamePreviousElement && hasSameNextElement) { + potentialMatches.putIfAbsent(MatchClassification.ALL, i); + } else if (hasSamePreviousElement) { + potentialMatches.putIfAbsent(MatchClassification.PREVIOUS_AND_SAME, i); + } else if (hasSameNextElement) { + potentialMatches.putIfAbsent(MatchClassification.NEXT_AND_SAME, i); + } else { + potentialMatches.putIfAbsent(MatchClassification.SAME_ONLY, i); + } + } else if (isAlmostCorrespondingElement(textElement, csmElement, node)) { + potentialMatches.putIfAbsent(MatchClassification.ALMOST, i); + } + } + } + // Prioritize the matches from best to worst + Optional bestMatchKey = potentialMatches.keySet().stream().min(Comparator.comparing(MatchClassification::getPriority)); + if (bestMatchKey.isPresent()) { + correspondingIndices.add(potentialMatches.get(bestMatchKey.get())); + } else { + correspondingIndices.add(-1); + } + } + return correspondingIndices; + } + + private boolean isCorrespondingElement(TextElement textElement, CsmElement csmElement, Node node) { + if (csmElement instanceof CsmToken) { + CsmToken csmToken = (CsmToken) csmElement; + if (textElement instanceof TokenTextElement) { + TokenTextElement tokenTextElement = (TokenTextElement) textElement; + return tokenTextElement.getTokenKind() == csmToken.getTokenType() && tokenTextElement.getText().equals(csmToken.getContent(node)); + } + } else if (csmElement instanceof CsmChild) { + CsmChild csmChild = (CsmChild) csmElement; + if (textElement instanceof ChildTextElement) { + ChildTextElement childTextElement = (ChildTextElement) textElement; + return childTextElement.getChild() == csmChild.getChild(); + } + } else if (csmElement instanceof CsmIndent) { + CsmIndent csmIndent = (CsmIndent) csmElement; + if (textElement instanceof TokenTextElement) { + TokenTextElement tokenTextElement = (TokenTextElement) textElement; + return tokenTextElement.isSpaceOrTab(); + } + } else { + throw new UnsupportedOperationException(); + } + return false; + } + + private boolean isAlmostCorrespondingElement(TextElement textElement, CsmElement csmElement, Node node) { + if (isCorrespondingElement(textElement, csmElement, node)) { + return false; + } + return textElement.isWhiteSpace() && csmElement instanceof CsmToken && ((CsmToken) csmElement).isWhiteSpace(); + } +} From 937830cb9b1988c823c9581f2553622b7681a8af Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Wed, 30 Aug 2023 13:20:39 +0200 Subject: [PATCH 069/136] Remove not used methods and compilation warnings --- .../lexicalpreservation/Difference.java | 50 +++---------------- 1 file changed, 8 insertions(+), 42 deletions(-) diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java index fc95a8f6c4..359c361a80 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java @@ -125,7 +125,7 @@ int lastIndexOfEol(List source) { private int posOfNextComment(int fromIndex, List elements) { if (!isValidIndex(fromIndex, elements)) return -1; - ArrayIterator iterator = new ArrayIterator(elements, fromIndex); + ArrayIterator iterator = new ArrayIterator<>(elements, fromIndex); // search for the next consecutive space characters while (iterator.hasNext()) { TextElement element = iterator.next(); @@ -157,7 +157,7 @@ private void removeElements(int fromIndex, int toIndex, List elemen // removing elements int count = fromIndex; while (iterator.hasNext() && count <= toIndex) { - TextElement element = iterator.next(); + iterator.next(); iterator.remove(); count++; } @@ -171,10 +171,10 @@ private boolean isValidIndex(int index, List elements) { * Returns the position of the last new line character or -1 if there is no eol in the specified list of TextElement */ int lastIndexOfEolWithoutGPT(List source) { - ListIterator listIterator = source.listIterator(source.size()); + ListIterator listIterator = source.listIterator(source.size()); int lastIndex = source.size() - 1; while (listIterator.hasPrevious()) { - TextElement elem = (TextElement) listIterator.previous(); + TextElement elem = listIterator.previous(); if (elem.isNewline()) { return lastIndex; } @@ -772,7 +772,7 @@ private int getIndexToNextTokenElement(TokenTextElement element, int nestedDiamo JavaToken nextToken = next.get(); Kind kind = Kind.valueOf(nextToken.getKind()); if (isDiamondOperator(kind)) { - if (kind.GT.equals(kind)) + if (Kind.GT.equals(kind)) nestedDiamondOperator--; else nestedDiamondOperator++; @@ -801,7 +801,7 @@ private int getIndexToNextTokenElementInArrayType(TokenTextElement element, int JavaToken nextToken = next.get(); Kind kind = Kind.valueOf(nextToken.getKind()); if (isBracket(kind)) { - if (kind.RBRACKET.equals(kind)) + if (Kind.RBRACKET.equals(kind)) arrayLevel--; } // manage the fact where the first token is not a diamond operator but a whitespace @@ -817,44 +817,14 @@ private int getIndexToNextTokenElementInArrayType(TokenTextElement element, int * Returns true if the token is possibly a diamond operator */ private boolean isDiamondOperator(Kind kind) { - return kind.GT.equals(kind) || kind.LT.equals(kind); + return Kind.GT.equals(kind) || Kind.LT.equals(kind); } /* * Returns true if the token is a bracket */ private boolean isBracket(Kind kind) { - return kind.LBRACKET.equals(kind) || kind.RBRACKET.equals(kind); - } - - private boolean openBraceWasOnSameLine() { - int index = originalIndex; - while (index >= 0 && !nodeText.getTextElement(index).isNewline()) { - if (nodeText.getTextElement(index).isToken(LBRACE)) { - return true; - } - index--; - } - return false; - } - - private boolean wasSpaceBetweenBraces() { - return nodeText.getTextElement(originalIndex).isToken(RBRACE) && doWeHaveLeftBraceFollowedBySpace(originalIndex - 1) && (diffIndex < 2 || !diffElements.get(diffIndex - 2).isRemoved()); - } - - private boolean doWeHaveLeftBraceFollowedBySpace(int index) { - index = rewindSpace(index); - return nodeText.getTextElement(index).isToken(LBRACE); - } - - private int rewindSpace(int index) { - if (index <= 0) { - return index; - } - if (nodeText.getTextElement(index).isWhiteSpace()) { - return rewindSpace(index - 1); - } - return index; + return Kind.LBRACKET.equals(kind) || Kind.RBRACKET.equals(kind); } private boolean nextIsRightBrace(int index) { @@ -989,10 +959,6 @@ private void applyAddedDiffElement(Added added) { diffIndex++; } - private String tokenDescription(int kind) { - return GeneratedJavaParserConstants.tokenImage[kind]; - } - /* * A list iterator which provides a method to know the current positioning */ From 4b30c8b12a8300eb894d8e99c94a509a6fd9c20f Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Wed, 30 Aug 2023 13:48:47 +0200 Subject: [PATCH 070/136] Remove useless index in ReshuffledDiffElementExtractor because this index is always equals to 0 --- .../ReshuffledDiffElementExtractor.java | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/ReshuffledDiffElementExtractor.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/ReshuffledDiffElementExtractor.java index 7ffa2afeb5..016ddfea23 100755 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/ReshuffledDiffElementExtractor.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/ReshuffledDiffElementExtractor.java @@ -41,8 +41,7 @@ private ReshuffledDiffElementExtractor(NodeText nodeText, Node node) { } public void extract(List diffElements) { - int originalIndex = 0; - ArrayIterator iterator = new ArrayIterator(diffElements); + ArrayIterator iterator = new ArrayIterator<>(diffElements); while (iterator.hasNext()) { DifferenceElement diffElement = iterator.next(); if (diffElement instanceof Reshuffled) { @@ -53,7 +52,7 @@ public void extract(List diffElements) { // This contains indexes from elementsFromNextOrder to indexes from elementsFromPreviousOrder Map correspondanceBetweenNextOrderAndPreviousOrder = getCorrespondanceBetweenNextOrderAndPreviousOrder(elementsFromPreviousOrder, elementsFromNextOrder); // We now find out which Node Text elements corresponds to the elements in the original CSM - List nodeTextIndexOfPreviousElements = findIndexOfCorrespondingNodeTextElement(elementsFromPreviousOrder.getElements(), nodeText, originalIndex, node); + List nodeTextIndexOfPreviousElements = findIndexOfCorrespondingNodeTextElement(elementsFromPreviousOrder.getElements(), nodeText, node); Map nodeTextIndexToPreviousCSMIndex = new HashMap<>(); for (int i = 0; i < nodeTextIndexOfPreviousElements.size(); i++) { int value = nodeTextIndexOfPreviousElements.get(i); @@ -97,7 +96,7 @@ public void extract(List diffElements) { // Remove the whole Reshuffled element iterator.remove(); if (lastNodeTextIndex != -1) { - for (int ntIndex = originalIndex; ntIndex <= lastNodeTextIndex; ntIndex++) { + for (int ntIndex = 0; ntIndex <= lastNodeTextIndex; ntIndex++) { if (nodeTextIndexToPreviousCSMIndex.containsKey(ntIndex)) { int indexOfOriginalCSMElement = nodeTextIndexToPreviousCSMIndex.get(ntIndex); if (elementsToAddBeforeGivenOriginalCSMElement.containsKey(indexOfOriginalCSMElement)) { @@ -164,14 +163,14 @@ private Map getCorrespondanceBetweenNextOrderAndPreviousOrder( return correspondanceBetweenNextOrderAndPreviousOrder; } - private List findIndexOfCorrespondingNodeTextElement(List elements, NodeText nodeText, int startIndex, Node node) { + private List findIndexOfCorrespondingNodeTextElement(List elements, NodeText nodeText, Node node) { List correspondingIndices = new ArrayList<>(); for (ListIterator csmElementListIterator = elements.listIterator(); csmElementListIterator.hasNext(); ) { int previousCsmElementIndex = csmElementListIterator.previousIndex(); CsmElement csmElement = csmElementListIterator.next(); int nextCsmElementIndex = csmElementListIterator.nextIndex(); Map potentialMatches = new EnumMap<>(MatchClassification.class); - for (int i = startIndex; i < nodeText.numberOfElements(); i++) { + for (int i = 0; i < nodeText.numberOfElements(); i++) { if (!correspondingIndices.contains(i)) { TextElement textElement = nodeText.getTextElement(i); boolean isCorresponding = isCorrespondingElement(textElement, csmElement, node); From 05f25973f00b897e770be92cdcb3263bf8813681 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Wed, 30 Aug 2023 14:06:21 +0200 Subject: [PATCH 071/136] Removes the notion of TokenContentCalculator appearing in the CsmToken class which is not used in JP and can be implemented by composition. This class was supposed to calculate a list of tokens from a node (namely the content of the node). --- .../concretesyntaxmodel/CsmElement.java | 16 ++++------ .../printer/concretesyntaxmodel/CsmToken.java | 30 +++++-------------- .../printer/lexicalpreservation/Added.java | 2 +- .../lexicalpreservation/Difference.java | 2 +- .../LexicalPreservingPrinter.java | 2 +- .../ReshuffledDiffElementExtractor.java | 30 ++++++++----------- 6 files changed, 29 insertions(+), 53 deletions(-) diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmElement.java b/javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmElement.java index a46ec56915..c6577ffa34 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmElement.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmElement.java @@ -20,18 +20,18 @@ */ package com.github.javaparser.printer.concretesyntaxmodel; +import static com.github.javaparser.TokenTypes.eolTokenKind; +import static com.github.javaparser.TokenTypes.spaceTokenKind; + +import java.util.Arrays; +import java.util.List; + import com.github.javaparser.GeneratedJavaParserConstants; import com.github.javaparser.ast.Node; import com.github.javaparser.ast.observer.ObservableProperty; import com.github.javaparser.printer.SourcePrinter; import com.github.javaparser.utils.LineSeparator; -import java.util.Arrays; -import java.util.List; - -import static com.github.javaparser.TokenTypes.eolTokenKind; -import static com.github.javaparser.TokenTypes.spaceTokenKind; - public interface CsmElement { void prettyPrint(Node node, SourcePrinter printer); @@ -72,10 +72,6 @@ static CsmElement token(int tokenType) { return new CsmToken(tokenType); } - static CsmElement token(int tokenType, CsmToken.TokenContentCalculator tokenContentCalculator) { - return new CsmToken(tokenType, tokenContentCalculator); - } - static CsmElement conditional(ObservableProperty property, CsmConditional.Condition condition, CsmElement thenElement) { return new CsmConditional(property, condition, thenElement); } diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmToken.java b/javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmToken.java index c60f7c6dba..e3eee08839 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmToken.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmToken.java @@ -20,36 +20,26 @@ */ package com.github.javaparser.printer.concretesyntaxmodel; +import static com.github.javaparser.TokenTypes.isEndOfLineToken; +import static com.github.javaparser.TokenTypes.isWhitespaceButNotEndOfLine; + import com.github.javaparser.GeneratedJavaParserConstants; import com.github.javaparser.TokenTypes; import com.github.javaparser.ast.Node; import com.github.javaparser.printer.SourcePrinter; import com.github.javaparser.utils.LineSeparator; -import static com.github.javaparser.TokenTypes.isEndOfLineToken; -import static com.github.javaparser.TokenTypes.isWhitespaceButNotEndOfLine; - public class CsmToken implements CsmElement { private final int tokenType; private String content; - private TokenContentCalculator tokenContentCalculator; - - public interface TokenContentCalculator { - - String calculate(Node node); - } - public int getTokenType() { return tokenType; } - public String getContent(Node node) { - if (tokenContentCalculator != null) { - return tokenContentCalculator.calculate(node); - } + public String getContent() { return content; } @@ -74,17 +64,12 @@ public CsmToken(int tokenType, String content) { this.content = content; } - public CsmToken(int tokenType, TokenContentCalculator tokenContentCalculator) { - this.tokenType = tokenType; - this.tokenContentCalculator = tokenContentCalculator; - } - @Override public void prettyPrint(Node node, SourcePrinter printer) { if (isEndOfLineToken(tokenType)) { printer.println(); } else { - printer.print(getContent(node)); + printer.print(getContent()); } } @@ -104,21 +89,20 @@ public boolean equals(Object o) { return false; if (content != null ? !content.equals(csmToken.content) : csmToken.content != null) return false; - return tokenContentCalculator != null ? tokenContentCalculator.equals(csmToken.tokenContentCalculator) : csmToken.tokenContentCalculator == null; + return true; } @Override public int hashCode() { int result = tokenType; result = 31 * result + (content != null ? content.hashCode() : 0); - result = 31 * result + (tokenContentCalculator != null ? tokenContentCalculator.hashCode() : 0); return result; } public boolean isWhiteSpace() { return TokenTypes.isWhitespace(tokenType); } - + public boolean isWhiteSpaceNotEol() { return isWhiteSpace() && !isNewLine(); } diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Added.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Added.java index 8cbe083c0c..572a9c2fee 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Added.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Added.java @@ -90,7 +90,7 @@ public TextElement toTextElement() { return new ChildTextElement(((LexicalDifferenceCalculator.CsmChild) element).getChild()); } if (element instanceof CsmToken) { - return new TokenTextElement(((CsmToken) element).getTokenType(), ((CsmToken) element).getContent(null)); + return new TokenTextElement(((CsmToken) element).getTokenType(), ((CsmToken) element).getContent()); } throw new UnsupportedOperationException(element.getClass().getSimpleName()); } diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java index 359c361a80..6d2a955c0e 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java @@ -346,7 +346,7 @@ private boolean isSpaceOrTabElement(NodeText nodeText, int i) { * to the difference (adding and removing the elements provided). */ void apply() { - ReshuffledDiffElementExtractor.of(nodeText, node).extract(diffElements); + ReshuffledDiffElementExtractor.of(nodeText).extract(diffElements); Map removedGroups = combineRemovedElementsToRemovedGroups(); do { boolean isLeftOverDiffElement = applyLeftOverDiffElements(); diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinter.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinter.java index 2a78af3407..d1084c9ec0 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinter.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinter.java @@ -603,7 +603,7 @@ private static NodeText interpret(Node node, CsmElement csm, NodeText nodeText) nodeText.addChild(((LexicalDifferenceCalculator.CsmChild) element).getChild()); } else if (element instanceof CsmToken) { CsmToken csmToken = (CsmToken) element; - nodeText.addToken(csmToken.getTokenType(), csmToken.getContent(node)); + nodeText.addToken(csmToken.getTokenType(), csmToken.getContent()); if (csmToken.isNewLine()) { pendingIndentation = true; } diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/ReshuffledDiffElementExtractor.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/ReshuffledDiffElementExtractor.java index 016ddfea23..8a3b36b789 100755 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/ReshuffledDiffElementExtractor.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/ReshuffledDiffElementExtractor.java @@ -2,7 +2,6 @@ import java.util.*; -import com.github.javaparser.ast.Node; import com.github.javaparser.printer.concretesyntaxmodel.CsmElement; import com.github.javaparser.printer.concretesyntaxmodel.CsmIndent; import com.github.javaparser.printer.concretesyntaxmodel.CsmMix; @@ -14,8 +13,6 @@ public class ReshuffledDiffElementExtractor { private final NodeText nodeText; - private final Node node; - private enum MatchClassification { ALL(1), PREVIOUS_AND_SAME(2), NEXT_AND_SAME(3), SAME_ONLY(4), ALMOST(5); @@ -31,13 +28,12 @@ int getPriority() { } } - static ReshuffledDiffElementExtractor of(NodeText nodeText, Node node) { - return new ReshuffledDiffElementExtractor(nodeText, node); + static ReshuffledDiffElementExtractor of(NodeText nodeText) { + return new ReshuffledDiffElementExtractor(nodeText); } - private ReshuffledDiffElementExtractor(NodeText nodeText, Node node) { + private ReshuffledDiffElementExtractor(NodeText nodeText) { this.nodeText = nodeText; - this.node = node; } public void extract(List diffElements) { @@ -52,7 +48,7 @@ public void extract(List diffElements) { // This contains indexes from elementsFromNextOrder to indexes from elementsFromPreviousOrder Map correspondanceBetweenNextOrderAndPreviousOrder = getCorrespondanceBetweenNextOrderAndPreviousOrder(elementsFromPreviousOrder, elementsFromNextOrder); // We now find out which Node Text elements corresponds to the elements in the original CSM - List nodeTextIndexOfPreviousElements = findIndexOfCorrespondingNodeTextElement(elementsFromPreviousOrder.getElements(), nodeText, node); + List nodeTextIndexOfPreviousElements = findIndexOfCorrespondingNodeTextElement(elementsFromPreviousOrder.getElements(), nodeText); Map nodeTextIndexToPreviousCSMIndex = new HashMap<>(); for (int i = 0; i < nodeTextIndexOfPreviousElements.size(); i++) { int value = nodeTextIndexOfPreviousElements.get(i); @@ -163,7 +159,7 @@ private Map getCorrespondanceBetweenNextOrderAndPreviousOrder( return correspondanceBetweenNextOrderAndPreviousOrder; } - private List findIndexOfCorrespondingNodeTextElement(List elements, NodeText nodeText, Node node) { + private List findIndexOfCorrespondingNodeTextElement(List elements, NodeText nodeText) { List correspondingIndices = new ArrayList<>(); for (ListIterator csmElementListIterator = elements.listIterator(); csmElementListIterator.hasNext(); ) { int previousCsmElementIndex = csmElementListIterator.previousIndex(); @@ -173,17 +169,17 @@ private List findIndexOfCorrespondingNodeTextElement(List e for (int i = 0; i < nodeText.numberOfElements(); i++) { if (!correspondingIndices.contains(i)) { TextElement textElement = nodeText.getTextElement(i); - boolean isCorresponding = isCorrespondingElement(textElement, csmElement, node); + boolean isCorresponding = isCorrespondingElement(textElement, csmElement); if (isCorresponding) { boolean hasSamePreviousElement = false; if (i > 0 && previousCsmElementIndex > -1) { TextElement previousTextElement = nodeText.getTextElement(i - 1); - hasSamePreviousElement = isCorrespondingElement(previousTextElement, elements.get(previousCsmElementIndex), node); + hasSamePreviousElement = isCorrespondingElement(previousTextElement, elements.get(previousCsmElementIndex)); } boolean hasSameNextElement = false; if (i < nodeText.numberOfElements() - 1 && nextCsmElementIndex < elements.size()) { TextElement nextTextElement = nodeText.getTextElement(i + 1); - hasSameNextElement = isCorrespondingElement(nextTextElement, elements.get(nextCsmElementIndex), node); + hasSameNextElement = isCorrespondingElement(nextTextElement, elements.get(nextCsmElementIndex)); } if (hasSamePreviousElement && hasSameNextElement) { potentialMatches.putIfAbsent(MatchClassification.ALL, i); @@ -194,7 +190,7 @@ private List findIndexOfCorrespondingNodeTextElement(List e } else { potentialMatches.putIfAbsent(MatchClassification.SAME_ONLY, i); } - } else if (isAlmostCorrespondingElement(textElement, csmElement, node)) { + } else if (isAlmostCorrespondingElement(textElement, csmElement)) { potentialMatches.putIfAbsent(MatchClassification.ALMOST, i); } } @@ -210,12 +206,12 @@ private List findIndexOfCorrespondingNodeTextElement(List e return correspondingIndices; } - private boolean isCorrespondingElement(TextElement textElement, CsmElement csmElement, Node node) { + private boolean isCorrespondingElement(TextElement textElement, CsmElement csmElement) { if (csmElement instanceof CsmToken) { CsmToken csmToken = (CsmToken) csmElement; if (textElement instanceof TokenTextElement) { TokenTextElement tokenTextElement = (TokenTextElement) textElement; - return tokenTextElement.getTokenKind() == csmToken.getTokenType() && tokenTextElement.getText().equals(csmToken.getContent(node)); + return tokenTextElement.getTokenKind() == csmToken.getTokenType() && tokenTextElement.getText().equals(csmToken.getContent()); } } else if (csmElement instanceof CsmChild) { CsmChild csmChild = (CsmChild) csmElement; @@ -235,8 +231,8 @@ private boolean isCorrespondingElement(TextElement textElement, CsmElement csmEl return false; } - private boolean isAlmostCorrespondingElement(TextElement textElement, CsmElement csmElement, Node node) { - if (isCorrespondingElement(textElement, csmElement, node)) { + private boolean isAlmostCorrespondingElement(TextElement textElement, CsmElement csmElement) { + if (isCorrespondingElement(textElement, csmElement)) { return false; } return textElement.isWhiteSpace() && csmElement instanceof CsmToken && ((CsmToken) csmElement).isWhiteSpace(); From 2c0bdef25f0de2330d3efe67450a3787afe705e7 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Wed, 30 Aug 2023 15:35:15 +0200 Subject: [PATCH 072/136] Refactor how to check if a TextElement matches the contents of a CsmElement --- .../concretesyntaxmodel/CsmElement.java | 8 ++++ .../concretesyntaxmodel/CsmIndent.java | 11 ++++++ .../printer/concretesyntaxmodel/CsmToken.java | 12 ++++++ .../lexicalpreservation/ChildTextElement.java | 15 ++++---- .../LexicalDifferenceCalculator.java | 19 +++++++--- .../ReshuffledDiffElementExtractor.java | 38 +++---------------- .../lexicalpreservation/TokenTextElement.java | 12 +++--- 7 files changed, 65 insertions(+), 50 deletions(-) diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmElement.java b/javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmElement.java index c6577ffa34..43cfaa8a34 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmElement.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmElement.java @@ -30,6 +30,7 @@ import com.github.javaparser.ast.Node; import com.github.javaparser.ast.observer.ObservableProperty; import com.github.javaparser.printer.SourcePrinter; +import com.github.javaparser.printer.lexicalpreservation.TextElement; import com.github.javaparser.utils.LineSeparator; public interface CsmElement { @@ -148,4 +149,11 @@ static CsmElement unindent() { static CsmElement block(CsmElement content) { return sequence(token(GeneratedJavaParserConstants.LBRACE), indent(), content, unindent(), token(GeneratedJavaParserConstants.RBRACE)); } + + /* + * Verifies if the content of the {@code CsmElement} is the same as the provided {@code TextElement} + */ + default boolean isCorrespondingElement(TextElement textElement) { + return false; + } } diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmIndent.java b/javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmIndent.java index 761ee1e7df..5397a0cf15 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmIndent.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmIndent.java @@ -22,6 +22,8 @@ import com.github.javaparser.ast.Node; import com.github.javaparser.printer.SourcePrinter; +import com.github.javaparser.printer.lexicalpreservation.TextElement; +import com.github.javaparser.printer.lexicalpreservation.TokenTextElement; public class CsmIndent implements CsmElement { @@ -30,6 +32,15 @@ public void prettyPrint(Node node, SourcePrinter printer) { printer.indent(); } + /* + * Verifies if the content of the {@code CsmElement} is the same as the provided {@code TextElement} + */ + @Override + public boolean isCorrespondingElement(TextElement textElement) { + return (textElement instanceof TokenTextElement) + && ((TokenTextElement)textElement).isSpaceOrTab(); + } + @Override public int hashCode() { return 1; diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmToken.java b/javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmToken.java index e3eee08839..f676360bda 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmToken.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmToken.java @@ -27,6 +27,8 @@ import com.github.javaparser.TokenTypes; import com.github.javaparser.ast.Node; import com.github.javaparser.printer.SourcePrinter; +import com.github.javaparser.printer.lexicalpreservation.TextElement; +import com.github.javaparser.printer.lexicalpreservation.TokenTextElement; import com.github.javaparser.utils.LineSeparator; public class CsmToken implements CsmElement { @@ -110,4 +112,14 @@ public boolean isWhiteSpaceNotEol() { public boolean isNewLine() { return TokenTypes.isEndOfLineToken(tokenType); } + + /* + * Verifies if the content of the {@code CsmElement} is the same as the provided {@code TextElement} + */ + @Override + public boolean isCorrespondingElement(TextElement textElement) { + return (textElement instanceof TokenTextElement) + && ((TokenTextElement)textElement).getTokenKind() == getTokenType() + && ((TokenTextElement)textElement).getText().equals(getContent()); + } } diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/ChildTextElement.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/ChildTextElement.java index 390a0a9131..caf84d9850 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/ChildTextElement.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/ChildTextElement.java @@ -20,16 +20,16 @@ */ package com.github.javaparser.printer.lexicalpreservation; +import java.util.Optional; + import com.github.javaparser.Range; import com.github.javaparser.ast.Node; import com.github.javaparser.ast.comments.Comment; -import java.util.Optional; - /** * Represent the position of a child node in the NodeText of its parent. */ -class ChildTextElement extends TextElement { +public class ChildTextElement extends TextElement { private final Node child; @@ -37,21 +37,22 @@ class ChildTextElement extends TextElement { this.child = child; } - String expand() { + @Override + public String expand() { return LexicalPreservingPrinter.print(child); } - Node getChild() { + public Node getChild() { return child; } @Override - boolean isToken(int tokenKind) { + public boolean isToken(int tokenKind) { return false; } @Override - boolean isNode(Node node) { + public boolean isNode(Node node) { return node == child; } diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalDifferenceCalculator.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalDifferenceCalculator.java index cbca1d4822..7e08f9597c 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalDifferenceCalculator.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalDifferenceCalculator.java @@ -20,6 +20,8 @@ */ package com.github.javaparser.printer.lexicalpreservation; +import java.util.*; + import com.github.javaparser.GeneratedJavaParserConstants; import com.github.javaparser.ast.Modifier; import com.github.javaparser.ast.Node; @@ -37,8 +39,6 @@ import com.github.javaparser.printer.lexicalpreservation.changes.*; import com.github.javaparser.utils.LineSeparator; -import java.util.*; - class LexicalDifferenceCalculator { /** @@ -71,7 +71,7 @@ void removeIndentationElements() { } } - static class CsmChild implements CsmElement { + public static class CsmChild implements CsmElement { private final Node child; @@ -88,6 +88,15 @@ public void prettyPrint(Node node, SourcePrinter printer) { throw new UnsupportedOperationException(); } + /* + * Verifies if the content of the {@code CsmElement} is the same as the provided {@code TextElement} + */ + @Override + public boolean isCorrespondingElement(TextElement textElement) { + return (textElement instanceof ChildTextElement) + && ((ChildTextElement)textElement).getChild() == getChild(); + } + @Override public String toString() { return "child(" + child.getClass().getSimpleName() + ")"; @@ -141,7 +150,7 @@ private void replaceEolTokens(List differenceElements, LineSe } /* - * Returns a new line token + * Returns a new line token */ private CsmElement getNewLineToken(LineSeparator lineSeparator) { return CsmElement.newline(lineSeparator); @@ -190,7 +199,7 @@ private void calculatedSyntaxModelForNode(CsmElement csm, Node node, List getCorrespondanceBetweenNextOrderAndPreviousOrder( private List findIndexOfCorrespondingNodeTextElement(List elements, NodeText nodeText) { List correspondingIndices = new ArrayList<>(); - for (ListIterator csmElementListIterator = elements.listIterator(); csmElementListIterator.hasNext(); ) { + ListIterator csmElementListIterator = elements.listIterator(); + while ( csmElementListIterator.hasNext() ) { int previousCsmElementIndex = csmElementListIterator.previousIndex(); CsmElement csmElement = csmElementListIterator.next(); int nextCsmElementIndex = csmElementListIterator.nextIndex(); @@ -169,17 +168,17 @@ private List findIndexOfCorrespondingNodeTextElement(List e for (int i = 0; i < nodeText.numberOfElements(); i++) { if (!correspondingIndices.contains(i)) { TextElement textElement = nodeText.getTextElement(i); - boolean isCorresponding = isCorrespondingElement(textElement, csmElement); + boolean isCorresponding = csmElement.isCorrespondingElement(textElement); if (isCorresponding) { boolean hasSamePreviousElement = false; if (i > 0 && previousCsmElementIndex > -1) { TextElement previousTextElement = nodeText.getTextElement(i - 1); - hasSamePreviousElement = isCorrespondingElement(previousTextElement, elements.get(previousCsmElementIndex)); + hasSamePreviousElement = elements.get(previousCsmElementIndex).isCorrespondingElement(previousTextElement); } boolean hasSameNextElement = false; if (i < nodeText.numberOfElements() - 1 && nextCsmElementIndex < elements.size()) { TextElement nextTextElement = nodeText.getTextElement(i + 1); - hasSameNextElement = isCorrespondingElement(nextTextElement, elements.get(nextCsmElementIndex)); + hasSameNextElement = elements.get(nextCsmElementIndex).isCorrespondingElement(nextTextElement); } if (hasSamePreviousElement && hasSameNextElement) { potentialMatches.putIfAbsent(MatchClassification.ALL, i); @@ -206,33 +205,8 @@ private List findIndexOfCorrespondingNodeTextElement(List e return correspondingIndices; } - private boolean isCorrespondingElement(TextElement textElement, CsmElement csmElement) { - if (csmElement instanceof CsmToken) { - CsmToken csmToken = (CsmToken) csmElement; - if (textElement instanceof TokenTextElement) { - TokenTextElement tokenTextElement = (TokenTextElement) textElement; - return tokenTextElement.getTokenKind() == csmToken.getTokenType() && tokenTextElement.getText().equals(csmToken.getContent()); - } - } else if (csmElement instanceof CsmChild) { - CsmChild csmChild = (CsmChild) csmElement; - if (textElement instanceof ChildTextElement) { - ChildTextElement childTextElement = (ChildTextElement) textElement; - return childTextElement.getChild() == csmChild.getChild(); - } - } else if (csmElement instanceof CsmIndent) { - CsmIndent csmIndent = (CsmIndent) csmElement; - if (textElement instanceof TokenTextElement) { - TokenTextElement tokenTextElement = (TokenTextElement) textElement; - return tokenTextElement.isSpaceOrTab(); - } - } else { - throw new UnsupportedOperationException(); - } - return false; - } - private boolean isAlmostCorrespondingElement(TextElement textElement, CsmElement csmElement) { - if (isCorrespondingElement(textElement, csmElement)) { + if (csmElement.isCorrespondingElement(textElement)) { return false; } return textElement.isWhiteSpace() && csmElement instanceof CsmToken && ((CsmToken) csmElement).isWhiteSpace(); diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/TokenTextElement.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/TokenTextElement.java index 9f36952507..9533c62e59 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/TokenTextElement.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/TokenTextElement.java @@ -20,14 +20,14 @@ */ package com.github.javaparser.printer.lexicalpreservation; +import java.util.Optional; + import com.github.javaparser.JavaToken; import com.github.javaparser.JavaToken.Kind; import com.github.javaparser.Range; import com.github.javaparser.ast.Node; -import java.util.Optional; - -class TokenTextElement extends TextElement { +public class TokenTextElement extends TextElement { private final JavaToken token; @@ -44,16 +44,16 @@ class TokenTextElement extends TextElement { } @Override - String expand() { + public String expand() { return token.getText(); } // Visible for testing - String getText() { + public String getText() { return token.getText(); } - int getTokenKind() { + public int getTokenKind() { return token.getKind(); } From dcfd52b307ad2f561e1b9eab668b3f11078352d6 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Wed, 30 Aug 2023 22:19:37 +0200 Subject: [PATCH 073/136] Simplifies the extraction of elements of type Reshuffled using iterators --- .../PeekingIteratorTest.java | 126 ++++++++++ .../LookaheadIterator.java | 30 +++ .../lexicalpreservation/PeekingIterator.java | 223 ++++++++++++++++++ .../ReshuffledDiffElementExtractor.java | 40 ++-- 4 files changed, 401 insertions(+), 18 deletions(-) create mode 100755 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/PeekingIteratorTest.java create mode 100755 javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LookaheadIterator.java create mode 100755 javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/PeekingIterator.java diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/PeekingIteratorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/PeekingIteratorTest.java new file mode 100755 index 0000000000..3e77c97a95 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/PeekingIteratorTest.java @@ -0,0 +1,126 @@ +package com.github.javaparser.printer.lexicalpreservation; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.NoSuchElementException; + +import org.junit.jupiter.api.*; + +class PeekingIteratorTest { + + private static final List EMPTY_LIST = new ArrayList(); + + private static List NON_EMPTY_LIST ; + + private PeekingIterator peekingIterator; + + @BeforeAll + static void setUpBeforeClass() throws Exception { + } + + @AfterAll + static void tearDownAfterClass() throws Exception { + } + + @BeforeEach + void setUp() throws Exception { + NON_EMPTY_LIST = Arrays.asList("A", "B", "C"); + } + + @AfterEach + void tearDown() throws Exception { + } + + @Test + void testHasNext() { + peekingIterator = new PeekingIterator(EMPTY_LIST.listIterator()); + assertFalse(peekingIterator.hasNext()); + peekingIterator = new PeekingIterator(NON_EMPTY_LIST.listIterator()); + assertTrue(peekingIterator.hasNext()); + } + + @Test + void testPeek() { + peekingIterator = new PeekingIterator(EMPTY_LIST.listIterator()); + assertEquals(null, peekingIterator.peek()); + peekingIterator = new PeekingIterator(NON_EMPTY_LIST.listIterator()); + assertEquals("A", peekingIterator.peek()); + assertEquals("A", peekingIterator.next()); + } + + @Test + void testElement() { + peekingIterator = new PeekingIterator(EMPTY_LIST.listIterator()); + assertEquals(null, peekingIterator.peek()); + peekingIterator = new PeekingIterator(NON_EMPTY_LIST.listIterator()); + assertEquals("A", peekingIterator.peek()); + assertEquals(1, peekingIterator.nextIndex()); + } + + @Test + void testNext() { + peekingIterator = new PeekingIterator(EMPTY_LIST.listIterator()); + assertThrows(NoSuchElementException.class, () -> peekingIterator.next()); + peekingIterator = new PeekingIterator(NON_EMPTY_LIST.listIterator()); + assertEquals("A", peekingIterator.next()); + } + + @Test + void testRemove() { + peekingIterator = new PeekingIterator(EMPTY_LIST.listIterator()); + assertThrows(IllegalStateException.class, () -> peekingIterator.remove()); + peekingIterator = new PeekingIterator(NON_EMPTY_LIST.listIterator()); + assertThrows(IllegalStateException.class, () -> peekingIterator.remove()); + String result = peekingIterator.next(); + assertThrows(UnsupportedOperationException.class, () -> peekingIterator.remove()); + } + + @Test + void testHasPrevious() { + peekingIterator = new PeekingIterator(EMPTY_LIST.listIterator()); + assertFalse(peekingIterator.hasPrevious()); + peekingIterator = new PeekingIterator(NON_EMPTY_LIST.listIterator()); + assertFalse(peekingIterator.hasPrevious()); + String result = peekingIterator.next(); + assertTrue(peekingIterator.hasPrevious()); + } + + @Test + void testPrevious() { + peekingIterator = new PeekingIterator(EMPTY_LIST.listIterator()); + assertThrows(NoSuchElementException.class, () -> peekingIterator.previous()); + peekingIterator = new PeekingIterator(NON_EMPTY_LIST.listIterator()); + assertThrows(NoSuchElementException.class, () -> peekingIterator.previous()); + } + + @Test + void testNextIndex() { + peekingIterator = new PeekingIterator(EMPTY_LIST.listIterator()); + assertEquals(0, peekingIterator.nextIndex()); + peekingIterator = new PeekingIterator(NON_EMPTY_LIST.listIterator()); + assertEquals(0, peekingIterator.nextIndex()); + } + + @Test + void testPreviousIndex() { + peekingIterator = new PeekingIterator(EMPTY_LIST.listIterator()); + assertEquals(-1, peekingIterator.previousIndex()); + peekingIterator = new PeekingIterator(NON_EMPTY_LIST.listIterator()); + assertEquals(-1, peekingIterator.previousIndex()); + } + + @Test + void testSet() { + peekingIterator = new PeekingIterator(EMPTY_LIST.listIterator()); + assertThrows(IllegalStateException.class, () -> peekingIterator.set("D")); + peekingIterator = new PeekingIterator(NON_EMPTY_LIST.listIterator()); + assertThrows(IllegalStateException.class, () -> peekingIterator.set("D")); + peekingIterator.next(); + peekingIterator.set("D"); + assertEquals(3, NON_EMPTY_LIST.size()); + } + +} diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LookaheadIterator.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LookaheadIterator.java new file mode 100755 index 0000000000..9847fe9268 --- /dev/null +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LookaheadIterator.java @@ -0,0 +1,30 @@ +package com.github.javaparser.printer.lexicalpreservation; + +import java.util.NoSuchElementException; + +public interface LookaheadIterator { + + /** + * Returns the next element in iteration without advancing the underlying iterator. + * If the iterator is already exhausted, null will be returned. + *

+ * Note: this method does not throw a {@link NoSuchElementException} if the iterator + * is already exhausted. If you want such a behavior, use {@link #element()} instead. + *

+ * The rationale behind this is to follow the {@link java.util.Queue} interface + * which uses the same terminology. + * + * @return the next element from the iterator + */ + public E peek(); + + /** + * Returns the next element in iteration without advancing the underlying iterator. + * If the iterator is already exhausted, null will be returned. + * + * @return the next element from the iterator + * @throws NoSuchElementException if the iterator is already exhausted according to {@link #hasNext()} + */ + public E element(); + +} diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/PeekingIterator.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/PeekingIterator.java new file mode 100755 index 0000000000..98fd0f5ad8 --- /dev/null +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/PeekingIterator.java @@ -0,0 +1,223 @@ +/* + * Copyright (C) 2011, 2013-2023 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ +package com.github.javaparser.printer.lexicalpreservation; + +import java.util.List; +import java.util.ListIterator; +import java.util.NoSuchElementException; +import java.util.Objects; + +/** + * Decorates an iterator to support one-element lookahead while iterating. + *

+ * The decorator supports the removal operation, but an {@link IllegalStateException} + * will be thrown if {@link #remove()}, {@link #add()}, {@link #set()}} is called directly after a call to + * {@link #peek()} or {@link #element()}. + * + * @param the type of elements returned by this iterator. + * @since 4.0 + */ +public class PeekingIterator implements ListIterator, LookaheadIterator { + + /** The iterator being decorated. */ + private final ListIterator iterator; + + /** Indicates that the decorated iterator is exhausted. */ + private boolean exhausted; + + /** Indicates if the lookahead slot is filled. */ + private boolean slotFilled; + + /** The current slot for lookahead. */ + private E slot; + + /** + * Decorates the specified iterator to support one-element lookahead. + *

+ * If the iterator is already a {@link PeekingIterator} it is returned directly. + * + * @param the element type + * @param iterator the iterator to decorate + * @return a new peeking iterator + * @throws NullPointerException if the iterator is null + */ + public PeekingIterator peekingIterator(final ListIterator iterator) { + Objects.requireNonNull(iterator, "iterator"); + if (iterator instanceof PeekingIterator) { + final PeekingIterator it = (PeekingIterator) iterator; + return it; + } + return new PeekingIterator<>(iterator); + } + + + /** + * Constructor. + * + * @param iterator the iterator to decorate + */ + public PeekingIterator(final ListIterator iterator) { + this.iterator = iterator; + } + + /** + * Constructor. + * + * @param list the provider of the iterator to decorate + */ + public PeekingIterator(final List list) { + this.iterator = list.listIterator(); + } + + private void fill() { + if (exhausted || slotFilled) { + return; + } + if (iterator.hasNext()) { + slot = iterator.next(); + slotFilled = true; + } else { + exhausted = true; + slot = null; + slotFilled = false; + } + } + + @Override + public boolean hasNext() { + if (exhausted) { + return false; + } + return slotFilled || iterator.hasNext(); + } + + /** + * Returns the next element in iteration without advancing the underlying iterator. + * If the iterator is already exhausted, null will be returned. + *

+ * Note: this method does not throw a {@link NoSuchElementException} if the iterator + * is already exhausted. If you want such a behavior, use {@link #element()} instead. + *

+ * The rationale behind this is to follow the {@link java.util.Queue} interface + * which uses the same terminology. + * + * @return the next element from the iterator + */ + @Override + public E peek() { + fill(); + return exhausted ? null : slot; + } + + /** + * Returns the next element in iteration without advancing the underlying iterator. + * If the iterator is already exhausted, null will be returned. + * + * @return the next element from the iterator + * @throws NoSuchElementException if the iterator is already exhausted according to {@link #hasNext()} + */ + @Override + public E element() { + fill(); + if (exhausted) { + throw new NoSuchElementException(); + } + return slot; + } + + @Override + public E next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + final E x = slotFilled ? slot : iterator.next(); + // reset the lookahead slot + slot = null; + slotFilled = false; + return x; + } + + /** + * {@inheritDoc} + * + * @throws IllegalStateException if {@link #peek()} or {@link #element()} has been called + * prior to the call to {@link #remove()} + */ + @Override + public void remove() { + if (slotFilled) { + throw new IllegalStateException("peek() or element() called before remove()"); + } + iterator.remove(); + } + + + @Override + public boolean hasPrevious() { + return iterator.hasPrevious(); + } + + + @Override + public E previous() { + return iterator.previous(); + } + + + @Override + public int nextIndex() { + return iterator.nextIndex(); + } + + /* + * Returns the index of the element that would be returned by the last call to next. + * Returns list size - 1 if the listiterator is at the end of the list. + * Returns -1 if the listiterator is at the beginning of the list. + */ + public int currentIndex() { + if (!hasPrevious()) return previousIndex(); + return nextIndex() - 1; + } + + + @Override + public int previousIndex() { + return iterator.previousIndex(); + } + + + @Override + public void set(E e) { + if (slotFilled) { + throw new IllegalStateException("peek() or element() called before set()"); + } + iterator.set(e); + } + + + @Override + public void add(E e) { + if (slotFilled) { + throw new IllegalStateException("peek() or element() called before add()"); + } + iterator.add(e); + } + +} diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/ReshuffledDiffElementExtractor.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/ReshuffledDiffElementExtractor.java index cc3ad5b11d..041ad5ef7e 100755 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/ReshuffledDiffElementExtractor.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/ReshuffledDiffElementExtractor.java @@ -47,11 +47,12 @@ public void extract(List diffElements) { Map correspondanceBetweenNextOrderAndPreviousOrder = getCorrespondanceBetweenNextOrderAndPreviousOrder(elementsFromPreviousOrder, elementsFromNextOrder); // We now find out which Node Text elements corresponds to the elements in the original CSM List nodeTextIndexOfPreviousElements = findIndexOfCorrespondingNodeTextElement(elementsFromPreviousOrder.getElements(), nodeText); + PeekingIterator nodeTextIndexOfPreviousElementsIterator = new PeekingIterator<>(nodeTextIndexOfPreviousElements); Map nodeTextIndexToPreviousCSMIndex = new HashMap<>(); - for (int i = 0; i < nodeTextIndexOfPreviousElements.size(); i++) { - int value = nodeTextIndexOfPreviousElements.get(i); + while (nodeTextIndexOfPreviousElementsIterator.hasNext()) { + int value = nodeTextIndexOfPreviousElementsIterator.next(); if (value != -1) { - nodeTextIndexToPreviousCSMIndex.put(value, i); + nodeTextIndexToPreviousCSMIndex.put(value, nodeTextIndexOfPreviousElementsIterator.currentIndex()); } } int lastNodeTextIndex = nodeTextIndexOfPreviousElements.stream().max(Integer::compareTo).orElse(-1); @@ -159,38 +160,41 @@ private Map getCorrespondanceBetweenNextOrderAndPreviousOrder( private List findIndexOfCorrespondingNodeTextElement(List elements, NodeText nodeText) { List correspondingIndices = new ArrayList<>(); - ListIterator csmElementListIterator = elements.listIterator(); + PeekingIterator csmElementListIterator = new PeekingIterator<>(elements); while ( csmElementListIterator.hasNext() ) { + boolean isFirstIterationOnCsmElements = !csmElementListIterator.hasPrevious(); int previousCsmElementIndex = csmElementListIterator.previousIndex(); CsmElement csmElement = csmElementListIterator.next(); - int nextCsmElementIndex = csmElementListIterator.nextIndex(); Map potentialMatches = new EnumMap<>(MatchClassification.class); - for (int i = 0; i < nodeText.numberOfElements(); i++) { - if (!correspondingIndices.contains(i)) { - TextElement textElement = nodeText.getTextElement(i); + PeekingIterator nodeTextListIterator = new PeekingIterator<>(nodeText.getElements()); + while (nodeTextListIterator.hasNext()) { + boolean isFirstIterationOnNodeTextElements = !nodeTextListIterator.hasPrevious(); + TextElement textElement = nodeTextListIterator.next(); + int currentTextElementIndex = nodeTextListIterator.currentIndex(); + if (!correspondingIndices.contains(currentTextElementIndex)) { boolean isCorresponding = csmElement.isCorrespondingElement(textElement); if (isCorresponding) { boolean hasSamePreviousElement = false; - if (i > 0 && previousCsmElementIndex > -1) { - TextElement previousTextElement = nodeText.getTextElement(i - 1); + if (!isFirstIterationOnNodeTextElements && !isFirstIterationOnCsmElements) { + TextElement previousTextElement = nodeText.getTextElement(currentTextElementIndex - 1); hasSamePreviousElement = elements.get(previousCsmElementIndex).isCorrespondingElement(previousTextElement); } boolean hasSameNextElement = false; - if (i < nodeText.numberOfElements() - 1 && nextCsmElementIndex < elements.size()) { - TextElement nextTextElement = nodeText.getTextElement(i + 1); - hasSameNextElement = elements.get(nextCsmElementIndex).isCorrespondingElement(nextTextElement); + if (csmElementListIterator.hasNext()) { + TextElement nextTextElement = nodeTextListIterator.peek(); + hasSameNextElement = elements.get(csmElementListIterator.nextIndex()).isCorrespondingElement(nextTextElement); } if (hasSamePreviousElement && hasSameNextElement) { - potentialMatches.putIfAbsent(MatchClassification.ALL, i); + potentialMatches.putIfAbsent(MatchClassification.ALL, currentTextElementIndex); } else if (hasSamePreviousElement) { - potentialMatches.putIfAbsent(MatchClassification.PREVIOUS_AND_SAME, i); + potentialMatches.putIfAbsent(MatchClassification.PREVIOUS_AND_SAME, currentTextElementIndex); } else if (hasSameNextElement) { - potentialMatches.putIfAbsent(MatchClassification.NEXT_AND_SAME, i); + potentialMatches.putIfAbsent(MatchClassification.NEXT_AND_SAME, currentTextElementIndex); } else { - potentialMatches.putIfAbsent(MatchClassification.SAME_ONLY, i); + potentialMatches.putIfAbsent(MatchClassification.SAME_ONLY, currentTextElementIndex); } } else if (isAlmostCorrespondingElement(textElement, csmElement)) { - potentialMatches.putIfAbsent(MatchClassification.ALMOST, i); + potentialMatches.putIfAbsent(MatchClassification.ALMOST, currentTextElementIndex); } } } From 3a1cc19afcc5d31fc12ea762e71acf877a7e8c3b Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Thu, 31 Aug 2023 08:40:58 +0200 Subject: [PATCH 074/136] Fix: issue 4133 Top-level class containerType() throws an exception instead of Optional.empty() --- .../declarations/JavaParserTypeAdapter.java | 2 ++ .../JavaParserClassDeclarationTest.java | 26 ++++++++++++++++--- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserTypeAdapter.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserTypeAdapter.java index 4480ae19eb..a3d4c48083 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserTypeAdapter.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserTypeAdapter.java @@ -24,6 +24,7 @@ import java.util.*; import java.util.stream.Collectors; +import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.Node; import com.github.javaparser.ast.NodeList; import com.github.javaparser.ast.body.*; @@ -157,6 +158,7 @@ public SymbolReference solveType(String name) { public Optional containerType() { return wrappedNode .getParentNode() + .filter(parentNode -> !(parentNode instanceof CompilationUnit)) .map(node -> node.getSymbolResolver().toTypeDeclaration(node)); } diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserClassDeclarationTest.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserClassDeclarationTest.java index 08fb1d0235..3db8f9a9af 100644 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserClassDeclarationTest.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserClassDeclarationTest.java @@ -34,6 +34,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import com.github.javaparser.JavaParserAdapter; import com.github.javaparser.ParserConfiguration; import com.github.javaparser.StaticJavaParser; import com.github.javaparser.ast.AccessSpecifier; @@ -49,10 +50,10 @@ import com.github.javaparser.resolution.types.ResolvedPrimitiveType; import com.github.javaparser.resolution.types.ResolvedReferenceType; import com.github.javaparser.resolution.types.ResolvedType; -import com.github.javaparser.symbolsolver.AbstractSymbolResolutionTest; import com.github.javaparser.symbolsolver.JavaSymbolSolver; import com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade; import com.github.javaparser.symbolsolver.reflectionmodel.ReflectionFactory; +import com.github.javaparser.symbolsolver.resolution.AbstractResolutionTest; import com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver; import com.github.javaparser.symbolsolver.resolution.typesolvers.JavaParserTypeSolver; import com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver; @@ -61,7 +62,7 @@ import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; -class JavaParserClassDeclarationTest extends AbstractSymbolResolutionTest { +class JavaParserClassDeclarationTest extends AbstractResolutionTest { private TypeSolver typeSolver; private TypeSolver typeSolverNewCode; @@ -957,7 +958,26 @@ void testHasInheritedAnnotation() throws IOException { // Set internalTypes() - // Optional containerType() + // issue #4133 + @Test + void testContainerType() { + String code = + "public class Foo {\n" + + " public static class Bar {\n" + + " public static class Baz {\n" + + " }\n" + + " }\n" + + "}\n"; + + JavaParserAdapter parser = JavaParserAdapter.of(createParserWithResolver(defaultTypeSolver())); + CompilationUnit cu = parser.parse(code); + + List declarations = cu.findAll(ClassOrInterfaceDeclaration.class); + // top level type + assertTrue(declarations.get(0).resolve().asReferenceType().containerType().isEmpty()); + assertEquals("Foo", declarations.get(1).resolve().asReferenceType().containerType().get().getQualifiedName()); + assertEquals("Foo.Bar", declarations.get(2).resolve().asReferenceType().containerType().get().getQualifiedName()); + } @Test From 4cac173dd9328f3a6771d8a752cfaad3f443e7b9 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Thu, 31 Aug 2023 08:58:53 +0200 Subject: [PATCH 075/136] Fix an issue relating to the use of a built-in feature in Java 11 --- .../declarations/JavaParserClassDeclarationTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserClassDeclarationTest.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserClassDeclarationTest.java index 3db8f9a9af..4ff72b79ed 100644 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserClassDeclarationTest.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserClassDeclarationTest.java @@ -974,7 +974,7 @@ void testContainerType() { List declarations = cu.findAll(ClassOrInterfaceDeclaration.class); // top level type - assertTrue(declarations.get(0).resolve().asReferenceType().containerType().isEmpty()); + assertFalse(declarations.get(0).resolve().asReferenceType().containerType().isPresent()); assertEquals("Foo", declarations.get(1).resolve().asReferenceType().containerType().get().getQualifiedName()); assertEquals("Foo.Bar", declarations.get(2).resolve().asReferenceType().containerType().get().getQualifiedName()); } From 6d41b7a880f4122396cceedaa638bdbed4b423f5 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Thu, 31 Aug 2023 10:07:49 +0200 Subject: [PATCH 076/136] Update changelog --- changelog.md | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 50 insertions(+), 2 deletions(-) diff --git a/changelog.md b/changelog.md index 012a69ed02..db50c4d2af 100644 --- a/changelog.md +++ b/changelog.md @@ -1,7 +1,7 @@ -Next Release (Version 3.25.5-snapshot) +Next Release (Version 3.25.6-snapshot) -------------------------------------- -[issues resolved](https://github.com/javaparser/javaparser/milestone/201?closed=1) +[issues resolved](https://github.com/javaparser/javaparser/milestone/202?closed=1) ### Added ### Changed @@ -11,6 +11,54 @@ Next Release (Version 3.25.5-snapshot) ### Security +Version 3.25.5 +-------------- +[issues resolved](https://github.com/javaparser/javaparser/milestone/201?closed=1) + +### Added + +* fix: issue 4115 ResolvedUnionType should give access to a list of resolved types (PR [#4119](https://github.com/javaparser/javaparser/pull/4119) by [@jlerbsc](https://github.com/jlerbsc)) +* Support getting more annotation default values using reflection (PR [#4103](https://github.com/javaparser/javaparser/pull/4103) by [@freya022](https://github.com/freya022)) + +### Changed + +* Minor refactoring: Simplifies how to group deleted tokens by extracting a method into an independent class (PR [#4134](https://github.com/javaparser/javaparser/pull/4134) by [@jlerbsc](https://github.com/jlerbsc)) +* Replace deprecated command with environment file (PR [#4122](https://github.com/javaparser/javaparser/pull/4122) by [@70825](https://github.com/70825)) +* Fixes missing named constructor in Modifier.java (PR [#4092](https://github.com/javaparser/javaparser/pull/4092) by [@Auties00](https://github.com/Auties00)) + +### Fixed + +* Fix: issue 4133 Top-level class containerType() throws an exception instead of Optional.empty() (PR [#4135](https://github.com/javaparser/javaparser/pull/4135) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: apply multiline strings (PR [#4130](https://github.com/javaparser/javaparser/pull/4130) by [@70825](https://github.com/70825)) +* Fix: issue 3976 Issue resolving implicit generic types (PR [#4128](https://github.com/javaparser/javaparser/pull/4128) by [@jlerbsc](https://github.com/jlerbsc)) +* Add unit test for PR 4091 Fixed missing permits in pretty printer (PR [#4126](https://github.com/javaparser/javaparser/pull/4126) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: issue 4124 UnsupportedOperationException: 'T' is thrown in MethodCallExpr resolve (PR [#4125](https://github.com/javaparser/javaparser/pull/4125) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: issue 4051 Switched upperBounds and lowerBounds on ResolvedTypeP… (PR [#4123](https://github.com/javaparser/javaparser/pull/4123) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix failing test on JDK 17 (PR [#4121](https://github.com/javaparser/javaparser/pull/4121) by [@mahesh-hegde](https://github.com/mahesh-hegde)) +* Fix: issue 3673 isAssignableBy method StackOverflowError (PR [#4118](https://github.com/javaparser/javaparser/pull/4118) by [@jlerbsc](https://github.com/jlerbsc)) +* Orphan comment added when using lexical preservation is not printed (PR [#4114](https://github.com/javaparser/javaparser/pull/4114) by [@jlerbsc](https://github.com/jlerbsc)) +* Fixed missing permits in pretty printer (PR [#4091](https://github.com/javaparser/javaparser/pull/4091) by [@Auties00](https://github.com/Auties00)) + +### Developer Changes + +* chore(deps): update actions/checkout action to v3.6.0 (PR [#4127](https://github.com/javaparser/javaparser/pull/4127) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): bump com.google.guava:guava from 32.1.1-jre to 32.1.2-jre (PR [#4109](https://github.com/javaparser/javaparser/pull/4109) by [@dependabot[bot]](https://github.com/apps/dependabot)) + +### Uncategorised + +* Fix: issue 4104 LPP doesn't handle new switch entries well (PR [#4106](https://github.com/javaparser/javaparser/pull/4106) by [@jlerbsc](https://github.com/jlerbsc)) + +### :heart: Contributors + +Thank You to all contributors who worked on this release! + +* [@freya022](https://github.com/freya022) +* [@Auties00](https://github.com/Auties00) +* [@mahesh-hegde](https://github.com/mahesh-hegde) +* [@jlerbsc](https://github.com/jlerbsc) +* [@70825](https://github.com/70825) + + Version 3.25.4 -------------- [issues resolved](https://github.com/javaparser/javaparser/milestone/200?closed=1) From 513c9d64ef73824f1ae79cf88dfcb8483618ee6a Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Thu, 31 Aug 2023 10:08:56 +0200 Subject: [PATCH 077/136] update readme --- readme.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/readme.md b/readme.md index 0c52074f6f..5284de6ded 100644 --- a/readme.md +++ b/readme.md @@ -37,14 +37,14 @@ Just add the following to your maven configuration or tailor to your own depende com.github.javaparser javaparser-symbol-solver-core - 3.25.4 + 3.25.5 ``` **Gradle**: ``` -implementation 'com.github.javaparser:javaparser-symbol-solver-core:3.25.4' +implementation 'com.github.javaparser:javaparser-symbol-solver-core:3.25.5' ``` Since Version 3.5.10, the JavaParser project includes the JavaSymbolSolver. @@ -59,14 +59,14 @@ Using the dependency above will add both JavaParser and JavaSymbolSolver to your com.github.javaparser javaparser-core - 3.25.4 + 3.25.5 ``` **Gradle**: ``` -implementation 'com.github.javaparser:javaparser-core:3.25.4' +implementation 'com.github.javaparser:javaparser-core:3.25.5' ``` Since version 3.6.17 the AST can be serialized to JSON. @@ -78,14 +78,14 @@ There is a separate module for this: com.github.javaparser javaparser-core-serialization - 3.25.4 + 3.25.5 ``` **Gradle**: ``` -implementation 'com.github.javaparser:javaparser-core-serialization:3.25.4' +implementation 'com.github.javaparser:javaparser-core-serialization:3.25.5' ``` ## How To Compile Sources From afaffe24e6a13a6f99db9516691d8424351d481e Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Thu, 31 Aug 2023 10:09:59 +0200 Subject: [PATCH 078/136] [maven-release-plugin] prepare release javaparser-parent-3.25.5 --- javaparser-core-generators/pom.xml | 2 +- javaparser-core-metamodel-generator/pom.xml | 2 +- javaparser-core-serialization/pom.xml | 2 +- javaparser-core-testing-bdd/pom.xml | 2 +- javaparser-core-testing/pom.xml | 2 +- javaparser-core/pom.xml | 2 +- javaparser-symbol-solver-core/pom.xml | 2 +- javaparser-symbol-solver-testing/pom.xml | 2 +- pom.xml | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) diff --git a/javaparser-core-generators/pom.xml b/javaparser-core-generators/pom.xml index 86e802971b..74cbfed6e0 100644 --- a/javaparser-core-generators/pom.xml +++ b/javaparser-core-generators/pom.xml @@ -3,7 +3,7 @@ javaparser-parent com.github.javaparser - 3.25.5-SNAPSHOT + 3.25.5 4.0.0 diff --git a/javaparser-core-metamodel-generator/pom.xml b/javaparser-core-metamodel-generator/pom.xml index 593c4d4886..4040390a58 100644 --- a/javaparser-core-metamodel-generator/pom.xml +++ b/javaparser-core-metamodel-generator/pom.xml @@ -3,7 +3,7 @@ javaparser-parent com.github.javaparser - 3.25.5-SNAPSHOT + 3.25.5 4.0.0 diff --git a/javaparser-core-serialization/pom.xml b/javaparser-core-serialization/pom.xml index 1afd575554..476d1fdfe5 100644 --- a/javaparser-core-serialization/pom.xml +++ b/javaparser-core-serialization/pom.xml @@ -2,7 +2,7 @@ javaparser-parent com.github.javaparser - 3.25.5-SNAPSHOT + 3.25.5 4.0.0 diff --git a/javaparser-core-testing-bdd/pom.xml b/javaparser-core-testing-bdd/pom.xml index 4620af8408..38559c5b9c 100644 --- a/javaparser-core-testing-bdd/pom.xml +++ b/javaparser-core-testing-bdd/pom.xml @@ -2,7 +2,7 @@ javaparser-parent com.github.javaparser - 3.25.5-SNAPSHOT + 3.25.5 4.0.0 diff --git a/javaparser-core-testing/pom.xml b/javaparser-core-testing/pom.xml index 767208eb79..cef19e1e08 100644 --- a/javaparser-core-testing/pom.xml +++ b/javaparser-core-testing/pom.xml @@ -2,7 +2,7 @@ javaparser-parent com.github.javaparser - 3.25.5-SNAPSHOT + 3.25.5 4.0.0 diff --git a/javaparser-core/pom.xml b/javaparser-core/pom.xml index 6a45c1bfcd..8ba892ccb3 100644 --- a/javaparser-core/pom.xml +++ b/javaparser-core/pom.xml @@ -2,7 +2,7 @@ javaparser-parent com.github.javaparser - 3.25.5-SNAPSHOT + 3.25.5 4.0.0 diff --git a/javaparser-symbol-solver-core/pom.xml b/javaparser-symbol-solver-core/pom.xml index 70ee8c8a79..e9b340a6c8 100644 --- a/javaparser-symbol-solver-core/pom.xml +++ b/javaparser-symbol-solver-core/pom.xml @@ -3,7 +3,7 @@ javaparser-parent com.github.javaparser - 3.25.5-SNAPSHOT + 3.25.5 4.0.0 diff --git a/javaparser-symbol-solver-testing/pom.xml b/javaparser-symbol-solver-testing/pom.xml index a83b511855..5f36f4f28a 100644 --- a/javaparser-symbol-solver-testing/pom.xml +++ b/javaparser-symbol-solver-testing/pom.xml @@ -3,7 +3,7 @@ javaparser-parent com.github.javaparser - 3.25.5-SNAPSHOT + 3.25.5 4.0.0 diff --git a/pom.xml b/pom.xml index 8050baf784..57179b730b 100644 --- a/pom.xml +++ b/pom.xml @@ -14,7 +14,7 @@ com.github.javaparser javaparser-parent pom - 3.25.5-SNAPSHOT + 3.25.5 javaparser-parent https://github.com/javaparser From fb2c649645c73750b1a0ec1e426cd3b78305deb3 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Thu, 31 Aug 2023 10:32:06 +0200 Subject: [PATCH 079/136] [maven-release-plugin] prepare for next development iteration --- javaparser-core-generators/pom.xml | 2 +- javaparser-core-metamodel-generator/pom.xml | 2 +- javaparser-core-serialization/pom.xml | 2 +- javaparser-core-testing-bdd/pom.xml | 2 +- javaparser-core-testing/pom.xml | 2 +- javaparser-core/pom.xml | 2 +- javaparser-symbol-solver-core/pom.xml | 2 +- javaparser-symbol-solver-testing/pom.xml | 2 +- pom.xml | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) diff --git a/javaparser-core-generators/pom.xml b/javaparser-core-generators/pom.xml index 74cbfed6e0..45a369769f 100644 --- a/javaparser-core-generators/pom.xml +++ b/javaparser-core-generators/pom.xml @@ -3,7 +3,7 @@ javaparser-parent com.github.javaparser - 3.25.5 + 3.25.6-SNAPSHOT 4.0.0 diff --git a/javaparser-core-metamodel-generator/pom.xml b/javaparser-core-metamodel-generator/pom.xml index 4040390a58..639fd0cca6 100644 --- a/javaparser-core-metamodel-generator/pom.xml +++ b/javaparser-core-metamodel-generator/pom.xml @@ -3,7 +3,7 @@ javaparser-parent com.github.javaparser - 3.25.5 + 3.25.6-SNAPSHOT 4.0.0 diff --git a/javaparser-core-serialization/pom.xml b/javaparser-core-serialization/pom.xml index 476d1fdfe5..1b75642581 100644 --- a/javaparser-core-serialization/pom.xml +++ b/javaparser-core-serialization/pom.xml @@ -2,7 +2,7 @@ javaparser-parent com.github.javaparser - 3.25.5 + 3.25.6-SNAPSHOT 4.0.0 diff --git a/javaparser-core-testing-bdd/pom.xml b/javaparser-core-testing-bdd/pom.xml index 38559c5b9c..1a6fd879b8 100644 --- a/javaparser-core-testing-bdd/pom.xml +++ b/javaparser-core-testing-bdd/pom.xml @@ -2,7 +2,7 @@ javaparser-parent com.github.javaparser - 3.25.5 + 3.25.6-SNAPSHOT 4.0.0 diff --git a/javaparser-core-testing/pom.xml b/javaparser-core-testing/pom.xml index cef19e1e08..a894e9ab83 100644 --- a/javaparser-core-testing/pom.xml +++ b/javaparser-core-testing/pom.xml @@ -2,7 +2,7 @@ javaparser-parent com.github.javaparser - 3.25.5 + 3.25.6-SNAPSHOT 4.0.0 diff --git a/javaparser-core/pom.xml b/javaparser-core/pom.xml index 8ba892ccb3..b271dcbfd2 100644 --- a/javaparser-core/pom.xml +++ b/javaparser-core/pom.xml @@ -2,7 +2,7 @@ javaparser-parent com.github.javaparser - 3.25.5 + 3.25.6-SNAPSHOT 4.0.0 diff --git a/javaparser-symbol-solver-core/pom.xml b/javaparser-symbol-solver-core/pom.xml index e9b340a6c8..02ebfb17a2 100644 --- a/javaparser-symbol-solver-core/pom.xml +++ b/javaparser-symbol-solver-core/pom.xml @@ -3,7 +3,7 @@ javaparser-parent com.github.javaparser - 3.25.5 + 3.25.6-SNAPSHOT 4.0.0 diff --git a/javaparser-symbol-solver-testing/pom.xml b/javaparser-symbol-solver-testing/pom.xml index 5f36f4f28a..3649400bed 100644 --- a/javaparser-symbol-solver-testing/pom.xml +++ b/javaparser-symbol-solver-testing/pom.xml @@ -3,7 +3,7 @@ javaparser-parent com.github.javaparser - 3.25.5 + 3.25.6-SNAPSHOT 4.0.0 diff --git a/pom.xml b/pom.xml index 57179b730b..bc770cfb5b 100644 --- a/pom.xml +++ b/pom.xml @@ -14,7 +14,7 @@ com.github.javaparser javaparser-parent pom - 3.25.5 + 3.25.6-SNAPSHOT javaparser-parent https://github.com/javaparser From fdee8246539385828d9b6db9cd5c150d248f73ce Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Thu, 31 Aug 2023 14:49:10 +0200 Subject: [PATCH 080/136] Fix: issue #2484 SymbolResolver on MethodCallExpr fails if method parameter is of kind Class --- .../logic/MethodResolutionLogic.java | 4 ++ .../reflectionmodel/ReflectionFactory.java | 24 +++++++---- .../JavaParserMethodDeclarationTest.java | 42 +++++++++++++++++-- 3 files changed, 58 insertions(+), 12 deletions(-) diff --git a/javaparser-core/src/main/java/com/github/javaparser/resolution/logic/MethodResolutionLogic.java b/javaparser-core/src/main/java/com/github/javaparser/resolution/logic/MethodResolutionLogic.java index 9d51840ebf..081b1324cb 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/resolution/logic/MethodResolutionLogic.java +++ b/javaparser-core/src/main/java/com/github/javaparser/resolution/logic/MethodResolutionLogic.java @@ -343,6 +343,10 @@ private static boolean isAssignableMatchTypeParametersMatchingQName(ResolvedRefe } if (expectedParam.isWildcard()) { if (expectedParam.asWildcard().isExtends()) { + // trying to compare with unbounded wildcard type parameter + if (actualParam.isWildcard() && !actualParam.asWildcard().isBounded()) { + return true; + } return isAssignableMatchTypeParameters(expectedParam.asWildcard().getBoundedType(), actual, matchedParameters); } // TODO verify super bound diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionFactory.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionFactory.java index 51bbfd12e9..0ba5ab500d 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionFactory.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionFactory.java @@ -21,13 +21,6 @@ package com.github.javaparser.symbolsolver.reflectionmodel; -import com.github.javaparser.ast.AccessSpecifier; -import com.github.javaparser.resolution.TypeSolver; -import com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration; -import com.github.javaparser.resolution.declarations.ResolvedTypeParameterDeclaration; -import com.github.javaparser.resolution.model.typesystem.ReferenceTypeImpl; -import com.github.javaparser.resolution.types.*; - import java.lang.reflect.GenericArrayType; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; @@ -36,11 +29,18 @@ import java.util.Arrays; import java.util.List; +import com.github.javaparser.ast.AccessSpecifier; +import com.github.javaparser.resolution.TypeSolver; +import com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration; +import com.github.javaparser.resolution.declarations.ResolvedTypeParameterDeclaration; +import com.github.javaparser.resolution.model.typesystem.ReferenceTypeImpl; +import com.github.javaparser.resolution.types.*; + /** * @author Federico Tomassetti */ public class ReflectionFactory { - + private static String JAVA_LANG_OBJECT = Object.class.getCanonicalName(); public static ResolvedReferenceTypeDeclaration typeDeclarationFor(Class clazz, TypeSolver typeSolver) { @@ -99,19 +99,25 @@ public static ResolvedType typeUsageFor(java.lang.reflect.Type type, TypeSolver WildcardType wildcardType = (WildcardType) type; if (wildcardType.getLowerBounds().length > 0 && wildcardType.getUpperBounds().length > 0) { if (wildcardType.getUpperBounds().length == 1 && wildcardType.getUpperBounds()[0].getTypeName().equals(JAVA_LANG_OBJECT)) { - // ok, it does not matter + return ResolvedWildcard.UNBOUNDED; } } if (wildcardType.getLowerBounds().length > 0) { if (wildcardType.getLowerBounds().length > 1) { throw new UnsupportedOperationException(); } + if (wildcardType.getUpperBounds().length == 1 && wildcardType.getUpperBounds()[0].getTypeName().equals(JAVA_LANG_OBJECT)) { + return ResolvedWildcard.UNBOUNDED; + } return ResolvedWildcard.superBound(typeUsageFor(wildcardType.getLowerBounds()[0], typeSolver)); } if (wildcardType.getUpperBounds().length > 0) { if (wildcardType.getUpperBounds().length > 1) { throw new UnsupportedOperationException(); } + if (wildcardType.getUpperBounds().length == 1 && wildcardType.getUpperBounds()[0].getTypeName().equals(JAVA_LANG_OBJECT)) { + return ResolvedWildcard.UNBOUNDED; + } return ResolvedWildcard.extendsBound(typeUsageFor(wildcardType.getUpperBounds()[0], typeSolver)); } return ResolvedWildcard.UNBOUNDED; diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserMethodDeclarationTest.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserMethodDeclarationTest.java index 61430b9d04..b471d03eed 100644 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserMethodDeclarationTest.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserMethodDeclarationTest.java @@ -21,18 +21,28 @@ package com.github.javaparser.symbolsolver.javaparsermodel.declarations; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.List; +import java.util.Optional; + +import org.junit.jupiter.api.Test; + +import com.github.javaparser.JavaParserAdapter; import com.github.javaparser.StaticJavaParser; +import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.Node; import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.expr.MethodCallExpr; import com.github.javaparser.resolution.TypeSolver; import com.github.javaparser.resolution.declarations.AssociableToAST; import com.github.javaparser.resolution.declarations.ResolvedMethodDeclarationTest; import com.github.javaparser.symbolsolver.core.resolution.TypeVariableResolutionCapabilityTest; +import com.github.javaparser.symbolsolver.resolution.AbstractResolutionTest; import com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver; -import java.util.Optional; - -class JavaParserMethodDeclarationTest implements ResolvedMethodDeclarationTest, TypeVariableResolutionCapabilityTest { +class JavaParserMethodDeclarationTest extends AbstractResolutionTest + implements ResolvedMethodDeclarationTest, TypeVariableResolutionCapabilityTest { @Override public Optional getWrappedDeclaration(AssociableToAST associableToAST) { @@ -49,4 +59,30 @@ public JavaParserMethodDeclaration createValue() { return new JavaParserMethodDeclaration(methodDeclaration, typeSolver); } + @Test + void issue2484() { + String code = + "public class MyClass {\n" + + " private Ibaz m_something;\n" + + "\n" + + " public interface Ibaz {\n" + + " }\n" + + " \n" + + " public void foo(Class clazz) {\n" + + " }\n" + + " \n" + + " protected void bar() {\n" + + " foo(null); // this works\n" + + " foo(m_something.getClass()); // this doesn't work\n" + + " }\n" + + "}"; + + JavaParserAdapter parser = JavaParserAdapter.of(createParserWithResolver(defaultTypeSolver())); + CompilationUnit cu = parser.parse(code); + + List mces = cu.findAll(MethodCallExpr.class); + assertEquals("MyClass.foo(java.lang.Class)", mces.get(0).resolve().getQualifiedSignature()); + assertEquals("MyClass.foo(java.lang.Class)", mces.get(1).resolve().getQualifiedSignature()); + } + } From e6ceffaff3a6f5c8a93112c89bf06f4aa3999f91 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Thu, 31 Aug 2023 17:20:23 +0200 Subject: [PATCH 081/136] Fix issues on test cases and improve the wildcard type resolution --- .../reflectionmodel/ReflectionFactory.java | 5 +---- .../javaparser/symbolsolver/Issue2823Test.java | 9 +++++---- .../ReflectionParameterDeclarationTest.java | 15 ++++++++------- .../resolution/LambdaResolutionTest.java | 9 +++++---- 4 files changed, 19 insertions(+), 19 deletions(-) diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionFactory.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionFactory.java index 0ba5ab500d..4a10f90ae8 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionFactory.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionFactory.java @@ -99,16 +99,13 @@ public static ResolvedType typeUsageFor(java.lang.reflect.Type type, TypeSolver WildcardType wildcardType = (WildcardType) type; if (wildcardType.getLowerBounds().length > 0 && wildcardType.getUpperBounds().length > 0) { if (wildcardType.getUpperBounds().length == 1 && wildcardType.getUpperBounds()[0].getTypeName().equals(JAVA_LANG_OBJECT)) { - return ResolvedWildcard.UNBOUNDED; + // ok, it does not matter } } if (wildcardType.getLowerBounds().length > 0) { if (wildcardType.getLowerBounds().length > 1) { throw new UnsupportedOperationException(); } - if (wildcardType.getUpperBounds().length == 1 && wildcardType.getUpperBounds()[0].getTypeName().equals(JAVA_LANG_OBJECT)) { - return ResolvedWildcard.UNBOUNDED; - } return ResolvedWildcard.superBound(typeUsageFor(wildcardType.getLowerBounds()[0], typeSolver)); } if (wildcardType.getUpperBounds().length > 0) { diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2823Test.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2823Test.java index b02811ce56..5aa3d5b6aa 100644 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2823Test.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2823Test.java @@ -20,6 +20,10 @@ package com.github.javaparser.symbolsolver; +import java.nio.file.Path; + +import org.junit.jupiter.api.Test; + import com.github.javaparser.ParserConfiguration; import com.github.javaparser.StaticJavaParser; import com.github.javaparser.ast.CompilationUnit; @@ -28,14 +32,11 @@ import com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver; import com.github.javaparser.symbolsolver.resolution.typesolvers.JavaParserTypeSolver; import com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver; -import org.junit.jupiter.api.Test; - -import java.nio.file.Path; public class Issue2823Test extends AbstractSymbolResolutionTest { @Test - public void test() { + void test() { final Path testRoot = adaptPath("src/test/resources/issue2823"); TypeSolver reflectionTypeSolver = new ReflectionTypeSolver(); JavaParserTypeSolver javaParserTypeSolver = new JavaParserTypeSolver(testRoot); diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionParameterDeclarationTest.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionParameterDeclarationTest.java index c7f94aacf7..6a7c481724 100644 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionParameterDeclarationTest.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionParameterDeclarationTest.java @@ -21,17 +21,18 @@ package com.github.javaparser.symbolsolver.reflectionmodel; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.Test; + import com.github.javaparser.resolution.TypeSolver; import com.github.javaparser.resolution.declarations.ResolvedClassDeclaration; import com.github.javaparser.resolution.declarations.ResolvedInterfaceDeclaration; import com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration; import com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver; -import org.junit.jupiter.api.Test; - -import java.util.List; -import java.util.Map; - -import static org.junit.jupiter.api.Assertions.assertEquals; class ReflectionParameterDeclarationTest { @@ -49,7 +50,7 @@ void testGetSignature() { assertEquals("hashCode()", hashCode.getSignature()); assertEquals("equals(java.lang.Object)", equals.getSignature()); - assertEquals("containsAll(java.util.Collection)", containsAll.getSignature()); + assertEquals("containsAll(java.util.Collection)", containsAll.getSignature()); assertEquals("subList(int, int)", subList.getSignature()); } diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/LambdaResolutionTest.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/LambdaResolutionTest.java index b0e420fd72..50b9e16d1e 100644 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/LambdaResolutionTest.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/LambdaResolutionTest.java @@ -21,6 +21,10 @@ package com.github.javaparser.symbolsolver.resolution; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.body.MethodDeclaration; import com.github.javaparser.ast.expr.Expression; @@ -31,9 +35,6 @@ import com.github.javaparser.resolution.types.ResolvedType; import com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade; import com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; class LambdaResolutionTest extends AbstractResolutionTest { @@ -134,7 +135,7 @@ void lambdaCollectParam() { JavaParserFacade javaParserFacade = JavaParserFacade.get(new ReflectionTypeSolver()); ResolvedType type = javaParserFacade.getType(expression); - assertEquals("java.util.stream.Collector>", type.describe()); + assertEquals("java.util.stream.Collector>", type.describe()); } @Test From 29bebf850d90ece5cb711a8ccac148e8add53b9d Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Thu, 31 Aug 2023 18:49:45 +0200 Subject: [PATCH 082/136] Fix issues on test resources --- .../com_github_javaparser_CommentsInserter.txt | 6 +++--- .../expected_output/com_github_javaparser_ast_Node.txt | 2 +- ...del_declarations_JavaParserAnonymousClassDeclaration.txt | 2 +- ...parser_symbolsolver_resolution_MethodResolutionLogic.txt | 2 +- ...vaparser_symbolsolver_model_typesystem_ReferenceType.txt | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_CommentsInserter.txt b/javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_CommentsInserter.txt index 003f216cb4..3fd04b86b2 100644 --- a/javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_CommentsInserter.txt +++ b/javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_CommentsInserter.txt @@ -15,7 +15,7 @@ Line 96) PositionUtils.sortByBeginPosition(children) ==> com.github.javaparser.utils.PositionUtils.sortByBeginPosition(java.util.List) Line 101) PositionUtils.nodeContains(child, c, configuration.doNotConsiderAnnotationsAsNodeStartForCodeAttribution) ==> com.github.javaparser.utils.PositionUtils.nodeContains(com.github.javaparser.ast.Node, com.github.javaparser.ast.Node, boolean) Line 103) commentsInsideChild.add(c) ==> java.util.TreeSet.add(E) - Line 106) commentsToAttribute.removeAll(commentsInsideChild) ==> java.util.AbstractSet.removeAll(java.util.Collection) + Line 106) commentsToAttribute.removeAll(commentsInsideChild) ==> java.util.AbstractSet.removeAll(java.util.Collection) Line 107) insertComments(child, commentsInsideChild) ==> com.github.javaparser.CommentsInserter.insertComments(com.github.javaparser.ast.Node, java.util.TreeSet) Line 114) comment.isLineComment() ==> com.github.javaparser.ast.comments.Comment.isLineComment() Line 116) child.getEnd() ==> com.github.javaparser.ast.Node.getEnd() @@ -31,7 +31,7 @@ Line 144) thereAreLinesBetween(previousComment, thing) ==> com.github.javaparser.CommentsInserter.thereAreLinesBetween(com.github.javaparser.ast.Node, com.github.javaparser.ast.Node) Line 145) thing.setComment(previousComment) ==> com.github.javaparser.ast.Node.setComment(com.github.javaparser.ast.comments.Comment) Line 146) attributedComments.add(previousComment) ==> java.util.List.add(E) - Line 153) commentsToAttribute.removeAll(attributedComments) ==> java.util.AbstractSet.removeAll(java.util.Collection) + Line 153) commentsToAttribute.removeAll(attributedComments) ==> java.util.AbstractSet.removeAll(java.util.Collection) Line 157) c.isOrphan() ==> com.github.javaparser.ast.comments.Comment.isOrphan() Line 158) node.addOrphanComment(c) ==> com.github.javaparser.ast.Node.addOrphanComment(com.github.javaparser.ast.comments.Comment) Line 166) node.getBegin() ==> com.github.javaparser.ast.Node.getBegin() @@ -41,7 +41,7 @@ Line 176) children.addAll(node.getChildrenNodes()) ==> java.util.List.addAll(java.util.Collection) Line 176) node.getChildrenNodes() ==> com.github.javaparser.ast.Node.getChildrenNodes() Line 177) PositionUtils.sortByBeginPosition(children) ==> com.github.javaparser.utils.PositionUtils.sortByBeginPosition(java.util.List) - Line 178) Collections.reverse(children) ==> java.util.Collections.reverse(java.util.List) + Line 178) Collections.reverse(children) ==> java.util.Collections.reverse(java.util.List) Line 181) attributeLineCommentToNodeOrChild(child, lineComment) ==> com.github.javaparser.CommentsInserter.attributeLineCommentToNodeOrChild(com.github.javaparser.ast.Node, com.github.javaparser.ast.comments.LineComment) Line 191) PositionUtils.areInOrder(a, b) ==> com.github.javaparser.utils.PositionUtils.areInOrder(com.github.javaparser.ast.Node, com.github.javaparser.ast.Node) Line 192) thereAreLinesBetween(b, a) ==> com.github.javaparser.CommentsInserter.thereAreLinesBetween(com.github.javaparser.ast.Node, com.github.javaparser.ast.Node) diff --git a/javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_Node.txt b/javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_Node.txt index 4ca45ef992..1d7b0b8e07 100644 --- a/javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_Node.txt +++ b/javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_Node.txt @@ -15,7 +15,7 @@ Line 207) toString() ==> com.github.javaparser.ast.Node.toString() Line 215) EqualsVisitor.equals(this, (Node) obj) ==> com.github.javaparser.ast.visitor.EqualsVisitor.equals(com.github.javaparser.ast.Node, com.github.javaparser.ast.Node) Line 220) this.accept(new CloneVisitor(), null) ==> com.github.javaparser.ast.Node.accept(com.github.javaparser.ast.visitor.GenericVisitor, A) - Line 231) classType.isAssignableFrom(parent.getClass()) ==> java.lang.Class.isAssignableFrom(java.lang.Class) + Line 231) classType.isAssignableFrom(parent.getClass()) ==> java.lang.Class.isAssignableFrom(java.lang.Class) Line 231) parent.getClass() ==> java.lang.Object.getClass() Line 243) range.contains(other.range) ==> com.github.javaparser.Range.contains(com.github.javaparser.Range) Line 247) orphanComments.add(comment) ==> java.util.List.add(E) diff --git a/javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_declarations_JavaParserAnonymousClassDeclaration.txt b/javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_declarations_JavaParserAnonymousClassDeclaration.txt index d044fbc633..d01f5aa8e5 100644 --- a/javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_declarations_JavaParserAnonymousClassDeclaration.txt +++ b/javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_declarations_JavaParserAnonymousClassDeclaration.txt @@ -13,7 +13,7 @@ Line 54) wrappedNode.getAnonymousClassBody().get().stream() ==> java.util.Collection.stream() Line 54) wrappedNode.getAnonymousClassBody().get() ==> java.util.Optional.get() Line 54) wrappedNode.getAnonymousClassBody() ==> com.github.javaparser.ast.expr.ObjectCreationExpr.getAnonymousClassBody() - Line 58) memberClass.isAssignableFrom(node.getClass()) ==> java.lang.Class.isAssignableFrom(java.lang.Class) + Line 58) memberClass.isAssignableFrom(node.getClass()) ==> java.lang.Class.isAssignableFrom(java.lang.Class) Line 58) node.getClass() ==> java.lang.Object.getClass() Line 60) Collectors.toList() ==> java.util.stream.Collectors.toList() Line 65) typeSolver.solveType(Object.class.getCanonicalName()) ==> com.github.javaparser.symbolsolver.model.resolution.TypeSolver.solveType(java.lang.String) diff --git a/javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_resolution_MethodResolutionLogic.txt b/javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_resolution_MethodResolutionLogic.txt index 0c37bf700e..a27f7fb478 100644 --- a/javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_resolution_MethodResolutionLogic.txt +++ b/javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_resolution_MethodResolutionLogic.txt @@ -260,7 +260,7 @@ Line 404) removeCandidates.isEmpty() ==> java.util.Set.isEmpty() Line 404) removeCandidates.size() ==> java.util.Set.size() Line 404) applicableMethods.size() ==> java.util.List.size() - Line 405) applicableMethods.removeAll(removeCandidates) ==> java.util.List.removeAll(java.util.Collection) + Line 405) applicableMethods.removeAll(removeCandidates) ==> java.util.List.removeAll(java.util.Collection) Line 409) applicableMethods.size() ==> java.util.List.size() Line 410) SymbolReference.solved(applicableMethods.get(0)) ==> com.github.javaparser.symbolsolver.model.resolution.SymbolReference.solved(S2) Line 410) applicableMethods.get(0) ==> java.util.List.get(int) diff --git a/javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_typesystem_ReferenceType.txt b/javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_typesystem_ReferenceType.txt index 6a1895d3a3..6cad1a9d5f 100644 --- a/javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_typesystem_ReferenceType.txt +++ b/javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_typesystem_ReferenceType.txt @@ -231,7 +231,7 @@ Line 453) Collectors.toList() ==> java.util.stream.Collectors.toList() Line 454) thisBounds.size() ==> java.util.List.size() Line 454) otherBounds.size() ==> java.util.List.size() - Line 454) otherBounds.containsAll(thisBounds) ==> java.util.List.containsAll(java.util.Collection) + Line 454) otherBounds.containsAll(thisBounds) ==> java.util.List.containsAll(java.util.Collection) Line 472) typeDeclaration.getTypeParameters().stream().map((tp) -> new TypeVariable(tp)).collect(Collectors.toList()) ==> java.util.stream.Stream.collect(java.util.stream.Collector) Line 472) typeDeclaration.getTypeParameters().stream().map((tp) -> new TypeVariable(tp)) ==> java.util.stream.Stream.map(java.util.function.Function) Line 472) typeDeclaration.getTypeParameters().stream() ==> java.util.Collection.stream() From e02a5e7735b899bf747d6bed118c8ea055f3c615 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Fri, 1 Sep 2023 15:41:47 +0200 Subject: [PATCH 083/136] Fix: issue #4036 LeastUpperBoundLogic.lub returns null when matches ConditionalExpr --- .../typeinference/LeastUpperBoundLogic.java | 31 +++++++++++++++++++ .../typeinference/LeastUpperBoundTest.java | 26 ++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/LeastUpperBoundLogic.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/LeastUpperBoundLogic.java index aebf49f27d..a9c2c79db3 100755 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/LeastUpperBoundLogic.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/LeastUpperBoundLogic.java @@ -40,6 +40,10 @@ public ResolvedType lub(Set types) { // One way to handle this case is to remove the type null from the list of types. Set resolvedTypes = types.stream().filter(type -> !(type instanceof NullType)).collect(Collectors.toSet()); + // reduces the set in the presence of enumeration type because members are + // not equal and they do not have an explicit super type. + // So we only keep one enumeration for all the members of an enumeration + filterEnumType(resolvedTypes); // The least upper bound, or "lub", of a set of reference types is a shared supertype that is more specific // than any other shared supertype (that is, no other shared supertype is a subtype of the least upper bound). @@ -196,6 +200,33 @@ public ResolvedType lub(Set types) { return erasedBest; } + /* + * Check the type declaration if it is an enum + */ + private boolean isEnum(ResolvedType type) { + return type.isReferenceType() && type.asReferenceType().getTypeDeclaration().get().isEnum(); + } + + /* + * Keep only one enum reference type per enum declaration + */ + private void filterEnumType(Set resolvedTypes) { + Map enumTypes = new HashMap<>(); + List erasedEnumTypes = new ArrayList<>(); + for (ResolvedType type : resolvedTypes) { + if (isEnum(type)) { + // enum qualified name i.e. java.math.RoundingMode + String qn = type.asReferenceType().getTypeDeclaration().get().asEnum().getQualifiedName(); + // Save the first occurrence and mark the others so they can be deleted + ResolvedType returnedType = enumTypes.putIfAbsent(qn, type); + if (returnedType != null) { + erasedEnumTypes.add(type); + } + } + } + resolvedTypes.removeAll(erasedEnumTypes); + } + private List> supertypes(Set types) { return types.stream() .map(type -> supertypes(type).stream().collect(Collectors.toCollection(LinkedHashSet::new))) diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/typeinference/LeastUpperBoundTest.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/typeinference/LeastUpperBoundTest.java index a323664aac..da375e9787 100755 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/typeinference/LeastUpperBoundTest.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/typeinference/LeastUpperBoundTest.java @@ -16,8 +16,10 @@ import com.github.javaparser.StaticJavaParser; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.EnumDeclaration; import com.github.javaparser.resolution.TypeSolver; import com.github.javaparser.resolution.UnsolvedSymbolException; +import com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration; import com.github.javaparser.resolution.model.typesystem.NullType; import com.github.javaparser.resolution.model.typesystem.ReferenceTypeImpl; import com.github.javaparser.resolution.types.ResolvedType; @@ -177,6 +179,21 @@ public void lub_of_null_and_object() { assertEquals(expected, lub); } + @Test + public void lub_of_enum() { + ResolvedType type = type("java.math.RoundingMode"); + + ResolvedReferenceTypeDeclaration typeDeclaration = type.asReferenceType().getTypeDeclaration().get(); + + List constanteTypes = typeDeclaration.asEnum().getEnumConstants().stream() + .map(enumConst -> enumConst.getType()).collect(Collectors.toList()); + + ResolvedType expected = constanteTypes.get(0); + + ResolvedType lub = leastUpperBound(constanteTypes.get(0), constanteTypes.get(1)); + assertEquals(expected.asReferenceType(), lub.asReferenceType()); + } + @Test public void lub_of_generics_with_shared_super_class() { List types = declaredTypes( @@ -387,6 +404,15 @@ private List declaredTypes(String... lines) { return results; } + private List declaredEnumTypes(String... lines) { + CompilationUnit tree = treeOf(lines); + List results = Lists.newLinkedList(); + for (EnumDeclaration classTree : tree.findAll(EnumDeclaration.class)) { + results.add(new ReferenceTypeImpl(classTree.resolve())); + } + return results; + } + private CompilationUnit treeOf(String... lines) { StringBuilder builder = new StringBuilder(); for (String line : lines) { From 6e955255b6e45cc19e606c1d96021fa1cd8c0cf6 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Fri, 1 Sep 2023 16:23:15 +0200 Subject: [PATCH 084/136] Fix unit test --- .../resolution/typeinference/LeastUpperBoundTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/typeinference/LeastUpperBoundTest.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/typeinference/LeastUpperBoundTest.java index da375e9787..7db9cfe0d9 100755 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/typeinference/LeastUpperBoundTest.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/typeinference/LeastUpperBoundTest.java @@ -191,7 +191,7 @@ public void lub_of_enum() { ResolvedType expected = constanteTypes.get(0); ResolvedType lub = leastUpperBound(constanteTypes.get(0), constanteTypes.get(1)); - assertEquals(expected.asReferenceType(), lub.asReferenceType()); + assertEquals(expected.asReferenceType().describe(), lub.asReferenceType().describe()); } @Test From 3296e4ad4e1866a8413fff96bf48734485ea8b1b Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Fri, 1 Sep 2023 20:58:12 +0200 Subject: [PATCH 085/136] Fix: issue #3214 calculateResolvedType Type error --- .../JavaParserTypeDeclarationAdapter.java | 12 ++-- .../JavaParserTypeDeclarationAdapterTest.java | 56 +++++++++++++++++++ 2 files changed, 64 insertions(+), 4 deletions(-) create mode 100755 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/JavaParserTypeDeclarationAdapterTest.java diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/JavaParserTypeDeclarationAdapter.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/JavaParserTypeDeclarationAdapter.java index 8d7dce32e4..6e2d71c4fd 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/JavaParserTypeDeclarationAdapter.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/JavaParserTypeDeclarationAdapter.java @@ -96,6 +96,13 @@ public SymbolReference solveType(String name, List symbolRef = context.getParent() + .orElseThrow(() -> new RuntimeException("Parent context unexpectedly empty.")) + .solveType(name, typeArguments); + if (symbolRef.isSolved()) + return symbolRef; + // Check if is a type parameter if (wrappedNode instanceof NodeWithTypeParameters) { NodeWithTypeParameters nodeWithTypeParameters = (NodeWithTypeParameters) wrappedNode; @@ -147,10 +154,7 @@ public SymbolReference solveType(String name, List new RuntimeException("Parent context unexpectedly empty.")) - .solveType(name, typeArguments); + return SymbolReference.unsolved(); } private boolean isCompositeName(String name) { diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/JavaParserTypeDeclarationAdapterTest.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/JavaParserTypeDeclarationAdapterTest.java new file mode 100755 index 0000000000..fce260b6f2 --- /dev/null +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/JavaParserTypeDeclarationAdapterTest.java @@ -0,0 +1,56 @@ +package com.github.javaparser.symbolsolver.javaparsermodel.contexts; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.*; + +import com.github.javaparser.JavaParserAdapter; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.expr.MethodCallExpr; +import com.github.javaparser.symbolsolver.resolution.AbstractResolutionTest; + +class JavaParserTypeDeclarationAdapterTest extends AbstractResolutionTest { + + @BeforeAll + static void setUpBeforeClass() throws Exception { + } + + @AfterAll + static void tearDownAfterClass() throws Exception { + } + + @BeforeEach + void setUp() throws Exception { + } + + @AfterEach + void tearDownAfterEach() throws Exception { + } + + @Test + void issue3214() { + String code = + "public interface Foo {\n" + + " interface Bar {}\n" + + " }\n" + + "\n" + + " public interface Bar {\n" + + " void show();\n" + + " }\n" + + "\n" + + " public class Test implements Foo.Bar {\n" + + " private Bar bar;\n" + + " private void m() {\n" + + " bar.show();\n" + + " }\n" + + " }"; + + JavaParserAdapter parser = JavaParserAdapter.of(createParserWithResolver(defaultTypeSolver())); + CompilationUnit cu = parser.parse(code); + + MethodCallExpr mce = cu.findAll(MethodCallExpr.class).get(0); + + assertEquals("Bar.show()",mce.resolve().getQualifiedSignature()); + } + +} From 1e95dbcb6f611a1ab80c04ab7136fdb8698b3d9c Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Sat, 2 Sep 2023 09:02:45 +0200 Subject: [PATCH 086/136] Fix: issue #3269 Test resources containing included interfaces do not compile --- .../ImplementedOrExtendedTypeResolution.java.txt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/javaparser-symbol-solver-testing/src/test/resources/ImplementedOrExtendedTypeResolution/ImplementedOrExtendedTypeResolution.java.txt b/javaparser-symbol-solver-testing/src/test/resources/ImplementedOrExtendedTypeResolution/ImplementedOrExtendedTypeResolution.java.txt index e99a1037ec..f09a3b9738 100644 --- a/javaparser-symbol-solver-testing/src/test/resources/ImplementedOrExtendedTypeResolution/ImplementedOrExtendedTypeResolution.java.txt +++ b/javaparser-symbol-solver-testing/src/test/resources/ImplementedOrExtendedTypeResolution/ImplementedOrExtendedTypeResolution.java.txt @@ -30,8 +30,8 @@ class C3 { class InterfaceTest implements I1, I2.I2_1, I3.I3_1.I3_1_1 { I1 field_i1; - I2_1 field_i2; - I3_1_1 field_i3; + I2.I2_1 field_i2; + I3.I3_1.I3_1_1 field_i3; } class ClassTest1 extends C1 { @@ -39,9 +39,9 @@ class ClassTest1 extends C1 { } class ClassTest2 extends C2.C2_1 { - C2_1 field_c2; + C2.C2_1 field_c2; } class ClassTest3 extends C3.C3_1.C3_1_1 { - C3_1_1 field_c3; + C3.C3_1.C3_1_1 field_c3; } From 84f22d7a0939c75f8634c5d0a4e1ddac33ff6ebf Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 4 Sep 2023 14:35:15 +0000 Subject: [PATCH 087/136] chore(deps): update actions/checkout action to v4 --- .github/workflows/create_github_release.yml | 2 +- .github/workflows/maven_tests.yml | 4 ++-- .github/workflows/prepare_release_changelog.yml | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/create_github_release.yml b/.github/workflows/create_github_release.yml index 12a4e0cf2c..d82ec1f420 100644 --- a/.github/workflows/create_github_release.yml +++ b/.github/workflows/create_github_release.yml @@ -13,7 +13,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout code - uses: actions/checkout@v3.6.0 + uses: actions/checkout@v4.0.0 - name: Create Release id: create_release diff --git a/.github/workflows/maven_tests.yml b/.github/workflows/maven_tests.yml index fe83eddbc0..1bc28720a2 100644 --- a/.github/workflows/maven_tests.yml +++ b/.github/workflows/maven_tests.yml @@ -45,7 +45,7 @@ jobs: steps: ## Checkout the current version of the code from the repo. - name: Checkout latest code - uses: actions/checkout@v3.6.0 + uses: actions/checkout@v4.0.0 with: fetch-depth: "0" @@ -109,7 +109,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout latest code - uses: actions/checkout@v3.6.0 + uses: actions/checkout@v4.0.0 with: fetch-depth: "0" - name: Set up JDK 11 diff --git a/.github/workflows/prepare_release_changelog.yml b/.github/workflows/prepare_release_changelog.yml index 59029b9a7a..b37083e6be 100644 --- a/.github/workflows/prepare_release_changelog.yml +++ b/.github/workflows/prepare_release_changelog.yml @@ -15,7 +15,7 @@ jobs: # Check out current repository - name: Fetch Sources - uses: actions/checkout@v3.6.0 + uses: actions/checkout@v4.0.0 # Setup Java 11 environment for the next steps - name: Setup Java From ba9779a5f0126a298ed1985bc8946d4f4f8f1104 Mon Sep 17 00:00:00 2001 From: volodya-lombrozo Date: Fri, 8 Sep 2023 18:01:41 +0300 Subject: [PATCH 088/136] feat(#4075): repair all the tests --- .../ast/validator/Java11ValidatorTest.java | 4 ++-- .../ast/validator/Java14ValidatorTest.java | 2 +- .../ast/validator/Java1_0ValidatorTest.java | 12 ++++++------ .../ast/validator/Java1_1ValidatorTest.java | 3 +-- .../ast/validator/Java1_3ValidatorTest.java | 2 +- .../ast/validator/Java1_4ValidatorTest.java | 18 +++++++++--------- .../ast/validator/Java5ValidatorTest.java | 2 +- .../ast/validator/Java6ValidatorTest.java | 2 +- .../ast/validator/Java7ValidatorTest.java | 2 +- .../ast/validator/Java8ValidatorTest.java | 4 ++-- 10 files changed, 25 insertions(+), 26 deletions(-) diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java11ValidatorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java11ValidatorTest.java index d8213ac89b..4c7e5bac60 100644 --- a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java11ValidatorTest.java +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java11ValidatorTest.java @@ -45,12 +45,12 @@ void varAllowedInLocalVariableDeclaration() { @Test void switchExpressionNotAllowed() { ParseResult result = javaParser.parse(STATEMENT, provider("int a = switch(x){};")); - assertProblems(result, "(line 1,col 9) Switch expressions are not supported."); + assertProblems(result, "(line 1,col 9) Switch expressions are not supported. Pay attention that this feature is supported starting from 'JAVA_12' language level. If you need that feature the language level must be configured in the configuration before parsing the source files."); } @Test void multiLabelCaseNotAllowed() { ParseResult result = javaParser.parse(STATEMENT, provider("switch(x){case 3,4,5: ;}")); - assertProblems(result, "(line 1,col 11) Only one label allowed in a switch-case."); + assertProblems(result, "(line 1,col 11) Only one label allowed in a switch-case. Pay attention that this feature is supported starting from 'JAVA_7' language level. If you need that feature the language level must be configured in the configuration before parsing the source files."); } } diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java14ValidatorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java14ValidatorTest.java index b46b3b4b37..dc0c96d16b 100644 --- a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java14ValidatorTest.java +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java14ValidatorTest.java @@ -72,7 +72,7 @@ class RecordDeclarationForbidden { void recordDeclaration() { String s = "record X() { }"; ParseResult result = javaParser.parse(COMPILATION_UNIT, provider(s)); - TestUtils.assertProblems(result, "(line 1,col 1) Record Declarations are not supported."); + TestUtils.assertProblems(result, "(line 1,col 1) Record Declarations are not supported. Pay attention that this feature is supported starting from 'JAVA_14' language level. If you need that feature the language level must be configured in the configuration before parsing the source files."); } } } diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java1_0ValidatorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java1_0ValidatorTest.java index 5d30263875..3e8e43790c 100644 --- a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java1_0ValidatorTest.java +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java1_0ValidatorTest.java @@ -42,8 +42,8 @@ class Java1_0ValidatorTest { void tryWithoutResources() { ParseResult result = javaParser.parse(STATEMENT, provider("try(X x=new Y()){}")); assertProblems(result, - "(line 1,col 1) Catch with resource is not supported.", - "(line 1,col 1) Try has no finally and no catch."); + "(line 1,col 1) Try has no finally and no catch. Pay attention that this feature is supported starting from 'JAVA_7' language level. If you need that feature the language level must be configured in the configuration before parsing the source files.", + "(line 1,col 1) Catch with resource is not supported. Pay attention that this feature is supported starting from 'JAVA_7' language level. If you need that feature the language level must be configured in the configuration before parsing the source files."); } @Test @@ -81,7 +81,7 @@ void leftHandAssignmentCannotBeEmptyBraces() { ParseResult result = javaParser.parse(EXPRESSION, provider("()=3")); assertProblems(result, "(line 1,col 1) Illegal left hand side of an assignment.", - "(line 1,col 1) Lambdas are not supported."); + "(line 1,col 1) Lambdas are not supported. Pay attention that this feature is supported starting from 'JAVA_8' language level. If you need that feature the language level must be configured in the configuration before parsing the source files."); } @Test @@ -93,19 +93,19 @@ void leftHandAssignmentCanBeInBraces() { @Test void noInnerClasses() { ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X{class Y{}}")); - assertProblems(result, "(line 1,col 9) inner classes or interfaces are not supported."); + assertProblems(result, "(line 1,col 9) inner classes or interfaces are not supported. Pay attention that this feature is supported starting from 'JAVA_1_1' language level. If you need that feature the language level must be configured in the configuration before parsing the source files."); } @Test void noReflection() { ParseResult result = javaParser.parse(EXPRESSION, provider("Abc.class")); - assertProblems(result, "(line 1,col 1) Reflection is not supported."); + assertProblems(result, "(line 1,col 1) Reflection is not supported. Pay attention that this feature is supported starting from 'JAVA_1_1' language level. If you need that feature the language level must be configured in the configuration before parsing the source files."); } @Test void noForEach() { ParseResult result = javaParser.parse(STATEMENT, provider("for(X x : xs){}")); - assertProblems(result, "(line 1,col 1) For-each loops are not supported."); + assertProblems(result, "(line 1,col 1) For-each loops are not supported. Pay attention that this feature is supported starting from 'JAVA_5' language level. If you need that feature the language level must be configured in the configuration before parsing the source files."); } @Test diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java1_1ValidatorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java1_1ValidatorTest.java index 5bf1a9f4d6..0359e25b2b 100644 --- a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java1_1ValidatorTest.java +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java1_1ValidatorTest.java @@ -293,8 +293,7 @@ void innerClasses() { @Test void localInterface() { ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X{ void x() {" + allModifiers + "interface I{}}}")); - assertProblems(result, "(line 1,col 20) There is no such thing as a local interface." - ); + assertProblems(result, "(line 1,col 20) There is no such thing as a local interface. Pay attention that this feature is supported starting from 'JAVA_16' language level. If you need that feature the language level must be configured in the configuration before parsing the source files."); } @Test diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java1_3ValidatorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java1_3ValidatorTest.java index c5b934ad68..ee359479d2 100644 --- a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java1_3ValidatorTest.java +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java1_3ValidatorTest.java @@ -38,6 +38,6 @@ class Java1_3ValidatorTest { @Test void noAssert() { ParseResult result = javaParser.parse(STATEMENT, provider("assert a;")); - assertProblems(result, "(line 1,col 1) 'assert' keyword is not supported."); + assertProblems(result, "(line 1,col 1) Record Declarations are not supported. Pay attention that this feature is supported starting from 'JAVA_14' language level. If you need that feature the language level must be configured in the configuration before parsing the source files."); } } diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java1_4ValidatorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java1_4ValidatorTest.java index 2cf73fb129..69fbf4dec4 100644 --- a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java1_4ValidatorTest.java +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java1_4ValidatorTest.java @@ -48,8 +48,8 @@ void yesAssert() { void noGenerics() { ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X{List b;}")); assertProblems(result, - "(line 1,col 12) Generics are not supported.", - "(line 1,col 1) Generics are not supported." + "(line 1,col 1) Generics are not supported. Pay attention that this feature is supported starting from 'JAVA_5' language level. If you need that feature the language level must be configured in the configuration before parsing the source files.", + "(line 1,col 12) Generics are not supported. Pay attention that this feature is supported starting from 'JAVA_5' language level. If you need that feature the language level must be configured in the configuration before parsing the source files." ); } @@ -57,30 +57,30 @@ void noGenerics() { void noAnnotations() { ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("@Abc @Def() @Ghi(a=3) @interface X{}")); assertProblems(result, - "(line 1,col 6) Annotations are not supported.", - "(line 1,col 13) Annotations are not supported.", - "(line 1,col 1) Annotations are not supported." + "(line 1,col 13) Annotations are not supported. Pay attention that this feature is supported starting from 'JAVA_5' language level. If you need that feature the language level must be configured in the configuration before parsing the source files.", + "(line 1,col 1) Annotations are not supported. Pay attention that this feature is supported starting from 'JAVA_5' language level. If you need that feature the language level must be configured in the configuration before parsing the source files.", + "(line 1,col 6) Annotations are not supported. Pay attention that this feature is supported starting from 'JAVA_5' language level. If you need that feature the language level must be configured in the configuration before parsing the source files." ); } @Test void novarargs() { ParseResult result = javaParser.parse(PARAMETER, provider("String... x")); - assertProblems(result, "(line 1,col 1) Varargs are not supported."); + assertProblems(result, "(line 1,col 1) Varargs are not supported. Pay attention that this feature is supported starting from 'JAVA_5' language level. If you need that feature the language level must be configured in the configuration before parsing the source files."); } @Test void noforeach() { ParseResult result = javaParser.parse(STATEMENT, provider("for(X x: xs){}")); - assertProblems(result, "(line 1,col 1) For-each loops are not supported."); + assertProblems(result, "(line 1,col 1) For-each loops are not supported. Pay attention that this feature is supported starting from 'JAVA_5' language level. If you need that feature the language level must be configured in the configuration before parsing the source files."); } @Test void staticImport() { ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("import static x;import static x.*;import x.X;import x.*;")); assertProblems(result, - "(line 1,col 17) Static imports are not supported.", - "(line 1,col 1) Static imports are not supported."); + "(line 1,col 1) Static imports are not supported. Pay attention that this feature is supported starting from 'JAVA_5' language level. If you need that feature the language level must be configured in the configuration before parsing the source files.", + "(line 1,col 17) Static imports are not supported. Pay attention that this feature is supported starting from 'JAVA_5' language level. If you need that feature the language level must be configured in the configuration before parsing the source files."); } @Test diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java5ValidatorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java5ValidatorTest.java index c76d0f6f40..ff8e5bb49c 100644 --- a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java5ValidatorTest.java +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java5ValidatorTest.java @@ -42,7 +42,7 @@ class Java5ValidatorTest { @Test void genericsWithoutDiamond() { ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X{List b = new ArrayList<>();}")); - assertProblems(result, "(line 1,col 33) The diamond operator is not supported."); + assertProblems(result, "(line 1,col 33) The diamond operator is not supported. Pay attention that this feature is supported starting from 'JAVA_7' language level. If you need that feature the language level must be configured in the configuration before parsing the source files."); } @Test diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java6ValidatorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java6ValidatorTest.java index dc672aec71..664c6dda5a 100644 --- a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java6ValidatorTest.java +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java6ValidatorTest.java @@ -52,6 +52,6 @@ void noUnderscoresInIntegerLiterals() { @Test void noMultiCatch() { ParseResult result = javaParser.parse(STATEMENT, provider("try{}catch(Abc|Def e){}")); - assertProblems(result, "(line 1,col 12) Multi-catch is not supported."); + assertProblems(result, "(line 1,col 12) Multi-catch is not supported. Pay attention that this feature is supported starting from 'JAVA_7' language level. If you need that feature the language level must be configured in the configuration before parsing the source files."); } } diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java7ValidatorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java7ValidatorTest.java index 26b9129369..a5f4a45a8a 100644 --- a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java7ValidatorTest.java +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java7ValidatorTest.java @@ -123,6 +123,6 @@ void multiCatchWithOneElement() { @Test void noLambdas() { ParseResult result = javaParser.parse(STATEMENT, provider("a(() -> 1);")); - assertProblems(result, "(line 1,col 3) Lambdas are not supported."); + assertProblems(result, "(line 1,col 3) Lambdas are not supported. Pay attention that this feature is supported starting from 'JAVA_8' language level. If you need that feature the language level must be configured in the configuration before parsing the source files."); } } diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java8ValidatorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java8ValidatorTest.java index 6570027a44..5384335096 100644 --- a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java8ValidatorTest.java +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java8ValidatorTest.java @@ -42,7 +42,7 @@ class Java8ValidatorTest { @Test void localInterface() { ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X {void a(){interface I{}};}")); - assertProblems(result, "(line 1,col 19) There is no such thing as a local interface."); + assertProblems(result, "(line 1,col 19) There is no such thing as a local interface. Pay attention that this feature is supported starting from 'JAVA_16' language level. If you need that feature the language level must be configured in the configuration before parsing the source files."); } @Test @@ -98,6 +98,6 @@ void lambdas() { @Test void noModules() { ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("open module x {}")); - assertProblems(result, "(line 1,col 1) Modules are not supported."); + assertProblems(result, "(line 1,col 1) Modules are not supported. Pay attention that this feature is supported starting from 'JAVA_9' language level. If you need that feature the language level must be configured in the configuration before parsing the source files."); } } From df08d055fce90b9f89ad760e3de911ab69f71ffd Mon Sep 17 00:00:00 2001 From: volodya-lombrozo Date: Sat, 9 Sep 2023 08:45:39 +0300 Subject: [PATCH 089/136] feat(#4075): repair all the test --- .../github/javaparser/ast/validator/Java15ValidatorTest.java | 2 +- .../github/javaparser/ast/validator/Java1_3ValidatorTest.java | 2 +- .../javaparser/symbolsolver/resolution/InstanceOfTest.java | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java15ValidatorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java15ValidatorTest.java index b9111bb7dc..11f295086e 100644 --- a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java15ValidatorTest.java +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java15ValidatorTest.java @@ -69,7 +69,7 @@ class RecordDeclarationForbidden { void recordDeclaration() { String s = "record X() { }"; ParseResult result = javaParser.parse(COMPILATION_UNIT, provider(s)); - TestUtils.assertProblems(result, "(line 1,col 1) Record Declarations are not supported."); + TestUtils.assertProblems(result, "(line 1,col 1) Record Declarations are not supported. Pay attention that this feature is supported starting from 'JAVA_14' language level. If you need that feature the language level must be configured in the configuration before parsing the source files."); } } } diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java1_3ValidatorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java1_3ValidatorTest.java index ee359479d2..c37e61a7e1 100644 --- a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java1_3ValidatorTest.java +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java1_3ValidatorTest.java @@ -38,6 +38,6 @@ class Java1_3ValidatorTest { @Test void noAssert() { ParseResult result = javaParser.parse(STATEMENT, provider("assert a;")); - assertProblems(result, "(line 1,col 1) Record Declarations are not supported. Pay attention that this feature is supported starting from 'JAVA_14' language level. If you need that feature the language level must be configured in the configuration before parsing the source files."); + assertProblems(result, "(line 1,col 1) 'assert' keyword is not supported. Pay attention that this feature is supported starting from 'JAVA_1_4' language level. If you need that feature the language level must be configured in the configuration before parsing the source files."); } } diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/InstanceOfTest.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/InstanceOfTest.java index 20cfd7c288..667ca576a5 100644 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/InstanceOfTest.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/InstanceOfTest.java @@ -228,7 +228,7 @@ public void givenInstanceOfPattern_usingJdk13_thenExpectException() { .parse(ParseStart.COMPILATION_UNIT, new StringProvider(x)); assertEquals(1, parseResult.getProblems().size()); - assertEquals("Use of patterns with instanceof is not supported.", parseResult.getProblem(0).getMessage()); + assertEquals("Use of patterns with instanceof is not supported. Pay attention that this feature is supported starting from 'JAVA_14' language level. If you need that feature the language level must be configured in the configuration before parsing the source files.", parseResult.getProblem(0).getMessage()); } @Nested From 6127499db2735325ad7503d15e5758ae3d840379 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 15 Sep 2023 18:12:48 +0000 Subject: [PATCH 090/136] chore(deps): update dependency org.apache.maven.plugins:maven-javadoc-plugin to v3.6.0 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index bc770cfb5b..b24fe29da2 100644 --- a/pom.xml +++ b/pom.xml @@ -275,7 +275,7 @@ org.apache.maven.plugins maven-javadoc-plugin - 3.5.0 + 3.6.0 ${java.version} From a61ada57c3b2c2045327f7ff4a569f95ca70fdba Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 19 Sep 2023 22:00:55 +0000 Subject: [PATCH 091/136] chore(deps): update dependency org.codehaus.mojo:versions-maven-plugin to v2.16.1 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index b24fe29da2..a83cb3de30 100644 --- a/pom.xml +++ b/pom.xml @@ -334,7 +334,7 @@ org.codehaus.mojo versions-maven-plugin - 2.16.0 + 2.16.1 false From 037d40af45cb35889d03897688879a7011bfd66b Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Fri, 22 Sep 2023 13:43:14 +0200 Subject: [PATCH 092/136] Fix: fix code marked as todo --- .../contexts/AbstractJavaParserContext.java | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/AbstractJavaParserContext.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/AbstractJavaParserContext.java index fc00797b6b..120af605d0 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/AbstractJavaParserContext.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/AbstractJavaParserContext.java @@ -101,17 +101,11 @@ public int hashCode() { public final Optional getParent() { Node parentNode = wrappedNode.getParentNode().orElse(null); - // TODO/FiXME: Document why the method call expression is treated differently. + // Resolution of the scope of the method call expression is delegated to parent + // context. if (parentNode instanceof MethodCallExpr) { MethodCallExpr parentCall = (MethodCallExpr) parentNode; - // TODO: Can this be replaced with: boolean found = parentCall.getArguments().contains(wrappedNode); - boolean found = false; - for (Expression expression : parentCall.getArguments()) { - if (expression == wrappedNode) { - found = true; - break; - } - } + boolean found = parentCall.getArguments().contains(wrappedNode); if (found) { Node notMethod = parentNode; while (notMethod instanceof MethodCallExpr) { @@ -121,7 +115,8 @@ public final Optional getParent() { } } Node notMethodNode = parentNode; - // to avoid an infinite loop if parent scope is the same as wrapped node + // To avoid loops JP must ensure that the scope of the parent context + // is not the same as the current node. while (notMethodNode instanceof MethodCallExpr || notMethodNode instanceof FieldAccessExpr || (notMethodNode != null && notMethodNode.hasScope() && getScope(notMethodNode).equals(wrappedNode)) ) { notMethodNode = notMethodNode.getParentNode().orElse(null); From dfbe16ceb36d4e12605e8c56c0f03363c45a48a7 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Fri, 22 Sep 2023 13:44:25 +0200 Subject: [PATCH 093/136] Fix: issue 3184 Unable to get the resolved type of class ResolvedReferenceType from T --- .../logic/MethodResolutionLogic.java | 5 ++- .../types/ResolvedReferenceType.java | 15 +++++---- .../JavaParserVariableDeclarationTest.java | 33 +++++++++---------- .../model/typesystem/ReferenceTypeTest.java | 2 +- .../MethodsResolutionLogicTest.java | 23 ++++++------- 5 files changed, 40 insertions(+), 38 deletions(-) diff --git a/javaparser-core/src/main/java/com/github/javaparser/resolution/logic/MethodResolutionLogic.java b/javaparser-core/src/main/java/com/github/javaparser/resolution/logic/MethodResolutionLogic.java index 081b1324cb..3df751545e 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/resolution/logic/MethodResolutionLogic.java +++ b/javaparser-core/src/main/java/com/github/javaparser/resolution/logic/MethodResolutionLogic.java @@ -347,7 +347,10 @@ private static boolean isAssignableMatchTypeParametersMatchingQName(ResolvedRefe if (actualParam.isWildcard() && !actualParam.asWildcard().isBounded()) { return true; } - return isAssignableMatchTypeParameters(expectedParam.asWildcard().getBoundedType(), actual, matchedParameters); + if (actualParam.isTypeVariable()) { + return matchTypeVariable(actualParam.asTypeVariable(), expectedParam.asWildcard().getBoundedType(), matchedParameters); + } + return isAssignableMatchTypeParameters(expectedParam.asWildcard().getBoundedType(), actualParam, matchedParameters); } // TODO verify super bound return true; diff --git a/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedReferenceType.java b/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedReferenceType.java index d7538b0421..506686cda8 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedReferenceType.java +++ b/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedReferenceType.java @@ -346,18 +346,19 @@ public String getId() { */ public abstract Set getDeclaredFields(); + /* + * A class or interface whose declaration has one or more type parameters is a + * generic class or interface [JLS, 8.1.2, 9.1.2]. For example, the List + * interface has a single type parameter, E, representing its element type. + * A raw type, is the name of the generic type used without any accompanying type + * parameters [JLS, 4.8]. For example, the raw type corresponding to List is + * List. + */ public boolean isRawType() { if (!typeDeclaration.getTypeParameters().isEmpty()) { if (typeParametersMap().isEmpty()) { return true; } - for (String name : typeParametersMap().getNames()) { - Optional value = typeParametersMap().getValueBySignature(name); - if (!value.isPresent() || !value.get().isTypeVariable() || !value.get().asTypeVariable().qualifiedName().equals(name)) { - return false; - } - } - return true; } return false; } diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserVariableDeclarationTest.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserVariableDeclarationTest.java index 1841ebd2b8..22bae2044e 100644 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserVariableDeclarationTest.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserVariableDeclarationTest.java @@ -21,8 +21,14 @@ package com.github.javaparser.symbolsolver.javaparsermodel.declarations; -import com.github.javaparser.ParserConfiguration; -import com.github.javaparser.StaticJavaParser; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.Optional; + +import org.junit.jupiter.api.Test; + +import com.github.javaparser.JavaParserAdapter; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.Node; import com.github.javaparser.ast.body.VariableDeclarator; @@ -30,17 +36,10 @@ import com.github.javaparser.resolution.declarations.AssociableToAST; import com.github.javaparser.resolution.declarations.ResolvedValueDeclaration; import com.github.javaparser.resolution.declarations.ResolvedValueDeclarationTest; -import com.github.javaparser.symbolsolver.JavaSymbolSolver; -import com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver; +import com.github.javaparser.symbolsolver.resolution.AbstractResolutionTest; import com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver; -import org.junit.jupiter.api.Test; -import java.util.List; -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -class JavaParserVariableDeclarationTest implements ResolvedValueDeclarationTest { +class JavaParserVariableDeclarationTest extends AbstractResolutionTest implements ResolvedValueDeclarationTest { @Override public Optional getWrappedDeclaration(AssociableToAST associableToAST) { @@ -52,8 +51,9 @@ public Optional getWrappedDeclaration(AssociableToAST associableToAST) { @Override public JavaParserVariableDeclaration createValue() { String code = "class A {a() {String s;}}"; - CompilationUnit compilationUnit = StaticJavaParser.parse(code); - VariableDeclarator variableDeclarator = compilationUnit.findFirst(VariableDeclarator.class).get(); + CompilationUnit cu = JavaParserAdapter.of( + createParserWithResolver(defaultTypeSolver())).parse(code); + VariableDeclarator variableDeclarator = cu.findFirst(VariableDeclarator.class).get(); ReflectionTypeSolver reflectionTypeSolver = new ReflectionTypeSolver(); return new JavaParserVariableDeclaration(variableDeclarator, reflectionTypeSolver); } @@ -80,11 +80,8 @@ void test3631() { + " }\n" + "}"; - ParserConfiguration configuration = new ParserConfiguration() - .setSymbolResolver(new JavaSymbolSolver(new CombinedTypeSolver(new ReflectionTypeSolver()))); - StaticJavaParser.setConfiguration(configuration); - - CompilationUnit cu = StaticJavaParser.parse(code); + CompilationUnit cu = JavaParserAdapter.of( + createParserWithResolver(defaultTypeSolver())).parse(code); List names = cu.findAll(NameExpr.class); ResolvedValueDeclaration rvd = names.get(3).resolve(); diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/model/typesystem/ReferenceTypeTest.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/model/typesystem/ReferenceTypeTest.java index 452a4ddab0..b7fdc66644 100644 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/model/typesystem/ReferenceTypeTest.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/model/typesystem/ReferenceTypeTest.java @@ -871,7 +871,7 @@ void erasure_rawtype() { ResolvedType rt = types.get(0); String expected = "A"; ResolvedType erasedType = rt.erasure(); - assertTrue(rt.asReferenceType().isRawType()); + assertFalse(rt.asReferenceType().isRawType()); assertTrue(erasedType.asReferenceType().typeParametersValues().isEmpty()); assertEquals(expected, erasedType.describe()); } diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/MethodsResolutionLogicTest.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/MethodsResolutionLogicTest.java index 4d3d644895..334482e134 100644 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/MethodsResolutionLogicTest.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/MethodsResolutionLogicTest.java @@ -21,6 +21,13 @@ package com.github.javaparser.symbolsolver.resolution; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.nio.file.Path; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import com.github.javaparser.resolution.MethodUsage; import com.github.javaparser.resolution.TypeSolver; import com.github.javaparser.resolution.logic.MethodResolutionLogic; @@ -32,12 +39,6 @@ import com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver; import com.github.javaparser.symbolsolver.utils.LeanParserConfiguration; import com.google.common.collect.ImmutableList; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.nio.file.Path; - -import static org.junit.jupiter.api.Assertions.assertEquals; class MethodsResolutionLogicTest extends AbstractResolutionTest { @@ -58,9 +59,9 @@ void compatibilityShouldConsiderAlsoTypeVariablesNegative() { JavaParserClassDeclaration constructorDeclaration = (JavaParserClassDeclaration) typeSolver.solveType("com.github.javaparser.ast.body.ConstructorDeclaration"); ResolvedReferenceType stringType = (ResolvedReferenceType) ReflectionFactory.typeUsageFor(String.class, typeSolver); - ResolvedReferenceType rawClassType = (ResolvedReferenceType) ReflectionFactory.typeUsageFor(Class.class, typeSolver); - assertEquals(true, rawClassType.isRawType()); - ResolvedReferenceType classOfStringType = (ResolvedReferenceType) rawClassType.replaceTypeVariables(rawClassType.getTypeDeclaration().get().getTypeParameters().get(0), stringType); + ResolvedReferenceType genericClassType = (ResolvedReferenceType) ReflectionFactory.typeUsageFor(Class.class, typeSolver); + assertEquals(false, genericClassType.isRawType()); + ResolvedReferenceType classOfStringType = (ResolvedReferenceType) genericClassType.replaceTypeVariables(genericClassType.getTypeDeclaration().get().getTypeParameters().get(0), stringType); MethodUsage mu = constructorDeclaration.getAllMethods().stream().filter(m -> m.getDeclaration().getSignature().equals("isThrows(java.lang.Class)")).findFirst().get(); assertEquals(false, MethodResolutionLogic.isApplicable(mu, "isThrows", ImmutableList.of(classOfStringType), typeSolver)); @@ -70,10 +71,10 @@ void compatibilityShouldConsiderAlsoTypeVariablesNegative() { void compatibilityShouldConsiderAlsoTypeVariablesRaw() { JavaParserClassDeclaration constructorDeclaration = (JavaParserClassDeclaration) typeSolver.solveType("com.github.javaparser.ast.body.ConstructorDeclaration"); - ResolvedReferenceType rawClassType = (ResolvedReferenceType) ReflectionFactory.typeUsageFor(Class.class, typeSolver); + ResolvedReferenceType genericClassType = (ResolvedReferenceType) ReflectionFactory.typeUsageFor(Class.class, typeSolver); MethodUsage mu = constructorDeclaration.getAllMethods().stream().filter(m -> m.getDeclaration().getSignature().equals("isThrows(java.lang.Class)")).findFirst().get(); - assertEquals(true, MethodResolutionLogic.isApplicable(mu, "isThrows", ImmutableList.of(rawClassType), typeSolver)); + assertEquals(true, MethodResolutionLogic.isApplicable(mu, "isThrows", ImmutableList.of(genericClassType.erasure()), typeSolver)); } @Test From c6c0d3244ce13b74f68455c355f363588ab07a35 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Fri, 22 Sep 2023 14:33:28 +0200 Subject: [PATCH 094/136] Add unit test --- .../symbolsolver/Issue3184Test.java | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100755 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3184Test.java diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3184Test.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3184Test.java new file mode 100755 index 0000000000..bbc30f22f3 --- /dev/null +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3184Test.java @@ -0,0 +1,50 @@ +package com.github.javaparser.symbolsolver; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; + +import org.junit.jupiter.api.Test; + +import com.github.javaparser.JavaParserAdapter; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.expr.ObjectCreationExpr; +import com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration; +import com.github.javaparser.resolution.declarations.ResolvedTypeParameterDeclaration; +import com.github.javaparser.resolution.types.ResolvedType; +import com.github.javaparser.symbolsolver.resolution.AbstractResolutionTest; +import com.github.javaparser.utils.Pair; + +public class Issue3184Test extends AbstractResolutionTest { + + @Test + void test() { + String code = "public class Program {\n" + + "\n" + + " public static class InnerClass {\n" + + " void method1() {\n" + + " new InnerClass();\n" + // Buggy + " }\n" + + " void method2() {\n" + + " new InnerClass();\n" + // OK + " new InnerClass();\n" + // Buggy + " }\n" + + " }\n" + + "}"; + + CompilationUnit cu = JavaParserAdapter.of(createParserWithResolver(defaultTypeSolver())).parse(code); + List objCrtExprs = cu.findAll(ObjectCreationExpr.class); + objCrtExprs.forEach(expr -> { + ResolvedType resRefType = expr.getType().resolve(); + ResolvedReferenceTypeDeclaration resRefTypeDecl = resRefType.asReferenceType().getTypeDeclaration().get(); + List resTypeParamsDecl = resRefTypeDecl.getTypeParameters(); + List> resTypeParamsDeclMap = resRefType.asReferenceType().getTypeParametersMap(); + assertFalse(resTypeParamsDecl.isEmpty()); + assertFalse(resTypeParamsDeclMap.isEmpty()); + for (Pair resTypeParamsDeclPair : resTypeParamsDeclMap) { + assertTrue(resTypeParamsDeclPair.b.isTypeVariable()); + } + }); + } +} From a6be10ec99623f989e079f3b1acadd056ea6d3c3 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 22 Sep 2023 18:23:35 +0000 Subject: [PATCH 095/136] chore(deps): update actions/checkout action to v4.1.0 --- .github/workflows/create_github_release.yml | 2 +- .github/workflows/maven_tests.yml | 4 ++-- .github/workflows/prepare_release_changelog.yml | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/create_github_release.yml b/.github/workflows/create_github_release.yml index d82ec1f420..84345779c7 100644 --- a/.github/workflows/create_github_release.yml +++ b/.github/workflows/create_github_release.yml @@ -13,7 +13,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout code - uses: actions/checkout@v4.0.0 + uses: actions/checkout@v4.1.0 - name: Create Release id: create_release diff --git a/.github/workflows/maven_tests.yml b/.github/workflows/maven_tests.yml index 1bc28720a2..64e43d228a 100644 --- a/.github/workflows/maven_tests.yml +++ b/.github/workflows/maven_tests.yml @@ -45,7 +45,7 @@ jobs: steps: ## Checkout the current version of the code from the repo. - name: Checkout latest code - uses: actions/checkout@v4.0.0 + uses: actions/checkout@v4.1.0 with: fetch-depth: "0" @@ -109,7 +109,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout latest code - uses: actions/checkout@v4.0.0 + uses: actions/checkout@v4.1.0 with: fetch-depth: "0" - name: Set up JDK 11 diff --git a/.github/workflows/prepare_release_changelog.yml b/.github/workflows/prepare_release_changelog.yml index b37083e6be..1c4519902a 100644 --- a/.github/workflows/prepare_release_changelog.yml +++ b/.github/workflows/prepare_release_changelog.yml @@ -15,7 +15,7 @@ jobs: # Check out current repository - name: Fetch Sources - uses: actions/checkout@v4.0.0 + uses: actions/checkout@v4.1.0 # Setup Java 11 environment for the next steps - name: Setup Java From 25139c9f1010f3063789b75c04471de90bd5cf8a Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 25 Sep 2023 16:47:35 +0000 Subject: [PATCH 096/136] chore(deps): update dependency org.jbehave:jbehave-core to v5.2.0 --- javaparser-core-testing-bdd/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javaparser-core-testing-bdd/pom.xml b/javaparser-core-testing-bdd/pom.xml index 1a6fd879b8..ca88a05e62 100644 --- a/javaparser-core-testing-bdd/pom.xml +++ b/javaparser-core-testing-bdd/pom.xml @@ -119,7 +119,7 @@ org.jbehave jbehave-core - 5.1.1 + 5.2.0 test From 83f4dbfd4e0778d4c1d93142f55ff55aab65d32d Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 2 Oct 2023 01:53:47 +0000 Subject: [PATCH 097/136] chore(deps): update dependency com.puppycrawl.tools:checkstyle to v10.12.4 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index a83cb3de30..82d1ecb442 100644 --- a/pom.xml +++ b/pom.xml @@ -352,7 +352,7 @@ com.puppycrawl.tools checkstyle - 10.12.3 + 10.12.4 From 387c4a7f10dc0634a03dc770e8e16a9cb2d0a7c9 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 4 Oct 2023 21:01:51 +0000 Subject: [PATCH 098/136] chore(deps): update dependency maven to v3.9.5 --- .mvn/wrapper/maven-wrapper.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties index ac184013fc..eacdc9ed17 100644 --- a/.mvn/wrapper/maven-wrapper.properties +++ b/.mvn/wrapper/maven-wrapper.properties @@ -14,5 +14,5 @@ # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.4/apache-maven-3.9.4-bin.zip +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.5/apache-maven-3.9.5-bin.zip wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar From f72119525b28ca4e858365a68a7cee0c9885a708 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 10 Oct 2023 23:50:43 +0000 Subject: [PATCH 099/136] chore(deps): bump com.google.guava:guava from 32.1.2-jre to 32.1.3-jre Bumps [com.google.guava:guava](https://github.com/google/guava) from 32.1.2-jre to 32.1.3-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 82d1ecb442..1597ac87a3 100644 --- a/pom.xml +++ b/pom.xml @@ -371,7 +371,7 @@ com.google.guava guava - 32.1.2-jre + 32.1.3-jre junit From 6fa0a76ac8727fd1ee8ba90d138a932c81a21ab5 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 10 Oct 2023 23:50:58 +0000 Subject: [PATCH 100/136] fix(deps): update dependency com.google.guava:guava to v32.1.3-jre --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 82d1ecb442..1597ac87a3 100644 --- a/pom.xml +++ b/pom.xml @@ -371,7 +371,7 @@ com.google.guava guava - 32.1.2-jre + 32.1.3-jre junit From 24627a59e1f1e39f132cc94900869acaeb4e177c Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Fri, 13 Oct 2023 09:48:10 +0200 Subject: [PATCH 101/136] Fix: issue 3673 isAssignableBy method StackOverflowError --- .../ResolvedReferenceTypeDeclaration.java | 4 +- .../JavaParserClassDeclaration.java | 2 +- .../JavaParserEnumDeclaration.java | 14 +++--- .../JavassistEnumDeclaration.java | 43 +++++++++++++++---- .../ReflectionEnumDeclaration.java | 36 +++++++++++++--- .../JavassistClassDeclarationTest.java | 11 +++++ 6 files changed, 84 insertions(+), 26 deletions(-) diff --git a/javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedReferenceTypeDeclaration.java b/javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedReferenceTypeDeclaration.java index dd17402924..d67e8e03c2 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedReferenceTypeDeclaration.java +++ b/javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedReferenceTypeDeclaration.java @@ -20,6 +20,7 @@ */ package com.github.javaparser.resolution.declarations; +import java.io.Serializable; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; @@ -36,7 +37,8 @@ public interface ResolvedReferenceTypeDeclaration extends ResolvedTypeDeclaration, ResolvedTypeParametrizable { String JAVA_LANG_ENUM = java.lang.Enum.class.getCanonicalName(); - + String JAVA_LANG_COMPARABLE = java.lang.Comparable.class.getCanonicalName(); + String JAVA_IO_SERIALIZABLE = Serializable.class.getCanonicalName(); String JAVA_LANG_OBJECT = java.lang.Object.class.getCanonicalName(); @Override diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserClassDeclaration.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserClassDeclaration.java index f65179f5da..3fee948158 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserClassDeclaration.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserClassDeclaration.java @@ -193,7 +193,7 @@ public Optional getSuperClass() { // If this is java.lang.Object, it has no super class. return Optional.empty(); } - if (wrappedNode.getExtendedTypes().isEmpty()) { + if (wrappedNode.getExtendedTypes().isEmpty()) { // All objects implicitly extend java.lang.Object -- inject it here (only when this isn't java.lang.Object) return Optional.of(object()); } diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserEnumDeclaration.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserEnumDeclaration.java index e5478c5e83..5358bef547 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserEnumDeclaration.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserEnumDeclaration.java @@ -21,6 +21,9 @@ package com.github.javaparser.symbolsolver.javaparsermodel.declarations; +import java.util.*; +import java.util.stream.Collectors; + import com.github.javaparser.ast.AccessSpecifier; import com.github.javaparser.ast.Node; import com.github.javaparser.ast.body.BodyDeclaration; @@ -48,10 +51,6 @@ import com.github.javaparser.symbolsolver.logic.AbstractTypeDeclaration; import com.github.javaparser.symbolsolver.reflectionmodel.ReflectionFactory; -import java.io.Serializable; -import java.util.*; -import java.util.stream.Collectors; - /** * @author Federico Tomassetti */ @@ -59,10 +58,6 @@ public class JavaParserEnumDeclaration extends AbstractTypeDeclaration implements ResolvedEnumDeclaration, MethodResolutionCapability, MethodUsageResolutionCapability, SymbolResolutionCapability { - private static String JAVA_LANG_ENUM = java.lang.Enum.class.getCanonicalName(); - private static String JAVA_LANG_COMPARABLE = java.lang.Comparable.class.getCanonicalName(); - private static String JAVA_IO_SERIALIZABLE = Serializable.class.getCanonicalName(); - private TypeSolver typeSolver; private EnumDeclaration wrappedNode; private JavaParserTypeAdapter javaParserTypeAdapter; @@ -380,7 +375,8 @@ public MethodUsage getUsage(Node node) { throw new UnsupportedOperationException(); } - public MethodUsage resolveTypeVariables(Context context, List parameterTypes) { + @Override + public MethodUsage resolveTypeVariables(Context context, List parameterTypes) { return new MethodUsage(this); } diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistEnumDeclaration.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistEnumDeclaration.java index 4548b99684..332a1e5071 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistEnumDeclaration.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistEnumDeclaration.java @@ -21,6 +21,12 @@ package com.github.javaparser.symbolsolver.javassistmodel; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + import com.github.javaparser.ast.AccessSpecifier; import com.github.javaparser.resolution.Context; import com.github.javaparser.resolution.MethodUsage; @@ -35,16 +41,11 @@ import com.github.javaparser.symbolsolver.core.resolution.SymbolResolutionCapability; import com.github.javaparser.symbolsolver.logic.AbstractTypeDeclaration; import com.github.javaparser.symbolsolver.resolution.SymbolSolver; + import javassist.CtClass; import javassist.CtField; import javassist.bytecode.AccessFlag; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - /** * @author Federico Tomassetti */ @@ -119,14 +120,37 @@ public Set getDeclaredMethods() { return javassistTypeDeclarationAdapter.getDeclaredMethods(); } + @Override + public boolean canBeAssignedTo(ResolvedReferenceTypeDeclaration other) { + String otherName = other.getQualifiedName(); + // Enums cannot be extended + if (otherName.equals(this.getQualifiedName())) { + return true; + } + if (otherName.equals(JAVA_LANG_ENUM)) { + return true; + } + // Enum implements Comparable and Serializable + if (otherName.equals(JAVA_LANG_COMPARABLE)) { + return true; + } + if (otherName.equals(JAVA_IO_SERIALIZABLE)) { + return true; + } + if (other.isJavaLangObject()) { + return true; + } + return false; + } + @Override public boolean isAssignableBy(ResolvedType type) { - throw new UnsupportedOperationException(); + return javassistTypeDeclarationAdapter.isAssignableBy(type); } @Override public boolean isAssignableBy(ResolvedReferenceTypeDeclaration other) { - throw new UnsupportedOperationException(); + return javassistTypeDeclarationAdapter.isAssignableBy(other); } @Override @@ -155,7 +179,8 @@ public SymbolReference solveMethod(String name, List< return JavassistUtils.solveMethod(name, argumentsTypes, staticOnly, typeSolver, this, ctClass); } - public Optional solveMethodAsUsage(String name, List argumentsTypes, + @Override + public Optional solveMethodAsUsage(String name, List argumentsTypes, Context invokationContext, List typeParameterValues) { return JavassistUtils.solveMethodAsUsage(name, argumentsTypes, typeSolver, invokationContext, typeParameterValues, this, ctClass); } diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionEnumDeclaration.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionEnumDeclaration.java index fec1caaa13..f18d7f7f1e 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionEnumDeclaration.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionEnumDeclaration.java @@ -21,6 +21,10 @@ package com.github.javaparser.symbolsolver.reflectionmodel; +import java.lang.reflect.Field; +import java.util.*; +import java.util.stream.Collectors; + import com.github.javaparser.ast.AccessSpecifier; import com.github.javaparser.resolution.Context; import com.github.javaparser.resolution.MethodUsage; @@ -37,10 +41,6 @@ import com.github.javaparser.symbolsolver.core.resolution.SymbolResolutionCapability; import com.github.javaparser.symbolsolver.logic.AbstractTypeDeclaration; -import java.lang.reflect.Field; -import java.util.*; -import java.util.stream.Collectors; - /** * @author Federico Tomassetti */ @@ -89,7 +89,7 @@ public ReflectionEnumDeclaration(Class clazz, TypeSolver typeSolver) { public AccessSpecifier accessSpecifier() { return ReflectionFactory.modifiersToAccessLevel(this.clazz.getModifiers()); } - + @Override public Optional containerType() { return reflectionClassAdapter.containerType(); @@ -144,6 +144,29 @@ public Set getDeclaredMethods() { return reflectionClassAdapter.getDeclaredMethods(); } + @Override + public boolean canBeAssignedTo(ResolvedReferenceTypeDeclaration other) { + String otherName = other.getQualifiedName(); + // Enums cannot be extended + if (otherName.equals(this.getQualifiedName())) { + return true; + } + if (otherName.equals(JAVA_LANG_ENUM)) { + return true; + } + // Enum implements Comparable and Serializable + if (otherName.equals(JAVA_LANG_COMPARABLE)) { + return true; + } + if (otherName.equals(JAVA_IO_SERIALIZABLE)) { + return true; + } + if (other.isJavaLangObject()) { + return true; + } + return false; + } + @Override public boolean isAssignableBy(ResolvedType type) { return reflectionClassAdapter.isAssignableBy(type); @@ -175,7 +198,8 @@ public SymbolReference solveMethod(String name, List< typeSolver,this, clazz); } - public Optional solveMethodAsUsage(String name, List parameterTypes, + @Override +public Optional solveMethodAsUsage(String name, List parameterTypes, Context invokationContext, List typeParameterValues) { Optional res = ReflectionMethodResolutionLogic.solveMethodAsUsage(name, parameterTypes, typeSolver, invokationContext, typeParameterValues, this, clazz); diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistClassDeclarationTest.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistClassDeclarationTest.java index 1b167ca664..9bda2de575 100644 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistClassDeclarationTest.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistClassDeclarationTest.java @@ -46,6 +46,7 @@ import com.github.javaparser.symbolsolver.logic.AbstractClassDeclaration; import com.github.javaparser.symbolsolver.logic.AbstractClassDeclarationTest; import com.github.javaparser.symbolsolver.logic.AbstractTypeDeclaration; +import com.github.javaparser.symbolsolver.reflectionmodel.ReflectionClassDeclaration; import com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver; import com.github.javaparser.symbolsolver.resolution.typesolvers.JarTypeSolver; import com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver; @@ -552,6 +553,16 @@ void whenInterfaceIsProvided() { assertFalse(classDeclaration.isAssignableBy(nodeWithImplements)); assertTrue(nodeWithImplements.isAssignableBy(classDeclaration)); } + + @Test + void issue3673() { + ReflectionClassDeclaration optionalDeclaration = (ReflectionClassDeclaration) typeSolver.solveType( + "java.util.Optional"); + JavassistEnumDeclaration enumDeclaration = (JavassistEnumDeclaration) anotherTypeSolver.solveType( + "com.github.javaparser.test.TestEnum"); + assertFalse(optionalDeclaration.isAssignableBy(enumDeclaration)); + assertFalse(enumDeclaration.isAssignableBy(optionalDeclaration)); + } } @Override From b87e88052f1c87609688df895c4566063947faa9 Mon Sep 17 00:00:00 2001 From: u7461674 Date: Sun, 15 Oct 2023 16:47:24 +1100 Subject: [PATCH 102/136] replace deprecated getConfiguration to getParserConfiguration --- .../symbolsolver/Issue1479Test.java | 40 +++++++------- .../AnalyseJavaSymbolSolver060Test.java | 2 +- .../resolution/AnnotationsResolutionTest.java | 2 +- .../AnonymousClassesResolutionTest.java | 4 +- .../CompilationUnitContextResolutionTest.java | 12 ++--- .../ConstructorsResolutionTest.java | 6 +-- .../resolution/EnumResolutionTest.java | 6 +-- .../FieldAccessExprResolutionTest.java | 2 +- .../resolution/FieldsResolutionTest.java | 10 ++-- ...plementedOrExtendedTypeResolutionTest.java | 12 ++--- .../MethodReferenceResolutionTest.java | 52 +++++++++---------- .../resolution/MethodsResolutionTest.java | 2 +- .../TypeResolutionWithSameNameTest.java | 14 ++--- 13 files changed, 82 insertions(+), 82 deletions(-) diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue1479Test.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue1479Test.java index 5b3ffe1aee..c41ede44c3 100644 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue1479Test.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue1479Test.java @@ -1,23 +1,23 @@ -/* - * Copyright (C) 2013-2023 The JavaParser Team. - * - * This file is part of JavaParser. - * - * JavaParser can be used either under the terms of - * a) the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * b) the terms of the Apache License - * - * You should have received a copy of both licenses in LICENCE.LGPL and - * LICENCE.APACHE. Please refer to those files for details. - * - * JavaParser is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - */ - +/* + * Copyright (C) 2013-2023 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + package com.github.javaparser.symbolsolver; import com.github.javaparser.StaticJavaParser; diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/AnalyseJavaSymbolSolver060Test.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/AnalyseJavaSymbolSolver060Test.java index 93d3312872..6eca1d0a10 100644 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/AnalyseJavaSymbolSolver060Test.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/AnalyseJavaSymbolSolver060Test.java @@ -92,7 +92,7 @@ private void parse(String projectName, String fileName) throws IOException { PrintStream outErr = new PrintStream(outErrStream); // set configuration to ignore comment - StaticJavaParser.getConfiguration().setAttributeComments(false); + StaticJavaParser.getParserConfiguration().setAttributeComments(false); sourceFileInfoExtractor.setOut(outErr); sourceFileInfoExtractor.setErr(outErr); diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/AnnotationsResolutionTest.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/AnnotationsResolutionTest.java index 33dca095da..0cd3c41f19 100644 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/AnnotationsResolutionTest.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/AnnotationsResolutionTest.java @@ -61,7 +61,7 @@ void configureSymbolSolver() throws IOException { CombinedTypeSolver typeSolver = new CombinedTypeSolver(); typeSolver.add(new ReflectionTypeSolver(false)); typeSolver.add(new JarTypeSolver(adaptPath("src/test/resources/junit-4.8.1.jar"))); - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(typeSolver)); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(typeSolver)); } @Test diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/AnonymousClassesResolutionTest.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/AnonymousClassesResolutionTest.java index c901d0f7c6..d9f547955f 100644 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/AnonymousClassesResolutionTest.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/AnonymousClassesResolutionTest.java @@ -54,13 +54,13 @@ static void configureSymbolSolver() throws IOException { cd); typeSolver.add(memoryTypeSolver); - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(typeSolver)); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(typeSolver)); } @AfterAll static void unConfigureSymbolSolver() { // unconfigure symbol solver so as not to potentially disturb tests in other classes - StaticJavaParser.getConfiguration().setSymbolResolver(null); + StaticJavaParser.getParserConfiguration().setSymbolResolver(null); } // See #1703 diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/CompilationUnitContextResolutionTest.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/CompilationUnitContextResolutionTest.java index a20db730ec..ae6cd5a53d 100644 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/CompilationUnitContextResolutionTest.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/CompilationUnitContextResolutionTest.java @@ -47,14 +47,14 @@ class CompilationUnitContextResolutionTest extends AbstractResolutionTest { @AfterEach void unConfigureSymbolSolver() { // unconfigure symbol solver so as not to potentially disturb tests in other classes - StaticJavaParser.getConfiguration().setSymbolResolver(null); + StaticJavaParser.getParserConfiguration().setSymbolResolver(null); } // in each case, the name itself doesn't matter -- we just want to assert that StackOverflowError wouldn't occur. @Test void solveMethodInReceiver() throws IOException { - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new CombinedTypeSolver( + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new CombinedTypeSolver( new ReflectionTypeSolver(), new JavaParserTypeSolver(adaptPath("src/test/resources/CompilationUnitContextResolutionTest/00_receiver"))))); @@ -66,7 +66,7 @@ void solveMethodInReceiver() throws IOException { @Test void solveMethodInParent() throws IOException { - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new CombinedTypeSolver( + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new CombinedTypeSolver( new ReflectionTypeSolver(), new JavaParserTypeSolver(adaptPath("src/test/resources/CompilationUnitContextResolutionTest/01_parent"))))); @@ -78,7 +78,7 @@ void solveMethodInParent() throws IOException { @Test void solveMethodInNested() throws IOException { - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new CombinedTypeSolver( + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new CombinedTypeSolver( new ReflectionTypeSolver(), new JavaParserTypeSolver(adaptPath("src/test/resources/CompilationUnitContextResolutionTest/02_nested"))))); @@ -90,7 +90,7 @@ void solveMethodInNested() throws IOException { @Test void solveSymbol() throws IOException { - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new CombinedTypeSolver( + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new CombinedTypeSolver( new ReflectionTypeSolver(), new JavaParserTypeSolver(adaptPath("src/test/resources/CompilationUnitContextResolutionTest/03_symbol"))))); @@ -102,7 +102,7 @@ void solveSymbol() throws IOException { @Test void solveMyself() throws IOException { - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new CombinedTypeSolver( + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new CombinedTypeSolver( new ReflectionTypeSolver(), new JavaParserTypeSolver(adaptPath("src/test/resources/CompilationUnitContextResolutionTest/04_reviewComment"))))); diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/ConstructorsResolutionTest.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/ConstructorsResolutionTest.java index 977189bf75..2e1b09dd2b 100644 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/ConstructorsResolutionTest.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/ConstructorsResolutionTest.java @@ -212,7 +212,7 @@ public void testIssue1436() { @Test void solveEnumConstructor() { // configure symbol solver before parsing - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); CompilationUnit cu = parseSample("ConstructorCallsEnum"); EnumDeclaration enumDeclaration = Navigator.demandEnum(cu, "ConstructorCallsEnum"); @@ -228,7 +228,7 @@ void solveEnumConstructor() { @Test void solveNonPublicParentConstructorReflection() { - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); CompilationUnit cu = parseSample("ReflectionTypeSolverConstructorResolution"); ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "ReflectionTypeSolverConstructionResolution"); @@ -247,7 +247,7 @@ void solveNonPublicParentConstructorReflection() { void testGenericParentContructorJavassist() throws IOException { Path pathToJar = adaptPath("src/test/resources/javassist_generics/generics.jar"); TypeSolver typeSolver = new CombinedTypeSolver(new JarTypeSolver(pathToJar), new ReflectionTypeSolver(true)); - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(typeSolver)); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(typeSolver)); CompilationUnit cu = parseSample("JarTypeSolverConstructorResolution"); ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "JarTypeSolverConstructionResolution"); diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/EnumResolutionTest.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/EnumResolutionTest.java index 15bec143ed..0f585ed972 100644 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/EnumResolutionTest.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/EnumResolutionTest.java @@ -78,7 +78,7 @@ void enumAndStaticInitializer() { void resolveEnumConstantAccess() { try { // configure symbol solver before parsing - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); // parse compilation unit and get field access expression CompilationUnit cu = parseSample("EnumFieldAccess"); @@ -105,7 +105,7 @@ void resolveEnumConstantAccess() { @Test void enumAccessSpecifier() { try { - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); CompilationUnit cu = parseSample("EnumAccessSpecifier"); ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "MyClass"); @@ -147,7 +147,7 @@ public void testResolveValueOfMethod() { " }\n" + "}"; TypeSolver typeSolver = new ReflectionTypeSolver(); - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(typeSolver)); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(typeSolver)); CompilationUnit cu = StaticJavaParser.parse(s); MethodCallExpr methodCallExpr = cu.findFirst(MethodCallExpr.class).get(); ResolvedMethodDeclaration rd = methodCallExpr.resolve(); diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/FieldAccessExprResolutionTest.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/FieldAccessExprResolutionTest.java index a599fdc473..df37a4a017 100644 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/FieldAccessExprResolutionTest.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/FieldAccessExprResolutionTest.java @@ -46,7 +46,7 @@ class FieldAccessExprResolutionTest extends AbstractResolutionTest { @BeforeEach void configureSymbolSolver() throws IOException { // configure symbol solver so as not to potentially disturb tests in other classes - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); } @Test diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/FieldsResolutionTest.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/FieldsResolutionTest.java index 003c7bd0c8..d7a345384c 100644 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/FieldsResolutionTest.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/FieldsResolutionTest.java @@ -127,7 +127,7 @@ void accessClassFieldThroughSuper() { @Test void resolveClassFieldThroughThis() { // configure symbol solver before parsing - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); // parse compilation unit and get field access expression CompilationUnit cu = parseSample("AccessClassMemberThroughThis"); @@ -149,7 +149,7 @@ void resolveClassFieldThroughThis() { @Test void resolveClassFieldThroughSuper() { // configure symbol solver before parsing - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); // parse compilation unit and get field access expression CompilationUnit cu = parseSample("AccessThroughSuper"); @@ -172,7 +172,7 @@ void resolveClassFieldThroughSuper() { @Test void resolveClassFieldOfClassExtendingUnknownClass1() { // configure symbol solver before parsing - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); // parse compilation unit and get field access expression CompilationUnit cu = parseSample("ClassExtendingUnknownClass"); @@ -194,7 +194,7 @@ void resolveClassFieldOfClassExtendingUnknownClass1() { @Test void resolveClassFieldOfClassExtendingUnknownClass2() { // configure symbol solver before parsing - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); // parse compilation unit and get field access expression CompilationUnit cu = parseSample("ClassExtendingUnknownClass"); @@ -216,7 +216,7 @@ void resolveClassFieldOfClassExtendingUnknownClass2() { @Test void resolveInheritedFieldFromInterface() { // configure symbol solver before parsing - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); // parse compilation unit and get field access expression CompilationUnit cu = parseSample("ReflectionTypeSolverFieldFromInterfaceResolution"); diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/ImplementedOrExtendedTypeResolutionTest.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/ImplementedOrExtendedTypeResolutionTest.java index 0c8d1deb70..cec7559b60 100644 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/ImplementedOrExtendedTypeResolutionTest.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/ImplementedOrExtendedTypeResolutionTest.java @@ -46,12 +46,12 @@ class ImplementedOrExtendedTypeResolutionTest extends AbstractResolutionTest { @AfterEach void unConfigureSymbolSolver() { // unconfigure symbol solver so as not to potentially disturb tests in other classes - StaticJavaParser.getConfiguration().setSymbolResolver(null); + StaticJavaParser.getParserConfiguration().setSymbolResolver(null); } @Test void solveImplementedTypes() { - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); CompilationUnit cu = parseSample("ImplementedOrExtendedTypeResolution/ImplementedOrExtendedTypeResolution"); ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "InterfaceTest"); @@ -62,7 +62,7 @@ void solveImplementedTypes() { @Test void solveExtendedType1() { - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); CompilationUnit cu = parseSample("ImplementedOrExtendedTypeResolution/ImplementedOrExtendedTypeResolution"); ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "ClassTest1"); @@ -71,7 +71,7 @@ void solveExtendedType1() { @Test void solveExtendedType2() { - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); CompilationUnit cu = parseSample("ImplementedOrExtendedTypeResolution/ImplementedOrExtendedTypeResolution"); ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "ClassTest2"); @@ -80,7 +80,7 @@ void solveExtendedType2() { @Test void solveExtendedType3() { - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); CompilationUnit cu = parseSample("ImplementedOrExtendedTypeResolution/ImplementedOrExtendedTypeResolution"); ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "ClassTest3"); @@ -89,7 +89,7 @@ void solveExtendedType3() { @Test void solveImplementedTypeWithSameName() throws IOException { - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver( + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver( new JavaParserTypeSolver(adaptPath("src/test/resources/ImplementedOrExtendedTypeResolution/pkg")))); CompilationUnit cu = StaticJavaParser.parse(adaptPath("src/test/resources/ImplementedOrExtendedTypeResolution/pkg/main/A.java")); diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/MethodReferenceResolutionTest.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/MethodReferenceResolutionTest.java index 4d3564427a..682c7bf3b3 100644 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/MethodReferenceResolutionTest.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/MethodReferenceResolutionTest.java @@ -49,7 +49,7 @@ class MethodReferenceResolutionTest extends AbstractResolutionTest { @Test void classMethod() { // configure symbol solver before parsing - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); // parse compilation unit and get method reference expression CompilationUnit cu = parseSample("MethodReferences"); @@ -68,7 +68,7 @@ void classMethod() { @Test void superclassMethodNotOverridden() { // configure symbol solver before parsing - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); // parse compilation unit and get method reference expression CompilationUnit cu = parseSample("MethodReferences"); @@ -87,7 +87,7 @@ void superclassMethodNotOverridden() { @Test void superclassMethodOverridden() { // configure symbol solver before parsing - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); // parse compilation unit and get method reference expression CompilationUnit cu = parseSample("MethodReferences"); @@ -106,7 +106,7 @@ void superclassMethodOverridden() { @Test void superclassMethodWithSubclassType() { // configure symbol solver before parsing - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); // parse compilation unit and get method reference expression CompilationUnit cu = parseSample("MethodReferences"); @@ -125,7 +125,7 @@ void superclassMethodWithSubclassType() { @Test void fieldAccessMethod() { // configure symbol solver before parsing - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); // parse compilation unit and get method reference expression CompilationUnit cu = parseSample("MethodReferences"); @@ -144,7 +144,7 @@ void fieldAccessMethod() { @Test void thisClassMethod() { // configure symbol solver before parsing - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); // parse compilation unit and get method reference expression CompilationUnit cu = parseSample("MethodReferences"); @@ -163,7 +163,7 @@ void thisClassMethod() { @Test void superclassMethod() { // configure symbol solver before parsing - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); // parse compilation unit and get method reference expression CompilationUnit cu = parseSample("MethodReferences"); @@ -182,7 +182,7 @@ void superclassMethod() { @Test void instanceMethod() { // configure symbol solver before parsing - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); // parse compilation unit and get method reference expression CompilationUnit cu = parseSample("MethodReferences"); @@ -201,7 +201,7 @@ void instanceMethod() { @Test void staticMethod() { // configure symbol solver before parsing - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); // parse compilation unit and get method reference expression CompilationUnit cu = parseSample("MethodReferences"); @@ -220,7 +220,7 @@ void staticMethod() { @Test void biFunction() { // configure symbol solver before parsing - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); // parse compilation unit and get method reference expression CompilationUnit cu = parseSample("MethodReferences"); @@ -239,7 +239,7 @@ void biFunction() { @Test void customTriFunction() { // configure symbol solver before parsing - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); // parse compilation unit and get method reference expression CompilationUnit cu = parseSample("MethodReferences"); @@ -258,7 +258,7 @@ void customTriFunction() { @Test void consumerDeclaredInMethod() { // configure symbol solver before parsing - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); // parse compilation unit and get method reference expression CompilationUnit cu = parseSample("MethodReferences"); @@ -276,7 +276,7 @@ void consumerDeclaredInMethod() { @Test void functionDeclaredInMethod() { // configure symbol solver before parsing - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); // parse compilation unit and get method reference expression CompilationUnit cu = parseSample("MethodReferences"); @@ -294,7 +294,7 @@ void functionDeclaredInMethod() { @Test void biFunctionDeclaredInMethod() { // configure symbol solver before parsing - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); // parse compilation unit and get method reference expression CompilationUnit cu = parseSample("MethodReferences"); @@ -312,7 +312,7 @@ void biFunctionDeclaredInMethod() { @Test void consumerUsedInStream() { // configure symbol solver before parsing - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); // parse compilation unit and get method reference expression CompilationUnit cu = parseSample("MethodReferences"); @@ -330,7 +330,7 @@ void consumerUsedInStream() { @Test void functionUsedInStream() { // configure symbol solver before parsing - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); // parse compilation unit and get method reference expression CompilationUnit cu = parseSample("MethodReferences"); @@ -348,7 +348,7 @@ void functionUsedInStream() { @Test void biFunctionUsedInStream() { // configure symbol solver before parsing - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); // parse compilation unit and get method reference expression CompilationUnit cu = parseSample("MethodReferences"); @@ -366,7 +366,7 @@ void biFunctionUsedInStream() { @Test void biFunctionInMethodCall() { // configure symbol solver before parsing - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); // parse compilation unit and get method reference expression CompilationUnit cu = parseSample("MethodReferences"); @@ -399,7 +399,7 @@ public void resolveOverloadedMethodReference() { " }\n" + "}"; TypeSolver typeSolver = new ReflectionTypeSolver(); - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(typeSolver)); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(typeSolver)); CompilationUnit cu = StaticJavaParser.parse(s); ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "StreamTest"); @@ -437,7 +437,7 @@ public void issue2657Test_StringValueOfInStream() { "}"; TypeSolver typeSolver = new ReflectionTypeSolver(); - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(typeSolver)); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(typeSolver)); CompilationUnit cu = StaticJavaParser.parse(s); int errorCount = 0; @@ -474,7 +474,7 @@ public void instanceMethodReferenceTest() { " }\n" + "}\n"; TypeSolver typeSolver = new ReflectionTypeSolver(false); - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(typeSolver)); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(typeSolver)); CompilationUnit cu = StaticJavaParser.parse(s); Set methodCallExpr = new HashSet<>(cu.findAll(MethodCallExpr.class)); @@ -516,7 +516,7 @@ public void unboundNonStaticMethodsTest() { "}"; TypeSolver typeSolver = new ReflectionTypeSolver(false); - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(typeSolver)); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(typeSolver)); CompilationUnit cu = StaticJavaParser.parse(s); Set methodCallExpr = new HashSet<>(cu.findAll(MethodCallExpr.class)); @@ -549,7 +549,7 @@ public void testIssue3289() { "}\n"; TypeSolver typeSolver = new ReflectionTypeSolver(); - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(typeSolver)); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(typeSolver)); CompilationUnit cu = StaticJavaParser.parse(code); int errorCount = 0; @@ -570,7 +570,7 @@ public void testIssue3289() { @Disabled(value = "Waiting for constructor calls to be resolvable") void zeroArgumentConstructor_resolveToDeclaration() { // configure symbol solver before parsing - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); // parse compilation unit and get method reference expression CompilationUnit cu = parseSample("MethodReferences"); @@ -589,7 +589,7 @@ void zeroArgumentConstructor_resolveToDeclaration() { @Test void zeroArgumentConstructor() { // configure symbol solver before parsing - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); // parse compilation unit and get method reference expression CompilationUnit cu = parseSample("MethodReferences"); @@ -607,7 +607,7 @@ void zeroArgumentConstructor() { @Test void singleArgumentConstructor() { // configure symbol solver before parsing - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); // parse compilation unit and get method reference expression CompilationUnit cu = parseSample("MethodReferences"); diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/MethodsResolutionTest.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/MethodsResolutionTest.java index bff581beb1..94db902823 100644 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/MethodsResolutionTest.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/MethodsResolutionTest.java @@ -61,7 +61,7 @@ void resetConfiguration() { @Test void testConsistentMethodResultion() { Log.setAdapter(new Log.StandardOutStandardErrorAdapter()); - StaticJavaParser.getConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver())); CompilationUnit cu = parseSample("PlatformTestUtil"); ClassOrInterfaceDeclaration classDeclaration = Navigator.demandClass(cu, "PlatformTestUtil"); diff --git a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/TypeResolutionWithSameNameTest.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/TypeResolutionWithSameNameTest.java index de83869e8b..03140dd7e3 100644 --- a/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/TypeResolutionWithSameNameTest.java +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/TypeResolutionWithSameNameTest.java @@ -54,7 +54,7 @@ void testTypesWithSameNameInPackageAndNested_directExtends() throws IOException JavaParserTypeSolver javaParserTypeSolver = new JavaParserTypeSolver(srcRootPath); StaticJavaParser - .getConfiguration() + .getParserConfiguration() .setSymbolResolver(new JavaSymbolSolver(javaParserTypeSolver)); CompilationUnit cu = StaticJavaParser.parse(extendsTypePath); @@ -84,7 +84,7 @@ void testTypesWithSameNameInPackageAndNested_directImplements() throws IOExcepti JavaParserTypeSolver javaParserTypeSolver = new JavaParserTypeSolver(srcRootPath); StaticJavaParser - .getConfiguration() + .getParserConfiguration() .setSymbolResolver(new JavaSymbolSolver(javaParserTypeSolver)); CompilationUnit cu = StaticJavaParser.parse(implementingTypePath); @@ -109,7 +109,7 @@ void testTypesWithSameNameStaticNonTypeAndNonStaticType() throws IOException { JavaParserTypeSolver javaParserTypeSolver = new JavaParserTypeSolver(srcRootPath); StaticJavaParser - .getConfiguration() + .getParserConfiguration() .setSymbolResolver(new JavaSymbolSolver(javaParserTypeSolver)); CompilationUnit cu = StaticJavaParser.parse(mainPath); @@ -127,7 +127,7 @@ void testTypesWithSameNameSingleTypeImportAndPackage() throws IOException { JavaParserTypeSolver javaParserTypeSolver = new JavaParserTypeSolver(srcRootPath); StaticJavaParser - .getConfiguration() + .getParserConfiguration() .setSymbolResolver(new JavaSymbolSolver(javaParserTypeSolver)); CompilationUnit cu = StaticJavaParser.parse(mainPath); @@ -145,7 +145,7 @@ void testTypesWithSameNamePackageAndAsteriskImport() throws IOException { JavaParserTypeSolver javaParserTypeSolver = new JavaParserTypeSolver(srcRootPath); StaticJavaParser - .getConfiguration() + .getParserConfiguration() .setSymbolResolver(new JavaSymbolSolver(javaParserTypeSolver)); CompilationUnit cu = StaticJavaParser.parse(mainPath); @@ -163,7 +163,7 @@ void testTypesWithSameNameAsteriskImportAndJavaLang() throws IOException { JavaParserTypeSolver javaParserTypeSolver = new JavaParserTypeSolver(srcRootPath); StaticJavaParser - .getConfiguration() + .getParserConfiguration() .setSymbolResolver(new JavaSymbolSolver(javaParserTypeSolver)); CompilationUnit cu = StaticJavaParser.parse(mainPath); @@ -191,7 +191,7 @@ void testTypesWithSameNameInPackageAndNestedMethodDeclaration() { "}\n"; StaticJavaParser - .getConfiguration() + .getParserConfiguration() .setSymbolResolver(new JavaSymbolSolver(new ReflectionTypeSolver(false))); CompilationUnit cu = StaticJavaParser.parse(code); From 4943085e2aff866e5878cb521612834ed73b002d Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 16 Oct 2023 16:42:38 +0000 Subject: [PATCH 103/136] chore(deps): update dependency org.jacoco:jacoco-maven-plugin to v0.8.11 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 1597ac87a3..7c66d2f286 100644 --- a/pom.xml +++ b/pom.xml @@ -270,7 +270,7 @@ org.jacoco jacoco-maven-plugin - 0.8.10 + 0.8.11 org.apache.maven.plugins From 82ee5b160f19fcb9a62c61d708e54f3854f3cc8a Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 17 Oct 2023 03:39:41 +0000 Subject: [PATCH 104/136] chore(deps): update dependency com.squareup.okhttp3:okhttp to v4.12.0 --- javaparser-core-testing/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javaparser-core-testing/pom.xml b/javaparser-core-testing/pom.xml index a894e9ab83..9c2716ed38 100644 --- a/javaparser-core-testing/pom.xml +++ b/javaparser-core-testing/pom.xml @@ -131,7 +131,7 @@ com.squareup.okhttp3 okhttp - 4.11.0 + 4.12.0 test From 0ed2a4bad27f1a8dc065548d3c7063325d7287e4 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 17 Oct 2023 16:57:51 +0000 Subject: [PATCH 105/136] chore(deps): update actions/checkout action to v4.1.1 --- .github/workflows/create_github_release.yml | 2 +- .github/workflows/maven_tests.yml | 4 ++-- .github/workflows/prepare_release_changelog.yml | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/create_github_release.yml b/.github/workflows/create_github_release.yml index 84345779c7..80ed0e35cf 100644 --- a/.github/workflows/create_github_release.yml +++ b/.github/workflows/create_github_release.yml @@ -13,7 +13,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout code - uses: actions/checkout@v4.1.0 + uses: actions/checkout@v4.1.1 - name: Create Release id: create_release diff --git a/.github/workflows/maven_tests.yml b/.github/workflows/maven_tests.yml index 64e43d228a..7822dc4d08 100644 --- a/.github/workflows/maven_tests.yml +++ b/.github/workflows/maven_tests.yml @@ -45,7 +45,7 @@ jobs: steps: ## Checkout the current version of the code from the repo. - name: Checkout latest code - uses: actions/checkout@v4.1.0 + uses: actions/checkout@v4.1.1 with: fetch-depth: "0" @@ -109,7 +109,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout latest code - uses: actions/checkout@v4.1.0 + uses: actions/checkout@v4.1.1 with: fetch-depth: "0" - name: Set up JDK 11 diff --git a/.github/workflows/prepare_release_changelog.yml b/.github/workflows/prepare_release_changelog.yml index 1c4519902a..1a233d631d 100644 --- a/.github/workflows/prepare_release_changelog.yml +++ b/.github/workflows/prepare_release_changelog.yml @@ -15,7 +15,7 @@ jobs: # Check out current repository - name: Fetch Sources - uses: actions/checkout@v4.1.0 + uses: actions/checkout@v4.1.1 # Setup Java 11 environment for the next steps - name: Setup Java From 570f1d070e1d5f717530a02178793b507d41a3bf Mon Sep 17 00:00:00 2001 From: Luciano Barcellos Date: Tue, 17 Oct 2023 15:42:46 -0300 Subject: [PATCH 106/136] Avoid use of temporary lists --- .../github/javaparser/printer/XmlPrinter.java | 70 ++++++++++++------- 1 file changed, 45 insertions(+), 25 deletions(-) diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/XmlPrinter.java b/javaparser-core/src/main/java/com/github/javaparser/printer/XmlPrinter.java index 8ea0feff31..d235619a9d 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/XmlPrinter.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/XmlPrinter.java @@ -28,7 +28,7 @@ import java.util.List; import static com.github.javaparser.utils.Utils.assertNotNull; -import static java.util.stream.Collectors.toList; +import java.util.function.Predicate; /** * Outputs an XML file containing the AST meant for inspecting it. @@ -51,35 +51,55 @@ public void output(Node node, String name, int level, StringBuilder builder) { assertNotNull(node); NodeMetaModel metaModel = node.getMetaModel(); List allPropertyMetaModels = metaModel.getAllPropertyMetaModels(); - List attributes = allPropertyMetaModels.stream().filter(PropertyMetaModel::isAttribute).filter(PropertyMetaModel::isSingular).collect(toList()); - List subNodes = allPropertyMetaModels.stream().filter(PropertyMetaModel::isNode).filter(PropertyMetaModel::isSingular).collect(toList()); - List subLists = allPropertyMetaModels.stream().filter(PropertyMetaModel::isNodeList).collect(toList()); + Predicate nonNullNode = propertyMetaModel -> propertyMetaModel.getValue(node) != null; + Predicate nonEmptyList = propertyMetaModel -> + ((NodeList) propertyMetaModel.getValue(node)).isNonEmpty(); + builder.append("<").append(name); + + // Output node type attribute if (outputNodeType) { builder.append(attribute("type", metaModel.getTypeName())); } - for (PropertyMetaModel attributeMetaModel : attributes) { - builder.append(attribute(attributeMetaModel.getName(), attributeMetaModel.getValue(node).toString())); - } + + // Output attributes + allPropertyMetaModels.stream() + .filter(PropertyMetaModel::isAttribute) + .filter(PropertyMetaModel::isSingular) + .forEach(attributeMetaModel -> { + final String attributeName = attributeMetaModel.getName(); + final String attributeValue = attributeMetaModel.getValue(node).toString(); + builder.append(attribute(attributeName, attributeValue)); + }); + builder.append(">"); - for (PropertyMetaModel subNodeMetaModel : subNodes) { - Node value = (Node) subNodeMetaModel.getValue(node); - if (value != null) { - output(value, subNodeMetaModel.getName(), level + 1, builder); - } - } - for (PropertyMetaModel subListMetaModel : subLists) { - NodeList subList = (NodeList) subListMetaModel.getValue(node); - if (subList != null && !subList.isEmpty()) { - String listName = subListMetaModel.getName(); - builder.append("<").append(listName).append(">"); - String singular = listName.substring(0, listName.length() - 1); - for (Node subListNode : subList) { - output(subListNode, singular, level + 1, builder); - } - builder.append(close(listName)); - } - } + + // Output singular subNodes + allPropertyMetaModels.stream() + .filter(PropertyMetaModel::isNode) + .filter(PropertyMetaModel::isSingular) + .filter(nonNullNode) + .forEach(subNodeMetaModel -> { + final Node subNode = (Node) subNodeMetaModel.getValue(node); + final String subNodeName = subNodeMetaModel.getName(); + output(subNode, subNodeName, level + 1, builder); + }); + + // Output list subNodes + allPropertyMetaModels.stream() + .filter(PropertyMetaModel::isNodeList) + .filter(nonNullNode) + .filter(nonEmptyList) + .forEach(listMetaModel -> { + final String listName = listMetaModel.getName(); + String singular = listName.substring(0, listName.length() - 1); + NodeList nodeList = (NodeList) listMetaModel.getValue(node); + builder.append("<").append(listName).append(">"); + for (Node subNode : nodeList) { + output(subNode, singular, level + 1, builder); + } + builder.append(close(listName)); + }); builder.append(close(name)); } From 687abcdc88b20b7e7c1e94f565b85ee66abf33c6 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Thu, 19 Oct 2023 17:38:20 +0200 Subject: [PATCH 107/136] Fix: issue 4163 Calling MethodDeclaration.getDeclarationAsString leads to MethodDelaration.getComment returning no comment --- .../lexicalpreservation/Issue4163Test.java | 75 +++++++++++++++++++ .../java/com/github/javaparser/ast/Node.java | 2 - .../ast/body/CallableDeclaration.java | 48 +++++++----- .../body/CompactConstructorDeclaration.java | 42 +++++++---- .../ast/body/ConstructorDeclaration.java | 20 ++--- .../ast/body/MethodDeclaration.java | 31 ++++---- 6 files changed, 159 insertions(+), 59 deletions(-) create mode 100755 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue4163Test.java diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue4163Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue4163Test.java new file mode 100755 index 0000000000..55785a4ee9 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue4163Test.java @@ -0,0 +1,75 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2023 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.printer.lexicalpreservation; + +import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol; + +import org.junit.jupiter.api.Test; + +import com.github.javaparser.StaticJavaParser; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.visitor.VoidVisitorAdapter; +import com.github.javaparser.printer.DefaultPrettyPrinter; +import com.github.javaparser.printer.Printer; +import com.github.javaparser.printer.configuration.DefaultConfigurationOption; +import com.github.javaparser.printer.configuration.DefaultPrinterConfiguration; +import com.github.javaparser.printer.configuration.DefaultPrinterConfiguration.ConfigOption; +import com.github.javaparser.printer.configuration.PrinterConfiguration; + +public class Issue4163Test extends AbstractLexicalPreservingTest { + + @Test + void test() { + VoidVisitorAdapter visitor = new VoidVisitorAdapter() { + @Override + public void visit(MethodDeclaration n, Object arg) { + System.out.println(n.getDeclarationAsString(true, true, true)); + System.out.println(n.getComment()); + } + }; + String code = + "class Foo {\n" + + " /*\n" + + " * comment\n" + + " */\n" + + " void m() {}\n" + + " }"; + + // setup pretty printer to print comments + PrinterConfiguration config = new DefaultPrinterConfiguration() + .addOption(new DefaultConfigurationOption(ConfigOption.PRINT_COMMENTS)); + Printer printer = new DefaultPrettyPrinter(config); + CompilationUnit cu = StaticJavaParser.parse(code); + MethodDeclaration md = cu.findFirst(MethodDeclaration.class).get(); + + // expected result is + String expected = md.getComment().get().asString()+"\n"; + + // set the new pretty printer in the compilation unit + cu.printer(printer); + // visit the MethodDeclaration node + visitor.visit(cu, null); + // checks that the comment is printed after executing the getDeclarationAsString method + assertEqualsStringIgnoringEol(expected, md.getComment().get().toString()); + } +} diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/Node.java b/javaparser-core/src/main/java/com/github/javaparser/ast/Node.java index b4fdaa020f..1f35979da5 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/Node.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/Node.java @@ -153,8 +153,6 @@ public enum Parsedness { // usefull to find if the node is a phantom node private static final int LEVELS_TO_EXPLORE = 3; - protected static final PrinterConfiguration prettyPrinterNoCommentsConfiguration = new DefaultPrinterConfiguration().removeOption(new DefaultConfigurationOption(ConfigOption.PRINT_COMMENTS)); - @InternalProperty private Range range; diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/body/CallableDeclaration.java b/javaparser-core/src/main/java/com/github/javaparser/ast/body/CallableDeclaration.java index 4ee92a5b10..328dbd3b97 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/body/CallableDeclaration.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/body/CallableDeclaration.java @@ -20,6 +20,14 @@ */ package com.github.javaparser.ast.body; +import static com.github.javaparser.utils.Utils.assertNotNull; +import static java.util.stream.Collectors.joining; +import static java.util.stream.Collectors.toList; + +import java.util.List; +import java.util.Optional; +import java.util.function.Consumer; + import com.github.javaparser.TokenRange; import com.github.javaparser.ast.*; import com.github.javaparser.ast.expr.AnnotationExpr; @@ -36,14 +44,6 @@ import com.github.javaparser.metamodel.JavaParserMetaModel; import com.github.javaparser.metamodel.OptionalProperty; -import java.util.List; -import java.util.Optional; -import java.util.function.Consumer; - -import static com.github.javaparser.utils.Utils.assertNotNull; -import static java.util.stream.Collectors.joining; -import static java.util.stream.Collectors.toList; - /** * Represents a declaration which is callable eg. a method or a constructor. */ @@ -88,12 +88,14 @@ public CallableDeclaration(TokenRange tokenRange, NodeList modifiers, * @return modifiers * @see Modifier */ - @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") + @Override + @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public NodeList getModifiers() { return modifiers; } - @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") + @Override + @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") @SuppressWarnings("unchecked") public T setModifiers(final NodeList modifiers) { assertNotNull(modifiers); @@ -108,12 +110,14 @@ public T setModifiers(final NodeList modifiers) { return (T) this; } - @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") + @Override + @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public SimpleName getName() { return name; } - @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") + @Override + @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") @SuppressWarnings("unchecked") public T setName(final SimpleName name) { assertNotNull(name); @@ -128,12 +132,14 @@ public T setName(final SimpleName name) { return (T) this; } - @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") + @Override + @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public NodeList getParameters() { return parameters; } - @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") + @Override + @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") @SuppressWarnings("unchecked") public T setParameters(final NodeList parameters) { assertNotNull(parameters); @@ -148,12 +154,14 @@ public T setParameters(final NodeList parameters) { return (T) this; } - @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") + @Override + @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public NodeList getThrownExceptions() { return thrownExceptions; } - @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") + @Override + @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") @SuppressWarnings("unchecked") public T setThrownExceptions(final NodeList thrownExceptions) { assertNotNull(thrownExceptions); @@ -168,12 +176,14 @@ public T setThrownExceptions(final NodeList thrownExceptions) { return (T) this; } - @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") + @Override + @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public NodeList getTypeParameters() { return typeParameters; } - @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") + @Override + @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") @SuppressWarnings("unchecked") public T setTypeParameters(final NodeList typeParameters) { assertNotNull(typeParameters); @@ -199,7 +209,7 @@ protected String appendThrowsIfRequested(boolean includingThrows) { } else { sb.append(", "); } - sb.append(thr.toString(prettyPrinterNoCommentsConfiguration)); + sb.append(thr); } } return sb.toString(); diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/body/CompactConstructorDeclaration.java b/javaparser-core/src/main/java/com/github/javaparser/ast/body/CompactConstructorDeclaration.java index cffaf44929..e710ddfd59 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/body/CompactConstructorDeclaration.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/body/CompactConstructorDeclaration.java @@ -20,6 +20,11 @@ */ package com.github.javaparser.ast.body; +import static com.github.javaparser.utils.Utils.assertNotNull; + +import java.util.Optional; +import java.util.function.Consumer; + import com.github.javaparser.TokenRange; import com.github.javaparser.ast.*; import com.github.javaparser.ast.expr.AnnotationExpr; @@ -38,11 +43,6 @@ import com.github.javaparser.resolution.Resolvable; import com.github.javaparser.resolution.declarations.ResolvedConstructorDeclaration; -import java.util.Optional; -import java.util.function.Consumer; - -import static com.github.javaparser.utils.Utils.assertNotNull; - /** *

The record declaration's constructor

* WARNING: This implementation is subject to change. @@ -121,7 +121,8 @@ public void accept(final VoidVisitor v, final A arg) { v.visit(this, arg); } - @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") + @Override + @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public BlockStmt getBody() { return body; } @@ -132,7 +133,8 @@ public BlockStmt getBody() { * @param body the body, can not be null * @return this, the ConstructorDeclaration */ - @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") + @Override + @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public CompactConstructorDeclaration setBody(final BlockStmt body) { assertNotNull(body); if (body == this.body) { @@ -146,12 +148,14 @@ public CompactConstructorDeclaration setBody(final BlockStmt body) { return this; } - @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") + @Override + @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public NodeList getModifiers() { return modifiers; } - @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") + @Override + @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public CompactConstructorDeclaration setModifiers(final NodeList modifiers) { assertNotNull(modifiers); if (modifiers == this.modifiers) { @@ -165,12 +169,14 @@ public CompactConstructorDeclaration setModifiers(final NodeList modif return this; } - @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") + @Override + @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public SimpleName getName() { return name; } - @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") + @Override + @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public CompactConstructorDeclaration setName(final SimpleName name) { assertNotNull(name); if (name == this.name) { @@ -184,12 +190,14 @@ public CompactConstructorDeclaration setName(final SimpleName name) { return this; } - @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") + @Override + @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public NodeList getThrownExceptions() { return thrownExceptions; } - @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") + @Override + @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public CompactConstructorDeclaration setThrownExceptions(final NodeList thrownExceptions) { assertNotNull(thrownExceptions); if (thrownExceptions == this.thrownExceptions) { @@ -203,12 +211,14 @@ public CompactConstructorDeclaration setThrownExceptions(final NodeList getTypeParameters() { return typeParameters; } - @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") + @Override + @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public CompactConstructorDeclaration setTypeParameters(final NodeList typeParameters) { assertNotNull(typeParameters); if (typeParameters == this.typeParameters) { @@ -252,7 +262,7 @@ protected String appendThrowsIfRequested(boolean includingThrows) { } else { sb.append(", "); } - sb.append(thr.toString(prettyPrinterNoCommentsConfiguration)); + sb.append(thr); } } return sb.toString(); diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/body/ConstructorDeclaration.java b/javaparser-core/src/main/java/com/github/javaparser/ast/body/ConstructorDeclaration.java index c16619a80a..f8d8d96c4b 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/body/ConstructorDeclaration.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/body/ConstructorDeclaration.java @@ -20,6 +20,11 @@ */ package com.github.javaparser.ast.body; +import static com.github.javaparser.utils.Utils.assertNotNull; + +import java.util.Optional; +import java.util.function.Consumer; + import com.github.javaparser.TokenRange; import com.github.javaparser.ast.*; import com.github.javaparser.ast.expr.AnnotationExpr; @@ -38,11 +43,6 @@ import com.github.javaparser.resolution.Resolvable; import com.github.javaparser.resolution.declarations.ResolvedConstructorDeclaration; -import java.util.Optional; -import java.util.function.Consumer; - -import static com.github.javaparser.utils.Utils.assertNotNull; - /** * A constructor declaration: {@code class X { X() { } }} where X(){} is the constructor declaration. *

@@ -98,7 +98,8 @@ public void accept(final VoidVisitor v, final A arg) { v.visit(this, arg); } - @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") + @Override + @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public BlockStmt getBody() { return body; } @@ -109,7 +110,8 @@ public BlockStmt getBody() { * @param body the body, can not be null * @return this, the ConstructorDeclaration */ - @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") + @Override + @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public ConstructorDeclaration setBody(final BlockStmt body) { assertNotNull(body); if (body == this.body) { @@ -171,9 +173,9 @@ public String getDeclarationAsString(boolean includingModifiers, boolean includi sb.append(", "); } if (includingParameterName) { - sb.append(param.toString(prettyPrinterNoCommentsConfiguration)); + sb.append(param); } else { - sb.append(param.getType().toString(prettyPrinterNoCommentsConfiguration)); + sb.append(param.getType()); } } sb.append(")"); diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/body/MethodDeclaration.java b/javaparser-core/src/main/java/com/github/javaparser/ast/body/MethodDeclaration.java index 4587fc898d..cf30305052 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/body/MethodDeclaration.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/body/MethodDeclaration.java @@ -20,6 +20,11 @@ */ package com.github.javaparser.ast.body; +import static com.github.javaparser.utils.Utils.assertNotNull; + +import java.util.Optional; +import java.util.function.Consumer; + import com.github.javaparser.TokenRange; import com.github.javaparser.ast.*; import com.github.javaparser.ast.expr.AnnotationExpr; @@ -41,11 +46,6 @@ import com.github.javaparser.resolution.Resolvable; import com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration; -import java.util.Optional; -import java.util.function.Consumer; - -import static com.github.javaparser.utils.Utils.assertNotNull; - /** * A method declaration. "public int abc() {return 1;}" in this example: {@code class X { public int abc() {return 1;} * }} @@ -106,7 +106,8 @@ public void accept(final VoidVisitor v, final A arg) { v.visit(this, arg); } - @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") + @Override + @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public Optional getBody() { return Optional.ofNullable(body); } @@ -117,7 +118,8 @@ public Optional getBody() { * @param body the body, can be null * @return this, the MethodDeclaration */ - @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") + @Override + @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public MethodDeclaration setBody(final BlockStmt body) { if (body == this.body) { return this; @@ -130,12 +132,14 @@ public MethodDeclaration setBody(final BlockStmt body) { return this; } - @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") + @Override + @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public Type getType() { return type; } - @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") + @Override + @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public MethodDeclaration setType(final Type type) { assertNotNull(type); if (type == this.type) { @@ -205,7 +209,7 @@ public String getDeclarationAsString(boolean includingModifiers, boolean includi sb.append("synchronized "); } } - sb.append(getType().toString(prettyPrinterNoCommentsConfiguration)); + sb.append(getType()); sb.append(" "); sb.append(getName()); sb.append("("); @@ -217,9 +221,9 @@ public String getDeclarationAsString(boolean includingModifiers, boolean includi sb.append(", "); } if (includingParameterName) { - sb.append(param.toString(prettyPrinterNoCommentsConfiguration)); + sb.append(param); } else { - sb.append(param.getType().toString(prettyPrinterNoCommentsConfiguration)); + sb.append(param.getType()); if (param.isVarArgs()) { sb.append("..."); } @@ -286,7 +290,8 @@ public boolean remove(Node node) { return super.remove(node); } - @Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator") + @Override + @Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator") public MethodDeclaration removeBody() { return setBody((BlockStmt) null); } From 0d909d718d7b11e3081e14aecf28d32976700760 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Thu, 19 Oct 2023 19:30:35 +0200 Subject: [PATCH 108/136] revert previous commit and add new behaviour in Node.toString() --- .../src/main/java/com/github/javaparser/ast/Node.java | 11 ++++++++++- .../javaparser/ast/body/CallableDeclaration.java | 2 +- .../ast/body/CompactConstructorDeclaration.java | 2 +- .../javaparser/ast/body/ConstructorDeclaration.java | 4 ++-- .../github/javaparser/ast/body/MethodDeclaration.java | 6 +++--- 5 files changed, 17 insertions(+), 8 deletions(-) diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/Node.java b/javaparser-core/src/main/java/com/github/javaparser/ast/Node.java index 1f35979da5..1205643567 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/Node.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/Node.java @@ -153,6 +153,9 @@ public enum Parsedness { // usefull to find if the node is a phantom node private static final int LEVELS_TO_EXPLORE = 3; + protected static final PrinterConfiguration prettyPrinterNoCommentsConfiguration = new DefaultPrinterConfiguration() + .removeOption(new DefaultConfigurationOption(ConfigOption.PRINT_COMMENTS)); + @InternalProperty private Range range; @@ -332,7 +335,13 @@ public final String toString() { * Formatting can be configured with parameter PrinterConfiguration. */ public final String toString(PrinterConfiguration configuration) { - return getPrinter(configuration).print(this); + // save the current configuration + PrinterConfiguration previousConfiguration = getPrinter().getConfiguration(); + // print with the new configuration + String result = getPrinter(configuration).print(this); + // restore the previous printer configuration (issue 4163) + getPrinter().setConfiguration(previousConfiguration); + return result; } @Override diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/body/CallableDeclaration.java b/javaparser-core/src/main/java/com/github/javaparser/ast/body/CallableDeclaration.java index 328dbd3b97..9d5d5c6815 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/body/CallableDeclaration.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/body/CallableDeclaration.java @@ -209,7 +209,7 @@ protected String appendThrowsIfRequested(boolean includingThrows) { } else { sb.append(", "); } - sb.append(thr); + sb.append(thr.toString(prettyPrinterNoCommentsConfiguration)); } } return sb.toString(); diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/body/CompactConstructorDeclaration.java b/javaparser-core/src/main/java/com/github/javaparser/ast/body/CompactConstructorDeclaration.java index e710ddfd59..7610dab804 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/body/CompactConstructorDeclaration.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/body/CompactConstructorDeclaration.java @@ -262,7 +262,7 @@ protected String appendThrowsIfRequested(boolean includingThrows) { } else { sb.append(", "); } - sb.append(thr); + sb.append(thr.toString(prettyPrinterNoCommentsConfiguration)); } } return sb.toString(); diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/body/ConstructorDeclaration.java b/javaparser-core/src/main/java/com/github/javaparser/ast/body/ConstructorDeclaration.java index f8d8d96c4b..a9dbd6e90d 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/body/ConstructorDeclaration.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/body/ConstructorDeclaration.java @@ -173,9 +173,9 @@ public String getDeclarationAsString(boolean includingModifiers, boolean includi sb.append(", "); } if (includingParameterName) { - sb.append(param); + sb.append(param.toString(prettyPrinterNoCommentsConfiguration)); } else { - sb.append(param.getType()); + sb.append(param.getType().toString(prettyPrinterNoCommentsConfiguration)); } } sb.append(")"); diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/body/MethodDeclaration.java b/javaparser-core/src/main/java/com/github/javaparser/ast/body/MethodDeclaration.java index cf30305052..eb68950cbf 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/body/MethodDeclaration.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/body/MethodDeclaration.java @@ -209,7 +209,7 @@ public String getDeclarationAsString(boolean includingModifiers, boolean includi sb.append("synchronized "); } } - sb.append(getType()); + sb.append(getType().toString(prettyPrinterNoCommentsConfiguration)); sb.append(" "); sb.append(getName()); sb.append("("); @@ -221,9 +221,9 @@ public String getDeclarationAsString(boolean includingModifiers, boolean includi sb.append(", "); } if (includingParameterName) { - sb.append(param); + sb.append(param.toString(prettyPrinterNoCommentsConfiguration)); } else { - sb.append(param.getType()); + sb.append(param.getType().toString(prettyPrinterNoCommentsConfiguration)); if (param.isVarArgs()) { sb.append("..."); } From 485665a32a1703e97723a94a422eb0f11e731a57 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Thu, 19 Oct 2023 19:53:12 +0200 Subject: [PATCH 109/136] Remove printing of comments on method name --- .../java/com/github/javaparser/ast/body/MethodDeclaration.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javaparser-core/src/main/java/com/github/javaparser/ast/body/MethodDeclaration.java b/javaparser-core/src/main/java/com/github/javaparser/ast/body/MethodDeclaration.java index eb68950cbf..8502ac3a68 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/ast/body/MethodDeclaration.java +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/body/MethodDeclaration.java @@ -211,7 +211,7 @@ public String getDeclarationAsString(boolean includingModifiers, boolean includi } sb.append(getType().toString(prettyPrinterNoCommentsConfiguration)); sb.append(" "); - sb.append(getName()); + sb.append(getName().toString(prettyPrinterNoCommentsConfiguration)); sb.append("("); boolean firstParam = true; for (Parameter param : getParameters()) { From e71c55e3c576c66921ea2c27185117445f580c65 Mon Sep 17 00:00:00 2001 From: Luciano Barcellos Date: Thu, 19 Oct 2023 18:32:32 -0300 Subject: [PATCH 110/136] Fix: issue #2749 Generated XML is invalid Replace "manual" generation of XML by use of JAXP API. The test cases were replaced as well so they now check for XML document equality instead of string equality. --- .../javaparser/printer/XmlPrinterTest.java | 49 +++++- .../github/javaparser/printer/XmlPrinter.java | 147 ++++++++++++------ 2 files changed, 140 insertions(+), 56 deletions(-) diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java index ac2385ff33..da637f3292 100644 --- a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java @@ -25,38 +25,73 @@ import org.junit.jupiter.api.Test; import static com.github.javaparser.StaticJavaParser.parseExpression; -import static org.junit.jupiter.api.Assertions.assertEquals; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.w3c.dom.Document; +import org.xml.sax.SAXException; class XmlPrinterTest { + + DocumentBuilderFactory dbf; + DocumentBuilder db; + { + try { + dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + dbf.setCoalescing(true); + dbf.setIgnoringElementContentWhitespace(true); + dbf.setIgnoringComments(true); + db = dbf.newDocumentBuilder(); + } catch (ParserConfigurationException ex) { + throw new RuntimeException(ex); + } + } + + public Document getDocument(String xml) throws SAXException, IOException { + InputStream inputStream = new ByteArrayInputStream(xml.getBytes()); + Document result = db.parse(inputStream); + result.normalizeDocument(); + return result; + } + + public void assertXMLEquals(String xml1, String xml2) throws SAXException, IOException { + assertTrue(getDocument(xml1).isEqualNode(getDocument(xml2))); + } + @Test - void testWithType() { + void testWithType() throws SAXException, IOException { Expression expression = parseExpression("1+1"); XmlPrinter xmlOutput = new XmlPrinter(true); String output = xmlOutput.output(expression); - assertEquals("", output); + assertXMLEquals("", output); } @Test - void testWithoutType() { + void testWithoutType() throws SAXException, IOException { Expression expression = parseExpression("1+1"); XmlPrinter xmlOutput = new XmlPrinter(false); String output = xmlOutput.output(expression); - assertEquals("", output); + assertXMLEquals("", output); } @Test - void testList() { + void testList() throws SAXException, IOException { Expression expression = parseExpression("a(1,2)"); XmlPrinter xmlOutput = new XmlPrinter(true); String output = xmlOutput.output(expression); - assertEquals("", output); + assertXMLEquals("", output); } } diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/XmlPrinter.java b/javaparser-core/src/main/java/com/github/javaparser/printer/XmlPrinter.java index d235619a9d..6715c2031d 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/XmlPrinter.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/XmlPrinter.java @@ -28,7 +28,12 @@ import java.util.List; import static com.github.javaparser.utils.Utils.assertNotNull; +import java.io.StringWriter; +import java.io.Writer; import java.util.function.Predicate; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamWriter; /** * Outputs an XML file containing the AST meant for inspecting it. @@ -42,12 +47,38 @@ public XmlPrinter(boolean outputNodeType) { } public String output(Node node) { - StringBuilder output = new StringBuilder(); - output(node, "root", 0, output); - return output.toString(); + return stringWriterOutput(node, "root").toString(); } + // Kept for backward compatibility public void output(Node node, String name, int level, StringBuilder builder) { + builder.append(stringWriterOutput(node, name).toString()); + } + + public StringWriter stringWriterOutput(Node node, String name) { + StringWriter stringWriter = new StringWriter(); + outputDocument(node, name, stringWriter); + return stringWriter; + } + + public void outputDocument(Node node, String name, Writer writer) { + XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); + try { + XMLStreamWriter xmlWriter = outputFactory.createXMLStreamWriter(writer); + outputDocument(node, name, xmlWriter); + } catch (XMLStreamException ex) { + throw new RuntimeXMLStreamException(ex); + } + } + + public void outputDocument(Node node, String name, XMLStreamWriter xmlWriter) throws XMLStreamException { + xmlWriter.writeStartDocument(); + outputNode(node, name, xmlWriter); + xmlWriter.writeEndDocument(); + } + + public void outputNode(Node node, String name, XMLStreamWriter xmlWriter) throws XMLStreamException { + assertNotNull(node); NodeMetaModel metaModel = node.getMetaModel(); List allPropertyMetaModels = metaModel.getAllPropertyMetaModels(); @@ -55,63 +86,81 @@ public void output(Node node, String name, int level, StringBuilder builder) { Predicate nonEmptyList = propertyMetaModel -> ((NodeList) propertyMetaModel.getValue(node)).isNonEmpty(); - builder.append("<").append(name); + xmlWriter.writeStartElement(name); // Output node type attribute if (outputNodeType) { - builder.append(attribute("type", metaModel.getTypeName())); + xmlWriter.writeAttribute("type", metaModel.getTypeName()); } - // Output attributes - allPropertyMetaModels.stream() - .filter(PropertyMetaModel::isAttribute) - .filter(PropertyMetaModel::isSingular) - .forEach(attributeMetaModel -> { - final String attributeName = attributeMetaModel.getName(); - final String attributeValue = attributeMetaModel.getValue(node).toString(); - builder.append(attribute(attributeName, attributeValue)); - }); - - builder.append(">"); - - // Output singular subNodes - allPropertyMetaModels.stream() - .filter(PropertyMetaModel::isNode) - .filter(PropertyMetaModel::isSingular) - .filter(nonNullNode) - .forEach(subNodeMetaModel -> { - final Node subNode = (Node) subNodeMetaModel.getValue(node); - final String subNodeName = subNodeMetaModel.getName(); - output(subNode, subNodeName, level + 1, builder); - }); - - // Output list subNodes - allPropertyMetaModels.stream() - .filter(PropertyMetaModel::isNodeList) - .filter(nonNullNode) - .filter(nonEmptyList) - .forEach(listMetaModel -> { - final String listName = listMetaModel.getName(); - String singular = listName.substring(0, listName.length() - 1); - NodeList nodeList = (NodeList) listMetaModel.getValue(node); - builder.append("<").append(listName).append(">"); - for (Node subNode : nodeList) { - output(subNode, singular, level + 1, builder); + try { + // Output attributes + allPropertyMetaModels.stream() + .filter(PropertyMetaModel::isAttribute) + .filter(PropertyMetaModel::isSingular) + .forEach(attributeMetaModel -> { + try { + final String attributeName = attributeMetaModel.getName(); + final String attributeValue = attributeMetaModel.getValue(node).toString(); + xmlWriter.writeAttribute(attributeName, attributeValue); + } catch (XMLStreamException ex) { + throw new RuntimeXMLStreamException(ex); } - builder.append(close(listName)); - }); - builder.append(close(name)); + }); + + // Output singular subNodes + allPropertyMetaModels.stream() + .filter(PropertyMetaModel::isNode) + .filter(PropertyMetaModel::isSingular) + .filter(nonNullNode) + .forEach(subNodeMetaModel -> { + try { + final Node subNode = (Node) subNodeMetaModel.getValue(node); + final String subNodeName = subNodeMetaModel.getName(); + outputNode(subNode, subNodeName, xmlWriter); + } catch (XMLStreamException ex) { + throw new RuntimeXMLStreamException(ex); + } + }); + + // Output list subNodes + allPropertyMetaModels.stream() + .filter(PropertyMetaModel::isNodeList) + .filter(nonNullNode) + .filter(nonEmptyList) + .forEach(listMetaModel -> { + try { + String listName = listMetaModel.getName(); + String singular = listName.substring(0, listName.length() - 1); + NodeList nodeList = (NodeList) listMetaModel.getValue(node); + xmlWriter.writeStartElement(listName); + for (Node subNode : nodeList) { + outputNode(subNode, singular, xmlWriter); + } + xmlWriter.writeEndElement(); + } catch (XMLStreamException ex) { + throw new RuntimeXMLStreamException(ex); + } + }); + } catch (RuntimeXMLStreamException ex) { + throw ex.getXMLStreamCause(); + } + + xmlWriter.writeEndElement(); } - private static String close(String name) { - return ""; + public static void print(Node node) { + System.out.println(new XmlPrinter(true).output(node)); } +} + +class RuntimeXMLStreamException extends RuntimeException { - private static String attribute(String name, String value) { - return " " + name + "='" + value + "'"; + public RuntimeXMLStreamException(XMLStreamException cause) { + super(cause); } - public static void print(Node node) { - System.out.println(new XmlPrinter(true).output(node)); + public XMLStreamException getXMLStreamCause() { + return (XMLStreamException) super.getCause(); } } From 2f5b010e5b1421f75c5b86fade578386c257cb59 Mon Sep 17 00:00:00 2001 From: u7461674 Date: Fri, 20 Oct 2023 12:35:00 +1100 Subject: [PATCH 111/136] reformat javaconcept take 2 --- .../ConcreteSyntaxModelAcceptanceTest.java | 14 +- .../printer/JavaConceptsBase_prettyprinted | 83 ++++ .../printer/JavaConceptsEnums_prettyprinted | 70 +++ .../JavaConceptsInnerClasses_prettyprinted | 135 ++++++ .../printer/JavaConceptsMethods_prettyprinted | 164 ++++++++ .../printer/JavaConceptsUgly_prettyprinted | 60 +++ .../printer/JavaConcepts_prettyprinted | 398 ------------------ .../javaparser/printer/JavaConcepts.java | 393 ----------------- .../javaparser/printer/JavaConceptsBase.java | 83 ++++ .../javaparser/printer/JavaConceptsEnums.java | 70 +++ .../printer/JavaConceptsInnerClasses.java | 135 ++++++ .../printer/JavaConceptsMethods.java | 164 ++++++++ .../javaparser/printer/JavaConceptsUgly.java | 60 +++ 13 files changed, 1035 insertions(+), 794 deletions(-) create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/printer/JavaConceptsBase_prettyprinted create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/printer/JavaConceptsEnums_prettyprinted create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/printer/JavaConceptsInnerClasses_prettyprinted create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/printer/JavaConceptsMethods_prettyprinted create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/printer/JavaConceptsUgly_prettyprinted delete mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/printer/JavaConcepts_prettyprinted delete mode 100644 javaparser-core-testing/src/test/test_sourcecode/com/github/javaparser/printer/JavaConcepts.java create mode 100644 javaparser-core-testing/src/test/test_sourcecode/com/github/javaparser/printer/JavaConceptsBase.java create mode 100644 javaparser-core-testing/src/test/test_sourcecode/com/github/javaparser/printer/JavaConceptsEnums.java create mode 100644 javaparser-core-testing/src/test/test_sourcecode/com/github/javaparser/printer/JavaConceptsInnerClasses.java create mode 100644 javaparser-core-testing/src/test/test_sourcecode/com/github/javaparser/printer/JavaConceptsMethods.java create mode 100644 javaparser-core-testing/src/test/test_sourcecode/com/github/javaparser/printer/JavaConceptsUgly.java diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/ConcreteSyntaxModelAcceptanceTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/ConcreteSyntaxModelAcceptanceTest.java index a2d4d689f0..1f81eeacfa 100644 --- a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/ConcreteSyntaxModelAcceptanceTest.java +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/ConcreteSyntaxModelAcceptanceTest.java @@ -51,8 +51,16 @@ void printingExamplePrettyPrintVisitor() throws IOException { @Test void printingExampleJavaConcepts() throws IOException { - CompilationUnit cu = parse(rootDir.resolve("com/github/javaparser/printer/JavaConcepts.java")); - TestUtils.assertEqualsStringIgnoringEol(prettyPrintedExpectation("JavaConcepts"), prettyPrint(cu)); - } + CompilationUnit base = parse(rootDir.resolve("com/github/javaparser/printer/JavaConceptsBase.java")); + CompilationUnit enums = parse(rootDir.resolve("com/github/javaparser/printer/JavaConceptsEnums.java")); + CompilationUnit innerClass = parse(rootDir.resolve("com/github/javaparser/printer/JavaConceptsInnerClasses.java")); + CompilationUnit methods = parse(rootDir.resolve("com/github/javaparser/printer/JavaConceptsMethods.java")); + CompilationUnit ugly = parse(rootDir.resolve("com/github/javaparser/printer/JavaConceptsUgly.java")); + TestUtils.assertEqualsStringIgnoringEol(prettyPrintedExpectation("JavaConceptsBase"), prettyPrint(base)); + TestUtils.assertEqualsStringIgnoringEol(prettyPrintedExpectation("JavaConceptsEnums"), prettyPrint(enums)); + TestUtils.assertEqualsStringIgnoringEol(prettyPrintedExpectation("JavaConceptsInnerClasses"), prettyPrint(innerClass)); + TestUtils.assertEqualsStringIgnoringEol(prettyPrintedExpectation("JavaConceptsMethods"), prettyPrint(methods)); + TestUtils.assertEqualsStringIgnoringEol(prettyPrintedExpectation("JavaConceptsUgly"), prettyPrint(ugly)); + } } diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/printer/JavaConceptsBase_prettyprinted b/javaparser-core-testing/src/test/resources/com/github/javaparser/printer/JavaConceptsBase_prettyprinted new file mode 100644 index 0000000000..0740244055 --- /dev/null +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/printer/JavaConceptsBase_prettyprinted @@ -0,0 +1,83 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ +package japa.bdd.samples; + +import com.github.javaparser.JavaParser; +import japa.parser.ParseException; +import com.github.javaparser.ast.CompilationUnit; +import java.io.*; +import java.util.*; + +@Deprecated +public class JavaConceptsBase, X> extends Base implements Serializable { + + static Class clz1 = String.class; + + protected Class clz2 = (String.class); + + Class clz3 = int.class; + + Class clz4 = (int.class); + + int[] arr = new int[10]; + + byte bye = 0; + + byte[] byebye = null; + + short sh1, sh2 = 1; + + int intWithUnderscore = 1234_5678; + + long longWithUnderscore = 1234_5678L; + + float floatWithUnderscore = 1_234.5_678f; + + float floatWithUnderscoreAndExponent = 1_234e1_0f; + + double doubleWithUnderscore = 1_234.5_678; + + double doubleWithUnderscoreAndExponent = 1_234e1_0; + + int binaryLiteral = 0b101101; + + List[][] arrLS = (List[][]) new List[10][]; + + int[][][][] arr2 = new int[10][2][1][0]; + + volatile float fff = 0x1.fffeP+127f; + + char cc = 'a'; + + int[][] arr3 = { { 1, 2 }, { 3, 4 } }; + + static int[][] arr4 = {}; + + static { + arr4 = new int[][] { { 2 }, { 1 } }; + } + + { + arr3 = new int[][] { { 2 }, { 1 } }; + } + + public static JavaConceptsBase t; +} diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/printer/JavaConceptsEnums_prettyprinted b/javaparser-core-testing/src/test/resources/com/github/javaparser/printer/JavaConceptsEnums_prettyprinted new file mode 100644 index 0000000000..734faabedf --- /dev/null +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/printer/JavaConceptsEnums_prettyprinted @@ -0,0 +1,70 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ +package japa.bdd.samples; + +@Deprecated +public class JavaConceptsEnums { + + public enum Teste { + + asc, + def + } + + public enum Sexo { + + m, + @Deprecated + f; + + public enum Sexo_ implements Serializable, Cloneable { + + } + } + + @Deprecated + public enum Enum { + + m(1) { + + @Override + void mm() { + } + } + , + f(2) { + + void mm() { + } + } + ; + + native void nnn(); + + transient int x; + + private Enum(int x) { + this.x = x; + } + + abstract void mm(); + } +} diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/printer/JavaConceptsInnerClasses_prettyprinted b/javaparser-core-testing/src/test/resources/com/github/javaparser/printer/JavaConceptsInnerClasses_prettyprinted new file mode 100644 index 0000000000..e1eb83c6ca --- /dev/null +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/printer/JavaConceptsInnerClasses_prettyprinted @@ -0,0 +1,135 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ +package japa.bdd.samples; + +import com.github.javaparser.JavaParser; +import japa.parser.ParseException; +import com.github.javaparser.ast.CompilationUnit; +import org.junit.Ignore; +import java.io.*; +import java.util.*; + +@Ignore +@Deprecated +public class JavaConceptsInnerClasses, X> extends Base implements Serializable { + + public JavaConceptsInnerClasses(int x) { + this.arr[0] = x; + T val1 = null; + E val2 = null; + super.check2(val1, val2); + boolean b = true, y = false; + abstract class X { + + int i = 0; + + public X() { + } + + public void m() { + } + } + @Deprecated + final class Y extends X { + + public Y() { + super(); + JavaConceptsInnerClasses.this.cc = 'c'; + super.i = 1; + Y.super.m(); + } + + public Y(int y) { + super(); + } + + public Y(long x) { + this(); + } + } + } + + public JavaConceptsInnerClasses(String str) { + } + + private class QWE extends JavaConceptsInnerClasses, String> { + + @Deprecated + final int z = 0; + + int i = (int) -1; + + public QWE(String... x) { + super(x[0]); + } + + public QWE(int... x) { + super(x[0]); + i = x[0]; + assert true; + assert 1 == 1 : 2; + { + int iii = 3; + iii += 3; + } + label: { + int iii = 1; + } + ; + ; + int min = -2147483648; + long sl = 123123123123l; + long minl = -9223372036854775808L; + switch(i) { + } + ll: switch(i) { + case 1: + System.out.println(1); + break ll; + default: + { + System.out.println("default"); + break; + } + case 2: + if (t instanceof Base) { + System.out.println(1); + } + i++; + ++i; + } + } + + private synchronized int[] doSomething() { + List x = new ArrayList(); + return new int[] { 1 }; + } + } +} + +class Base { + + public void check2(A val1, B val2) { + } +} + +interface XXX extends Serializable, Cloneable { +} diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/printer/JavaConceptsMethods_prettyprinted b/javaparser-core-testing/src/test/resources/com/github/javaparser/printer/JavaConceptsMethods_prettyprinted new file mode 100644 index 0000000000..122fc5b7e4 --- /dev/null +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/printer/JavaConceptsMethods_prettyprinted @@ -0,0 +1,164 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ +package japa.bdd.samples; + +import com.github.javaparser.JavaParser; +import japa.parser.ParseException; +import com.github.javaparser.ast.CompilationUnit; +import java.io.*; +import java.util.*; + +public class JavaConceptsMethods { + + strictfp double ddd() { + return 0.0; + } + + public static void main(String[] args) throws ParseException, IOException { + int x = 2; + CompilationUnit cu = parse(new File("src/japa/parser/javacc/Parser.java")); + System.out.println(cu); + JavaConcepts teste = new JavaConcepts(2); + JavaConcepts.QWE qwe = teste.new QWE(1); + if (1 + 1 == 2) { + teste = null; + teste = new JavaConcepts(1); + } else { + x = 3; + teste = new JavaConcepts(1); + x = x == 0 ? 2 : 4; + } + if (true) + x = 1; + else + x = 3; + if (true) + x = 1; + else if (false) + x = 3; + else + x = 2; + while (true) { + xxx: while (x == 3) continue xxx; + break; + } + do { + x++; + } while (x < 100); + do x++; while (x < 100); + for (@Deprecated int i : arr4[0]) { + x--; + } + for (@Deprecated final int i = 0, j = 1; i < 10; x++) { + break; + } + int i, j; + for (i = 0, j = 1; i < 10 && j < 2; i++, j--) { + break; + } + } + + public static CompilationUnit parse(@Deprecated File file) throws ParseException, IOException { + String a = ((String) "qwe"); + String x = ((String) clz1.getName()); + int y = ((Integer) (Object) x).intValue(); + synchronized (file) { + file = null; + file = new File(""); + } + try { + if (file == null) { + throw new NullPointerException("blah"); + } + } catch (final NullPointerException e) { + System.out.println("catch"); + } catch (RuntimeException e) { + System.out.println("catch"); + } finally { + System.out.println("finally"); + } + try { + if (file == null) { + throw new NullPointerException("blah"); + } + } finally { + System.out.println("finally"); + } + try { + if (file == null) { + throw new NullPointerException("blah"); + } + } catch (RuntimeException e) { + System.out.println("catch"); + } + try (InputStream in = createInputStream()) { + System.out.println(in); + } catch (IOException e) { + System.out.println("catch"); + } + try (InputStream in = createInputStream(); + InputStream in2 = createInputStream()) { + System.out.println(in); + } catch (IOException e) { + System.out.println("catch"); + } + try (InputStream in = createInputStream()) { + System.out.println(in); + } + try { + System.out.println("whatever"); + } catch (RuntimeException e) { + System.out.println(e); + } catch (final Exception | Error e) { + System.out.println(e); + } + return JavaParser.parse(file); + } + + class A implements XXX, Serializable { + + public A(Integer integer, ABC string) throws Exception, IOException { + } + } + + private void x(Map x) { + @Deprecated Comparator c = new Comparator() { + + public int compare(Object o1, Object o2) { + try { + A a = new A(new Integer(11), "foo") { + }; + } catch (Exception e) { + } + return 0; + } + + @Override + public boolean equals(Object obj) { + return super.equals(obj); + } + }; + } + + private static InputStream createInputStream() { + return new ByteArrayInputStream(null); + } +} diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/printer/JavaConceptsUgly_prettyprinted b/javaparser-core-testing/src/test/resources/com/github/javaparser/printer/JavaConceptsUgly_prettyprinted new file mode 100644 index 0000000000..b34d8f0790 --- /dev/null +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/printer/JavaConceptsUgly_prettyprinted @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ +package japa.bdd.samples; + +@Deprecated +public class JavaConceptsUgly { + + static int x = 0; + + public static void main(String[] args) { + x = +x; + x = ~x; + --x; + boolean b = !false; + x &= 2; + x |= 2; + x ^= 2; + x -= 2; + x %= 2; + x /= 2; + x *= 2; + x <<= 2; + x >>= 2; + x >>>= 2; + b = b || false; + b = b | false; + b = b & false; + b = b ^ false; + b = b != false; + b = x > 1; + b = x < 1; + b = x >= 1; + b = x <= 1; + x = x << 1; + x = x >> 1; + x = x >>> 1; + x = x - 1; + x = x * 1; + x = x % 1; + x = x / 1; + } +} diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/printer/JavaConcepts_prettyprinted b/javaparser-core-testing/src/test/resources/com/github/javaparser/printer/JavaConcepts_prettyprinted deleted file mode 100644 index 014fd9cb8c..0000000000 --- a/javaparser-core-testing/src/test/resources/com/github/javaparser/printer/JavaConcepts_prettyprinted +++ /dev/null @@ -1,398 +0,0 @@ -package japa.bdd.samples; - -import com.github.javaparser.JavaParser; -import japa.parser.ParseException; -import com.github.javaparser.ast.CompilationUnit; -import org.junit.Ignore; -import java.io.*; -import java.util.*; - -@Ignore -@Deprecated -public class JavaConcepts, X> extends Base implements Serializable { - - static Class clz1 = String.class; - - protected Class clz2 = (String.class); - - Class clz3 = int.class; - - Class clz4 = (int.class); - - int[] arr = new int[10]; - - byte bye = 0; - - byte[] byebye = null; - - short sh1, sh2 = 1; - - int intWithUnderscore = 1234_5678; - - long longWithUnderscore = 1234_5678L; - - float floatWithUnderscore = 1_234.5_678f; - - float floatWithUnderscoreAndExponent = 1_234e1_0f; - - double doubleWithUnderscore = 1_234.5_678; - - double doubleWithUnderscoreAndExponent = 1_234e1_0; - - int binaryLiteral = 0b101101; - - List[][] arrLS = (List[][]) new List[10][]; - - { - int z = 0, y = 0; - int a = (z) + y; - a = (+z) + y; - byte b = (byte) +y; - } - - List diamond1 = new LinkedList<>(); - - @Deprecated - static class Ugly { - - static int x = 0; - - public static void main(String[] args) { - x = +x; - x = ~x; - --x; - boolean b = !false; - x &= 2; - x |= 2; - x ^= 2; - x -= 2; - x %= 2; - x /= 2; - x *= 2; - x <<= 2; - x >>= 2; - x >>>= 2; - b = b || false; - b = b | false; - b = b & false; - b = b ^ false; - b = b != false; - b = x > 1; - b = x < 1; - b = x >= 1; - b = x <= 1; - x = x << 1; - x = x >> 1; - x = x >>> 1; - x = x - 1; - x = x * 1; - x = x % 1; - x = x / 1; - } - } - - @Deprecated - int[][][][] arr2 = new int[10][2][1][0]; - - volatile float fff = 0x1.fffeP+127f; - - char cc = 'a'; - - int[][] arr3 = { { 1, 2 }, { 3, 4 } }; - - static int[][] arr4 = {}; - - public static JavaConcepts t; - - static { - arr4 = new int[][] { { 2 }, { 1 } }; - } - - { - arr3 = new int[][] { { 2 }, { 1 } }; - } - - public enum Teste { - - asc, - def - } - - public enum Sexo { - - m, - @Deprecated - f; - - public enum Sexo_ implements Serializable, Cloneable { - - } - - private Sexo() { - } - } - - @Deprecated - public enum Enum { - - m(1) { - - @Override - void mm() { - } - } - , - f(2) { - - void mm() { - } - } - ; - - native void nnn(); - - transient int x; - - private Enum(int x) { - this.x = x; - } - - abstract void mm(); - } - - strictfp double ddd() { - return 0.0; - } - - public JavaConcepts(int x) { - this.arr[0] = x; - T val1 = null; - E val2 = null; - super.check2(val1, val2); - boolean b = true, y = false; - abstract class X { - - int i = 0; - - public X() { - } - - public void m() { - } - } - @Deprecated - final class Y extends X { - - public Y() { - super(); - JavaConcepts.this.cc = 'c'; - super.i = 1; - Y.super.m(); - } - - public Y(int y) { - super(); - } - - public Y(long x) { - this(); - } - } - } - - public JavaConcepts(String str) { - } - - private class QWE extends JavaConcepts, String> { - - @Deprecated - final int z = 0; - - int i = (int) -1; - - public QWE(String... x) { - super(x[0]); - } - - public QWE(int... x) { - super(x[0]); - i = x[0]; - assert true; - assert 1 == 1 : 2; - { - int iii = 3; - iii += 3; - } - label: { - int iii = 1; - } - ; - ; - int min = -2147483648; - long sl = 123123123123l; - long minl = -9223372036854775808L; - switch(i) { - } - ll: switch(i) { - case 1: - System.out.println(1); - break ll; - default: - { - System.out.println("default"); - break; - } - case 2: - if (t instanceof Base) { - System.out.println(1); - } - i++; - ++i; - } - } - - private synchronized int[] doSomething() { - List x = new ArrayList(); - return new int[] { 1 }; - } - } - - public static void main(String[] args) throws ParseException, IOException { - int x = 2; - CompilationUnit cu = parse(new File("src/japa/parser/javacc/Parser.java")); - System.out.println(cu); - JavaConcepts teste = new JavaConcepts(2); - JavaConcepts.QWE qwe = teste.new QWE(1); - if (1 + 1 == 2) { - teste = null; - teste = new JavaConcepts(1); - } else { - x = 3; - teste = new JavaConcepts(1); - x = x == 0 ? 2 : 4; - } - if (true) - x = 1; - else - x = 3; - if (true) - x = 1; - else if (false) - x = 3; - else - x = 2; - while (true) { - xxx: while (x == 3) continue xxx; - break; - } - do { - x++; - } while (x < 100); - do x++; while (x < 100); - for (@Deprecated int i : arr4[0]) { - x--; - } - for (@Deprecated final int i = 0, j = 1; i < 10; x++) { - break; - } - int i, j; - for (i = 0, j = 1; i < 10 && j < 2; i++, j--) { - break; - } - } - - public static CompilationUnit parse(@Deprecated File file) throws ParseException, IOException { - String a = ((String) "qwe"); - String x = ((String) clz1.getName()); - int y = ((Integer) (Object) x).intValue(); - synchronized (file) { - file = null; - file = new File(""); - } - try { - if (file == null) { - throw new NullPointerException("blah"); - } - } catch (final NullPointerException e) { - System.out.println("catch"); - } catch (RuntimeException e) { - System.out.println("catch"); - } finally { - System.out.println("finally"); - } - try { - if (file == null) { - throw new NullPointerException("blah"); - } - } finally { - System.out.println("finally"); - } - try { - if (file == null) { - throw new NullPointerException("blah"); - } - } catch (RuntimeException e) { - System.out.println("catch"); - } - try (InputStream in = createInputStream()) { - System.out.println(in); - } catch (IOException e) { - System.out.println("catch"); - } - try (InputStream in = createInputStream(); - InputStream in2 = createInputStream()) { - System.out.println(in); - } catch (IOException e) { - System.out.println("catch"); - } - try (InputStream in = createInputStream()) { - System.out.println(in); - } - try { - System.out.println("whatever"); - } catch (RuntimeException e) { - System.out.println(e); - } catch (final Exception | Error e) { - System.out.println(e); - } - return JavaParser.parse(file); - } - - class A implements XXX, Serializable { - - public A(Integer integer, ABC string) throws Exception, IOException { - } - } - - private void x(Map x) { - @Deprecated Comparator c = new Comparator() { - - public int compare(Object o1, Object o2) { - try { - A a = new A(new Integer(11), "foo") { - }; - } catch (Exception e) { - } - return 0; - } - - @Override - public boolean equals(Object obj) { - return super.equals(obj); - } - }; - } - - private static InputStream createInputStream() { - return new ByteArrayInputStream(null); - } -} - -class Base { - - public void check2(A val1, B val2) { - } -} - -interface XXX extends Serializable, Cloneable { -} diff --git a/javaparser-core-testing/src/test/test_sourcecode/com/github/javaparser/printer/JavaConcepts.java b/javaparser-core-testing/src/test/test_sourcecode/com/github/javaparser/printer/JavaConcepts.java deleted file mode 100644 index 2a53e5f5b6..0000000000 --- a/javaparser-core-testing/src/test/test_sourcecode/com/github/javaparser/printer/JavaConcepts.java +++ /dev/null @@ -1,393 +0,0 @@ -package japa.bdd.samples; - -import com.github.javaparser.JavaParser; -import japa.parser.ParseException; -import com.github.javaparser.ast.CompilationUnit; -import org.junit.Ignore; - -import java.io.*; -import java.util.*; - -@Ignore -@Deprecated -public class JavaConcepts, X> extends Base implements Serializable { - - static Class clz1 = String.class; - - protected Class clz2 = (String.class); - - Class clz3 = int.class; - - Class clz4 = (int.class); - - int[] arr = new int[10]; - - byte bye = 0; - - byte byebye[] = null; - - short sh1, sh2 = 1; - - int intWithUnderscore = 1234_5678; - - long longWithUnderscore = 1234_5678L; - - float floatWithUnderscore = 1_234.5_678f; - - float floatWithUnderscoreAndExponent = 1_234e1_0f; - - double doubleWithUnderscore = 1_234.5_678; - - double doubleWithUnderscoreAndExponent = 1_234e1_0; - - int binaryLiteral = 0b101101; - - List[][] arrLS = (List[][]) new List[10][]; - - { - int z = 0, y = 0; - int a = (z) + y; - a = (+z) + y; - byte b = (byte) +y; - } - - List diamond1 = new LinkedList<>(); - - @Deprecated() - static class Ugly { - - static int x = 0; - - public static void main(String[] args) { - x = +x; - x = ~x; - --x; - boolean b = !false; - x &= 2; - x |= 2; - x ^= 2; - x -= 2; - x %= 2; - x /= 2; - x *= 2; - x <<= 2; - x >>= 2; - x >>>= 2; - b = b || false; - b = b | false; - b = b & false; - b = b ^ false; - b = b != false; - b = x > 1; - b = x < 1; - b = x >= 1; - b = x <= 1; - x = x << 1; - x = x >> 1; - x = x >>> 1; - x = x - 1; - x = x * 1; - x = x % 1; - x = x / 1; - } - } - - @Deprecated() - int[][][][] arr2 = new int[10][2][1][0]; - - volatile float fff = 0x1.fffeP+127f; - - char cc = 'a'; - - int[][] arr3 = {{1, 2}, {3, 4}}; - - static int[] arr4[] = {}; - - public static JavaConcepts t; - - static { - arr4 = new int[][]{{2}, {1}}; - } - - { - arr3 = new int[][]{{2}, {1}}; - } - - public enum Teste { - - asc, def - } - - public enum Sexo { - - m, @Deprecated - f; - - public enum Sexo_ implements Serializable, Cloneable { - } - - private Sexo() { - } - } - - @Deprecated - public enum Enum { - - m(1) { - @Override - void mm() { - } - }, f(2) { - void mm() { - } - }; - - native void nnn(); - - transient int x; - - private Enum(int x) { - this.x = x; - } - - abstract void mm(); - } - - strictfp double ddd() { - return 0.0; - } - - public JavaConcepts(int x) { - this.arr[0] = x; - T val1 = null; - E val2 = null; - super.check2(val1, val2); - boolean b = true, y = false; - abstract class X { - - int i = 0; - - public X() { - } - - public void m() { - } - } - @Deprecated - final class Y extends X { - - public Y() { - super(); - JavaConcepts.this.cc = 'c'; - super.i = 1; - Y.super.m(); - } - - public Y(int y) { - super(); - } - - public Y(long x) { - this(); - } - } - } - - public JavaConcepts(String str) { - } - - private class QWE extends JavaConcepts, String> { - - @Deprecated - final int z = 0; - - int i = (int) -1; - - public QWE(String... x) { - super(x[0]); - } - - public QWE(int... x) { - super(x[0]); - i = x[0]; - assert true; - assert 1 == 1 : 2; - { - int iii = 3; - iii += 3; - } - label: - { - int iii = 1; - } - ; - ; - int min = -2147483648; - long sl = 123123123123l; - long minl = -9223372036854775808L; - switch (i) { - } - ll: - switch (i) { - case 1: - System.out.println(1); - break ll; - default: { - System.out.println("default"); - break; - } - case 2: - if (t instanceof Base) { - System.out.println(1); - } - i++; - ++i; - } - } - - private synchronized int doSomething()[] { - List x = new ArrayList(); - return new int[]{1}; - } - } - - public static void main(String[] args) throws ParseException, IOException { - int x = 2; - CompilationUnit cu = parse(new File("src/japa/parser/javacc/Parser.java")); - System.out.println(cu); - JavaConcepts teste = new JavaConcepts(2); - JavaConcepts.QWE qwe = teste.new QWE(1); - if (1 + 1 == 2) { - teste = null; - teste = new JavaConcepts(1); - } else { - x = 3; - teste = new JavaConcepts(1); - x = x == 0 ? 2 : 4; - } - if (true) - x = 1; - else - x = 3; - if (true) - x = 1; - else if (false) - x = 3; - else - x = 2; - while (true) { - xxx: - while (x == 3) continue xxx; - break; - } - do { - x++; - } while (x < 100); - do x++; while (x < 100); - for (@Deprecated int i : arr4[0]) { - x--; - } - for (@Deprecated final int i = 0, j = 1; i < 10; x++) { - break; - } - int i, j; - for (i = 0, j = 1; i < 10 && j < 2; i++, j--) { - break; - } - } - - public static CompilationUnit parse(@Deprecated File file) throws ParseException, IOException { - String a = ((String) "qwe"); - String x = ((String) clz1.getName()); - int y = ((Integer) (Object) x).intValue(); - synchronized (file) { - file = null; - file = new File(""); - } - try { - if (file == null) { - throw new NullPointerException("blah"); - } - } catch (final NullPointerException e) { - System.out.println("catch"); - } catch (RuntimeException e) { - System.out.println("catch"); - } finally { - System.out.println("finally"); - } - try { - if (file == null) { - throw new NullPointerException("blah"); - } - } finally { - System.out.println("finally"); - } - try { - if (file == null) { - throw new NullPointerException("blah"); - } - } catch (RuntimeException e) { - System.out.println("catch"); - } - try (InputStream in = createInputStream()) { - System.out.println(in); - } catch (IOException e) { - System.out.println("catch"); - } - try (InputStream in = createInputStream(); - InputStream in2 = createInputStream()) { - System.out.println(in); - } catch (IOException e) { - System.out.println("catch"); - } - try (InputStream in = createInputStream()) { - System.out.println(in); - } - try { - System.out.println("whatever"); - } catch (RuntimeException e) { - System.out.println(e); - } catch (final Exception | Error e) { - System.out.println(e); - } - return JavaParser.parse(file); - } - - class A implements XXX, Serializable { - - public A(Integer integer, ABC string) throws Exception, IOException { - } - } - - private void x(Map x) { - @Deprecated Comparator c = new Comparator() { - - public int compare(Object o1, Object o2) { - try { - A a = new A(new Integer(11), "foo") { - }; - } catch (Exception e) { - } - return 0; - } - - @Override - public boolean equals(Object obj) { - return super.equals(obj); - } - }; - } - - private static InputStream createInputStream() { - return new ByteArrayInputStream(null); - } -} - -class Base { - - public void check2(A val1, B val2) { - } -} - -interface XXX extends Serializable, Cloneable { -} diff --git a/javaparser-core-testing/src/test/test_sourcecode/com/github/javaparser/printer/JavaConceptsBase.java b/javaparser-core-testing/src/test/test_sourcecode/com/github/javaparser/printer/JavaConceptsBase.java new file mode 100644 index 0000000000..0740244055 --- /dev/null +++ b/javaparser-core-testing/src/test/test_sourcecode/com/github/javaparser/printer/JavaConceptsBase.java @@ -0,0 +1,83 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ +package japa.bdd.samples; + +import com.github.javaparser.JavaParser; +import japa.parser.ParseException; +import com.github.javaparser.ast.CompilationUnit; +import java.io.*; +import java.util.*; + +@Deprecated +public class JavaConceptsBase, X> extends Base implements Serializable { + + static Class clz1 = String.class; + + protected Class clz2 = (String.class); + + Class clz3 = int.class; + + Class clz4 = (int.class); + + int[] arr = new int[10]; + + byte bye = 0; + + byte[] byebye = null; + + short sh1, sh2 = 1; + + int intWithUnderscore = 1234_5678; + + long longWithUnderscore = 1234_5678L; + + float floatWithUnderscore = 1_234.5_678f; + + float floatWithUnderscoreAndExponent = 1_234e1_0f; + + double doubleWithUnderscore = 1_234.5_678; + + double doubleWithUnderscoreAndExponent = 1_234e1_0; + + int binaryLiteral = 0b101101; + + List[][] arrLS = (List[][]) new List[10][]; + + int[][][][] arr2 = new int[10][2][1][0]; + + volatile float fff = 0x1.fffeP+127f; + + char cc = 'a'; + + int[][] arr3 = { { 1, 2 }, { 3, 4 } }; + + static int[][] arr4 = {}; + + static { + arr4 = new int[][] { { 2 }, { 1 } }; + } + + { + arr3 = new int[][] { { 2 }, { 1 } }; + } + + public static JavaConceptsBase t; +} diff --git a/javaparser-core-testing/src/test/test_sourcecode/com/github/javaparser/printer/JavaConceptsEnums.java b/javaparser-core-testing/src/test/test_sourcecode/com/github/javaparser/printer/JavaConceptsEnums.java new file mode 100644 index 0000000000..734faabedf --- /dev/null +++ b/javaparser-core-testing/src/test/test_sourcecode/com/github/javaparser/printer/JavaConceptsEnums.java @@ -0,0 +1,70 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ +package japa.bdd.samples; + +@Deprecated +public class JavaConceptsEnums { + + public enum Teste { + + asc, + def + } + + public enum Sexo { + + m, + @Deprecated + f; + + public enum Sexo_ implements Serializable, Cloneable { + + } + } + + @Deprecated + public enum Enum { + + m(1) { + + @Override + void mm() { + } + } + , + f(2) { + + void mm() { + } + } + ; + + native void nnn(); + + transient int x; + + private Enum(int x) { + this.x = x; + } + + abstract void mm(); + } +} diff --git a/javaparser-core-testing/src/test/test_sourcecode/com/github/javaparser/printer/JavaConceptsInnerClasses.java b/javaparser-core-testing/src/test/test_sourcecode/com/github/javaparser/printer/JavaConceptsInnerClasses.java new file mode 100644 index 0000000000..e1eb83c6ca --- /dev/null +++ b/javaparser-core-testing/src/test/test_sourcecode/com/github/javaparser/printer/JavaConceptsInnerClasses.java @@ -0,0 +1,135 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ +package japa.bdd.samples; + +import com.github.javaparser.JavaParser; +import japa.parser.ParseException; +import com.github.javaparser.ast.CompilationUnit; +import org.junit.Ignore; +import java.io.*; +import java.util.*; + +@Ignore +@Deprecated +public class JavaConceptsInnerClasses, X> extends Base implements Serializable { + + public JavaConceptsInnerClasses(int x) { + this.arr[0] = x; + T val1 = null; + E val2 = null; + super.check2(val1, val2); + boolean b = true, y = false; + abstract class X { + + int i = 0; + + public X() { + } + + public void m() { + } + } + @Deprecated + final class Y extends X { + + public Y() { + super(); + JavaConceptsInnerClasses.this.cc = 'c'; + super.i = 1; + Y.super.m(); + } + + public Y(int y) { + super(); + } + + public Y(long x) { + this(); + } + } + } + + public JavaConceptsInnerClasses(String str) { + } + + private class QWE extends JavaConceptsInnerClasses, String> { + + @Deprecated + final int z = 0; + + int i = (int) -1; + + public QWE(String... x) { + super(x[0]); + } + + public QWE(int... x) { + super(x[0]); + i = x[0]; + assert true; + assert 1 == 1 : 2; + { + int iii = 3; + iii += 3; + } + label: { + int iii = 1; + } + ; + ; + int min = -2147483648; + long sl = 123123123123l; + long minl = -9223372036854775808L; + switch(i) { + } + ll: switch(i) { + case 1: + System.out.println(1); + break ll; + default: + { + System.out.println("default"); + break; + } + case 2: + if (t instanceof Base) { + System.out.println(1); + } + i++; + ++i; + } + } + + private synchronized int[] doSomething() { + List x = new ArrayList(); + return new int[] { 1 }; + } + } +} + +class Base { + + public void check2(A val1, B val2) { + } +} + +interface XXX extends Serializable, Cloneable { +} diff --git a/javaparser-core-testing/src/test/test_sourcecode/com/github/javaparser/printer/JavaConceptsMethods.java b/javaparser-core-testing/src/test/test_sourcecode/com/github/javaparser/printer/JavaConceptsMethods.java new file mode 100644 index 0000000000..122fc5b7e4 --- /dev/null +++ b/javaparser-core-testing/src/test/test_sourcecode/com/github/javaparser/printer/JavaConceptsMethods.java @@ -0,0 +1,164 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ +package japa.bdd.samples; + +import com.github.javaparser.JavaParser; +import japa.parser.ParseException; +import com.github.javaparser.ast.CompilationUnit; +import java.io.*; +import java.util.*; + +public class JavaConceptsMethods { + + strictfp double ddd() { + return 0.0; + } + + public static void main(String[] args) throws ParseException, IOException { + int x = 2; + CompilationUnit cu = parse(new File("src/japa/parser/javacc/Parser.java")); + System.out.println(cu); + JavaConcepts teste = new JavaConcepts(2); + JavaConcepts.QWE qwe = teste.new QWE(1); + if (1 + 1 == 2) { + teste = null; + teste = new JavaConcepts(1); + } else { + x = 3; + teste = new JavaConcepts(1); + x = x == 0 ? 2 : 4; + } + if (true) + x = 1; + else + x = 3; + if (true) + x = 1; + else if (false) + x = 3; + else + x = 2; + while (true) { + xxx: while (x == 3) continue xxx; + break; + } + do { + x++; + } while (x < 100); + do x++; while (x < 100); + for (@Deprecated int i : arr4[0]) { + x--; + } + for (@Deprecated final int i = 0, j = 1; i < 10; x++) { + break; + } + int i, j; + for (i = 0, j = 1; i < 10 && j < 2; i++, j--) { + break; + } + } + + public static CompilationUnit parse(@Deprecated File file) throws ParseException, IOException { + String a = ((String) "qwe"); + String x = ((String) clz1.getName()); + int y = ((Integer) (Object) x).intValue(); + synchronized (file) { + file = null; + file = new File(""); + } + try { + if (file == null) { + throw new NullPointerException("blah"); + } + } catch (final NullPointerException e) { + System.out.println("catch"); + } catch (RuntimeException e) { + System.out.println("catch"); + } finally { + System.out.println("finally"); + } + try { + if (file == null) { + throw new NullPointerException("blah"); + } + } finally { + System.out.println("finally"); + } + try { + if (file == null) { + throw new NullPointerException("blah"); + } + } catch (RuntimeException e) { + System.out.println("catch"); + } + try (InputStream in = createInputStream()) { + System.out.println(in); + } catch (IOException e) { + System.out.println("catch"); + } + try (InputStream in = createInputStream(); + InputStream in2 = createInputStream()) { + System.out.println(in); + } catch (IOException e) { + System.out.println("catch"); + } + try (InputStream in = createInputStream()) { + System.out.println(in); + } + try { + System.out.println("whatever"); + } catch (RuntimeException e) { + System.out.println(e); + } catch (final Exception | Error e) { + System.out.println(e); + } + return JavaParser.parse(file); + } + + class A implements XXX, Serializable { + + public A(Integer integer, ABC string) throws Exception, IOException { + } + } + + private void x(Map x) { + @Deprecated Comparator c = new Comparator() { + + public int compare(Object o1, Object o2) { + try { + A a = new A(new Integer(11), "foo") { + }; + } catch (Exception e) { + } + return 0; + } + + @Override + public boolean equals(Object obj) { + return super.equals(obj); + } + }; + } + + private static InputStream createInputStream() { + return new ByteArrayInputStream(null); + } +} diff --git a/javaparser-core-testing/src/test/test_sourcecode/com/github/javaparser/printer/JavaConceptsUgly.java b/javaparser-core-testing/src/test/test_sourcecode/com/github/javaparser/printer/JavaConceptsUgly.java new file mode 100644 index 0000000000..b34d8f0790 --- /dev/null +++ b/javaparser-core-testing/src/test/test_sourcecode/com/github/javaparser/printer/JavaConceptsUgly.java @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ +package japa.bdd.samples; + +@Deprecated +public class JavaConceptsUgly { + + static int x = 0; + + public static void main(String[] args) { + x = +x; + x = ~x; + --x; + boolean b = !false; + x &= 2; + x |= 2; + x ^= 2; + x -= 2; + x %= 2; + x /= 2; + x *= 2; + x <<= 2; + x >>= 2; + x >>>= 2; + b = b || false; + b = b | false; + b = b & false; + b = b ^ false; + b = b != false; + b = x > 1; + b = x < 1; + b = x >= 1; + b = x <= 1; + x = x << 1; + x = x >> 1; + x = x >>> 1; + x = x - 1; + x = x * 1; + x = x % 1; + x = x / 1; + } +} From f5d243fd814ab193aa689b0011c63e932a281ba9 Mon Sep 17 00:00:00 2001 From: Luciano Barcellos Date: Sat, 21 Oct 2023 17:30:19 -0300 Subject: [PATCH 112/136] Some refactoring about checked exceptions --- .../com/github/javaparser/printer/XmlPrinter.java | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/XmlPrinter.java b/javaparser-core/src/main/java/com/github/javaparser/printer/XmlPrinter.java index 6715c2031d..32b07e3430 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/XmlPrinter.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/XmlPrinter.java @@ -57,17 +57,21 @@ public void output(Node node, String name, int level, StringBuilder builder) { public StringWriter stringWriterOutput(Node node, String name) { StringWriter stringWriter = new StringWriter(); - outputDocument(node, name, stringWriter); + try { + outputDocument(node, name, stringWriter); + } catch (XMLStreamException ex) { + throw new RuntimeXMLStreamException(ex); + } return stringWriter; } - public void outputDocument(Node node, String name, Writer writer) { + public void outputDocument(Node node, String name, Writer writer) throws XMLStreamException { XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); + XMLStreamWriter xmlWriter = outputFactory.createXMLStreamWriter(writer); try { - XMLStreamWriter xmlWriter = outputFactory.createXMLStreamWriter(writer); outputDocument(node, name, xmlWriter); - } catch (XMLStreamException ex) { - throw new RuntimeXMLStreamException(ex); + } finally { + xmlWriter.close(); } } From 531b74fe0dda37acdea9a03a3baf417c6256ffbe Mon Sep 17 00:00:00 2001 From: Luciano Barcellos Date: Sat, 21 Oct 2023 17:31:05 -0300 Subject: [PATCH 113/136] Additional assertions on outputNode method parameters --- .../main/java/com/github/javaparser/printer/XmlPrinter.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/XmlPrinter.java b/javaparser-core/src/main/java/com/github/javaparser/printer/XmlPrinter.java index 32b07e3430..34689fd441 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/XmlPrinter.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/XmlPrinter.java @@ -28,6 +28,7 @@ import java.util.List; import static com.github.javaparser.utils.Utils.assertNotNull; +import static com.github.javaparser.utils.Utils.assertNonEmpty; import java.io.StringWriter; import java.io.Writer; import java.util.function.Predicate; @@ -84,6 +85,9 @@ public void outputDocument(Node node, String name, XMLStreamWriter xmlWriter) th public void outputNode(Node node, String name, XMLStreamWriter xmlWriter) throws XMLStreamException { assertNotNull(node); + assertNonEmpty(name); + assertNotNull(xmlWriter); + NodeMetaModel metaModel = node.getMetaModel(); List allPropertyMetaModels = metaModel.getAllPropertyMetaModels(); Predicate nonNullNode = propertyMetaModel -> propertyMetaModel.getValue(node) != null; From ae52c214e59d94f781343a617bdbb9516b6a0ed3 Mon Sep 17 00:00:00 2001 From: Luciano Barcellos Date: Sat, 21 Oct 2023 17:31:38 -0300 Subject: [PATCH 114/136] Code documentation --- .../github/javaparser/printer/XmlPrinter.java | 94 ++++++++++++++++++- 1 file changed, 93 insertions(+), 1 deletion(-) diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/XmlPrinter.java b/javaparser-core/src/main/java/com/github/javaparser/printer/XmlPrinter.java index 34689fd441..634024f299 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/XmlPrinter.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/XmlPrinter.java @@ -47,15 +47,42 @@ public XmlPrinter(boolean outputNodeType) { this.outputNodeType = outputNodeType; } + /** + * Generate a xml string for given AST Node. Tag name of root element in the result document will be "root". + * + * @param node AST node to be converted to XML + * @return XML document corresponding to node + */ public String output(Node node) { return stringWriterOutput(node, "root").toString(); } - // Kept for backward compatibility + /** + * Output XML data from an AST node to a String Builder. This method is kept for backward compatilibity only and + * should be removed in future releases. + * + * @param node AST node to be converted to XML + * @param name Tag name of root element in the resulting document + * @param level Nesting level of node in tree. Not used. + * @param builder Target object to receive the generated XML + */ + @Deprecated public void output(Node node, String name, int level, StringBuilder builder) { builder.append(stringWriterOutput(node, name).toString()); } + /** + * Create a string writer filled with XML document representing an AST node. + *

+ * Returned stringWriter is not closed upon return because doing so {@link StringWriter#close() has no effect}. + * So users of this method are not required to close it. + *

+ * @param node AST node to be converted to XML + * @param name Tag name of root element in the resulting document + * @return Stringwriter filled with XML document + * @throws RuntimeXMLStreamException Unchecked exception wrapping checked {@link XMLStreamException}, when any + * error on producing XML output occours + */ public StringWriter stringWriterOutput(Node node, String name) { StringWriter stringWriter = new StringWriter(); try { @@ -66,6 +93,21 @@ public StringWriter stringWriterOutput(Node node, String name) { return stringWriter; } + /** + * Output the XML Document representing given AST node to given writer. + *

+ * This method creates a {@link XMLStreamWriter} that writes to given writer and delegates execution to + * {@link #outputDocument(Node, String, XMLStreamWriter)} + *

+ *

+ * Provided writer is NOT closed at the end of execution of this method. + *

+ * + * @param node AST node to be converted to XML + * @param name Tag name of root element of document + * @param writer Target to get the document writen to + * @throws XMLStreamException When any error on outputting XML occours + */ public void outputDocument(Node node, String name, Writer writer) throws XMLStreamException { XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); XMLStreamWriter xmlWriter = outputFactory.createXMLStreamWriter(writer); @@ -76,12 +118,55 @@ public void outputDocument(Node node, String name, Writer writer) throws XMLStre } } + /** + * Output the XML Document representing an AST node to given XMLStreamWriter. + *

+ * This method outputs the starting of XML document, then delegates to + * {@link #outputNode(Node, String, XMLStreamWriter) for writing the root element of XML document, and finally + * outputs the ending of XML document. + *

+ *

+ * This method is used when the root element of an XML document corresponds to an AST node. Would an element + * corresponding to an AST node be written as child of another element, then + * {@link #outputNode(String, Node, XMLStreamWriter)} should be used instead. Actually, outputNode is used + * recursively for outputting nested elements from AST. + *

+ *

+ * Provided xmlWriter is NOT closed at the end of execution of this method. + *

+ * + * @param node AST node to be converted to XML + * @param name Tag name of root element of document + * @param xmlWriter Target to get document written to + * @throws XMLStreamException When any error on outputting XML occours + * @see outputNode(String, Node, XMLStreamWriter) + */ public void outputDocument(Node node, String name, XMLStreamWriter xmlWriter) throws XMLStreamException { xmlWriter.writeStartDocument(); outputNode(node, name, xmlWriter); xmlWriter.writeEndDocument(); } + /** + * Output the XML Element representing an AST node to given writer. + *

+ * This method outputs an XML Element with given tag name to writer. It is used recursively for generating nested + * elements corresponding to AST. + *

+ *

+ * For generating a complete XML document from an AST node, {@link outputDocument(String, Node, XMLStreamWriter)} + * should be used instead. + *

+ *

+ * Provided xmlWriter is NOT closed at the end of execution of this method. + *

+ * + * @param node AST node to be converted to XML + * @param name Tag name of element corresponding to node + * @param xmlWriter Target to get XML written to + * @throws XMLStreamException When any error on outputting XML occours + * @see outputDocument(String, Node, XMLStreamWriter) + */ public void outputNode(Node node, String name, XMLStreamWriter xmlWriter) throws XMLStreamException { assertNotNull(node); @@ -162,6 +247,13 @@ public static void print(Node node) { } } +/** + * RuntimeException subclass encapsulationg XMLStreamException. + *

+ * Used for generating methods without checked exceptions, but allowing to selectively capture of XMLStreamException at + * higher levels. + *

+ */ class RuntimeXMLStreamException extends RuntimeException { public RuntimeXMLStreamException(XMLStreamException cause) { From 9d4f0bcdde39648e702748017a1d5b14b6643a2a Mon Sep 17 00:00:00 2001 From: Luciano Barcellos Date: Sat, 21 Oct 2023 17:33:31 -0300 Subject: [PATCH 115/136] Renaming and refactoring (no functional change) --- .../javaparser/printer/XmlPrinterTest.java | 24 +++++++++++-------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java index da637f3292..667fe3e629 100644 --- a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java @@ -32,21 +32,25 @@ import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.BeforeAll; import org.w3c.dom.Document; import org.xml.sax.SAXException; class XmlPrinterTest { - DocumentBuilderFactory dbf; - DocumentBuilder db; - { + // Used for building XML documents + private static DocumentBuilderFactory documentBuilderFactory; + private static DocumentBuilder documentBuilder; + + @BeforeAll + public static void setupDocumentBuilder() { try { - dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - dbf.setCoalescing(true); - dbf.setIgnoringElementContentWhitespace(true); - dbf.setIgnoringComments(true); - db = dbf.newDocumentBuilder(); + documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + documentBuilderFactory.setCoalescing(true); + documentBuilderFactory.setIgnoringElementContentWhitespace(true); + documentBuilderFactory.setIgnoringComments(true); + documentBuilder = documentBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException ex) { throw new RuntimeException(ex); } @@ -54,7 +58,7 @@ class XmlPrinterTest { public Document getDocument(String xml) throws SAXException, IOException { InputStream inputStream = new ByteArrayInputStream(xml.getBytes()); - Document result = db.parse(inputStream); + Document result = documentBuilder.parse(inputStream); result.normalizeDocument(); return result; } From e166273339d79fa29c3aede365dafb788fdf9d5b Mon Sep 17 00:00:00 2001 From: Luciano Barcellos Date: Sat, 21 Oct 2023 17:38:22 -0300 Subject: [PATCH 116/136] Richer error reporting on test --- .../javaparser/printer/XmlPrinterTest.java | 48 +++++++++++++++++-- 1 file changed, 45 insertions(+), 3 deletions(-) diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java index 667fe3e629..e3a391584d 100644 --- a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java @@ -28,10 +28,18 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; +import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; -import static org.junit.jupiter.api.Assertions.assertTrue; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import static org.junit.jupiter.api.Assertions.fail; import org.junit.jupiter.api.BeforeAll; import org.w3c.dom.Document; import org.xml.sax.SAXException; @@ -56,6 +64,21 @@ public static void setupDocumentBuilder() { } } + // Used for serializing XML documents (Necessary only when doing error reporting) + private static TransformerFactory transformerFactory; + private static Transformer transformer; + + @BeforeAll + public static void setupTransformerFactory() { + try { + transformerFactory = TransformerFactory.newInstance(); + transformer = transformerFactory.newTransformer(); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + } catch (TransformerConfigurationException ex) { + throw new RuntimeException(ex); + } + } + public Document getDocument(String xml) throws SAXException, IOException { InputStream inputStream = new ByteArrayInputStream(xml.getBytes()); Document result = documentBuilder.parse(inputStream); @@ -63,8 +86,27 @@ public Document getDocument(String xml) throws SAXException, IOException { return result; } - public void assertXMLEquals(String xml1, String xml2) throws SAXException, IOException { - assertTrue(getDocument(xml1).isEqualNode(getDocument(xml2))); + public String getXML(Document document) throws TransformerException { + StringWriter result = new StringWriter(); // Closing a StringWriter is not needed + transformer.transform(new DOMSource(document), new StreamResult(result)); + return result.toString(); + } + + public void assertXMLEquals(String expected, String actual) throws SAXException, IOException { + final Document expectedDocument = getDocument(expected); + final Document actualDocument = getDocument(actual); + + if (!expectedDocument.isEqualNode(actualDocument)) { + try { + fail(String.format("-- expected:\n%s-- actual:\n%s", + getXML(expectedDocument), getXML(actualDocument))); + } catch(TransformerException ex) { + fail(String.format("" + + "expected: <%s>, but it was <%s>\n" + + "Additionally, a TransformerException was raised when trying to report XML document contents", + expected, actual), ex); + } + } } @Test From 01f5e19fb7a87989b4d8c38f4fc6408764afad5b Mon Sep 17 00:00:00 2001 From: Luciano Barcellos Date: Sat, 21 Oct 2023 17:43:27 -0300 Subject: [PATCH 117/136] Test cleanup and temp file support --- .../javaparser/printer/XmlPrinterTest.java | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java index e3a391584d..a2199b7509 100644 --- a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java @@ -26,9 +26,12 @@ import static com.github.javaparser.StaticJavaParser.parseExpression; import java.io.ByteArrayInputStream; +import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; +import java.util.HashSet; +import java.util.Set; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; @@ -39,8 +42,10 @@ import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; +import org.junit.jupiter.api.AfterEach; import static org.junit.jupiter.api.Assertions.fail; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.w3c.dom.Document; import org.xml.sax.SAXException; @@ -79,6 +84,32 @@ public static void setupTransformerFactory() { } } + /** + * Set of cleanups to be done at the end of each test execution. + */ + private Set cleanupSet; + + /** + * Add given runnable to set of elements to be called. + * + * @param cleanup Object to be called at the end of each test execution + */ + private void onEnd(Cleanup cleanup) { + cleanupSet.add(cleanup); + } + + @BeforeEach + public void clearCleanupSet() { + cleanupSet = new HashSet<>(); + } + + @AfterEach + public void runCleanup() throws Exception { + for (Cleanup cleanup : cleanupSet) { + cleanup.run(); + } + } + public Document getDocument(String xml) throws SAXException, IOException { InputStream inputStream = new ByteArrayInputStream(xml.getBytes()); Document result = documentBuilder.parse(inputStream); @@ -92,6 +123,12 @@ public String getXML(Document document) throws TransformerException { return result.toString(); } + private File createTempFile() throws IOException { + File result = File.createTempFile("javaparser", "test.xml"); + onEnd(result::delete); // Schedule file deletion at the end of Test + return result; + } + public void assertXMLEquals(String expected, String actual) throws SAXException, IOException { final Document expectedDocument = getDocument(expected); final Document actualDocument = getDocument(actual); @@ -141,3 +178,7 @@ void testList() throws SAXException, IOException { assertXMLEquals("", output); } } + +interface Cleanup { + void run() throws Exception; +} From 9d4efde6d5f34cf20d1f69048622a603f15e75c0 Mon Sep 17 00:00:00 2001 From: Luciano Barcellos Date: Sat, 21 Oct 2023 17:44:59 -0300 Subject: [PATCH 118/136] Test streaming to file --- .../javaparser/printer/XmlPrinterTest.java | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java index a2199b7509..ddd90478b3 100644 --- a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java @@ -27,14 +27,18 @@ import static com.github.javaparser.StaticJavaParser.parseExpression; import java.io.ByteArrayInputStream; import java.io.File; +import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.util.HashSet; import java.util.Set; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; +import javax.xml.stream.XMLStreamException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; @@ -177,6 +181,30 @@ void testList() throws SAXException, IOException { assertXMLEquals("", output); } + + // Demonstrate the use of streaming, without use of temporary strings. + @Test + void testStreamToFile() throws SAXException, IOException, XMLStreamException { + + File tempFile = createTempFile(); + + try ( + FileWriter fileWriter = new FileWriter(tempFile, StandardCharsets.UTF_8) + ) { + XmlPrinter xmlOutput = new XmlPrinter(false); + xmlOutput.outputDocument(parseExpression("1+1"), "root", fileWriter); + } + + assertXMLEquals("" + // Expected + + "" + + "" + + "" + + "", + // Actual (Using temporary string for checking results. No one has been used when generating XML) + new String(Files.readAllBytes(tempFile.toPath()), StandardCharsets.UTF_8) + ); + } } interface Cleanup { From a23a0283ada3bd0dbfe74647841a06f778253c1c Mon Sep 17 00:00:00 2001 From: Luciano Barcellos Date: Sat, 21 Oct 2023 17:45:56 -0300 Subject: [PATCH 119/136] Test custom XML --- .../javaparser/printer/XmlPrinterTest.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java index ddd90478b3..9ce7e6f979 100644 --- a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java @@ -38,7 +38,9 @@ import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; +import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamWriter; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; @@ -205,6 +207,47 @@ void testStreamToFile() throws SAXException, IOException, XMLStreamException { new String(Files.readAllBytes(tempFile.toPath()), StandardCharsets.UTF_8) ); } + + @Test + void testCustomXML() throws SAXException, IOException, XMLStreamException { + + StringWriter stringWriter = new StringWriter(); + + XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); + XMLStreamWriter xmlWriter = outputFactory.createXMLStreamWriter(stringWriter); + onEnd(xmlWriter::close); + + XmlPrinter xmlOutput = new XmlPrinter(false); + + xmlWriter.writeStartDocument(); + xmlWriter.writeStartElement("custom"); + + xmlOutput.outputNode(parseExpression("1+1"), "plusExpr", xmlWriter); + xmlOutput.outputNode(parseExpression("a(1,2)"), "callExpr", xmlWriter); + + xmlWriter.writeEndElement(); + xmlWriter.writeEndDocument(); + xmlWriter.close(); + + assertXMLEquals("" + // Expected + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "", + // Actual + stringWriter.toString() + ); + } } interface Cleanup { From d98b68a68e13832e2b341d1c007660823c6c445f Mon Sep 17 00:00:00 2001 From: Luciano Barcellos Date: Sat, 21 Oct 2023 18:34:46 -0300 Subject: [PATCH 120/136] Java 8 compatibility fix. No need to worry about which charset is used, as the same is going to be used for saving and loading. --- .../java/com/github/javaparser/printer/XmlPrinterTest.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java index 9ce7e6f979..626364c2fd 100644 --- a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java @@ -31,7 +31,6 @@ import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.HashSet; import java.util.Set; @@ -191,7 +190,7 @@ void testStreamToFile() throws SAXException, IOException, XMLStreamException { File tempFile = createTempFile(); try ( - FileWriter fileWriter = new FileWriter(tempFile, StandardCharsets.UTF_8) + FileWriter fileWriter = new FileWriter(tempFile) ) { XmlPrinter xmlOutput = new XmlPrinter(false); xmlOutput.outputDocument(parseExpression("1+1"), "root", fileWriter); @@ -204,7 +203,7 @@ void testStreamToFile() throws SAXException, IOException, XMLStreamException { + "" + "", // Actual (Using temporary string for checking results. No one has been used when generating XML) - new String(Files.readAllBytes(tempFile.toPath()), StandardCharsets.UTF_8) + new String(Files.readAllBytes(tempFile.toPath())) ); } From 2df3bf9eeca4c066f461abcfb7ff8f5b9b935cc0 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 23 Oct 2023 21:14:35 +0000 Subject: [PATCH 121/136] chore(deps): update dependency org.apache.maven.plugins:maven-surefire-plugin to v3.2.1 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 7c66d2f286..7ce84ea284 100644 --- a/pom.xml +++ b/pom.xml @@ -304,7 +304,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.1.2 + 3.2.1 org.codehaus.mojo From 6fe751f39d6e89b5a6112f81c0566d902d2be451 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 23 Oct 2023 21:47:53 +0000 Subject: [PATCH 122/136] chore(deps): update dependency org.apache.maven.plugins:maven-dependency-plugin to v3.6.1 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 7ce84ea284..073a13973b 100644 --- a/pom.xml +++ b/pom.xml @@ -329,7 +329,7 @@ org.apache.maven.plugins maven-dependency-plugin - 3.6.0 + 3.6.1 org.codehaus.mojo From c8a226dc50cfbf68658075c014171945264d329f Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 24 Oct 2023 11:19:03 +0000 Subject: [PATCH 123/136] chore(deps): update dependency org.apache.maven.plugins:maven-checkstyle-plugin to v3.3.1 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 073a13973b..468d01b3d1 100644 --- a/pom.xml +++ b/pom.xml @@ -342,7 +342,7 @@ org.apache.maven.plugins maven-checkstyle-plugin - 3.3.0 + 3.3.1 dev-files/JavaParser-CheckStyle.xml true From 0613c33350a44396f282c873e093bf6bd114fc67 Mon Sep 17 00:00:00 2001 From: Oanh Pham Date: Wed, 25 Oct 2023 18:55:20 +1100 Subject: [PATCH 124/136] Modified and added message to UnsupportedOperationException() --- .../printer/lexicalpreservation/LexicalPreservingPrinter.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinter.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinter.java index d1084c9ec0..e35ccd8a3c 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinter.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinter.java @@ -392,7 +392,7 @@ public void concreteListChange(NodeList changedList, ListChangeType type, int } else if (type == AstObserver.ListChangeType.ADDITION) { differenceElements = LEXICAL_DIFFERENCE_CALCULATOR.calculateListAdditionDifference(findNodeListName(changedList), changedList, index, nodeAddedOrRemoved); } else { - throw new UnsupportedOperationException(); + throw new UnsupportedOperationException("Unknown ListChangeType: " + type); } Difference difference = new Difference(differenceElements, nodeText, changedList.getParentNodeForChildren()); difference.apply(); @@ -614,7 +614,7 @@ private static NodeText interpret(Node node, CsmElement csm, NodeText nodeText) // Indentation should probably be dealt with before because an indentation has effects also on the // following lines if (!(element instanceof CsmIndent) && !(element instanceof CsmUnindent)) { - throw new UnsupportedOperationException(element.getClass().getSimpleName()); + throw new UnsupportedOperationException("Unknown element type: " + element.getClass().getSimpleName()); } } } From 6164ac2fc4789173b12f7bad5a43f97f8505e7c7 Mon Sep 17 00:00:00 2001 From: Oanh Pham Date: Thu, 26 Oct 2023 10:42:41 +1100 Subject: [PATCH 125/136] Modified and added message to UnsupportedOperationException() in LexicalDifferenceCalculator --- .../lexicalpreservation/LexicalDifferenceCalculator.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalDifferenceCalculator.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalDifferenceCalculator.java index 7e08f9597c..cd8a633786 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalDifferenceCalculator.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalDifferenceCalculator.java @@ -85,7 +85,7 @@ public Node getChild() { @Override public void prettyPrint(Node node, SourcePrinter printer) { - throw new UnsupportedOperationException(); + throw new UnsupportedOperationException("The prettyPrint method is not supported or implemented"); } /* @@ -262,7 +262,7 @@ private void calculatedSyntaxModelForNode(CsmElement csm, Node node, List Date: Thu, 26 Oct 2023 10:47:43 +1100 Subject: [PATCH 126/136] Modified and added message to UnsupportedOperationException() in Added.java --- .../github/javaparser/printer/lexicalpreservation/Added.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Added.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Added.java index 572a9c2fee..eefa33fe93 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Added.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Added.java @@ -92,7 +92,7 @@ public TextElement toTextElement() { if (element instanceof CsmToken) { return new TokenTextElement(((CsmToken) element).getTokenType(), ((CsmToken) element).getContent()); } - throw new UnsupportedOperationException(element.getClass().getSimpleName()); + throw new UnsupportedOperationException("Unsupported element type: " + element.getClass().getSimpleName()); } /* From 3ba609ec60a179ea1dee315d83f24a4a4bb078dc Mon Sep 17 00:00:00 2001 From: Oanh Pham Date: Thu, 26 Oct 2023 21:44:38 +1100 Subject: [PATCH 127/136] Modified and added message to UnsupportedOperationException() in ConcreteSyntaxModel, Difference and NodeText class --- .../java/com/github/javaparser/printer/ConcreteSyntaxModel.java | 2 +- .../javaparser/printer/lexicalpreservation/Difference.java | 2 +- .../github/javaparser/printer/lexicalpreservation/NodeText.java | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/ConcreteSyntaxModel.java b/javaparser-core/src/main/java/com/github/javaparser/printer/ConcreteSyntaxModel.java index ca1e9ba810..d9b311d6cf 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/ConcreteSyntaxModel.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/ConcreteSyntaxModel.java @@ -222,7 +222,7 @@ public static CsmElement forClass(Class nodeClazz) { throw new IllegalStateException(s); }); if (!concreteSyntaxModelByClass.containsKey(nodeClazz)) { - throw new UnsupportedOperationException(nodeClazz.getSimpleName()); + throw new UnsupportedOperationException("Class " + nodeClazz.getSimpleName() + " not found!"); } return concreteSyntaxModelByClass.get(nodeClazz); } diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java index 6d2a955c0e..d999a7aeb7 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java @@ -365,7 +365,7 @@ void apply() { Removed removed = (Removed) diffElement; applyRemovedDiffElement(removedGroups.get(removed), removed, originalElement, originalElementIsChild, originalElementIsToken); } else { - throw new UnsupportedOperationException("" + diffElement + " vs " + originalElement); + throw new UnsupportedOperationException("Unable to apply operations from " + diffElement.getClass().getSimpleName() + " to " + originalElement.getClass().getSimpleName()); } } } diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/NodeText.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/NodeText.java index abd3ef556a..636fcaef75 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/NodeText.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/NodeText.java @@ -137,7 +137,7 @@ public void remove(TextElementMatcher matcher, boolean potentiallyFollowingWhite elements.remove(i); } } else { - throw new UnsupportedOperationException(); + throw new UnsupportedOperationException("There is no element to remove!"); } } return; From 8ff8b78015736fdd7125086fa22cae4ffb3cc01f Mon Sep 17 00:00:00 2001 From: Oanh Pham Date: Thu, 26 Oct 2023 21:45:15 +1100 Subject: [PATCH 128/136] Changes unknown to not supported --- .../lexicalpreservation/LexicalDifferenceCalculator.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalDifferenceCalculator.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalDifferenceCalculator.java index cd8a633786..7316f7ec22 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalDifferenceCalculator.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalDifferenceCalculator.java @@ -262,7 +262,7 @@ private void calculatedSyntaxModelForNode(CsmElement csm, Node node, List Date: Thu, 26 Oct 2023 21:50:18 +1100 Subject: [PATCH 129/136] Modified exception message thrown for unknown change type --- .../printer/lexicalpreservation/LexicalPreservingPrinter.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinter.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinter.java index e35ccd8a3c..9aece07281 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinter.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinter.java @@ -392,7 +392,7 @@ public void concreteListChange(NodeList changedList, ListChangeType type, int } else if (type == AstObserver.ListChangeType.ADDITION) { differenceElements = LEXICAL_DIFFERENCE_CALCULATOR.calculateListAdditionDifference(findNodeListName(changedList), changedList, index, nodeAddedOrRemoved); } else { - throw new UnsupportedOperationException("Unknown ListChangeType: " + type); + throw new UnsupportedOperationException("Unknown change type: " + type); } Difference difference = new Difference(differenceElements, nodeText, changedList.getParentNodeForChildren()); difference.apply(); From 205e34818a34f6f87182658f46970f83fe3e29c3 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Thu, 26 Oct 2023 23:00:51 +0000 Subject: [PATCH 130/136] chore(deps): update dependency org.apache.maven.plugins:maven-clean-plugin to v3.3.2 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 468d01b3d1..671004ae07 100644 --- a/pom.xml +++ b/pom.xml @@ -200,7 +200,7 @@ org.apache.maven.plugins maven-clean-plugin - 3.3.1 + 3.3.2 org.apache.maven.plugins From 936baefabfb412b87c189eac7281fc2c2a129654 Mon Sep 17 00:00:00 2001 From: Oanh Pham Date: Fri, 27 Oct 2023 18:45:05 +1100 Subject: [PATCH 131/136] Added messages to LambdaExprContext and TypeExtractor --- .../symbolsolver/javaparsermodel/TypeExtractor.java | 4 ++-- .../javaparsermodel/contexts/LambdaExprContext.java | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/TypeExtractor.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/TypeExtractor.java index 54528547dc..226dd07bba 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/TypeExtractor.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/TypeExtractor.java @@ -445,7 +445,7 @@ public ResolvedType visit(UnaryExpr node, Boolean solveLambdas) { @Override public ResolvedType visit(VariableDeclarationExpr node, Boolean solveLambdas) { if (node.getVariables().size() != 1) { - throw new UnsupportedOperationException(); + throw new UnsupportedOperationException("TypeExtractor supports only one variable declaration in a variable declaration expression"); } return facade.convertToUsage(node.getVariables().get(0).getType()); } @@ -563,7 +563,7 @@ private ResolvedType resolveLambda(LambdaExpr node, ResolvedType result) { } else { - throw new UnsupportedOperationException(); + throw new UnsupportedOperationException("Cannot resolve the type of lambda expression body " + lambdaExpr.getBody()); } ResolvedType formalType = functionalMethod.get().returnType(); diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/LambdaExprContext.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/LambdaExprContext.java index 46841127a3..69870f8f64 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/LambdaExprContext.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/LambdaExprContext.java @@ -138,7 +138,7 @@ public Optional solveSymbolAsValue(String name) { Value value = new Value(lambdaType, name); return Optional.of(value); } - throw new UnsupportedOperationException(); + throw new UnsupportedOperationException("functional method is not present in variable declarator"); } if (parentNode instanceof ReturnStmt) { ReturnStmt returnStmt = (ReturnStmt) parentNode; @@ -166,7 +166,7 @@ public Optional solveSymbolAsValue(String name) { Value value = new Value(lambdaType, name); return Optional.of(value); } - throw new UnsupportedOperationException(); + throw new UnsupportedOperationException("functional method is not present in return statement"); } } if (parentNode instanceof CastExpr) { @@ -193,9 +193,9 @@ public Optional solveSymbolAsValue(String name) { Value value = new Value(lambdaType, name); return Optional.of(value); } - throw new UnsupportedOperationException(); + throw new UnsupportedOperationException("functional method is not present in cast expression"); } - throw new UnsupportedOperationException(); + throw new UnsupportedOperationException("Unknown node type: " + parentNode.getClass().getSimpleName()); } } } From 0d6379c328dfab8286a0e074be8c592d09dcac1c Mon Sep 17 00:00:00 2001 From: Oanh Pham Date: Fri, 27 Oct 2023 21:07:00 +1100 Subject: [PATCH 132/136] Added messages to LambdaExprContext --- .../javaparsermodel/contexts/LambdaExprContext.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/LambdaExprContext.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/LambdaExprContext.java index 69870f8f64..3e59d79da9 100644 --- a/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/LambdaExprContext.java +++ b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/LambdaExprContext.java @@ -241,7 +241,7 @@ protected final Optional solveWithAsValue(SymbolDeclarator symbolDeclarat for (ResolvedValueDeclaration decl : symbolDeclarator.getSymbolDeclarations()) { if (decl.getName().equals(name)) { - throw new UnsupportedOperationException(); + throw new UnsupportedOperationException("Symbol with name " + name + " already exists in symbol declarator"); } } return Optional.empty(); From a0e407282d9f4a8e2d08b33076a96dcefe1b316a Mon Sep 17 00:00:00 2001 From: Luciano Barcellos Date: Sun, 29 Oct 2023 10:57:46 -0300 Subject: [PATCH 133/136] Fix: issue #2751 new HashSet()" != "new HashSet<>() Change XML generator so that an empty type argument list is emmitted as an empty XML element. All other empty lists keep not being emmitted. --- .../javaparser/printer/XmlPrinterTest.java | 60 +++++++++++++++++++ .../github/javaparser/printer/XmlPrinter.java | 6 +- 2 files changed, 65 insertions(+), 1 deletion(-) diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java index 626364c2fd..468ed07bc1 100644 --- a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java @@ -247,6 +247,66 @@ void testCustomXML() throws SAXException, IOException, XMLStreamException { stringWriter.toString() ); } + + @Test + void testAbsentTypeParameterList() throws SAXException, IOException, XMLStreamException { + Expression expression = parseExpression("new HashSet()"); + XmlPrinter xmlOutput = new XmlPrinter(false); + String output = xmlOutput.output(expression); + assertXMLEquals("" + // Expected + + "" + + "" + + "" + + "" + + "", + // Actual + output + ); + } + + @Test + void testEmptyTypeParameterList() throws SAXException, IOException, XMLStreamException { + Expression expression = parseExpression("new HashSet<>()"); + XmlPrinter xmlOutput = new XmlPrinter(false); + String output = xmlOutput.output(expression); + assertXMLEquals("" + // Expected + + "" + + "" + + "" + + "" + + "" + + "", + // Actual + output + ); + } + + @Test + void testNonEmptyTypeParameterList() throws SAXException, IOException, XMLStreamException { + Expression expression = parseExpression("new HashSet()"); + XmlPrinter xmlOutput = new XmlPrinter(false); + String output = xmlOutput.output(expression); + assertXMLEquals("" + // Expected + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "", + // Actual + output + ); + } } interface Cleanup { diff --git a/javaparser-core/src/main/java/com/github/javaparser/printer/XmlPrinter.java b/javaparser-core/src/main/java/com/github/javaparser/printer/XmlPrinter.java index 634024f299..3a7d6ddadf 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/printer/XmlPrinter.java +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/XmlPrinter.java @@ -22,6 +22,7 @@ import com.github.javaparser.ast.Node; import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.type.Type; import com.github.javaparser.metamodel.NodeMetaModel; import com.github.javaparser.metamodel.PropertyMetaModel; @@ -42,6 +43,7 @@ public class XmlPrinter { private final boolean outputNodeType; + private static final Class TYPE_CLASS = Type.class; public XmlPrinter(boolean outputNodeType) { this.outputNodeType = outputNodeType; @@ -178,6 +180,8 @@ public void outputNode(Node node, String name, XMLStreamWriter xmlWriter) throws Predicate nonNullNode = propertyMetaModel -> propertyMetaModel.getValue(node) != null; Predicate nonEmptyList = propertyMetaModel -> ((NodeList) propertyMetaModel.getValue(node)).isNonEmpty(); + Predicate typeList = propertyMetaModel -> + TYPE_CLASS == propertyMetaModel.getType(); xmlWriter.writeStartElement(name); @@ -220,7 +224,7 @@ public void outputNode(Node node, String name, XMLStreamWriter xmlWriter) throws allPropertyMetaModels.stream() .filter(PropertyMetaModel::isNodeList) .filter(nonNullNode) - .filter(nonEmptyList) + .filter(nonEmptyList.or(typeList)) .forEach(listMetaModel -> { try { String listName = listMetaModel.getName(); From 3b6558b3c6944aa992ba406b163dd80ac01ac6fb Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Wed, 1 Nov 2023 17:26:11 +0100 Subject: [PATCH 134/136] Update changelog --- changelog.md | 43 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/changelog.md b/changelog.md index db50c4d2af..da31941211 100644 --- a/changelog.md +++ b/changelog.md @@ -1,7 +1,7 @@ -Next Release (Version 3.25.6-snapshot) +Next Release (Version 3.25.7-snapshot) -------------------------------------- -[issues resolved](https://github.com/javaparser/javaparser/milestone/202?closed=1) +[issues resolved](https://github.com/javaparser/javaparser/milestone/203?closed=1) ### Added ### Changed @@ -10,6 +10,45 @@ Next Release (Version 3.25.6-snapshot) ### Fixed ### Security +Version 3.25.6 +-------------- +[issues resolved](https://github.com/javaparser/javaparser/milestone/202?closed=1) + +### Changed + +* reformat javaconcept take 2 (PR [#4167](https://github.com/javaparser/javaparser/pull/4167) by [@JimmyGan437](https://github.com/JimmyGan437)) +* Using JAXP on XMLPrinter implementation (PR [#4166](https://github.com/javaparser/javaparser/pull/4166) by [@lcbarcellos](https://github.com/lcbarcellos)) +* replace deprecated methond calls to their replacements (PR [#4157](https://github.com/javaparser/javaparser/pull/4157) by [@JimmyGan437](https://github.com/JimmyGan437)) +* feat(#4075): Improve the validation error messages (PR [#4116](https://github.com/javaparser/javaparser/pull/4116) by [@volodya-lombrozo](https://github.com/volodya-lombrozo)) + +### Fixed + +* Fix: issue #2751 new HashSet()" != "new HashSet<>() (PR [#4183](https://github.com/javaparser/javaparser/pull/4183) by [@lcbarcellos](https://github.com/lcbarcellos)) +* Fixes #2625 Add messages to thrown exceptions (PR [#4177](https://github.com/javaparser/javaparser/pull/4177) by [@oannhpham](https://github.com/oannhpham)) +* Fix: issue 4163 Calling MethodDeclaration.getDeclarationAsString leads to MethodDelaration.getComment returning no comment (PR [#4165](https://github.com/javaparser/javaparser/pull/4165) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: issue 3673 isAssignableBy method StackOverflowError (PR [#4156](https://github.com/javaparser/javaparser/pull/4156) by [@jlerbsc](https://github.com/jlerbsc)) +* fix: issue 3184 Unable to get the resolved type of class ResolvedReferenceType from T (PR [#4147](https://github.com/javaparser/javaparser/pull/4147) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: issue #3269 Test resources containing included interfaces do not compile (PR [#4139](https://github.com/javaparser/javaparser/pull/4139) by [@jlerbsc](https://github.com/jlerbsc)) +* CalculateResolvedType Type error (PR [#4138](https://github.com/javaparser/javaparser/pull/4138) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: issue #4036 LeastUpperBoundLogic.lub returns null when matches ConditionalExpr (PR [#4137](https://github.com/javaparser/javaparser/pull/4137) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: issue #2484 SymbolResolver on MethodCallExpr fails if method parameter is of kind Class (PR [#4136](https://github.com/javaparser/javaparser/pull/4136) by [@jlerbsc](https://github.com/jlerbsc)) + +### Developer Changes + +* chore(deps): bump com.google.guava:guava from 32.1.2-jre to 32.1.3-jre (PR [#4154](https://github.com/javaparser/javaparser/pull/4154) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): update actions/checkout action to v4 (PR [#4141](https://github.com/javaparser/javaparser/pull/4141) by [@renovate[bot]](https://github.com/apps/renovate)) + +### :heart: Contributors + +Thank You to all contributors who worked on this release! + +* [@lcbarcellos](https://github.com/lcbarcellos) +* [@volodya-lombrozo](https://github.com/volodya-lombrozo) +* [@JimmyGan437](https://github.com/JimmyGan437) +* [@jlerbsc](https://github.com/jlerbsc) +* [@oannhpham](https://github.com/oannhpham) + + Version 3.25.5 -------------- From 962ded3ae07b437b615c276abb5457d1e893bb09 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Wed, 1 Nov 2023 17:27:43 +0100 Subject: [PATCH 135/136] update readme --- readme.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/readme.md b/readme.md index 5284de6ded..918b08b1a2 100644 --- a/readme.md +++ b/readme.md @@ -37,14 +37,14 @@ Just add the following to your maven configuration or tailor to your own depende com.github.javaparser javaparser-symbol-solver-core - 3.25.5 + 3.25.6 ``` **Gradle**: ``` -implementation 'com.github.javaparser:javaparser-symbol-solver-core:3.25.5' +implementation 'com.github.javaparser:javaparser-symbol-solver-core:3.25.6' ``` Since Version 3.5.10, the JavaParser project includes the JavaSymbolSolver. @@ -59,14 +59,14 @@ Using the dependency above will add both JavaParser and JavaSymbolSolver to your com.github.javaparser javaparser-core - 3.25.5 + 3.25.6 ``` **Gradle**: ``` -implementation 'com.github.javaparser:javaparser-core:3.25.5' +implementation 'com.github.javaparser:javaparser-core:3.25.6' ``` Since version 3.6.17 the AST can be serialized to JSON. @@ -78,14 +78,14 @@ There is a separate module for this: com.github.javaparser javaparser-core-serialization - 3.25.5 + 3.25.6 ``` **Gradle**: ``` -implementation 'com.github.javaparser:javaparser-core-serialization:3.25.5' +implementation 'com.github.javaparser:javaparser-core-serialization:3.25.6' ``` ## How To Compile Sources From cf75fd02230e73fde0f3824e9af31f35a2cb93b8 Mon Sep 17 00:00:00 2001 From: jlerbsc Date: Wed, 1 Nov 2023 17:29:16 +0100 Subject: [PATCH 136/136] [maven-release-plugin] prepare release javaparser-parent-3.25.6 --- javaparser-core-generators/pom.xml | 2 +- javaparser-core-metamodel-generator/pom.xml | 2 +- javaparser-core-serialization/pom.xml | 2 +- javaparser-core-testing-bdd/pom.xml | 2 +- javaparser-core-testing/pom.xml | 2 +- javaparser-core/pom.xml | 2 +- javaparser-symbol-solver-core/pom.xml | 2 +- javaparser-symbol-solver-testing/pom.xml | 2 +- pom.xml | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) diff --git a/javaparser-core-generators/pom.xml b/javaparser-core-generators/pom.xml index 45a369769f..ac09961ef7 100644 --- a/javaparser-core-generators/pom.xml +++ b/javaparser-core-generators/pom.xml @@ -3,7 +3,7 @@ javaparser-parent com.github.javaparser - 3.25.6-SNAPSHOT + 3.25.6 4.0.0 diff --git a/javaparser-core-metamodel-generator/pom.xml b/javaparser-core-metamodel-generator/pom.xml index 639fd0cca6..5fcc96f22c 100644 --- a/javaparser-core-metamodel-generator/pom.xml +++ b/javaparser-core-metamodel-generator/pom.xml @@ -3,7 +3,7 @@ javaparser-parent com.github.javaparser - 3.25.6-SNAPSHOT + 3.25.6 4.0.0 diff --git a/javaparser-core-serialization/pom.xml b/javaparser-core-serialization/pom.xml index 1b75642581..947131c5eb 100644 --- a/javaparser-core-serialization/pom.xml +++ b/javaparser-core-serialization/pom.xml @@ -2,7 +2,7 @@ javaparser-parent com.github.javaparser - 3.25.6-SNAPSHOT + 3.25.6 4.0.0 diff --git a/javaparser-core-testing-bdd/pom.xml b/javaparser-core-testing-bdd/pom.xml index ca88a05e62..4fa7c4ead0 100644 --- a/javaparser-core-testing-bdd/pom.xml +++ b/javaparser-core-testing-bdd/pom.xml @@ -2,7 +2,7 @@ javaparser-parent com.github.javaparser - 3.25.6-SNAPSHOT + 3.25.6 4.0.0 diff --git a/javaparser-core-testing/pom.xml b/javaparser-core-testing/pom.xml index 9c2716ed38..c2b2382cde 100644 --- a/javaparser-core-testing/pom.xml +++ b/javaparser-core-testing/pom.xml @@ -2,7 +2,7 @@ javaparser-parent com.github.javaparser - 3.25.6-SNAPSHOT + 3.25.6 4.0.0 diff --git a/javaparser-core/pom.xml b/javaparser-core/pom.xml index b271dcbfd2..b1abcb933f 100644 --- a/javaparser-core/pom.xml +++ b/javaparser-core/pom.xml @@ -2,7 +2,7 @@ javaparser-parent com.github.javaparser - 3.25.6-SNAPSHOT + 3.25.6 4.0.0 diff --git a/javaparser-symbol-solver-core/pom.xml b/javaparser-symbol-solver-core/pom.xml index 02ebfb17a2..d3d3b22320 100644 --- a/javaparser-symbol-solver-core/pom.xml +++ b/javaparser-symbol-solver-core/pom.xml @@ -3,7 +3,7 @@ javaparser-parent com.github.javaparser - 3.25.6-SNAPSHOT + 3.25.6 4.0.0 diff --git a/javaparser-symbol-solver-testing/pom.xml b/javaparser-symbol-solver-testing/pom.xml index 3649400bed..7580360253 100644 --- a/javaparser-symbol-solver-testing/pom.xml +++ b/javaparser-symbol-solver-testing/pom.xml @@ -3,7 +3,7 @@ javaparser-parent com.github.javaparser - 3.25.6-SNAPSHOT + 3.25.6 4.0.0 diff --git a/pom.xml b/pom.xml index 671004ae07..5c0e089dd9 100644 --- a/pom.xml +++ b/pom.xml @@ -14,7 +14,7 @@ com.github.javaparser javaparser-parent pom - 3.25.6-SNAPSHOT + 3.25.6 javaparser-parent https://github.com/javaparser