diff --git a/.github/workflows/create_github_release.yml b/.github/workflows/create_github_release.yml index ab63efb7a3..7925db0aee 100644 --- a/.github/workflows/create_github_release.yml +++ b/.github/workflows/create_github_release.yml @@ -15,7 +15,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout code - uses: actions/checkout@v3.5.2 + uses: actions/checkout@v4.1.1 - name: Create Release id: create_release diff --git a/.github/workflows/prepare_release_changelog.yml b/.github/workflows/prepare_release_changelog.yml index 4b4788fe08..4947bec1d8 100644 --- a/.github/workflows/prepare_release_changelog.yml +++ b/.github/workflows/prepare_release_changelog.yml @@ -17,7 +17,7 @@ jobs: # Check out current repository - name: Fetch Sources - uses: actions/checkout@v3.5.2 + uses: actions/checkout@v4.1.1 # Setup Java 11 environment for the next steps - name: Setup Java @@ -41,11 +41,13 @@ 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<> $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 - name: Output variables diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties index d8b2495a1e..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.1/apache-maven-3.9.1-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 diff --git a/changelog.md b/changelog.md index 468b0ce5cf..dff67ae58d 100644 --- a/changelog.md +++ b/changelog.md @@ -1,24 +1,211 @@ - -Next Release (Version 3.25.4-snapshot) +Next Release (Version 3.25.7-snapshot) -------------------------------------- -[issues resolved](https://github.com/javaparser/javaparser/milestone/200?closed=1) +[issues resolved](https://github.com/javaparser/javaparser/milestone/203?closed=1) ### Added +### Changed +### Deprecated +### Removed +### Fixed +### Security + +Version 3.25.6 +-------------- +[issues resolved](https://github.com/javaparser/javaparser/milestone/202?closed=1) ### Changed -### Deprecated +* 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)) -### Removed +### 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 +-------------- +[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 -### Security +* 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) + +### 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) +### 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) @@ -90,6 +277,7 @@ Thank You to all contributors who worked on this release! * [@jlerbsc](https://github.com/jlerbsc) * [@XenoAmess](https://github.com/XenoAmess) + Version 3.25.2 -------------- [issues resolved](https://github.com/javaparser/javaparser/milestone/198?closed=1) @@ -274,6 +462,7 @@ Thank You to all contributors who worked on this release! * [@marcluque](https://github.com/marcluque) * [@4everTheOne](https://github.com/4everTheOne) + Version 3.24.10 --------------- [issues resolved](https://github.com/javaparser/javaparser/milestone/194?closed=1) @@ -345,6 +534,7 @@ Thank You to all contributors who worked on this release! * [@mernst](https://github.com/mernst) * [@4everTheOne](https://github.com/4everTheOne) + Version 3.24.9 --------------- [issues resolved](https://github.com/javaparser/javaparser/milestone/193?closed=1) @@ -413,6 +603,7 @@ Thank You to all contributors who worked on this release! * [@icmdaf](https://github.com/icmdaf) * [@4everTheOne](https://github.com/4everTheOne) + Version 3.24.8 -------------- [issues resolved](https://github.com/javaparser/javaparser/milestone/192?closed=1) @@ -522,6 +713,7 @@ Thank You to all contributors who worked on this release! * [@Blackgen](https://github.com/Blackgen) * [@jlerbsc](https://github.com/jlerbsc) + Version 3.24.6 -------------- [issues resolved](https://github.com/javaparser/javaparser/milestone/190?closed=1) @@ -648,6 +840,7 @@ Thank You to all contributors who worked on this release! * [@matozoid](https://github.com/matozoid) * [@4everTheOne](https://github.com/4everTheOne) + Version 3.24.4 - Repeat of 3.24.3 --------------------------------- [issues resolved](https://github.com/javaparser/javaparser/milestone/190?closed=1) @@ -770,6 +963,7 @@ Thank You to all contributors who worked on this release! * [@matozoid](https://github.com/matozoid) * [@4everTheOne](https://github.com/4everTheOne) + Version 3.24.3 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/190?closed=1) @@ -881,6 +1075,7 @@ Thank You to all contributors who worked on this release! * [@MysterAitch](https://github.com/MysterAitch) * [@jlerbsc](https://github.com/jlerbsc) + Version 3.24.1 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/189?closed=1) @@ -962,6 +1157,7 @@ Thank You to all contributors who worked on this release! * [@kanghj](https://github.com/kanghj) * [@sergekukharev](https://github.com/sergekukharev) + Version 3.24.0 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/187?closed=1) @@ -1153,6 +1349,7 @@ Thank You to all contributors who worked on this release! * [@4everTheOne](https://github.com/4everTheOne) * [@matozoid](https://github.com/matozoid) + Version 3.23.0 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/185?closed=1) @@ -1318,6 +1515,7 @@ Version 3.22.0 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/183?closed=1) + ### API or Behaviour Change * Implemented isAssignableBy for VoidType - now return `false` instead of throwing `UnsupportedOperationException` ( @@ -1460,14 +1658,11 @@ Version 3.20.0 [issues resolved](https://github.com/javaparser/javaparser/milestone/181?closed=1) ### Added - * Issue #2991 - Added support for Iterables in CombinedTypeSolver (PR [#3033](https://github.com/javaparser/javaparser/pull/3033), by [@4everTheOne](https://github.com/4everTheOne)) * Implemented logic for getAllFields in Annotations (PR [#3097](https://github.com/javaparser/javaparser/pull/3097), by [@4everTheOne](https://github.com/4everTheOne)) - ### Changed - * Issue #2717 - Removed "empty" label from break statement and added additional test for BreakStmt (PR [#3109](https://github.com/javaparser/javaparser/pull/3109), by [@4everTheOne](https://github.com/4everTheOne)) * Issue #2708 - Improvement to the generated code (removal of redundant casts, and additions of `@Override`) @@ -1488,9 +1683,7 @@ Version 3.20.0 (PR [#3110](https://github.com/javaparser/javaparser/pull/3110), by [@dependabot](https://github.com/dependabot)) * Bump junit from 4.13.1 to 4.13.2 (PR [#3129](https://github.com/javaparser/javaparser/pull/3129), by [@dependabot](https://github.com/dependabot)) - ### Fixed - * Issue #3038 and Issue #3071 - Hanging when certain names are resolved (PR [#3072](https://github.com/javaparser/javaparser/pull/3072), by [@col-e](https://github.com/Col-E)) * Javadoc fixes @@ -1500,12 +1693,12 @@ Version 3.20.0 * Issue #3106 - Wrong descriptor for primitive type long (PR [#3107](https://github.com/javaparser/javaparser/pull/3107), by [@jlerbsc](https://github.com/jlerbsc)) + Version 3.19.0 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/180?closed=1) ### Added - * Adding test case on PrettyPrinter indentation (PR [#2950](https://github.com/javaparser/javaparser/pull/2950), by [@jlerbsc](https://github.com/jlerbsc)) * Adding interface Printable for printer @@ -1533,9 +1726,7 @@ Version 3.19.0 (PR [#3068](https://github.com/javaparser/javaparser/pull/3068), by [@4everTheOne](https://github.com/4everTheOne)) * Add unit tests to issue #3074 Unable to delete .jar files after parsing and using symbol solver (re: #3074) (PR [#3076](https://github.com/javaparser/javaparser/pull/3076), by [@jlerbsc](https://github.com/jlerbsc)) - ### Changed - * Minor refactoring regarding indentation management (PR [#2969](https://github.com/javaparser/javaparser/pull/2969), by [@jlerbsc](https://github.com/jlerbsc)) * Minor refactoring regarding indentation management (part2) @@ -1567,14 +1758,10 @@ Version 3.19.0 (PR [#3026](https://github.com/javaparser/javaparser/pull/3026), by [@jlerbsc](https://github.com/jlerbsc)) * Issue #3050 - Minor improvement to thread safety (PR [#3052](https://github.com/javaparser/javaparser/pull/3052), by [@jlerbsc](https://github.com/jlerbsc)) - ### Deprecated - * `PhantomNodeLogic` is now deprecated, with the logic now being handled by the node itself. (PR [#3002](https://github.com/javaparser/javaparser/pull/3002), by [@jlerbsc](https://github.com/jlerbsc)) - ### Fixed - * Fix issue on pretty configuration change (PR [#2979](https://github.com/javaparser/javaparser/pull/2979), by [@jlerbsc](https://github.com/jlerbsc)) * Fix trivial poly expression lambda, method reference, and parenthesized expressions @@ -1610,12 +1797,12 @@ Version 3.19.0 * Issue #3083 Fix choosing the most specific method in case of java.lang.Object argument type (PR [#3084](https://github.com/javaparser/javaparser/pull/3084), by [@jlerbsc](https://github.com/jlerbsc)) + Version 3.18.0 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/179?closed=1) ### Added - * Add a convenient method (hasRange) to the interface NodeWithRange (PR [#2929](https://github.com/javaparser/javaparser/pull/2929), by [@jlerbsc](https://github.com/jlerbsc)) * Add test case to issue 1017 LambdaExpr left side too permissive @@ -1625,9 +1812,7 @@ Version 3.18.0 * Added java 15 (latest released) and java 16 (bleeding edge) language level options, incl. some validators / post processors / configuration options (PR [#2959](https://github.com/javaparser/javaparser/pull/2959), by [@MysterAitch](https://github.com/MysterAitch)) - ### Changed - * Minor change in PrettyPrinterConfiguration : adding default char in enum IndentType (PR [#2948](https://github.com/javaparser/javaparser/pull/2948), by [@jlerbsc](https://github.com/jlerbsc)) * Minor refactoring rename interface Printable to Stringable. Something that has a printable form. I.e., it can be @@ -1641,14 +1826,11 @@ Version 3.18.0 (PR [#2957](https://github.com/javaparser/javaparser/pull/2957), by [@MysterAitch](https://github.com/MysterAitch)) * Bump mockito-core from 3.6.0 to 3.6.28 (PR [#2942](https://github.com/javaparser/javaparser/pull/2942), by dependabot - ### Removed * Removed .travis.yml -- per #2919 (PR [#2958](https://github.com/javaparser/javaparser/pull/2958), by [@MysterAitch](https://github.com/MysterAitch)) - ### Fixed - * Issue 2909 Improving search for the most relevant declaration of the specified class (PR [#2927](https://github.com/javaparser/javaparser/pull/2927), by [@jlerbsc](https://github.com/jlerbsc)) * Issue 2926 NoSuchElementException in PhantomNodeLogic after adding node @@ -1675,12 +1857,11 @@ Version 3.18.0 * Issue 1945 JavaParser choking on multiple generic method calls on the same line (PR [#2966](https://github.com/javaparser/javaparser/pull/2966), by [@jlerbsc](https://github.com/jlerbsc)) + Version 3.17.0 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/178?closed=1) - ### Fixed - * BEHAVIOUR CHANGE: Fix ArrayType brackets precedence (PR [#2758](https://github.com/javaparser/javaparser/pull/2758), by [@iTakeshi](https://github.com/iTakeshi)) * BEHAVIOUR CHANGE: Issue 2535 Comments within method missing indentation @@ -1708,7 +1889,6 @@ Version 3.17.0 (PR [#2795](https://github.com/javaparser/javaparser/pull/2918), by [@jwaataja](https://github.com/jwaataja)) ### Changed - * Updated dependencies, and dependabot config (PR [#2893](https://github.com/javaparser/javaparser/pull/2893), by [@mysteraitch](https://github.com/mysteraitch)) (PR [#2902](https://github.com/javaparser/javaparser/pull/2902), by Dependabot) @@ -1724,10 +1904,10 @@ Version 3.17.0 (PR [#2901](https://github.com/javaparser/javaparser/pull/2901), by [@mysteraitch](https://github.com/mysteraitch)) (PR [#2913](https://github.com/javaparser/javaparser/pull/2913), by [@mernst](https://github.com/mernst)) + Version 3.16.3 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/177?closed=1) - * ADDED: Created MANY test cases for older issues resolved but not directly linked/closed. (PRs [#2838](https://github.com/javaparser/javaparser/pull/2838), @@ -1772,23 +1952,24 @@ Version 3.16.3 * FIXED: Fix issue Solving symbol as value in the case where the scope is a constraint (PR [#2883](https://github.com/javaparser/javaparser/pull/2883), by [@jlerbsc](https://github.com/jlerbsc)) + Version 3.16.2 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/176?closed=1) - * FIXED: Enhanced the handling of line separator, introducing an enum `LineSeparator` that can be used. (PR [#2685](https://github.com/javaparser/javaparser/pull/2685), by [@MysterAitch](https://github.com/MysterAitch)) * FIXED: The generated metamodel classes now have the `@Generated` annotation (PR [#2706](https://github.com/javaparser/javaparser/pull/2706), by [@MysterAitch](https://github.com/MysterAitch)) * various other bugfixes and enhancements + Version 3.16.1 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/175?closed=1) - * FIXED: Fixed typo (PR [#2697](https://github.com/javaparser/javaparser/pull/2697), by [@hfreeb](https://github.com/hfreeb)) + Version 3.16.0 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/174?closed=1) @@ -1842,6 +2023,7 @@ Version 3.15.22 * FIXED: Fixed resolving overloaded static method references (e.g. `String::valueOf` in a stream map/filter) ([#2662](https://github.com/javaparser/javaparser/pull/2662)) + Version 3.15.21 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/172?closed=1) @@ -1863,6 +2045,7 @@ Version 3.15.21 constructor. ([#2619](https://github.com/javaparser/javaparser/pull/2619)) + Version 3.15.20 ------------------ _skipped_ @@ -1877,8 +2060,8 @@ Version 3.15.18 * CHANGED: Dependencies should now all be up-to-date. ([#2572](https://github.com/javaparser/javaparser/pull/2572) / [#2581](https://github.com/javaparser/javaparser/pull/2581)) - - Note that the JavaCC update introduced a breaking change that now requires a StreamProvider to be passed a charset - if using an InputStream source. + - Note that the JavaCC update introduced a breaking change that now requires a StreamProvider to be passed a charset + if using an InputStream source. * FIXED (possible CHANGED/BREAKING): Improvements have been made to method `PositionUtils#nodeContains()` for clarity and precision in behaviour. ([#2502](https://github.com/javaparser/javaparser/pull/2502)) @@ -1944,7 +2127,6 @@ Version 3.15.8 Version 3.15.7 ------------------ - * BREAKING: Range.overlapsWith works slightly different now. [issues resolved](https://github.com/javaparser/javaparser/milestone/162?closed=1) @@ -1955,7 +2137,6 @@ Version 3.15.6 Version 3.15.5 ------------------ - * BREAKING: bugs have been fixed in how SourceRoot configures parsing, so behaviour may change (which can be fixed by setting configuration on SourceRoot correctly.) @@ -1979,7 +2160,6 @@ Version 3.15.1 Version 3.15.0 ------------------ - - The funny "PI" version number messed up the release order in the maven site, so here is a new minor release. [issues resolved](https://github.com/javaparser/javaparser/milestone/153?closed=1) @@ -2002,7 +2182,6 @@ Version 3.14.13 Version 3.14.12 ------------------ - - BREAKING: `NodeWithConstructors` has been merged into `NodeWithMembers`, so if you don't have a very specific need to only find nodes that support constructors, you can use `NodeWithMembers` instead. @@ -2011,7 +2190,6 @@ Version 3.14.12 Version 3.14.11 ------------------ - - BREAKING: the pseudo-language levels have been turned into constants with the same name in the same place. With a little luck everything will keep compiling. @@ -2019,7 +2197,6 @@ Version 3.14.11 Version 3.14.10 (buggy!) ------------------ - - BREAKING: Java 13: `break` no longer has an expression, this was part of a language preview in Java 12 and has been removed in Java 13. - BREAKING: Java 13: `YieldStatement` and the keyword `yield` have been added. @@ -2068,7 +2245,6 @@ Version 3.14.1 Version 3.14.0 ------------------ - * BREAKING: `SuperExpr` and `ThisExpr` used to have an `Expression classExpr`. this has been tightened to `Name typeName` which is more specific and easier to use. Checking if the expression is a `FieldAccessExpr` or `NameExpr` is no longer needed. @@ -2116,7 +2292,6 @@ Version 3.13.3 Version 3.13.2 ------------------ - * Version 3.13.0 and 3.13.1 contain rather bad bugs that have been fixed here. [issues resolved](https://github.com/javaparser/javaparser/milestone/128?closed=1) @@ -2130,14 +2305,12 @@ Version 3.13.1 (buggy!) Version 3.13.0 (buggy!) ------------------ - * "BREAKING": The static `JavaParser.parse...` methods have moved to `StaticJavaParser.parse...`! [issues resolved](https://github.com/javaparser/javaparser/milestone/126?closed=1) Version 3.12.0 ------------------ - * "BREAKING": all deprecated code was removed. If you don't know what to do, try version 3.11.0 and read the Javadoc for the deprecated methods. It tells you what to use instead. @@ -2146,7 +2319,6 @@ Version 3.12.0 Version 3.11.0 ------------------ - * BREAKING: `SwitchEntryStmt` is now `SwitchEntry`, because it was never a statement. * BREAKING: a case in a switch can now have multiple labels, so `SwitchEntry` no longer has an `Expression label`, @@ -2166,7 +2338,6 @@ Version 3.10.1 Version 3.10.0 ------------------ - * slightly breaking: besides `break;` and `break [label];` there is now `break [expression];` like `break 1+2;` or `break "bye!";` . That means that `BreakStmt` no longer has a `label`, it has a `value` which is of type `Expression`. @@ -2181,7 +2352,6 @@ Version 3.9.1 Version 3.9.0 ------------------ - * MAJOR BREAKAGE: modifiers (like public, static, transient) used to be a special case: they were enums stored in an EnumSet. This meant they were not true `Node`s, had to be treated in a special way, and missed some information. @@ -2195,7 +2365,6 @@ Version 3.8.3 Version 3.8.2 ------------------ - * slightly breaking: `ObjectCreationExpr` no longer gets a diamond when constructed with the default constructor. [issues resolved](https://github.com/javaparser/javaparser/milestone/116?closed=1) @@ -2206,14 +2375,12 @@ Version 3.8.1 Version 3.8.0 ------------------ - * A Unicode preprocessing filter is now available again. [issues resolved](https://github.com/javaparser/javaparser/milestone/113?closed=1) Version 3.7.1 ------------------ - * slightly breaking: the enum constants in JsonToken are now capitalized. * slightly breaking: [some obscure methods in the symbol solver changed](https://github.com/javaparser/javaparser/pull/1922) @@ -2222,7 +2389,6 @@ Version 3.7.1 Version 3.7.0 ------------------ - * BREAKING: `ForeachStmt` is now correctly capitalized: `ForEachStmt` * BREAKING: when using modules, everything that was called `...Statement` is now correctly called `...Directive` @@ -2230,7 +2396,6 @@ Version 3.7.0 Version 3.6.27 ------------------ - * The Json serialization now serializes more fields, which *should* not impact existing code. @@ -2238,7 +2403,6 @@ Version 3.6.27 Version 3.6.26 ------------------ - * BREAKING: Node.getData now throws an exception if the data was not set before. This can be rewritten by checking with Node.containsData before doing getData. @@ -2250,7 +2414,6 @@ Version 3.6.25 Version 3.6.24 ------------------ - * `findAncestor(type, predicate)` is now available [issues resolved](https://github.com/javaparser/javaparser/milestone/108?closed=1) @@ -2277,7 +2440,6 @@ Version 3.6.19 Version 3.6.18 ------------------ - * Parsing Java 11 is now supported. * Running on Java 11 is now supported. * Building on JDK 11 is NOT yet supported. @@ -2286,7 +2448,6 @@ Version 3.6.18 Version 3.6.17 ------------------ - * A new artifact was added: javaparser-core-serialization. It contains a JSON serializer, and might get more serializers in the future. @@ -2294,7 +2455,6 @@ Version 3.6.17 Version 3.6.16 ------------------ - * BREAKING: some parts of the module syntax used `Type` where they should have used `Name`. This is now fixed, but your code may need to be adapted if you are parsing modules. @@ -2322,7 +2482,6 @@ Version 3.6.12 Version 3.6.10 & Version 3.6.11 ------------------ - * A mixup during the release put all the issues in the same milestone: [issues resolved](https://github.com/javaparser/javaparser/milestone/94?closed=1) @@ -2334,7 +2493,6 @@ Version 3.6.9 Version 3.6.8 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/92?closed=1) - * Intellij Idea project files were deleted from the repository, so if you have a clone of the JP source, your local files will be deleted as well. Save anything you want to keep. @@ -2346,13 +2504,11 @@ Version 3.6.7 Version 3.6.6 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/90?closed=1) - * You can now configure the parser inside JavaParserTypeSolver. Version 3.6.5 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/89?closed=1) - * Be aware of annotations or indents looking slightly different when output! Version 3.6.4 @@ -2370,20 +2526,17 @@ Version 3.6.2 Version 3.6.1 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/85?closed=1) - * BREAKING: `SymbolSolverQuickSetup` has been removed in favor of `ProjectRoot` and `SymbolSolverCollectionStrategy`. Version 3.6.0 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/84?closed=1) - * @daanschipper added `ProjectRoot` which is used for analysing and storing project structure. * Upgraded version from 3.5.20 to 3.6.0 because people got tired of seeing 3.5. Version 3.5.20 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/83?closed=1) - * Thanks to @daanschipper for the PR :-) Version 3.5.19 @@ -2405,7 +2558,6 @@ Version 3.5.16 Version 3.5.15 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/78?closed=1) - * Java 10 support is complete. * BREAKING: Java language level support has changed to make Java 10 support possible. [Here's a little article about it](https://matozoid.github.io/2017/04/11/enable-java-9-support.html) @@ -2413,7 +2565,6 @@ Version 3.5.15 Version 3.5.14 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/77?closed=1) - * Java 10's `var` can now be parsed and will be turned into a `VarType` node. It can not be resolved yet. * `NodeList` now has a pretty complete set of `...First` and `...Last` methods. @@ -2422,19 +2573,16 @@ Version 3.5.14 Version 3.5.13 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/76?closed=1) - * The Javadoc parser has received a lot of attention. Version 3.5.12 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/75?closed=1) - * Thanks to un0btanium for fixing the readme file! Version 3.5.11 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/74?closed=1) - * BREAKING: `AssignExpr.Operator.AND` is now `AssignExpr.Operator.BINARY_AND`. * BREAKING: `AssignExpr.Operator.OR` is now `AssignExpr.Operator.BINARY_OR`. * `getPrimaryTypeName` and `getPrimaryType` give access to the type that has the same name as the file it came from. @@ -2444,14 +2592,12 @@ Version 3.5.11 Version 3.5.10 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/73?closed=1) - * JavaSymbolSolver is now in the same project as JavaParser, meaning they get released together from now on. * LexicalPreservingPrinter has had a big speed optimization. Version 3.5.9 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/72?closed=1) - * BREAKING: the very confusing constructor `NodeList(Node)` (which sets the parent) was removed. * To avoid using the int type for token kinds, use the new `JavaToken.Kind` enum. It can convert to and from the int kind. @@ -2459,7 +2605,6 @@ Version 3.5.9 Version 3.5.8 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/71?closed=1) - * the module name is now set to com.github.javaparser.core Version 3.5.7 @@ -2469,7 +2614,6 @@ Version 3.5.7 Version 3.5.6 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/69?closed=1) - * `toSomeType()` methods have been added for many types that give more functional access to a subtype. * BETA: the below work on Java Symbol Solver is still ongoing. @@ -2483,13 +2627,11 @@ Version 3.5.5 Version 3.5.4 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/67?closed=1) - * BETA: the below work on Java Symbol Solver is still ongoing. Version 3.5.3 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/66?closed=1) - * Unicode escapes (`\u1234`) are now retained in the AST, but they are now only allowed in comments, string and character literals, and identifiers. * BETA: the below work on Java Symbol Solver is still ongoing. @@ -2497,20 +2639,17 @@ Version 3.5.3 Version 3.5.2 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/65?closed=1) - * The pretty printer now cleans up Javadoc comments. * BETA: the below work on Java Symbol Solver is still ongoing. Version 3.5.1 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/64?closed=1) - * BETA: the below work on Java Symbol Solver is still ongoing. Version 3.5.0 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/63?closed=1) - * A functional visitor API has been added. See [PR 1195](https://github.com/javaparser/javaparser/pull/1195) for now. * Build is working again on Windows thanks to Leonardo Herrera. * The pretty printer now has an option to order imports, also thanks to Leonardo Herrera. @@ -2521,7 +2660,6 @@ Version 3.5.0 Version 3.4.4 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/62?closed=1) - * BETA: the below work on Java Symbol Solver is still ongoing. Version 3.4.3 @@ -2558,6 +2696,7 @@ Version 3.4.1 * `traverseScope` was added to all nodes with a scope, so you can travel through the scope without tripping over (non-) optionality. + Version 3.4.0 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/58?closed=1) @@ -2581,7 +2720,6 @@ Version 3.3.5 Version 3.3.4 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/56?closed=1) - * `SourceZip` has been added. Use it to read source code from jars or zip files. Thank you @ryan-beckett ! @@ -2593,27 +2731,23 @@ Version 3.3.4 Version 3.3.3 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/55?closed=1) - * Parsing a partial java file (like an expression or statement) no longer ignores trailing code. * New memory saving option: turn off token list. Version 3.3.2 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/54?closed=1) - * `VisitorMap` lets you override hashcode/equals for nodes when used as a key for a map. Version 3.3.1 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/53?closed=1) - * The token list is now mutable - see methods on `JavaToken`. This caused mild breakage - some fields have become `Optional`. Version 3.3.0 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/52?closed=1) - * Breaking: `TryStmt::tryBlock` and `EnclosedExpr::inner` were optional for no good reason. Now they are required. * You can now ask a `JavaToken` for its category, which is useful for examining the token list or doing syntax highlighting or so. @@ -2626,13 +2760,11 @@ Version 3.2.12 Version 3.2.11 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/50?closed=1) - * We're up to date with the latest Java 9 module system again. Version 3.2.10 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/49?closed=1) - * `Node.replace(old, new)` was added, including property-specific `X.replaceY(newY)` methods Version 3.2.9 @@ -2667,7 +2799,6 @@ Version 3.2.6 Version 3.2.5 ------------------ [issues resolved](https://github.com/javaparser/javaparser/milestone/45?closed=1) - * `NodeWithCondition` was added on all nodes containing a condition. * Lots of work on improving lexical preservation. * If a file was parsed from a file system, you can now get path information etc. from `CompilationUnit` @@ -2681,7 +2812,6 @@ Version 3.2.4 New style changelog, no more issue numbers, but a link: [issues resolved](https://github.com/javaparser/javaparser/milestone/44?closed=1) and any notable changes: - * the new method `Node.removeForced()` by removing it, or removing the first parent that is optional. This is different from `Node.remove()`, `remove()` only tries to remove the node from the parent and fails if it can't. @@ -2691,7 +2821,6 @@ and any notable changes: Version 3.2.3 ------------------ - * 907 906 905 903 911 910 909 908 smaller improvements and fixes Version 3.2.2 @@ -2730,13 +2859,10 @@ Beta: `TreeStructureVisitor`, and `LexicalPreservingPrinter`. A start has been made on source level support. The default level is Java 8. It can be set to Java 9 like this for a parser *instance*: - ```java private final JavaParser parser = new JavaParser(new ParserConfiguration().setValidator(new Java9Validator())); ``` - and like this for the static parse methods: - ```java QuickJavaParser.getConfiguration().setValidator(new Java9Validator()); ``` @@ -2795,7 +2921,6 @@ This version needs a minor version increase because of a backwards compatability that is what they do now. New: - * 658 718 736 737 we have created a metamodel. It gives information about the structure of the various AST nodes, as if you are introspecting them. You can find it in `javaparser-metamodel`, the main class is `JavaParserMetaModel` @@ -2808,13 +2933,11 @@ If you want to generate your own visitors, you can use the `VisitorGenerator` cl If you want to reuse the code generation utilities, look at module `javaparser-generator-utils` - there is a very useful `SourceRoot` class in there that takes away a lot of file management troubles. - * 538 735 `TreeStructureVisitor` has been added, which should be considered beta. * 220 733 717 749 745 750 743 748 666 732 746 734 733 smaller improvements and fixes Version 3.0.1 ------------------ - * 699 433 325 Javadoc can now be parsed * 703 696 added NodeWithOptionalScope * 702 FieldAccessExpr now implements NodeWithSimpleName, *which means that "field" has been renamed to "name"* @@ -2823,12 +2946,10 @@ Version 3.0.1 Version 3.0.0 ------------------ - * 695 697 689 680 693 691 682 690 677 679 688 684 683 smaller improvements and fixes Version 3.0.0-RC.4 ------------------ - * 668 669 TypeDeclarationStmt became LocalClassDeclarationStmt * 347 665 every node now has some documentation * 660 670 673 four types of import declaration have been merged back into the old ImportDeclaration @@ -2843,7 +2964,6 @@ Version 3.0.0-RC.3 Version 3.0.0-RC.2 ------------------ - * 593 EmptyImportDeclaration and NonEmptyImportDeclaration have been removed * 612 VariableDeclaratorId has been removed. It has been substituted by "SimpleName name" * 614 617 the list of tokens has been linearized and simplified @@ -2853,19 +2973,16 @@ Version 3.0.0-RC.2 Version 3.0.0-RC.1 ------------------ - * 499 601 renames many fields to be more consistent * 596 605 602 604 smaller improvements and fixes Version 3.0.0-alpha.11 ------------------ - * 547 595 Node.range is now using Optional instead of Range.UNKNOWN * 584 588 548 585 bug fixes and improvements Version 3.0.0-alpha.10 ------------------ - * 578 579 577 575 290 570 568 567 562 564 551 bug fixes and improvements Version 3.0.0-alpha.9 @@ -2879,13 +2996,11 @@ Version 3.0.0-alpha.9 Version 3.0.0-alpha.8 ------------------ - * 344 529 turn DumpVisitor into an official PrettyPrinter * 532 508 427 530 531 513 528 cleanups Version 3.0.0-alpha.7 ------------------ - * 515 roll back attempt at using Optional * 522 504 make NodeList not a Node (restores parent/children behaviour to before alpha.4) * 527 526 rename getChildrenNodes to getChildNodes @@ -2893,7 +3008,6 @@ Version 3.0.0-alpha.7 Version 3.0.0-alpha.6 ------------------ - * 503 modified ImportDeclaration hierarchy to have getters for static and "asterisk" again * 506 bug fix @@ -2907,7 +3021,6 @@ Version 3.0.0-alpha.5 Version 3.0.0-alpha.4 ------------------ - * 463 471 nodes can now be removed easily * 491 import handling changed. Instead of "ImportDeclaration", we now have the four types of import as described in the JLS. [See issue](https://github.com/javaparser/javaparser/pull/491) @@ -2927,14 +3040,12 @@ Version 3.0.0-alpha.3 Version 3.0.0-alpha.2 ------------------ - * 157 a new parser frontend, check https://github.com/javaparser/javaparser/pull/447 for explanations * 435 more builder methods like 400 and 405 * 111 440 443 444 445 446 bugs & cleanups Version 3.0.0-alpha.1 ------------------ - * 400 405 introduce many "builder" style methods for constructing code. Thanks DeepSnowNeeL! * 409 remove ASTHelper (methods are now on specific Node subclasses) * 414 JavaParser can now be instantiated and reused. InstanceJavaParser removed @@ -2943,7 +3054,6 @@ Version 3.0.0-alpha.1 Version 2.5.1 ------------- - * 394 OSGi manifest added * 391 fix ModifierVisitor NullPointerException bug * 385 a few new parse methods @@ -2972,7 +3082,6 @@ API breaking changes: Version 2.4.0 ------------- - * several fixes in DumpVisitor for bugs due to lazy initialization * make TypeDeclaration implements DocumentableNode directly * TypedNode interface introduced @@ -2989,7 +3098,6 @@ Version 2.4.0 Version 2.3.0 ------------- - * ClassOrInterfaceType implements NamedNode * DumpVisitor can now be extended * Improved documentation @@ -2997,7 +3105,6 @@ Version 2.3.0 Version 2.1.0 ------------- - * Features * [#75 performance improvement for `PositionUtils.sortByBeginPosition`](https://github.com/javaparser/javaparser/issues/75) * [#64 In getDeclarationAsString parameter names should be optional](https://github.com/javaparser/javaparser/issues/64) @@ -3018,18 +3125,16 @@ Version 2.1.0 Version 2.0.0 ------------- - * support Java 8 Version 1.0.8 (2010-01-17) ------------- - * Fixed issues: - * Issue 17: A refactor suggestion for AnnotationExpr and its subclasses - * Issue 21: Java 5 JavaParser compiled JARs - * Issue 22: Please use java.lang.reflect.Modifier constants in japa.parser.ast.body.ModifierSet - * Issue 27: Implement the "equal" method - * Issue 30: equals and hashCode methods + * Issue 17: A refactor suggestion for AnnotationExpr and its subclasses + * Issue 21: Java 5 JavaParser compiled JARs + * Issue 22: Please use java.lang.reflect.Modifier constants in japa.parser.ast.body.ModifierSet + * Issue 27: Implement the "equal" method + * Issue 30: equals and hashCode methods Version 1.0.7 (2009-04-12) ------------- @@ -3039,7 +3144,6 @@ Version 1.0.7 (2009-04-12) Version 1.0.6 (2009-01-11) ------------- - * Issue 11 fixed: changed method get/setPakage to get/setPackage in the class CompilationUnit * Created new visitor adapter to help AST modification: ModifierVisitorAdapter * Changed visitor adapters to abstract @@ -3052,13 +3156,11 @@ Version 1.0.5 (2008-10-26) Version 1.0.4 (2008-10-07) ------------- - * Moved to javacc 4.1. * The java_1_5.jj can be build alone without compilation errors Version 1.0.3 (2008-09-06) ------------- - * Removed SuperMemberAccessExpr class, it was no longer used * Removed the methods get/setTypeArgs() from ArrayCreationExpr, this node shouldn't have these methods. * Fixed the bug with start/end position of the nodes IntegerLiteralMinValueExpr and LongLiteralMinValueExpr @@ -3066,23 +3168,20 @@ Version 1.0.3 (2008-09-06) Version 1.0.2 (2008-07-20) ------------- - * Issue fixed: Issue 1: Add support for editing AST nodes or create new ones Version 1.0.1 (2008-07-01) ------------- - * Issue fixed: Issue 5: end line and end column equal to begin line and begin column Version 1.0.0 (2008-06-25) ------------- - * Changed version numbering, starting version 1.0.0 * Javadoc done for packages: - * japa.parser - * japa.parser.ast + * japa.parser + * japa.parser.ast * Corrected bug when parsing in multithread: - * JavaParser.setCacheParser(false) must be called before to use the parser concurrent + * JavaParser.setCacheParser(false) must be called before to use the parser concurrent 2008-06-19 ------------- @@ -3093,91 +3192,78 @@ Version 1.0.0 (2008-06-25) ------------- * Bug corrected: NPE in VoidVisitorAdapter - * http://code.google.com/p/javaparser/issues/detail?id=2 + * http://code.google.com/p/javaparser/issues/detail?id=2 2008-06-09 ------------- - * Added Adapters for de visitors 2008-05-28 ------------- - * This project now is published at Google Code: - * http://code.google.com/p/javaparser/ + * http://code.google.com/p/javaparser/ 2008-05-25 ------------- * Added support for comments and javadoc to the tree. - * Javadocs are stored directly to members (BodyDeclaration and all deriveds (classes, methods, fields, etc.)), - accessible by the method getJavadoc(). - * All comments are stored in the CompilationUnit, accessible by the method getComments(). + * Javadocs are stored directly to members (BodyDeclaration and all deriveds (classes, methods, fields, etc.)), + accessible by the method getJavadoc(). + * All comments are stored in the CompilationUnit, accessible by the method getComments(). 2008-04-01 ------------- - * Changed all nodes public attributes to be private and created getters to access them * Changed the methods of the Node getLine e getColumn to getBeginLine and getBeginColumn * Added the methods getEndLine and getEndColumn to the Node class (works only in the BlockNode) 2007-12-22 ------------- - * Corrected ConditionalExpression bug 2007-10-21 ------------- - * Added LGPL License 2007-10-21 ------------- * Bugs corrected: - * Created PackageDeclaration member of CompilationUnit to add suport for annotations in the package declaration + * Created PackageDeclaration member of CompilationUnit to add suport for annotations in the package declaration * Parameterized anonymous constructor invocation * Explicit constructor invotation Type Arguments * ctrl+z ("\u001A") ar end of compilation unit 2007-10-09 ------------- - * EnumConstantDeclaration annotation support corrected * Parssing Java Unicode escape characters suport added 2007-10-03 ------------- - * Bug corrected: "MotifComboPopup.this.super()" statement was generating parser error 2007-10-01 ------------- - * Bug corrected: Casting signed primitive values - ``` double d = (double) -1; ^ ``` - 2007-08-06 ------------- - * Bug with the single line comments in the final of the unit corrected 2007-07-31 ------------- - * Fixed the bug with the following expression: `Class c = (int.class);` 2007-06-26 ------------- - * Bug fixes from Leon Poyyayil work - * suport for hex floating point - * unicode digits in indentifier - * MemberValueArrayInitializer + * suport for hex floating point + * unicode digits in indentifier + * MemberValueArrayInitializer 2007-03-09 ------------- @@ -3191,6 +3277,5 @@ Version 1.0.0 (2008-06-25) 2007-02-01 ------------- - * Many bug fixes * Added line/column to nodes diff --git a/javaparser-core-generators/pom.xml b/javaparser-core-generators/pom.xml index a71bd9334c..b574bbdfe1 100644 --- a/javaparser-core-generators/pom.xml +++ b/javaparser-core-generators/pom.xml @@ -4,7 +4,7 @@ jmlparser-parent io.github.jmltoolkit - 3.25.3 + 3.25.6 4.0.0 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 dc15208531..75b0b086de 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 @@ -50,8 +50,7 @@ public static String castValue(String value, Type requiredType, String valueType if (requiredTypeName.equals(valueType)) return value; - else - return String.format("(%s) %s", requiredTypeName, 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-metamodel-generator/pom.xml b/javaparser-core-metamodel-generator/pom.xml index e9956c7cea..94765bdaed 100644 --- a/javaparser-core-metamodel-generator/pom.xml +++ b/javaparser-core-metamodel-generator/pom.xml @@ -4,7 +4,7 @@ jmlparser-parent io.github.jmltoolkit - 3.25.3 + 3.25.6 4.0.0 diff --git a/javaparser-core-serialization/pom.xml b/javaparser-core-serialization/pom.xml index 5fa292467e..d732a50207 100644 --- a/javaparser-core-serialization/pom.xml +++ b/javaparser-core-serialization/pom.xml @@ -3,7 +3,7 @@ jmlparser-parent io.github.jmltoolkit - 3.25.3 + 3.25.6 4.0.0 diff --git a/javaparser-core-testing-bdd/pom.xml b/javaparser-core-testing-bdd/pom.xml index e3659486fe..55bbbdb30a 100644 --- a/javaparser-core-testing-bdd/pom.xml +++ b/javaparser-core-testing-bdd/pom.xml @@ -3,7 +3,7 @@ jmlparser-parent io.github.jmltoolkit - 3.25.3 + 3.25.6 4.0.0 @@ -121,13 +121,13 @@ org.jbehave jbehave-core - 4.8.3 + 5.2.0 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" diff --git a/javaparser-core-testing/pom.xml b/javaparser-core-testing/pom.xml index dd9b1044d0..874a3cf077 100644 --- a/javaparser-core-testing/pom.xml +++ b/javaparser-core-testing/pom.xml @@ -3,7 +3,7 @@ jmlparser-parent io.github.jmltoolkit - 3.25.3 + 3.25.6 4.0.0 @@ -134,7 +134,7 @@ com.squareup.okhttp3 okhttp - 4.11.0 + 4.12.0 test 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 435ffa9d6c..849745c2f8 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 f2dbd614c6..dbdfe6d674 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()); 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 9586138889..2cff24c989 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.DefaultKeyword.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-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 dc8b91c5c3..fe99fd3951 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.NodeList; @@ -29,8 +30,7 @@ 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.junit.jupiter.api.Assertions.*; class FieldDeclarationTest { @Test @@ -99,4 +99,32 @@ 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); + assertAll( + () -> assertFalse(i.isPublic()), + () -> assertFalse(i.isStatic()), + () -> assertFalse(i.isFinal()) + ); + } } 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/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_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..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) 'assert' keyword is not supported."); + 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-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."); } } 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..144c953814 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/java/com/github/javaparser/printer/PrettyPrintVisitorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/PrettyPrintVisitorTest.java index 78616e3c5b..b5f33f5165 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()); + } } 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..1acb3246b8 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,294 @@ 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.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +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.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; +import javax.xml.transform.TransformerException; +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; class XmlPrinterTest { + + // Used for building XML documents + private static DocumentBuilderFactory documentBuilderFactory; + private static DocumentBuilder documentBuilder; + + @BeforeAll + public static void setupDocumentBuilder() { + try { + 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); + } + } + + // 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); + } + } + + /** + * 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); + result.normalizeDocument(); + return result; + } + + 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(); + } + + 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); + + 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 - 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); } + + // 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) + ) { + 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())) + ); + } + + @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() + ); + } + + @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 { + void run() throws Exception; } 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..ad4d5a743c --- /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-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..fa9d7de1c4 --- /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-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 9fd2e4745f..6cbb11c27d 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,6 +21,20 @@ 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; @@ -36,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.DefaultKeyword.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) { @@ -1493,7 +1494,7 @@ void testArrayPreservation_WithSingleCLanguageStyle() { * Given a field that have arrays declared in C style and * When a marker annotation is added to the code * Assert that the result matches the expected. - *

+ * * Issue: 3419 */ @Test @@ -1640,7 +1641,7 @@ void testClassOrInterfacePreservationWithFullyQualifiedName_MultipleVariablesDec } - // issue 3588 Modifier is removed when removing an annotation. + // issue 3588 Modifier is removed when removing an annotation. @Test void testRemovingInlinedAnnotation() { // Given @@ -1662,7 +1663,7 @@ void testRemovingInlinedAnnotation() { } - // issue 3588 Modifier is removed when removing an annotation. + // issue 3588 Modifier is removed when removing an annotation. @Test void testRemovingInlinedAnnotation_alternate_case() { // Given @@ -1741,6 +1742,86 @@ 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() { 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..0c813ce871 --- /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-testing/src/test/java/com/github/javaparser/utils/SourceRootTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/utils/SourceRootTest.java index 4b49ea8d96..78737041ed 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)); } 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; + } +} diff --git a/javaparser-core/pom.xml b/javaparser-core/pom.xml index ca2aa7c484..cea256cb5a 100644 --- a/javaparser-core/pom.xml +++ b/javaparser-core/pom.xml @@ -3,7 +3,7 @@ jmlparser-parent io.github.jmltoolkit - 3.25.3 + 3.25.6 4.0.0 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 330838ba11..b0e2c0eb9c 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/JavadocParser.java +++ b/javaparser-core/src/main/java/com/github/javaparser/JavadocParser.java @@ -95,17 +95,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()); @@ -127,15 +124,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 fb1dba18c0..f774163840 100644 --- a/javaparser-core/src/main/java/com/github/javaparser/LineEndingProcessingProvider.java +++ b/javaparser-core/src/main/java/com/github/javaparser/LineEndingProcessingProvider.java @@ -114,13 +114,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); @@ -139,9 +138,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 35825c67f5..a89ed44f5d 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; } @@ -128,10 +126,9 @@ private int nextOutputChar() throws IOException { case BACKSLASH: { if (_backslashSeen) { return clearBackSlashSeen(next); - } else { + } return backSlashSeen(); } - } default: { // An arbitrary character. return clearBackSlashSeen(next); @@ -341,17 +338,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); } /** @@ -478,7 +471,7 @@ private static final class PositionMappingBuilder { /** * Creates a {@link PositionMappingBuilder}. * - * @param left The source {@link LineCounter}. + * @param left The source {@link LineCounter}. * @param right The target {@link LineCounter}. */ public PositionMappingBuilder(LineCounter left, LineCounter right) { 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 c726547a49..818dbba9c0 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 @@ -300,10 +300,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) { @@ -395,9 +393,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/Modifier.java b/javaparser-core/src/main/java/com/github/javaparser/ast/Modifier.java index 12d594b884..727cd885ee 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 @@ -127,6 +127,14 @@ public interface Keyword { String name(); } + public static Modifier sealedModifier() { + return new Modifier(DefaultKeyword.SEALED); + } + + public static Modifier nonSealedModifier() { + return new Modifier(DefaultKeyword.NON_SEALED); + } + /** * The Java modifier keywords. */ 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 34479c4d8b..fb4cc7000d 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,7 +153,8 @@ 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)); + protected static final PrinterConfiguration prettyPrinterNoCommentsConfiguration = new DefaultPrinterConfiguration() + .removeOption(new DefaultConfigurationOption(ConfigOption.PRINT_COMMENTS)); @InternalProperty private Range range; @@ -334,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 @@ -366,6 +373,7 @@ public List getChildNodes() { } public void addOrphanComment(Comment comment) { + notifyPropertyChange(ObservableProperty.COMMENT, null, comment); orphanComments.add(comment); comment.setParentNode(this); } @@ -813,9 +821,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")); } @@ -1136,15 +1143,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 c823558766..b8e93805aa 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 @@ -318,9 +318,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/body/CallableDeclaration.java b/javaparser-core/src/main/java/com/github/javaparser/ast/body/CallableDeclaration.java index ee8948dfbb..f476849a9e 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; @@ -37,13 +45,6 @@ import com.github.javaparser.metamodel.CallableDeclarationMetaModel; 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. */ @@ -92,11 +93,13 @@ public CallableDeclaration(TokenRange tokenRange, NodeList modifiers, * @return modifiers * @see Modifier */ + @Override @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public NodeList getModifiers() { return modifiers; } + @Override @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") @SuppressWarnings("unchecked") public T setModifiers(final NodeList modifiers) { @@ -112,11 +115,13 @@ public T setModifiers(final NodeList modifiers) { return (T) this; } + @Override @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public SimpleName getName() { return name; } + @Override @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") @SuppressWarnings("unchecked") public T setName(final SimpleName name) { @@ -132,11 +137,13 @@ public T setName(final SimpleName name) { return (T) this; } + @Override @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public NodeList getParameters() { return parameters; } + @Override @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") @SuppressWarnings("unchecked") public T setParameters(final NodeList parameters) { @@ -152,11 +159,13 @@ public T setParameters(final NodeList parameters) { return (T) this; } + @Override @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public NodeList getThrownExceptions() { return thrownExceptions; } + @Override @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") @SuppressWarnings("unchecked") public T setThrownExceptions(final NodeList thrownExceptions) { @@ -172,11 +181,13 @@ public T setThrownExceptions(final NodeList thrownExceptions) { return (T) this; } + @Override @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public NodeList getTypeParameters() { return typeParameters; } + @Override @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") @SuppressWarnings("unchecked") public T setTypeParameters(final NodeList typeParameters) { 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 cbe16ea2bf..6d409c4fcf 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; @@ -37,10 +42,6 @@ import com.github.javaparser.metamodel.JavaParserMetaModel; 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. @@ -119,6 +120,7 @@ public void accept(final VoidVisitor v, final A arg) { v.visit(this, arg); } + @Override @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public BlockStmt getBody() { return body; @@ -130,6 +132,7 @@ public BlockStmt getBody() { * @param body the body, can not be null * @return this, the ConstructorDeclaration */ + @Override @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public CompactConstructorDeclaration setBody(final BlockStmt body) { assertNotNull(body); @@ -144,11 +147,13 @@ public CompactConstructorDeclaration setBody(final BlockStmt body) { return this; } + @Override @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public NodeList getModifiers() { return modifiers; } + @Override @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public CompactConstructorDeclaration setModifiers(final NodeList modifiers) { assertNotNull(modifiers); @@ -163,11 +168,13 @@ public CompactConstructorDeclaration setModifiers(final NodeList modif return this; } + @Override @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public SimpleName getName() { return name; } + @Override @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public CompactConstructorDeclaration setName(final SimpleName name) { assertNotNull(name); @@ -182,11 +189,13 @@ public CompactConstructorDeclaration setName(final SimpleName name) { return this; } + @Override @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public NodeList getThrownExceptions() { return thrownExceptions; } + @Override @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public CompactConstructorDeclaration setThrownExceptions(final NodeList thrownExceptions) { assertNotNull(thrownExceptions); @@ -201,11 +210,13 @@ public CompactConstructorDeclaration setThrownExceptions(final NodeList getTypeParameters() { return typeParameters; } + @Override @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public CompactConstructorDeclaration setTypeParameters(final NodeList typeParameters) { assertNotNull(typeParameters); 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 4494f3e137..df2add0887 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,10 +43,6 @@ import com.github.javaparser.metamodel.JavaParserMetaModel; 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. *

@@ -105,6 +106,7 @@ public void accept(final VoidVisitor v, final A arg) { v.visit(this, arg); } + @Override @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public BlockStmt getBody() { return body; @@ -116,6 +118,7 @@ public BlockStmt getBody() { * @param body the body, can not be null * @return this, the ConstructorDeclaration */ + @Override @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public ConstructorDeclaration setBody(final BlockStmt body) { assertNotNull(body); 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 e869f35134..b852c79ae7 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 @@ -263,8 +263,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 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 f2b39c8448..0b443defde 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,10 +46,6 @@ import com.github.javaparser.metamodel.OptionalProperty; 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;} * }} @@ -109,6 +110,7 @@ public void accept(final VoidVisitor v, final A arg) { v.visit(this, arg); } + @Override @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public Optional getBody() { return Optional.ofNullable(body); @@ -120,6 +122,7 @@ public Optional getBody() { * @param body the body, can be null * @return this, the MethodDeclaration */ + @Override @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public MethodDeclaration setBody(final BlockStmt body) { if (body == this.body) { @@ -133,11 +136,13 @@ public MethodDeclaration setBody(final BlockStmt body) { return this; } + @Override @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public Type getType() { return type; } + @Override @Generated("com.github.javaparser.generator.core.node.PropertyGenerator") public MethodDeclaration setType(final Type type) { assertNotNull(type); @@ -210,7 +215,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()) { @@ -289,6 +294,7 @@ public boolean remove(Node node) { return super.remove(node); } + @Override @Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator") public MethodDeclaration removeBody() { return setBody((BlockStmt) null); 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 495b3a90de..805edf42f3 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 @@ -141,15 +141,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 c82ec36a31..1e8ce1e4cb 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 @@ -138,9 +138,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 4af5f406c3..3fdf96bed3 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 @@ -127,17 +127,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 77557a2f28..52eaec5cdf 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 @@ -206,9 +206,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 4ac627f518..27b8c87908 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 @@ -134,16 +134,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 4b96e7ba76..69ef75b733 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 @@ -70,9 +70,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 f2b40ddd0e..56070481a3 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 @@ -180,9 +180,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) { @@ -228,16 +227,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); } @@ -260,14 +258,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 135212f152..4eb331987a 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 @@ -176,8 +176,7 @@ private Optional forEachStmtWithVariableDeclarator(VariableDeclarat node = node.get().getParentNode(); if (!node.isPresent() || !(node.get() instanceof ForEachStmt)) { return Optional.empty(); - } else { + } return Optional.of((ForEachStmt) node.get()); } } -} 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 62a1f4daac..9f64097c3f 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,6 +23,7 @@ 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; @@ -37,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. * @@ -44,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/Java17Validator.java b/javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java17Validator.java index 256d49c1dc..5398119d4e 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/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 2d068d50d3..0387cdebc9 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, 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, "inner classes or interfaces are not supported.")); + 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, "Reflection is not supported.")); + 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, "Generics are not supported."); + 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, "Generics are not supported."); + 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, "Try has no finally and no catch."); + reporter.report(n, new UpgradeJavaMessage("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, 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, "Annotations are not supported."); + 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, "Enumerations are not supported.")); + 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, "Varargs are not supported.")); + 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, "For-each loops are not supported.")); + 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, "Static imports are not supported.")); + 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(), "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(), 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, "Only labels allowed in break statements.")); + 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, "Multi-catch is not supported.")); + 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, "Lambdas are not supported.")); + 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, "Modules are not supported.")); + 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, "Switch expressions are not supported.")); + 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, "Use of patterns with instanceof is not supported.")); + 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, "Text Block Literals are not supported.")); + 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, "Record Declarations are not supported.")); + 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.DefaultKeyword.SEALED) || n.hasModifier(Modifier.DefaultKeyword.NON_SEALED), (n, reporter) -> reporter.report(n, "Sealed classes are not supported.")); + final Validator noSealedClasses = new SimpleValidator<>(ClassOrInterfaceDeclaration.class, n -> n.hasModifier(Modifier.DefaultKeyword.SEALED) || n.hasModifier(Modifier.DefaultKeyword.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, "Permitted sub-classes are not supported.")); + 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()); 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 cd798122cb..a579a3ca06 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; @@ -42,7 +43,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..2a317cdadd --- /dev/null +++ b/javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/UpgradeJavaMessage.java @@ -0,0 +1,66 @@ +/* + * 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() + ); + } +} 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 1a2646af87..6f3b29fe00 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 @@ -72,7 +72,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/ConcreteSyntaxModel.java b/javaparser-core/src/main/java/com/github/javaparser/printer/ConcreteSyntaxModel.java index 8e9c3b363b..e8e6a45eba 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 @@ -277,7 +277,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/DefaultPrettyPrinterVisitor.java b/javaparser-core/src/main/java/com/github/javaparser/printer/DefaultPrettyPrinterVisitor.java index 445df43219..339fb05fa4 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 @@ -313,6 +313,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 7f00325d8d..d29c2f299f 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 @@ -313,6 +313,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/XmlPrinter.java b/javaparser-core/src/main/java/com/github/javaparser/printer/XmlPrinter.java index 7f6db33a16..37384c72a1 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,11 +22,19 @@ 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; import java.util.List; import static com.github.javaparser.utils.Utils.assertNotNull; -import static java.util.stream.Collectors.toList; +import static com.github.javaparser.utils.Utils.assertNonEmpty; + +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. @@ -34,62 +42,229 @@ public class XmlPrinter { private final boolean outputNodeType; + private static final Class TYPE_CLASS = Type.class; 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) { - StringBuilder output = new StringBuilder(); - output(node, "root", 0, output); - return output.toString(); + return stringWriterOutput(node, "root").toString(); } + /** + * 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 { + outputDocument(node, name, stringWriter); + } catch (XMLStreamException ex) { + throw new RuntimeXMLStreamException(ex); + } + 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); + try { + outputDocument(node, name, xmlWriter); + } finally { + xmlWriter.close(); + } + } + + /** + * 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); + assertNonEmpty(name); + assertNotNull(xmlWriter); + 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()); - builder.append("<").append(name); + 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); + + // Output node type attribute if (outputNodeType) { - builder.append(attribute("type", metaModel.getTypeName())); + xmlWriter.writeAttribute("type", metaModel.getTypeName()); } - for (PropertyMetaModel attributeMetaModel : attributes) { - builder.append(attribute(attributeMetaModel.getName(), attributeMetaModel.getValue(node).toString())); - } - 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)); - } + + 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); + } + }); + + // 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.or(typeList)) + .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(); } - builder.append(close(name)); + + xmlWriter.writeEndElement(); } - private static String close(String name) { - return ""; + public static void print(Node node) { + System.out.println(new XmlPrinter(true).output(node)); } +} - private static String attribute(String name, String value) { - return " " + name + "='" + value + "'"; +/** + * 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) { + super(cause); } - public static void print(Node node) { - System.out.println(new XmlPrinter(true).output(node)); + public XMLStreamException getXMLStreamCause() { + return (XMLStreamException) super.getCause(); } } 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 623adfb81f..2e1b639d75 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,16 +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.printer.lexicalpreservation.TextElement; 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); @@ -70,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); } @@ -150,4 +148,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..7abf899370 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 6d541ab232..2e82bc0c12 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,35 +20,27 @@ */ 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.printer.lexicalpreservation.TextElement; +import com.github.javaparser.printer.lexicalpreservation.TokenTextElement; 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; } @@ -73,17 +65,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()); } } @@ -103,14 +90,13 @@ 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; } @@ -125,4 +111,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/Added.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Added.java index e9769b58ee..e08e79e1b0 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) { - return new TokenTextElement(((CsmToken) element).getTokenType(), ((CsmToken) element).getContent(null)); - } else { - throw new UnsupportedOperationException(element.getClass().getSimpleName()); } + if (element instanceof CsmToken) { + return new TokenTextElement(((CsmToken) element).getTokenType(), ((CsmToken) element).getContent()); + } + throw new UnsupportedOperationException("Unsupported element type: " + element.getClass().getSimpleName()); } /* 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 e9a39a5a80..4f258b70dc 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,15 +20,15 @@ */ 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; @@ -36,21 +36,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/Difference.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java index ac78aea26d..c16128fe01 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; /** * A Difference should give me a sequence of elements I should find (to indicate the context) followed by a list of elements @@ -79,7 +81,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) @@ -117,7 +119,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(); @@ -149,7 +151,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++; } @@ -163,10 +165,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; } @@ -209,7 +211,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()); } @@ -312,7 +314,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()) { @@ -339,7 +341,7 @@ private boolean isSpaceOrTabElement(NodeText nodeText, int i) { * to the difference (adding and removing the elements provided). */ void apply() { - extractReshuffledDiffElements(diffElements); + ReshuffledDiffElementExtractor.of(nodeText).extract(diffElements); Map removedGroups = combineRemovedElementsToRemovedGroups(); do { boolean isLeftOverDiffElement = applyLeftOverDiffElements(); @@ -358,7 +360,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()); } } } @@ -399,90 +401,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. @@ -845,7 +763,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++; @@ -874,7 +792,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 @@ -890,45 +808,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); - } else { - return index; - } + return Kind.LBRACKET.equals(kind) || Kind.RBRACKET.equals(kind); } private boolean nextIsRightBrace(int index) { @@ -1039,6 +926,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++; @@ -1058,110 +948,73 @@ private void applyAddedDiffElement(Added added) { diffIndex++; } - 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}. + * A list iterator which provides a method to know the current positioning */ - private Map getCorrespondanceBetweenNextOrderAndPreviousOrder(CsmMix elementsFromPreviousOrder, CsmMix elementsFromNextOrder) { - Map correspondanceBetweenNextOrderAndPreviousOrder = new HashMap<>(); - ReadOnlyListIterator previousOrderElementsIterator = new ReadOnlyListIterator(elementsFromPreviousOrder.getElements()); - int syncNextIndex = 0; - while (previousOrderElementsIterator.hasNext()) { - CsmElement pe = previousOrderElementsIterator.next(); - ReadOnlyListIterator nextOrderElementsIterator = new ReadOnlyListIterator(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; - } + public static class ArrayIterator implements ListIterator { - /* - * 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 iterator; - ListIterator elements; - - public ReadOnlyListIterator(List elements) { + 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 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); + ; } } @@ -1173,100 +1026,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/DifferenceElementCalculator.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/DifferenceElementCalculator.java index 953ec7b64b..cc98cea682 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 @@ -69,16 +69,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 @@ -87,18 +90,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()); @@ -113,17 +120,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/LexicalDifferenceCalculator.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalDifferenceCalculator.java index f5337959d8..a6da43a8e3 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; @@ -36,8 +38,6 @@ import com.github.javaparser.printer.concretesyntaxmodel.*; import com.github.javaparser.printer.lexicalpreservation.changes.*; import com.github.javaparser.utils.LineSeparator; -import java.util.*; - class LexicalDifferenceCalculator { /** @@ -70,7 +70,7 @@ void removeIndentationElements() { } } - static class CsmChild implements CsmElement { + public static class CsmChild implements CsmElement { private final Node child; @@ -84,7 +84,16 @@ 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"); + } + + /* + * 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 @@ -252,7 +261,7 @@ private void calculatedSyntaxModelForNode(CsmElement csm, Node node, List matchingTokens = findTokenTextElementForComment((Comment) oldValue, nodeText); if (matchingTokens.size() != 1) { throw new IllegalStateException("The matching comment to be replaced could not be found"); @@ -332,26 +365,28 @@ private boolean isEqualRange(Optional range1, Optional range2) { } /** - * 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. + * 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 where a new comment will be added to + * @param index The position at which the analysis should start */ - private void fixIndentOfMovedNode(NodeText nodeText, int index) { + 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())); @@ -375,7 +410,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 change type: " + type); } Difference difference = new Difference(differenceElements, nodeText, changedList.getParentNodeForChildren()); difference.apply(); @@ -470,11 +505,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())); } @@ -588,7 +620,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; } @@ -599,7 +631,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()); } } } @@ -636,9 +668,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/LookaheadIterator.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LookaheadIterator.java new file mode 100755 index 0000000000..cab076a51f --- /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/NodeText.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/NodeText.java index 3b67344404..9abab110e8 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 @@ -136,7 +136,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; 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..79eb841718 --- /dev/null +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/PeekingIterator.java @@ -0,0 +1,231 @@ +/* + * 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/PhantomNodeLogic.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/PhantomNodeLogic.java index 6b703c1701..79e25e3628 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 @@ -51,15 +51,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 78a92a745d..a153126ff4 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 @@ -176,11 +176,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/ReshuffledDiffElementExtractor.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/ReshuffledDiffElementExtractor.java new file mode 100755 index 0000000000..f0e788ff6a --- /dev/null +++ b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/ReshuffledDiffElementExtractor.java @@ -0,0 +1,218 @@ +package com.github.javaparser.printer.lexicalpreservation; + +import java.util.*; + +import com.github.javaparser.printer.concretesyntaxmodel.CsmElement; +import com.github.javaparser.printer.concretesyntaxmodel.CsmMix; +import com.github.javaparser.printer.concretesyntaxmodel.CsmToken; +import com.github.javaparser.printer.lexicalpreservation.Difference.ArrayIterator; + +public class ReshuffledDiffElementExtractor { + + private final NodeText nodeText; + + 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) { + return new ReshuffledDiffElementExtractor(nodeText); + } + + private ReshuffledDiffElementExtractor(NodeText nodeText) { + this.nodeText = nodeText; + } + + public void extract(List diffElements) { + 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); + PeekingIterator nodeTextIndexOfPreviousElementsIterator = new PeekingIterator<>(nodeTextIndexOfPreviousElements); + Map nodeTextIndexToPreviousCSMIndex = new HashMap<>(); + while (nodeTextIndexOfPreviousElementsIterator.hasNext()) { + int value = nodeTextIndexOfPreviousElementsIterator.next(); + if (value != -1) { + nodeTextIndexToPreviousCSMIndex.put(value, nodeTextIndexOfPreviousElementsIterator.currentIndex()); + } + } + 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 = 0; 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) { + List correspondingIndices = new ArrayList<>(); + PeekingIterator csmElementListIterator = new PeekingIterator<>(elements); + while (csmElementListIterator.hasNext()) { + boolean isFirstIterationOnCsmElements = !csmElementListIterator.hasPrevious(); + int previousCsmElementIndex = csmElementListIterator.previousIndex(); + CsmElement csmElement = csmElementListIterator.next(); + Map potentialMatches = new EnumMap<>(MatchClassification.class); + 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 (!isFirstIterationOnNodeTextElements && !isFirstIterationOnCsmElements) { + TextElement previousTextElement = nodeText.getTextElement(currentTextElementIndex - 1); + hasSamePreviousElement = elements.get(previousCsmElementIndex).isCorrespondingElement(previousTextElement); + } + boolean hasSameNextElement = false; + if (csmElementListIterator.hasNext()) { + TextElement nextTextElement = nodeTextListIterator.peek(); + hasSameNextElement = elements.get(csmElementListIterator.nextIndex()).isCorrespondingElement(nextTextElement); + } + if (hasSamePreviousElement && hasSameNextElement) { + potentialMatches.putIfAbsent(MatchClassification.ALL, currentTextElementIndex); + } else if (hasSamePreviousElement) { + potentialMatches.putIfAbsent(MatchClassification.PREVIOUS_AND_SAME, currentTextElementIndex); + } else if (hasSameNextElement) { + potentialMatches.putIfAbsent(MatchClassification.NEXT_AND_SAME, currentTextElementIndex); + } else { + potentialMatches.putIfAbsent(MatchClassification.SAME_ONLY, currentTextElementIndex); + } + } else if (isAlmostCorrespondingElement(textElement, csmElement)) { + potentialMatches.putIfAbsent(MatchClassification.ALMOST, currentTextElementIndex); + } + } + } + // 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 isAlmostCorrespondingElement(TextElement textElement, CsmElement 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/TextElementIteratorsFactory.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/TextElementIteratorsFactory.java index 44a8f57d7a..8c8db5f473 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/TokenTextElement.java b/javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/TokenTextElement.java index 1406c2a38b..2827e02c0e 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,13 +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; @@ -43,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(); } 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 3132793801..00fdd9d272 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 @@ -61,9 +61,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 8505d8c5cc..6580ef6e6c 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 @@ -59,9 +59,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 d71519b98c..4f0bf224cb 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 @@ -61,9 +61,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 8041783ca4..d95e5cc1c9 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 @@ -122,9 +122,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 87044211f6..f307ccba0e 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 @@ -39,9 +39,8 @@ public interface TypeSolver { default TypeSolver getRoot() { if (getParent() == null) { return this; - } else { - return getParent().getRoot(); } + return getParent().getRoot(); } /** @@ -67,9 +66,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 ad98329e59..3ce3fe6b47 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 @@ -128,9 +128,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 633a4ea9ae..e1f4f46f7d 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 @@ -175,9 +177,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 +188,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/declarations/ResolvedTypeParameterDeclaration.java b/javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedTypeParameterDeclaration.java index 5fb52d0f41..6e483728fa 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 @@ -190,7 +190,7 @@ default boolean hasBound() { */ default boolean hasLowerBound() { for (Bound b : getBounds()) { - if (b.isExtends()) { + if (b.isSuper()) { return true; } } @@ -202,7 +202,7 @@ default boolean hasLowerBound() { */ default boolean hasUpperBound() { for (Bound b : getBounds()) { - if (b.isSuper()) { + if (b.isExtends()) { return true; } } @@ -216,7 +216,7 @@ default boolean hasUpperBound() { */ default ResolvedType getLowerBound() { for (Bound b : getBounds()) { - if (b.isExtends()) { + if (b.isSuper()) { return b.getType(); } } @@ -230,7 +230,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/logic/ConstructorResolutionLogic.java b/javaparser-core/src/main/java/com/github/javaparser/resolution/logic/ConstructorResolutionLogic.java index dd013e48fd..cd343f86e6 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 @@ -151,11 +151,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; @@ -180,8 +180,7 @@ public static SymbolReference findMostApplicable } } } - return SymbolReference.solved(winningCandidate); - } + return SymbolReference.solved(winningCandidate); } private static boolean isMoreSpecific(ResolvedConstructorDeclaration constructorA, ResolvedConstructorDeclaration constructorB, TypeSolver typeSolver) { 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 d7c7835610..84b263a296 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 @@ -51,9 +51,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 ad30efb138..78bb165dce 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 @@ -185,48 +185,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 39da71a69b..e54b256384 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 @@ -109,9 +109,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(); @@ -119,15 +118,14 @@ public ResolvedType equivalentType() { Set notTypeVariables = equivalentTypes.stream().filter(t -> !t.isTypeVariable() && !hasInferenceVariables(t)).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 0e530541d4..a5ddc15293 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 @@ -288,6 +288,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); @@ -295,15 +298,22 @@ 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); + // trying to compare with unbounded wildcard type parameter + if (actualParam.isWildcard() && !actualParam.asWildcard().isBounded()) { + return true; + } + if (actualParam.isTypeVariable()) { + return matchTypeVariable(actualParam.asTypeVariable(), expectedParam.asWildcard().getBoundedType(), matchedParameters); + } + return isAssignableMatchTypeParameters(expectedParam.asWildcard().getBoundedType(), actualParam, matchedParameters); } // TODO verify super bound return true; - } else { - throw new UnsupportedOperationException(expectedParam.describe()); } + throw new UnsupportedOperationException(expectedParam.describe()); } return true; } @@ -314,7 +324,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; @@ -715,9 +726,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 @@ -734,8 +745,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 a4163f72d6..40de0765f1 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 @@ -110,9 +110,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 9d6ecab939..ec235a31fc 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 @@ -24,6 +24,8 @@ 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. * @@ -70,8 +72,14 @@ 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); + } + + /* + * 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/ResolvedPrimitiveType.java b/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedPrimitiveType.java index accb574a87..240f841d71 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 @@ -138,7 +138,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; } @@ -148,9 +149,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() { @@ -180,14 +180,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 ee5f7af9a5..fd947eb579 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 @@ -344,18 +344,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; } @@ -468,9 +469,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 2bef1ebf31..1bced4299a 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 @@ -66,9 +66,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 de8d731205..d512a6b799 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 @@ -79,9 +79,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 @@ -113,9 +112,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/ResolvedUnionType.java b/javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedUnionType.java index 8ba8ec0e8a..c8a565964e 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 @@ -24,6 +24,8 @@ 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. * @@ -83,4 +85,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-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 4734a21d42..944ab7d1f9 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 @@ -101,13 +101,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() { @@ -134,13 +135,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 @@ -157,9 +159,8 @@ public ResolvedType replaceTypeVariables(ResolvedTypeParameterDeclaration tpToRe } if (boundedTypeReplaced != boundedType) { return new ResolvedWildcard(type, boundedTypeReplaced); - } else { - return this; } + return this; } @Override @@ -168,11 +169,11 @@ public boolean mention(List typeParameters) { } public boolean isUpperBounded() { - return isSuper(); + return isExtends(); } public boolean isLowerBounded() { - return isExtends(); + return isSuper(); } public enum BoundType { @@ -189,9 +190,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 a7aff41006..5770838ee7 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 @@ -53,9 +53,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 b9eb32105c..7763358039 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 @@ -102,17 +102,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 ce41db9eb1..8d6b6a13f5 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 @@ -38,7 +38,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); @@ -47,9 +48,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 + "'"); @@ -65,9 +68,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 dbf6ca4a27..29789b7e7e 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 @@ -54,16 +54,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 842ea4cbb7..452dea2e82 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 @@ -121,25 +121,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 bf977eccc9..494ed086de 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 @@ -74,18 +74,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) { @@ -96,9 +94,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) { @@ -110,37 +107,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 eed8c43791..4b173cc7be 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 @@ -598,9 +598,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-core/src/main/javacc/java.jj b/javaparser-core/src/main/javacc/java.jj index 68e4b95a10..dd14ab6c1c 100644 --- a/javaparser-core/src/main/javacc/java.jj +++ b/javaparser-core/src/main/javacc/java.jj @@ -3345,7 +3345,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 - | | | + | | | | | // or a bunch of JML clause words | | | | | | | diff --git a/javaparser-symbol-solver-core/pom.xml b/javaparser-symbol-solver-core/pom.xml index c281117bc9..8eca098770 100644 --- a/javaparser-symbol-solver-core/pom.xml +++ b/javaparser-symbol-solver-core/pom.xml @@ -4,7 +4,7 @@ jmlparser-parent io.github.jmltoolkit - 3.25.3 + 3.25.6 4.0.0 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 0097f50278..24f394432f 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.*; @@ -342,7 +344,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()); } 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/cache/InMemoryCache.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/cache/InMemoryCache.java index a7c0059185..c0cd532c18 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; @@ -46,7 +47,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) { 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 89bcc2b386..710e6d98d3 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; } @@ -627,10 +625,9 @@ private Optional forEachStmtWithVariableDeclarator( node = node.get().getParentNode(); if (!node.isPresent() || !(node.get() instanceof ForEachStmt)) { return Optional.empty(); - } else { + } return Optional.of((ForEachStmt) node.get()); } - } public ResolvedType convert(Type type, Node node) { return convert(type, JavaParserFactory.getContext(node, typeSolver)); 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 d7fa0a8561..399ec64191 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 @@ -69,61 +69,87 @@ public static Context getContext(Node node, TypeSolver typeSolver) { 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) { @@ -140,8 +166,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)) { @@ -150,8 +176,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 a5b287c3fb..a0e1508296 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 @@ -67,8 +67,8 @@ public class TypeExtractor extends DefaultVisitorAdapter { private static final String JAVA_LANG_STRING = String.class.getCanonicalName(); private final ResolvedType stringReferenceType; - private final TypeSolver typeSolver; - private final JavaParserFacade facade; + private TypeSolver typeSolver; + private JavaParserFacade facade; public TypeExtractor(TypeSolver typeSolver, JavaParserFacade facade) { @@ -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 @@ -446,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()); } @@ -496,7 +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(); @@ -504,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(); @@ -512,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) { @@ -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(); @@ -634,7 +634,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/AbstractJavaParserContext.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/AbstractJavaParserContext.java index 496defdcca..f8613623c5 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); @@ -133,7 +128,7 @@ public final Optional getParent() { return Optional.of(parentContext); } - // before to call this method verify the node has a scope + // before to call this method verify the node has a scope protected Node getScope(Node node) { return (Node) ((NodeWithOptionalScope) node).getScope().get(); } @@ -160,7 +155,8 @@ public SymbolReference solveSymbolInParentCo 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 +213,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 +232,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 +241,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()) { + if (typeOfScope.isUnionType()) { return typeOfScope.asUnionType().getCommonAncestor() .flatMap(ResolvedReferenceType::getTypeDeclaration) .map(Collections::singletonList) @@ -289,9 +287,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 ae3a59b990..0b08b12dcd 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 @@ -82,9 +82,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 @@ -135,13 +134,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()); } } @@ -229,28 +231,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 f4e696ee17..de27bfa3d0 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 1456479310..a27f3a33ef 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..6d7e18cb3f 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 cd23ec4876..367697bd80 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,14 +86,23 @@ 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); } } } + // Check class or interface declared in the compilation unit + SymbolReference 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; @@ -145,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) { @@ -185,9 +191,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; } /** @@ -216,9 +221,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 da43d5091d..174847b3e5 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 @@ -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("functional method is not present in variable declarator"); + } + 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("functional method is not present in return statement"); } - } 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("functional method is not present in cast expression"); } + throw new UnsupportedOperationException("Unknown node type: " + parentNode.getClass().getSimpleName()); } } } @@ -243,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(); 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 bb745de3db..4ffbde2d11 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 { @@ -90,10 +92,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 +230,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) { @@ -410,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; @@ -491,35 +563,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 +605,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 ff5f264d59..3958417c44 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 { /// @@ -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(); @@ -103,7 +100,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); @@ -133,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); @@ -159,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()) { @@ -187,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 ec675dbff7..a3251c46ee 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); } @@ -231,14 +233,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 cc01096171..de31f61a50 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..831e54186d 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 38a48e7676..ba6616ec8f 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 c4d0a77c07..3932153802 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 @@ -192,13 +192,12 @@ public Optional getSuperClass() { 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/JavaParserEnumDeclaration.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserEnumDeclaration.java index 89e9b4ee9f..cb2c5fa247 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,6 +375,7 @@ public MethodUsage getUsage(Node node) { throw new UnsupportedOperationException(); } + @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/javaparsermodel/declarations/JavaParserInterfaceDeclaration.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserInterfaceDeclaration.java index 52084d16cb..e79e0cbdd5 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 @@ -339,11 +339,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 dab019c0fc..a2b108b49e 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 cce21bf9da..ab5210484b 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.*; @@ -69,9 +70,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 +92,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 +124,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(); } } } @@ -158,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-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 79fe4de134..177adce146 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 e8e93bcf8c..3e25b03aea 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); - } else { - return qualifiedName; } + return qualifiedName; } @Override 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 bb8e46e25b..9f7838498f 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)) { + 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 interfaceType : getInterfaces()) { - if (interfaceType.isAssignableBy(type)) { + 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/JavassistEnumDeclaration.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistEnumDeclaration.java index 631a949955..dac74e603f 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,6 +179,7 @@ public SymbolReference solveMethod(String name, List< return JavassistUtils.solveMethod(name, argumentsTypes, staticOnly, typeSolver, this, ctClass); } + @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/javassistmodel/JavassistFactory.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistFactory.java index df8603084d..49cc0dcb2c 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 new ReferenceTypeImpl(new JavassistInterfaceDeclaration(ctClazz, typeSolver)); - } else if (ctClazz.isEnum()) { - return new ReferenceTypeImpl(new JavassistEnumDeclaration(ctClazz, typeSolver)); - } else { - return new ReferenceTypeImpl(new JavassistClassDeclaration(ctClazz, typeSolver)); } + if (ctClazz.isEnum()) { + return new ReferenceTypeImpl(new JavassistEnumDeclaration(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); } - } 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; } - } } 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 ca69be99f6..8280438137 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 c86c90c464..ec7766e919 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; @@ -83,17 +85,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); } @@ -214,8 +214,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()) @@ -224,7 +224,6 @@ public List getTypeParameters() { } catch (BadBytecode badBytecode) { throw new RuntimeException(badBytecode); } - } } public Optional containerType() { @@ -237,23 +236,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-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 e2a2815e89..0cd1ff982c 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 7f1bcf8eda..02d2cea19f 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()); } /* @@ -171,9 +172,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) { @@ -183,12 +183,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) { @@ -201,16 +201,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 015e03f4d7..240f7f5c53 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 @@ -85,9 +85,8 @@ public String getClassName() { String qualifiedName = getQualifiedName(); 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/ReflectionAnnotationMemberDeclaration.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionAnnotationMemberDeclaration.java index 9fd5d141c1..c1dbdd9ec8 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; @@ -40,15 +44,18 @@ */ 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)); + valueAsExpressionConverters.put(Class.class, (value) -> { + final ClassOrInterfaceType type = new ClassOrInterfaceType(null, ((Class) value).getSimpleName()); + return new ClassExpr(type); + }); } private Method annotationMember; @@ -62,9 +69,43 @@ public ReflectionAnnotationMemberDeclaration(Method annotationMember, TypeSolver @Override public Expression getDefaultValue() { Object value = annotationMember.getDefaultValue(); - Function fn = valueAsExressionConverter.get(value.getClass()); + 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())); + 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-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 e6f25e1381..eafb77d519 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 */ @@ -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,6 +198,7 @@ public SymbolReference solveMethod(String name, List< typeSolver, this, clazz); } + @Override public Optional solveMethodAsUsage(String name, List parameterTypes, Context invokationContext, List typeParameterValues) { Optional res = ReflectionMethodResolutionLogic.solveMethodAsUsage(name, parameterTypes, typeSolver, invokationContext, 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 631436727e..609e749523 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,6 +29,13 @@ 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 */ @@ -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)) { @@ -106,23 +112,26 @@ public static ResolvedType typeUsageFor(java.lang.reflect.Type type, TypeSolver 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; - } 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 0a40e84501..9aef9b9bc7 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 b13cdb322d..4a53c8768d 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..6e8d6a239a 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 163df52d7a..58feac5cfa 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 @@ -96,7 +96,8 @@ public ResolvedType resolveType() { if (thenExpr.isPrimitive() && elseExpr.isPrimitive()) { if (((ResolvedPrimitiveType) thenExpr).in(resolvedPrimitiveTypeSubList) && elseExpr.equals(ResolvedPrimitiveType.INT)) { return thenExpr; - } else if (((ResolvedPrimitiveType) elseExpr).in(resolvedPrimitiveTypeSubList) && thenExpr.equals(ResolvedPrimitiveType.INT)) { + } + if (((ResolvedPrimitiveType) elseExpr).in(resolvedPrimitiveTypeSubList) && thenExpr.equals(ResolvedPrimitiveType.INT)) { return elseExpr; } } @@ -107,7 +108,8 @@ public ResolvedType resolveType() { // How can we know it? if (thenExpr.isReference() && elseExpr.isPrimitive() && thenExpr.asReferenceType().isUnboxable() && thenExpr.asReferenceType().toUnboxedType().get().in(resolvedPrimitiveTypeSubList) && elseExpr.equals(ResolvedPrimitiveType.INT)) { return thenExpr.asReferenceType().toUnboxedType().get(); - } else if (elseExpr.isReference() && thenExpr.isPrimitive() && elseExpr.asReferenceType().isUnboxable() && elseExpr.asReferenceType().toUnboxedType().get().in(resolvedPrimitiveTypeSubList) && thenExpr.equals(ResolvedPrimitiveType.INT)) { + } + if (elseExpr.isReference() && thenExpr.isPrimitive() && elseExpr.asReferenceType().isUnboxable() && elseExpr.asReferenceType().toUnboxedType().get().in(resolvedPrimitiveTypeSubList) && thenExpr.equals(ResolvedPrimitiveType.INT)) { return elseExpr.asReferenceType().toUnboxedType().get(); } // Otherwise, binary numeric promotion (§5.6.2) is applied to the operand types, 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 cd00a06f17..150b050716 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 401cd0f3cf..c094734677 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/LeastUpperBoundLogic.java b/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/LeastUpperBoundLogic.java index 0347f30843..1644aa2016 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 @@ -41,6 +41,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). @@ -197,6 +201,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-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 a8ea111ea6..2dd77d5a1e 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; @@ -184,9 +183,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) { @@ -233,13 +231,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. @@ -316,9 +308,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 d0e1745c90..5a44fe2558 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 25025198a8..502d28b53a 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 5e199c9bc6..429892cee3 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..d23c39980a 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 1d9ea94c5b..9596d2902e 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 @@ -184,9 +184,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 cf0ca9bffc..298e684c96 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 @@ -268,9 +268,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(); } } diff --git a/javaparser-symbol-solver-testing/pom.xml b/javaparser-symbol-solver-testing/pom.xml index 0db5adb9e6..d119a12a73 100644 --- a/javaparser-symbol-solver-testing/pom.xml +++ b/javaparser-symbol-solver-testing/pom.xml @@ -4,7 +4,7 @@ jmlparser-parent io.github.jmltoolkit - 3.25.3 + 3.25.6 4.0.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/Issue3184Test.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3184Test.java new file mode 100755 index 0000000000..dda4828696 --- /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()); + } + }); + } +} 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..6016e0cb0e --- /dev/null +++ b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3976Test.java @@ -0,0 +1,35 @@ +package com.github.javaparser.symbolsolver; + +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; +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 + @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" + + "}"; + + 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()); + } +} 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..0b4b8cc79e --- /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()); + }); + } +} 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..d86a1b7390 --- /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()); + } +} 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..c0908fa726 --- /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()); + } + +} 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 36698bce61..fa839441c8 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 + 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()); + } @Test 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..c3698ca814 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()); + } + } 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..aeb0f0eb10 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/javassistmodel/JavassistClassDeclarationTest.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistClassDeclarationTest.java index 73b94042e6..14e4661305 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; @@ -539,7 +540,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 +550,18 @@ 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)); + } + + @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)); } } 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 9c639121ea..ffd393ff78 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()"); } } 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 dc052c2f9c..1c566f4c2c 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 { @@ -267,6 +268,7 @@ public ResolvedReferenceTypeTester(ResolvedReferenceTypeDeclaration typeDeclarat super(typeDeclaration); } + @Override public boolean isCorrespondingBoxingType(String name) { return super.isCorrespondingBoxingType(name); } @@ -869,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()); } @@ -927,6 +929,20 @@ void erasure_nested_type() { 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)); @@ -953,15 +969,29 @@ private ResolvedType type(String type, List 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)); } @@ -975,7 +1005,7 @@ 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(); 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/AnalyseJavaSymbolSolver060Test.java b/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/AnalyseJavaSymbolSolver060Test.java index f22190daca..897d3fc244 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 6264198360..60aa366ae3 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,9 +59,9 @@ 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)); + StaticJavaParser.getParserConfiguration().setSymbolResolver(new JavaSymbolSolver(typeSolver)); } @Test @@ -359,4 +361,84 @@ void solveInnerClassAnnotationMember() throws IOException { assertEquals(am.getType().asReferenceType().getQualifiedName(), "foo.bar.MyAnnotationWithInnerClass.MyInnerClass"); } + @Test + void solveReflectionMarkerAnnotationWithDefaultArrayValue() 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[] - {} + 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()); + } + + @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(); + final FieldAccessExpr fieldAccessExpr = assertInstanceOf(FieldAccessExpr.class, enumExpr); + 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(); + 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/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 08ae2f6ff2..fb7a64591a 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 d8c18d6543..5207e5d8da 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 @@ -77,7 +77,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"); @@ -104,7 +104,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"); @@ -146,7 +146,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 d827f5f854..e45a254111 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/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 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 e209b76c93..f2dc4853bb 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 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 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 6d91c5c20f..24f0aa9c66 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 @@ -48,7 +48,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"); @@ -67,7 +67,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"); @@ -86,7 +86,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"); @@ -105,7 +105,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"); @@ -124,7 +124,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"); @@ -143,7 +143,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"); @@ -162,7 +162,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"); @@ -181,7 +181,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"); @@ -200,7 +200,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"); @@ -219,7 +219,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"); @@ -238,7 +238,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"); @@ -257,7 +257,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"); @@ -275,7 +275,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"); @@ -293,7 +293,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"); @@ -311,7 +311,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"); @@ -329,7 +329,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"); @@ -347,7 +347,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"); @@ -365,7 +365,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"); @@ -398,7 +398,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"); @@ -436,7 +436,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; @@ -473,7 +473,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)); @@ -515,7 +515,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)); @@ -548,7 +548,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; @@ -569,7 +569,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"); @@ -588,7 +588,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"); @@ -606,7 +606,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/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 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 93db8e214e..6ed7aa506c 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); 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 0bb5e0f177..d04ecec7e7 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,22 +2,24 @@ 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.net.URISyntaxException; import java.util.*; import java.util.stream.Collectors; -import net.bytebuddy.jar.asm.ClassTooLargeException; import org.junit.jupiter.api.*; import com.github.javaparser.ParserConfiguration; 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; @@ -145,11 +147,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(ClassTooLargeException.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); } @@ -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().describe(), lub.asReferenceType().describe()); + } + @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) { 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 { } 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; } 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() diff --git a/jmlparser-jml-tests/pom.xml b/jmlparser-jml-tests/pom.xml index b7fbe3a537..0c8e89ea6a 100644 --- a/jmlparser-jml-tests/pom.xml +++ b/jmlparser-jml-tests/pom.xml @@ -2,7 +2,7 @@ jmlparser-parent io.github.jmltoolkit - 3.25.3 + 3.25.6 4.0.0 diff --git a/jmlparser-jml-tools/pom.xml b/jmlparser-jml-tools/pom.xml index d2e8575757..452b3a9c47 100644 --- a/jmlparser-jml-tools/pom.xml +++ b/jmlparser-jml-tools/pom.xml @@ -6,7 +6,7 @@ jmlparser-parent io.github.jmltoolkit - 3.25.3 + 3.25.6 jmlparser-jml-tools diff --git a/pom.xml b/pom.xml index 1e179f0213..31a06603f0 100644 --- a/pom.xml +++ b/pom.xml @@ -17,7 +17,7 @@ io.github.jmltoolkit jmlparser-parent pom - 3.25.3 + 3.25.6 jmlparser-parent https://github.com/wadoon/jmlparser @@ -200,7 +200,7 @@ org.apache.maven.plugins maven-clean-plugin - 3.2.0 + 3.3.2 org.apache.maven.plugins @@ -239,7 +239,7 @@ org.apache.maven.plugins maven-release-plugin - 3.0.0 + 3.0.1 true @@ -259,12 +259,12 @@ org.apache.maven.plugins maven-scm-plugin - 2.0.0 + 2.0.1 org.apache.maven.plugins maven-source-plugin - 3.2.1 + 3.3.0 org.eluder.coveralls @@ -281,12 +281,12 @@ org.jacoco jacoco-maven-plugin - 0.8.10 + 0.8.11 org.apache.maven.plugins maven-javadoc-plugin - 3.5.0 + 3.6.0 ${java.version} @@ -312,7 +312,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.0.0-M8 + 3.2.1 org.codehaus.mojo @@ -327,7 +327,7 @@ org.codehaus.mojo build-helper-maven-plugin - 3.3.0 + 3.4.0 org.codehaus.mojo @@ -337,12 +337,12 @@ org.apache.maven.plugins maven-dependency-plugin - 3.5.0 + 3.6.1 org.codehaus.mojo versions-maven-plugin - 2.15.0 + 2.16.1 false @@ -350,7 +350,7 @@ org.apache.maven.plugins maven-checkstyle-plugin - 3.2.2 + 3.3.1 dev-files/JavaParser-CheckStyle.xml true @@ -360,7 +360,7 @@ com.puppycrawl.tools checkstyle - 10.10.0 + 10.12.4 @@ -379,7 +379,7 @@ com.google.guava guava - 31.1-jre + 32.1.3-jre junit @@ -402,19 +402,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 @@ -514,7 +514,7 @@ org.apache.maven.plugins maven-gpg-plugin - 3.0.1 + 3.1.0 sign-artifacts