From deedeecdd7a908322f75c39ca1723febbeb531f4 Mon Sep 17 00:00:00 2001 From: xzl Date: Wed, 8 May 2024 14:30:38 +0800 Subject: [PATCH] feat: update javaparser to 3.25.10+dfsg Java library for parsing Java 7 Issue: https://github.com/deepin-community/sig-deepin-sysdev-team/issues/547 Log: update repo --- .mvn/wrapper/MavenWrapperDownloader.java | 117 + .mvn/wrapper/maven-wrapper.properties | 18 + CONTRIBUTING.md | 30 + FEATURES.md | 309 + LICENSE | 6 + LICENSE.APACHE | 202 + LICENSE.GPL | 674 ++ LICENSE.LGPL | 165 + PULL_REQUEST_TEMPLATE.md | 1 + README.md | 1 - appveyor.yml | 42 + changelog.md | 2867 +++++ codecov.yml | 90 + debian/README.source | 9 + debian/changelog | 63 +- debian/compat | 1 - debian/control | 46 +- debian/copyright | 35 +- debian/libjavaparser-java.poms | 9 + debian/maven.ignoreRules | 6 + debian/maven.rules | 1 + debian/patches/javacc_coordinates.patch | 35 + debian/patches/series | 1 + debian/upstream/metadata | 5 + debian/watch | 3 + dev-files/JavaParser-CheckStyle.xml | 46 + dev-files/JavaParser-eclipse.xml | 295 + dev-files/JavaParser-idea.xml | 38 + dev-files/settings.xml | 35 + doc/component_diagram.puml | 29 + doc/readme.md | 132 + javaparser-core-generators/pom.xml | 55 + .../generator/CompilationUnitGenerator.java | 46 + .../javaparser/generator/Generator.java | 125 + .../javaparser/generator/NodeGenerator.java | 83 + .../generator/VisitorGenerator.java | 103 + .../generator/core/CoreGenerator.java | 104 + .../generator/core/node/AcceptGenerator.java | 55 + .../generator/core/node/CloneGenerator.java | 50 + .../core/node/GetMetaModelGenerator.java | 51 + .../core/node/MainConstructorGenerator.java | 75 + .../core/node/NodeModifierGenerator.java | 41 + .../core/node/PropertyGenerator.java | 177 + .../core/node/RemoveMethodGenerator.java | 113 + .../core/node/ReplaceMethodGenerator.java | 97 + .../core/node/TypeCastingGenerator.java | 131 + .../generator/core/other/BndGenerator.java | 78 + .../core/other/GrammarLetterGenerator.java | 75 + .../core/other/TokenKindGenerator.java | 92 + .../core/quality/NotNullGenerator.java | 208 + .../generator/core/utils/CodeUtils.java | 57 + .../core/visitor/CloneVisitorGenerator.java | 86 + .../core/visitor/EqualsVisitorGenerator.java | 69 + .../GenericListVisitorAdapterGenerator.java | 77 + .../GenericVisitorAdapterGenerator.java | 68 + .../core/visitor/GenericVisitorGenerator.java | 44 + .../GenericVisitorWithDefaultsGenerator.java | 48 + .../visitor/HashCodeVisitorGenerator.java | 80 + .../visitor/ModifierVisitorGenerator.java | 124 + .../NoCommentEqualsVisitorGenerator.java | 76 + .../NoCommentHashCodeVisitorGenerator.java | 89 + .../ObjectIdentityEqualsVisitorGenerator.java | 48 + ...bjectIdentityHashCodeVisitorGenerator.java | 47 + .../visitor/VoidVisitorAdapterGenerator.java | 64 + .../core/visitor/VoidVisitorGenerator.java | 44 + .../VoidVisitorWithDefaultsGenerator.java | 48 + .../core/quality/NotNullGeneratorTest.java | 81 + .../generator/core/utils/CodeUtilsTest.java | 52 + .../expected/ConstructorParameterTest.java | 42 + .../ConstructorParameterWithSuperTest.java | 36 + .../expected/MethodParameterRerunTest.java | 31 + .../expected/MethodParameterTest.java | 33 + .../original/ConstructorParameterTest.java | 40 + .../ConstructorParameterWithSuperTest.java | 34 + .../original/MethodParameterRerunTest.java | 31 + .../original/MethodParameterTest.java | 31 + javaparser-core-metamodel-generator/pom.xml | 63 + .../generator/AbstractGenerator.java | 343 + .../generator/metamodel/AstTypeAnalysis.java | 72 + ...structorParametersStatementsGenerator.java | 79 + ...PropertyMetaModelsStatementsGenerator.java | 98 + .../metamodel/MetaModelGenerator.java | 283 + .../metamodel/NodeMetaModelGenerator.java | 185 + javaparser-core-serialization/pom.xml | 71 + .../JavaParserJsonDeserializer.java | 208 + .../JavaParserJsonSerializer.java | 203 + .../JavaParserJsonDeserializerTest.java | 235 + .../JavaParserJsonSerializerTest.java | 62 + javaparser-core-testing-bdd/pom.xml | 132 + .../github/javaparser/BasicJBehaveTest.java | 65 + .../github/javaparser/CommentParsingTest.java | 42 + .../com/github/javaparser/ComparingTest.java | 51 + .../github/javaparser/ManipulationTest.java | 49 + .../com/github/javaparser/ParsingTest.java | 51 + .../github/javaparser/PositionRangeTest.java | 51 + .../github/javaparser/PrettyPrintingTest.java | 42 + .../java/com/github/javaparser/TestUtils.java | 37 + .../com/github/javaparser/VisitorTest.java | 51 + .../javaparser/steps/CommentParsingSteps.java | 432 + .../javaparser/steps/ComparingSteps.java | 61 + .../steps/ExistenceOfParentNodeVerifier.java | 551 + .../javaparser/steps/ManipulationSteps.java | 285 + .../github/javaparser/steps/ParsingSteps.java | 344 + .../javaparser/steps/PositionRangeSteps.java | 128 + .../javaparser/steps/PrettyPrintingSteps.java | 112 + .../github/javaparser/steps/SharedSteps.java | 163 + .../github/javaparser/steps/VisitorSteps.java | 171 + .../visitors/PositionTestVisitor.java | 562 + .../comment_attribution_scenarios.story | 498 + .../comment_parsing_scenarios.story | 281 + .../javaparser/comparing_scenarios.story | 19 + .../javaparser/manipulation_scenarios.story | 137 + .../github/javaparser/parsing_scenarios.story | 500 + .../javaparser/position_range_scenarios.story | 55 + .../pretty_printing_java_concepts.story | 400 + .../pretty_printing_scenarios.story | 520 + .../javaparser/samples/ClassInLatin1.java | 6 + .../javaparser/samples/JavaConcepts.java | 397 + .../javaparser/samples/package-info.java | 5 + .../github/javaparser/visitor_scenarios.story | 67 + javaparser-core-testing/pom.xml | 143 + .../javaparser/CommentsInserterTest.java | 113 + .../github/javaparser/ExpectedTokensTest.java | 73 + .../GeneratedJavaParserTokenManagerTest.java | 39 + .../com/github/javaparser/Issue1017Test.java | 38 + .../com/github/javaparser/Issue2482Test.java | 75 + .../com/github/javaparser/Issue3064Test.java | 62 + .../com/github/javaparser/Issue3577Test.java | 46 + .../javaparser/JavaParserAdapterTest.java | 287 + .../com/github/javaparser/JavaParserTest.java | 329 + .../com/github/javaparser/JavaTokenTest.java | 161 + .../github/javaparser/JavadocParserTest.java | 174 + .../LineSeparatorProcessorTest.java | 124 + .../javaparser/ParseErrorRecoveryTest.java | 86 + .../javaparser/ParserConfigurationTest.java | 53 + .../javaparser/PositionMappingTest.java | 165 + .../com/github/javaparser/PositionTest.java | 57 + .../com/github/javaparser/ProblemTest.java | 52 + .../com/github/javaparser/ProvidersTest.java | 63 + .../java/com/github/javaparser/RangeTest.java | 293 + .../com/github/javaparser/TokenRangeTest.java | 72 + .../com/github/javaparser/TokenTypesTest.java | 58 + .../UnicodeEscapeProcessingProviderTest.java | 150 + .../ast/AncestorDescendantTests.java | 129 + .../javaparser/ast/CompilationUnitTest.java | 109 + .../github/javaparser/ast/DataKeyTest.java | 86 + .../github/javaparser/ast/FindNodeTest.java | 107 + .../javaparser/ast/ListObservationTest.java | 250 + .../github/javaparser/ast/NodeListTest.java | 432 + .../javaparser/ast/NodePositionTest.java | 95 + .../com/github/javaparser/ast/NodeTest.java | 155 + .../javaparser/ast/ObservationTest.java | 232 + .../javaparser/ast/ParseResultTest.java | 65 + .../javaparser/ast/ReplaceNodeTest.java | 53 + .../github/javaparser/ast/WalkFindTest.java | 135 + .../ast/body/AnnotationDeclarationTest.java | 42 + .../body/AnnotationMemberDeclarationTest.java | 65 + .../body/ClassOrInterfaceDeclarationTest.java | 146 + .../ast/body/ConstructorDeclarationTest.java | 39 + .../ast/body/FieldDeclarationTest.java | 131 + .../ast/body/MethodDeclarationTest.java | 162 + .../ast/body/RecordDeclarationTest.java | 765 ++ .../ast/body/TypeDeclarationTest.java | 84 + .../javaparser/ast/comments/CommentTest.java | 204 + .../ast/expr/ArrayCreationExprTest.java | 57 + .../javaparser/ast/expr/AssignExprTest.java | 33 + .../javaparser/ast/expr/BinaryExprTest.java | 139 + .../ast/expr/CharLiteralExprTest.java | 72 + .../ast/expr/DoubleLiteralExprTest.java | 64 + .../ast/expr/InstanceOfExprTest.java | 181 + .../javaparser/ast/expr/LambdaExprTest.java | 97 + .../ast/expr/LiteralStringValueExprTest.java | 185 + .../ast/expr/MethodCallExprTest.java | 43 + .../ast/expr/MethodReferenceExprTest.java | 135 + .../github/javaparser/ast/expr/NameTest.java | 101 + .../ast/expr/ObjectCreationExprTest.java | 35 + .../javaparser/ast/expr/SimpleNameTest.java | 52 + .../ast/expr/StringLiteralExprTest.java | 35 + .../javaparser/ast/expr/SuperExprTest.java | 54 + .../javaparser/ast/expr/SwitchExprTest.java | 213 + .../ast/expr/TextBlockLiteralExprTest.java | 204 + .../javaparser/ast/expr/ThisExprTest.java | 86 + .../ast/imports/ImportDeclarationTest.java | 57 + .../ast/nodeTypes/NodeWithArgumentsTest.java | 56 + .../ast/nodeTypes/NodeWithBodyTest.java | 59 + .../ast/nodeTypes/NodeWithJavadocTest.java | 70 + .../ast/nodeTypes/NodeWithModifiersTest.java | 93 + .../nodeTypes/NodeWithOptionalScopeTest.java | 51 + .../NodeWithTraversableScopeTest.java | 44 + .../ast/nodeTypes/NodeWithVariablesTest.java | 110 + .../observer/PropagatingAstObserverTest.java | 60 + .../javaparser/ast/stmt/BreakStmtTest.java | 127 + .../javaparser/ast/stmt/ForEachStmtTest.java | 47 + .../javaparser/ast/stmt/IfElseStmtTest.java | 56 + .../javaparser/ast/stmt/SwitchStmtTest.java | 60 + .../javaparser/ast/stmt/TryStmtTest.java | 120 + .../javaparser/ast/stmt/YieldStmtTest.java | 118 + .../javaparser/ast/type/ArrayTypeTest.java | 200 + .../ast/type/ClassOrInterfaceTypeTest.java | 139 + .../github/javaparser/ast/type/TypeTest.java | 89 + .../ast/validator/Java10ValidatorTest.java | 135 + .../ast/validator/Java11ValidatorTest.java | 56 + .../ast/validator/Java12ValidatorTest.java | 55 + .../ast/validator/Java13ValidatorTest.java | 43 + .../validator/Java14PreviewValidatorTest.java | 99 + .../ast/validator/Java14ValidatorTest.java | 79 + .../validator/Java15PreviewValidatorTest.java | 99 + .../ast/validator/Java15ValidatorTest.java | 77 + .../validator/Java16PreviewValidatorTest.java | 33 + .../ast/validator/Java16ValidatorTest.java | 110 + .../ast/validator/Java17ValidatorTest.java | 57 + .../ast/validator/Java18ValidatorTest.java | 34 + .../ast/validator/Java1_0ValidatorTest.java | 122 + .../ast/validator/Java1_1ValidatorTest.java | 310 + .../ast/validator/Java1_2ValidatorTest.java | 295 + .../ast/validator/Java1_3ValidatorTest.java | 43 + .../ast/validator/Java1_4ValidatorTest.java | 91 + .../ast/validator/Java5ValidatorTest.java | 194 + .../ast/validator/Java6ValidatorTest.java | 57 + .../ast/validator/Java7ValidatorTest.java | 128 + .../ast/validator/Java8ValidatorTest.java | 103 + .../ast/validator/Java9ValidatorTest.java | 100 + .../ast/visitor/CloneVisitorTest.java | 107 + .../GenericListVisitorAdapterTest.java | 2553 +++++ .../visitor/GenericVisitorAdapterTest.java | 2552 +++++ .../GenericVisitorWithDefaultsTest.java | 707 ++ .../ast/visitor/HashCodeVisitorTest.java | 968 ++ .../ast/visitor/ModifierVisitorTest.java | 144 + .../visitor/NoCommentEqualsVisitorTest.java | 53 + .../visitor/NoCommentHashCodeVisitorTest.java | 1067 ++ .../ast/visitor/NodeFinderVisitorTest.java | 100 + .../ObjectIdentityEqualsVisitorTest.java | 928 ++ .../ObjectIdentityHashCodeVisitorTest.java | 625 ++ .../ast/visitor/TreeVisitorTest.java | 160 + .../ast/visitor/VoidVisitorTest.java | 81 + .../visitor/VoidVisitorWithDefaultsTest.java | 705 ++ ...assOrInterfaceDeclarationBuildersTest.java | 70 + .../builders/CompilationUnitBuildersTest.java | 292 + .../builders/EnumDeclarationBuildersTest.java | 54 + .../FieldDeclarationBuildersTest.java | 123 + .../NodeWithAnnotationsBuildersTest.java | 88 + .../builders/NodeWithMembersBuildersTest.java | 280 + .../NodeWithParametersBuildersTest.java | 66 + .../NodeWithThrownExceptionsBuildersTest.java | 46 + .../javaparser/issues/Issue2627Test.java | 165 + .../javaparser/issues/Issue3113Test.java | 61 + .../javaparser/issues/Issue3255Test.java | 85 + .../javadoc/JavadocExtractorTest.java | 66 + .../javaparser/javadoc/JavadocTest.java | 172 + .../description/JavadocInlineTagTest.java | 36 + .../javaparser/manual/BulkParseTest.java | 164 + .../metamodel/BaseNodeMetaModelTest.java | 46 + .../metamodel/PropertyMetaModelTest.java | 66 + .../modules/ModuleDeclarationTest.java | 259 + .../ConcreteSyntaxModelAcceptanceTest.java | 66 + .../printer/ConcreteSyntaxModelTest.java | 97 + .../printer/DefaultPrettyPrinterTest.java | 665 ++ .../javaparser/printer/DotPrinterTest.java | 105 + .../javaparser/printer/JsonPrinterTest.java | 20 + .../printer/PrettyPrintVisitorTest.java | 539 + .../javaparser/printer/PrettyPrinterTest.java | 577 + .../printer/PrinterConfigurationTest.java | 96 + .../javaparser/printer/TestVisitor.java | 37 + .../javaparser/printer/XmlPrinterTest.java | 314 + .../javaparser/printer/YamlPrinterTest.java | 83 + .../DefaultImportOrderingStrategyTest.java | 79 + .../EclipseImportOrderingStrategyTest.java | 101 + .../IntelliJImportOrderingStrategyTest.java | 83 + .../AbstractLexicalPreservingTest.java | 102 + .../AnnotationSpaceTest.java | 46 + .../DifferenceElementCalculatorTest.java | 452 + .../lexicalpreservation/Issue1467Test.java | 69 + .../lexicalpreservation/Issue1634Test.java | 48 + .../lexicalpreservation/Issue1766Test.java | 84 + .../lexicalpreservation/Issue1793Test.java | 53 + .../lexicalpreservation/Issue2137Test.java | 58 + .../lexicalpreservation/Issue2290Test.java | 54 + .../lexicalpreservation/Issue2374Test.java | 65 + .../lexicalpreservation/Issue2393Test.java | 40 + .../lexicalpreservation/Issue2517Test.java | 62 + .../lexicalpreservation/Issue2592Test.java | 71 + .../lexicalpreservation/Issue2610Test.java | 54 + .../lexicalpreservation/Issue2620Test.java | 120 + .../lexicalpreservation/Issue2806Test.java | 54 + .../lexicalpreservation/Issue3296Test.java | 59 + .../lexicalpreservation/Issue3358Test.java | 74 + .../lexicalpreservation/Issue3387Test.java | 66 + .../lexicalpreservation/Issue3440Test.java | 40 + .../lexicalpreservation/Issue3441Test.java | 56 + .../lexicalpreservation/Issue3721Test.java | 53 + .../lexicalpreservation/Issue3746Test.java | 63 + .../lexicalpreservation/Issue3750Test.java | 55 + .../lexicalpreservation/Issue3761Test.java | 56 + .../lexicalpreservation/Issue3773Test.java | 148 + .../lexicalpreservation/Issue3796Test.java | 54 + .../lexicalpreservation/Issue3818Test.java | 57 + .../lexicalpreservation/Issue3924Test.java | 76 + .../lexicalpreservation/Issue3936Test.java | 72 + .../lexicalpreservation/Issue3937Test.java | 70 + .../lexicalpreservation/Issue3949Test.java | 68 + .../lexicalpreservation/Issue4104Test.java | 81 + .../lexicalpreservation/Issue4163Test.java | 75 + .../lexicalpreservation/Issue4245Test.java | 57 + .../LexicalDifferenceCalculatorTest.java | 327 + .../LexicalPreservingPrinterTest.java | 1858 ++++ .../PeekingIteratorTest.java | 146 + .../PrettyPrinterIssue2340Test.java | 77 + .../PrettyPrinterIssue2351Test.java | 46 + .../TransformationsTest.java | 343 + .../changes/NoChangeTest.java | 61 + ...ArrayCreationLevelTransformationsTest.java | 91 + .../CompilationUnitTransformationsTest.java | 64 + ...otationDeclarationTransformationsTest.java | 128 + ...nMemberDeclarationTransformationsTest.java | 174 + ...terfaceDeclarationTransformationsTest.java | 210 + ...tructorDeclarationTransformationsTest.java | 123 + ...onstantDeclarationTransformationsTest.java | 51 + .../EnumDeclarationTransformationsTest.java | 97 + .../FieldDeclarationTransformationsTest.java | 111 + ...ializerDeclarationTransformationsTest.java | 59 + .../MethodDeclarationTransformationsTest.java | 526 + .../ast/body/OperatorTransformationsTest.java | 55 + .../body/StatementTransformationsTest.java | 59 + .../javaparser/quality/PreconditionsTest.java | 52 + .../javaparser/remove/NodeRemovalTest.java | 124 + .../utils/CodeGenerationUtilsTest.java | 57 + .../javaparser/utils/ExtractingVisitors.java | 49 + .../javaparser/utils/LineSeparatorTest.java | 117 + .../com/github/javaparser/utils/LogTest.java | 89 + .../com/github/javaparser/utils/PairTest.java | 42 + .../utils/ParserCollectionStrategyTest.java | 198 + .../javaparser/utils/PositionUtilsTest.java | 282 + .../javaparser/utils/SourceRootTest.java | 112 + .../javaparser/utils/SourceZipTest.java | 79 + .../github/javaparser/utils/TestParser.java | 94 + .../github/javaparser/utils/TestUtils.java | 395 + .../github/javaparser/utils/UtilsTest.java | 230 + .../javaparser/utils/VisitorListTest.java | 185 + .../javaparser/utils/VisitorMapTest.java | 99 + .../javaparser/utils/VisitorSetTest.java | 136 + .../version/Java10PostProcessorTest.java | 58 + .../github/javaparser/EscapeSequences.java | 32 + .../com/github/javaparser/Sample.java | 17 + .../github/javaparser/TestFileIso88591.java | 7 + ...vaparser_core_generators_src_main_java.txt | 1 + ...core_metamodel_generator_src_main_java.txt | 1 + ..._results_javaparser_core_src_main_java.txt | 1 + ..._javaparser_core_testing_src_test_java.txt | 1 + ...rser_metamodel_generator_src_main_java.txt | 1 + ...arser_symbol_solver_core_src_main_java.txt | 1 + ...rser_symbol_solver_logic_src_main_java.txt | 1 + ...rser_symbol_solver_model_src_main_java.txt | 1 + ...er_symbol_solver_testing_src_test_java.txt | 1 + ...sults_javaparser_testing_src_test_java.txt | 1 + .../openjdk_src_repo_test_results.txt | 655 ++ .../openjdk_src_zip_test_results.txt | 4 + .../issue_samples/Issue290.java.txt | 34 + .../issue_samples/Issue412.java.expected.txt | 35 + .../issue_samples/Issue412.java.txt | 33 + .../issue_samples/Issue624.java.txt | 14 + .../issue_samples/issue1003.java.txt | 1470 +++ .../issue_2627/DefaultStrategy.java | 297 + .../issue_samples/issue_2627/Ops.java | 7632 ++++++++++++++ .../issue_samples/issue_2627/Ops_cr.java | 1 + .../issue_samples/issue_2627/Ops_crlf.java | 7632 ++++++++++++++ .../issue_samples/issue_2627/Ops_lf.java | 7632 ++++++++++++++ .../issue_samples/issue_2627/Ops_minimal.java | 265 + .../ASimpleClassWithMoreFormatting.java.txt | 26 + ...mpleClassWithMoreFormatting_step1.java.txt | 26 + ...mpleClassWithMoreFormatting_step2.java.txt | 29 + ...mpleClassWithMoreFormatting_step3.java.txt | 29 + ...mpleClassWithMoreFormatting_step4.java.txt | 30 + ...ionDeclaration_Example10_expected.java.txt | 11 + ...tionDeclaration_Example1_expected.java.txt | 11 + ...tionDeclaration_Example1_original.java.txt | 11 + ...tionDeclaration_Example2_expected.java.txt | 11 + ...tionDeclaration_Example3_expected.java.txt | 11 + ...tionDeclaration_Example3_original.java.txt | 11 + ...tionDeclaration_Example4_expected.java.txt | 11 + ...tionDeclaration_Example5_expected.java.txt | 12 + ...tionDeclaration_Example6_expected.java.txt | 10 + ...tionDeclaration_Example7_expected.java.txt | 11 + ...tionDeclaration_Example8_expected.java.txt | 12 + ...tionDeclaration_Example9_expected.java.txt | 10 + ...tionDeclaration_Example9_original.java.txt | 11 + .../Example10_expected.java.txt | 3 + .../Example10_original.java.txt | 4 + .../Example1_expected.java.txt | 4 + .../Example1_original.java.txt | 4 + .../Example2_expected.java.txt | 4 + .../Example2_original.java.txt | 4 + .../Example3_expected.java.txt | 4 + .../Example3_original.java.txt | 4 + .../Example4_original.java.txt | 398 + .../Example5_expected.java.txt | 4 + .../Example5_original.java.txt | 4 + .../Example6_expected.java.txt | 4 + .../Example6_original.java.txt | 4 + .../Example7_expected.java.txt | 4 + .../Example7_original.java.txt | 4 + .../Example8_expected.java.txt | 4 + .../Example8_original.java.txt | 4 + .../Example9_expected.java.txt | 4 + .../Example9_original.java.txt | 4 + .../Example_param1_expected.java.txt | 4 + .../Example_param1_original.java.txt | 4 + .../Example_param2_expected.java.txt | 4 + .../Example_param3_expected.java.txt | 4 + .../Example_param3_original.java.txt | 4 + .../Example_param4_expected.java.txt | 4 + .../Example_param5_expected.java.txt | 6 + .../Example_param5b_expected.java.txt | 4 + .../FixIndentOfMovedNode.java.txt | 202 + .../FixIndentOfMovedNodeExpected.java.txt | 204 + .../IndentOfInsertedCodeBlocks.java.txt | 5 + ...ndentOfInsertedCodeBlocksExpected.java.txt | 15 + .../MethodWithOneStatement.java.txt | 5 + .../printer/JavaConceptsBase_prettyprinted | 83 + .../printer/JavaConceptsEnums_prettyprinted | 70 + .../JavaConceptsInnerClasses_prettyprinted | 135 + .../printer/JavaConceptsMethods_prettyprinted | 164 + .../printer/JavaConceptsUgly_prettyprinted | 60 + .../printer/PrettyPrintVisitor_prettyprinted | 1353 +++ ...yamlParsingJavadocWithQuoteAndNewline.yaml | 13 + ...thColonFollowedByLineSeparatorInValue.yaml | 4 + .../yamlWithColonFollowedBySpaceInValue.yaml | 4 + .../javaparser/printer/yamlWithType.yaml | 10 + .../javaparser/printer/yamlWithoutType.yaml | 8 + .../com/github/javaparser/range/A.java | 7 + .../com/github/javaparser/range/B.java | 7 + .../com/github/javaparser/source_zip/test.txt | 1 + .../com/github/javaparser/source_zip/test.zip | Bin 0 -> 1278 bytes .../com/github/javaparser/storage/A.java | 1 + .../com/github/javaparser/storage/B.java | 0 .../javaparser/storage/PrimaryType.java | 5 + .../javaparser/storage/PrimaryType2.java | 1 + .../com/github/javaparser/storage/Z.java | 1 + .../com/github/javaparser/utils/.abc/bla.java | 0 .../com/github/javaparser/utils/Bla.java | 2 + .../github/javaparser/utils/module-info.java | 2 + .../issue2615/with_module_info/demo/Main.java | 46 + .../with_module_info/demo/module-info.java | 2 + .../with_module_info_in_root/demo/Main.java | 46 + .../with_module_info_in_root/module-info.java | 2 + .../without_module_info/demo/Main.java | 46 + .../javaparser/utils/source.root/Y.java | 3 + .../javaparser/wiki_samples/TestFile.java | 15 + .../javaparser/printer/JavaConceptsBase.java | 83 + .../javaparser/printer/JavaConceptsEnums.java | 70 + .../printer/JavaConceptsInnerClasses.java | 135 + .../printer/JavaConceptsMethods.java | 164 + .../javaparser/printer/JavaConceptsUgly.java | 60 + .../printer/PrettyPrintVisitor.java | 1413 +++ javaparser-core/bnd.bnd | 46 + javaparser-core/bnd.bnd.template | 16 + javaparser-core/pom.xml | 118 + .../github/javaparser/JavaParserBuild.java | 39 + .../github/javaparser/CommentsInserter.java | 196 + .../com/github/javaparser/HasParentNode.java | 113 + .../com/github/javaparser/JavaParser.java | 552 + .../github/javaparser/JavaParserAdapter.java | 201 + .../java/com/github/javaparser/JavaToken.java | 833 ++ .../com/github/javaparser/JavadocParser.java | 139 + .../LineEndingProcessingProvider.java | 146 + .../javaparser/ParseProblemException.java | 59 + .../com/github/javaparser/ParseResult.java | 109 + .../com/github/javaparser/ParseStart.java | 97 + .../javaparser/ParserConfiguration.java | 473 + .../java/com/github/javaparser/Position.java | 209 + .../java/com/github/javaparser/Problem.java | 107 + .../java/com/github/javaparser/Processor.java | 39 + .../java/com/github/javaparser/Providers.java | 109 + .../java/com/github/javaparser/Range.java | 256 + .../github/javaparser/StaticJavaParser.java | 554 + .../com/github/javaparser/TokenRange.java | 106 + .../com/github/javaparser/TokenTypes.java | 263 + .../UnicodeEscapeProcessingProvider.java | 592 ++ .../javaparser/ast/AccessSpecifier.java | 43 + .../javaparser/ast/AllFieldsConstructor.java | 34 + .../javaparser/ast/ArrayCreationLevel.java | 193 + .../javaparser/ast/CompilationUnit.java | 854 ++ .../com/github/javaparser/ast/DataKey.java | 56 + .../com/github/javaparser/ast/Generated.java | 45 + .../javaparser/ast/ImportDeclaration.java | 171 + .../com/github/javaparser/ast/Modifier.java | 200 + .../java/com/github/javaparser/ast/Node.java | 1189 +++ .../com/github/javaparser/ast/NodeList.java | 650 ++ .../javaparser/ast/PackageDeclaration.java | 188 + .../ast/body/AnnotationDeclaration.java | 129 + .../ast/body/AnnotationMemberDeclaration.java | 289 + .../javaparser/ast/body/BodyDeclaration.java | 381 + .../ast/body/CallableDeclaration.java | 457 + .../ast/body/ClassOrInterfaceDeclaration.java | 326 + .../body/CompactConstructorDeclaration.java | 382 + .../ast/body/ConstructorDeclaration.java | 251 + .../ast/body/EnumConstantDeclaration.java | 241 + .../javaparser/ast/body/EnumDeclaration.java | 232 + .../javaparser/ast/body/FieldDeclaration.java | 360 + .../ast/body/InitializerDeclaration.java | 167 + .../ast/body/MethodDeclaration.java | 396 + .../github/javaparser/ast/body/Parameter.java | 346 + .../ast/body/ReceiverParameter.java | 220 + .../ast/body/RecordDeclaration.java | 393 + .../javaparser/ast/body/TypeDeclaration.java | 281 + .../ast/body/VariableDeclarator.java | 285 + .../javaparser/ast/comments/BlockComment.java | 121 + .../javaparser/ast/comments/Comment.java | 242 + .../ast/comments/CommentsCollection.java | 98 + .../ast/comments/JavadocComment.java | 124 + .../javaparser/ast/comments/LineComment.java | 120 + .../javaparser/ast/expr/AnnotationExpr.java | 150 + .../javaparser/ast/expr/ArrayAccessExpr.java | 173 + .../ast/expr/ArrayCreationExpr.java | 272 + .../ast/expr/ArrayInitializerExpr.java | 167 + .../javaparser/ast/expr/AssignExpr.java | 262 + .../javaparser/ast/expr/BinaryExpr.java | 257 + .../ast/expr/BooleanLiteralExpr.java | 136 + .../github/javaparser/ast/expr/CastExpr.java | 176 + .../javaparser/ast/expr/CharLiteralExpr.java | 148 + .../github/javaparser/ast/expr/ClassExpr.java | 150 + .../javaparser/ast/expr/ConditionalExpr.java | 209 + .../ast/expr/DoubleLiteralExpr.java | 130 + .../javaparser/ast/expr/EnclosedExpr.java | 162 + .../javaparser/ast/expr/Expression.java | 884 ++ .../javaparser/ast/expr/FieldAccessExpr.java | 278 + .../javaparser/ast/expr/InstanceOfExpr.java | 294 + .../ast/expr/IntegerLiteralExpr.java | 183 + .../javaparser/ast/expr/LambdaExpr.java | 286 + .../javaparser/ast/expr/LiteralExpr.java | 89 + .../ast/expr/LiteralStringValueExpr.java | 109 + .../javaparser/ast/expr/LongLiteralExpr.java | 190 + .../ast/expr/MarkerAnnotationExpr.java | 114 + .../javaparser/ast/expr/MemberValuePair.java | 151 + .../javaparser/ast/expr/MethodCallExpr.java | 385 + .../ast/expr/MethodReferenceExpr.java | 251 + .../com/github/javaparser/ast/expr/Name.java | 201 + .../github/javaparser/ast/expr/NameExpr.java | 174 + .../ast/expr/NormalAnnotationExpr.java | 183 + .../javaparser/ast/expr/NullLiteralExpr.java | 104 + .../ast/expr/ObjectCreationExpr.java | 387 + .../javaparser/ast/expr/PatternExpr.java | 247 + .../javaparser/ast/expr/SimpleName.java | 111 + .../ast/expr/SingleMemberAnnotationExpr.java | 146 + .../ast/expr/StringLiteralExpr.java | 150 + .../github/javaparser/ast/expr/SuperExpr.java | 178 + .../javaparser/ast/expr/SwitchExpr.java | 211 + .../ast/expr/TextBlockLiteralExpr.java | 201 + .../github/javaparser/ast/expr/ThisExpr.java | 185 + .../github/javaparser/ast/expr/TypeExpr.java | 151 + .../github/javaparser/ast/expr/UnaryExpr.java | 216 + .../ast/expr/VariableDeclarationExpr.java | 275 + .../ast/modules/ModuleDeclaration.java | 234 + .../ast/modules/ModuleDirective.java | 256 + .../ast/modules/ModuleExportsDirective.java | 219 + .../ast/modules/ModuleOpensDirective.java | 213 + .../ast/modules/ModuleProvidesDirective.java | 213 + .../ast/modules/ModuleRequiresDirective.java | 232 + .../ast/modules/ModuleUsesDirective.java | 183 + .../ast/nodeTypes/NodeWithAnnotations.java | 220 + .../ast/nodeTypes/NodeWithArguments.java | 84 + .../ast/nodeTypes/NodeWithBlockStmt.java | 40 + .../ast/nodeTypes/NodeWithBody.java | 47 + .../ast/nodeTypes/NodeWithCondition.java | 31 + .../ast/nodeTypes/NodeWithDeclaration.java | 64 + .../ast/nodeTypes/NodeWithExpression.java | 40 + .../ast/nodeTypes/NodeWithExtends.java | 100 + .../ast/nodeTypes/NodeWithIdentifier.java | 41 + .../ast/nodeTypes/NodeWithImplements.java | 92 + .../ast/nodeTypes/NodeWithJavadoc.java | 88 + .../ast/nodeTypes/NodeWithMembers.java | 459 + .../ast/nodeTypes/NodeWithModifiers.java | 116 + .../ast/nodeTypes/NodeWithName.java | 51 + .../nodeTypes/NodeWithOptionalBlockStmt.java | 44 + .../ast/nodeTypes/NodeWithOptionalLabel.java | 49 + .../ast/nodeTypes/NodeWithOptionalScope.java | 42 + .../ast/nodeTypes/NodeWithParameters.java | 169 + .../ast/nodeTypes/NodeWithRange.java | 86 + .../ast/nodeTypes/NodeWithScope.java | 40 + .../ast/nodeTypes/NodeWithSimpleName.java | 53 + .../ast/nodeTypes/NodeWithStatements.java | 117 + .../nodeTypes/NodeWithThrownExceptions.java | 90 + .../ast/nodeTypes/NodeWithTokenRange.java | 35 + .../nodeTypes/NodeWithTraversableScope.java | 39 + .../ast/nodeTypes/NodeWithType.java | 78 + .../ast/nodeTypes/NodeWithTypeArguments.java | 85 + .../ast/nodeTypes/NodeWithTypeParameters.java | 69 + .../ast/nodeTypes/NodeWithVariables.java | 173 + .../javaparser/ast/nodeTypes/SwitchNode.java | 62 + .../modifiers/NodeWithAbstractModifier.java | 41 + .../modifiers/NodeWithAccessModifiers.java | 29 + .../modifiers/NodeWithFinalModifier.java | 44 + .../modifiers/NodeWithPrivateModifier.java | 41 + .../modifiers/NodeWithProtectedModifier.java | 41 + .../modifiers/NodeWithPublicModifier.java | 41 + .../modifiers/NodeWithStaticModifier.java | 45 + .../modifiers/NodeWithStrictfpModifier.java | 41 + .../javaparser/ast/observer/AstObserver.java | 69 + .../ast/observer/AstObserverAdapter.java | 47 + .../javaparser/ast/observer/Observable.java | 43 + .../ast/observer/ObservableProperty.java | 293 + .../ast/observer/PropagatingAstObserver.java | 117 + .../javaparser/ast/stmt/AssertStmt.java | 207 + .../github/javaparser/ast/stmt/BlockStmt.java | 165 + .../github/javaparser/ast/stmt/BreakStmt.java | 193 + .../javaparser/ast/stmt/CatchClause.java | 158 + .../javaparser/ast/stmt/ContinueStmt.java | 181 + .../github/javaparser/ast/stmt/DoStmt.java | 177 + .../github/javaparser/ast/stmt/EmptyStmt.java | 102 + .../ExplicitConstructorInvocationStmt.java | 304 + .../javaparser/ast/stmt/ExpressionStmt.java | 149 + .../javaparser/ast/stmt/ForEachStmt.java | 239 + .../github/javaparser/ast/stmt/ForStmt.java | 295 + .../github/javaparser/ast/stmt/IfStmt.java | 265 + .../javaparser/ast/stmt/LabeledStmt.java | 177 + .../ast/stmt/LocalClassDeclarationStmt.java | 153 + .../ast/stmt/LocalRecordDeclarationStmt.java | 148 + .../javaparser/ast/stmt/ReturnStmt.java | 182 + .../github/javaparser/ast/stmt/Statement.java | 486 + .../javaparser/ast/stmt/SwitchEntry.java | 244 + .../javaparser/ast/stmt/SwitchStmt.java | 229 + .../javaparser/ast/stmt/SynchronizedStmt.java | 177 + .../github/javaparser/ast/stmt/ThrowStmt.java | 150 + .../github/javaparser/ast/stmt/TryStmt.java | 319 + .../javaparser/ast/stmt/UnparsableStmt.java | 109 + .../github/javaparser/ast/stmt/WhileStmt.java | 177 + .../github/javaparser/ast/stmt/YieldStmt.java | 159 + .../github/javaparser/ast/type/ArrayType.java | 337 + .../ast/type/ClassOrInterfaceType.java | 359 + .../ast/type/ConvertibleToUsage.java | 33 + .../javaparser/ast/type/IntersectionType.java | 195 + .../javaparser/ast/type/PrimitiveType.java | 270 + .../javaparser/ast/type/ReferenceType.java | 97 + .../com/github/javaparser/ast/type/Type.java | 372 + .../javaparser/ast/type/TypeParameter.java | 252 + .../github/javaparser/ast/type/UnionType.java | 209 + .../javaparser/ast/type/UnknownType.java | 151 + .../github/javaparser/ast/type/VarType.java | 189 + .../github/javaparser/ast/type/VoidType.java | 136 + .../javaparser/ast/type/WildcardType.java | 282 + .../ast/validator/ProblemReporter.java | 64 + .../RecordAsTypeIdentifierNotAllowed.java | 63 + .../validator/ReservedKeywordValidator.java | 58 + .../ast/validator/SimpleValidator.java | 41 + .../validator/SingleNodeTypeValidator.java | 46 + .../ast/validator/TreeVisitorValidator.java | 43 + .../ast/validator/TypedValidator.java | 51 + .../javaparser/ast/validator/Validator.java | 36 + .../javaparser/ast/validator/Validators.java | 66 + .../ast/validator/VisitorValidator.java | 37 + .../Java10PreviewValidator.java | 39 + .../Java10Validator.java | 48 + .../Java11PreviewValidator.java | 39 + .../Java11Validator.java | 47 + .../Java12PreviewValidator.java | 50 + .../Java12Validator.java | 35 + .../Java13PreviewValidator.java | 52 + .../Java13Validator.java | 35 + .../Java14PreviewValidator.java | 47 + .../Java14Validator.java | 68 + .../Java15PreviewValidator.java | 46 + .../Java15Validator.java | 36 + .../Java16PreviewValidator.java | 39 + .../Java16Validator.java | 42 + .../Java17PreviewValidator.java | 39 + .../Java17Validator.java | 45 + .../Java18Validator.java | 32 + .../Java1_0Validator.java | 142 + .../Java1_1Validator.java | 44 + .../Java1_2Validator.java | 41 + .../Java1_3Validator.java | 31 + .../Java1_4Validator.java | 32 + .../Java5Validator.java | 89 + .../Java6Validator.java | 31 + .../Java7Validator.java | 59 + .../Java8Validator.java | 56 + .../Java9Validator.java | 59 + .../UpgradeJavaMessage.java | 65 + .../chunks/CommonValidators.java | 73 + .../chunks/ModifierValidator.java | 234 + .../NoBinaryIntegerLiteralsValidator.java | 48 + ...UnderscoresInIntegerLiteralsValidator.java | 48 + .../chunks/RecordDeclarationValidator.java | 86 + .../chunks/UnderscoreKeywordValidator.java | 48 + .../chunks/VarValidator.java | 113 + .../postprocessors/Java10PostProcessor.java | 72 + .../postprocessors/Java11PostProcessor.java | 27 + .../postprocessors/Java12PostProcessor.java | 27 + .../postprocessors/Java13PostProcessor.java | 27 + .../postprocessors/Java14PostProcessor.java | 27 + .../postprocessors/Java15PostProcessor.java | 27 + .../postprocessors/Java16PostProcessor.java | 27 + .../postprocessors/Java17PostProcessor.java | 27 + .../postprocessors/Java18PostProcessor.java | 26 + .../postprocessors/PostProcessors.java | 68 + .../javaparser/ast/visitor/CloneVisitor.java | 1290 +++ .../javaparser/ast/visitor/EqualsVisitor.java | 1414 +++ .../visitor/GenericListVisitorAdapter.java | 2309 ++++ .../ast/visitor/GenericVisitor.java | 244 + .../ast/visitor/GenericVisitorAdapter.java | 2211 ++++ .../visitor/GenericVisitorWithDefaults.java | 552 + .../ast/visitor/HashCodeVisitor.java | 465 + .../ast/visitor/ModifierVisitor.java | 1338 +++ .../ast/visitor/NoCommentEqualsVisitor.java | 1162 ++ .../ast/visitor/NoCommentHashCodeVisitor.java | 457 + .../ast/visitor/NodeFinderVisitor.java | 2619 +++++ .../visitor/ObjectIdentityEqualsVisitor.java | 545 + .../ObjectIdentityHashCodeVisitor.java | 457 + .../javaparser/ast/visitor/TreeVisitor.java | 97 + .../javaparser/ast/visitor/Visitable.java | 44 + .../javaparser/ast/visitor/VoidVisitor.java | 239 + .../ast/visitor/VoidVisitorAdapter.java | 754 ++ .../ast/visitor/VoidVisitorWithDefaults.java | 548 + .../github/javaparser/javadoc/Javadoc.java | 162 + .../javaparser/javadoc/JavadocBlockTag.java | 163 + .../description/JavadocDescription.java | 113 + .../JavadocDescriptionElement.java | 31 + .../javadoc/description/JavadocInlineTag.java | 134 + .../javadoc/description/JavadocSnippet.java | 64 + .../AnnotationDeclarationMetaModel.java | 44 + .../metamodel/AnnotationExprMetaModel.java | 52 + .../AnnotationMemberDeclarationMetaModel.java | 52 + .../metamodel/ArrayAccessExprMetaModel.java | 48 + .../metamodel/ArrayCreationExprMetaModel.java | 50 + .../ArrayCreationLevelMetaModel.java | 48 + .../ArrayInitializerExprMetaModel.java | 46 + .../metamodel/ArrayTypeMetaModel.java | 48 + .../metamodel/AssertStmtMetaModel.java | 48 + .../metamodel/AssignExprMetaModel.java | 50 + .../metamodel/BaseNodeMetaModel.java | 245 + .../metamodel/BinaryExprMetaModel.java | 50 + .../metamodel/BlockCommentMetaModel.java | 44 + .../metamodel/BlockStmtMetaModel.java | 46 + .../metamodel/BodyDeclarationMetaModel.java | 52 + .../BooleanLiteralExprMetaModel.java | 46 + .../metamodel/BreakStmtMetaModel.java | 46 + .../CallableDeclarationMetaModel.java | 62 + .../metamodel/CastExprMetaModel.java | 48 + .../metamodel/CatchClauseMetaModel.java | 48 + .../metamodel/CharLiteralExprMetaModel.java | 44 + .../metamodel/ClassExprMetaModel.java | 46 + .../ClassOrInterfaceDeclarationMetaModel.java | 54 + .../ClassOrInterfaceTypeMetaModel.java | 52 + .../metamodel/CommentMetaModel.java | 52 + ...ompactConstructorDeclarationMetaModel.java | 54 + .../metamodel/CompilationUnitMetaModel.java | 52 + .../metamodel/ConditionalExprMetaModel.java | 50 + .../ConstructorDeclarationMetaModel.java | 46 + .../metamodel/ContinueStmtMetaModel.java | 46 + .../javaparser/metamodel/DerivedProperty.java | 38 + .../javaparser/metamodel/DoStmtMetaModel.java | 48 + .../metamodel/DoubleLiteralExprMetaModel.java | 44 + .../metamodel/EmptyStmtMetaModel.java | 44 + .../metamodel/EnclosedExprMetaModel.java | 46 + .../EnumConstantDeclarationMetaModel.java | 50 + .../metamodel/EnumDeclarationMetaModel.java | 48 + ...citConstructorInvocationStmtMetaModel.java | 54 + .../metamodel/ExpressionMetaModel.java | 50 + .../metamodel/ExpressionStmtMetaModel.java | 46 + .../metamodel/FieldAccessExprMetaModel.java | 52 + .../metamodel/FieldDeclarationMetaModel.java | 50 + .../metamodel/ForEachStmtMetaModel.java | 50 + .../metamodel/ForStmtMetaModel.java | 52 + .../javaparser/metamodel/IfStmtMetaModel.java | 58 + .../metamodel/ImportDeclarationMetaModel.java | 50 + .../InitializerDeclarationMetaModel.java | 48 + .../metamodel/InstanceOfExprMetaModel.java | 50 + .../IntegerLiteralExprMetaModel.java | 44 + .../metamodel/InternalProperty.java | 37 + .../metamodel/IntersectionTypeMetaModel.java | 46 + .../metamodel/JavaParserMetaModel.java | 1200 +++ .../metamodel/JavadocCommentMetaModel.java | 44 + .../metamodel/LabeledStmtMetaModel.java | 48 + .../metamodel/LambdaExprMetaModel.java | 52 + .../metamodel/LineCommentMetaModel.java | 44 + .../metamodel/LiteralExprMetaModel.java | 50 + .../LiteralStringValueExprMetaModel.java | 52 + .../LocalClassDeclarationStmtMetaModel.java | 46 + .../LocalRecordDeclarationStmtMetaModel.java | 46 + .../metamodel/LongLiteralExprMetaModel.java | 44 + .../MarkerAnnotationExprMetaModel.java | 44 + .../metamodel/MemberValuePairMetaModel.java | 48 + .../metamodel/MethodCallExprMetaModel.java | 54 + .../metamodel/MethodDeclarationMetaModel.java | 48 + .../MethodReferenceExprMetaModel.java | 52 + .../metamodel/ModifierMetaModel.java | 46 + .../metamodel/ModuleDeclarationMetaModel.java | 52 + .../metamodel/ModuleDirectiveMetaModel.java | 50 + .../ModuleExportsDirectiveMetaModel.java | 48 + .../ModuleOpensDirectiveMetaModel.java | 48 + .../ModuleProvidesDirectiveMetaModel.java | 48 + .../ModuleRequiresDirectiveMetaModel.java | 48 + .../ModuleUsesDirectiveMetaModel.java | 46 + .../metamodel/NameExprMetaModel.java | 46 + .../javaparser/metamodel/NameMetaModel.java | 48 + .../javaparser/metamodel/NodeMetaModel.java | 51 + .../metamodel/NonEmptyProperty.java | 38 + .../NormalAnnotationExprMetaModel.java | 46 + .../metamodel/NullLiteralExprMetaModel.java | 44 + .../ObjectCreationExprMetaModel.java | 56 + .../metamodel/OptionalProperty.java | 36 + .../PackageDeclarationMetaModel.java | 48 + .../metamodel/ParameterMetaModel.java | 56 + .../metamodel/PatternExprMetaModel.java | 50 + .../metamodel/PrimitiveTypeMetaModel.java | 46 + .../metamodel/PropertyMetaModel.java | 265 + .../metamodel/ReceiverParameterMetaModel.java | 50 + .../metamodel/RecordDeclarationMetaModel.java | 52 + .../metamodel/ReferenceTypeMetaModel.java | 50 + .../metamodel/ReturnStmtMetaModel.java | 46 + .../metamodel/SimpleNameMetaModel.java | 46 + .../SingleMemberAnnotationExprMetaModel.java | 46 + .../metamodel/StatementMetaModel.java | 50 + .../metamodel/StringLiteralExprMetaModel.java | 44 + .../metamodel/SuperExprMetaModel.java | 46 + .../metamodel/SwitchEntryMetaModel.java | 50 + .../metamodel/SwitchExprMetaModel.java | 48 + .../metamodel/SwitchStmtMetaModel.java | 48 + .../metamodel/SynchronizedStmtMetaModel.java | 48 + .../TextBlockLiteralExprMetaModel.java | 44 + .../metamodel/ThisExprMetaModel.java | 46 + .../metamodel/ThrowStmtMetaModel.java | 46 + .../metamodel/TryStmtMetaModel.java | 52 + .../metamodel/TypeDeclarationMetaModel.java | 56 + .../metamodel/TypeExprMetaModel.java | 46 + .../javaparser/metamodel/TypeMetaModel.java | 52 + .../metamodel/TypeParameterMetaModel.java | 48 + .../metamodel/UnaryExprMetaModel.java | 52 + .../metamodel/UnionTypeMetaModel.java | 46 + .../metamodel/UnknownTypeMetaModel.java | 44 + .../metamodel/UnparsableStmtMetaModel.java | 44 + .../metamodel/VarTypeMetaModel.java | 44 + .../VariableDeclarationExprMetaModel.java | 52 + .../VariableDeclaratorMetaModel.java | 50 + .../metamodel/VoidTypeMetaModel.java | 44 + .../metamodel/WhileStmtMetaModel.java | 48 + .../metamodel/WildcardTypeMetaModel.java | 48 + .../metamodel/YieldStmtMetaModel.java | 46 + .../printer/ConcreteSyntaxModel.java | 229 + .../printer/DefaultPrettyPrinter.java | 98 + .../printer/DefaultPrettyPrinterVisitor.java | 1882 ++++ .../github/javaparser/printer/DotPrinter.java | 99 + .../printer/PrettyPrintVisitor.java | 1861 ++++ .../javaparser/printer/PrettyPrinter.java | 79 + .../github/javaparser/printer/Printer.java | 37 + .../javaparser/printer/SourcePrinter.java | 281 + .../github/javaparser/printer/Stringable.java | 29 + .../github/javaparser/printer/XmlPrinter.java | 270 + .../javaparser/printer/YamlPrinter.java | 98 + .../concretesyntaxmodel/CsmAttribute.java | 94 + .../printer/concretesyntaxmodel/CsmChar.java | 50 + .../concretesyntaxmodel/CsmComment.java | 40 + .../concretesyntaxmodel/CsmConditional.java | 134 + .../concretesyntaxmodel/CsmElement.java | 159 + .../concretesyntaxmodel/CsmIndent.java | 53 + .../printer/concretesyntaxmodel/CsmList.java | 129 + .../printer/concretesyntaxmodel/CsmMix.java | 75 + .../printer/concretesyntaxmodel/CsmNone.java | 31 + .../CsmOrphanCommentsEnding.java | 56 + .../concretesyntaxmodel/CsmSequence.java | 57 + .../CsmSingleReference.java | 52 + .../concretesyntaxmodel/CsmString.java | 50 + .../concretesyntaxmodel/CsmTextBlock.java | 53 + .../printer/concretesyntaxmodel/CsmToken.java | 125 + .../concretesyntaxmodel/CsmUnindent.java | 42 + .../concretesyntaxmodel/PrintingHelper.java | 40 + .../configuration/ConfigurationOption.java | 51 + .../DefaultConfigurationOption.java | 115 + .../DefaultPrinterConfiguration.java | 167 + .../configuration/ImportOrderingStrategy.java | 71 + .../printer/configuration/Indentation.java | 154 + .../PrettyPrinterConfiguration.java | 278 + .../configuration/PrinterConfiguration.java | 56 + .../DefaultImportOrderingStrategy.java | 60 + .../EclipseImportOrderingStrategy.java | 92 + .../IntelliJImportOrderingStrategy.java | 80 + .../printer/lexicalpreservation/Added.java | 113 + .../lexicalpreservation/ChildTextElement.java | 143 + .../lexicalpreservation/Difference.java | 1130 ++ .../DifferenceElement.java | 62 + .../DifferenceElementCalculator.java | 339 + .../printer/lexicalpreservation/Kept.java | 129 + .../LexicalDifferenceCalculator.java | 423 + .../LexicalPreservingPrinter.java | 730 ++ .../LexicalPreservingVisitor.java | 49 + .../LookaheadIterator.java | 50 + .../printer/lexicalpreservation/NodeText.java | 196 + .../lexicalpreservation/PeekingIterator.java | 223 + .../lexicalpreservation/PhantomNodeLogic.java | 79 + .../PrintableTextElement.java | 26 + .../printer/lexicalpreservation/Removed.java | 127 + .../lexicalpreservation/RemovedGroup.java | 257 + .../lexicalpreservation/Reshuffled.java | 125 + .../ReshuffledDiffElementExtractor.java | 238 + .../lexicalpreservation/TextElement.java | 90 + .../TextElementIteratorsFactory.java | 197 + .../TextElementMatcher.java | 37 + .../TextElementMatchers.java | 45 + .../lexicalpreservation/TokenTextElement.java | 153 + .../lexicalpreservation/changes/Change.java | 115 + .../changes/ListAdditionChange.java | 73 + .../changes/ListRemovalChange.java | 91 + .../changes/ListReplacementChange.java | 73 + .../lexicalpreservation/changes/NoChange.java | 40 + .../changes/PropertyChange.java | 63 + .../github/javaparser/quality/NotNull.java | 30 + .../github/javaparser/quality/Nullable.java | 30 + .../javaparser/quality/Preconditions.java | 78 + .../github/javaparser/resolution/Context.java | 421 + .../resolution/MethodAmbiguityException.java | 36 + .../javaparser/resolution/MethodUsage.java | 261 + .../javaparser/resolution/Navigator.java | 283 + .../javaparser/resolution/Resolvable.java | 26 + .../github/javaparser/resolution/Solver.java | 82 + .../resolution/SymbolDeclarator.java | 35 + .../javaparser/resolution/SymbolResolver.java | 50 + .../javaparser/resolution/TypeSolver.java | 85 + .../resolution/UnsolvedSymbolException.java | 74 + .../javaparser/resolution/cache/Cache.java | 103 + .../resolution/cache/CacheStats.java | 151 + .../declarations/AssociableToAST.java | 74 + .../declarations/HasAccessSpecifier.java | 37 + .../ResolvedAnnotationDeclaration.java | 43 + .../ResolvedAnnotationMemberDeclaration.java | 31 + .../ResolvedClassDeclaration.java | 86 + .../ResolvedConstructorDeclaration.java | 35 + .../declarations/ResolvedDeclaration.java | 134 + .../ResolvedEnumConstantDeclaration.java | 39 + .../declarations/ResolvedEnumDeclaration.java | 51 + .../ResolvedFieldDeclaration.java | 54 + .../ResolvedInterfaceDeclaration.java | 56 + .../ResolvedMethodDeclaration.java | 98 + .../ResolvedMethodLikeDeclaration.java | 170 + .../ResolvedParameterDeclaration.java | 62 + .../ResolvedPatternDeclaration.java | 51 + .../ResolvedReferenceTypeDeclaration.java | 373 + .../declarations/ResolvedTypeDeclaration.java | 213 + .../ResolvedTypeParameterDeclaration.java | 350 + .../ResolvedTypeParametrizable.java | 47 + .../ResolvedValueDeclaration.java | 36 + .../ConflictingGenericTypesException.java | 34 + .../logic/ConstructorResolutionLogic.java | 236 + .../logic/FunctionalInterfaceLogic.java | 121 + .../resolution/logic/InferenceContext.java | 247 + .../logic/InferenceVariableType.java | 157 + .../logic/MethodResolutionCapability.java | 33 + .../logic/MethodResolutionLogic.java | 945 ++ .../model/LambdaArgumentTypePlaceholder.java | 71 + .../resolution/model/SymbolReference.java | 132 + .../javaparser/resolution/model/Value.java | 65 + .../resolution/model/typesystem/LazyType.java | 140 + .../resolution/model/typesystem/NullType.java | 68 + .../model/typesystem/ReferenceTypeImpl.java | 267 + .../promotion/ConditionalExprHandler.java | 27 + .../resolution/types/ResolvedArrayType.java | 135 + .../types/ResolvedIntersectionType.java | 84 + .../types/ResolvedLambdaConstraintType.java | 63 + .../types/ResolvedPrimitiveType.java | 234 + .../types/ResolvedReferenceType.java | 589 ++ .../resolution/types/ResolvedType.java | 244 + .../types/ResolvedTypeTransformer.java | 30 + .../types/ResolvedTypeVariable.java | 151 + .../resolution/types/ResolvedUnionType.java | 97 + .../resolution/types/ResolvedVoidType.java | 65 + .../resolution/types/ResolvedWildcard.java | 210 + .../ResolvedTypeParameterValueProvider.java | 74 + .../ResolvedTypeParametersMap.java | 140 + .../ResolvedTypeParametrized.java | 31 + .../github/javaparser/utils/ClassUtils.java | 88 + .../javaparser/utils/CodeGenerationUtils.java | 163 + .../javaparser/utils/CollectionStrategy.java | 78 + .../javaparser/utils/LineSeparator.java | 187 + .../java/com/github/javaparser/utils/Log.java | 165 + .../com/github/javaparser/utils/Pair.java | 68 + .../utils/ParserCollectionStrategy.java | 104 + .../javaparser/utils/PositionUtils.java | 185 + .../github/javaparser/utils/ProjectRoot.java | 76 + .../utils/SeparatedItemStringBuilder.java | 68 + .../github/javaparser/utils/SourceRoot.java | 625 ++ .../github/javaparser/utils/SourceZip.java | 147 + .../javaparser/utils/StringEscapeUtils.java | 395 + .../github/javaparser/utils/TypeUtils.java | 76 + .../com/github/javaparser/utils/Utils.java | 322 + .../github/javaparser/utils/VisitorList.java | 300 + .../github/javaparser/utils/VisitorMap.java | 145 + .../github/javaparser/utils/VisitorSet.java | 190 + .../javaparser/GeneratedJavaParserBase.java | 449 + .../GeneratedJavaParserTokenManagerBase.java | 58 + .../com/github/javaparser/ModifierHolder.java | 43 + .../com/github/javaparser/RangedList.java | 54 + .../com/github/javaparser/TokenBase.java | 39 + javaparser-core/src/main/javacc/java.jj | 5842 +++++++++++ javaparser-symbol-solver-core/.gitignore | 5 + javaparser-symbol-solver-core/pom.xml | 64 + .../symbolsolver/JavaSymbolSolver.java | 428 + .../symbolsolver/SourceFileInfoExtractor.java | 223 + .../symbolsolver/cache/DefaultCacheStats.java | 321 + .../symbolsolver/cache/GuavaCache.java | 102 + .../symbolsolver/cache/InMemoryCache.java | 102 + .../symbolsolver/cache/NoCache.java | 89 + .../MethodUsageResolutionCapability.java | 34 + .../SymbolResolutionCapability.java | 37 + .../TypeVariableResolutionCapability.java | 32 + .../common/MethodDeclarationCommonLogic.java | 111 + .../symbolsolver/javaparser/package-info.java | 25 + .../DefaultVisitorAdapter.java | 536 + .../javaparsermodel/FailureHandler.java | 79 + .../javaparsermodel/JavaParserFacade.java | 708 ++ .../javaparsermodel/JavaParserFactory.java | 186 + .../javaparsermodel/TypeExtractor.java | 668 ++ .../contexts/AbstractJavaParserContext.java | 289 + .../AbstractMethodLikeDeclarationContext.java | 131 + .../AnnotationDeclarationContext.java | 78 + .../AnonymousClassDeclarationContext.java | 210 + .../contexts/ArrayAccessExprContext.java | 97 + .../contexts/BinaryExprContext.java | 248 + .../contexts/BlockStmtContext.java | 108 + .../contexts/CatchClauseContext.java | 94 + .../ClassOrInterfaceDeclarationContext.java | 129 + ...sOrInterfaceDeclarationExtendsContext.java | 53 + .../contexts/CompilationUnitContext.java | 349 + .../contexts/ConstructorContext.java | 54 + .../contexts/ContextHelper.java | 52 + .../contexts/EnclosedExprContext.java | 81 + .../contexts/EnumDeclarationContext.java | 87 + .../contexts/FieldAccessContext.java | 134 + .../contexts/ForEachStatementContext.java | 74 + .../contexts/ForStatementContext.java | 85 + .../contexts/IfStatementContext.java | 183 + .../contexts/InstanceOfExprContext.java | 87 + .../JavaParserTypeDeclarationAdapter.java | 295 + .../contexts/LambdaExprContext.java | 249 + .../contexts/MethodCallExprContext.java | 619 ++ .../contexts/MethodContext.java | 54 + .../contexts/MethodReferenceExprContext.java | 223 + .../contexts/ObjectCreationContext.java | 83 + .../contexts/StatementContext.java | 335 + .../contexts/SwitchEntryContext.java | 100 + .../contexts/TryWithResourceContext.java | 119 + .../contexts/UnaryExprContext.java | 75 + .../VariableDeclarationExprContext.java | 83 + .../contexts/VariableDeclaratorContext.java | 62 + .../declarations/AstResolutionUtils.java | 128 + .../DefaultConstructorDeclaration.java | 88 + .../JavaParserAnnotationDeclaration.java | 166 + ...JavaParserAnnotationMemberDeclaration.java | 77 + .../JavaParserAnonymousClassDeclaration.java | 268 + .../JavaParserClassDeclaration.java | 495 + .../JavaParserConstructorDeclaration.java | 115 + .../JavaParserEnumConstantDeclaration.java | 72 + .../JavaParserEnumDeclaration.java | 579 + .../JavaParserFieldDeclaration.java | 122 + .../JavaParserInterfaceDeclaration.java | 410 + .../JavaParserMethodDeclaration.java | 178 + .../JavaParserParameterDeclaration.java | 90 + .../JavaParserPatternDeclaration.java | 72 + .../JavaParserSymbolDeclaration.java | 74 + .../declarations/JavaParserTypeAdapter.java | 201 + .../declarations/JavaParserTypeParameter.java | 245 + .../JavaParserTypeVariableDeclaration.java | 207 + .../JavaParserVariableDeclaration.java | 95 + .../declarators/AbstractSymbolDeclarator.java | 40 + .../declarators/FieldSymbolDeclarator.java | 51 + .../declarators/NoSymbolDeclarator.java | 45 + .../ParameterSymbolDeclarator.java | 47 + .../declarators/PatternSymbolDeclarator.java | 49 + .../declarators/VariableSymbolDeclarator.java | 71 + .../javaparsermodel/package-info.java | 25 + .../JavassistAnnotationDeclaration.java | 163 + .../JavassistAnnotationMemberDeclaration.java | 94 + .../JavassistClassDeclaration.java | 329 + .../JavassistConstructorDeclaration.java | 112 + .../JavassistEnumConstantDeclaration.java | 75 + .../JavassistEnumDeclaration.java | 263 + .../javassistmodel/JavassistFactory.java | 94 + .../JavassistFieldDeclaration.java | 101 + .../JavassistInterfaceDeclaration.java | 271 + .../JavassistMethodDeclaration.java | 150 + ...JavassistMethodLikeDeclarationAdapter.java | 120 + .../JavassistParameterDeclaration.java | 92 + .../JavassistTypeDeclarationAdapter.java | 294 + .../JavassistTypeParameter.java | 134 + .../javassistmodel/JavassistUtils.java | 252 + .../javassistmodel/package-info.java | 25 + .../logic/AbstractClassDeclaration.java | 90 + .../logic/AbstractTypeDeclaration.java | 91 + .../symbolsolver/logic/ObjectProvider.java | 32 + .../ReflectionAnnotationDeclaration.java | 241 + ...ReflectionAnnotationMemberDeclaration.java | 129 + .../ReflectionClassAdapter.java | 226 + .../ReflectionClassDeclaration.java | 401 + .../ReflectionConstructorDeclaration.java | 102 + .../ReflectionEnumConstantDeclaration.java | 56 + .../ReflectionEnumDeclaration.java | 259 + .../reflectionmodel/ReflectionFactory.java | 137 + .../ReflectionFieldDeclaration.java | 107 + .../ReflectionInterfaceDeclaration.java | 322 + .../ReflectionMethodDeclaration.java | 163 + .../ReflectionMethodResolutionLogic.java | 160 + .../ReflectionParameterDeclaration.java | 120 + .../ReflectionPatternDeclaration.java | 85 + .../ReflectionTypeParameter.java | 137 + .../comparators/ClassComparator.java | 46 + .../comparators/MethodComparator.java | 46 + .../comparators/ParameterComparator.java | 40 + .../reflectionmodel/package-info.java | 25 + .../symbolsolver/resolution/SymbolSolver.java | 191 + .../resolution/naming/NameCategory.java | 68 + .../resolution/naming/NameLogic.java | 1005 ++ .../resolution/naming/NameRole.java | 30 + .../BooleanConditionalExprHandler.java | 48 + .../promotion/ConditionalExprResolver.java | 53 + .../NumericConditionalExprHandler.java | 172 + .../ReferenceConditionalExprHandler.java | 50 + .../resolution/typeinference/Bound.java | 125 + .../resolution/typeinference/BoundSet.java | 835 ++ .../typeinference/ConstraintFormula.java | 146 + .../typeinference/ConstraintFormulaSet.java | 74 + .../typeinference/ControlFlowLogic.java | 319 + .../typeinference/InferenceVariable.java | 119 + .../InferenceVariableSubstitution.java | 57 + .../typeinference/Instantiation.java | 72 + .../typeinference/InstantiationSet.java | 89 + .../typeinference/LeastUpperBoundLogic.java | 548 + .../resolution/typeinference/MethodType.java | 76 + .../typeinference/ProperLowerBound.java | 71 + .../typeinference/ProperUpperBound.java | 71 + .../typeinference/Substitution.java | 66 + .../resolution/typeinference/TypeHelper.java | 325 + .../typeinference/TypeInference.java | 735 ++ .../typeinference/TypeInferenceCache.java | 77 + .../typeinference/bounds/CapturesBound.java | 90 + .../typeinference/bounds/FalseBound.java | 62 + .../typeinference/bounds/SameAsBound.java | 112 + .../typeinference/bounds/SubtypeOfBound.java | 117 + .../typeinference/bounds/ThrowsBound.java | 83 + .../ExpressionCompatibleWithType.java | 365 + .../LambdaThrowsCompatibleWithType.java | 88 + ...thodReferenceThrowsCompatibleWithType.java | 83 + .../TypeCompatibleWithType.java | 142 + .../TypeContainedByType.java | 116 + .../constraintformulas/TypeSameAsType.java | 159 + .../constraintformulas/TypeSubtypeOfType.java | 158 + .../resolution/typesolvers/AarTypeSolver.java | 78 + .../typesolvers/ClassLoaderTypeSolver.java | 113 + .../typesolvers/CombinedTypeSolver.java | 267 + .../resolution/typesolvers/JarTypeSolver.java | 285 + .../typesolvers/JavaParserTypeSolver.java | 313 + .../typesolvers/MemoryTypeSolver.java | 98 + .../typesolvers/ReflectionTypeSolver.java | 58 + .../typesolvers/TypeSolverBuilder.java | 327 + .../symbolsolver/utils/FileUtils.java | 46 + .../utils/SymbolSolverCollectionStrategy.java | 130 + javaparser-symbol-solver-testing/.gitignore | 5 + javaparser-symbol-solver-testing/pom.xml | 200 + .../java/com/github/javaparser/SlowTest.java | 35 + .../ast/type/ClassOrInterfaceTypeTest.java | 79 + .../declarations/AssociableToASTTest.java | 86 + .../declarations/HasAccessSpecifierTest.java | 37 + .../ResolvedAnnotationDeclarationTest.java | 38 + ...solvedAnnotationMemberDeclarationTest.java | 29 + .../ResolvedClassDeclarationTest.java | 60 + .../ResolvedConstructorDeclarationTest.java | 29 + .../declarations/ResolvedDeclarationTest.java | 107 + .../ResolvedEnumConstantDeclarationTest.java | 44 + .../ResolvedEnumDeclarationTest.java | 38 + .../ResolvedFieldDeclarationTest.java | 56 + .../ResolvedMethodDeclarationTest.java | 30 + .../ResolvedMethodLikeDeclarationTest.java | 31 + .../ResolvedParameterDeclarationTest.java | 44 + .../ResolvedPatternDeclarationTest.java | 43 + .../ResolvedReferenceTypeDeclarationTest.java | 54 + .../ResolvedTypeDeclarationTest.java | 93 + .../ResolvedTypeParameterDeclarationTest.java | 40 + .../ResolvedTypeParametrizableTest.java | 47 + .../ResolvedValueDeclarationTest.java | 43 + .../AbstractSymbolResolutionTest.java | 161 + .../symbolsolver/FindingAllFieldsTest.java | 61 + .../javaparser/symbolsolver/Issue113Test.java | 74 + .../javaparser/symbolsolver/Issue116Test.java | 56 + .../javaparser/symbolsolver/Issue128Test.java | 69 + .../symbolsolver/Issue1364Test.java | 101 + .../symbolsolver/Issue1370Test.java | 68 + .../javaparser/symbolsolver/Issue144Test.java | 91 + .../symbolsolver/Issue1456Test.java | 59 + .../symbolsolver/Issue1479Test.java | 66 + .../symbolsolver/Issue1480Test.java | 57 + .../symbolsolver/Issue1485Test.java | 64 + .../symbolsolver/Issue1491Test.java | 126 + .../symbolsolver/Issue1511Test.java | 87 + .../symbolsolver/Issue1518Test.java | 63 + .../symbolsolver/Issue1526Test.java | 91 + .../javaparser/symbolsolver/Issue156Test.java | 51 + .../symbolsolver/Issue1574Test.java | 108 + .../symbolsolver/Issue1599Test.java | 68 + .../symbolsolver/Issue1668Test.java | 74 + .../symbolsolver/Issue1713Test.java | 57 + .../symbolsolver/Issue1726Test.java | 57 + .../symbolsolver/Issue1757Test.java | 64 + .../symbolsolver/Issue1769Test.java | 85 + .../symbolsolver/Issue1774Test.java | 81 + .../symbolsolver/Issue1814Test.java | 105 + .../symbolsolver/Issue1817Test.java | 65 + .../symbolsolver/Issue1827Test.java | 69 + .../javaparser/symbolsolver/Issue185Test.java | 56 + .../symbolsolver/Issue1868Test.java | 74 + .../javaparser/symbolsolver/Issue186Test.java | 68 + .../javaparser/symbolsolver/Issue18Test.java | 51 + .../symbolsolver/Issue1945Test.java | 113 + .../symbolsolver/Issue1946Test.java | 61 + .../symbolsolver/Issue1950Test.java | 70 + .../javaparser/symbolsolver/Issue200Test.java | 51 + .../symbolsolver/Issue2035Test.java | 179 + .../symbolsolver/Issue2044Test.java | 222 + .../symbolsolver/Issue2062Test.java | 61 + .../symbolsolver/Issue2065Test.java | 60 + .../symbolsolver/Issue2083Test.java | 58 + .../symbolsolver/Issue2132Test.java | 60 + .../symbolsolver/Issue2162Test.java | 148 + .../symbolsolver/Issue2210Test.java | 64 + .../symbolsolver/Issue2236Test.java | 59 + .../symbolsolver/Issue2259Test.java | 70 + .../symbolsolver/Issue2284Test.java | 67 + .../symbolsolver/Issue2289Test.java | 71 + .../javaparser/symbolsolver/Issue228Test.java | 52 + .../javaparser/symbolsolver/Issue232Test.java | 47 + .../javaparser/symbolsolver/Issue235Test.java | 64 + .../javaparser/symbolsolver/Issue2360.java | 112 + .../symbolsolver/Issue2362Test.java | 63 + .../symbolsolver/Issue2367Test.java | 61 + .../symbolsolver/Issue2397Test.java | 79 + .../symbolsolver/Issue2406Test.java | 77 + .../javaparser/symbolsolver/Issue241Test.java | 62 + .../symbolsolver/Issue2477Test.java | 58 + .../symbolsolver/Issue2481Test.java | 53 + .../symbolsolver/Issue2489Test.java | 64 + .../javaparser/symbolsolver/Issue251Test.java | 50 + .../symbolsolver/Issue2595Test.java | 170 + .../symbolsolver/Issue2602Test.java | 98 + .../symbolsolver/Issue2740Test.java | 69 + .../symbolsolver/Issue2764Test.java | 66 + .../javaparser/symbolsolver/Issue276Test.java | 62 + .../symbolsolver/Issue2781Test.java | 70 + .../symbolsolver/Issue2823Test.java | 64 + .../symbolsolver/Issue2878Test.java | 77 + .../symbolsolver/Issue2909Test.java | 143 + .../symbolsolver/Issue2943Test.java | 56 + .../symbolsolver/Issue2951Test.java | 105 + .../symbolsolver/Issue2953Test.java | 91 + .../symbolsolver/Issue2987Test.java | 55 + .../symbolsolver/Issue2995Test.java | 58 + .../javaparser/symbolsolver/Issue300Test.java | 64 + .../symbolsolver/Issue3024Test.java | 63 + .../symbolsolver/Issue3028Test.java | 55 + .../symbolsolver/Issue3030Test.java | 114 + .../symbolsolver/Issue3038Test.java | 106 + .../symbolsolver/Issue3045Test.java | 66 + .../symbolsolver/Issue3083Test.java | 56 + .../symbolsolver/Issue3087Test.java | 70 + .../symbolsolver/Issue3099Test.java | 78 + .../symbolsolver/Issue3112Test.java | 82 + .../symbolsolver/Issue3136Test.java | 61 + .../javaparser/symbolsolver/Issue314Test.java | 78 + .../symbolsolver/Issue3159Test.java | 59 + .../symbolsolver/Issue3173Test.java | 58 + .../symbolsolver/Issue3184Test.java | 70 + .../symbolsolver/Issue3200Test.java | 97 + .../symbolsolver/Issue3272Test.java | 78 + .../symbolsolver/Issue3278Test.java | 75 + .../symbolsolver/Issue3308Test.java | 128 + .../javaparser/symbolsolver/Issue343Test.java | 90 + .../javaparser/symbolsolver/Issue347Test.java | 67 + .../symbolsolver/Issue3614Test.java | 55 + .../javaparser/symbolsolver/Issue366Test.java | 54 + .../symbolsolver/Issue3859Test.java | 73 + .../symbolsolver/Issue3866Test.java | 69 + .../symbolsolver/Issue3878Test.java | 58 + .../symbolsolver/Issue3918Test.java | 71 + .../symbolsolver/Issue3951Test.java | 67 + .../symbolsolver/Issue3972Test.java | 58 + .../symbolsolver/Issue3976Test.java | 55 + .../symbolsolver/Issue4037Test.java | 59 + .../symbolsolver/Issue4047Test.java | 63 + .../symbolsolver/Issue4124Test.java | 71 + .../symbolsolver/Issue4284Test.java | 57 + .../symbolsolver/Issue4358Test.java | 38 + .../javaparser/symbolsolver/Issue546Test.java | 67 + .../javaparser/symbolsolver/Issue84Test.java | 46 + .../JavaParserAPIIntegrationTest.java | 283 + .../symbolsolver/JavaSymbolSolverTest.java | 70 + .../symbolsolver/PullRequest2398Test.java | 84 + .../SolveMethodDeclaredInEnumTest.java | 64 + .../cache/GuavaCacheAdapterTest.java | 165 + .../symbolsolver/cache/InMemoryCacheTest.java | 140 + .../symbolsolver/cache/NoCacheTest.java | 83 + .../MethodUsageResolutionCapabilityTest.java | 30 + .../TypeVariableResolutionCapabilityTest.java | 28 + .../javaparsermodel/ConvertToUsageTest.java | 60 + .../DifferentiateDotExpressionTest.java | 119 + .../javaparsermodel/JavaParserFacadeTest.java | 101 + ...lassOrInterfaceDeclarationContextTest.java | 79 + .../JavaParserTypeDeclarationAdapterTest.java | 112 + .../MultiCatchMethodCallExprTest.java | 52 + .../JavaParserAnnotationDeclarationTest.java | 133 + ...vaParserAnonymousClassDeclarationTest.java | 137 + .../JavaParserClassDeclarationTest.java | 1043 ++ .../JavaParserEnumDeclarationTest.java | 981 ++ .../JavaParserFieldDeclarationTest.java | 103 + .../JavaParserInterfaceDeclarationTest.java | 944 ++ .../JavaParserMethodDeclarationTest.java | 88 + .../JavaParserParameterDeclarationTest.java | 55 + .../JavaParserPatternDeclarationTest.java | 63 + .../JavaParserSymbolDeclarationTest.java | 95 + .../JavaParserTypeParameterTest.java | 58 + ...JavaParserTypeVariableDeclarationTest.java | 109 + .../JavaParserVariableDeclarationTest.java | 94 + .../javassistmodel/Issue257Test.java | 67 + .../JavassistAnnotationDeclarationTest.java | 153 + ...assistAnnotationMemberDeclarationTest.java | 63 + .../JavassistClassDeclarationTest.java | 589 ++ .../JavassistConstructorDeclarationTest.java | 56 + .../JavassistEnumConstantDeclarationTest.java | 61 + .../JavassistEnumDeclarationTest.java | 150 + .../JavassistFieldDeclarationTest.java | 52 + .../JavassistInterfaceDeclarationTest.java | 261 + .../JavassistMethodDeclarationTest.java | 111 + .../JavassistParameterDeclarationTest.java | 168 + .../JavassistTypeDeclarationAdapterTest.java | 108 + ...JavassistTypeParameterDeclarationTest.java | 110 + .../logic/AbstractClassDeclarationTest.java | 32 + .../logic/AbstractTypeDeclarationTest.java | 53 + .../logic/FunctionInterfaceLogicTest.java | 80 + .../logic/InferenceContextTest.java | 91 + .../logic/MethodResolutionCapabilityTest.java | 32 + .../model/resolution/SymbolReferenceTest.java | 111 + .../model/typesystem/ArrayTypeTest.java | 189 + .../model/typesystem/LazyTypeTest.java | 83 + .../model/typesystem/NullTypeTest.java | 152 + .../model/typesystem/PrimitiveTypeTest.java | 350 + .../model/typesystem/ReferenceTypeTest.java | 1050 ++ .../typesystem/TypeVariableUsageTest.java | 56 + .../model/typesystem/VoidTypeTest.java | 127 + .../model/typesystem/WildcardUsageTest.java | 486 + .../ReflectionAnnotationDeclarationTest.java | 122 + .../ReflectionClassDeclarationTest.java | 838 ++ .../ReflectionEnumDeclarationTest.java | 130 + .../ReflectionFieldDeclarationTest.java | 49 + .../ReflectionInterfaceDeclarationTest.java | 128 + .../ReflectionMethodDeclarationTest.java | 72 + .../ReflectionParameterDeclarationTest.java | 84 + .../reflectionmodel/ReflectionTestObject.java | 42 + .../resolution/AbstractResolutionTest.java | 75 + .../resolution/AnalyseJavaParserTest.java | 273 + .../AnalyseJavaSymbolSolver060Test.java | 371 + .../AnalyseNewJavaParserHelpersTest.java | 102 + .../resolution/AnalyseNewJavaParserTest.java | 326 + .../resolution/AnnotationsResolutionTest.java | 444 + .../AnonymousClassesResolutionTest.java | 83 + .../resolution/ArrayExprTest.java | 70 + .../CompilationUnitContextResolutionTest.java | 124 + .../resolution/ConditionalExprTest.java | 179 + .../ConstructorsResolutionTest.java | 265 + .../symbolsolver/resolution/ContextTest.java | 1570 +++ .../resolution/DefaultPackageTest.java | 192 + .../EnumLiteralsInAnnotatedClassTest.java | 138 + .../resolution/EnumResolutionTest.java | 160 + .../resolution/ExprResolutionTest.java | 427 + .../FieldAccessExprResolutionTest.java | 92 + .../resolution/FieldsResolutionTest.java | 231 + .../resolution/GenericsResolutionTest.java | 501 + ...plementedOrExtendedTypeResolutionTest.java | 102 + .../resolution/InstanceOfTest.java | 600 ++ .../InternalClassInInterfaceTest.java | 139 + .../JavaParserFacadeResolutionTest.java | 391 + .../LambdaGenericResolutionTest.java | 76 + .../resolution/LambdaResolutionTest.java | 195 + .../resolution/MethodDescriptorTest.java | 140 + .../resolution/MethodLikeSignaturesTest.java | 72 + .../MethodReferenceResolutionTest.java | 626 ++ .../MethodsResolutionLogicTest.java | 91 + .../resolution/MethodsResolutionTest.java | 651 ++ .../MethodsResolutionWithJavassistTest.java | 77 + .../resolution/NotQuiteCyclicParentTest.java | 57 + .../PolyExpressionResolutionTest.java | 141 + .../QualifiedNameResolutionTest.java | 51 + .../ReferenceTypeResolutionTest.java | 103 + .../StatementContextResolutionTest.java | 112 + .../resolution/SymbolSolverTest.java | 100 + .../SymbolSolverWithJavassistClassTest.java | 143 + .../SymbolSolverWithJavassistEnumTest.java | 125 + ...ymbolSolverWithJavassistInterfaceTest.java | 115 + .../resolution/TypeDescriptorTest.java | 59 + ...TypeInClassWithAnnotationAncestorTest.java | 48 + .../TypeResolutionWithSameNameTest.java | 205 + .../UnknownMethodsResolutionTest.java | 63 + .../resolution/VariableResolutionTest.java | 64 + .../resolution/VariadicResolutionTest.java | 137 + .../resolution/javaparser/VarTypeTest.java | 88 + .../BlockStmtContextResolutionTest.java | 86 + ...rfaceDeclarationContextResolutionTest.java | 496 + .../CompilationUnitContextResolutionTest.java | 247 + .../EnumDeclarationContextResolutionTest.java | 121 + .../FieldAccessContextResolutionTest.java | 55 + .../LambdaExprContextResolutionTest.java | 141 + .../MethodCallExprContextResolutionTest.java | 212 + .../contexts/MethodContextResolutionTest.java | 63 + ...JavaParserTypeParameterResolutionTest.java | 104 + .../logic/FunctionalInterfaceLogicTest.java | 319 + .../naming/AbstractNameLogicTest.java | 105 + .../naming/NameLogicDisambiguationTest.java | 377 + .../resolution/naming/NameLogicTest.java | 961 ++ .../naming/NameLogicTestingJss060Test.java | 520 + .../SymbolResolutionResolutionTest.java | 90 + .../typeinference/LeastUpperBoundTest.java | 444 + .../typeinference/bounds/SameAsBoundTest.java | 53 + .../bounds/SubtypeOfBoundTest.java | 110 + .../ConstraintFormulaTest.java | 91 + .../types/ResolvedArrayTypeTest.java | 194 + .../types/ResolvedPrimitiveTypeTest.java | 121 + .../typesolvers/AarTypeSolverTest.java | 61 + .../typesolvers/AbstractTypeSolverTest.java | 102 + .../ClassLoaderTypeSolverTest.java | 56 + .../typesolvers/CombinedTypeSolverTest.java | 189 + .../typesolvers/JarTypeSolverTest.java | 165 + .../typesolvers/JavaParserTypeSolverTest.java | 191 + .../typesolvers/MemoryTypeSolverTest.java | 111 + .../typesolvers/ReflectionTypeSolverTest.java | 82 + .../typesolvers/TypeSolverBuilderTest.java | 317 + .../testingclasses/SomeClass.java | 29 + .../testingclasses/TargetType.java | 45 + .../testingclasses/UtilityClass.java | 28 + .../utils/LeanParserConfiguration.java | 33 + .../SymbolSolverCollectionStrategyTest.java | 84 + .../test/resources/AClassWithFields.java.txt | 11 + .../AClassWithFieldsAndGenerics.java.txt | 13 + .../AccessClassMemberThroughThis.java.txt | 17 + .../AccessEnumMemberThroughThis.java.txt | 15 + .../resources/AccessThroughSuper.java.txt | 25 + .../src/test/resources/AnEnum.java.txt | 9 + .../src/test/resources/AnInterface.java.txt | 2 + .../src/test/resources/Ancestor.java | 5 + .../src/test/resources/Annotations.java.txt | 91 + .../AnonymousClassDeclarations.java.txt | 75 + .../AnonymousClassMethodClass.java.txt | 14 + .../src/test/resources/ArrayAccess.java.txt | 9 + .../src/test/resources/ClassCast.java.txt | 13 + .../test/resources/ClassExpression.java.txt | 9 + .../ClassExtendingUnknownClass.java.txt | 20 + .../resources/ClassTypeParameter.java.txt | 7 + .../ClassWithAnnotationAncestor.java.txt | 16 + .../test/resources/ClassWithMethods.java.txt | 14 + .../test/resources/ClassWithSymbols.java.txt | 39 + .../resources/ClassWithTypeVariables.java.txt | 3 + .../test/resources/ClassWithTypes.java.txt | 19 + .../00_receiver/main/Child.java | 8 + .../00_receiver/main/Main.java | 10 + .../00_receiver/main/Parent.java | 12 + .../01_parent/main/Child.java | 5 + .../01_parent/main/GrandParent.java | 12 + .../01_parent/main/Main.java | 10 + .../01_parent/main/Parent.java | 8 + .../02_nested/main/Child.java | 8 + .../02_nested/main/Main.java | 10 + .../02_nested/main/Parent.java | 15 + .../03_symbol/main/Clazz.java | 12 + .../03_symbol/main/Main.java | 11 + .../04_reviewComment/main/Main.java | 20 + .../resources/CompilationUnitSymbols.java.txt | 5 + .../CompilationUnitWithImports.java.txt | 4 + .../resources/ComplexTypeResolving.java.txt | 23 + .../test/resources/ConstructorCalls.java.txt | 52 + .../resources/ConstructorCallsEnum.java.txt | 10 + .../src/test/resources/ElementOfList.java.txt | 23 + .../resources/EnumAccessSpecifier.java.txt | 13 + .../EnumAndStaticInitializer.java.txt | 25 + .../test/resources/EnumFieldAccess.java.txt | 9 + .../FieldAccessExprResolution.java.txt | 59 + .../GenericArrayMethodArgument.java.txt | 12 + .../resources/GenericClassNavigator.java.txt | 31 + .../test/resources/GenericCollection.java.txt | 12 + .../GenericCollectionWithExtension.java.txt | 21 + .../src/test/resources/GenericFields.java.txt | 15 + .../test/resources/GenericLambdas.java.txt | 9 + .../resources/GenericMethodArguments.java.txt | 33 + .../src/test/resources/Generics.java.txt | 63 + .../test/resources/GenericsWildcard.java.txt | 19 + .../test/resources/Generics_issue7.java.txt | 32 + .../ISSUES_Generic_Parameter.java.txt | 14 + ...plementedOrExtendedTypeResolution.java.txt | 47 + .../pkg/another/A.java | 4 + .../pkg/main/A.java | 5 + .../resources/InterfaceInheritance.java.txt | 16 + .../src/test/resources/Issue116.java.txt | 7 + .../src/test/resources/Issue1482.java.txt | 13 + .../src/test/resources/Issue156.java.txt | 9 + .../src/test/resources/Issue18.java.txt | 8 + .../src/test/resources/Issue186.java.txt | 23 + .../src/test/resources/Issue200.java.txt | 33 + .../src/test/resources/Issue2258.java.txt | 11 + .../src/test/resources/Issue232.java.txt | 12 + .../src/test/resources/Issue235.java.txt | 17 + .../src/test/resources/Issue241.java.txt | 7 + .../src/test/resources/Issue251.java.txt | 17 + .../src/test/resources/Issue2667.java.txt | 10 + .../src/test/resources/Issue3028.java.txt | 16 + .../src/test/resources/Issue338.java.txt | 93 + .../src/test/resources/Issue84.java.txt | 10 + ...arTypeSolverConstructorResolution.java.txt | 9 + .../JreConditionalExpression.java.txt | 10 + .../src/test/resources/Lambda.java.txt | 60 + .../src/test/resources/LambdaCollect.java.txt | 12 + .../src/test/resources/LambdaMulti.java.txt | 30 + .../src/test/resources/LambdaVoid.java.txt | 14 + .../resources/LocalTypeDeclarations.java.txt | 14 + .../resources/LocalVariableInParent.java.txt | 57 + .../src/test/resources/MethodCalls.java.txt | 89 + .../MethodLikeSignaturesTest.java.txt | 9 + .../test/resources/MethodReferences.java.txt | 168 + .../resources/MethodTypeParameter.java.txt | 7 + .../test/resources/MethodTypeParams.java.txt | 38 + .../test/resources/MethodWithTypes.java.txt | 6 + .../src/test/resources/Navigator.java.txt | 26 + .../src/test/resources/Navigator2.java.txt | 23 + .../src/test/resources/Navigator3.java.txt | 25 + .../resources/NavigatorSimplified.java.txt | 33 + .../src/test/resources/NestedClasses.java.txt | 13 + .../test/resources/NestedInterfaces.java.txt | 13 + ...estedInterfacesWithIdenticalNames.java.txt | 13 + .../resources/NotQuiteCyclicParent.java.txt | 7 + .../resources/OverloadedMethodCall.java.txt | 12 + .../test/resources/OverloadedMethods.java.txt | 55 + .../test/resources/PlatformTestUtil.java.txt | 135 + .../test/resources/QualifiedNameTest.java.txt | 8 + .../test/resources/ReferencesToField.java.txt | 18 + .../resources/ReferencesToParameter.java.txt | 11 + .../ReflectionFieldOfItself.java.txt | 7 + ...onTypeSolverConstructorResolution.java.txt | 7 + ...olverFieldFromInterfaceResolution.java.txt | 7 + .../src/test/resources/SwitchOnEnum.java.txt | 15 + .../resources/SymbolResolverExample.java.txt | 11 + .../resources/ThisInAnonymousClass.java.txt | 13 + .../src/test/resources/TryInSwitch.java.txt | 20 + .../resources/TypeParamOnReturnType.java.txt | 15 + .../extends_duplicate/A.java | 7 + .../extends_duplicate/DuplicateTypeName.java | 5 + .../implements_duplicate/A.java | 7 + .../DuplicateTypeName.java | 5 + .../another/A.java | 4 + .../another/MyEnum.java | 5 + .../main/Main.java | 8 + .../another/A.java | 4 + .../main/A.java | 4 + .../main/Main.java | 7 + .../another/A.java | 4 + .../main/A.java | 4 + .../main/Main.java | 7 + .../another/String.java | 4 + .../main/Main.java | 7 + .../test/resources/UnknownMethods.java.txt | 16 + ...VariableResolutionInVariousScopes.java.txt | 15 + .../FieldDotExpressions.java | 33 + .../InnerClassDotExpressions.java | 25 + .../InnerStaticClassFieldDotExpressions.java | 8 + .../PackageDotExpressions.java | 16 + .../com/packageName/ClassInPackage.java | 7 + .../com/packageName/InnerClassContainer.java | 17 + .../packageName/InnerClassFieldContainer.java | 25 + .../InnerStaticClassFieldContainer.java | 15 + .../foo/bar/AClass.java | 6 + .../foo/bar/BinaryExpr.java | 11 + .../foo/bar/differentpackage/AClass2.java | 8 + .../resources/enums/EnumWithAncestor.java | 5 + .../resources/enums/EnumWithInnerType.java | 7 + .../foo/bar/AClass.java | 6 + .../foo/bar/AnInterface.java | 9 + .../foo/bar/differentpackage/AClass2.java | 8 + .../resources/issue113/com/foo/Widget.java | 45 + .../issue113/com/foo/base/Widget.java | 6 + .../test/resources/issue128/foo/Issue128.java | 10 + .../test/resources/issue144/HelloWorld.java | 8 + .../src/test/resources/issue1456/bar/A.java | 4 + .../src/test/resources/issue1456/foo/A.java | 4 + .../src/test/resources/issue1479/A.java | 3 + .../src/test/resources/issue1479/B.java | 3 + .../src/test/resources/issue1480/A.java | 5 + .../src/test/resources/issue1480/B.java | 11 + .../src/test/resources/issue1485/Complex.java | 27 + .../src/test/resources/issue1491/A.java | 20 + .../src/test/resources/issue1511/A.java | 5 + .../src/test/resources/issue1518/Test1.java | 7 + .../issue1526/compiles/a/b/c/DataObject.java | 4 + .../compiles/a/b/c/DataObjectFactory.java | 5 + .../compiles/a/b/c/ExampleClass.java | 19 + .../compiles/d/e/f/DataObjectFactory.java | 11 + .../issue1526/errors/a/b/c/DataObject.java | 4 + .../errors/a/b/c/DataObjectFactory.java | 5 + .../issue1526/errors/a/b/c/ExampleClass.java | 19 + .../errors/d/e/f/DataObjectFactory.java | 11 + .../resources/issue1574/BlockComment.java | 15 + .../issue1574/ClassWithOrphanComments.java | 15 + .../src/test/resources/issue1574/Comment.java | 9 + .../src/test/resources/issue1599/A.java | 3 + .../resources/issue1769/foo/OtherClass.java | 4 + .../src/test/resources/issue1817/X.java | 5 + .../src/test/resources/issue1868/B.java | 5 + .../implementations/HairTypeWool.java | 11 + .../issue1945/implementations/Sheep.java | 13 + .../implementations/WoolRenderer.java | 18 + .../issue1945/interfaces/HairType.java | 7 + .../interfaces/HairTypeRenderer.java | 20 + .../issue1945/interfaces/HairyAnimal.java | 7 + .../issue1945/main/MainIssue1945.java | 48 + .../src/test/resources/issue2236/A.java | 11 + .../src/test/resources/issue2362/Test.java | 11 + .../src/test/resources/issue2366/Test.java | 14 + .../test/resources/issue2367/Issue2367.java | 8 + .../issue241/TypeWithMemberType.java | 9 + .../resources/issue2489/ComponentBase.java | 2 + .../resources/issue2489/ObjectContext.java | 5 + .../issue2489/ObjectContextDecorator .java | 6 + .../src/test/resources/issue257/A.java.txt | 9 + .../issue2667/javaparser/JSONObject.java | 24 + .../src/test/resources/issue276/foo/A.java | 11 + .../src/test/resources/issue276/foo/B.java | 5 + .../src/test/resources/issue276/foo/C.java | 11 + .../src/test/resources/issue2823/ClassA.java | 3 + .../src/test/resources/issue2823/ClassB.java | 3 + .../src/test/resources/issue2878/U9.java | 7 + .../test/resources/issue2909/OuterClass.java | 2 + .../src/test/resources/issue2951/foo/A.class | Bin 0 -> 293 bytes .../src/test/resources/issue2951/foo/A.java | 5 + .../src/test/resources/issue2953/foo/A.class | Bin 0 -> 986 bytes .../src/test/resources/issue2953/foo/A.java | 15 + .../src/test/resources/issue2953/foo/IB.class | Bin 0 -> 320 bytes .../src/test/resources/issue2953/foo/IB.java | 8 + .../src/test/resources/issue300/Issue300.java | 12 + .../issue3099/com/example/Alpha.java | 26 + .../resources/issue3099/com/example/Beta.java | 30 + .../src/test/resources/issue4358/foo/A.java | 9 + .../src/test/resources/issue4358/foo/B.java | 6 + .../javaparser/GenericClass.java | 46 + .../resources/javassist_symbols/README.md | 8 + .../excluded_jar/result/doNotDelete.md | 0 .../excluded_jar/InterfaceExcludedJar.java | 5 + .../excluded_jar/SuperClassExcludedJar.java | 5 + .../included_jar/result/doNotDelete.md | 0 .../included_jar/InterfaceIncludedJar.java | 5 + .../included_jar/SuperClassIncludedJar.java | 5 + .../main_jar/result/doNotDelete.md | 0 .../main_jar/ConcreteClass.java | 6 + .../main_jar/ConcreteEnum.java | 10 + .../EnumInterfaceUserExcludedJar.java | 7 + .../EnumInterfaceUserIncludedJar.java | 7 + .../main_jar/EnumInterfaceUserOwnJar.java | 5 + .../main_jar/InterfaceOwnJar.java | 5 + .../main_jar/InterfaceUserExcludedJar.java | 7 + .../main_jar/InterfaceUserIncludedJar.java | 7 + .../main_jar/InterfaceUserOwnJar.java | 5 + .../main_jar/StandaloneInterface.java | 6 + .../main_jar/SubClassExcludedJar.java | 7 + .../main_jar/SubClassIncludedJar.java | 7 + .../main_jar/SubClassOwnJar.java | 5 + .../main_jar/SubInterfaceExcludedJar.java | 7 + .../main_jar/SubInterfaceIncludedJar.java | 7 + .../main_jar/SubInterfaceOwnJar.java | 5 + .../main_jar/SuperClassOwnJar.java | 5 + .../test/resources/javassistmethoddecl/C.java | 20 + .../test/resources/pullRequest2398/A.class | Bin 0 -> 228 bytes .../src/test/resources/pullRequest2398/A.java | 9 + .../test/resources/pullRequest2398/B.class | Bin 0 -> 176 bytes .../src/test/resources/pullRequest2398/B.java | 6 + .../test/resources/recursion-issue/Base.java | 5 + .../resources/recursion-issue/Extends.java | 8 + .../test/resources/recursion-issue/Usage.java | 6 + .../solveMethodDeclaredInEnum/MyEnum.java | 6 + .../symbolsolver_quicksetup/a/src/a.java | 2 + .../a/src/package_a/a.java | 4 + .../symbolsolver_quicksetup/b/src/b.java | 2 + .../b/src/package_b/b.java | 4 + .../symbolsolver_quicksetup/c/src/c.java | 2 + .../c/src/package_c/c.java | 4 + .../symbolsolver_quicksetup/src/Main.java | 6 + ...com_github_javaparser_CommentsInserter.txt | 49 + .../com_github_javaparser_JavaParser.txt | 49 + ...ithub_javaparser_ParseProblemException.txt | 10 + .../com_github_javaparser_ParseResult.txt | 19 + .../com_github_javaparser_ParseStart.txt | 2 + ..._github_javaparser_ParserConfiguration.txt | 0 .../com_github_javaparser_Position.txt | 9 + .../com_github_javaparser_Problem.txt | 7 + .../com_github_javaparser_Providers.txt | 18 + .../com_github_javaparser_Range.txt | 23 + ..._github_javaparser_ast_AccessSpecifier.txt | 0 ...github_javaparser_ast_ArrayBracketPair.txt | 5 + ...thub_javaparser_ast_ArrayCreationLevel.txt | 7 + ..._github_javaparser_ast_CompilationUnit.txt | 103 + .../com_github_javaparser_ast_Example.txt | 2 + ...ithub_javaparser_ast_ImportDeclaration.txt | 9 + .../com_github_javaparser_ast_Modifier.txt | 4 + .../com_github_javaparser_ast_Node.txt | 46 + ...thub_javaparser_ast_PackageDeclaration.txt | 11 + .../com_github_javaparser_ast_UserDataKey.txt | 5 + ...aparser_ast_body_AnnotationDeclaration.txt | 2 + ...r_ast_body_AnnotationMemberDeclaration.txt | 19 + ...ub_javaparser_ast_body_BodyDeclaration.txt | 4 + ...r_ast_body_ClassOrInterfaceDeclaration.txt | 17 + ...parser_ast_body_ConstructorDeclaration.txt | 53 + ...parser_ast_body_EmptyMemberDeclaration.txt | 4 + ...vaparser_ast_body_EmptyTypeDeclaration.txt | 4 + ...arser_ast_body_EnumConstantDeclaration.txt | 18 + ...ub_javaparser_ast_body_EnumDeclaration.txt | 13 + ...b_javaparser_ast_body_FieldDeclaration.txt | 68 + ...parser_ast_body_InitializerDeclaration.txt | 9 + ..._javaparser_ast_body_MethodDeclaration.txt | 98 + ...m_github_javaparser_ast_body_Parameter.txt | 32 + ...ub_javaparser_ast_body_TypeDeclaration.txt | 21 + ...javaparser_ast_body_VariableDeclarator.txt | 25 + ...vaparser_ast_body_VariableDeclaratorId.txt | 7 + ...b_javaparser_ast_comments_BlockComment.txt | 2 + ...github_javaparser_ast_comments_Comment.txt | 1 + ...parser_ast_comments_CommentsCollection.txt | 34 + ...javaparser_ast_comments_JavadocComment.txt | 2 + ...ub_javaparser_ast_comments_LineComment.txt | 2 + ...hub_javaparser_ast_expr_AnnotationExpr.txt | 1 + ...ub_javaparser_ast_expr_ArrayAccessExpr.txt | 8 + ..._javaparser_ast_expr_ArrayCreationExpr.txt | 16 + ...vaparser_ast_expr_ArrayInitializerExpr.txt | 6 + ..._github_javaparser_ast_expr_AssignExpr.txt | 10 + ..._github_javaparser_ast_expr_BinaryExpr.txt | 10 + ...javaparser_ast_expr_BooleanLiteralExpr.txt | 4 + ...om_github_javaparser_ast_expr_CastExpr.txt | 8 + ...ub_javaparser_ast_expr_CharLiteralExpr.txt | 3 + ...m_github_javaparser_ast_expr_ClassExpr.txt | 5 + ...ub_javaparser_ast_expr_ConditionalExpr.txt | 11 + ..._javaparser_ast_expr_DoubleLiteralExpr.txt | 2 + ...ithub_javaparser_ast_expr_EnclosedExpr.txt | 5 + ..._github_javaparser_ast_expr_Expression.txt | 0 ...ub_javaparser_ast_expr_FieldAccessExpr.txt | 12 + ...hub_javaparser_ast_expr_InstanceOfExpr.txt | 8 + ...javaparser_ast_expr_IntegerLiteralExpr.txt | 4 + ...er_ast_expr_IntegerLiteralMinValueExpr.txt | 2 + ..._github_javaparser_ast_expr_LambdaExpr.txt | 8 + ...github_javaparser_ast_expr_LiteralExpr.txt | 0 ...ub_javaparser_ast_expr_LongLiteralExpr.txt | 7 + ...arser_ast_expr_LongLiteralMinValueExpr.txt | 2 + ...vaparser_ast_expr_MarkerAnnotationExpr.txt | 4 + ...ub_javaparser_ast_expr_MemberValuePair.txt | 7 + ...hub_javaparser_ast_expr_MethodCallExpr.txt | 22 + ...avaparser_ast_expr_MethodReferenceExpr.txt | 7 + ...om_github_javaparser_ast_expr_NameExpr.txt | 3 + ...vaparser_ast_expr_NormalAnnotationExpr.txt | 13 + ...ub_javaparser_ast_expr_NullLiteralExpr.txt | 2 + ...javaparser_ast_expr_ObjectCreationExpr.txt | 18 + ..._javaparser_ast_expr_QualifiedNameExpr.txt | 5 + ...er_ast_expr_SingleMemberAnnotationExpr.txt | 7 + ..._javaparser_ast_expr_StringLiteralExpr.txt | 5 + ...m_github_javaparser_ast_expr_SuperExpr.txt | 5 + ...om_github_javaparser_ast_expr_ThisExpr.txt | 5 + ...om_github_javaparser_ast_expr_TypeExpr.txt | 4 + ...m_github_javaparser_ast_expr_UnaryExpr.txt | 7 + ...arser_ast_expr_VariableDeclarationExpr.txt | 42 + ...rser_ast_nodeTypes_NodeWithAnnotations.txt | 40 + ...parser_ast_nodeTypes_NodeWithBlockStmt.txt | 2 + ..._javaparser_ast_nodeTypes_NodeWithBody.txt | 2 + ...rser_ast_nodeTypes_NodeWithDeclaration.txt | 0 ...rser_ast_nodeTypes_NodeWithElementType.txt | 4 + ...vaparser_ast_nodeTypes_NodeWithExtends.txt | 6 + ...arser_ast_nodeTypes_NodeWithImplements.txt | 6 + ...vaparser_ast_nodeTypes_NodeWithJavaDoc.txt | 1 + ...vaparser_ast_nodeTypes_NodeWithMembers.txt | 116 + ...parser_ast_nodeTypes_NodeWithModifiers.txt | 28 + ..._javaparser_ast_nodeTypes_NodeWithName.txt | 0 ...arser_ast_nodeTypes_NodeWithParameters.txt | 40 + ...arser_ast_nodeTypes_NodeWithStatements.txt | 11 + ...parser_ast_nodeTypes_NodeWithThrowable.txt | 13 + ..._javaparser_ast_nodeTypes_NodeWithType.txt | 4 + ...er_ast_nodeTypes_NodeWithTypeArguments.txt | 7 + ...parser_ast_nodeTypes_NodeWithVariables.txt | 0 ..._github_javaparser_ast_stmt_AssertStmt.txt | 9 + ...m_github_javaparser_ast_stmt_BlockStmt.txt | 6 + ...m_github_javaparser_ast_stmt_BreakStmt.txt | 2 + ...github_javaparser_ast_stmt_CatchClause.txt | 9 + ...ithub_javaparser_ast_stmt_ContinueStmt.txt | 2 + .../com_github_javaparser_ast_stmt_DoStmt.txt | 8 + ...m_github_javaparser_ast_stmt_EmptyStmt.txt | 2 + ...stmt_ExplicitConstructorInvocationStmt.txt | 13 + ...hub_javaparser_ast_stmt_ExpressionStmt.txt | 5 + ...com_github_javaparser_ast_stmt_ForStmt.txt | 16 + ...github_javaparser_ast_stmt_ForeachStmt.txt | 14 + .../com_github_javaparser_ast_stmt_IfStmt.txt | 11 + ...github_javaparser_ast_stmt_LabeledStmt.txt | 7 + ..._github_javaparser_ast_stmt_ReturnStmt.txt | 6 + ...m_github_javaparser_ast_stmt_Statement.txt | 0 ...ub_javaparser_ast_stmt_SwitchEntryStmt.txt | 9 + ..._github_javaparser_ast_stmt_SwitchStmt.txt | 9 + ...b_javaparser_ast_stmt_SynchronizedStmt.txt | 9 + ...m_github_javaparser_ast_stmt_ThrowStmt.txt | 5 + ...com_github_javaparser_ast_stmt_TryStmt.txt | 15 + ...avaparser_ast_stmt_TypeDeclarationStmt.txt | 5 + ...m_github_javaparser_ast_stmt_WhileStmt.txt | 8 + ...m_github_javaparser_ast_type_ArrayType.txt | 14 + ...vaparser_ast_type_ClassOrInterfaceType.txt | 13 + ...b_javaparser_ast_type_IntersectionType.txt | 6 + ...thub_javaparser_ast_type_PrimitiveType.txt | 6 + ...thub_javaparser_ast_type_ReferenceType.txt | 0 .../com_github_javaparser_ast_type_Type.txt | 3 + ...thub_javaparser_ast_type_TypeParameter.txt | 12 + ...m_github_javaparser_ast_type_UnionType.txt | 6 + ...github_javaparser_ast_type_UnknownType.txt | 2 + ...om_github_javaparser_ast_type_VoidType.txt | 2 + ...ithub_javaparser_ast_type_WildcardType.txt | 9 + ...ub_javaparser_ast_visitor_CloneVisitor.txt | 690 ++ ...hub_javaparser_ast_visitor_DumpVisitor.txt | 1066 ++ ...b_javaparser_ast_visitor_EqualsVisitor.txt | 619 ++ ..._javaparser_ast_visitor_GenericVisitor.txt | 0 ...rser_ast_visitor_GenericVisitorAdapter.txt | 451 + ...ser_ast_visitor_ModifierVisitorAdapter.txt | 685 ++ ...hub_javaparser_ast_visitor_TreeVisitor.txt | 3 + ...hub_javaparser_ast_visitor_VoidVisitor.txt | 0 ...aparser_ast_visitor_VoidVisitorAdapter.txt | 511 + ...com_github_javaparser_utils_ClassUtils.txt | 16 + .../com_github_javaparser_utils_Pair.txt | 0 ..._github_javaparser_utils_PositionUtils.txt | 43 + .../com_github_javaparser_utils_Utils.txt | 14 + .../github/javaparser/CommentsInserter.java | 198 + .../com/github/javaparser/JavaParser.java | 318 + .../javaparser/PackageLocalClasses.java | 4 + .../javaparser/ParseProblemException.java | 40 + .../com/github/javaparser/ParseResult.java | 88 + .../com/github/javaparser/ParseStart.java | 32 + .../javaparser/ParserConfiguration.java | 6 + .../com/github/javaparser/Position.java | 142 + .../com/github/javaparser/Problem.java | 39 + .../com/github/javaparser/Providers.java | 61 + .../com/github/javaparser/Range.java | 89 + .../javaparser/ast/AccessSpecifier.java | 47 + .../javaparser/ast/ArrayBracketPair.java | 44 + .../javaparser/ast/ArrayCreationLevel.java | 56 + .../javaparser/ast/CompilationUnit.java | 413 + .../com/github/javaparser/ast/Example.java | 31 + .../javaparser/ast/ImportDeclaration.java | 188 + .../com/github/javaparser/ast/Modifier.java | 46 + .../com/github/javaparser/ast/Node.java | 396 + .../javaparser/ast/PackageDeclaration.java | 130 + .../github/javaparser/ast/UserDataKey.java | 39 + .../ast/body/AnnotationDeclaration.java | 65 + .../ast/body/AnnotationMemberDeclaration.java | 150 + .../javaparser/ast/body/BodyDeclaration.java | 69 + .../ast/body/ClassOrInterfaceDeclaration.java | 165 + .../ast/body/ConstructorDeclaration.java | 256 + .../ast/body/EmptyMemberDeclaration.java | 61 + .../ast/body/EmptyTypeDeclaration.java | 53 + .../ast/body/EnumConstantDeclaration.java | 133 + .../javaparser/ast/body/EnumDeclaration.java | 115 + .../javaparser/ast/body/FieldDeclaration.java | 277 + .../ast/body/InitializerDeclaration.java | 92 + .../ast/body/MethodDeclaration.java | 399 + .../github/javaparser/ast/body/Parameter.java | 227 + .../javaparser/ast/body/TypeDeclaration.java | 160 + .../ast/body/VariableDeclarator.java | 147 + .../ast/body/VariableDeclaratorId.java | 88 + .../javaparser/ast/comments/BlockComment.java | 59 + .../javaparser/ast/comments/Comment.java | 110 + .../ast/comments/CommentsCollection.java | 103 + .../ast/comments/JavadocComment.java | 53 + .../javaparser/ast/comments/LineComment.java | 64 + .../javaparser/ast/expr/AnnotationExpr.java | 48 + .../javaparser/ast/expr/ArrayAccessExpr.java | 80 + .../ast/expr/ArrayCreationExpr.java | 115 + .../ast/expr/ArrayInitializerExpr.java | 71 + .../javaparser/ast/expr/AssignExpr.java | 108 + .../javaparser/ast/expr/BinaryExpr.java | 115 + .../ast/expr/BooleanLiteralExpr.java | 65 + .../github/javaparser/ast/expr/CastExpr.java | 84 + .../javaparser/ast/expr/CharLiteralExpr.java | 61 + .../github/javaparser/ast/expr/ClassExpr.java | 75 + .../javaparser/ast/expr/ConditionalExpr.java | 94 + .../ast/expr/DoubleLiteralExpr.java | 51 + .../javaparser/ast/expr/EnclosedExpr.java | 64 + .../javaparser/ast/expr/Expression.java | 39 + .../javaparser/ast/expr/FieldAccessExpr.java | 107 + .../javaparser/ast/expr/InstanceOfExpr.java | 82 + .../ast/expr/IntegerLiteralExpr.java | 61 + .../ast/expr/IntegerLiteralMinValueExpr.java | 49 + .../javaparser/ast/expr/LambdaExpr.java | 99 + .../javaparser/ast/expr/LiteralExpr.java | 37 + .../javaparser/ast/expr/LongLiteralExpr.java | 62 + .../ast/expr/LongLiteralMinValueExpr.java | 49 + .../ast/expr/MarkerAnnotationExpr.java | 53 + .../javaparser/ast/expr/MemberValuePair.java | 81 + .../javaparser/ast/expr/MethodCallExpr.java | 145 + .../ast/expr/MethodReferenceExpr.java | 105 + .../github/javaparser/ast/expr/NameExpr.java | 85 + .../ast/expr/NormalAnnotationExpr.java | 99 + .../javaparser/ast/expr/NullLiteralExpr.java | 47 + .../ast/expr/ObjectCreationExpr.java | 165 + .../ast/expr/QualifiedNameExpr.java | 65 + .../ast/expr/SingleMemberAnnotationExpr.java | 66 + .../ast/expr/StringLiteralExpr.java | 76 + .../github/javaparser/ast/expr/SuperExpr.java | 64 + .../github/javaparser/ast/expr/ThisExpr.java | 64 + .../github/javaparser/ast/expr/TypeExpr.java | 70 + .../github/javaparser/ast/expr/UnaryExpr.java | 88 + .../ast/expr/VariableDeclarationExpr.java | 200 + .../ast/nodeTypes/NodeWithAnnotations.java | 167 + .../ast/nodeTypes/NodeWithBlockStmt.java | 18 + .../ast/nodeTypes/NodeWithBody.java | 18 + .../ast/nodeTypes/NodeWithDeclaration.java | 57 + .../ast/nodeTypes/NodeWithElementType.java | 73 + .../ast/nodeTypes/NodeWithExtends.java | 37 + .../ast/nodeTypes/NodeWithImplements.java | 37 + .../ast/nodeTypes/NodeWithJavaDoc.java | 48 + .../ast/nodeTypes/NodeWithMembers.java | 284 + .../ast/nodeTypes/NodeWithModifiers.java | 73 + .../ast/nodeTypes/NodeWithName.java | 35 + .../ast/nodeTypes/NodeWithParameters.java | 100 + .../ast/nodeTypes/NodeWithStatements.java | 46 + .../ast/nodeTypes/NodeWithThrowable.java | 57 + .../ast/nodeTypes/NodeWithType.java | 69 + .../ast/nodeTypes/NodeWithTypeArguments.java | 81 + .../ast/nodeTypes/NodeWithVariables.java | 36 + .../javaparser/ast/stmt/AssertStmt.java | 85 + .../github/javaparser/ast/stmt/BlockStmt.java | 77 + .../github/javaparser/ast/stmt/BreakStmt.java | 63 + .../javaparser/ast/stmt/CatchClause.java | 120 + .../javaparser/ast/stmt/ContinueStmt.java | 63 + .../github/javaparser/ast/stmt/DoStmt.java | 82 + .../github/javaparser/ast/stmt/EmptyStmt.java | 47 + .../ExplicitConstructorInvocationStmt.java | 119 + .../javaparser/ast/stmt/ExpressionStmt.java | 66 + .../github/javaparser/ast/stmt/ForStmt.java | 121 + .../javaparser/ast/stmt/ForeachStmt.java | 116 + .../github/javaparser/ast/stmt/IfStmt.java | 94 + .../javaparser/ast/stmt/LabeledStmt.java | 77 + .../javaparser/ast/stmt/ReturnStmt.java | 76 + .../github/javaparser/ast/stmt/Statement.java | 39 + .../javaparser/ast/stmt/SwitchEntryStmt.java | 90 + .../javaparser/ast/stmt/SwitchStmt.java | 88 + .../javaparser/ast/stmt/SynchronizedStmt.java | 105 + .../github/javaparser/ast/stmt/ThrowStmt.java | 65 + .../github/javaparser/ast/stmt/TryStmt.java | 116 + .../ast/stmt/TypeDeclarationStmt.java | 65 + .../github/javaparser/ast/stmt/WhileStmt.java | 82 + .../github/javaparser/ast/type/ArrayType.java | 86 + .../ast/type/ClassOrInterfaceType.java | 119 + .../javaparser/ast/type/IntersectionType.java | 60 + .../javaparser/ast/type/PrimitiveType.java | 117 + .../javaparser/ast/type/ReferenceType.java | 37 + .../com/github/javaparser/ast/type/Type.java | 67 + .../javaparser/ast/type/TypeParameter.java | 138 + .../github/javaparser/ast/type/UnionType.java | 52 + .../javaparser/ast/type/UnknownType.java | 62 + .../github/javaparser/ast/type/VoidType.java | 51 + .../javaparser/ast/type/WildcardType.java | 85 + .../javaparser/ast/visitor/CloneVisitor.java | 1296 +++ .../javaparser/ast/visitor/DumpVisitor.java | 1644 +++ .../javaparser/ast/visitor/EqualsVisitor.java | 1514 +++ .../ast/visitor/GenericVisitor.java | 257 + .../ast/visitor/GenericVisitorAdapter.java | 1677 +++ .../ast/visitor/ModifierVisitorAdapter.java | 1149 ++ .../javaparser/ast/visitor/TreeVisitor.java | 44 + .../javaparser/ast/visitor/VoidVisitor.java | 257 + .../ast/visitor/VoidVisitorAdapter.java | 806 ++ .../github/javaparser/utils/ClassUtils.java | 69 + .../com/github/javaparser/utils/Pair.java | 16 + .../javaparser/utils/PositionUtils.java | 135 + .../com/github/javaparser/utils/Utils.java | 107 + .../com/github/javaparser/ASTParser.java | 9318 +++++++++++++++++ .../github/javaparser/ASTParserConstants.java | 438 + .../javaparser/ASTParserTokenManager.java | 2643 +++++ .../com/github/javaparser/JavaCharStream.java | 560 + .../com/github/javaparser/ParseException.java | 227 + .../com/github/javaparser/Provider.java | 39 + .../com/github/javaparser/StreamProvider.java | 70 + .../com/github/javaparser/StringProvider.java | 60 + .../com/github/javaparser/Token.java | 143 + .../com/github/javaparser/TokenMgrError.java | 159 + .../github/javaparser/TokenMgrException.java | 158 + .../com_github_javaparser_ASTHelper.txt | 79 + .../com_github_javaparser_JavaParser.txt | 155 + .../com_github_javaparser_Position.txt | 11 + .../com_github_javaparser_PositionUtils.txt | 68 + .../com_github_javaparser_SourcesHelper.txt | 23 + ..._github_javaparser_ast_AccessSpecifier.txt | 2 + ..._github_javaparser_ast_CompilationUnit.txt | 28 + ...github_javaparser_ast_DocumentableNode.txt | 0 ...ithub_javaparser_ast_ImportDeclaration.txt | 24 + .../com_github_javaparser_ast_NamedNode.txt | 0 .../com_github_javaparser_ast_Node.txt | 95 + ...thub_javaparser_ast_PackageDeclaration.txt | 22 + .../com_github_javaparser_ast_TreeVisitor.txt | 7 + ...om_github_javaparser_ast_TypeParameter.txt | 32 + ...thub_javaparser_ast_body_AnnotableNode.txt | 0 ...aparser_ast_body_AnnotationDeclaration.txt | 28 + ...r_ast_body_AnnotationMemberDeclaration.txt | 41 + ...thub_javaparser_ast_body_BaseParameter.txt | 26 + ...ub_javaparser_ast_body_BodyDeclaration.txt | 17 + ...r_ast_body_ClassOrInterfaceDeclaration.txt | 48 + ...parser_ast_body_ConstructorDeclaration.txt | 89 + ...parser_ast_body_EmptyMemberDeclaration.txt | 18 + ...vaparser_ast_body_EmptyTypeDeclaration.txt | 25 + ...arser_ast_body_EnumConstantDeclaration.txt | 34 + ...ub_javaparser_ast_body_EnumDeclaration.txt | 38 + ...b_javaparser_ast_body_FieldDeclaration.txt | 41 + ...parser_ast_body_InitializerDeclaration.txt | 27 + ..._javaparser_ast_body_MethodDeclaration.txt | 120 + ...github_javaparser_ast_body_ModifierSet.txt | 36 + ...javaparser_ast_body_MultiTypeParameter.txt | 22 + ...m_github_javaparser_ast_body_Parameter.txt | 27 + ...ub_javaparser_ast_body_TypeDeclaration.txt | 31 + ...javaparser_ast_body_VariableDeclarator.txt | 22 + ...vaparser_ast_body_VariableDeclaratorId.txt | 19 + ...ub_javaparser_ast_body_WithDeclaration.txt | 0 ...b_javaparser_ast_comments_BlockComment.txt | 14 + ...github_javaparser_ast_comments_Comment.txt | 26 + ...parser_ast_comments_CommentsCollection.txt | 39 + ...javaparser_ast_comments_CommentsParser.txt | 104 + ...javaparser_ast_comments_JavadocComment.txt | 14 + ...ub_javaparser_ast_comments_LineComment.txt | 15 + ...hub_javaparser_ast_expr_AnnotationExpr.txt | 13 + ...ub_javaparser_ast_expr_ArrayAccessExpr.txt | 22 + ..._javaparser_ast_expr_ArrayCreationExpr.txt | 45 + ...vaparser_ast_expr_ArrayInitializerExpr.txt | 17 + ..._github_javaparser_ast_expr_AssignExpr.txt | 26 + ..._github_javaparser_ast_expr_BinaryExpr.txt | 26 + ...javaparser_ast_expr_BooleanLiteralExpr.txt | 17 + ...om_github_javaparser_ast_expr_CastExpr.txt | 22 + ...ub_javaparser_ast_expr_CharLiteralExpr.txt | 16 + ...m_github_javaparser_ast_expr_ClassExpr.txt | 17 + ...ub_javaparser_ast_expr_ConditionalExpr.txt | 27 + ..._javaparser_ast_expr_DoubleLiteralExpr.txt | 16 + ...ithub_javaparser_ast_expr_EnclosedExpr.txt | 17 + ..._github_javaparser_ast_expr_Expression.txt | 9 + ...ub_javaparser_ast_expr_FieldAccessExpr.txt | 27 + ...hub_javaparser_ast_expr_InstanceOfExpr.txt | 22 + ...javaparser_ast_expr_IntegerLiteralExpr.txt | 21 + ...er_ast_expr_IntegerLiteralMinValueExpr.txt | 17 + ..._github_javaparser_ast_expr_LambdaExpr.txt | 23 + ...github_javaparser_ast_expr_LiteralExpr.txt | 10 + ...ub_javaparser_ast_expr_LongLiteralExpr.txt | 22 + ...arser_ast_expr_LongLiteralMinValueExpr.txt | 17 + ...vaparser_ast_expr_MarkerAnnotationExpr.txt | 15 + ...ub_javaparser_ast_expr_MemberValuePair.txt | 21 + ...hub_javaparser_ast_expr_MethodCallExpr.txt | 34 + ...avaparser_ast_expr_MethodReferenceExpr.txt | 23 + ...om_github_javaparser_ast_expr_NameExpr.txt | 17 + ...vaparser_ast_expr_NormalAnnotationExpr.txt | 20 + ...ub_javaparser_ast_expr_NullLiteralExpr.txt | 13 + ...javaparser_ast_expr_ObjectCreationExpr.txt | 35 + ..._javaparser_ast_expr_QualifiedNameExpr.txt | 21 + ...er_ast_expr_SingleMemberAnnotationExpr.txt | 20 + ..._javaparser_ast_expr_StringLiteralExpr.txt | 17 + ...m_github_javaparser_ast_expr_SuperExpr.txt | 17 + ...om_github_javaparser_ast_expr_ThisExpr.txt | 17 + ...om_github_javaparser_ast_expr_TypeExpr.txt | 16 + ...m_github_javaparser_ast_expr_UnaryExpr.txt | 21 + ...arser_ast_expr_VariableDeclarationExpr.txt | 32 + ...m_github_javaparser_ast_internal_Utils.txt | 5 + ..._github_javaparser_ast_stmt_AssertStmt.txt | 23 + ...m_github_javaparser_ast_stmt_BlockStmt.txt | 17 + ...m_github_javaparser_ast_stmt_BreakStmt.txt | 16 + ...github_javaparser_ast_stmt_CatchClause.txt | 23 + ...ithub_javaparser_ast_stmt_ContinueStmt.txt | 16 + .../com_github_javaparser_ast_stmt_DoStmt.txt | 22 + ...m_github_javaparser_ast_stmt_EmptyStmt.txt | 12 + ...stmt_ExplicitConstructorInvocationStmt.txt | 30 + ...hub_javaparser_ast_stmt_ExpressionStmt.txt | 17 + ...com_github_javaparser_ast_stmt_ForStmt.txt | 32 + ...github_javaparser_ast_stmt_ForeachStmt.txt | 27 + .../com_github_javaparser_ast_stmt_IfStmt.txt | 27 + ...github_javaparser_ast_stmt_LabeledStmt.txt | 21 + ..._github_javaparser_ast_stmt_ReturnStmt.txt | 17 + ...m_github_javaparser_ast_stmt_Statement.txt | 9 + ...ub_javaparser_ast_stmt_SwitchEntryStmt.txt | 22 + ..._github_javaparser_ast_stmt_SwitchStmt.txt | 22 + ...b_javaparser_ast_stmt_SynchronizedStmt.txt | 22 + ...m_github_javaparser_ast_stmt_ThrowStmt.txt | 17 + ...com_github_javaparser_ast_stmt_TryStmt.txt | 31 + ...avaparser_ast_stmt_TypeDeclarationStmt.txt | 17 + ...m_github_javaparser_ast_stmt_WhileStmt.txt | 22 + ...vaparser_ast_type_ClassOrInterfaceType.txt | 30 + ...thub_javaparser_ast_type_PrimitiveType.txt | 23 + ...thub_javaparser_ast_type_ReferenceType.txt | 32 + .../com_github_javaparser_ast_type_Type.txt | 17 + ...github_javaparser_ast_type_UnknownType.txt | 8 + ...om_github_javaparser_ast_type_VoidType.txt | 12 + ...ithub_javaparser_ast_type_WildcardType.txt | 23 + ...ub_javaparser_ast_visitor_CloneVisitor.txt | 819 ++ ...hub_javaparser_ast_visitor_DumpVisitor.txt | 1076 ++ ...b_javaparser_ast_visitor_EqualsVisitor.txt | 720 ++ ..._javaparser_ast_visitor_GenericVisitor.txt | 0 ...rser_ast_visitor_GenericVisitorAdapter.txt | 836 ++ ...ser_ast_visitor_ModifierVisitorAdapter.txt | 662 ++ ...hub_javaparser_ast_visitor_VoidVisitor.txt | 0 ...aparser_ast_visitor_VoidVisitorAdapter.txt | 425 + .../com/github/javaparser/ASTParser.java | 9148 ++++++++++++++++ .../github/javaparser/ASTParserConstants.java | 414 + .../javaparser/ASTParserTokenManager.java | 2559 +++++ .../com/github/javaparser/JavaCharStream.java | 629 ++ .../com/github/javaparser/ParseException.java | 199 + .../com/github/javaparser/Token.java | 143 + .../com/github/javaparser/TokenMgrError.java | 159 + .../com/github/javaparser/ASTHelper.java | 297 + .../com/github/javaparser/JavaParser.java | 452 + .../com/github/javaparser/Position.java | 53 + .../com/github/javaparser/PositionUtils.java | 143 + .../com/github/javaparser/SourcesHelper.java | 63 + .../javaparser/ast/AccessSpecifier.java | 47 + .../javaparser/ast/CompilationUnit.java | 180 + .../javaparser/ast/DocumentableNode.java | 33 + .../javaparser/ast/ImportDeclaration.java | 135 + .../com/github/javaparser/ast/NamedNode.java | 33 + .../com/github/javaparser/ast/Node.java | 376 + .../javaparser/ast/PackageDeclaration.java | 117 + .../github/javaparser/ast/TreeVisitor.java | 35 + .../github/javaparser/ast/TypeParameter.java | 129 + .../javaparser/ast/body/AnnotableNode.java | 36 + .../ast/body/AnnotationDeclaration.java | 73 + .../ast/body/AnnotationMemberDeclaration.java | 135 + .../javaparser/ast/body/BaseParameter.java | 92 + .../javaparser/ast/body/BodyDeclaration.java | 60 + .../ast/body/ClassOrInterfaceDeclaration.java | 133 + .../ast/body/ConstructorDeclaration.java | 237 + .../ast/body/EmptyMemberDeclaration.java | 63 + .../ast/body/EmptyTypeDeclaration.java | 61 + .../ast/body/EnumConstantDeclaration.java | 113 + .../javaparser/ast/body/EnumDeclaration.java | 101 + .../javaparser/ast/body/FieldDeclaration.java | 129 + .../ast/body/InitializerDeclaration.java | 92 + .../ast/body/MethodDeclaration.java | 305 + .../javaparser/ast/body/ModifierSet.java | 146 + .../ast/body/MultiTypeParameter.java | 63 + .../github/javaparser/ast/body/Parameter.java | 84 + .../javaparser/ast/body/TypeDeclaration.java | 106 + .../ast/body/VariableDeclarator.java | 83 + .../ast/body/VariableDeclaratorId.java | 77 + .../javaparser/ast/body/WithDeclaration.java | 57 + .../javaparser/ast/comments/BlockComment.java | 58 + .../javaparser/ast/comments/Comment.java | 112 + .../ast/comments/CommentsCollection.java | 104 + .../ast/comments/CommentsParser.java | 171 + .../ast/comments/JavadocComment.java | 52 + .../javaparser/ast/comments/LineComment.java | 62 + .../javaparser/ast/expr/AnnotationExpr.java | 46 + .../javaparser/ast/expr/ArrayAccessExpr.java | 77 + .../ast/expr/ArrayCreationExpr.java | 131 + .../ast/expr/ArrayInitializerExpr.java | 66 + .../javaparser/ast/expr/AssignExpr.java | 104 + .../javaparser/ast/expr/BinaryExpr.java | 111 + .../ast/expr/BooleanLiteralExpr.java | 63 + .../github/javaparser/ast/expr/CastExpr.java | 78 + .../javaparser/ast/expr/CharLiteralExpr.java | 52 + .../github/javaparser/ast/expr/ClassExpr.java | 65 + .../javaparser/ast/expr/ConditionalExpr.java | 90 + .../ast/expr/DoubleLiteralExpr.java | 51 + .../javaparser/ast/expr/EnclosedExpr.java | 63 + .../javaparser/ast/expr/Expression.java | 38 + .../javaparser/ast/expr/FieldAccessExpr.java | 98 + .../javaparser/ast/expr/InstanceOfExpr.java | 77 + .../ast/expr/IntegerLiteralExpr.java | 61 + .../ast/expr/IntegerLiteralMinValueExpr.java | 48 + .../javaparser/ast/expr/LambdaExpr.java | 94 + .../javaparser/ast/expr/LiteralExpr.java | 35 + .../javaparser/ast/expr/LongLiteralExpr.java | 62 + .../ast/expr/LongLiteralMinValueExpr.java | 48 + .../ast/expr/MarkerAnnotationExpr.java | 53 + .../javaparser/ast/expr/MemberValuePair.java | 77 + .../javaparser/ast/expr/MethodCallExpr.java | 116 + .../ast/expr/MethodReferenceExpr.java | 98 + .../github/javaparser/ast/expr/NameExpr.java | 64 + .../ast/expr/NormalAnnotationExpr.java | 67 + .../javaparser/ast/expr/NullLiteralExpr.java | 46 + .../ast/expr/ObjectCreationExpr.java | 119 + .../ast/expr/QualifiedNameExpr.java | 64 + .../ast/expr/SingleMemberAnnotationExpr.java | 65 + .../ast/expr/StringLiteralExpr.java | 62 + .../github/javaparser/ast/expr/SuperExpr.java | 63 + .../github/javaparser/ast/expr/ThisExpr.java | 63 + .../github/javaparser/ast/expr/TypeExpr.java | 65 + .../github/javaparser/ast/expr/UnaryExpr.java | 86 + .../ast/expr/VariableDeclarationExpr.java | 117 + .../github/javaparser/ast/internal/Utils.java | 41 + .../javaparser/ast/stmt/AssertStmt.java | 83 + .../github/javaparser/ast/stmt/BlockStmt.java | 67 + .../github/javaparser/ast/stmt/BreakStmt.java | 61 + .../javaparser/ast/stmt/CatchClause.java | 88 + .../javaparser/ast/stmt/ContinueStmt.java | 62 + .../github/javaparser/ast/stmt/DoStmt.java | 77 + .../github/javaparser/ast/stmt/EmptyStmt.java | 46 + .../ExplicitConstructorInvocationStmt.java | 109 + .../javaparser/ast/stmt/ExpressionStmt.java | 64 + .../github/javaparser/ast/stmt/ForStmt.java | 110 + .../javaparser/ast/stmt/ForeachStmt.java | 96 + .../github/javaparser/ast/stmt/IfStmt.java | 90 + .../javaparser/ast/stmt/LabeledStmt.java | 75 + .../javaparser/ast/stmt/ReturnStmt.java | 64 + .../github/javaparser/ast/stmt/Statement.java | 38 + .../javaparser/ast/stmt/SwitchEntryStmt.java | 82 + .../javaparser/ast/stmt/SwitchStmt.java | 83 + .../javaparser/ast/stmt/SynchronizedStmt.java | 80 + .../github/javaparser/ast/stmt/ThrowStmt.java | 64 + .../github/javaparser/ast/stmt/TryStmt.java | 108 + .../ast/stmt/TypeDeclarationStmt.java | 64 + .../github/javaparser/ast/stmt/WhileStmt.java | 77 + .../ast/type/ClassOrInterfaceType.java | 104 + .../javaparser/ast/type/PrimitiveType.java | 97 + .../javaparser/ast/type/ReferenceType.java | 125 + .../com/github/javaparser/ast/type/Type.java | 60 + .../javaparser/ast/type/UnknownType.java | 48 + .../github/javaparser/ast/type/VoidType.java | 47 + .../javaparser/ast/type/WildcardType.java | 81 + .../javaparser/ast/visitor/CloneVisitor.java | 1211 +++ .../javaparser/ast/visitor/DumpVisitor.java | 1657 +++ .../javaparser/ast/visitor/EqualsVisitor.java | 1468 +++ .../ast/visitor/GenericVisitor.java | 254 + .../ast/visitor/GenericVisitorAdapter.java | 1613 +++ .../ast/visitor/ModifierVisitorAdapter.java | 973 ++ .../javaparser/ast/visitor/VoidVisitor.java | 254 + .../ast/visitor/VoidVisitorAdapter.java | 846 ++ ...r_symbolsolver_SourceFileInfoExtractor.txt | 77 + ...r_symbolsolver_core_resolution_Context.txt | 16 + ...olsolver_core_resolution_ContextHelper.txt | 4 + ...ns_common_MethodDeclarationCommonLogic.txt | 34 + ...rser_symbolsolver_javaparser_Navigator.txt | 104 + ..._javaparsermodel_DefaultVisitorAdapter.txt | 180 + ...olver_javaparsermodel_JavaParserFacade.txt | 253 + ...lver_javaparsermodel_JavaParserFactory.txt | 26 + ...sermodel_LambdaArgumentTypePlaceholder.txt | 0 ...olsolver_javaparsermodel_TypeExtractor.txt | 279 + ...avaparsermodel_UnsolvedSymbolException.txt | 1 + ...del_contexts_AbstractJavaParserContext.txt | 30 + ...s_AbstractMethodLikeDeclarationContext.txt | 44 + ...texts_AnonymousClassDeclarationContext.txt | 96 + ...arsermodel_contexts_CatchClauseContext.txt | 14 + ...xts_ClassOrInterfaceDeclarationContext.txt | 28 + ...rmodel_contexts_CompilationUnitContext.txt | 130 + ...arsermodel_contexts_ConstructorContext.txt | 0 ...javaparsermodel_contexts_ContextHelper.txt | 13 + ...rmodel_contexts_EnumDeclarationContext.txt | 15 + ...arsermodel_contexts_FieldAccessContext.txt | 37 + ...rsermodel_contexts_ForStatementContext.txt | 15 + ...rmodel_contexts_ForechStatementContext.txt | 17 + ...texts_JavaParserTypeDeclarationAdapter.txt | 80 + ...parsermodel_contexts_LambdaExprContext.txt | 78 + ...ermodel_contexts_MethodCallExprContext.txt | 322 + ...javaparsermodel_contexts_MethodContext.txt | 0 ...aparsermodel_contexts_StatementContext.txt | 93 + ...arsermodel_contexts_SwitchEntryContext.txt | 23 + ...rmodel_contexts_TryWithResourceContext.txt | 25 + ...arations_DefaultConstructorDeclaration.txt | 2 + ...er_javaparsermodel_declarations_Helper.txt | 26 + ...ations_JavaParserAnnotationDeclaration.txt | 12 + ...ns_JavaParserAnonymousClassDeclaration.txt | 87 + ...eclarations_JavaParserClassDeclaration.txt | 139 + ...tions_JavaParserConstructorDeclaration.txt | 15 + ...ions_JavaParserEnumConstantDeclaration.txt | 3 + ...declarations_JavaParserEnumDeclaration.txt | 71 + ...eclarations_JavaParserFieldDeclaration.txt | 23 + ...rations_JavaParserInterfaceDeclaration.txt | 120 + ...clarations_JavaParserMethodDeclaration.txt | 30 + ...rations_JavaParserParameterDeclaration.txt | 7 + ...clarations_JavaParserSymbolDeclaration.txt | 46 + ...del_declarations_JavaParserTypeAdapter.txt | 48 + ...l_declarations_JavaParserTypeParameter.txt | 45 + ...ions_JavaParserTypeVariableDeclaration.txt | 13 + ...l_declarators_AbstractSymbolDeclarator.txt | 0 ...odel_declarators_FieldSymbolDeclarator.txt | 3 + ...ermodel_declarators_NoSymbolDeclarator.txt | 1 + ..._declarators_ParameterSymbolDeclarator.txt | 2 + ...l_declarators_VariableSymbolDeclarator.txt | 7 + ...vassistmodel_JavassistClassDeclaration.txt | 128 + ...tmodel_JavassistConstructorDeclaration.txt | 22 + ...avassistmodel_JavassistEnumDeclaration.txt | 81 + ...solver_javassistmodel_JavassistFactory.txt | 17 + ...vassistmodel_JavassistFieldDeclaration.txt | 9 + ...istmodel_JavassistInterfaceDeclaration.txt | 104 + ...assistmodel_JavassistMethodDeclaration.txt | 33 + ...istmodel_JavassistParameterDeclaration.txt | 1 + ...tmodel_JavassistTypeDeclarationAdapter.txt | 32 + ..._javassistmodel_JavassistTypeParameter.txt | 23 + ...olsolver_javassistmodel_JavassistUtils.txt | 77 + ...symbolsolver_model_typesystem_LazyType.txt | 39 + ...ver_model_typesystem_ReferenceTypeImpl.txt | 53 + ...olver_reflectionmodel_MyObjectProvider.txt | 3 + ...reflectionmodel_ReflectionClassAdapter.txt | 89 + ...ectionmodel_ReflectionClassDeclaration.txt | 121 + ...model_ReflectionConstructorDeclaration.txt | 17 + ...lectionmodel_ReflectionEnumDeclaration.txt | 44 + ...lver_reflectionmodel_ReflectionFactory.txt | 48 + ...ectionmodel_ReflectionFieldDeclaration.txt | 10 + ...onmodel_ReflectionInterfaceDeclaration.txt | 81 + ...ctionmodel_ReflectionMethodDeclaration.txt | 30 + ...nmodel_ReflectionMethodResolutionLogic.txt | 85 + ...onmodel_ReflectionParameterDeclaration.txt | 1 + ...eflectionmodel_ReflectionTypeParameter.txt | 25 + ...ctionmodel_comparators_ClassComparator.txt | 15 + ...tionmodel_comparators_MethodComparator.txt | 12 + ...nmodel_comparators_ParameterComparator.txt | 6 + ..._resolution_ConstructorResolutionLogic.txt | 110 + ...olver_resolution_MethodResolutionLogic.txt | 416 + ...mbolsolver_resolution_SymbolDeclarator.txt | 0 ...r_symbolsolver_resolution_SymbolSolver.txt | 40 + ...olution_typesolvers_CombinedTypeSolver.txt | 9 + ...r_resolution_typesolvers_JarTypeSolver.txt | 31 + ...ution_typesolvers_JavaParserTypeSolver.txt | 48 + ...esolution_typesolvers_MemoryTypeSolver.txt | 9 + ...ution_typesolvers_ReflectionTypeSolver.txt | 26 + ...lsolver_logic_AbstractClassDeclaration.txt | 18 + ...olsolver_logic_AbstractTypeDeclaration.txt | 13 + ...ogic_ConfilictingGenericTypesException.txt | 1 + ...lsolver_logic_FunctionalInterfaceLogic.txt | 42 + ...er_symbolsolver_logic_InferenceContext.txt | 169 + ...mbolsolver_logic_InferenceVariableType.txt | 53 + ...rser_symbolsolver_logic_ObjectProvider.txt | 0 ...lsolver_model_declarations_AccessLevel.txt | 0 ...del_declarations_AnnotationDeclaration.txt | 0 ...er_model_declarations_ClassDeclaration.txt | 0 ...el_declarations_ConstructorDeclaration.txt | 0 ...lsolver_model_declarations_Declaration.txt | 4 + ...ver_model_declarations_EnumDeclaration.txt | 0 ...er_model_declarations_FieldDeclaration.txt | 0 ...lver_model_declarations_HasAccessLevel.txt | 0 ...odel_declarations_InterfaceDeclaration.txt | 4 + ..._declarations_MethodAmbiguityException.txt | 0 ...r_model_declarations_MethodDeclaration.txt | 0 ...del_declarations_MethodLikeDeclaration.txt | 33 + ...odel_declarations_ParameterDeclaration.txt | 7 + ..._declarations_ReferenceTypeDeclaration.txt | 85 + ...ver_model_declarations_TypeDeclaration.txt | 22 + ..._declarations_TypeParameterDeclaration.txt | 7 + ..._model_declarations_TypeParametrizable.txt | 0 ...er_model_declarations_ValueDeclaration.txt | 0 ...symbolsolver_model_methods_MethodUsage.txt | 24 + ...olver_model_resolution_SymbolReference.txt | 9 + ...mbolsolver_model_resolution_TypeSolver.txt | 6 + ...del_resolution_UnsolvedSymbolException.txt | 0 ...er_symbolsolver_model_resolution_Value.txt | 2 + ...ymbolsolver_model_typesystem_ArrayType.txt | 18 + ..._model_typesystem_LambdaConstraintType.txt | 2 + ...symbolsolver_model_typesystem_NullType.txt | 0 ...lsolver_model_typesystem_PrimitiveType.txt | 33 + ...lsolver_model_typesystem_ReferenceType.txt | 240 + ...ser_symbolsolver_model_typesystem_Type.txt | 17 + ...olver_model_typesystem_TypeTransformer.txt | 0 ...olsolver_model_typesystem_TypeVariable.txt | 22 + ...symbolsolver_model_typesystem_VoidType.txt | 0 ...symbolsolver_model_typesystem_Wildcard.txt | 9 + ...metrization_TypeParameterValueProvider.txt | 23 + ...stem_parametrization_TypeParametersMap.txt | 24 + ...ystem_parametrization_TypeParametrized.txt | 0 .../symbolsolver/SourceFileInfoExtractor.java | 216 + .../symbolsolver/core/resolution/Context.java | 98 + .../core/resolution/ContextHelper.java | 51 + .../common/MethodDeclarationCommonLogic.java | 94 + .../symbolsolver/javaparser/Navigator.java | 295 + .../symbolsolver/javaparser/package-info.java | 20 + .../DefaultVisitorAdapter.java | 465 + .../javaparsermodel/JavaParserFacade.java | 531 + .../javaparsermodel/JavaParserFactory.java | 135 + .../LambdaArgumentTypePlaceholder.java | 72 + .../javaparsermodel/TypeExtractor.java | 523 + .../UnsolvedSymbolException.java | 67 + .../contexts/AbstractJavaParserContext.java | 138 + .../AbstractMethodLikeDeclarationContext.java | 101 + .../AnonymousClassDeclarationContext.java | 186 + .../contexts/CatchClauseContext.java | 54 + .../ClassOrInterfaceDeclarationContext.java | 108 + .../contexts/CompilationUnitContext.java | 285 + .../contexts/ConstructorContext.java | 35 + .../contexts/ContextHelper.java | 71 + .../contexts/EnumDeclarationContext.java | 80 + .../contexts/FieldAccessContext.java | 93 + .../contexts/ForStatementContext.java | 69 + .../contexts/ForechStatementContext.java | 60 + .../JavaParserTypeDeclarationAdapter.java | 133 + .../contexts/LambdaExprContext.java | 194 + .../contexts/MethodCallExprContext.java | 476 + .../contexts/MethodContext.java | 36 + .../contexts/StatementContext.java | 200 + .../contexts/SwitchEntryContext.java | 80 + .../contexts/TryWithResourceContext.java | 82 + .../DefaultConstructorDeclaration.java | 64 + .../javaparsermodel/declarations/Helper.java | 89 + .../JavaParserAnnotationDeclaration.java | 92 + .../JavaParserAnonymousClassDeclaration.java | 203 + .../JavaParserClassDeclaration.java | 381 + .../JavaParserConstructorDeclaration.java | 82 + .../JavaParserEnumConstantDeclaration.java | 59 + .../JavaParserEnumDeclaration.java | 340 + .../JavaParserFieldDeclaration.java | 123 + .../JavaParserInterfaceDeclaration.java | 319 + .../JavaParserMethodDeclaration.java | 149 + .../JavaParserParameterDeclaration.java | 88 + .../JavaParserSymbolDeclaration.java | 177 + .../declarations/JavaParserTypeAdapter.java | 120 + .../declarations/JavaParserTypeParameter.java | 224 + .../JavaParserTypeVariableDeclaration.java | 187 + .../declarators/AbstractSymbolDeclarator.java | 35 + .../declarators/FieldSymbolDeclarator.java | 46 + .../declarators/NoSymbolDeclarator.java | 40 + .../ParameterSymbolDeclarator.java | 42 + .../declarators/VariableSymbolDeclarator.java | 52 + .../javaparsermodel/package-info.java | 20 + .../JavassistClassDeclaration.java | 383 + .../JavassistConstructorDeclaration.java | 122 + .../JavassistEnumDeclaration.java | 231 + .../javassistmodel/JavassistFactory.java | 84 + .../JavassistFieldDeclaration.java | 84 + .../JavassistInterfaceDeclaration.java | 280 + .../JavassistMethodDeclaration.java | 165 + .../JavassistParameterDeclaration.java | 80 + .../JavassistTypeDeclarationAdapter.java | 93 + .../JavassistTypeParameter.java | 117 + .../javassistmodel/JavassistUtils.java | 177 + .../javassistmodel/package-info.java | 20 + .../model/typesystem/LazyType.java | 117 + .../model/typesystem/ReferenceTypeImpl.java | 148 + .../reflectionmodel/MyObjectProvider.java | 36 + .../ReflectionClassAdapter.java | 190 + .../ReflectionClassDeclaration.java | 343 + .../ReflectionConstructorDeclaration.java | 77 + .../ReflectionEnumDeclaration.java | 191 + .../reflectionmodel/ReflectionFactory.java | 118 + .../ReflectionFieldDeclaration.java | 97 + .../ReflectionInterfaceDeclaration.java | 305 + .../ReflectionMethodDeclaration.java | 135 + .../ReflectionMethodResolutionLogic.java | 144 + .../ReflectionParameterDeclaration.java | 75 + .../ReflectionTypeParameter.java | 130 + .../comparators/ClassComparator.java | 25 + .../comparators/MethodComparator.java | 25 + .../comparators/ParameterComparator.java | 19 + .../reflectionmodel/package-info.java | 20 + .../ConstructorResolutionLogic.java | 226 + .../resolution/MethodResolutionLogic.java | 679 ++ .../resolution/SymbolDeclarator.java | 30 + .../symbolsolver/resolution/SymbolSolver.java | 164 + .../typesolvers/CombinedTypeSolver.java | 76 + .../resolution/typesolvers/JarTypeSolver.java | 138 + .../typesolvers/JavaParserTypeSolver.java | 158 + .../typesolvers/MemoryTypeSolver.java | 86 + .../typesolvers/ReflectionTypeSolver.java | 94 + .../logic/AbstractClassDeclaration.java | 85 + .../logic/AbstractTypeDeclaration.java | 65 + .../ConfilictingGenericTypesException.java | 13 + .../logic/FunctionalInterfaceLogic.java | 85 + .../symbolsolver/logic/InferenceContext.java | 209 + .../logic/InferenceVariableType.java | 164 + .../symbolsolver/logic/ObjectProvider.java | 27 + .../model/declarations/AccessLevel.java | 27 + .../declarations/AnnotationDeclaration.java | 7 + .../model/declarations/ClassDeclaration.java | 79 + .../declarations/ConstructorDeclaration.java | 28 + .../model/declarations/Declaration.java | 93 + .../model/declarations/EnumDeclaration.java | 35 + .../model/declarations/FieldDeclaration.java | 46 + .../model/declarations/HasAccessLevel.java | 31 + .../declarations/InterfaceDeclaration.java | 52 + .../MethodAmbiguityException.java | 33 + .../model/declarations/MethodDeclaration.java | 49 + .../declarations/MethodLikeDeclaration.java | 122 + .../declarations/ParameterDeclaration.java | 52 + .../ReferenceTypeDeclaration.java | 225 + .../model/declarations/TypeDeclaration.java | 171 + .../TypeParameterDeclaration.java | 222 + .../declarations/TypeParametrizable.java | 40 + .../model/declarations/ValueDeclaration.java | 33 + .../model/methods/MethodUsage.java | 148 + .../model/resolution/SymbolReference.java | 80 + .../model/resolution/TypeSolver.java | 68 + .../resolution/UnsolvedSymbolException.java | 56 + .../symbolsolver/model/resolution/Value.java | 60 + .../model/typesystem/ArrayType.java | 108 + .../typesystem/LambdaConstraintType.java | 37 + .../model/typesystem/NullType.java | 66 + .../model/typesystem/PrimitiveType.java | 127 + .../model/typesystem/ReferenceType.java | 478 + .../symbolsolver/model/typesystem/Type.java | 168 + .../model/typesystem/TypeTransformer.java | 25 + .../model/typesystem/TypeVariable.java | 119 + .../model/typesystem/VoidType.java | 44 + .../model/typesystem/Wildcard.java | 163 + .../TypeParameterValueProvider.java | 51 + .../parametrization/TypeParametersMap.java | 138 + .../parametrization/TypeParametrized.java | 26 + mvnw | 308 + mvnw.cmd | 205 + pom.xml | 520 + readme.md | 141 + ruleset.xml | 144 + run_core_generators.sh | 19 + run_core_metamodel_generator.sh | 24 + run_release_perform.sh | 50 + run_release_prepare.sh | 54 + run_release_prepare_non-interactive.sh | 97 + scripts/.gitignore | 1 + scripts/release-notes-config-id.yml | 38 + scripts/release-notes-config-title.yml | 38 + .../run_generate_changelog_by_milestone_id.sh | 70 + ...n_generate_changelog_by_milestone_title.sh | 70 + 2499 files changed, 353902 insertions(+), 37 deletions(-) create mode 100644 .mvn/wrapper/MavenWrapperDownloader.java create mode 100644 .mvn/wrapper/maven-wrapper.properties create mode 100644 CONTRIBUTING.md create mode 100644 FEATURES.md create mode 100644 LICENSE create mode 100644 LICENSE.APACHE create mode 100644 LICENSE.GPL create mode 100644 LICENSE.LGPL create mode 100644 PULL_REQUEST_TEMPLATE.md delete mode 100644 README.md create mode 100644 appveyor.yml create mode 100644 changelog.md create mode 100644 codecov.yml create mode 100644 debian/README.source delete mode 100644 debian/compat create mode 100644 debian/libjavaparser-java.poms create mode 100644 debian/maven.ignoreRules create mode 100644 debian/maven.rules create mode 100644 debian/patches/javacc_coordinates.patch create mode 100644 debian/patches/series create mode 100644 debian/upstream/metadata create mode 100644 debian/watch create mode 100644 dev-files/JavaParser-CheckStyle.xml create mode 100644 dev-files/JavaParser-eclipse.xml create mode 100644 dev-files/JavaParser-idea.xml create mode 100644 dev-files/settings.xml create mode 100644 doc/component_diagram.puml create mode 100644 doc/readme.md create mode 100644 javaparser-core-generators/pom.xml create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/CompilationUnitGenerator.java create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/Generator.java create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/NodeGenerator.java create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/VisitorGenerator.java create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/CoreGenerator.java create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/AcceptGenerator.java create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/CloneGenerator.java create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/GetMetaModelGenerator.java create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/MainConstructorGenerator.java create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/NodeModifierGenerator.java create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/PropertyGenerator.java create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/RemoveMethodGenerator.java create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/ReplaceMethodGenerator.java create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/TypeCastingGenerator.java create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/other/BndGenerator.java create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/other/GrammarLetterGenerator.java create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/other/TokenKindGenerator.java create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/quality/NotNullGenerator.java create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/utils/CodeUtils.java create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/CloneVisitorGenerator.java create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/EqualsVisitorGenerator.java create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/GenericListVisitorAdapterGenerator.java create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/GenericVisitorAdapterGenerator.java create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/GenericVisitorGenerator.java create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/GenericVisitorWithDefaultsGenerator.java create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/HashCodeVisitorGenerator.java create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/ModifierVisitorGenerator.java create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/NoCommentEqualsVisitorGenerator.java create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/NoCommentHashCodeVisitorGenerator.java create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/ObjectIdentityEqualsVisitorGenerator.java create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/ObjectIdentityHashCodeVisitorGenerator.java create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/VoidVisitorAdapterGenerator.java create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/VoidVisitorGenerator.java create mode 100644 javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/VoidVisitorWithDefaultsGenerator.java create mode 100644 javaparser-core-generators/src/test/java/com/github/javaparser/generator/core/quality/NotNullGeneratorTest.java create mode 100644 javaparser-core-generators/src/test/java/com/github/javaparser/generator/core/utils/CodeUtilsTest.java create mode 100644 javaparser-core-generators/src/test/resources/com/github/javaparser/generator/core/quality/NotNullGeneratorTest/expected/ConstructorParameterTest.java create mode 100644 javaparser-core-generators/src/test/resources/com/github/javaparser/generator/core/quality/NotNullGeneratorTest/expected/ConstructorParameterWithSuperTest.java create mode 100644 javaparser-core-generators/src/test/resources/com/github/javaparser/generator/core/quality/NotNullGeneratorTest/expected/MethodParameterRerunTest.java create mode 100644 javaparser-core-generators/src/test/resources/com/github/javaparser/generator/core/quality/NotNullGeneratorTest/expected/MethodParameterTest.java create mode 100644 javaparser-core-generators/src/test/resources/com/github/javaparser/generator/core/quality/NotNullGeneratorTest/original/ConstructorParameterTest.java create mode 100644 javaparser-core-generators/src/test/resources/com/github/javaparser/generator/core/quality/NotNullGeneratorTest/original/ConstructorParameterWithSuperTest.java create mode 100644 javaparser-core-generators/src/test/resources/com/github/javaparser/generator/core/quality/NotNullGeneratorTest/original/MethodParameterRerunTest.java create mode 100644 javaparser-core-generators/src/test/resources/com/github/javaparser/generator/core/quality/NotNullGeneratorTest/original/MethodParameterTest.java create mode 100644 javaparser-core-metamodel-generator/pom.xml create mode 100644 javaparser-core-metamodel-generator/src/main/java/com/github/javaparser/generator/AbstractGenerator.java create mode 100644 javaparser-core-metamodel-generator/src/main/java/com/github/javaparser/generator/metamodel/AstTypeAnalysis.java create mode 100644 javaparser-core-metamodel-generator/src/main/java/com/github/javaparser/generator/metamodel/InitializeConstructorParametersStatementsGenerator.java create mode 100644 javaparser-core-metamodel-generator/src/main/java/com/github/javaparser/generator/metamodel/InitializePropertyMetaModelsStatementsGenerator.java create mode 100644 javaparser-core-metamodel-generator/src/main/java/com/github/javaparser/generator/metamodel/MetaModelGenerator.java create mode 100644 javaparser-core-metamodel-generator/src/main/java/com/github/javaparser/generator/metamodel/NodeMetaModelGenerator.java create mode 100644 javaparser-core-serialization/pom.xml create mode 100644 javaparser-core-serialization/src/main/java/com/github/javaparser/serialization/JavaParserJsonDeserializer.java create mode 100644 javaparser-core-serialization/src/main/java/com/github/javaparser/serialization/JavaParserJsonSerializer.java create mode 100644 javaparser-core-serialization/src/test/java/com/github/javaparser/serialization/JavaParserJsonDeserializerTest.java create mode 100644 javaparser-core-serialization/src/test/java/com/github/javaparser/serialization/JavaParserJsonSerializerTest.java create mode 100644 javaparser-core-testing-bdd/pom.xml create mode 100644 javaparser-core-testing-bdd/src/test/java/com/github/javaparser/BasicJBehaveTest.java create mode 100644 javaparser-core-testing-bdd/src/test/java/com/github/javaparser/CommentParsingTest.java create mode 100644 javaparser-core-testing-bdd/src/test/java/com/github/javaparser/ComparingTest.java create mode 100644 javaparser-core-testing-bdd/src/test/java/com/github/javaparser/ManipulationTest.java create mode 100644 javaparser-core-testing-bdd/src/test/java/com/github/javaparser/ParsingTest.java create mode 100644 javaparser-core-testing-bdd/src/test/java/com/github/javaparser/PositionRangeTest.java create mode 100644 javaparser-core-testing-bdd/src/test/java/com/github/javaparser/PrettyPrintingTest.java create mode 100644 javaparser-core-testing-bdd/src/test/java/com/github/javaparser/TestUtils.java create mode 100644 javaparser-core-testing-bdd/src/test/java/com/github/javaparser/VisitorTest.java create mode 100644 javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/CommentParsingSteps.java create mode 100644 javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/ComparingSteps.java create mode 100644 javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/ExistenceOfParentNodeVerifier.java create mode 100644 javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/ManipulationSteps.java create mode 100644 javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/ParsingSteps.java create mode 100644 javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/PositionRangeSteps.java create mode 100644 javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/PrettyPrintingSteps.java create mode 100644 javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/SharedSteps.java create mode 100644 javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/VisitorSteps.java create mode 100644 javaparser-core-testing-bdd/src/test/java/com/github/javaparser/visitors/PositionTestVisitor.java create mode 100644 javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/comment_attribution_scenarios.story create mode 100644 javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/comment_parsing_scenarios.story create mode 100644 javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/comparing_scenarios.story create mode 100644 javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/manipulation_scenarios.story create mode 100644 javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/parsing_scenarios.story create mode 100644 javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/position_range_scenarios.story create mode 100644 javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/pretty_printing_java_concepts.story create mode 100644 javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/pretty_printing_scenarios.story create mode 100644 javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/samples/ClassInLatin1.java create mode 100644 javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/samples/JavaConcepts.java create mode 100644 javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/samples/package-info.java create mode 100644 javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/visitor_scenarios.story create mode 100644 javaparser-core-testing/pom.xml create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/CommentsInserterTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ExpectedTokensTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/GeneratedJavaParserTokenManagerTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/Issue1017Test.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/Issue2482Test.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/Issue3064Test.java create mode 100755 javaparser-core-testing/src/test/java/com/github/javaparser/Issue3577Test.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/JavaParserAdapterTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/JavaParserTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/JavaTokenTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/JavadocParserTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/LineSeparatorProcessorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ParseErrorRecoveryTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ParserConfigurationTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/PositionMappingTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/PositionTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ProblemTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ProvidersTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/RangeTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/TokenRangeTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/TokenTypesTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/UnicodeEscapeProcessingProviderTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/AncestorDescendantTests.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/CompilationUnitTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/DataKeyTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/FindNodeTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/ListObservationTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/NodeListTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/NodePositionTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/NodeTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/ObservationTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/ParseResultTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/ReplaceNodeTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/WalkFindTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/AnnotationDeclarationTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/AnnotationMemberDeclarationTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/ClassOrInterfaceDeclarationTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/ConstructorDeclarationTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/FieldDeclarationTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/MethodDeclarationTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/RecordDeclarationTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/TypeDeclarationTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/comments/CommentTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/ArrayCreationExprTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/AssignExprTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/BinaryExprTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/CharLiteralExprTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/DoubleLiteralExprTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/InstanceOfExprTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/LambdaExprTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/LiteralStringValueExprTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/MethodCallExprTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/MethodReferenceExprTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/NameTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/ObjectCreationExprTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/SimpleNameTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/StringLiteralExprTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/SuperExprTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/SwitchExprTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/TextBlockLiteralExprTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/ThisExprTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/imports/ImportDeclarationTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithArgumentsTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithBodyTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithJavadocTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithModifiersTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithOptionalScopeTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithTraversableScopeTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithVariablesTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/observer/PropagatingAstObserverTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/stmt/BreakStmtTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/stmt/ForEachStmtTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/stmt/IfElseStmtTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/stmt/SwitchStmtTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/stmt/TryStmtTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/stmt/YieldStmtTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/type/ArrayTypeTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/type/ClassOrInterfaceTypeTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/type/TypeTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java10ValidatorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java11ValidatorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java12ValidatorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java13ValidatorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java14PreviewValidatorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java14ValidatorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java15PreviewValidatorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java15ValidatorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java16PreviewValidatorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java16ValidatorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java17ValidatorTest.java create mode 100755 javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java18ValidatorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java1_0ValidatorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java1_1ValidatorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java1_2ValidatorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java1_3ValidatorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java1_4ValidatorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java5ValidatorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java6ValidatorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java7ValidatorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java8ValidatorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java9ValidatorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/CloneVisitorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/GenericListVisitorAdapterTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/GenericVisitorAdapterTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/GenericVisitorWithDefaultsTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/HashCodeVisitorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/ModifierVisitorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/NoCommentEqualsVisitorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/NoCommentHashCodeVisitorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/NodeFinderVisitorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/ObjectIdentityEqualsVisitorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/ObjectIdentityHashCodeVisitorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/TreeVisitorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/VoidVisitorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/VoidVisitorWithDefaultsTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/builders/ClassOrInterfaceDeclarationBuildersTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/builders/CompilationUnitBuildersTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/builders/EnumDeclarationBuildersTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/builders/FieldDeclarationBuildersTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/builders/NodeWithAnnotationsBuildersTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/builders/NodeWithMembersBuildersTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/builders/NodeWithParametersBuildersTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/builders/NodeWithThrownExceptionsBuildersTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/issues/Issue2627Test.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/issues/Issue3113Test.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/issues/Issue3255Test.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/javadoc/JavadocExtractorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/javadoc/JavadocTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/javadoc/description/JavadocInlineTagTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/manual/BulkParseTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/metamodel/BaseNodeMetaModelTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/metamodel/PropertyMetaModelTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/modules/ModuleDeclarationTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/ConcreteSyntaxModelAcceptanceTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/ConcreteSyntaxModelTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/DefaultPrettyPrinterTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/DotPrinterTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/JsonPrinterTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/PrettyPrintVisitorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/PrettyPrinterTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/PrinterConfigurationTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/TestVisitor.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/YamlPrinterTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/configuration/imports/DefaultImportOrderingStrategyTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/configuration/imports/EclipseImportOrderingStrategyTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/configuration/imports/IntelliJImportOrderingStrategyTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/AbstractLexicalPreservingTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/AnnotationSpaceTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/DifferenceElementCalculatorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue1467Test.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue1634Test.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue1766Test.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue1793Test.java create mode 100755 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2137Test.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2290Test.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2374Test.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2393Test.java create mode 100755 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2517Test.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2592Test.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2610Test.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2620Test.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2806Test.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3296Test.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3358Test.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3387Test.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3440Test.java create mode 100755 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3441Test.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3721Test.java create mode 100755 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3746Test.java create mode 100755 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3750Test.java create mode 100755 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3761Test.java create mode 100755 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3773Test.java create mode 100755 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3796Test.java create mode 100755 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3818Test.java create mode 100755 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3924Test.java create mode 100755 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3936Test.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3937Test.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3949Test.java create mode 100755 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue4104Test.java create mode 100755 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue4163Test.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue4245Test.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/LexicalDifferenceCalculatorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinterTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/PeekingIteratorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/PrettyPrinterIssue2340Test.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/PrettyPrinterIssue2351Test.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/TransformationsTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/changes/NoChangeTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/ArrayCreationLevelTransformationsTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/CompilationUnitTransformationsTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/AnnotationDeclarationTransformationsTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/AnnotationMemberDeclarationTransformationsTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/ClassOrInterfaceDeclarationTransformationsTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/ConstructorDeclarationTransformationsTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/EnumConstantDeclarationTransformationsTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/EnumDeclarationTransformationsTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/FieldDeclarationTransformationsTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/InitializerDeclarationTransformationsTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/MethodDeclarationTransformationsTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/OperatorTransformationsTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/StatementTransformationsTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/quality/PreconditionsTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/remove/NodeRemovalTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/utils/CodeGenerationUtilsTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/utils/ExtractingVisitors.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/utils/LineSeparatorTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/utils/LogTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/utils/PairTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/utils/ParserCollectionStrategyTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/utils/PositionUtilsTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/utils/SourceRootTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/utils/SourceZipTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/utils/TestParser.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/utils/TestUtils.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/utils/UtilsTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/utils/VisitorListTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/utils/VisitorMapTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/utils/VisitorSetTest.java create mode 100644 javaparser-core-testing/src/test/java/com/github/javaparser/version/Java10PostProcessorTest.java create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/EscapeSequences.java create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/Sample.java create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/TestFileIso88591.java create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_core_generators_src_main_java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_core_metamodel_generator_src_main_java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_core_src_main_java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_core_testing_src_test_java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_metamodel_generator_src_main_java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_symbol_solver_core_src_main_java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_symbol_solver_logic_src_main_java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_symbol_solver_model_src_main_java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_symbol_solver_testing_src_test_java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_testing_src_test_java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/openjdk_src_repo_test_results.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/openjdk_src_zip_test_results.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/issue_samples/Issue290.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/issue_samples/Issue412.java.expected.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/issue_samples/Issue412.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/issue_samples/Issue624.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/issue_samples/issue1003.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/issue_samples/issue_2627/DefaultStrategy.java create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/issue_samples/issue_2627/Ops.java create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/issue_samples/issue_2627/Ops_cr.java create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/issue_samples/issue_2627/Ops_crlf.java create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/issue_samples/issue_2627/Ops_lf.java create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/issue_samples/issue_2627/Ops_minimal.java create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/ASimpleClassWithMoreFormatting.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/ASimpleClassWithMoreFormatting_step1.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/ASimpleClassWithMoreFormatting_step2.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/ASimpleClassWithMoreFormatting_step3.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/ASimpleClassWithMoreFormatting_step4.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example10_expected.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example1_expected.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example1_original.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example2_expected.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example3_expected.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example3_original.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example4_expected.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example5_expected.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example6_expected.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example7_expected.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example8_expected.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example9_expected.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example9_original.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example10_expected.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example10_original.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example1_expected.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example1_original.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example2_expected.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example2_original.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example3_expected.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example3_original.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example4_original.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example5_expected.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example5_original.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example6_expected.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example6_original.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example7_expected.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example7_original.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example8_expected.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example8_original.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example9_expected.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example9_original.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param1_expected.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param1_original.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param2_expected.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param3_expected.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param3_original.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param4_expected.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param5_expected.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param5b_expected.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/FixIndentOfMovedNode.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/FixIndentOfMovedNodeExpected.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/IndentOfInsertedCodeBlocks.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/IndentOfInsertedCodeBlocksExpected.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/MethodWithOneStatement.java.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/printer/JavaConceptsBase_prettyprinted create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/printer/JavaConceptsEnums_prettyprinted create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/printer/JavaConceptsInnerClasses_prettyprinted create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/printer/JavaConceptsMethods_prettyprinted create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/printer/JavaConceptsUgly_prettyprinted create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/printer/PrettyPrintVisitor_prettyprinted create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/printer/yamlParsingJavadocWithQuoteAndNewline.yaml create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/printer/yamlWithColonFollowedByLineSeparatorInValue.yaml create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/printer/yamlWithColonFollowedBySpaceInValue.yaml create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/printer/yamlWithType.yaml create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/printer/yamlWithoutType.yaml create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/range/A.java create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/range/B.java create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/source_zip/test.txt create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/source_zip/test.zip create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/storage/A.java create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/storage/B.java create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/storage/PrimaryType.java create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/storage/PrimaryType2.java create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/storage/Z.java create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/utils/.abc/bla.java create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/utils/Bla.java create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/utils/module-info.java create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/utils/projectroot/issue2615/with_module_info/demo/Main.java create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/utils/projectroot/issue2615/with_module_info/demo/module-info.java create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/utils/projectroot/issue2615/with_module_info_in_root/demo/Main.java create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/utils/projectroot/issue2615/with_module_info_in_root/module-info.java create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/utils/projectroot/issue2615/without_module_info/demo/Main.java create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/utils/source.root/Y.java create mode 100644 javaparser-core-testing/src/test/resources/com/github/javaparser/wiki_samples/TestFile.java create mode 100644 javaparser-core-testing/src/test/test_sourcecode/com/github/javaparser/printer/JavaConceptsBase.java create mode 100644 javaparser-core-testing/src/test/test_sourcecode/com/github/javaparser/printer/JavaConceptsEnums.java create mode 100644 javaparser-core-testing/src/test/test_sourcecode/com/github/javaparser/printer/JavaConceptsInnerClasses.java create mode 100644 javaparser-core-testing/src/test/test_sourcecode/com/github/javaparser/printer/JavaConceptsMethods.java create mode 100644 javaparser-core-testing/src/test/test_sourcecode/com/github/javaparser/printer/JavaConceptsUgly.java create mode 100644 javaparser-core-testing/src/test/test_sourcecode/com/github/javaparser/printer/PrettyPrintVisitor.java create mode 100644 javaparser-core/bnd.bnd create mode 100644 javaparser-core/bnd.bnd.template create mode 100644 javaparser-core/pom.xml create mode 100644 javaparser-core/src/main/java-templates/com/github/javaparser/JavaParserBuild.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/CommentsInserter.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/HasParentNode.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/JavaParser.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/JavaParserAdapter.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/JavaToken.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/JavadocParser.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/LineEndingProcessingProvider.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ParseProblemException.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ParseResult.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ParseStart.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ParserConfiguration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/Position.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/Problem.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/Processor.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/Providers.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/Range.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/StaticJavaParser.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/TokenRange.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/TokenTypes.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/UnicodeEscapeProcessingProvider.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/AccessSpecifier.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/AllFieldsConstructor.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/ArrayCreationLevel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/CompilationUnit.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/DataKey.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/Generated.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/ImportDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/Modifier.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/Node.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/NodeList.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/PackageDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/body/AnnotationDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/body/AnnotationMemberDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/body/BodyDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/body/CallableDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/body/ClassOrInterfaceDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/body/CompactConstructorDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/body/ConstructorDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/body/EnumConstantDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/body/EnumDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/body/FieldDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/body/InitializerDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/body/MethodDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/body/Parameter.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/body/ReceiverParameter.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/body/RecordDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/body/TypeDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/body/VariableDeclarator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/comments/BlockComment.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/comments/Comment.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/comments/CommentsCollection.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/comments/JavadocComment.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/comments/LineComment.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/AnnotationExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/ArrayAccessExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/ArrayCreationExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/ArrayInitializerExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/AssignExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/BinaryExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/BooleanLiteralExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/CastExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/CharLiteralExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/ClassExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/ConditionalExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/DoubleLiteralExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/EnclosedExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/Expression.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/FieldAccessExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/InstanceOfExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/IntegerLiteralExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/LambdaExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/LiteralExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/LiteralStringValueExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/LongLiteralExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/MarkerAnnotationExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/MemberValuePair.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/MethodCallExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/MethodReferenceExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/Name.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/NameExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/NormalAnnotationExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/NullLiteralExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/ObjectCreationExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/PatternExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/SimpleName.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/SingleMemberAnnotationExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/StringLiteralExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/SuperExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/SwitchExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/TextBlockLiteralExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/ThisExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/TypeExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/UnaryExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/expr/VariableDeclarationExpr.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/modules/ModuleDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/modules/ModuleDirective.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/modules/ModuleExportsDirective.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/modules/ModuleOpensDirective.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/modules/ModuleProvidesDirective.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/modules/ModuleRequiresDirective.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/modules/ModuleUsesDirective.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithAnnotations.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithArguments.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithBlockStmt.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithBody.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithCondition.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithExpression.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithExtends.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithIdentifier.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithImplements.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithJavadoc.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithMembers.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithModifiers.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithName.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithOptionalBlockStmt.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithOptionalLabel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithOptionalScope.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithParameters.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithRange.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithScope.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithSimpleName.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithStatements.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithThrownExceptions.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithTokenRange.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithTraversableScope.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithType.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithTypeArguments.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithTypeParameters.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/NodeWithVariables.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/SwitchNode.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/modifiers/NodeWithAbstractModifier.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/modifiers/NodeWithAccessModifiers.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/modifiers/NodeWithFinalModifier.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/modifiers/NodeWithPrivateModifier.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/modifiers/NodeWithProtectedModifier.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/modifiers/NodeWithPublicModifier.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/modifiers/NodeWithStaticModifier.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/nodeTypes/modifiers/NodeWithStrictfpModifier.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/observer/AstObserver.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/observer/AstObserverAdapter.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/observer/Observable.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/observer/ObservableProperty.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/observer/PropagatingAstObserver.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/stmt/AssertStmt.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/stmt/BlockStmt.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/stmt/BreakStmt.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/stmt/CatchClause.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/stmt/ContinueStmt.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/stmt/DoStmt.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/stmt/EmptyStmt.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/stmt/ExplicitConstructorInvocationStmt.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/stmt/ExpressionStmt.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/stmt/ForEachStmt.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/stmt/ForStmt.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/stmt/IfStmt.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/stmt/LabeledStmt.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/stmt/LocalClassDeclarationStmt.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/stmt/LocalRecordDeclarationStmt.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/stmt/ReturnStmt.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/stmt/Statement.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/stmt/SwitchEntry.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/stmt/SwitchStmt.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/stmt/SynchronizedStmt.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/stmt/ThrowStmt.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/stmt/TryStmt.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/stmt/UnparsableStmt.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/stmt/WhileStmt.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/stmt/YieldStmt.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/type/ArrayType.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/type/ClassOrInterfaceType.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/type/ConvertibleToUsage.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/type/IntersectionType.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/type/PrimitiveType.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/type/ReferenceType.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/type/Type.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/type/TypeParameter.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/type/UnionType.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/type/UnknownType.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/type/VarType.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/type/VoidType.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/type/WildcardType.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/ProblemReporter.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/RecordAsTypeIdentifierNotAllowed.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/ReservedKeywordValidator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/SimpleValidator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/SingleNodeTypeValidator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/TreeVisitorValidator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/TypedValidator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/Validator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/Validators.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/VisitorValidator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java10PreviewValidator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java10Validator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java11PreviewValidator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java11Validator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java12PreviewValidator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java12Validator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java13PreviewValidator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java13Validator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java14PreviewValidator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java14Validator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java15PreviewValidator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java15Validator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java16PreviewValidator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java16Validator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java17PreviewValidator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java17Validator.java create mode 100755 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java18Validator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java1_0Validator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java1_1Validator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java1_2Validator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java1_3Validator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java1_4Validator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java5Validator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java6Validator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java7Validator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java8Validator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/Java9Validator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/UpgradeJavaMessage.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/chunks/CommonValidators.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/chunks/ModifierValidator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/chunks/NoBinaryIntegerLiteralsValidator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/chunks/NoUnderscoresInIntegerLiteralsValidator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/chunks/RecordDeclarationValidator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/chunks/UnderscoreKeywordValidator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/language_level_validations/chunks/VarValidator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/postprocessors/Java10PostProcessor.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/postprocessors/Java11PostProcessor.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/postprocessors/Java12PostProcessor.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/postprocessors/Java13PostProcessor.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/postprocessors/Java14PostProcessor.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/postprocessors/Java15PostProcessor.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/postprocessors/Java16PostProcessor.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/postprocessors/Java17PostProcessor.java create mode 100755 javaparser-core/src/main/java/com/github/javaparser/ast/validator/postprocessors/Java18PostProcessor.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/validator/postprocessors/PostProcessors.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/visitor/CloneVisitor.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/visitor/EqualsVisitor.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/visitor/GenericListVisitorAdapter.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/visitor/GenericVisitor.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/visitor/GenericVisitorAdapter.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/visitor/GenericVisitorWithDefaults.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/visitor/HashCodeVisitor.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/visitor/ModifierVisitor.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/visitor/NoCommentEqualsVisitor.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/visitor/NoCommentHashCodeVisitor.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/visitor/NodeFinderVisitor.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/visitor/ObjectIdentityEqualsVisitor.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/visitor/ObjectIdentityHashCodeVisitor.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/visitor/TreeVisitor.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/visitor/Visitable.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/visitor/VoidVisitor.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/visitor/VoidVisitorAdapter.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/ast/visitor/VoidVisitorWithDefaults.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/javadoc/Javadoc.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/javadoc/JavadocBlockTag.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/javadoc/description/JavadocDescription.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/javadoc/description/JavadocDescriptionElement.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/javadoc/description/JavadocInlineTag.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/javadoc/description/JavadocSnippet.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/AnnotationDeclarationMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/AnnotationExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/AnnotationMemberDeclarationMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/ArrayAccessExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/ArrayCreationExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/ArrayCreationLevelMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/ArrayInitializerExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/ArrayTypeMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/AssertStmtMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/AssignExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/BaseNodeMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/BinaryExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/BlockCommentMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/BlockStmtMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/BodyDeclarationMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/BooleanLiteralExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/BreakStmtMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/CallableDeclarationMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/CastExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/CatchClauseMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/CharLiteralExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/ClassExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/ClassOrInterfaceDeclarationMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/ClassOrInterfaceTypeMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/CommentMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/CompactConstructorDeclarationMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/CompilationUnitMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/ConditionalExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/ConstructorDeclarationMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/ContinueStmtMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/DerivedProperty.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/DoStmtMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/DoubleLiteralExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/EmptyStmtMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/EnclosedExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/EnumConstantDeclarationMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/EnumDeclarationMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/ExplicitConstructorInvocationStmtMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/ExpressionMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/ExpressionStmtMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/FieldAccessExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/FieldDeclarationMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/ForEachStmtMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/ForStmtMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/IfStmtMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/ImportDeclarationMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/InitializerDeclarationMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/InstanceOfExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/IntegerLiteralExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/InternalProperty.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/IntersectionTypeMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/JavaParserMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/JavadocCommentMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/LabeledStmtMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/LambdaExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/LineCommentMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/LiteralExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/LiteralStringValueExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/LocalClassDeclarationStmtMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/LocalRecordDeclarationStmtMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/LongLiteralExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/MarkerAnnotationExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/MemberValuePairMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/MethodCallExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/MethodDeclarationMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/MethodReferenceExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/ModifierMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/ModuleDeclarationMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/ModuleDirectiveMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/ModuleExportsDirectiveMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/ModuleOpensDirectiveMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/ModuleProvidesDirectiveMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/ModuleRequiresDirectiveMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/ModuleUsesDirectiveMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/NameExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/NameMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/NodeMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/NonEmptyProperty.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/NormalAnnotationExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/NullLiteralExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/ObjectCreationExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/OptionalProperty.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/PackageDeclarationMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/ParameterMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/PatternExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/PrimitiveTypeMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/PropertyMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/ReceiverParameterMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/RecordDeclarationMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/ReferenceTypeMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/ReturnStmtMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/SimpleNameMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/SingleMemberAnnotationExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/StatementMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/StringLiteralExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/SuperExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/SwitchEntryMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/SwitchExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/SwitchStmtMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/SynchronizedStmtMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/TextBlockLiteralExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/ThisExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/ThrowStmtMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/TryStmtMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/TypeDeclarationMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/TypeExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/TypeMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/TypeParameterMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/UnaryExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/UnionTypeMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/UnknownTypeMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/UnparsableStmtMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/VarTypeMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/VariableDeclarationExprMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/VariableDeclaratorMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/VoidTypeMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/WhileStmtMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/WildcardTypeMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/metamodel/YieldStmtMetaModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/ConcreteSyntaxModel.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/DefaultPrettyPrinter.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/DefaultPrettyPrinterVisitor.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/DotPrinter.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/PrettyPrintVisitor.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/PrettyPrinter.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/Printer.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/SourcePrinter.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/Stringable.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/XmlPrinter.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/YamlPrinter.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmAttribute.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmChar.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmComment.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmConditional.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmElement.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmIndent.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmList.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmMix.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmNone.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmOrphanCommentsEnding.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmSequence.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmSingleReference.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmString.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmTextBlock.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmToken.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/CsmUnindent.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/concretesyntaxmodel/PrintingHelper.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/configuration/ConfigurationOption.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/configuration/DefaultConfigurationOption.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/configuration/DefaultPrinterConfiguration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/configuration/ImportOrderingStrategy.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/configuration/Indentation.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/configuration/PrettyPrinterConfiguration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/configuration/PrinterConfiguration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/configuration/imports/DefaultImportOrderingStrategy.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/configuration/imports/EclipseImportOrderingStrategy.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/configuration/imports/IntelliJImportOrderingStrategy.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Added.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/ChildTextElement.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Difference.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/DifferenceElement.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/DifferenceElementCalculator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Kept.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalDifferenceCalculator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinter.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingVisitor.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/LookaheadIterator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/NodeText.java create mode 100755 javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/PeekingIterator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/PhantomNodeLogic.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/PrintableTextElement.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Removed.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/RemovedGroup.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/Reshuffled.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/ReshuffledDiffElementExtractor.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/TextElement.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/TextElementIteratorsFactory.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/TextElementMatcher.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/TextElementMatchers.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/TokenTextElement.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/changes/Change.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/changes/ListAdditionChange.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/changes/ListRemovalChange.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/changes/ListReplacementChange.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/changes/NoChange.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/printer/lexicalpreservation/changes/PropertyChange.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/quality/NotNull.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/quality/Nullable.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/quality/Preconditions.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/Context.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/MethodAmbiguityException.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/MethodUsage.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/Navigator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/Resolvable.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/Solver.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/SymbolDeclarator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/SymbolResolver.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/TypeSolver.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/UnsolvedSymbolException.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/cache/Cache.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/cache/CacheStats.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/AssociableToAST.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/HasAccessSpecifier.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedAnnotationDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedAnnotationMemberDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedClassDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedConstructorDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedEnumConstantDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedEnumDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedFieldDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedInterfaceDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedMethodDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedMethodLikeDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedParameterDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedPatternDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedReferenceTypeDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedTypeDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedTypeParameterDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedTypeParametrizable.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/declarations/ResolvedValueDeclaration.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/logic/ConflictingGenericTypesException.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/logic/ConstructorResolutionLogic.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/logic/FunctionalInterfaceLogic.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/logic/InferenceContext.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/logic/InferenceVariableType.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/logic/MethodResolutionCapability.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/logic/MethodResolutionLogic.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/model/LambdaArgumentTypePlaceholder.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/model/SymbolReference.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/model/Value.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/model/typesystem/LazyType.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/model/typesystem/NullType.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/model/typesystem/ReferenceTypeImpl.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/promotion/ConditionalExprHandler.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedArrayType.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedIntersectionType.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedLambdaConstraintType.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedPrimitiveType.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedReferenceType.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedType.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedTypeTransformer.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedTypeVariable.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedUnionType.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedVoidType.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/types/ResolvedWildcard.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/types/parametrization/ResolvedTypeParameterValueProvider.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/types/parametrization/ResolvedTypeParametersMap.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/resolution/types/parametrization/ResolvedTypeParametrized.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/utils/ClassUtils.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/utils/CodeGenerationUtils.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/utils/CollectionStrategy.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/utils/LineSeparator.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/utils/Log.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/utils/Pair.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/utils/ParserCollectionStrategy.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/utils/PositionUtils.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/utils/ProjectRoot.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/utils/SeparatedItemStringBuilder.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/utils/SourceRoot.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/utils/SourceZip.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/utils/StringEscapeUtils.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/utils/TypeUtils.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/utils/Utils.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/utils/VisitorList.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/utils/VisitorMap.java create mode 100644 javaparser-core/src/main/java/com/github/javaparser/utils/VisitorSet.java create mode 100644 javaparser-core/src/main/javacc-support/com/github/javaparser/GeneratedJavaParserBase.java create mode 100644 javaparser-core/src/main/javacc-support/com/github/javaparser/GeneratedJavaParserTokenManagerBase.java create mode 100644 javaparser-core/src/main/javacc-support/com/github/javaparser/ModifierHolder.java create mode 100644 javaparser-core/src/main/javacc-support/com/github/javaparser/RangedList.java create mode 100644 javaparser-core/src/main/javacc-support/com/github/javaparser/TokenBase.java create mode 100644 javaparser-core/src/main/javacc/java.jj create mode 100644 javaparser-symbol-solver-core/.gitignore create mode 100644 javaparser-symbol-solver-core/pom.xml create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/JavaSymbolSolver.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/SourceFileInfoExtractor.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/cache/DefaultCacheStats.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/cache/GuavaCache.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/cache/InMemoryCache.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/cache/NoCache.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/core/resolution/MethodUsageResolutionCapability.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/core/resolution/SymbolResolutionCapability.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/core/resolution/TypeVariableResolutionCapability.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/declarations/common/MethodDeclarationCommonLogic.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparser/package-info.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/DefaultVisitorAdapter.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/FailureHandler.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/JavaParserFacade.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/JavaParserFactory.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/TypeExtractor.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/AbstractJavaParserContext.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/AbstractMethodLikeDeclarationContext.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/AnnotationDeclarationContext.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/AnonymousClassDeclarationContext.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/ArrayAccessExprContext.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/BinaryExprContext.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/BlockStmtContext.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/CatchClauseContext.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/ClassOrInterfaceDeclarationContext.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/ClassOrInterfaceDeclarationExtendsContext.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/CompilationUnitContext.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/ConstructorContext.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/ContextHelper.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/EnclosedExprContext.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/EnumDeclarationContext.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/FieldAccessContext.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/ForEachStatementContext.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/ForStatementContext.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/IfStatementContext.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/InstanceOfExprContext.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/JavaParserTypeDeclarationAdapter.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/LambdaExprContext.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/MethodCallExprContext.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/MethodContext.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/MethodReferenceExprContext.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/ObjectCreationContext.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/StatementContext.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/SwitchEntryContext.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/TryWithResourceContext.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/UnaryExprContext.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/VariableDeclarationExprContext.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/VariableDeclaratorContext.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/AstResolutionUtils.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/DefaultConstructorDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserAnnotationDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserAnnotationMemberDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserAnonymousClassDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserClassDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserConstructorDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserEnumConstantDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserEnumDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserFieldDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserInterfaceDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserMethodDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserParameterDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserPatternDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserSymbolDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserTypeAdapter.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserTypeParameter.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserTypeVariableDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserVariableDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarators/AbstractSymbolDeclarator.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarators/FieldSymbolDeclarator.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarators/NoSymbolDeclarator.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarators/ParameterSymbolDeclarator.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarators/PatternSymbolDeclarator.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarators/VariableSymbolDeclarator.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/package-info.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistAnnotationDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistAnnotationMemberDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistClassDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistConstructorDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistEnumConstantDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistEnumDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistFactory.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistFieldDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistInterfaceDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistMethodDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistMethodLikeDeclarationAdapter.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistParameterDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistTypeDeclarationAdapter.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistTypeParameter.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistUtils.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/package-info.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/logic/AbstractClassDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/logic/AbstractTypeDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/logic/ObjectProvider.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionAnnotationDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionAnnotationMemberDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionClassAdapter.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionClassDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionConstructorDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionEnumConstantDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionEnumDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionFactory.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionFieldDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionInterfaceDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionMethodDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionMethodResolutionLogic.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionParameterDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionPatternDeclaration.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionTypeParameter.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/comparators/ClassComparator.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/comparators/MethodComparator.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/comparators/ParameterComparator.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/package-info.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/SymbolSolver.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/naming/NameCategory.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/naming/NameLogic.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/naming/NameRole.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/promotion/BooleanConditionalExprHandler.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/promotion/ConditionalExprResolver.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/promotion/NumericConditionalExprHandler.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/promotion/ReferenceConditionalExprHandler.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/Bound.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/BoundSet.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/ConstraintFormula.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/ConstraintFormulaSet.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/ControlFlowLogic.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/InferenceVariable.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/InferenceVariableSubstitution.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/Instantiation.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/InstantiationSet.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/LeastUpperBoundLogic.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/MethodType.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/ProperLowerBound.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/ProperUpperBound.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/Substitution.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/TypeHelper.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/TypeInference.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/TypeInferenceCache.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/bounds/CapturesBound.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/bounds/FalseBound.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/bounds/SameAsBound.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/bounds/SubtypeOfBound.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/bounds/ThrowsBound.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/constraintformulas/ExpressionCompatibleWithType.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/constraintformulas/LambdaThrowsCompatibleWithType.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/constraintformulas/MethodReferenceThrowsCompatibleWithType.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/constraintformulas/TypeCompatibleWithType.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/constraintformulas/TypeContainedByType.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/constraintformulas/TypeSameAsType.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/constraintformulas/TypeSubtypeOfType.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typesolvers/AarTypeSolver.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typesolvers/ClassLoaderTypeSolver.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typesolvers/CombinedTypeSolver.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typesolvers/JarTypeSolver.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typesolvers/JavaParserTypeSolver.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typesolvers/MemoryTypeSolver.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typesolvers/ReflectionTypeSolver.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typesolvers/TypeSolverBuilder.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/utils/FileUtils.java create mode 100644 javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/utils/SymbolSolverCollectionStrategy.java create mode 100644 javaparser-symbol-solver-testing/.gitignore create mode 100644 javaparser-symbol-solver-testing/pom.xml create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/SlowTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/ast/type/ClassOrInterfaceTypeTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/resolution/declarations/AssociableToASTTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/resolution/declarations/HasAccessSpecifierTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/resolution/declarations/ResolvedAnnotationDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/resolution/declarations/ResolvedAnnotationMemberDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/resolution/declarations/ResolvedClassDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/resolution/declarations/ResolvedConstructorDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/resolution/declarations/ResolvedDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/resolution/declarations/ResolvedEnumConstantDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/resolution/declarations/ResolvedEnumDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/resolution/declarations/ResolvedFieldDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/resolution/declarations/ResolvedMethodDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/resolution/declarations/ResolvedMethodLikeDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/resolution/declarations/ResolvedParameterDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/resolution/declarations/ResolvedPatternDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/resolution/declarations/ResolvedReferenceTypeDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/resolution/declarations/ResolvedTypeDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/resolution/declarations/ResolvedTypeParameterDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/resolution/declarations/ResolvedTypeParametrizableTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/resolution/declarations/ResolvedValueDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/AbstractSymbolResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/FindingAllFieldsTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue113Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue116Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue128Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue1364Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue1370Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue144Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue1456Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue1479Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue1480Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue1485Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue1491Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue1511Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue1518Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue1526Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue156Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue1574Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue1599Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue1668Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue1713Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue1726Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue1757Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue1769Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue1774Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue1814Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue1817Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue1827Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue185Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue1868Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue186Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue18Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue1945Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue1946Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue1950Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue200Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2035Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2044Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2062Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2065Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2083Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2132Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2162Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2210Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2236Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2259Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2284Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2289Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue228Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue232Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue235Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2360.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2362Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2367Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2397Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2406Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue241Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2477Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2481Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2489Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue251Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2595Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2602Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2740Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2764Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue276Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2781Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2823Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2878Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2909Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2943Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2951Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2953Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2987Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue2995Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue300Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3024Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3028Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3030Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3038Test.java create mode 100755 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3045Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3083Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3087Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3099Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3112Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3136Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue314Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3159Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3173Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3184Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3200Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3272Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3278Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3308Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue343Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue347Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3614Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue366Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3859Test.java create mode 100755 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3866Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3878Test.java create mode 100755 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3918Test.java create mode 100755 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3951Test.java create mode 100755 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3972Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue3976Test.java create mode 100755 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue4037Test.java create mode 100755 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue4047Test.java create mode 100755 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue4124Test.java create mode 100755 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue4284Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue4358Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue546Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/Issue84Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/JavaParserAPIIntegrationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/JavaSymbolSolverTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/PullRequest2398Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/SolveMethodDeclaredInEnumTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/cache/GuavaCacheAdapterTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/cache/InMemoryCacheTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/cache/NoCacheTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/core/resolution/MethodUsageResolutionCapabilityTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/core/resolution/TypeVariableResolutionCapabilityTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/ConvertToUsageTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/DifferentiateDotExpressionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/JavaParserFacadeTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/ClassOrInterfaceDeclarationContextTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/JavaParserTypeDeclarationAdapterTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/contexts/MultiCatchMethodCallExprTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserAnnotationDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserAnonymousClassDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserClassDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserEnumDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserFieldDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserInterfaceDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserMethodDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserParameterDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserPatternDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserSymbolDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserTypeParameterTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserTypeVariableDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserVariableDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javassistmodel/Issue257Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistAnnotationDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistAnnotationMemberDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistClassDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistConstructorDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistEnumConstantDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistEnumDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistFieldDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistInterfaceDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistMethodDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistParameterDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistTypeDeclarationAdapterTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistTypeParameterDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/logic/AbstractClassDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/logic/AbstractTypeDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/logic/FunctionInterfaceLogicTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/logic/InferenceContextTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/logic/MethodResolutionCapabilityTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/model/resolution/SymbolReferenceTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/model/typesystem/ArrayTypeTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/model/typesystem/LazyTypeTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/model/typesystem/NullTypeTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/model/typesystem/PrimitiveTypeTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/model/typesystem/ReferenceTypeTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/model/typesystem/TypeVariableUsageTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/model/typesystem/VoidTypeTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/model/typesystem/WildcardUsageTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionAnnotationDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionClassDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionEnumDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionFieldDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionInterfaceDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionMethodDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionParameterDeclarationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionTestObject.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/AbstractResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/AnalyseJavaParserTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/AnalyseJavaSymbolSolver060Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/AnalyseNewJavaParserHelpersTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/AnalyseNewJavaParserTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/AnnotationsResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/AnonymousClassesResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/ArrayExprTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/CompilationUnitContextResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/ConditionalExprTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/ConstructorsResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/ContextTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/DefaultPackageTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/EnumLiteralsInAnnotatedClassTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/EnumResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/ExprResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/FieldAccessExprResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/FieldsResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/GenericsResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/ImplementedOrExtendedTypeResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/InstanceOfTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/InternalClassInInterfaceTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/JavaParserFacadeResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/LambdaGenericResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/LambdaResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/MethodDescriptorTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/MethodLikeSignaturesTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/MethodReferenceResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/MethodsResolutionLogicTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/MethodsResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/MethodsResolutionWithJavassistTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/NotQuiteCyclicParentTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/PolyExpressionResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/QualifiedNameResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/ReferenceTypeResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/StatementContextResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/SymbolSolverTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/SymbolSolverWithJavassistClassTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/SymbolSolverWithJavassistEnumTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/SymbolSolverWithJavassistInterfaceTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/TypeDescriptorTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/TypeInClassWithAnnotationAncestorTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/TypeResolutionWithSameNameTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/UnknownMethodsResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/VariableResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/VariadicResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/javaparser/VarTypeTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/javaparser/contexts/BlockStmtContextResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/javaparser/contexts/ClassOrInterfaceDeclarationContextResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/javaparser/contexts/CompilationUnitContextResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/javaparser/contexts/EnumDeclarationContextResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/javaparser/contexts/FieldAccessContextResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/javaparser/contexts/LambdaExprContextResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/javaparser/contexts/MethodCallExprContextResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/javaparser/contexts/MethodContextResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/javaparser/declarations/JavaParserTypeParameterResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/logic/FunctionalInterfaceLogicTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/naming/AbstractNameLogicTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/naming/NameLogicDisambiguationTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/naming/NameLogicTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/naming/NameLogicTestingJss060Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/reflectionmodel/SymbolResolutionResolutionTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/typeinference/LeastUpperBoundTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/typeinference/bounds/SameAsBoundTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/typeinference/bounds/SubtypeOfBoundTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/typeinference/constraintformulas/ConstraintFormulaTest.java create mode 100755 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/types/ResolvedArrayTypeTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/types/ResolvedPrimitiveTypeTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/typesolvers/AarTypeSolverTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/typesolvers/AbstractTypeSolverTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/typesolvers/ClassLoaderTypeSolverTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/typesolvers/CombinedTypeSolverTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/typesolvers/JarTypeSolverTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/typesolvers/JavaParserTypeSolverTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/typesolvers/MemoryTypeSolverTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/typesolvers/ReflectionTypeSolverTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/typesolvers/TypeSolverBuilderTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/testingclasses/SomeClass.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/testingclasses/TargetType.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/testingclasses/UtilityClass.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/utils/LeanParserConfiguration.java create mode 100644 javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/utils/SymbolSolverCollectionStrategyTest.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/AClassWithFields.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/AClassWithFieldsAndGenerics.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/AccessClassMemberThroughThis.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/AccessEnumMemberThroughThis.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/AccessThroughSuper.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/AnEnum.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/AnInterface.java.txt create mode 100755 javaparser-symbol-solver-testing/src/test/resources/Ancestor.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/Annotations.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/AnonymousClassDeclarations.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/AnonymousClassMethodClass.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/ArrayAccess.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/ClassCast.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/ClassExpression.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/ClassExtendingUnknownClass.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/ClassTypeParameter.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/ClassWithAnnotationAncestor.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/ClassWithMethods.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/ClassWithSymbols.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/ClassWithTypeVariables.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/ClassWithTypes.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/CompilationUnitContextResolutionTest/00_receiver/main/Child.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/CompilationUnitContextResolutionTest/00_receiver/main/Main.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/CompilationUnitContextResolutionTest/00_receiver/main/Parent.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/CompilationUnitContextResolutionTest/01_parent/main/Child.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/CompilationUnitContextResolutionTest/01_parent/main/GrandParent.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/CompilationUnitContextResolutionTest/01_parent/main/Main.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/CompilationUnitContextResolutionTest/01_parent/main/Parent.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/CompilationUnitContextResolutionTest/02_nested/main/Child.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/CompilationUnitContextResolutionTest/02_nested/main/Main.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/CompilationUnitContextResolutionTest/02_nested/main/Parent.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/CompilationUnitContextResolutionTest/03_symbol/main/Clazz.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/CompilationUnitContextResolutionTest/03_symbol/main/Main.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/CompilationUnitContextResolutionTest/04_reviewComment/main/Main.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/CompilationUnitSymbols.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/CompilationUnitWithImports.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/ComplexTypeResolving.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/ConstructorCalls.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/ConstructorCallsEnum.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/ElementOfList.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/EnumAccessSpecifier.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/EnumAndStaticInitializer.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/EnumFieldAccess.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/FieldAccessExprResolution.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/GenericArrayMethodArgument.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/GenericClassNavigator.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/GenericCollection.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/GenericCollectionWithExtension.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/GenericFields.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/GenericLambdas.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/GenericMethodArguments.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/Generics.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/GenericsWildcard.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/Generics_issue7.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/ISSUES_Generic_Parameter.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/ImplementedOrExtendedTypeResolution/ImplementedOrExtendedTypeResolution.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/ImplementedOrExtendedTypeResolution/pkg/another/A.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/ImplementedOrExtendedTypeResolution/pkg/main/A.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/InterfaceInheritance.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/Issue116.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/Issue1482.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/Issue156.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/Issue18.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/Issue186.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/Issue200.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/Issue2258.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/Issue232.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/Issue235.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/Issue241.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/Issue251.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/Issue2667.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/Issue3028.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/Issue338.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/Issue84.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/JarTypeSolverConstructorResolution.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/JreConditionalExpression.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/Lambda.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/LambdaCollect.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/LambdaMulti.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/LambdaVoid.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/LocalTypeDeclarations.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/LocalVariableInParent.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/MethodCalls.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/MethodLikeSignaturesTest.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/MethodReferences.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/MethodTypeParameter.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/MethodTypeParams.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/MethodWithTypes.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/Navigator.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/Navigator2.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/Navigator3.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/NavigatorSimplified.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/NestedClasses.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/NestedInterfaces.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/NestedInterfacesWithIdenticalNames.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/NotQuiteCyclicParent.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/OverloadedMethodCall.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/OverloadedMethods.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/PlatformTestUtil.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/QualifiedNameTest.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/ReferencesToField.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/ReferencesToParameter.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/ReflectionFieldOfItself.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/ReflectionTypeSolverConstructorResolution.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/ReflectionTypeSolverFieldFromInterfaceResolution.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/SwitchOnEnum.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/SymbolResolverExample.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/ThisInAnonymousClass.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/TryInSwitch.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/TypeParamOnReturnType.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/TypeResolutionWithSameNameTest/00_package_precedes_nested_class/extends_duplicate/A.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/TypeResolutionWithSameNameTest/00_package_precedes_nested_class/extends_duplicate/DuplicateTypeName.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/TypeResolutionWithSameNameTest/01_package_precedes_nested_interface/implements_duplicate/A.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/TypeResolutionWithSameNameTest/01_package_precedes_nested_interface/implements_duplicate/DuplicateTypeName.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/TypeResolutionWithSameNameTest/02_ignore_static_non_type_import/another/A.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/TypeResolutionWithSameNameTest/02_ignore_static_non_type_import/another/MyEnum.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/TypeResolutionWithSameNameTest/02_ignore_static_non_type_import/main/Main.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/TypeResolutionWithSameNameTest/03_single_type_import_precedes_package_member/another/A.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/TypeResolutionWithSameNameTest/03_single_type_import_precedes_package_member/main/A.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/TypeResolutionWithSameNameTest/03_single_type_import_precedes_package_member/main/Main.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/TypeResolutionWithSameNameTest/04_package_member_precedes_asterisk_import/another/A.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/TypeResolutionWithSameNameTest/04_package_member_precedes_asterisk_import/main/A.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/TypeResolutionWithSameNameTest/04_package_member_precedes_asterisk_import/main/Main.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/TypeResolutionWithSameNameTest/05_asterisk_import_precedes_java_lang/another/String.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/TypeResolutionWithSameNameTest/05_asterisk_import_precedes_java_lang/main/Main.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/UnknownMethods.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/VariableResolutionInVariousScopes.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/differentiate_dot_expressions/FieldDotExpressions.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/differentiate_dot_expressions/InnerClassDotExpressions.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/differentiate_dot_expressions/InnerStaticClassFieldDotExpressions.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/differentiate_dot_expressions/PackageDotExpressions.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/differentiate_dot_expressions/com/packageName/ClassInPackage.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/differentiate_dot_expressions/com/packageName/InnerClassContainer.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/differentiate_dot_expressions/com/packageName/InnerClassFieldContainer.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/differentiate_dot_expressions/com/packageName/InnerStaticClassFieldContainer.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/enumLiteralsInAnnotatedClass/foo/bar/AClass.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/enumLiteralsInAnnotatedClass/foo/bar/BinaryExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/enumLiteralsInAnnotatedClass/foo/bar/differentpackage/AClass2.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/enums/EnumWithAncestor.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/enums/EnumWithInnerType.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/internalClassInInterface/foo/bar/AClass.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/internalClassInInterface/foo/bar/AnInterface.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/internalClassInInterface/foo/bar/differentpackage/AClass2.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue113/com/foo/Widget.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue113/com/foo/base/Widget.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue128/foo/Issue128.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue144/HelloWorld.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue1456/bar/A.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue1456/foo/A.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue1479/A.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue1479/B.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue1480/A.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue1480/B.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue1485/Complex.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue1491/A.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue1511/A.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue1518/Test1.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue1526/compiles/a/b/c/DataObject.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue1526/compiles/a/b/c/DataObjectFactory.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue1526/compiles/a/b/c/ExampleClass.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue1526/compiles/d/e/f/DataObjectFactory.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue1526/errors/a/b/c/DataObject.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue1526/errors/a/b/c/DataObjectFactory.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue1526/errors/a/b/c/ExampleClass.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue1526/errors/d/e/f/DataObjectFactory.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue1574/BlockComment.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue1574/ClassWithOrphanComments.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue1574/Comment.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue1599/A.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue1769/foo/OtherClass.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue1817/X.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue1868/B.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue1945/issue1945/implementations/HairTypeWool.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue1945/issue1945/implementations/Sheep.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue1945/issue1945/implementations/WoolRenderer.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue1945/issue1945/interfaces/HairType.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue1945/issue1945/interfaces/HairTypeRenderer.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue1945/issue1945/interfaces/HairyAnimal.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue1945/issue1945/main/MainIssue1945.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue2236/A.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue2362/Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue2366/Test.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue2367/Issue2367.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue241/TypeWithMemberType.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue2489/ComponentBase.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue2489/ObjectContext.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue2489/ObjectContextDecorator .java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue257/A.java.txt create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue2667/javaparser/JSONObject.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue276/foo/A.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue276/foo/B.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue276/foo/C.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue2823/ClassA.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue2823/ClassB.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue2878/U9.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue2909/OuterClass.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue2951/foo/A.class create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue2951/foo/A.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue2953/foo/A.class create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue2953/foo/A.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue2953/foo/IB.class create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue2953/foo/IB.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue300/Issue300.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue3099/com/example/Alpha.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue3099/com/example/Beta.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue4358/foo/A.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/issue4358/foo/B.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/javassist_generics/javaparser/GenericClass.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/javassist_symbols/README.md create mode 100644 javaparser-symbol-solver-testing/src/test/resources/javassist_symbols/excluded_jar/result/doNotDelete.md create mode 100644 javaparser-symbol-solver-testing/src/test/resources/javassist_symbols/excluded_jar/src/com/github/javaparser/javasymbolsolver/javassist_symbols/excluded_jar/InterfaceExcludedJar.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/javassist_symbols/excluded_jar/src/com/github/javaparser/javasymbolsolver/javassist_symbols/excluded_jar/SuperClassExcludedJar.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/javassist_symbols/included_jar/result/doNotDelete.md create mode 100644 javaparser-symbol-solver-testing/src/test/resources/javassist_symbols/included_jar/src/com/github/javaparser/javasymbolsolver/javassist_symbols/included_jar/InterfaceIncludedJar.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/javassist_symbols/included_jar/src/com/github/javaparser/javasymbolsolver/javassist_symbols/included_jar/SuperClassIncludedJar.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/javassist_symbols/main_jar/result/doNotDelete.md create mode 100644 javaparser-symbol-solver-testing/src/test/resources/javassist_symbols/main_jar/src/com/github/javaparser/javasymbolsolver/javassist_symbols/main_jar/ConcreteClass.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/javassist_symbols/main_jar/src/com/github/javaparser/javasymbolsolver/javassist_symbols/main_jar/ConcreteEnum.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/javassist_symbols/main_jar/src/com/github/javaparser/javasymbolsolver/javassist_symbols/main_jar/EnumInterfaceUserExcludedJar.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/javassist_symbols/main_jar/src/com/github/javaparser/javasymbolsolver/javassist_symbols/main_jar/EnumInterfaceUserIncludedJar.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/javassist_symbols/main_jar/src/com/github/javaparser/javasymbolsolver/javassist_symbols/main_jar/EnumInterfaceUserOwnJar.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/javassist_symbols/main_jar/src/com/github/javaparser/javasymbolsolver/javassist_symbols/main_jar/InterfaceOwnJar.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/javassist_symbols/main_jar/src/com/github/javaparser/javasymbolsolver/javassist_symbols/main_jar/InterfaceUserExcludedJar.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/javassist_symbols/main_jar/src/com/github/javaparser/javasymbolsolver/javassist_symbols/main_jar/InterfaceUserIncludedJar.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/javassist_symbols/main_jar/src/com/github/javaparser/javasymbolsolver/javassist_symbols/main_jar/InterfaceUserOwnJar.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/javassist_symbols/main_jar/src/com/github/javaparser/javasymbolsolver/javassist_symbols/main_jar/StandaloneInterface.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/javassist_symbols/main_jar/src/com/github/javaparser/javasymbolsolver/javassist_symbols/main_jar/SubClassExcludedJar.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/javassist_symbols/main_jar/src/com/github/javaparser/javasymbolsolver/javassist_symbols/main_jar/SubClassIncludedJar.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/javassist_symbols/main_jar/src/com/github/javaparser/javasymbolsolver/javassist_symbols/main_jar/SubClassOwnJar.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/javassist_symbols/main_jar/src/com/github/javaparser/javasymbolsolver/javassist_symbols/main_jar/SubInterfaceExcludedJar.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/javassist_symbols/main_jar/src/com/github/javaparser/javasymbolsolver/javassist_symbols/main_jar/SubInterfaceIncludedJar.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/javassist_symbols/main_jar/src/com/github/javaparser/javasymbolsolver/javassist_symbols/main_jar/SubInterfaceOwnJar.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/javassist_symbols/main_jar/src/com/github/javaparser/javasymbolsolver/javassist_symbols/main_jar/SuperClassOwnJar.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/javassistmethoddecl/C.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/pullRequest2398/A.class create mode 100644 javaparser-symbol-solver-testing/src/test/resources/pullRequest2398/A.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/pullRequest2398/B.class create mode 100644 javaparser-symbol-solver-testing/src/test/resources/pullRequest2398/B.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/recursion-issue/Base.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/recursion-issue/Extends.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/recursion-issue/Usage.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/solveMethodDeclaredInEnum/MyEnum.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/symbolsolver_quicksetup/a/src/a.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/symbolsolver_quicksetup/a/src/package_a/a.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/symbolsolver_quicksetup/b/src/b.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/symbolsolver_quicksetup/b/src/package_b/b.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/symbolsolver_quicksetup/c/src/c.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/symbolsolver_quicksetup/c/src/package_c/c.java create mode 100644 javaparser-symbol-solver-testing/src/test/resources/symbolsolver_quicksetup/src/Main.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_CommentsInserter.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_JavaParser.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ParseProblemException.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ParseResult.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ParseStart.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ParserConfiguration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_Position.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_Problem.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_Providers.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_Range.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_AccessSpecifier.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_ArrayBracketPair.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_ArrayCreationLevel.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_CompilationUnit.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_Example.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_ImportDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_Modifier.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_Node.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_PackageDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_UserDataKey.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_body_AnnotationDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_body_AnnotationMemberDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_body_BodyDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_body_ClassOrInterfaceDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_body_ConstructorDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_body_EmptyMemberDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_body_EmptyTypeDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_body_EnumConstantDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_body_EnumDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_body_FieldDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_body_InitializerDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_body_MethodDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_body_Parameter.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_body_TypeDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_body_VariableDeclarator.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_body_VariableDeclaratorId.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_comments_BlockComment.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_comments_Comment.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_comments_CommentsCollection.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_comments_JavadocComment.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_comments_LineComment.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_AnnotationExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_ArrayAccessExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_ArrayCreationExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_ArrayInitializerExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_AssignExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_BinaryExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_BooleanLiteralExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_CastExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_CharLiteralExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_ClassExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_ConditionalExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_DoubleLiteralExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_EnclosedExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_Expression.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_FieldAccessExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_InstanceOfExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_IntegerLiteralExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_IntegerLiteralMinValueExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_LambdaExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_LiteralExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_LongLiteralExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_LongLiteralMinValueExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_MarkerAnnotationExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_MemberValuePair.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_MethodCallExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_MethodReferenceExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_NameExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_NormalAnnotationExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_NullLiteralExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_ObjectCreationExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_QualifiedNameExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_SingleMemberAnnotationExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_StringLiteralExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_SuperExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_ThisExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_TypeExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_UnaryExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_expr_VariableDeclarationExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_nodeTypes_NodeWithAnnotations.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_nodeTypes_NodeWithBlockStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_nodeTypes_NodeWithBody.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_nodeTypes_NodeWithDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_nodeTypes_NodeWithElementType.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_nodeTypes_NodeWithExtends.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_nodeTypes_NodeWithImplements.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_nodeTypes_NodeWithJavaDoc.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_nodeTypes_NodeWithMembers.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_nodeTypes_NodeWithModifiers.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_nodeTypes_NodeWithName.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_nodeTypes_NodeWithParameters.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_nodeTypes_NodeWithStatements.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_nodeTypes_NodeWithThrowable.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_nodeTypes_NodeWithType.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_nodeTypes_NodeWithTypeArguments.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_nodeTypes_NodeWithVariables.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_stmt_AssertStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_stmt_BlockStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_stmt_BreakStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_stmt_CatchClause.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_stmt_ContinueStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_stmt_DoStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_stmt_EmptyStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_stmt_ExplicitConstructorInvocationStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_stmt_ExpressionStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_stmt_ForStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_stmt_ForeachStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_stmt_IfStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_stmt_LabeledStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_stmt_ReturnStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_stmt_Statement.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_stmt_SwitchEntryStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_stmt_SwitchStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_stmt_SynchronizedStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_stmt_ThrowStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_stmt_TryStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_stmt_TypeDeclarationStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_stmt_WhileStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_type_ArrayType.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_type_ClassOrInterfaceType.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_type_IntersectionType.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_type_PrimitiveType.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_type_ReferenceType.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_type_Type.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_type_TypeParameter.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_type_UnionType.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_type_UnknownType.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_type_VoidType.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_type_WildcardType.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_visitor_CloneVisitor.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_visitor_DumpVisitor.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_visitor_EqualsVisitor.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_visitor_GenericVisitor.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_visitor_GenericVisitorAdapter.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_visitor_ModifierVisitorAdapter.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_visitor_TreeVisitor.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_visitor_VoidVisitor.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_ast_visitor_VoidVisitorAdapter.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_utils_ClassUtils.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_utils_Pair.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_utils_PositionUtils.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/expected_output/com_github_javaparser_utils_Utils.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/CommentsInserter.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/JavaParser.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/PackageLocalClasses.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ParseProblemException.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ParseResult.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ParseStart.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ParserConfiguration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/Position.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/Problem.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/Providers.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/Range.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/AccessSpecifier.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/ArrayBracketPair.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/ArrayCreationLevel.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/CompilationUnit.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/Example.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/ImportDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/Modifier.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/Node.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/PackageDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/UserDataKey.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/body/AnnotationDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/body/AnnotationMemberDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/body/BodyDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/body/ClassOrInterfaceDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/body/ConstructorDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/body/EmptyMemberDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/body/EmptyTypeDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/body/EnumConstantDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/body/EnumDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/body/FieldDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/body/InitializerDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/body/MethodDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/body/Parameter.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/body/TypeDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/body/VariableDeclarator.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/body/VariableDeclaratorId.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/comments/BlockComment.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/comments/Comment.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/comments/CommentsCollection.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/comments/JavadocComment.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/comments/LineComment.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/AnnotationExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/ArrayAccessExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/ArrayCreationExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/ArrayInitializerExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/AssignExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/BinaryExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/BooleanLiteralExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/CastExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/CharLiteralExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/ClassExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/ConditionalExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/DoubleLiteralExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/EnclosedExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/Expression.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/FieldAccessExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/InstanceOfExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/IntegerLiteralExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/IntegerLiteralMinValueExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/LambdaExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/LiteralExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/LongLiteralExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/LongLiteralMinValueExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/MarkerAnnotationExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/MemberValuePair.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/MethodCallExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/MethodReferenceExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/NameExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/NormalAnnotationExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/NullLiteralExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/ObjectCreationExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/QualifiedNameExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/SingleMemberAnnotationExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/StringLiteralExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/SuperExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/ThisExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/TypeExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/UnaryExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/expr/VariableDeclarationExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/nodeTypes/NodeWithAnnotations.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/nodeTypes/NodeWithBlockStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/nodeTypes/NodeWithBody.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/nodeTypes/NodeWithDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/nodeTypes/NodeWithElementType.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/nodeTypes/NodeWithExtends.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/nodeTypes/NodeWithImplements.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/nodeTypes/NodeWithJavaDoc.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/nodeTypes/NodeWithMembers.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/nodeTypes/NodeWithModifiers.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/nodeTypes/NodeWithName.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/nodeTypes/NodeWithParameters.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/nodeTypes/NodeWithStatements.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/nodeTypes/NodeWithThrowable.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/nodeTypes/NodeWithType.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/nodeTypes/NodeWithTypeArguments.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/nodeTypes/NodeWithVariables.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/stmt/AssertStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/stmt/BlockStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/stmt/BreakStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/stmt/CatchClause.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/stmt/ContinueStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/stmt/DoStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/stmt/EmptyStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/stmt/ExplicitConstructorInvocationStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/stmt/ExpressionStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/stmt/ForStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/stmt/ForeachStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/stmt/IfStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/stmt/LabeledStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/stmt/ReturnStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/stmt/Statement.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/stmt/SwitchEntryStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/stmt/SwitchStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/stmt/SynchronizedStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/stmt/ThrowStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/stmt/TryStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/stmt/TypeDeclarationStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/stmt/WhileStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/type/ArrayType.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/type/ClassOrInterfaceType.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/type/IntersectionType.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/type/PrimitiveType.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/type/ReferenceType.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/type/Type.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/type/TypeParameter.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/type/UnionType.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/type/UnknownType.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/type/VoidType.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/type/WildcardType.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/visitor/CloneVisitor.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/visitor/DumpVisitor.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/visitor/EqualsVisitor.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/visitor/GenericVisitor.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/visitor/GenericVisitorAdapter.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/visitor/ModifierVisitorAdapter.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/visitor/TreeVisitor.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/visitor/VoidVisitor.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/ast/visitor/VoidVisitorAdapter.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/utils/ClassUtils.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/utils/Pair.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/utils/PositionUtils.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-core/com/github/javaparser/utils/Utils.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-generated-sources/com/github/javaparser/ASTParser.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-generated-sources/com/github/javaparser/ASTParserConstants.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-generated-sources/com/github/javaparser/ASTParserTokenManager.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-generated-sources/com/github/javaparser/JavaCharStream.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-generated-sources/com/github/javaparser/ParseException.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-generated-sources/com/github/javaparser/Provider.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-generated-sources/com/github/javaparser/StreamProvider.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-generated-sources/com/github/javaparser/StringProvider.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-generated-sources/com/github/javaparser/Token.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-generated-sources/com/github/javaparser/TokenMgrError.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_new_src/javaparser-generated-sources/com/github/javaparser/TokenMgrException.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ASTHelper.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_JavaParser.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_Position.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_PositionUtils.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_SourcesHelper.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_AccessSpecifier.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_CompilationUnit.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_DocumentableNode.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_ImportDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_NamedNode.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_Node.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_PackageDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_TreeVisitor.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_TypeParameter.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_body_AnnotableNode.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_body_AnnotationDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_body_AnnotationMemberDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_body_BaseParameter.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_body_BodyDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_body_ClassOrInterfaceDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_body_ConstructorDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_body_EmptyMemberDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_body_EmptyTypeDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_body_EnumConstantDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_body_EnumDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_body_FieldDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_body_InitializerDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_body_MethodDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_body_ModifierSet.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_body_MultiTypeParameter.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_body_Parameter.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_body_TypeDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_body_VariableDeclarator.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_body_VariableDeclaratorId.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_body_WithDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_comments_BlockComment.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_comments_Comment.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_comments_CommentsCollection.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_comments_CommentsParser.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_comments_JavadocComment.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_comments_LineComment.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_AnnotationExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_ArrayAccessExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_ArrayCreationExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_ArrayInitializerExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_AssignExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_BinaryExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_BooleanLiteralExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_CastExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_CharLiteralExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_ClassExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_ConditionalExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_DoubleLiteralExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_EnclosedExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_Expression.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_FieldAccessExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_InstanceOfExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_IntegerLiteralExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_IntegerLiteralMinValueExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_LambdaExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_LiteralExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_LongLiteralExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_LongLiteralMinValueExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_MarkerAnnotationExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_MemberValuePair.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_MethodCallExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_MethodReferenceExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_NameExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_NormalAnnotationExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_NullLiteralExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_ObjectCreationExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_QualifiedNameExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_SingleMemberAnnotationExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_StringLiteralExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_SuperExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_ThisExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_TypeExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_UnaryExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_expr_VariableDeclarationExpr.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_internal_Utils.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_stmt_AssertStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_stmt_BlockStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_stmt_BreakStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_stmt_CatchClause.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_stmt_ContinueStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_stmt_DoStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_stmt_EmptyStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_stmt_ExplicitConstructorInvocationStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_stmt_ExpressionStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_stmt_ForStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_stmt_ForeachStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_stmt_IfStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_stmt_LabeledStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_stmt_ReturnStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_stmt_Statement.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_stmt_SwitchEntryStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_stmt_SwitchStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_stmt_SynchronizedStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_stmt_ThrowStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_stmt_TryStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_stmt_TypeDeclarationStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_stmt_WhileStmt.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_type_ClassOrInterfaceType.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_type_PrimitiveType.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_type_ReferenceType.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_type_Type.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_type_UnknownType.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_type_VoidType.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_type_WildcardType.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_visitor_CloneVisitor.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_visitor_DumpVisitor.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_visitor_EqualsVisitor.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_visitor_GenericVisitor.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_visitor_GenericVisitorAdapter.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_visitor_ModifierVisitorAdapter.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_visitor_VoidVisitor.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/expected_output/com_github_javaparser_ast_visitor_VoidVisitorAdapter.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/generated/com/github/javaparser/ASTParser.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/generated/com/github/javaparser/ASTParserConstants.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/generated/com/github/javaparser/ASTParserTokenManager.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/generated/com/github/javaparser/JavaCharStream.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/generated/com/github/javaparser/ParseException.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/generated/com/github/javaparser/Token.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/generated/com/github/javaparser/TokenMgrError.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ASTHelper.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/JavaParser.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/Position.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/PositionUtils.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/SourcesHelper.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/AccessSpecifier.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/CompilationUnit.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/DocumentableNode.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/ImportDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/NamedNode.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/Node.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/PackageDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/TreeVisitor.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/TypeParameter.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/body/AnnotableNode.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/body/AnnotationDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/body/AnnotationMemberDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/body/BaseParameter.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/body/BodyDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/body/ClassOrInterfaceDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/body/ConstructorDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/body/EmptyMemberDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/body/EmptyTypeDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/body/EnumConstantDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/body/EnumDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/body/FieldDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/body/InitializerDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/body/MethodDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/body/ModifierSet.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/body/MultiTypeParameter.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/body/Parameter.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/body/TypeDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/body/VariableDeclarator.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/body/VariableDeclaratorId.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/body/WithDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/comments/BlockComment.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/comments/Comment.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/comments/CommentsCollection.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/comments/CommentsParser.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/comments/JavadocComment.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/comments/LineComment.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/AnnotationExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/ArrayAccessExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/ArrayCreationExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/ArrayInitializerExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/AssignExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/BinaryExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/BooleanLiteralExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/CastExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/CharLiteralExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/ClassExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/ConditionalExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/DoubleLiteralExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/EnclosedExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/Expression.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/FieldAccessExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/InstanceOfExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/IntegerLiteralExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/IntegerLiteralMinValueExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/LambdaExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/LiteralExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/LongLiteralExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/LongLiteralMinValueExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/MarkerAnnotationExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/MemberValuePair.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/MethodCallExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/MethodReferenceExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/NameExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/NormalAnnotationExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/NullLiteralExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/ObjectCreationExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/QualifiedNameExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/SingleMemberAnnotationExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/StringLiteralExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/SuperExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/ThisExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/TypeExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/UnaryExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/expr/VariableDeclarationExpr.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/internal/Utils.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/stmt/AssertStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/stmt/BlockStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/stmt/BreakStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/stmt/CatchClause.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/stmt/ContinueStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/stmt/DoStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/stmt/EmptyStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/stmt/ExplicitConstructorInvocationStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/stmt/ExpressionStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/stmt/ForStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/stmt/ForeachStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/stmt/IfStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/stmt/LabeledStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/stmt/ReturnStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/stmt/Statement.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/stmt/SwitchEntryStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/stmt/SwitchStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/stmt/SynchronizedStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/stmt/ThrowStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/stmt/TryStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/stmt/TypeDeclarationStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/stmt/WhileStmt.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/type/ClassOrInterfaceType.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/type/PrimitiveType.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/type/ReferenceType.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/type/Type.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/type/UnknownType.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/type/VoidType.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/type/WildcardType.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/visitor/CloneVisitor.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/visitor/DumpVisitor.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/visitor/EqualsVisitor.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/visitor/GenericVisitor.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/visitor/GenericVisitorAdapter.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/visitor/ModifierVisitorAdapter.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/visitor/VoidVisitor.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javaparser_src/proper_source/com/github/javaparser/ast/visitor/VoidVisitorAdapter.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_SourceFileInfoExtractor.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_core_resolution_Context.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_core_resolution_ContextHelper.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_declarations_common_MethodDeclarationCommonLogic.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparser_Navigator.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_DefaultVisitorAdapter.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_JavaParserFacade.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_JavaParserFactory.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_LambdaArgumentTypePlaceholder.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_TypeExtractor.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_UnsolvedSymbolException.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_contexts_AbstractJavaParserContext.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_contexts_AbstractMethodLikeDeclarationContext.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_contexts_AnonymousClassDeclarationContext.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_contexts_CatchClauseContext.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_contexts_ClassOrInterfaceDeclarationContext.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_contexts_CompilationUnitContext.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_contexts_ConstructorContext.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_contexts_ContextHelper.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_contexts_EnumDeclarationContext.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_contexts_FieldAccessContext.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_contexts_ForStatementContext.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_contexts_ForechStatementContext.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_contexts_JavaParserTypeDeclarationAdapter.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_contexts_LambdaExprContext.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_contexts_MethodCallExprContext.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_contexts_MethodContext.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_contexts_StatementContext.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_contexts_SwitchEntryContext.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_contexts_TryWithResourceContext.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_declarations_DefaultConstructorDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_declarations_Helper.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_declarations_JavaParserAnnotationDeclaration.txt create mode 100644 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 create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_declarations_JavaParserClassDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_declarations_JavaParserConstructorDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_declarations_JavaParserEnumConstantDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_declarations_JavaParserEnumDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_declarations_JavaParserFieldDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_declarations_JavaParserInterfaceDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_declarations_JavaParserMethodDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_declarations_JavaParserParameterDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_declarations_JavaParserSymbolDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_declarations_JavaParserTypeAdapter.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_declarations_JavaParserTypeParameter.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_declarations_JavaParserTypeVariableDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_declarators_AbstractSymbolDeclarator.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_declarators_FieldSymbolDeclarator.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_declarators_NoSymbolDeclarator.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_declarators_ParameterSymbolDeclarator.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javaparsermodel_declarators_VariableSymbolDeclarator.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javassistmodel_JavassistClassDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javassistmodel_JavassistConstructorDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javassistmodel_JavassistEnumDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javassistmodel_JavassistFactory.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javassistmodel_JavassistFieldDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javassistmodel_JavassistInterfaceDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javassistmodel_JavassistMethodDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javassistmodel_JavassistParameterDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javassistmodel_JavassistTypeDeclarationAdapter.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javassistmodel_JavassistTypeParameter.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_javassistmodel_JavassistUtils.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_model_typesystem_LazyType.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_model_typesystem_ReferenceTypeImpl.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_reflectionmodel_MyObjectProvider.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_reflectionmodel_ReflectionClassAdapter.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_reflectionmodel_ReflectionClassDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_reflectionmodel_ReflectionConstructorDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_reflectionmodel_ReflectionEnumDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_reflectionmodel_ReflectionFactory.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_reflectionmodel_ReflectionFieldDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_reflectionmodel_ReflectionInterfaceDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_reflectionmodel_ReflectionMethodDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_reflectionmodel_ReflectionMethodResolutionLogic.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_reflectionmodel_ReflectionParameterDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_reflectionmodel_ReflectionTypeParameter.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_reflectionmodel_comparators_ClassComparator.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_reflectionmodel_comparators_MethodComparator.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_reflectionmodel_comparators_ParameterComparator.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_resolution_ConstructorResolutionLogic.txt create mode 100644 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 create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_resolution_SymbolDeclarator.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_resolution_SymbolSolver.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_resolution_typesolvers_CombinedTypeSolver.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_resolution_typesolvers_JarTypeSolver.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_resolution_typesolvers_JavaParserTypeSolver.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_resolution_typesolvers_MemoryTypeSolver.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-core/com_github_javaparser_symbolsolver_resolution_typesolvers_ReflectionTypeSolver.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-logic/com_github_javaparser_symbolsolver_logic_AbstractClassDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-logic/com_github_javaparser_symbolsolver_logic_AbstractTypeDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-logic/com_github_javaparser_symbolsolver_logic_ConfilictingGenericTypesException.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-logic/com_github_javaparser_symbolsolver_logic_FunctionalInterfaceLogic.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-logic/com_github_javaparser_symbolsolver_logic_InferenceContext.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-logic/com_github_javaparser_symbolsolver_logic_InferenceVariableType.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-logic/com_github_javaparser_symbolsolver_logic_ObjectProvider.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_declarations_AccessLevel.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_declarations_AnnotationDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_declarations_ClassDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_declarations_ConstructorDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_declarations_Declaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_declarations_EnumDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_declarations_FieldDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_declarations_HasAccessLevel.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_declarations_InterfaceDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_declarations_MethodAmbiguityException.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_declarations_MethodDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_declarations_MethodLikeDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_declarations_ParameterDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_declarations_ReferenceTypeDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_declarations_TypeDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_declarations_TypeParameterDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_declarations_TypeParametrizable.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_declarations_ValueDeclaration.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_methods_MethodUsage.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_resolution_SymbolReference.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_resolution_TypeSolver.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_resolution_UnsolvedSymbolException.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_resolution_Value.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_typesystem_ArrayType.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_typesystem_LambdaConstraintType.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_typesystem_NullType.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_typesystem_PrimitiveType.txt create mode 100644 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 create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_typesystem_Type.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_typesystem_TypeTransformer.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_typesystem_TypeVariable.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_typesystem_VoidType.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_typesystem_Wildcard.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_typesystem_parametrization_TypeParameterValueProvider.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_typesystem_parametrization_TypeParametersMap.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/expected_output/java-symbol-solver-model/com_github_javaparser_symbolsolver_model_typesystem_parametrization_TypeParametrized.txt create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/SourceFileInfoExtractor.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/core/resolution/Context.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/core/resolution/ContextHelper.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/declarations/common/MethodDeclarationCommonLogic.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparser/Navigator.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparser/package-info.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/DefaultVisitorAdapter.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/JavaParserFacade.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/JavaParserFactory.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/LambdaArgumentTypePlaceholder.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/TypeExtractor.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/UnsolvedSymbolException.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/contexts/AbstractJavaParserContext.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/contexts/AbstractMethodLikeDeclarationContext.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/contexts/AnonymousClassDeclarationContext.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/contexts/CatchClauseContext.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/contexts/ClassOrInterfaceDeclarationContext.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/contexts/CompilationUnitContext.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/contexts/ConstructorContext.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/contexts/ContextHelper.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/contexts/EnumDeclarationContext.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/contexts/FieldAccessContext.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/contexts/ForStatementContext.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/contexts/ForechStatementContext.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/contexts/JavaParserTypeDeclarationAdapter.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/contexts/LambdaExprContext.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/contexts/MethodCallExprContext.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/contexts/MethodContext.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/contexts/StatementContext.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/contexts/SwitchEntryContext.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/contexts/TryWithResourceContext.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/declarations/DefaultConstructorDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/declarations/Helper.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserAnnotationDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserAnonymousClassDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserClassDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserConstructorDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserEnumConstantDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserEnumDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserFieldDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserInterfaceDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserMethodDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserParameterDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserSymbolDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserTypeAdapter.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserTypeParameter.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/declarations/JavaParserTypeVariableDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/declarators/AbstractSymbolDeclarator.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/declarators/FieldSymbolDeclarator.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/declarators/NoSymbolDeclarator.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/declarators/ParameterSymbolDeclarator.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/declarators/VariableSymbolDeclarator.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javaparsermodel/package-info.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javassistmodel/JavassistClassDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javassistmodel/JavassistConstructorDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javassistmodel/JavassistEnumDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javassistmodel/JavassistFactory.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javassistmodel/JavassistFieldDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javassistmodel/JavassistInterfaceDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javassistmodel/JavassistMethodDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javassistmodel/JavassistParameterDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javassistmodel/JavassistTypeDeclarationAdapter.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javassistmodel/JavassistTypeParameter.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javassistmodel/JavassistUtils.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/javassistmodel/package-info.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/model/typesystem/LazyType.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/model/typesystem/ReferenceTypeImpl.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/reflectionmodel/MyObjectProvider.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionClassAdapter.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionClassDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionConstructorDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionEnumDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionFactory.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionFieldDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionInterfaceDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionMethodDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionMethodResolutionLogic.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionParameterDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionTypeParameter.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/reflectionmodel/comparators/ClassComparator.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/reflectionmodel/comparators/MethodComparator.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/reflectionmodel/comparators/ParameterComparator.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/reflectionmodel/package-info.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/resolution/ConstructorResolutionLogic.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/resolution/MethodResolutionLogic.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/resolution/SymbolDeclarator.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/resolution/SymbolSolver.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/resolution/typesolvers/CombinedTypeSolver.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/resolution/typesolvers/JarTypeSolver.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/resolution/typesolvers/JavaParserTypeSolver.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/resolution/typesolvers/MemoryTypeSolver.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/resolution/typesolvers/ReflectionTypeSolver.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-logic/com/github/javaparser/symbolsolver/logic/AbstractClassDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-logic/com/github/javaparser/symbolsolver/logic/AbstractTypeDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-logic/com/github/javaparser/symbolsolver/logic/ConfilictingGenericTypesException.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-logic/com/github/javaparser/symbolsolver/logic/FunctionalInterfaceLogic.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-logic/com/github/javaparser/symbolsolver/logic/InferenceContext.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-logic/com/github/javaparser/symbolsolver/logic/InferenceVariableType.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-logic/com/github/javaparser/symbolsolver/logic/ObjectProvider.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/declarations/AccessLevel.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/declarations/AnnotationDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/declarations/ClassDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/declarations/ConstructorDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/declarations/Declaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/declarations/EnumDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/declarations/FieldDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/declarations/HasAccessLevel.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/declarations/InterfaceDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/declarations/MethodAmbiguityException.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/declarations/MethodDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/declarations/MethodLikeDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/declarations/ParameterDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/declarations/ReferenceTypeDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/declarations/TypeDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/declarations/TypeParameterDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/declarations/TypeParametrizable.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/declarations/ValueDeclaration.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/methods/MethodUsage.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/resolution/SymbolReference.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/resolution/TypeSolver.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/resolution/UnsolvedSymbolException.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/resolution/Value.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/typesystem/ArrayType.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/typesystem/LambdaConstraintType.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/typesystem/NullType.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/typesystem/PrimitiveType.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/typesystem/ReferenceType.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/typesystem/Type.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/typesystem/TypeTransformer.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/typesystem/TypeVariable.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/typesystem/VoidType.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/typesystem/Wildcard.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/typesystem/parametrization/TypeParameterValueProvider.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/typesystem/parametrization/TypeParametersMap.java create mode 100644 javaparser-symbol-solver-testing/src/test/test_sourcecode/javasymbolsolver_0_6_0/src/java-symbol-solver-model/com/github/javaparser/symbolsolver/model/typesystem/parametrization/TypeParametrized.java create mode 100755 mvnw create mode 100644 mvnw.cmd create mode 100644 pom.xml create mode 100644 readme.md create mode 100644 ruleset.xml create mode 100755 run_core_generators.sh create mode 100755 run_core_metamodel_generator.sh create mode 100755 run_release_perform.sh create mode 100755 run_release_prepare.sh create mode 100755 run_release_prepare_non-interactive.sh create mode 100644 scripts/.gitignore create mode 100644 scripts/release-notes-config-id.yml create mode 100644 scripts/release-notes-config-title.yml create mode 100755 scripts/run_generate_changelog_by_milestone_id.sh create mode 100755 scripts/run_generate_changelog_by_milestone_title.sh diff --git a/.mvn/wrapper/MavenWrapperDownloader.java b/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000..b901097 --- /dev/null +++ b/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,117 @@ +/* + * Copyright 2007-present the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import java.net.*; +import java.io.*; +import java.nio.channels.*; +import java.util.Properties; + +public class MavenWrapperDownloader { + + private static final String WRAPPER_VERSION = "0.5.6"; + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" + + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if(mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if(mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if(!outputFile.getParentFile().exists()) { + if(!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { + String username = System.getenv("MVNW_USERNAME"); + char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); + Authenticator.setDefault(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } + }); + } + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..346d645 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.6/apache-maven-3.9.6-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/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..533a738 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,30 @@ +## Getting started +Here is some information that's good to know when contributing to JavaParser: + +- There is some interesting information on the [wiki](https://github.com/javaparser/javaparser/wiki). +- We work on JavaParser because we like to, not because it earns us money. Please remember that we try to run a professional project in our spare time, on a budget of zero. +- Be sure to check [the coding guidelines](https://github.com/javaparser/javaparser/wiki/Coding-Guidelines) which are easily used by installing the formatting rules as described there. +- If you're new and like to casually contribute something, check out the [easy issues](https://github.com/javaparser/javaparser/labels/Easy). +- If you're new and would like to become a member, start your own project that uses JavaParser. +We noticed we get the best feedback from those. +Here are [some fun project ideas](https://github.com/javaparser/javaparser/labels/fun%20project%20idea). +- If you start working on an issue, please say so with a comment in the issue. +- If you know how to fix a problem, please fix it and open a pull request instead of opening an issue. + +Thanks for helping! + +## Contribution Workflow + +Our development workflow is based on Pull Request. If you are not familiar with the Pull Requests, we suggest you to checkout the [Github Documentation](https://help.github.com/articles/creating-a-pull-request/) for more information. + +1. **Fork** the JavaParser project. If you already have a fork, ensure to fetch the latest commits. +2. In your forked project, **create a branch** related to the issue you are working on. This is important to ensure that your pull request will not contain unrelated work. +3. When your work in your branch is done, **push your branch to your forked repository**. +4. Go back to the [javaparser project site](https://github.com/javaparser/javaparser) and it should have a message offering to **create a pull request**. If it doesn't you can [create one manually](https://github.com/javaparser/javaparser/compare). + +### Remember: +- A pull request should include tests. You can either use BDD or JUnit. +- Every pull request will automatically be checked by a few tools. Make sure AppVeyor and Travis are green. +- Pull requests often stay open for at least a few days to give people a chance to review it. +- A pull request is merged when all comments on it have been resolved. +- If you create a pull request for an issue, mention the issue in the format #123 to make github link it automatically. diff --git a/FEATURES.md b/FEATURES.md new file mode 100644 index 0000000..4755a33 --- /dev/null +++ b/FEATURES.md @@ -0,0 +1,309 @@ + +# Features +This page describes the changes introduced within each version. + +Language-related changes should normally have a validator, used in conjunction with the grammar, as part of the parsing process. + +Where a change is not a language-related change _(e.g. JVM and garbage collection changes)_, this is marked as "Not Applicable (NA)". + +## JDK 1.0 - January 1996 +Source: https://en.wikipedia.org/wiki/Java_version_history#JDK_1.0 +## JDK 1.1 - February 1997 +Source: https://en.wikipedia.org/wiki/Java_version_history#JDK_1.1 +## JDK 1.2 - December 1998 +Source: https://en.wikipedia.org/wiki/Java_version_history#J2SE_1.2 +## JDK 1.3 - May 2000 +Source: https://en.wikipedia.org/wiki/Java_version_history#J2SE_1.3 +## JDK 1.4 - February 2002 +Source: https://en.wikipedia.org/wiki/Java_version_history#J2SE_1.4 +## JDK 5 - September 2004 +Source: https://en.wikipedia.org/wiki/Java_version_history#J2SE_5.0 +## JDK 6 - December 2006 +Source: https://en.wikipedia.org/wiki/Java_version_history#Java_SE_6 + +## JDK 7 - July 2011 +Source: https://en.wikipedia.org/wiki/Java_version_history#Java_SE_7 + + +## JDK 8 - March 2014 +Source: https://en.wikipedia.org/wiki/Java_version_history#Java_SE_8 + +- JSR 335, JEP 126: Language-level support for lambda expressions (officially, lambda expressions; unofficially, closures) under Project Lambda and default methods (virtual extension methods) which allow the addition of methods to interfaces without breaking existing implementations. There was an ongoing debate in the Java community on whether to add support for lambda expressions. Sun later declared that lambda expressions would be included in Java and asked for community input to refine the feature. Supporting lambda expressions also enables functional-style operations on streams of elements, such as MapReduce-inspired transformations on collections. Default methods allow an author of an API to add new methods to an interface without breaking the old code using it. Although it was not their primary intent, default methods also allow multiple inheritance of behavior (but not state). +- JSR 223, JEP 174: Project Nashorn, a JavaScript runtime which allows developers to embed JavaScript code within applications +- JSR 308, JEP 104: Annotation on Java types, Unsigned integer arithmetic +- JSR 337, JEP 120: Repeating annotations +- JSR 310, JEP 150: Date and time API +- JEP 178: Statically-linked JNI libraries +- JEP 153: Launch JavaFX applications (direct launching of JavaFX application JARs) +- JEP 122: Remove the permanent generation + +## JDK 9 - September 2017 +Source: https://en.wikipedia.org/wiki/Java_version_history#Java_SE_9 + +- JSR 376: Modularization of the JDK under Project Jigsaw (Java Platform Module System) +- JEP 222: JShell: The Java Shell (a Java REPL) +- JEP 295: Ahead-of-time compilation +- JEP 268: XML catalogs +- JEP 266: More concurrency updates. It includes a Java implementation of Reactive Streams, including a new Flow class that included the interfaces previously provided by Reactive Streams +- JEP 193: Variable handles: define a standard means to invoke the equivalents of various java.util.concurrent.atomic and sun.misc.Unsafe operations +- JEP 282: jlink: The Java Linker: create a tool that can assemble and optimize a set of modules and their dependencies into a custom run-time image. It effectively allows to produce a fully usable executable including the JVM to run it. JavaDB was removed from JDK +- JEP 263: HiDPI graphics: automatic scaling and sizing +- JEP 254: Compact Strings +- JEP 213: Milling Project Coin + +## JDK 10 - March 2018 +Source: https://openjdk.java.net/projects/jdk/10/ + +Java 10 support [complete on 25/Feb/2018](https://github.com/javaparser/javaparser/blob/master/changelog.md#version-3515) + +| JEP | Status | JavaParser Since | Description | +|:--------------------------------------------:|:----------------:|:---------------------------------------------------------------:|---------------------------------------------------------| +| [JEP 286](https://openjdk.java.net/jeps/286) | **Release** | **Supported Since: v3.5.15
Released on: 25/Feb/2018** | **Local-Variable Type Inference** | +| [JEP 296](https://openjdk.java.net/jeps/296) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Consolidate the JDK Forest into a Single Repository~~ | +| [JEP 304](https://openjdk.java.net/jeps/304) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Garbage-Collector Interface~~ | +| [JEP 307](https://openjdk.java.net/jeps/307) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Parallel Full GC for G1~~ | +| [JEP 310](https://openjdk.java.net/jeps/310) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Application Class-Data Sharing~~ | +| [JEP 312](https://openjdk.java.net/jeps/312) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Thread-Local Handshakes~~ | +| [JEP 313](https://openjdk.java.net/jeps/313) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Remove the Native-Header Generation Tool (javah)~~ | +| [JEP 314](https://openjdk.java.net/jeps/314) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Additional Unicode Language-Tag Extensions~~ | +| [JEP 316](https://openjdk.java.net/jeps/316) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Heap Allocation on Alternative Memory Devices~~ | +| [JEP 317](https://openjdk.java.net/jeps/317) | ~~Experimental~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Experimental Java-Based JIT Compiler~~ | +| [JEP 319](https://openjdk.java.net/jeps/319) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Root Certificates~~ | +| [JEP 322](https://openjdk.java.net/jeps/322) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Time-Based Release Versioning~~ | + +## JDK 11 - September 2018 +Source: https://openjdk.java.net/projects/jdk/11/ + +Java 11 support [complete on 19/Aug/2018](https://github.com/javaparser/javaparser/blob/master/changelog.md#version-3618) + +| JEP | Status | JavaParser Since | Description | +|:--------------------------------------------:|:----------------:|:----------------------------------------------------------------------------------------------------:|------------------------------------------------------------------| +| [JEP 323](https://openjdk.java.net/jeps/323) | **Release** | **Supported Since: v3.xx.yy
Released on: dd/mmm/yyyy** | **Local-Variable Syntax for Lambda Parameters** | +| [JEP 327](https://openjdk.java.net/jeps/327) | _Release_ | _Discussion Needed [JEP327](#f_11_JEP327)_ | _Unicode 10_ | +| [JEP 181](https://openjdk.java.net/jeps/181) | _Release_ | _Discussion Needed [JEP181](#f_11_JEP181)_ | _Nest-Based Access Control_ | +| [JEP 309](https://openjdk.java.net/jeps/309) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Dynamic Class-File Constants~~ | +| [JEP 315](https://openjdk.java.net/jeps/315) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Improve Aarch64 Intrinsics~~ | +| [JEP 318](https://openjdk.java.net/jeps/318) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Epsilon: A No-Op Garbage Collector~~ | +| [JEP 320](https://openjdk.java.net/jeps/320) | ~~_Release_~~ | ~~_Not Applicable - Not a language change (NA) [JEP320](#f_11_JEP320)_~~ | ~~Remove the Java EE and CORBA Modules~~ | +| [JEP 321](https://openjdk.java.net/jeps/321) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~HTTP Client (Standard)~~ | +| [JEP 324](https://openjdk.java.net/jeps/324) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Key Agreement with Curve25519 and Curve448~~ | +| [JEP 328](https://openjdk.java.net/jeps/328) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Flight Recorder~~ | +| [JEP 329](https://openjdk.java.net/jeps/329) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~ChaCha20 and Poly1305 Cryptographic Algorithms~~ | +| [JEP 330](https://openjdk.java.net/jeps/330) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Launch Single-File Source-Code Programs~~ | +| [JEP 331](https://openjdk.java.net/jeps/331) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Low-Overhead Heap Profiling~~ | +| [JEP 332](https://openjdk.java.net/jeps/332) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Transport Layer Security (TLS) 1.3~~ | +| [JEP 333](https://openjdk.java.net/jeps/333) | ~~Experimental~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~ZGC: A Scalable Low-Latency Garbage Collector (Experimental)~~ | +| [JEP 335](https://openjdk.java.net/jeps/335) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Deprecate the Nashorn JavaScript Engine~~ | +| [JEP 336](https://openjdk.java.net/jeps/336) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Deprecate the Pack200 Tools and API~~ | + +##### Footnotes: + +- JEP181 - Based on a cursory reading of this JEP, it is unclear if this is a change that affects JavaParser. + Comments/discussion on this are welcomed. [↩](#a_11_JEP181) +- JEP327 - Based on a cursory reading of this JEP, it is unclear if this is a change that affects JavaParser. + Comments/discussion on this are welcomed. [↩](#a_11_JEP327) +- JEP320 - JEP 320 is marked as NA. This is because JavaParser does not make use of classes within these packages, + and any users of JavaParser will need to provide the relevant files in order to do parsing/solving + (e.g. as source files, a jar, or via reflection). [↩](#a_11_JEP320) + + +## JDK 12 - March 2019 +Source: https://openjdk.java.net/projects/jdk/12/ + +Parsing support for Java 12 (including preview features) [complete on 03/Feb/2019](https://github.com/javaparser/javaparser/blob/master/changelog.md#version-3110) + +Resolution support for Java 12 complete on ??/??/2019 + +| JEP | Status | JavaParser Since | Description | +|:--------------------------------------------:|:----------------:|:---------------------------------------------------------------:|-------------------------------------------------------------------| +| [JEP 325](https://openjdk.java.net/jeps/325) | **_Preview_** | **Supported Since: v3.11.0
Released on: 03/Feb/2019** | Switch Expressions (Preview) | +| [JEP 189](https://openjdk.java.net/jeps/189) | ~~Experimental~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Shenandoah: A Low-Pause-Time Garbage Collector (Experimental)~~ | +| [JEP 230](https://openjdk.java.net/jeps/230) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Microbenchmark Suite~~ | +| [JEP 334](https://openjdk.java.net/jeps/334) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~JVM Constants API~~ | +| [JEP 340](https://openjdk.java.net/jeps/340) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~One AArch64 Port, Not Two~~ | +| [JEP 341](https://openjdk.java.net/jeps/341) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Default CDS Archives~~ | +| [JEP 344](https://openjdk.java.net/jeps/344) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Abortable Mixed Collections for G1~~ | +| [JEP 346](https://openjdk.java.net/jeps/346) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Promptly Return Unused Committed Memory from G1~~ | + +## JDK 13 - September 2018 +Source: https://openjdk.java.net/projects/jdk/13/ + +No language specification changes in JDK 13 -- thus no "complete" date. Details of preview support is below. + +| JEP | Status | JavaParser Since | Description | +|:--------------------------------------------:|:-------------:|:---------------------------------------------------------------:|---------------------------------------| +| [JEP 354](https://openjdk.java.net/jeps/354) | **_Preview_** | **Supported Since: v3.11.0
Released on: 03/Feb/2019** | Switch Expressions (Preview) | +| [JEP 355](https://openjdk.java.net/jeps/355) | **_Preview_** | **Supported Since: v3.14.0
Released on: 05/May/2019** | Text Blocks (Preview) | +| [JEP 350](https://openjdk.java.net/jeps/350) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Dynamic CDS Archives~~ | +| [JEP 351](https://openjdk.java.net/jeps/351) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~ZGC: Uncommit Unused Memory~~ | +| [JEP 353](https://openjdk.java.net/jeps/353) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Reimplement the Legacy Socket API~~ | + + + +## JDK 14 - March 2020 +Source: https://openjdk.java.net/projects/jdk/14/ + +Switch support was complete during preview status. + +The preview features of records are work-in-progress. + +| JEP | Status | JavaParser Since | Description | +|:--------------------------------------------:|:---------------:|:-----------------------------------------------------------------------------------------------------------------:|---------------------------------------------------------------| +| [JEP 361](https://openjdk.java.net/jeps/361) | **Release** | **Supported Since: v3.xx.yy
Released on: dd/mmm/yyyy** | **Switch Expressions (Standard)** | +| [JEP 368](https://openjdk.java.net/jeps/368) | **2nd Preview** | **Supported Since: v3.14.0
Released on: 05/May/2019** | **Text Blocks (Second Preview)** | +| [JEP 305](https://openjdk.java.net/jeps/305) | **_Preview_** | **Supported Since: v3.18.0
Released on: 01/Dec/2020** | **Pattern Matching for `instanceof` (Preview)** | +| [JEP 359](https://openjdk.java.net/jeps/359) | **_Preview_** | **Partial Support Since: v3.22.0
Released on: 11/May/2021 [JEP343](#f_14_JEP359)** | **Records (Preview)** | +| [JEP 343](https://openjdk.java.net/jeps/343) | ~~_Incubator_~~ | ~~_Not Applicable (NA)[JEP343](#f_14_JEP343)_~~ | ~~Packaging Tool (Incubator)~~ | +| [JEP 345](https://openjdk.java.net/jeps/345) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~NUMA-Aware Memory Allocation for G1~~ | +| [JEP 349](https://openjdk.java.net/jeps/349) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~JFR Event Streaming~~ | +| [JEP 352](https://openjdk.java.net/jeps/352) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Non-Volatile Mapped Byte Buffers~~ | +| [JEP 358](https://openjdk.java.net/jeps/358) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Helpful NullPointerExceptions~~ | +| [JEP 362](https://openjdk.java.net/jeps/362) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Deprecate the Solaris and SPARC Ports~~ | +| [JEP 363](https://openjdk.java.net/jeps/363) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Remove the Concurrent Mark Sweep (CMS) Garbage Collector~~ | +| [JEP 364](https://openjdk.java.net/jeps/364) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~ZGC on macOS~~ | +| [JEP 365](https://openjdk.java.net/jeps/365) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~ZGC on Windows~~ | +| [JEP 366](https://openjdk.java.net/jeps/366) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Deprecate the ParallelScavenge + SerialOld GC Combination~~ | +| [JEP 367](https://openjdk.java.net/jeps/367) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Remove the Pack200 Tools and API~~ | +| [JEP 370](https://openjdk.java.net/jeps/370) | ~~_Release_~~ | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Foreign-Memory Access API (Incubator)~~ | + +##### Footnotes: + +- JEP343 - JEP 343 is marked as not applicable, as it relates to packaging of apps - e.g. as `.exe`/`.msi`/`.deb`/`.rpm`/`.pkg`/`.dmg`. + The JEP describes the layout/structure of the output file, suggesting that _maybe_ in the future the files may be examined, and _potentially_ used similarly to a `.jar` or set of `.class` files. + This is not going to be actively pursued (_especially_ since this is still in the incubator stage), though tested PRs are always welcome. + [↩](#a_14_JEP343) + + +- JEP359 - The behaviour of records changed between preview/2nd preview/release. + Unless otherwise stated, the JavaParser implementation follows the released behaviour. + Additionally, note that "partial" support refers to javaparser-core being complete since 3.21.0, and javaparser-symbol-solver-core support is TBC. + [↩](#a_14_JEP359) + + + +## JDK 15 - September 2020 +Source: https://openjdk.java.net/projects/jdk/15/ + +Note: Unless otherwise stated, the JavaParser implementations of features follows the released behaviour. + +| JEP | Status | JavaParser Since | Description | +|:--------------------------------------------:|:---------------:|:-----------------------------------------------------------------------------------------------------------------:|--------------------------------------------------------| +| [JEP 378](https://openjdk.java.net/jeps/378) | **_Release_** | **Supported Since: v3.14.0
Released on: 05/May/2019** | **Text Blocks** | +| [JEP 384](https://openjdk.java.net/jeps/384) | **_Release_** | **Partial Support Since: v3.22.0
Released on: 11/May/2021 [JEP384](#f_15_JEP384)** | **Records (Second Preview)** | +| [JEP 375](https://openjdk.java.net/jeps/375) | **_Release_** | **Supported Since: v3.18.0
Released on: 01/Dec/2020** | **Pattern Matching for `instanceof` (Second Preview)** | +| [JEP 360](https://openjdk.java.net/jeps/360) | **_Preview_** | | **Sealed Classes (Preview)** | +| [JEP 339](https://openjdk.java.net/jeps/339) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Edwards-Curve Digital Signature Algorithm (EdDSA)~~ | +| [JEP 371](https://openjdk.java.net/jeps/371) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Hidden Classes~~ | +| [JEP 372](https://openjdk.java.net/jeps/372) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Remove the Nashorn JavaScript Engine~~ | +| [JEP 373](https://openjdk.java.net/jeps/373) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Reimplement the Legacy DatagramSocket API~~ | +| [JEP 374](https://openjdk.java.net/jeps/374) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Disable and Deprecate Biased Locking~~ | +| [JEP 377](https://openjdk.java.net/jeps/377) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~ZGC: A Scalable Low-Latency Garbage Collector~~ | +| [JEP 379](https://openjdk.java.net/jeps/379) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Shenandoah: A Low-Pause-Time Garbage Collector~~ | +| [JEP 381](https://openjdk.java.net/jeps/381) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Remove the Solaris and SPARC Ports~~ | +| [JEP 383](https://openjdk.java.net/jeps/383) | **_Incubator_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Foreign-Memory Access API (Second Incubator)~~ | +| [JEP 385](https://openjdk.java.net/jeps/385) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Deprecate RMI Activation for Removal~~ | + +- JEP384 - The behaviour of records changed between preview/2nd preview/release. + Unless otherwise stated, the JavaParser implementation follows the released behaviour. + Additionally, note that "partial" support refers to javaparser-core being complete since 3.21.0, and javaparser-symbol-solver-core support is TBC. + [↩](#a_15_JEP384) + + + +## JDK 16 - March 2021 +Source: https://openjdk.java.net/projects/jdk/16/ + +Note: Unless otherwise stated, the JavaParser implementations of features follows the released behaviour. + +| JEP | Status | JavaParser Since | Description | +|:--------------------------------------------:|:---------------:|:------------------------------------------------------------------------------------------------------------------------------:|---------------------------------------------------| +| [JEP 395](https://openjdk.java.net/jeps/395) | **_Release_** | **Parser Support Since: v3.22.0
Released on: 11/May/2021, Solving TBC [JEP395](#f_16_JEP395)** | **Records** | +| [JEP 394](https://openjdk.java.net/jeps/394) | **_Release_** | **Supported Since: v3.18.0
Released on: 01/Dec/2020** | **Pattern Matching for `instanceof`** | +| [JEP 397](https://openjdk.java.net/jeps/397) | **2nd Preview** | | **Sealed Classes (Second Preview)** | +| [JEP 338](https://openjdk.java.net/jeps/338) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Vector API (Incubator)~~ | +| [JEP 347](https://openjdk.java.net/jeps/347) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Enable C++14 Language Features~~ | +| [JEP 357](https://openjdk.java.net/jeps/357) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Migrate from Mercurial to Git~~ | +| [JEP 369](https://openjdk.java.net/jeps/369) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Migrate to GitHub~~ | +| [JEP 376](https://openjdk.java.net/jeps/376) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~ZGC: Concurrent Thread-Stack Processing~~ | +| [JEP 380](https://openjdk.java.net/jeps/380) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Unix-Domain Socket Channels~~ | +| [JEP 386](https://openjdk.java.net/jeps/386) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Alpine Linux Port~~ | +| [JEP 387](https://openjdk.java.net/jeps/387) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Elastic Metaspace~~ | +| [JEP 388](https://openjdk.java.net/jeps/388) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Windows/AArch64 Port~~ | +| [JEP 389](https://openjdk.java.net/jeps/389) | **_Incubator_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Foreign Linker API (Incubator)~~ | +| [JEP 390](https://openjdk.java.net/jeps/390) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Warnings for Value-Based Classes~~ | +| [JEP 392](https://openjdk.java.net/jeps/392) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Packaging Tool~~ | +| [JEP 393](https://openjdk.java.net/jeps/393) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Foreign-Memory Access API (Third Incubator)~~ | +| [JEP 396](https://openjdk.java.net/jeps/396) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | ~~Strongly Encapsulate JDK Internals by Default~~ | + +- JEP395 - The behaviour of records changed between preview/2nd preview/release. + Unless otherwise stated, the JavaParser implementation follows the released behaviour. + Additionally, note that "partial" support refers to javaparser-core being complete since 3.21.0, and javaparser-symbol-solver-core support is TBC. + [↩](#a_16_JEP395) + + +## JDK 17 - September 2021 +Source: https://openjdk.java.net/projects/jdk/17/ + +Note: Unless otherwise stated, the JavaParser implementations of features follows the released behaviour. + +| JEP | Status | JavaParser Since | Description | +|:--------------------------------------------:|:-------------------:|:---------------------------------------------------------------:|------------------------------------------------| +| [JEP 306](https://openjdk.java.net/jeps/306) | **_Release_** | | Restore Always-Strict Floating-Point Semantics | +| [JEP 409](https://openjdk.java.net/jeps/409) | **_Release_** | | Sealed Classes | +| [JEP 406](https://openjdk.java.net/jeps/406) | **_Preview_** | | Pattern Matching for `switch` (Preview) | +| [JEP 356](https://openjdk.java.net/jeps/356) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | Enhanced Pseudo-Random Number Generators | +| [JEP 382](https://openjdk.java.net/jeps/382) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | New macOS Rendering Pipeline | +| [JEP 391](https://openjdk.java.net/jeps/391) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | macOS/AArch64 Port | +| [JEP 398](https://openjdk.java.net/jeps/398) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | Deprecate the Applet API for Removal | +| [JEP 403](https://openjdk.java.net/jeps/403) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | Strongly Encapsulate JDK Internals | +| [JEP 407](https://openjdk.java.net/jeps/407) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | Remove RMI Activation | +| [JEP 410](https://openjdk.java.net/jeps/410) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | Remove the Experimental AOT and JIT Compiler | +| [JEP 411](https://openjdk.java.net/jeps/411) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | Deprecate the Security Manager for Removal | +| [JEP 412](https://openjdk.java.net/jeps/412) | **_Incubator_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | Foreign Function & Memory API (Incubator) | +| [JEP 414](https://openjdk.java.net/jeps/414) | **_2nd Incubator_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | Vector API (Second Incubator) | +| [JEP 415](https://openjdk.java.net/jeps/415) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | Context-Specific Deserialization Filters | + + + +## JDK 18 - March 2022 +Source: https://openjdk.java.net/projects/jdk/18/ + +Note: Unless otherwise stated, the JavaParser implementations of features follows the released behaviour. + +### Schedule + + 2021/12/09 Rampdown Phase One (fork from main line) + 2022/01/20 Rampdown Phase Two + 2022/02/10 Initial Release Candidate + 2022/02/24 Final Release Candidate + 2022/03/22 General Availability + + +### Features + +| JEP | Status | JavaParser Since | Description | +|:--------------------------------------------:|:-------------------:|:---------------------------------------------------------------:|--------------------------------------------------| +| [JEP 413](https://openjdk.java.net/jeps/413) | **_Release_** | | Code Snippets in Java API Documentation | +| [JEP 420](https://openjdk.java.net/jeps/420) | **_Preview_** | | Pattern Matching for `switch` (Second Preview) | +| [JEP 400](https://openjdk.java.net/jeps/400) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | UTF-8 by Default | +| [JEP 408](https://openjdk.java.net/jeps/408) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | Simple Web Server | +| [JEP 416](https://openjdk.java.net/jeps/416) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | Reimplement Core Reflection with Method Handles | +| [JEP 417](https://openjdk.java.net/jeps/417) | **_3rd Incubator_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | Vector API (Third Incubator) | +| [JEP 418](https://openjdk.java.net/jeps/418) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | Internet-Address Resolution SPI | +| [JEP 419](https://openjdk.java.net/jeps/419) | **_2nd Incubator_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | Foreign Function & Memory API (Second Incubator) | +| [JEP 421](https://openjdk.java.net/jeps/421) | **_Release_** | ~~_Not Applicable - Not a language specification change (NA)_~~ | Deprecate Finalization for Removal | + + + +## JDK 19 - _targeted for September 2022_ +Source: https://openjdk.java.net/projects/jdk/18/ + +Note: Unless otherwise stated, the JavaParser implementations of features follows the released behaviour. + +### Features + + JEPs targeted to JDK 19, so far + 422: Linux/RISC-V Port + + Last update: 2022/3/18 16:38 UTC + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..012ddda --- /dev/null +++ b/LICENSE @@ -0,0 +1,6 @@ +JavaParser is available either under the terms of the LGPL License or the Apache License. You as the user are entitled to choose the terms under which to adopt JavaParser. + +For details about the LGPL License please refer to LICENSE.LGPL. Please note +that LGPL is just an extension to GPL, located in LICENSE.GPL. + +For details about the Apache License please refer to LICENSE.APACHE diff --git a/LICENSE.APACHE b/LICENSE.APACHE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE.APACHE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSE.GPL b/LICENSE.GPL new file mode 100644 index 0000000..fb1a1b0 --- /dev/null +++ b/LICENSE.GPL @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + Java 1.5 japa.parser and Abstract Syntax Tree + Copyright (C) 2007 J�lio Vilmar Gesser + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Java 1.5 japa.parser and Abstract Syntax Tree Copyright (C) 2007 J�lio Vilmar Gesser + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/LICENSE.LGPL b/LICENSE.LGPL new file mode 100644 index 0000000..b87303c --- /dev/null +++ b/LICENSE.LGPL @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..1548fdd --- /dev/null +++ b/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1 @@ +Fixes #9999. diff --git a/README.md b/README.md deleted file mode 100644 index 9ebb840..0000000 --- a/README.md +++ /dev/null @@ -1 +0,0 @@ -# template-repository \ No newline at end of file diff --git a/appveyor.yml b/appveyor.yml new file mode 100644 index 0000000..9008921 --- /dev/null +++ b/appveyor.yml @@ -0,0 +1,42 @@ +version: '{build}' +os: Windows Server 2012 + +environment: + appveyor_build_worker_cloud: gce + +init: + # Setup autocrlf -- by default, appveyor uses autocrlf input + # ... This affects tests which expect resource files to have the systems's line separator. + - git config --global core.autocrlf true + +install: + # Download maven + - ps: | + Add-Type -AssemblyName System.IO.Compression.FileSystem + if (!(Test-Path -Path "C:\maven" )) { + (new-object System.Net.WebClient).DownloadFile( + 'http://www.us.apache.org/dist/maven/maven-3/3.6.3/binaries/apache-maven-3.6.3-bin.zip', + 'C:\maven-bin.zip' + ) + [System.IO.Compression.ZipFile]::ExtractToDirectory("C:\maven-bin.zip", "C:\maven") + } + # Setup environment variables for Maven and Java + - cmd: SET JAVA_HOME=C:\Program Files\Java\jdk10 + - cmd: SET M2_HOME=C:\maven\apache-maven-3.6.3 + - cmd: SET MAVEN_OPTS=-Xmx1g + - cmd: SET JAVA_OPTS=-Xmx1g + - cmd: SET PATH=C:\maven\apache-maven-3.6.3\bin;%JAVA_HOME%\bin;%PATH% + # Output the git config re: autocrlf to verify the "current" setting + - cmd: git config core.autocrlf + +# Appveyor is used for testing only -- the build script is not required. +build_script: + - echo ignore this + +test_script: + - mvn -B clean install --batch-mode + +# Use of the cache speeds up future tests, meaning that dependencies do not need to be re-downloaded on every run. +cache: + - C:\maven\ + - C:\Users\appveyor\.m2 diff --git a/changelog.md b/changelog.md new file mode 100644 index 0000000..951ede2 --- /dev/null +++ b/changelog.md @@ -0,0 +1,2867 @@ + +Next Release (Version 3.25.11-snapshot) +-------------------------------------- +[issues resolved](https://github.com/javaparser/javaparser/milestone/207?closed=1) + +### Added +### Changed +### Deprecated +### Removed +### Fixed +### Security + + +Version 3.25.10 +--------------- +[issues resolved](https://github.com/javaparser/javaparser/milestone/206?closed=1) + +### Fixed + +* Fix issue 4345 Strange error when trying to find erasure of generic t… (PR [#4362](https://github.com/javaparser/javaparser/pull/4362) by [@jlerbsc](https://github.com/jlerbsc)) +* fix: issue 4358 prevent infinite cycles with static imports (PR [#4359](https://github.com/javaparser/javaparser/pull/4359) by [@kdunee](https://github.com/kdunee)) +* Refactor `ResolvedReferenceType#equals` (PR [#4351](https://github.com/javaparser/javaparser/pull/4351) by [@freya022](https://github.com/freya022)) +* fix: issue 4331 Cannot be 'abstract' and also 'private'. for a private method in an interface (PR [#4332](https://github.com/javaparser/javaparser/pull/4332) by [@jlerbsc](https://github.com/jlerbsc)) + +### Developer Changes + +* chore(deps): bump actions/checkout from 4.1.1 to 4.1.2 (PR [#4341](https://github.com/javaparser/javaparser/pull/4341) by [@dependabot[bot]](https://github.com/apps/dependabot)) + +### :heart: Contributors + +Thank You to all contributors who worked on this release! + +* [@kdunee](https://github.com/kdunee) +* [@freya022](https://github.com/freya022) +* [@jlerbsc](https://github.com/jlerbsc) + + + +Version 3.25.9 +-------------- +[issues resolved](https://github.com/javaparser/javaparser/milestone/205?closed=1) + +### Added + +* Fix: issue #3878 resolve MethodReference in ObjectCreationExpr (PR [#4296](https://github.com/javaparser/javaparser/pull/4296) by [@fishautumn](https://github.com/fishautumn)) + +### Changed + +* Switch order of literals to prevent NullPointerException (PR [#4322](https://github.com/javaparser/javaparser/pull/4322) by [@citizenjosh](https://github.com/citizenjosh)) +* Minor refactoring to use the existing getArgumentPosition method (PR [#4306](https://github.com/javaparser/javaparser/pull/4306) by [@jlerbsc](https://github.com/jlerbsc)) +* Optimize find ancestor (PR [#4294](https://github.com/javaparser/javaparser/pull/4294) by [@magicwerk](https://github.com/magicwerk)) +* refac: Removes useless ExpressionHelper utility class and replaces some explicit casts by using the javaparser API (PR [#4291](https://github.com/javaparser/javaparser/pull/4291) by [@jlerbsc](https://github.com/jlerbsc)) + +### Fixed + +* fix: Dead stores should be removed (sonar rule) (PR [#4329](https://github.com/javaparser/javaparser/pull/4329) by [@jlerbsc](https://github.com/jlerbsc)) +* fix: Replace this if-then-else statement by a single return statement (sonar rule) (PR [#4328](https://github.com/javaparser/javaparser/pull/4328) by [@jlerbsc](https://github.com/jlerbsc)) +* fix: issue 2043 getAccessSpecifier should return public for interface methods (PR [#4317](https://github.com/javaparser/javaparser/pull/4317) by [@jlerbsc](https://github.com/jlerbsc)) +* Further improve correction of whitespace during difference application (PR [#4316](https://github.com/javaparser/javaparser/pull/4316) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: issue #3946 Symbol solver is unable to resolve inherited inner classes (PR [#4314](https://github.com/javaparser/javaparser/pull/4314) by [@jlerbsc](https://github.com/jlerbsc)) +* fix: issue 4311 IllegalStateException when removing all comments with LexicalPreservingPrinter (PR [#4313](https://github.com/javaparser/javaparser/pull/4313) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: issue 3939 SymbolResolver.calculateType(Expression) may fails on first try, then succeed on later tries (PR [#4290](https://github.com/javaparser/javaparser/pull/4290) by [@jlerbsc](https://github.com/jlerbsc)) +* Adds unit test for issue 4284 "ClassCastException when resolving MethodCallExpr inside an enhanced switch statement" (PR [#4285](https://github.com/javaparser/javaparser/pull/4285) by [@jlerbsc](https://github.com/jlerbsc)) +* Change `SwitchStmt` to `SwitchNode` in `SwitchEntryContext` to avoid `ClassCastException` (PR [#4283](https://github.com/javaparser/javaparser/pull/4283) by [@PalashSharma20](https://github.com/PalashSharma20)) + +### Developer Changes + +* chore(deps): bump org.codehaus.mojo:exec-maven-plugin from 3.1.1 to 3.2.0 (PR [#4323](https://github.com/javaparser/javaparser/pull/4323) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): update junit5 monorepo to v5.10.2 (PR [#4307](https://github.com/javaparser/javaparser/pull/4307) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update codecov/codecov-action action to v4 (PR [#4304](https://github.com/javaparser/javaparser/pull/4304) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update actions/cache action to v4 (PR [#4293](https://github.com/javaparser/javaparser/pull/4293) by [@renovate[bot]](https://github.com/apps/renovate)) + +### :heart: Contributors + +Thank You to all contributors who worked on this release! + +* [@citizenjosh](https://github.com/citizenjosh) +* [@magicwerk](https://github.com/magicwerk) +* [@PalashSharma20](https://github.com/PalashSharma20) +* [@jlerbsc](https://github.com/jlerbsc) +* [@fishautumn](https://github.com/fishautumn) + + +Version 3.25.8 +-------------- +[issues resolved](https://github.com/javaparser/javaparser/milestone/204?closed=1) + +### Added + +* feat: creates cache statistics and moves Cache interface to javaparser-core (PR [#4278](https://github.com/javaparser/javaparser/pull/4278) by [@jlerbsc](https://github.com/jlerbsc)) +* feat: Add parseArrayInitializerExpr to JavaParser API (PR [#4276](https://github.com/javaparser/javaparser/pull/4276) by [@iMashtak](https://github.com/iMashtak)) +* feat: A visitor looking for a node by its position in an AST (PR [#4258](https://github.com/javaparser/javaparser/pull/4258) by [@jlerbsc](https://github.com/jlerbsc)) + +### Changed + +* fix: Partial removal of the use of instanceof in favour of the use of the API (PR [#4280](https://github.com/javaparser/javaparser/pull/4280) by [@jlerbsc](https://github.com/jlerbsc)) +* [GHA] Run on java 18 (PR [#4252](https://github.com/javaparser/javaparser/pull/4252) by [@hazendaz](https://github.com/hazendaz)) + +### Fixed + +* fix: issue 4240 Calling resolve on catch block parameter throws exception (PR [#4279](https://github.com/javaparser/javaparser/pull/4279) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: issue 4270 Exception when resolving ObjectCreationExpr with nested varargs (PR [#4273](https://github.com/javaparser/javaparser/pull/4273) by [@jlerbsc](https://github.com/jlerbsc)) +* add Java_18 to yieldSupport (PR [#4262](https://github.com/javaparser/javaparser/pull/4262) by [@Kimmmey](https://github.com/Kimmmey)) +* fix: issue #4245 UnsupportedOperationException with LexicalPreservingPrinter when removing a sealed modified (PR [#4253](https://github.com/javaparser/javaparser/pull/4253) by [@jlerbsc](https://github.com/jlerbsc)) +* [ci] Fix change log released version as 3.25.7 (PR [#4251](https://github.com/javaparser/javaparser/pull/4251) by [@hazendaz](https://github.com/hazendaz)) +* Fix: issue 3278 Lazy types cause stack overflow when trying to find the least upper bound type (PR [#4246](https://github.com/javaparser/javaparser/pull/4246) by [@jlerbsc](https://github.com/jlerbsc)) + +### Developer Changes + +* chore(deps): bump com.google.guava:guava from 32.1.3-jre to 33.0.0-jre (PR [#4264](https://github.com/javaparser/javaparser/pull/4264) by [@dependabot[bot]](https://github.com/apps/dependabot)) + +### Uncategorised + +* Revert "Refactoring: Move cache features to javaparser-core" (PR [#4274](https://github.com/javaparser/javaparser/pull/4274) by [@jlerbsc](https://github.com/jlerbsc)) + +### :heart: Contributors + +Thank You to all contributors who worked on this release! + +* [@hazendaz](https://github.com/hazendaz) +* [@iMashtak](https://github.com/iMashtak) +* [@jlerbsc](https://github.com/jlerbsc) +* [@Kimmmey](https://github.com/Kimmmey) + +Version 3.25.7 +-------------- +[issues resolved](https://github.com/javaparser/javaparser/milestone/203?closed=1) + +### Added + +* [GHA] Remove old comment that is no longer valid around jdks and add jdk 17 (PR [#4226](https://github.com/javaparser/javaparser/pull/4226) by [@hazendaz](https://github.com/hazendaz)) +* Fix: issue 3833 No enum constant com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_18 (PR [#4221](https://github.com/javaparser/javaparser/pull/4221) by [@jlerbsc](https://github.com/jlerbsc)) + +### Changed + +* Refactoring: Move cache features to javaparser-core (PR [#4238](https://github.com/javaparser/javaparser/pull/4238) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: removes reference to coveralls plugin which is not useful because codecov is used to track code coverage (PR [#4235](https://github.com/javaparser/javaparser/pull/4235) by [@jlerbsc](https://github.com/jlerbsc)) +* Uses jakarta.json api, upgrades jakarta.json-api to the latest version & uses new default Eclipse Parsson (PR [#4234](https://github.com/javaparser/javaparser/pull/4234) by [@jlerbsc](https://github.com/jlerbsc)) +* Move mockito to 4.11.0 and handle byte buddy consistently as well as properly define its agent in argLine for surefire (PR [#4228](https://github.com/javaparser/javaparser/pull/4228) by [@hazendaz](https://github.com/hazendaz)) +* Cleanup poms, use jakarta provided (javax namespace), hamcrest follow up, and switch coveralls plugin - Fixes #4111 (PR [#4225](https://github.com/javaparser/javaparser/pull/4225) by [@hazendaz](https://github.com/hazendaz)) +* [pom] Switch from hamcrest-library (deprecated) to hamcrest (PR [#4200](https://github.com/javaparser/javaparser/pull/4200) by [@hazendaz](https://github.com/hazendaz)) +* Putting code in the .orElse that has a side effect that can affect performance (PR [#4199](https://github.com/javaparser/javaparser/pull/4199) by [@jlerbsc](https://github.com/jlerbsc)) + +### Fixed + +* Fix: issue 3650 unreproducible MAVEN_BUILD_TIMESTAMP (PR [#4243](https://github.com/javaparser/javaparser/pull/4243) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: issue 3972 StackOverflowError when resolving type of scope of a MethodCall (PR [#4236](https://github.com/javaparser/javaparser/pull/4236) by [@jlerbsc](https://github.com/jlerbsc)) +* [fix] Jdk 18 enum stub was extended off java 16 post processor not java17 (PR [#4227](https://github.com/javaparser/javaparser/pull/4227) by [@hazendaz](https://github.com/hazendaz)) +* Fix: issue #4047 Symbol Solver mixes name with type (PR [#4206](https://github.com/javaparser/javaparser/pull/4206) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix grammar (PR [#4203](https://github.com/javaparser/javaparser/pull/4203) by [@mernst](https://github.com/mernst)) +* Minor changes : corrupted format, useless cast, javadoc (PR [#4198](https://github.com/javaparser/javaparser/pull/4198) by [@jlerbsc](https://github.com/jlerbsc)) + +### Developer Changes + +* chore(deps): update actions/setup-java action to v4 (PR [#4241](https://github.com/javaparser/javaparser/pull/4241) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): bump org.codehaus.mojo:build-helper-maven-plugin from 3.4.0 to 3.5.0 (PR [#4223](https://github.com/javaparser/javaparser/pull/4223) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* Adds sponsor link to help the project live and grow (PR [#4204](https://github.com/javaparser/javaparser/pull/4204) by [@jlerbsc](https://github.com/jlerbsc)) +* chore(deps): bump org.codehaus.mojo:templating-maven-plugin from 1.0.0 to 3.0.0 (PR [#4195](https://github.com/javaparser/javaparser/pull/4195) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): update junit5 monorepo to v5.10.1 (PR [#4193](https://github.com/javaparser/javaparser/pull/4193) by [@renovate[bot]](https://github.com/apps/renovate)) + +### Uncategorised + +* Added unit tests for visitors (PR [#4239](https://github.com/javaparser/javaparser/pull/4239) by [@4everTheOne](https://github.com/4everTheOne)) +* Unit tests for class GenericListVisitorAdapter (PR [#4237](https://github.com/javaparser/javaparser/pull/4237) by [@4everTheOne](https://github.com/4everTheOne)) +* Update readme.md (PR [#4222](https://github.com/javaparser/javaparser/pull/4222) by [@jlerbsc](https://github.com/jlerbsc)) + +### :heart: Contributors + +Thank You to all contributors who worked on this release! + +* [@hazendaz](https://github.com/hazendaz) +* [@jlerbsc](https://github.com/jlerbsc) +* [@mernst](https://github.com/mernst) +* [@4everTheOne](https://github.com/4everTheOne) + + +Version 3.25.6 +-------------- +[issues resolved](https://github.com/javaparser/javaparser/milestone/202?closed=1) + +### Changed + +* reformat javaconcept take 2 (PR [#4167](https://github.com/javaparser/javaparser/pull/4167) by [@JimmyGan437](https://github.com/JimmyGan437)) +* Using JAXP on XMLPrinter implementation (PR [#4166](https://github.com/javaparser/javaparser/pull/4166) by [@lcbarcellos](https://github.com/lcbarcellos)) +* replace deprecated methond calls to their replacements (PR [#4157](https://github.com/javaparser/javaparser/pull/4157) by [@JimmyGan437](https://github.com/JimmyGan437)) +* feat(#4075): Improve the validation error messages (PR [#4116](https://github.com/javaparser/javaparser/pull/4116) by [@volodya-lombrozo](https://github.com/volodya-lombrozo)) + +### Fixed + +* Fix: issue #2751 new HashSet()" != "new HashSet<>() (PR [#4183](https://github.com/javaparser/javaparser/pull/4183) by [@lcbarcellos](https://github.com/lcbarcellos)) +* Fixes #2625 Add messages to thrown exceptions (PR [#4177](https://github.com/javaparser/javaparser/pull/4177) by [@oannhpham](https://github.com/oannhpham)) +* Fix: issue 4163 Calling MethodDeclaration.getDeclarationAsString leads to MethodDelaration.getComment returning no comment (PR [#4165](https://github.com/javaparser/javaparser/pull/4165) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: issue 3673 isAssignableBy method StackOverflowError (PR [#4156](https://github.com/javaparser/javaparser/pull/4156) by [@jlerbsc](https://github.com/jlerbsc)) +* fix: issue 3184 Unable to get the resolved type of class ResolvedReferenceType from T (PR [#4147](https://github.com/javaparser/javaparser/pull/4147) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: issue #3269 Test resources containing included interfaces do not compile (PR [#4139](https://github.com/javaparser/javaparser/pull/4139) by [@jlerbsc](https://github.com/jlerbsc)) +* CalculateResolvedType Type error (PR [#4138](https://github.com/javaparser/javaparser/pull/4138) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: issue #4036 LeastUpperBoundLogic.lub returns null when matches ConditionalExpr (PR [#4137](https://github.com/javaparser/javaparser/pull/4137) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: issue #2484 SymbolResolver on MethodCallExpr fails if method parameter is of kind Class (PR [#4136](https://github.com/javaparser/javaparser/pull/4136) by [@jlerbsc](https://github.com/jlerbsc)) + +### Developer Changes + +* chore(deps): bump com.google.guava:guava from 32.1.2-jre to 32.1.3-jre (PR [#4154](https://github.com/javaparser/javaparser/pull/4154) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): update actions/checkout action to v4 (PR [#4141](https://github.com/javaparser/javaparser/pull/4141) by [@renovate[bot]](https://github.com/apps/renovate)) + +### :heart: Contributors + +Thank You to all contributors who worked on this release! + +* [@lcbarcellos](https://github.com/lcbarcellos) +* [@volodya-lombrozo](https://github.com/volodya-lombrozo) +* [@JimmyGan437](https://github.com/JimmyGan437) +* [@jlerbsc](https://github.com/jlerbsc) +* [@oannhpham](https://github.com/oannhpham) + + + +Version 3.25.5 +-------------- +[issues resolved](https://github.com/javaparser/javaparser/milestone/201?closed=1) + +### Added + +* fix: issue 4115 ResolvedUnionType should give access to a list of resolved types (PR [#4119](https://github.com/javaparser/javaparser/pull/4119) by [@jlerbsc](https://github.com/jlerbsc)) +* Support getting more annotation default values using reflection (PR [#4103](https://github.com/javaparser/javaparser/pull/4103) by [@freya022](https://github.com/freya022)) + +### Changed + +* Minor refactoring: Simplifies how to group deleted tokens by extracting a method into an independent class (PR [#4134](https://github.com/javaparser/javaparser/pull/4134) by [@jlerbsc](https://github.com/jlerbsc)) +* Replace deprecated command with environment file (PR [#4122](https://github.com/javaparser/javaparser/pull/4122) by [@70825](https://github.com/70825)) +* Fixes missing named constructor in Modifier.java (PR [#4092](https://github.com/javaparser/javaparser/pull/4092) by [@Auties00](https://github.com/Auties00)) + +### Fixed + +* Fix: issue 4133 Top-level class containerType() throws an exception instead of Optional.empty() (PR [#4135](https://github.com/javaparser/javaparser/pull/4135) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: apply multiline strings (PR [#4130](https://github.com/javaparser/javaparser/pull/4130) by [@70825](https://github.com/70825)) +* Fix: issue 3976 Issue resolving implicit generic types (PR [#4128](https://github.com/javaparser/javaparser/pull/4128) by [@jlerbsc](https://github.com/jlerbsc)) +* Add unit test for PR 4091 Fixed missing permits in pretty printer (PR [#4126](https://github.com/javaparser/javaparser/pull/4126) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: issue 4124 UnsupportedOperationException: 'T' is thrown in MethodCallExpr resolve (PR [#4125](https://github.com/javaparser/javaparser/pull/4125) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: issue 4051 Switched upperBounds and lowerBounds on ResolvedTypeP… (PR [#4123](https://github.com/javaparser/javaparser/pull/4123) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix failing test on JDK 17 (PR [#4121](https://github.com/javaparser/javaparser/pull/4121) by [@mahesh-hegde](https://github.com/mahesh-hegde)) +* Fix: issue 3673 isAssignableBy method StackOverflowError (PR [#4118](https://github.com/javaparser/javaparser/pull/4118) by [@jlerbsc](https://github.com/jlerbsc)) +* Orphan comment added when using lexical preservation is not printed (PR [#4114](https://github.com/javaparser/javaparser/pull/4114) by [@jlerbsc](https://github.com/jlerbsc)) +* Fixed missing permits in pretty printer (PR [#4091](https://github.com/javaparser/javaparser/pull/4091) by [@Auties00](https://github.com/Auties00)) + +### Developer Changes + +* chore(deps): update actions/checkout action to v3.6.0 (PR [#4127](https://github.com/javaparser/javaparser/pull/4127) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): bump com.google.guava:guava from 32.1.1-jre to 32.1.2-jre (PR [#4109](https://github.com/javaparser/javaparser/pull/4109) by [@dependabot[bot]](https://github.com/apps/dependabot)) + +### Uncategorised + +* Fix: issue 4104 LPP doesn't handle new switch entries well (PR [#4106](https://github.com/javaparser/javaparser/pull/4106) by [@jlerbsc](https://github.com/jlerbsc)) + +### :heart: Contributors + +Thank You to all contributors who worked on this release! + +* [@freya022](https://github.com/freya022) +* [@Auties00](https://github.com/Auties00) +* [@mahesh-hegde](https://github.com/mahesh-hegde) +* [@jlerbsc](https://github.com/jlerbsc) +* [@70825](https://github.com/70825) + + +Version 3.25.4 +-------------- +[issues resolved](https://github.com/javaparser/javaparser/milestone/200?closed=1) + +### 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) by [@jlerbsc](https://github.com/jlerbsc)) +* Perf: Remove unnecessary methods and quickly return to the Range.cont… (PR [#3996](https://github.com/javaparser/javaparser/pull/3996) by [@jlerbsc](https://github.com/jlerbsc)) + +### Fixed + +* Fix: issue 1843 Problems with hasAnnotation() and hasDirectlyAnnotati… (PR [#4015](https://github.com/javaparser/javaparser/pull/4015) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: Issue 3995 resolving a method call with a variadic argument of p… (PR [#3998](https://github.com/javaparser/javaparser/pull/3998) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: issue 3983 why FieldDeclaration in an interface calling isStatic… (PR [#3986](https://github.com/javaparser/javaparser/pull/3986) by [@jlerbsc](https://github.com/jlerbsc)) + +### Developer Changes + +* chore(deps): bump checkstyle from 10.9.3 to 10.10.0 (PR [#4014](https://github.com/javaparser/javaparser/pull/4014) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): update junit5 monorepo to v5.9.3 (PR [#4012](https://github.com/javaparser/javaparser/pull/4012) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): bump jacoco-maven-plugin from 0.8.9 to 0.8.10 (PR [#4011](https://github.com/javaparser/javaparser/pull/4011) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps-dev): bump okhttp from 4.10.0 to 4.11.0 (PR [#4009](https://github.com/javaparser/javaparser/pull/4009) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): bump codecov/codecov-action from 3.1.2 to 3.1.3 (PR [#4006](https://github.com/javaparser/javaparser/pull/4006) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): bump maven-checkstyle-plugin from 3.2.1 to 3.2.2 (PR [#4005](https://github.com/javaparser/javaparser/pull/4005) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): bump actions/checkout from 3.5.1 to 3.5.2 (PR [#3994](https://github.com/javaparser/javaparser/pull/3994) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): bump actions/checkout from 3.5.0 to 3.5.1 (PR [#3992](https://github.com/javaparser/javaparser/pull/3992) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): bump codecov/codecov-action from 3.1.1 to 3.1.2 (PR [#3988](https://github.com/javaparser/javaparser/pull/3988) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): bump maven-deploy-plugin from 3.1.0 to 3.1.1 (PR [#3985](https://github.com/javaparser/javaparser/pull/3985) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): bump jacoco-maven-plugin from 0.8.8 to 0.8.9 (PR [#3981](https://github.com/javaparser/javaparser/pull/3981) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): bump checkstyle from 10.9.1 to 10.9.3 (PR [#3980](https://github.com/javaparser/javaparser/pull/3980) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): bump maven-resources-plugin from 3.3.0 to 3.3.1 (PR [#3979](https://github.com/javaparser/javaparser/pull/3979) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): bump maven-install-plugin from 3.1.0 to 3.1.1 (PR [#3975](https://github.com/javaparser/javaparser/pull/3975) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): bump maven-release-plugin from 2.5.3 to 3.0.0 (PR [#3965](https://github.com/javaparser/javaparser/pull/3965) by [@dependabot[bot]](https://github.com/apps/dependabot)) + +### Uncategorised + +* add test for showing interface field shall be static & final (PR [#3984](https://github.com/javaparser/javaparser/pull/3984) by [@XenoAmess](https://github.com/XenoAmess)) + +### :heart: Contributors + +Thank You to all contributors who worked on this release! + +* [@kris-scheibe](https://github.com/kris-scheibe) +* [@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) + +### Changed + +* chore(deps): bump maven-scm-plugin from 1.13.0 to 2.0.0 (PR [#3961](https://github.com/javaparser/javaparser/pull/3961) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): bump checkstyle from 10.8.1 to 10.9.1 (PR [#3958](https://github.com/javaparser/javaparser/pull/3958) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): bump actions/checkout from 3.3.0 to 3.4.0 (PR [#3954](https://github.com/javaparser/javaparser/pull/3954) by [@dependabot[bot]](https://github.com/apps/dependabot)) + +### Fixed + +* Fix: issue 3947 MANIFEST.MF points to non-existent URL (PR [#3966](https://github.com/javaparser/javaparser/pull/3966) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: issue 3951 ConfilictingGenericTypesException is thrown when an Object type is expected as a parameter and an interface is provided as the actual parameter (PR [#3963](https://github.com/javaparser/javaparser/pull/3963) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: issue 3949 LexicalPreservingPrinter Ignores Changes to LambdaExp… (PR [#3959](https://github.com/javaparser/javaparser/pull/3959) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: Unit test since Return-Type-Substituable is fully implemented on reference type (PR [#3943](https://github.com/javaparser/javaparser/pull/3943) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: issue on FunctionalInterfaceLogic but waiting for Return-Type-Su… (PR [#3941](https://github.com/javaparser/javaparser/pull/3941) by [@jlerbsc](https://github.com/jlerbsc)) +* Suggested fix: hardcoded specific LambdaExpr case in LexicalDifferenc… (PR [#3938](https://github.com/javaparser/javaparser/pull/3938) by [@blacelle](https://github.com/blacelle)) +* Fix TextBlockLiteralExpr in LexicalDifferenceCalculator (PR [#3937](https://github.com/javaparser/javaparser/pull/3937) by [@blacelle](https://github.com/blacelle)) +* Fix: issue 3919 An array of primitive type cannot be assigned to an array of object (PR [#3933](https://github.com/javaparser/javaparser/pull/3933) by [@jlerbsc](https://github.com/jlerbsc)) + +### Developer Changes + +* chore(deps): update actions/checkout action to v3.5.0 (PR [#3953](https://github.com/javaparser/javaparser/pull/3953) by [@renovate[bot]](https://github.com/apps/renovate)) + +### :heart: Contributors + +Thank You to all contributors who worked on this release! + +* [@blacelle](https://github.com/blacelle) +* [@jlerbsc](https://github.com/jlerbsc) + + +Version 3.25.1 +-------------- +[issues resolved](https://github.com/javaparser/javaparser/milestone/197?closed=1) + +### API or Behaviour Change + +* Fix: Issue 3045 Unexpected exception when solving type inside an Anonymous class (PR [#3896](https://github.com/javaparser/javaparser/pull/3896) by [@jlerbsc](https://github.com/jlerbsc)) + +### Added + +* Improved search for functional interfaces (PR [#3894](https://github.com/javaparser/javaparser/pull/3894) by [@jlerbsc](https://github.com/jlerbsc)) + +### Changed + +* chore(deps): bump maven-compiler-plugin from 3.10.1 to 3.11.0 (PR [#3928](https://github.com/javaparser/javaparser/pull/3928) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): bump checkstyle from 10.7.0 to 10.8.0 (PR [#3927](https://github.com/javaparser/javaparser/pull/3927) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): bump versions-maven-plugin from 2.14.2 to 2.15.0 (PR [#3914](https://github.com/javaparser/javaparser/pull/3914) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): bump maven-javadoc-plugin from 3.4.1 to 3.5.0 (PR [#3906](https://github.com/javaparser/javaparser/pull/3906) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* Refactor: cleanup/refactor code after fixing #3859 (PR [#3886](https://github.com/javaparser/javaparser/pull/3886) by [@abego](https://github.com/abego)) + +### Fixed + +* Fix: issue 3924 Removing ImportDeclaration with Annotated package thr… (PR [#3926](https://github.com/javaparser/javaparser/pull/3926) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: issue 3918 JavaParserTypeDeclarationAdapter resolving wrong Type via Ancestor (PR [#3921](https://github.com/javaparser/javaparser/pull/3921) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: issue 3919 ResolvedType::isAssignableBy(ResolvedType) is wrong f… (PR [#3920](https://github.com/javaparser/javaparser/pull/3920) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: issue 3911 java.lang.UnsupportedOperationException: T[] while resolving generic method with type parameter with arrays like List (PR [#3917](https://github.com/javaparser/javaparser/pull/3917) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: \s escape gives lexical error but should be valid since Java 15 (PR [#3903](https://github.com/javaparser/javaparser/pull/3903) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: Issue 3045 Unexpected exception when solving type inside an Anonymous class (PR [#3896](https://github.com/javaparser/javaparser/pull/3896) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix issue 1883 Finding lambda return type (PR [#3890](https://github.com/javaparser/javaparser/pull/3890) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: issue 1815 ArrayIndexOutOfBoundsException when resolving lambda parameter. This fix is offered by Blackgen (PR [#3888](https://github.com/javaparser/javaparser/pull/3888) by [@jlerbsc](https://github.com/jlerbsc)) + +### Developer Changes + +* chore(deps): bump checkstyle from 10.6.0 to 10.7.0 (PR [#3885](https://github.com/javaparser/javaparser/pull/3885) by [@dependabot[bot]](https://github.com/apps/dependabot)) + +### :heart: Contributors + +Thank You to all contributors who worked on this release! + +* [@abego](https://github.com/abego) +* [@jlerbsc](https://github.com/jlerbsc) + + +Version 3.25.0 +-------------- + +[issues resolved](https://github.com/javaparser/javaparser/milestone/196?closed=1) + +### Added + +* First part of the implementation of least upper bound logic (PR [#3880](https://github.com/javaparser/javaparser/pull/3880) by [@jlerbsc](https://github.com/jlerbsc)) +* feat: Improved support for calculating the type of an object creation… (PR [#3877](https://github.com/javaparser/javaparser/pull/3877) by [@jlerbsc](https://github.com/jlerbsc)) +* feat: Implement addRecord & getRecordByName for CompilationUnit (PR [#3836](https://github.com/javaparser/javaparser/pull/3836) by [@marcluque](https://github.com/marcluque)) +* Support Jigsaw requires static (PR [#3826](https://github.com/javaparser/javaparser/pull/3826) by [@jlerbsc](https://github.com/jlerbsc)) +* Add toDescriptor to ResolvedMethodDeclaration (PR [#3819](https://github.com/javaparser/javaparser/pull/3819) by [@vanHekthor](https://github.com/vanHekthor)) +* Refactoring context (WIP) (PR [#3792](https://github.com/javaparser/javaparser/pull/3792) by [@jlerbsc](https://github.com/jlerbsc)) +* Refactoring context (WIP) (PR [#3782](https://github.com/javaparser/javaparser/pull/3782) by [@jlerbsc](https://github.com/jlerbsc)) +* Refactoring convert to usage (PR [#3774](https://github.com/javaparser/javaparser/pull/3774) by [@jlerbsc](https://github.com/jlerbsc)) +* Simplified usage of class AssociableToAST (PR [#3063](https://github.com/javaparser/javaparser/pull/3063) by [@4everTheOne](https://github.com/4everTheOne)) + +### Changed + +* Revert import related checkstyle rule from error to warning (PR [#3881](https://github.com/javaparser/javaparser/pull/3881) by [@jlerbsc](https://github.com/jlerbsc)) +* Minor refactoring for example to get all parameter types (PR [#3879](https://github.com/javaparser/javaparser/pull/3879) by [@jlerbsc](https://github.com/jlerbsc)) +* Add header and footer methods in comments instead of using literal st… (PR [#3876](https://github.com/javaparser/javaparser/pull/3876) by [@jlerbsc](https://github.com/jlerbsc)) +* In the context of lexical preservation, the CSM token must be added m… (PR [#3874](https://github.com/javaparser/javaparser/pull/3874) by [@jlerbsc](https://github.com/jlerbsc)) +* Refactoring: remove useless code that is already implemented (PR [#3869](https://github.com/javaparser/javaparser/pull/3869) by [@jlerbsc](https://github.com/jlerbsc)) +* Memory usage improvement when printing a node from the LexicalPreserv… (PR [#3858](https://github.com/javaparser/javaparser/pull/3858) by [@jlerbsc](https://github.com/jlerbsc)) +* chore(deps-dev): bump assertj-core from 3.24.1 to 3.24.2 (PR [#3852](https://github.com/javaparser/javaparser/pull/3852) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): bump maven-checkstyle-plugin from 3.2.0 to 3.2.1 (PR [#3846](https://github.com/javaparser/javaparser/pull/3846) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): bump maven-dependency-plugin from 3.4.0 to 3.5.0 (PR [#3845](https://github.com/javaparser/javaparser/pull/3845) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): update junit5 monorepo to v5.9.2 (PR [#3840](https://github.com/javaparser/javaparser/pull/3840) by [@renovate[bot]](https://github.com/apps/renovate)) +* Minor refactoring on Difference class (PR [#3839](https://github.com/javaparser/javaparser/pull/3839) by [@jlerbsc](https://github.com/jlerbsc)) +* chore(deps-dev): bump assertj-core from 3.23.1 to 3.24.1 (PR [#3837](https://github.com/javaparser/javaparser/pull/3837) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): bump actions/checkout from 3.2.0 to 3.3.0 (PR [#3834](https://github.com/javaparser/javaparser/pull/3834) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): bump checkstyle from 10.5.0 to 10.6.0 (PR [#3829](https://github.com/javaparser/javaparser/pull/3829) by [@dependabot[bot]](https://github.com/apps/dependabot)) + +### Fixed + +* Fix: Method hasScope must return true on NodeWithOptionalScope and No… (PR [#3875](https://github.com/javaparser/javaparser/pull/3875) by [@jlerbsc](https://github.com/jlerbsc)) +* fix #3859 UnsupportedOperationException when trying to resolve a type… (PR [#3873](https://github.com/javaparser/javaparser/pull/3873) by [@abego](https://github.com/abego)) +* Fix: issue 3866 Symbol solver is unable to resolve inner classes of ancestors when they are prefixed with a subclass (PR [#3868](https://github.com/javaparser/javaparser/pull/3868) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: issue 3703 Allow removing empty parentheses after removing all pairs from an annotation (PR [#3865](https://github.com/javaparser/javaparser/pull/3865) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: One must be able to know if any resolved type is a boxed primiti… (PR [#3864](https://github.com/javaparser/javaparser/pull/3864) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: Issue 2374 Comments of added Nodes are ignored in LexicalPreserv… (PR [#3856](https://github.com/javaparser/javaparser/pull/3856) by [@jlerbsc](https://github.com/jlerbsc)) +* Checkstyle for unused import (PR [#3841](https://github.com/javaparser/javaparser/pull/3841) by [@4everTheOne](https://github.com/4everTheOne)) +* Update bnd file (PR [#3783](https://github.com/javaparser/javaparser/pull/3783) by [@jlerbsc](https://github.com/jlerbsc)) + +### Developer Changes + +* Update javaparser copyright headers (PR [#3862](https://github.com/javaparser/javaparser/pull/3862) by [@jlerbsc](https://github.com/jlerbsc)) + +### Uncategorised + +* Add test case to verify range calculation on ArrayType (PR [#3828](https://github.com/javaparser/javaparser/pull/3828) by [@jlerbsc](https://github.com/jlerbsc)) +* Add test case to verify that LexicalPreservation supports TextBlock (PR [#3827](https://github.com/javaparser/javaparser/pull/3827) by [@jlerbsc](https://github.com/jlerbsc)) +* Refactoring: Removing useless method convertToUsage in JavaParserFacade (PR [#3780](https://github.com/javaparser/javaparser/pull/3780) by [@jlerbsc](https://github.com/jlerbsc)) + +### :heart: Contributors + +Thank You to all contributors who worked on this release! + +* [@vanHekthor](https://github.com/vanHekthor) +* [@abego](https://github.com/abego) +* [@jlerbsc](https://github.com/jlerbsc) +* [@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) + +### Added + +* Add a method in LexicalPreservingPrinter to know if LPP is available/activated on the specified node (PR [#3823](https://github.com/javaparser/javaparser/pull/3823) by [@jlerbsc](https://github.com/jlerbsc)) +* Handle nested records (PR [#3814](https://github.com/javaparser/javaparser/pull/3814) by [@mernst](https://github.com/mernst)) +* Source printer import ordering strategy (PR [#3807](https://github.com/javaparser/javaparser/pull/3807) by [@4everTheOne](https://github.com/4everTheOne)) + +### Changed + +* chore(deps): bump versions-maven-plugin from 2.14.1 to 2.14.2 (PR [#3817](https://github.com/javaparser/javaparser/pull/3817) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* Enabled import validation (PR [#3812](https://github.com/javaparser/javaparser/pull/3812) by [@4everTheOne](https://github.com/4everTheOne)) +* Part 5 | Import organization (PR [#3805](https://github.com/javaparser/javaparser/pull/3805) by [@4everTheOne](https://github.com/4everTheOne)) +* Part 4 | Import organization (PR [#3804](https://github.com/javaparser/javaparser/pull/3804) by [@4everTheOne](https://github.com/4everTheOne)) +* Part 3 | Import organization (PR [#3803](https://github.com/javaparser/javaparser/pull/3803) by [@4everTheOne](https://github.com/4everTheOne)) +* Part 2 | Import organization (PR [#3802](https://github.com/javaparser/javaparser/pull/3802) by [@4everTheOne](https://github.com/4everTheOne)) +* Part 1 | Import organization (PR [#3801](https://github.com/javaparser/javaparser/pull/3801) by [@4everTheOne](https://github.com/4everTheOne)) +* Checkstyle configuration tweaks (PR [#3799](https://github.com/javaparser/javaparser/pull/3799) by [@4everTheOne](https://github.com/4everTheOne)) +* chore(deps): bump versions-maven-plugin from 2.13.0 to 2.14.1 (PR [#3797](https://github.com/javaparser/javaparser/pull/3797) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): bump actions/checkout from 3.1.0 to 3.2.0 (PR [#3789](https://github.com/javaparser/javaparser/pull/3789) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): bump checkstyle from 8.45.1 to 10.5.0 (PR [#3788](https://github.com/javaparser/javaparser/pull/3788) by [@dependabot[bot]](https://github.com/apps/dependabot)) + +### Fixed + +* explicit use asString for performance (PR [#3821](https://github.com/javaparser/javaparser/pull/3821) by [@dencat](https://github.com/dencat)) +* Fix: issue #3818 Wrong range calculation on ArrayType with multiple d… (PR [#3820](https://github.com/javaparser/javaparser/pull/3820) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: Lexical Preserving Fails To Remove Comment (PR [#3810](https://github.com/javaparser/javaparser/pull/3810) by [@jlerbsc](https://github.com/jlerbsc)) + +### Developer Changes + +* chore(deps): bump versions-maven-plugin from 2.13.0 to 2.14.0 (PR [#3794](https://github.com/javaparser/javaparser/pull/3794) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* Basic CheckStyle validation (PR [#3781](https://github.com/javaparser/javaparser/pull/3781) by [@4everTheOne](https://github.com/4everTheOne)) + +### Uncategorised + +* Fix: 3412 Remove walkmod again (PR [#3806](https://github.com/javaparser/javaparser/pull/3806) by [@jlerbsc](https://github.com/jlerbsc)) + +### :heart: Contributors + +Thank You to all contributors who worked on this release! + +* [@dencat](https://github.com/dencat) +* [@jlerbsc](https://github.com/jlerbsc) +* [@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) + +### Highlights + +* Remove "executable" bit from code files (PR [#3755](https://github.com/javaparser/javaparser/pull/3755) by [@icmdaf](https://github.com/icmdaf)) + +### Added + +* Created TypeSolverBuilder (PR [#3421](https://github.com/javaparser/javaparser/pull/3421) by [@4everTheOne](https://github.com/4everTheOne)) + +### Changed + +* Changing, in test classes, the initialization of the lexical preserva… (PR [#3779](https://github.com/javaparser/javaparser/pull/3779) by [@jlerbsc](https://github.com/jlerbsc)) +* chore(deps): bump maven-dependency-plugin from 3.3.0 to 3.4.0 (PR [#3770](https://github.com/javaparser/javaparser/pull/3770) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): bump maven-install-plugin from 3.0.1 to 3.1.0 (PR [#3756](https://github.com/javaparser/javaparser/pull/3756) by [@dependabot[bot]](https://github.com/apps/dependabot)) + +### Fixed + +* Fix: #3195 Resolved methods in outer classes not inferred correcly (PR [#3778](https://github.com/javaparser/javaparser/pull/3778) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: #3681 LineComment alwaysing trimming content (PR [#3777](https://github.com/javaparser/javaparser/pull/3777) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: #3773 Replacing nodes causes error in lexical preserving printer… (PR [#3776](https://github.com/javaparser/javaparser/pull/3776) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: #2517 Modifying some nodes with the lexicalPreservation enabled … (PR [#3775](https://github.com/javaparser/javaparser/pull/3775) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: #3725 JavaParserFacade var type in for-each loop cannot be resolved (PR [#3768](https://github.com/javaparser/javaparser/pull/3768) by [@abego](https://github.com/abego)) +* Fix: #3216 LexicalPreservingPrinter add Wrong indentation when removing comments (PR [#3766](https://github.com/javaparser/javaparser/pull/3766) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: #3472 Line comment removal causes IllegalStateException with LexicalPreservingPrinter (PR [#3765](https://github.com/javaparser/javaparser/pull/3765) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: #3441 LexicalPreservingPrinter prints wrong output with line com… (PR [#3764](https://github.com/javaparser/javaparser/pull/3764) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: #2137 ClassOrInterfaceDeclaration addMember using index (PR [#3763](https://github.com/javaparser/javaparser/pull/3763) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: #3761 Lexical preserving corrupts source when adding a modifier in first position (PR [#3762](https://github.com/javaparser/javaparser/pull/3762) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: #3693 Removing modifiers from method declaration results in loss… (PR [#3760](https://github.com/javaparser/javaparser/pull/3760) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: #3750 Lexical preserving corrupts source (PR [#3759](https://github.com/javaparser/javaparser/pull/3759) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix: Fix the indentation generated by the LexicalPreservingPrinter wh… (PR [#3758](https://github.com/javaparser/javaparser/pull/3758) by [@jlerbsc](https://github.com/jlerbsc)) + +### Security + +* Remove "executable" bit from code files (PR [#3755](https://github.com/javaparser/javaparser/pull/3755) by [@icmdaf](https://github.com/icmdaf)) + +### :heart: Contributors + +Thank You to all contributors who worked on this release! + +* [@abego](https://github.com/abego) +* [@jlerbsc](https://github.com/jlerbsc) +* [@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) + +### Added + +* [Fixes #3099] Added ability to solve type with a list of expected type arguments (PR [#3213](https://github.com/javaparser/javaparser/pull/3213) by [@4everTheOne](https://github.com/4everTheOne)) +* [Suggestion] NonNull generator for parameters (PR [#3127](https://github.com/javaparser/javaparser/pull/3127) by [@4everTheOne](https://github.com/4everTheOne)) + +### Changed + +* Updated workflow to only run one job per PR (PR [#3744](https://github.com/javaparser/javaparser/pull/3744) by [@4everTheOne](https://github.com/4everTheOne)) +* Remove or comment system.out.println statement in unit tests (PR [#3741](https://github.com/javaparser/javaparser/pull/3741) by [@jlerbsc](https://github.com/jlerbsc)) +* Added Optional method in SymbolReference (PR [#3740](https://github.com/javaparser/javaparser/pull/3740) by [@4everTheOne](https://github.com/4everTheOne)) +* Centralized management of symbol solver exceptions to prevent exception type Erasion (PR [#3731](https://github.com/javaparser/javaparser/pull/3731) by [@jlerbsc](https://github.com/jlerbsc)) + +### Fixed + +* Fix issue #1827 Issue resolving a constructor of a class using generics (PR [#3752](https://github.com/javaparser/javaparser/pull/3752) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix issue #3728 ParseProblemException (PR [#3743](https://github.com/javaparser/javaparser/pull/3743) by [@jlerbsc](https://github.com/jlerbsc)) +* Updated Badge for Build and Coverage (PR [#3742](https://github.com/javaparser/javaparser/pull/3742) by [@4everTheOne](https://github.com/4everTheOne)) +* Position (PR [#3734](https://github.com/javaparser/javaparser/pull/3734) by [@ameliagenova](https://github.com/ameliagenova)) +* Fix part of issue #3721 UnsupportedOperationException while trying to modify the type of a variable (PR [#3726](https://github.com/javaparser/javaparser/pull/3726) by [@jlerbsc](https://github.com/jlerbsc)) +* Implemented isReferenceType in `ResolvedTypeDeclaration` and isTypeParameter in `ResolvedTypeParameterDeclaration` (PR [#3206](https://github.com/javaparser/javaparser/pull/3206) by [@4everTheOne](https://github.com/4everTheOne)) + +### Developer Changes + +* chore(deps): bump versions-maven-plugin from 2.12.0 to 2.13.0 (PR [#3727](https://github.com/javaparser/javaparser/pull/3727) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* Fix maven wrapper not found in generator scripts (PR [#3717](https://github.com/javaparser/javaparser/pull/3717) by [@PPazderski](https://github.com/PPazderski)) +* chore(deps): bump actions/checkout from 3.0.2 to 3.1.0 (PR [#3716](https://github.com/javaparser/javaparser/pull/3716) by [@dependabot[bot]](https://github.com/apps/dependabot)) + +### Uncategorised + +* Change issue 1945 test to paramaterized (PR [#3739](https://github.com/javaparser/javaparser/pull/3739) by [@flanbino](https://github.com/flanbino)) +* More unit tests for JavaToken and CodeGenerationUtils (PR [#3736](https://github.com/javaparser/javaparser/pull/3736) by [@ameliagenova](https://github.com/ameliagenova)) + +### :heart: Contributors + +Thank You to all contributors who worked on this release! + +* [@flanbino](https://github.com/flanbino) +* [@PPazderski](https://github.com/PPazderski) +* [@ameliagenova](https://github.com/ameliagenova) +* [@jlerbsc](https://github.com/jlerbsc) +* [@4everTheOne](https://github.com/4everTheOne) + + + +Version 3.24.7 +-------------- +[issues resolved](https://github.com/javaparser/javaparser/milestone/191?closed=1) + +### Highlights + +* Issue #3415 (PR [#3722](https://github.com/javaparser/javaparser/pull/3722) by [@nelson-ng-96](https://github.com/nelson-ng-96)) + +### Changed + +* Refactoring - use of existing methods (PR [#3697](https://github.com/javaparser/javaparser/pull/3697) by [@jlerbsc](https://github.com/jlerbsc)) +* Refactoring adding convenient methods to know if a DifferenceElement is added, removed or kept (PR [#3695](https://github.com/javaparser/javaparser/pull/3695) by [@jlerbsc](https://github.com/jlerbsc)) + +### Deprecated + +* Issue #3415 (PR [#3722](https://github.com/javaparser/javaparser/pull/3722) by [@nelson-ng-96](https://github.com/nelson-ng-96)) + +### Fixed + +* Fix for ReflectionAnnotationDeclaration getClassName() (PR [#3723](https://github.com/javaparser/javaparser/pull/3723) by [@Blackgen](https://github.com/Blackgen)) +* Fix some yield expressions not recognized (PR [#3714](https://github.com/javaparser/javaparser/pull/3714) by [@PPazderski](https://github.com/PPazderski)) +* Accept final in instanceof pattern (PR [#3713](https://github.com/javaparser/javaparser/pull/3713) by [@PPazderski](https://github.com/PPazderski)) +* [Fix] Avoid test failure due to line separator differences on windows host (PR [#3711](https://github.com/javaparser/javaparser/pull/3711) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix issue #3700 Removing last statement with LexicalPreservingPrinter results in loss of indendation (PR [#3704](https://github.com/javaparser/javaparser/pull/3704) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix issue #3678 Function accepts a configuration but it does not do anything (PR [#3692](https://github.com/javaparser/javaparser/pull/3692) by [@jlerbsc](https://github.com/jlerbsc)) + +### :heart: Contributors + +Thank You to all contributors who worked on this release! + +* [@PPazderski](https://github.com/PPazderski) +* [@nelson-ng-96](https://github.com/nelson-ng-96) +* [@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) + +### API or Behaviour Change + +* Issue #3405 thread safety of pre/postprocessors (incl. breaking change to `Processor` with pre/post processor methods). (PR [#3515](https://github.com/javaparser/javaparser/pull/3515) by [@matozoid](https://github.com/matozoid)) + +### Changed + +* chore(deps): bump javassist from 3.29.0-GA to 3.29.1-GA (PR [#3661](https://github.com/javaparser/javaparser/pull/3661) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): update junit5 monorepo to v5.9.0 (PR [#3645](https://github.com/javaparser/javaparser/pull/3645) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): bump maven-resources-plugin from 3.2.0 to 3.3.0 (PR [#3644](https://github.com/javaparser/javaparser/pull/3644) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* Flexible symbol resolution for declaration types (PR [#3634](https://github.com/javaparser/javaparser/pull/3634) by [@Col-E](https://github.com/Col-E)) +* Minor refactoring to manage check in range and use hasRange method in class CommentsInserter (PR [#3587](https://github.com/javaparser/javaparser/pull/3587) by [@jlerbsc](https://github.com/jlerbsc)) +* Renaming PACKAGE_PRIVATE to NONE (this refers to the discussion in the issue #2242) (PR [#3573](https://github.com/javaparser/javaparser/pull/3573) by [@jlerbsc](https://github.com/jlerbsc)) + +### Fixed + +* Fix typos (PR [#3675](https://github.com/javaparser/javaparser/pull/3675) by [@mernst](https://github.com/mernst)) +* Fix issue #3614 UnsolvedSymbolException when package declaration contains comment (PR [#3671](https://github.com/javaparser/javaparser/pull/3671) by [@jlerbsc](https://github.com/jlerbsc)) +* chore(deps): update dependency org.apache.maven.plugins:maven-install-plugin to v3.0.0 (PR [#3640](https://github.com/javaparser/javaparser/pull/3640) by [@renovate[bot]](https://github.com/apps/renovate)) +* Fix documentation of `JAVA_17` (PR [#3623](https://github.com/javaparser/javaparser/pull/3623) by [@mernst](https://github.com/mernst)) +* Fix issue 3631 NameExpr.resolve() does not take end of inner block scopes into account (PR [#3613](https://github.com/javaparser/javaparser/pull/3613) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix issue #3588 Modifier is removed when removing an annotation (PR [#3600](https://github.com/javaparser/javaparser/pull/3600) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix lambda generic types that are always resolved to the first type param (PR [#3595](https://github.com/javaparser/javaparser/pull/3595) by [@johannescoetzee](https://github.com/johannescoetzee)) +* Fix issue #3489 SourceRoot.tryToParse() fails if the root path ends with a directory that is not a java identifier (PR [#3551](https://github.com/javaparser/javaparser/pull/3551) by [@jlerbsc](https://github.com/jlerbsc)) +* Default pretty printer should print inner-class receiver parameters on constructors (PR [#3527](https://github.com/javaparser/javaparser/pull/3527) by [@kelloggm](https://github.com/kelloggm)) +* Issue #3405 thread safety of pre/postprocessors (incl. breaking change to `Processor` with pre/post processor methods). (PR [#3515](https://github.com/javaparser/javaparser/pull/3515) by [@matozoid](https://github.com/matozoid)) + +### Developer Changes + +* chore(deps): update dependency org.apache.maven.plugins:maven-install-plugin to v3.0.1 (PR [#3641](https://github.com/javaparser/javaparser/pull/3641) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.apache.maven.plugins:maven-deploy-plugin to v3.0.0 (PR [#3639](https://github.com/javaparser/javaparser/pull/3639) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): bump exec-maven-plugin from 3.0.0 to 3.1.0 (PR [#3637](https://github.com/javaparser/javaparser/pull/3637) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): update dependency com.squareup.okhttp3:okhttp to v4.10.0 (PR [#3612](https://github.com/javaparser/javaparser/pull/3612) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency biz.aqute.bnd:bnd-maven-plugin to v6.3.1 (PR [#3607](https://github.com/javaparser/javaparser/pull/3607) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.apache.maven.plugins:maven-surefire-plugin to v3.0.0-m7 (PR [#3605](https://github.com/javaparser/javaparser/pull/3605) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.mockito:mockito-inline to v4.6.1 (PR [#3601](https://github.com/javaparser/javaparser/pull/3601) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency biz.aqute.bnd:bnd-maven-plugin to v6.3.0 (PR [#3598](https://github.com/javaparser/javaparser/pull/3598) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.assertj:assertj-core to v3.23.1 (PR [#3596](https://github.com/javaparser/javaparser/pull/3596) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.assertj:assertj-core to v3.23.0 (PR [#3594](https://github.com/javaparser/javaparser/pull/3594) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.apache.maven.plugins:maven-scm-plugin to v1.13.0 (PR [#3593](https://github.com/javaparser/javaparser/pull/3593) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.mockito:mockito-inline to v4.6.0 (PR [#3589](https://github.com/javaparser/javaparser/pull/3589) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.codehaus.mojo:versions-maven-plugin to v2.11.0 (PR [#3585](https://github.com/javaparser/javaparser/pull/3585) by [@renovate[bot]](https://github.com/apps/renovate)) +* fix(deps): update dependency org.javassist:javassist to v3.29.0-ga (PR [#3581](https://github.com/javaparser/javaparser/pull/3581) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.jbehave:jbehave-core to v4.8.3 (PR [#3574](https://github.com/javaparser/javaparser/pull/3574) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): bump codecov/codecov-action from 3.0.0 to 3.1.0 (PR [#3567](https://github.com/javaparser/javaparser/pull/3567) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): update actions/checkout action to v3.0.2 (PR [#3565](https://github.com/javaparser/javaparser/pull/3565) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.mockito:mockito-inline to v4.5.1 (PR [#3564](https://github.com/javaparser/javaparser/pull/3564) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.apache.maven.plugins:maven-site-plugin to v3.12.0 (PR [#3561](https://github.com/javaparser/javaparser/pull/3561) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.apache.maven.plugins:maven-javadoc-plugin to v3.4.0 (PR [#3560](https://github.com/javaparser/javaparser/pull/3560) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.mockito:mockito-inline to v4.5.0 (PR [#3557](https://github.com/javaparser/javaparser/pull/3557) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update actions/checkout action to v3.0.1 (PR [#3555](https://github.com/javaparser/javaparser/pull/3555) by [@renovate[bot]](https://github.com/apps/renovate)) +* official Apache Maven wrapper (PR [#3552](https://github.com/javaparser/javaparser/pull/3552) by [@sullis](https://github.com/sullis)) +* chore(deps): update codecov/codecov-action action to v3 (PR [#3545](https://github.com/javaparser/javaparser/pull/3545) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.jacoco:jacoco-maven-plugin to v0.8.8 (PR [#3544](https://github.com/javaparser/javaparser/pull/3544) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.apache.maven.plugins:maven-clean-plugin to v3.2.0 (PR [#3542](https://github.com/javaparser/javaparser/pull/3542) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.apache.maven.plugins:maven-surefire-plugin to v3.0.0-m6 (PR [#3541](https://github.com/javaparser/javaparser/pull/3541) by [@renovate[bot]](https://github.com/apps/renovate)) + +### Uncategorised + +* Implemented JavaParserTypeVariableDeclaration getAncestors method (PR [#3060](https://github.com/javaparser/javaparser/pull/3060) by [@4everTheOne](https://github.com/4everTheOne)) + +### :heart: Contributors + +Thank You to all contributors who worked on this release! + +* [@sullis](https://github.com/sullis) +* [@johannescoetzee](https://github.com/johannescoetzee) +* [@kelloggm](https://github.com/kelloggm) +* [@jlerbsc](https://github.com/jlerbsc) +* [@mernst](https://github.com/mernst) +* [@Col-E](https://github.com/Col-E) +* [@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) + +GPG Fingerprint: `253E8E4C6FB28D11748115C1249DEE8E2C07A0A2` + +### API or Behaviour Change + +* Issue #3405 thread safety of pre/postprocessors (incl. breaking change to `Processor` with pre/post processor methods). (PR [#3515](https://github.com/javaparser/javaparser/pull/3515) by [@matozoid](https://github.com/matozoid)) + +### Changed + +* chore(deps): update junit5 monorepo to v5.9.0 (PR [#3645](https://github.com/javaparser/javaparser/pull/3645) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): bump maven-resources-plugin from 3.2.0 to 3.3.0 (PR [#3644](https://github.com/javaparser/javaparser/pull/3644) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* Flexible symbol resolution for declaration types (PR [#3634](https://github.com/javaparser/javaparser/pull/3634) by [@Col-E](https://github.com/Col-E)) +* Minor refactoring to manage check in range and use hasRange method in class CommentsInserter (PR [#3587](https://github.com/javaparser/javaparser/pull/3587) by [@jlerbsc](https://github.com/jlerbsc)) +* Renaming PACKAGE_PRIVATE to NONE (this refers to the discussion in the issue #2242) (PR [#3573](https://github.com/javaparser/javaparser/pull/3573) by [@jlerbsc](https://github.com/jlerbsc)) + +### Fixed + +* chore(deps): update dependency org.apache.maven.plugins:maven-install-plugin to v3.0.0 (PR [#3640](https://github.com/javaparser/javaparser/pull/3640) by [@renovate[bot]](https://github.com/apps/renovate)) +* Fix documentation of `JAVA_17` (PR [#3623](https://github.com/javaparser/javaparser/pull/3623) by [@mernst](https://github.com/mernst)) +* Fix issue 3631 NameExpr.resolve() does not take end of inner block scopes into account (PR [#3613](https://github.com/javaparser/javaparser/pull/3613) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix issue #3588 Modifier is removed when removing an annotation (PR [#3600](https://github.com/javaparser/javaparser/pull/3600) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix lambda generic types that are always resolved to the first type param (PR [#3595](https://github.com/javaparser/javaparser/pull/3595) by [@johannescoetzee](https://github.com/johannescoetzee)) +* Fix issue #3489 SourceRoot.tryToParse() fails if the root path ends with a directory that is not a java identifier (PR [#3551](https://github.com/javaparser/javaparser/pull/3551) by [@jlerbsc](https://github.com/jlerbsc)) +* Default pretty printer should print inner-class receiver parameters on constructors (PR [#3527](https://github.com/javaparser/javaparser/pull/3527) by [@kelloggm](https://github.com/kelloggm)) +* Issue #3405 thread safety of pre/postprocessors (incl. breaking change to `Processor` with pre/post processor methods). (PR [#3515](https://github.com/javaparser/javaparser/pull/3515) by [@matozoid](https://github.com/matozoid)) + +### Developer Changes + +* chore(deps): update dependency org.apache.maven.plugins:maven-install-plugin to v3.0.1 (PR [#3641](https://github.com/javaparser/javaparser/pull/3641) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.apache.maven.plugins:maven-deploy-plugin to v3.0.0 (PR [#3639](https://github.com/javaparser/javaparser/pull/3639) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): bump exec-maven-plugin from 3.0.0 to 3.1.0 (PR [#3637](https://github.com/javaparser/javaparser/pull/3637) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): update dependency com.squareup.okhttp3:okhttp to v4.10.0 (PR [#3612](https://github.com/javaparser/javaparser/pull/3612) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency biz.aqute.bnd:bnd-maven-plugin to v6.3.1 (PR [#3607](https://github.com/javaparser/javaparser/pull/3607) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.apache.maven.plugins:maven-surefire-plugin to v3.0.0-m7 (PR [#3605](https://github.com/javaparser/javaparser/pull/3605) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.mockito:mockito-inline to v4.6.1 (PR [#3601](https://github.com/javaparser/javaparser/pull/3601) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency biz.aqute.bnd:bnd-maven-plugin to v6.3.0 (PR [#3598](https://github.com/javaparser/javaparser/pull/3598) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.assertj:assertj-core to v3.23.1 (PR [#3596](https://github.com/javaparser/javaparser/pull/3596) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.assertj:assertj-core to v3.23.0 (PR [#3594](https://github.com/javaparser/javaparser/pull/3594) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.apache.maven.plugins:maven-scm-plugin to v1.13.0 (PR [#3593](https://github.com/javaparser/javaparser/pull/3593) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.mockito:mockito-inline to v4.6.0 (PR [#3589](https://github.com/javaparser/javaparser/pull/3589) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.codehaus.mojo:versions-maven-plugin to v2.11.0 (PR [#3585](https://github.com/javaparser/javaparser/pull/3585) by [@renovate[bot]](https://github.com/apps/renovate)) +* fix(deps): update dependency org.javassist:javassist to v3.29.0-ga (PR [#3581](https://github.com/javaparser/javaparser/pull/3581) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.jbehave:jbehave-core to v4.8.3 (PR [#3574](https://github.com/javaparser/javaparser/pull/3574) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): bump codecov/codecov-action from 3.0.0 to 3.1.0 (PR [#3567](https://github.com/javaparser/javaparser/pull/3567) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): update actions/checkout action to v3.0.2 (PR [#3565](https://github.com/javaparser/javaparser/pull/3565) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.mockito:mockito-inline to v4.5.1 (PR [#3564](https://github.com/javaparser/javaparser/pull/3564) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.apache.maven.plugins:maven-site-plugin to v3.12.0 (PR [#3561](https://github.com/javaparser/javaparser/pull/3561) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.apache.maven.plugins:maven-javadoc-plugin to v3.4.0 (PR [#3560](https://github.com/javaparser/javaparser/pull/3560) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.mockito:mockito-inline to v4.5.0 (PR [#3557](https://github.com/javaparser/javaparser/pull/3557) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update actions/checkout action to v3.0.1 (PR [#3555](https://github.com/javaparser/javaparser/pull/3555) by [@renovate[bot]](https://github.com/apps/renovate)) +* official Apache Maven wrapper (PR [#3552](https://github.com/javaparser/javaparser/pull/3552) by [@sullis](https://github.com/sullis)) +* chore(deps): update codecov/codecov-action action to v3 (PR [#3545](https://github.com/javaparser/javaparser/pull/3545) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.jacoco:jacoco-maven-plugin to v0.8.8 (PR [#3544](https://github.com/javaparser/javaparser/pull/3544) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.apache.maven.plugins:maven-clean-plugin to v3.2.0 (PR [#3542](https://github.com/javaparser/javaparser/pull/3542) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.apache.maven.plugins:maven-surefire-plugin to v3.0.0-m6 (PR [#3541](https://github.com/javaparser/javaparser/pull/3541) by [@renovate[bot]](https://github.com/apps/renovate)) + +### Uncategorised + +* Implemented JavaParserTypeVariableDeclaration getAncestors method (PR [#3060](https://github.com/javaparser/javaparser/pull/3060) by [@4everTheOne](https://github.com/4everTheOne)) + +### :heart: Contributors + +Thank You to all contributors who worked on this release! + +* [@sullis](https://github.com/sullis) +* [@johannescoetzee](https://github.com/johannescoetzee) +* [@kelloggm](https://github.com/kelloggm) +* [@jlerbsc](https://github.com/jlerbsc) +* [@mernst](https://github.com/mernst) +* [@Col-E](https://github.com/Col-E) +* [@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) + +### API or Behaviour Change + +* Issue #3405 thread safety of pre/postprocessors (incl. breaking change to `Processor` with pre/post processor methods). (PR [#3515](https://github.com/javaparser/javaparser/pull/3515) by [@matozoid](https://github.com/matozoid)) + +### Changed + +* Minor refactoring to manage check in range and use hasRange method in class CommentsInserter (PR [#3587](https://github.com/javaparser/javaparser/pull/3587) by [@jlerbsc](https://github.com/jlerbsc)) +* Renaming PACKAGE_PRIVATE to NONE (this refers to the discussion in the issue #2242) (PR [#3573](https://github.com/javaparser/javaparser/pull/3573) by [@jlerbsc](https://github.com/jlerbsc)) + +### Fixed + +* Fix documentation of `JAVA_17` (PR [#3623](https://github.com/javaparser/javaparser/pull/3623) by [@mernst](https://github.com/mernst)) +* Fix issue 3631 NameExpr.resolve() does not take end of inner block scopes into account (PR [#3613](https://github.com/javaparser/javaparser/pull/3613) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix issue #3588 Modifier is removed when removing an annotation (PR [#3600](https://github.com/javaparser/javaparser/pull/3600) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix lambda generic types that are always resolved to the first type param (PR [#3595](https://github.com/javaparser/javaparser/pull/3595) by [@johannescoetzee](https://github.com/johannescoetzee)) +* Fix issue #3489 SourceRoot.tryToParse() fails if the root path ends with a directory that is not a java identifier (PR [#3551](https://github.com/javaparser/javaparser/pull/3551) by [@jlerbsc](https://github.com/jlerbsc)) +* Default pretty printer should print inner-class receiver parameters on constructors (PR [#3527](https://github.com/javaparser/javaparser/pull/3527) by [@kelloggm](https://github.com/kelloggm)) +* Issue #3405 thread safety of pre/postprocessors (incl. breaking change to `Processor` with pre/post processor methods). (PR [#3515](https://github.com/javaparser/javaparser/pull/3515) by [@matozoid](https://github.com/matozoid)) + +### Developer Changes + +* chore(deps): update actions/checkout action to v3.0.1 (PR [#3555](https://github.com/javaparser/javaparser/pull/3555) by [@renovate[bot]](https://github.com/apps/renovate)) +* official Apache Maven wrapper (PR [#3552](https://github.com/javaparser/javaparser/pull/3552) by [@sullis](https://github.com/sullis)) +* chore(deps): update codecov/codecov-action action to v3 (PR [#3545](https://github.com/javaparser/javaparser/pull/3545) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.jacoco:jacoco-maven-plugin to v0.8.8 (PR [#3544](https://github.com/javaparser/javaparser/pull/3544) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.apache.maven.plugins:maven-clean-plugin to v3.2.0 (PR [#3542](https://github.com/javaparser/javaparser/pull/3542) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.apache.maven.plugins:maven-surefire-plugin to v3.0.0-m6 (PR [#3541](https://github.com/javaparser/javaparser/pull/3541) by [@renovate[bot]](https://github.com/apps/renovate)) + +### :heart: Contributors + +Thank You to all contributors who worked on this release! + +* [@sullis](https://github.com/sullis) +* [@johannescoetzee](https://github.com/johannescoetzee) +* [@kelloggm](https://github.com/kelloggm) +* [@jlerbsc](https://github.com/jlerbsc) +* [@mernst](https://github.com/mernst) +* [@matozoid](https://github.com/matozoid) + +Version 3.24.2 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/188?closed=1) + +GPG Fingerprint: `253E8E4C6FB28D11748115C1249DEE8E2C07A0A2` + +### Added + +* Improve unit test for BlockStmtContextResolutionTest (PR [#3530](https://github.com/javaparser/javaparser/pull/3530) by [@jlerbsc](https://github.com/jlerbsc)) + +### Changed + +* Improve Conditional Operator resolution [JLS 15.25] (PR [#3522](https://github.com/javaparser/javaparser/pull/3522) by [@jlerbsc](https://github.com/jlerbsc)) + +### Fixed + +* Fix issue #3526 Variable or FieldDeclaration is not resolved correctl… (PR [#3529](https://github.com/javaparser/javaparser/pull/3529) by [@jlerbsc](https://github.com/jlerbsc)) + +### Developer Changes + +* Bump jbehave-junit-runner from 2.3.0 to 2.3.1 (PR [#3531](https://github.com/javaparser/javaparser/pull/3531) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* Bump actions/cache from 2.1.7 to 3 (PR [#3525](https://github.com/javaparser/javaparser/pull/3525) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* Update JDK 18 and add JDK 19 feature details to FEATURES.md (PR [#3521](https://github.com/javaparser/javaparser/pull/3521) by [@MysterAitch](https://github.com/MysterAitch)) +* Bump maven-dependency-plugin from 3.2.0 to 3.3.0 (PR [#3514](https://github.com/javaparser/javaparser/pull/3514) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): update dependency org.apache.maven.plugins:maven-dependency-plugin to v3.3.0 (PR [#3512](https://github.com/javaparser/javaparser/pull/3512) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.apache.maven.plugins:maven-compiler-plugin to v3.10.1 (PR [#3511](https://github.com/javaparser/javaparser/pull/3511) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update actions/checkout action (PR [#3508](https://github.com/javaparser/javaparser/pull/3508) by [@renovate[bot]](https://github.com/apps/renovate)) +* Bump bnd-maven-plugin from 6.1.0 to 6.2.0 (PR [#3505](https://github.com/javaparser/javaparser/pull/3505) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): update dependency biz.aqute.bnd:bnd-maven-plugin to v6.2.0 (PR [#3503](https://github.com/javaparser/javaparser/pull/3503) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update actions/setup-java action to v3 (PR [#3502](https://github.com/javaparser/javaparser/pull/3502) by [@renovate[bot]](https://github.com/apps/renovate)) + +### :heart: Contributors + +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) + +### Fixed + +* Adding constructor descriptor (PR [#3499](https://github.com/javaparser/javaparser/pull/3499) by [@kanghj](https://github.com/kanghj)) +* Fix issue #3491 Method has a multidimensional arrays argument in jar … (PR [#3493](https://github.com/javaparser/javaparser/pull/3493) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix issue #3218 GetSourceRoots() does not return all source roots (PR [#3485](https://github.com/javaparser/javaparser/pull/3485) by [@jlerbsc](https://github.com/jlerbsc)) +* Bug in ArrayCreationExpr constructors (PR [#3473](https://github.com/javaparser/javaparser/pull/3473) by [@sergekukharev](https://github.com/sergekukharev)) +* Fix issue 3440 Removing a node with LexicalPreservingPrinter causes UnsupportedOperationException (PR [#3449](https://github.com/javaparser/javaparser/pull/3449) by [@jlerbsc](https://github.com/jlerbsc)) + +### Developer Changes + +* chore(deps): update dependency org.codehaus.mojo:versions-maven-plugin to v2.10.0 (PR [#3517](https://github.com/javaparser/javaparser/pull/3517) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.mockito:mockito-core to v4.4.0 (PR [#3510](https://github.com/javaparser/javaparser/pull/3510) by [@renovate[bot]](https://github.com/apps/renovate)) +* fix(deps): update dependency com.google.guava:guava to v31.1-jre (PR [#3507](https://github.com/javaparser/javaparser/pull/3507) by [@renovate[bot]](https://github.com/apps/renovate)) +* Bump guava from 31.0.1-jre to 31.1-jre (PR [#3506](https://github.com/javaparser/javaparser/pull/3506) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): update dependency org.apache.maven.plugins:maven-site-plugin to v3.11.0 (PR [#3496](https://github.com/javaparser/javaparser/pull/3496) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.apache.maven.plugins:maven-compiler-plugin to v3.10.0 (PR [#3494](https://github.com/javaparser/javaparser/pull/3494) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.apache.maven.plugins:maven-javadoc-plugin to v3.3.2 (PR [#3492](https://github.com/javaparser/javaparser/pull/3492) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.mockito:mockito-core to v4.3.1 (PR [#3481](https://github.com/javaparser/javaparser/pull/3481) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.mockito:mockito-core to v4.3.0 (PR [#3479](https://github.com/javaparser/javaparser/pull/3479) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.codehaus.mojo:versions-maven-plugin to v2.9.0 (PR [#3477](https://github.com/javaparser/javaparser/pull/3477) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.apache.maven.plugins:maven-jar-plugin to v3.2.2 (PR [#3470](https://github.com/javaparser/javaparser/pull/3470) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.apache.maven.plugins:maven-compiler-plugin to v3.9.0 (PR [#3469](https://github.com/javaparser/javaparser/pull/3469) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency com.helger.maven:ph-javacc-maven-plugin to v4.1.5 (PR [#3468](https://github.com/javaparser/javaparser/pull/3468) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency com.github.javaparser:javaparser-parent to v3 (PR [#3465](https://github.com/javaparser/javaparser/pull/3465) by [@renovate[bot]](https://github.com/apps/renovate)) +* Partial revert of #3462 (removed GitHub Action) (PR [#3464](https://github.com/javaparser/javaparser/pull/3464) by [@MysterAitch](https://github.com/MysterAitch)) +* Updated release script to be non-interactive, and added option to use a manually-triggered GitHub Action to build a release (PR [#3462](https://github.com/javaparser/javaparser/pull/3462) by [@MysterAitch](https://github.com/MysterAitch)) +* chore(deps): update dependency org.apache.maven.plugins:maven-jar-plugin to v3.2.1 (PR [#3459](https://github.com/javaparser/javaparser/pull/3459) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.codehaus.mojo:build-helper-maven-plugin to v3.3.0 (PR [#3458](https://github.com/javaparser/javaparser/pull/3458) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.assertj:assertj-core to v3.22.0 (PR [#3457](https://github.com/javaparser/javaparser/pull/3457) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.apache.maven.plugins:maven-scm-plugin to v1.12.2 (PR [#3456](https://github.com/javaparser/javaparser/pull/3456) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.apache.maven.plugins:maven-deploy-plugin to v3.0.0-m2 (PR [#3453](https://github.com/javaparser/javaparser/pull/3453) by [@renovate[bot]](https://github.com/apps/renovate)) + +### Uncategorised + +* Fix the release gha, originally submitted in #3462 (PR [#3463](https://github.com/javaparser/javaparser/pull/3463) by [@MysterAitch](https://github.com/MysterAitch)) +* Update changelog.md to contain 3.24.0 changes, and prepare for 3.24.1 (PR [#3461](https://github.com/javaparser/javaparser/pull/3461) by [@MysterAitch](https://github.com/MysterAitch)) +* Update changelog.md (PR [#3460](https://github.com/javaparser/javaparser/pull/3460) by [@MysterAitch](https://github.com/MysterAitch)) + +### :heart: Contributors + +Thank You to all contributors who worked on this release! + +* [@MysterAitch](https://github.com/MysterAitch) +* [@jlerbsc](https://github.com/jlerbsc) +* [@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) + +### Added + +* Add erasure on parametrized type (PR [#3438](https://github.com/javaparser/javaparser/pull/3438) by [@jlerbsc](https://github.com/jlerbsc)) +* Add test cases for `NoChange` API (PR [#3431](https://github.com/javaparser/javaparser/pull/3431) by [@jlerbsc](https://github.com/jlerbsc)) + +### Changed + +* Minor refactoring on `LexicalreservingPrinter` especially in the class `Difference` (PR [#3424](https://github.com/javaparser/javaparser/pull/3424) by [@jlerbsc](https://github.com/jlerbsc)) +* Update the readme with `@pedrombmachado` 's suggestions (#3357), and also to switch from `mvn` to `mvnw` within some sample instructions (PR [#3420](https://github.com/javaparser/javaparser/pull/3420) by [@MysterAitch](https://github.com/MysterAitch)) +* Reducing deeply nested logic in `MethodResolutionLogic` (work in progress) (PR [#3411](https://github.com/javaparser/javaparser/pull/3411) by [@jlerbsc](https://github.com/jlerbsc)) +* Reducing deeply nested logic in `MethodResolutionLogic` (PR [#3409](https://github.com/javaparser/javaparser/pull/3409) by [@jlerbsc](https://github.com/jlerbsc)) +* Improved `RemoveMethodGenerator` and `ReplaceMethodGenerator` to only override super when needed. (PR [#3248](https://github.com/javaparser/javaparser/pull/3248) by [@4everTheOne](https://github.com/4everTheOne)) +* Reduced complexity for methods in `JavaParserFacade` (PR [#3204](https://github.com/javaparser/javaparser/pull/3204) by [@4everTheOne](https://github.com/4everTheOne)) + +### Fixed + +* Fix issue #3436 `getAncestors()`/`getAllAncestors()` does not work if base class starts with the same name (PR [#3437](https://github.com/javaparser/javaparser/pull/3437) by [@jlerbsc](https://github.com/jlerbsc)) +* Add a missing `hashCode()` method (PR [#3432](https://github.com/javaparser/javaparser/pull/3432) by [@msridhar](https://github.com/msridhar)) +* Call `orElse()` instead of `orElseGet()` (PR [#3430](https://github.com/javaparser/javaparser/pull/3430) by [@msridhar](https://github.com/msridhar)) +* Fix issue #3408 `LexicalPreservationPrinter` fails to add annotation to a class field decalared with fully qualified name (PR [#3429](https://github.com/javaparser/javaparser/pull/3429) by [@jlerbsc](https://github.com/jlerbsc)) +* Issue #3419 - Fixed bug in `Difference.java` (PR [#3428](https://github.com/javaparser/javaparser/pull/3428) by [@4everTheOne](https://github.com/4everTheOne)) +* Issue #3406 `ParseProblemException` when parsing char `\u005cn` (PR [#3407](https://github.com/javaparser/javaparser/pull/3407) by [@apixandru](https://github.com/apixandru)) +* Fix issue #3399 Failed to resolve methods that evaluate as argument (PR [#3401](https://github.com/javaparser/javaparser/pull/3401) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix resoure leak due to `File.walk` (PR [#3398](https://github.com/javaparser/javaparser/pull/3398) by [@lujiefsi](https://github.com/lujiefsi)) +* Fix issue #2259 Type resolution issue when type of formal parameter is Object (PR [#3397](https://github.com/javaparser/javaparser/pull/3397) by [@jlerbsc](https://github.com/jlerbsc)) +* Fixes an issue where `JavaParserTypeSolver` ignores the character encoding configuration. (PR [#3396](https://github.com/javaparser/javaparser/pull/3396) by [@crucoba](https://github.com/crucoba)) +* Issue #3272 resolve lambda exp type (PR [#3273](https://github.com/javaparser/javaparser/pull/3273) by [@si-e](https://github.com/si-e)) +* Issue #3200 `this` exp in anonymous class (PR [#3268](https://github.com/javaparser/javaparser/pull/3268) by [@si-e](https://github.com/si-e)) + +### Developer Changes + +* Partial revert of #3462 (removed GitHub Action) (PR [#3464](https://github.com/javaparser/javaparser/pull/3462) by [@MysterAitch](https://github.com/MysterAitch)) +* Updated release script to be non-interactive, and added option to use a manually-triggered GitHub Action to build a release (PR [#3462](https://github.com/javaparser/javaparser/pull/3462) by [@MysterAitch](https://github.com/MysterAitch)) +* chore(deps): update dependency org.apache.maven.plugins:maven-jar-plugin to v3.2.1 (PR [#3459](https://github.com/javaparser/javaparser/pull/3459) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.codehaus.mojo:build-helper-maven-plugin to v3.3.0 (PR [#3458](https://github.com/javaparser/javaparser/pull/3458) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.assertj:assertj-core to v3.22.0 (PR [#3457](https://github.com/javaparser/javaparser/pull/3457) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.apache.maven.plugins:maven-scm-plugin to v1.12.2 (PR [#3456](https://github.com/javaparser/javaparser/pull/3456) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.apache.maven.plugins:maven-deploy-plugin to v3.0.0-m2 (PR [#3453](https://github.com/javaparser/javaparser/pull/3453) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.apache.maven.plugins:maven-site-plugin to v3.10.0 (PR [#3448](https://github.com/javaparser/javaparser/pull/3448) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.mockito:mockito-core to v4.2.0 (PR [#3442](https://github.com/javaparser/javaparser/pull/3442) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update junit5 monorepo to v5.8.2 (PR [#3425](https://github.com/javaparser/javaparser/pull/3425) by [@renovate[bot]](https://github.com/apps/renovate)) +* Update / document `codecov.yml` (PR [#3418](https://github.com/javaparser/javaparser/pull/3418) by [@MysterAitch](https://github.com/MysterAitch)) +* chore(deps): update actions/cache action to v2.1.7 (PR [#3417](https://github.com/javaparser/javaparser/pull/3417) by [@renovate[bot]](https://github.com/apps/renovate)) +* Bump bnd-maven-plugin from 6.0.0 to 6.1.0 (PR [#3416](https://github.com/javaparser/javaparser/pull/3416) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): update dependency biz.aqute.bnd:bnd-maven-plugin to v6.1.0 (PR [#3414](https://github.com/javaparser/javaparser/pull/3414) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency com.squareup.okhttp3:okhttp to v4.9.3 (PR [#3413](https://github.com/javaparser/javaparser/pull/3413) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update actions/checkout action to v2.4.0 (PR [#3402](https://github.com/javaparser/javaparser/pull/3402) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update actions/checkout action to v2.3.5 (PR [#3395](https://github.com/javaparser/javaparser/pull/3395) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.mockito:mockito-core to v4 (PR [#3393](https://github.com/javaparser/javaparser/pull/3393) by [@renovate[bot]](https://github.com/apps/renovate)) + +### :heart: Contributors + +Thank You to all contributors who worked on this release! + +* [@crucoba](https://github.com/crucoba) +* [@msridhar](https://github.com/msridhar) +* [@MysterAitch](https://github.com/MysterAitch) +* [@lujiefsi](https://github.com/lujiefsi) +* [@apixandru](https://github.com/apixandru) +* [@si-e](https://github.com/si-e) +* [@jlerbsc](https://github.com/jlerbsc) +* [@4everTheOne](https://github.com/4everTheOne) + + + +Version 3.23.1 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/186?closed=1) + +### Fixed + +* `record` may be used as variable name in Java 16 (PR [#3362](https://github.com/javaparser/javaparser/pull/3362) by [@koppor](github.com/koppor/)) + +### API or Behaviour Change + +* Java 11 is now the most used version (PR [#3301](https://github.com/javaparser/javaparser/pull/3301) by [@matozoid](https://github.com/matozoid)) + +### Added + +* Manage `@Inherited` annotation to prepare the fix on the issue 1843 (PR [#3383](https://github.com/javaparser/javaparser/pull/3383) by [@jlerbsc](https://github.com/jlerbsc)) + +### Changed + +* Configurable caching system for type solvers (PR [#3343](https://github.com/javaparser/javaparser/pull/3343) by [@4everTheOne](https://github.com/4everTheOne)) +* Java 11 is now the most used version (PR [#3301](https://github.com/javaparser/javaparser/pull/3301) by [@matozoid](https://github.com/matozoid)) + +### Fixed + +* Fix issue 3387 LexicalPreservingPrinter adds wrong indentation when adding new comments (PR [#3392](https://github.com/javaparser/javaparser/pull/3392) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix issue 2360 Symbol Solver is missing promotion of byte, char, and short in unary expressions (PR [#3384](https://github.com/javaparser/javaparser/pull/3384) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix "record" as non-type identifier in Java 16 (PR [#3362](https://github.com/javaparser/javaparser/pull/3362) by [@koppor](https://github.com/koppor)) +* Fix issue 3358 LexicalPreservingPrinter error on ArrayType (PR [#3359](https://github.com/javaparser/javaparser/pull/3359) by [@jlerbsc](https://github.com/jlerbsc)) + +### Developer Changes + +* generate changelog for milestones - scripts included to do this by milestone id, milestone title, and a github action to add the output to a draft snapshot release (PR [#3391](https://github.com/javaparser/javaparser/pull/3391) by [@MysterAitch](https://github.com/MysterAitch)) +* Bump bnd-maven-plugin from 5.3.0 to 6.0.0 (PR [#3390](https://github.com/javaparser/javaparser/pull/3390) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): update dependency biz.aqute.bnd:bnd-maven-plugin to v6 (PR [#3389](https://github.com/javaparser/javaparser/pull/3389) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency com.squareup.okhttp3:okhttp to v4.9.2 (PR [#3388](https://github.com/javaparser/javaparser/pull/3388) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency com.google.guava:guava to v31.0.1-jre (PR [#3385](https://github.com/javaparser/javaparser/pull/3385) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency com.google.guava:guava to v31 (PR [#3381](https://github.com/javaparser/javaparser/pull/3381) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update junit5 monorepo to v5.8.1 (PR [#3380](https://github.com/javaparser/javaparser/pull/3380) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.assertj:assertj-core to v3.21.0 (PR [#3378](https://github.com/javaparser/javaparser/pull/3378) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.apache.maven.plugins:maven-scm-plugin to v1.12.0 (PR [#3376](https://github.com/javaparser/javaparser/pull/3376) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update codecov/codecov-action action to v2.1.0 (PR [#3373](https://github.com/javaparser/javaparser/pull/3373) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update junit5 monorepo to v5.8.0 (PR [#3372](https://github.com/javaparser/javaparser/pull/3372) by [@renovate[bot]](https://github.com/apps/renovate)) +* remove accidentally-added pom release backup files, and added it to gitignore to prevent them being re-added (PR [#3370](https://github.com/javaparser/javaparser/pull/3370) by [@MysterAitch](https://github.com/MysterAitch)) +* chore(deps): update dependency org.apache.maven.plugins:maven-javadoc-plugin to v3.3.1 (PR [#3368](https://github.com/javaparser/javaparser/pull/3368) by [@renovate[bot]](https://github.com/apps/renovate)) +* Reduce mvn verbosity on GitHub actions (and switch to mvnw) (PR [#3363](https://github.com/javaparser/javaparser/pull/3363) by [@koppor](https://github.com/koppor)) + +### Uncategorised + +* Prepare changelog for next version (PR [#3354](https://github.com/javaparser/javaparser/pull/3354) by [@MysterAitch](https://github.com/MysterAitch)) + +### :heart: Contributors + +Thank You to all contributors who worked on this release! + +* [@MysterAitch](https://github.com/MysterAitch) +* [@jlerbsc](https://github.com/jlerbsc) +* [@koppor](https://github.com/koppor) +* [@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) + +### Added + +* Improving `toString` on CSM classes (PR [#3315](https://github.com/javaparser/javaparser/pull/3315) by [@jlerbsc](https://github.com/jlerbsc)) +* Add test case for issue #2210 Resolution of Method References (PR [#3310](https://github.com/javaparser/javaparser/pull/3310) by [@jlerbsc](https://github.com/jlerbsc)) +* Implemented method reference resolution on expressions (PR [#3307](https://github.com/javaparser/javaparser/pull/3307) by [@maartenc](https://github.com/maartenc)) +* Define if a field is volatile through the ResolvedFieldDeclaration interface - from issue #3240 (PR [#3276](https://github.com/javaparser/javaparser/pull/3276) by [@jlerbsc](https://github.com/jlerbsc)) +* Implemented logic for internalTypes in `JavaParserAnnotationDeclaration` and `JavassistAnnotationDeclaration` (PR [#3215](https://github.com/javaparser/javaparser/pull/3215) by [@4everTheOne](https://github.com/4everTheOne)) + +### Changed + +* Check if ancestor also for super class (PR [#3324](https://github.com/javaparser/javaparser/pull/3324) by [@ReallyLiri](https://github.com/ReallyLiri)) +* Remove useless instanceof usage in Type (PR [#3311](https://github.com/javaparser/javaparser/pull/3311) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix Java 11+ AST postprocessing (PR [#3302](https://github.com/javaparser/javaparser/pull/3302) by [@matozoid](https://github.com/matozoid)) +* Move duplicate code to JavaParserTypeAdapter (PR [#3267](https://github.com/javaparser/javaparser/pull/3267) by [@maartenc](https://github.com/maartenc)) +* Improved performance when resolving types for big source files (PR [#3265](https://github.com/javaparser/javaparser/pull/3265) by [@maartenc](https://github.com/maartenc)) +* Optimizations for Node class (CPU time and Memory usage) (PR [#3233](https://github.com/javaparser/javaparser/pull/3233) by [@4everTheOne](https://github.com/4everTheOne)) +* Fix Javadoc comment * escaping problem. (PR [#3221](https://github.com/javaparser/javaparser/pull/3221) by [@matozoid](https://github.com/matozoid)) +* Remove broken link (PR [#2912](https://github.com/javaparser/javaparser/pull/2912) by [@mernst](https://github.com/mernst)) + +### Fixed + +* Preserving field order when getting the fields declared from a ReferenceType (PR [#3342](https://github.com/javaparser/javaparser/pull/3342) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix String Index out of range in TextBlockLiteralExpr (PR [#3337](https://github.com/javaparser/javaparser/pull/3337) by [@134ARG](https://github.com/134ARG)) +* Fixed prettyprinting new switch-statements (and switch-expressions). (PR [#3335](https://github.com/javaparser/javaparser/pull/3335) by [@kozsik](https://github.com/kozsik)) +* Fix pretty printing of generic records (PR [#3334](https://github.com/javaparser/javaparser/pull/3334) by [@twistedsquare](https://github.com/twistedsquare)) +* Fix issue #3317 Comment in the middle of a multi-line single statement (PR [#3318](https://github.com/javaparser/javaparser/pull/3318) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix issue 3296 LexicalPreservation bug for array brackets (PR [#3316](https://github.com/javaparser/javaparser/pull/3316) by [@jlerbsc](https://github.com/jlerbsc)) +* Fixes Issue #3308 -- stackoverflow when resolving the `FieldAccessExpr` of an `ArrayAccessExpr` (PR [#3312](https://github.com/javaparser/javaparser/pull/3312) by [@MysterAitch](https://github.com/MysterAitch)) +* Fix StackOverflow when resolving ClassOrInterfaceType of nested ObjectCreationExpr (PR [#3279](https://github.com/javaparser/javaparser/pull/3279) by [@maartenc](https://github.com/maartenc)) +* ResolvedMethods from javassist never had exceptions (PR [#3264](https://github.com/javaparser/javaparser/pull/3264) by [@maartenc](https://github.com/maartenc)) +* Issue 3064 conditional nested lambda (PR [#3238](https://github.com/javaparser/javaparser/pull/3238) by [@si-e](https://github.com/si-e)) +* Further optimization in resolving in StatementContext (PR [#3185](https://github.com/javaparser/javaparser/pull/3185) by [@Col-E](https://github.com/Col-E)) +* Improve type resolution for duplicate names (PR [#3012](https://github.com/javaparser/javaparser/pull/3012) by [@thejk](https://github.com/thejk)) + +### Developer Changes + +* chore(deps): update dependency org.mockito:mockito-core to v3.12.4 (PR [#3350](https://github.com/javaparser/javaparser/pull/3350) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.mockito:mockito-core to v3.12.3 (PR [#3349](https://github.com/javaparser/javaparser/pull/3349) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update codecov/codecov-action action to v2.0.3 (PR [#3348](https://github.com/javaparser/javaparser/pull/3348) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.mockito:mockito-core to v3.12.2 (PR [#3347](https://github.com/javaparser/javaparser/pull/3347) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.mockito:mockito-core to v3.12.1 (PR [#3345](https://github.com/javaparser/javaparser/pull/3345) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.mockito:mockito-core to v3.12.0 (PR [#3344](https://github.com/javaparser/javaparser/pull/3344) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.apache.maven.plugins:maven-scm-plugin to v1.11.3 (PR [#3339](https://github.com/javaparser/javaparser/pull/3339) by [@renovate[bot]](https://github.com/apps/renovate)) +* Bump codecov/codecov-action from 1.5.2 to 2.0.2 (PR [#3326](https://github.com/javaparser/javaparser/pull/3326) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* chore(deps): update dependency org.mockito:mockito-core to v3.11.2 (PR [#3305](https://github.com/javaparser/javaparser/pull/3305) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.assertj:assertj-core to v3.20.2 (PR [#3297](https://github.com/javaparser/javaparser/pull/3297) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.assertj:assertj-core to v3.20.0 (PR [#3295](https://github.com/javaparser/javaparser/pull/3295) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.apache.maven.plugins:maven-dependency-plugin to v3.2.0 (PR [#3294](https://github.com/javaparser/javaparser/pull/3294) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.mockito:mockito-core to v3.11.1 (PR [#3293](https://github.com/javaparser/javaparser/pull/3293) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update codecov/codecov-action action to v1.5.2 (PR [#3287](https://github.com/javaparser/javaparser/pull/3287) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.mockito:mockito-core to v3.11.0 (PR [#3285](https://github.com/javaparser/javaparser/pull/3285) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update actions/cache action to v2.1.6 (PR [#3280](https://github.com/javaparser/javaparser/pull/3280) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.apache.maven.plugins:maven-javadoc-plugin to v3.3.0 (PR [#3270](https://github.com/javaparser/javaparser/pull/3270) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update junit5 monorepo to v5.7.2 (PR [#3262](https://github.com/javaparser/javaparser/pull/3262) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.apache.maven.plugins:maven-gpg-plugin to v3 (PR [#3250](https://github.com/javaparser/javaparser/pull/3250) by [@renovate[bot]](https://github.com/apps/renovate)) + +### :heart: Contributors + +Thank You to all contributors who worked on this release! + +* [@maartenc](https://github.com/maartenc) +* [@kozsik](https://github.com/kozsik) +* [@ReallyLiri](https://github.com/ReallyLiri) +* [@mernst](https://github.com/mernst) +* [@matozoid](https://github.com/matozoid) +* [@Col-E](https://github.com/Col-E) +* [@134ARG](https://github.com/134ARG) +* [@MysterAitch](https://github.com/MysterAitch) +* [@si-e](https://github.com/si-e) +* [@thejk](https://github.com/thejk) +* [@twistedsquare](https://github.com/twistedsquare) +* [@jlerbsc](https://github.com/jlerbsc) +* [@4everTheOne](https://github.com/4everTheOne) + + + +Version 3.22.1 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/184?closed=1) + +### Added + +* Recover wrong statements no only to ';', but to '}' (not including) as well (PR [#3247](https://github.com/javaparser/javaparser/pull/3247) by [@32kda](https://github.com/32kda)) + +### Fixed + +* update features.md -- fixed release version and date of records support, status of java 16 sealed classes to 2nd preview, and java 17 features (PR [#3263](https://github.com/javaparser/javaparser/pull/3263) by [@MysterAitch](https://github.com/MysterAitch)) +* fixes #3255 -- bugfix grammar case when using `record` to as an identifier (PR [#3256](https://github.com/javaparser/javaparser/pull/3256) by [@MysterAitch](https://github.com/MysterAitch)) +* Fixes issue #3113 -- Arrow missing in Switch Expression + jumbled up in LexicalPreservingPrinter (PR [#3235](https://github.com/javaparser/javaparser/pull/3235) by [@Zoom1111](https://github.com/Zoom1111)) +* Handle possibility of tokens not being available (PR [#3231](https://github.com/javaparser/javaparser/pull/3231) by [@mernst](https://github.com/mernst)) + +### Developer Changes + +* chore(deps): update dependency org.mockito:mockito-core to v3.10.0 (PR [#3259](https://github.com/javaparser/javaparser/pull/3259) by [@renovate[bot]](https://github.com/apps/renovate)) +* Bump codecov/codecov-action from 1 to 1.5.0 (PR [#3258](https://github.com/javaparser/javaparser/pull/3258) by [@dependabot[bot]](https://github.com/apps/dependabot)) +* Bump actions/create-release from 1 to 1.1.4 (PR [#3257](https://github.com/javaparser/javaparser/pull/3257) by [@dependabot[bot]](https://github.com/apps/dependabot)) + +### :heart: Contributors + +Thank You to all contributors who worked on this release! + +* [@32kda](https://github.com/32kda) +* [@MysterAitch](https://github.com/MysterAitch) +* [@Zoom1111](https://github.com/Zoom1111) +* [@mernst](https://github.com/mernst) + + + +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` (PR [#3197](https://github.com/javaparser/javaparser/pull/3197) by [@4everTheOne](https://github.com/4everTheOne)) +* fixed ellipsis and doublecolon to be categorised as separators not operators (fixes #2897) (PR [#2924](https://github.com/javaparser/javaparser/pull/2924) by [@MysterAitch](https://github.com/MysterAitch)) + +### Added + +* Update parser configuration and validators to include the release of java 16, and java 17 being in development (PR [#3222](https://github.com/javaparser/javaparser/pull/3222) by [@MysterAitch](https://github.com/MysterAitch)) +* Adding convenient methods to find out if a method is a variable/fixed arity method (PR [#3196](https://github.com/javaparser/javaparser/pull/3196) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix issue #3173: Add isAnnotation() and asAnnotation() methods for ResolvedTypeDeclaration (PR [#3187](https://github.com/javaparser/javaparser/pull/3187) by [@deadlocklogic](https://github.com/deadlocklogic)) +* Record support (compilation / parsing only, solving to follow separately) (PR [#3022](https://github.com/javaparser/javaparser/pull/3022) by [@MysterAitch](https://github.com/MysterAitch)) + +### Changed + +* Implemented isAssignableBy for VoidType - now return `false` instead of throwing `UnsupportedOperationException` (PR [#3197](https://github.com/javaparser/javaparser/pull/3197) by [@4everTheOne](https://github.com/4everTheOne)) +* Simplify how to find the package name from AstResolutionUtils (PR [#3193](https://github.com/javaparser/javaparser/pull/3193) by [@jlerbsc](https://github.com/jlerbsc)) +* Type resolution improvment (PR [#3189](https://github.com/javaparser/javaparser/pull/3189) by [@jlerbsc](https://github.com/jlerbsc)) +* Memory optimization for JarTypeSolver (Up to 42% less memory) (PR [#3188](https://github.com/javaparser/javaparser/pull/3188) by [@4everTheOne](https://github.com/4everTheOne)) +* Fixes #3048 (`JavaParserSymbolDeclaration#localVar` returning old declaration) and adds tests for `JavaParserSymbolDeclaration` (PR [#3049](https://github.com/javaparser/javaparser/pull/3049) by [@4everTheOne](https://github.com/4everTheOne)) + +### Fixed + +* Fix issue #3244 OrphanComment in BlockStmt not appearing (PR [#3245](https://github.com/javaparser/javaparser/pull/3245) by [@jlerbsc](https://github.com/jlerbsc)) +* fix Log.error() throwing NullPointerException (PR [#3243](https://github.com/javaparser/javaparser/pull/3243) by [@CD4017BE](https://github.com/CD4017BE)) +* fixed ellipsis and doublecolon to be categorised as separators not operators (fixes #2897) (PR [#2924](https://github.com/javaparser/javaparser/pull/2924) by [@MysterAitch](https://github.com/MysterAitch)) + +### Developer Changes + +* Include and use a Maven wrapper (PR [#3254](https://github.com/javaparser/javaparser/pull/3254) by [@MysterAitch](https://github.com/MysterAitch)) +* chore(deps): update dependency org.javassist:javassist to v3.28.0-ga (PR [#3249](https://github.com/javaparser/javaparser/pull/3249) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.jacoco:jacoco-maven-plugin to v0.8.7 (PR [#3246](https://github.com/javaparser/javaparser/pull/3246) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update actions/cache action to v2.1.5 (PR [#3226](https://github.com/javaparser/javaparser/pull/3226) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update dependency org.mockito:mockito-core to v3.9.0 (PR [#3224](https://github.com/javaparser/javaparser/pull/3224) by [@renovate[bot]](https://github.com/apps/renovate)) +* chore(deps): update actions/setup-java action to v2 (PR [#3220](https://github.com/javaparser/javaparser/pull/3220) by [@renovate[bot]](https://github.com/apps/renovate)) +* Update javaparser copyright headers (PR [#3212](https://github.com/javaparser/javaparser/pull/3212) by [@jlerbsc](https://github.com/jlerbsc)) +* Update readme template so that #3096 becomes permanent (PR [#3210](https://github.com/javaparser/javaparser/pull/3210) by [@MysterAitch](https://github.com/MysterAitch)) +* Improve tests on `getAllAncestors` method (PR [#3209](https://github.com/javaparser/javaparser/pull/3209) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix surefire configuration to allow jacoco to run correctly on JSS tests (PR [#3208](https://github.com/javaparser/javaparser/pull/3208) by [@MysterAitch](https://github.com/MysterAitch)) + +### :heart: Contributors + +Thank You to all contributors who worked on this release! + +* [@MysterAitch](https://github.com/MysterAitch) +* [@CD4017BE](https://github.com/CD4017BE) +* [@jlerbsc](https://github.com/jlerbsc) +* [@deadlocklogic](https://github.com/deadlocklogic) +* [@4everTheOne](https://github.com/4everTheOne) + +Version 3.21.2 +------------------ +**v3.21.1 released as 3.21.2 without change** + +Version 3.21.1 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/182?closed=1) + +### Added + +* Implemented logic for isAssignableBy in JavassistInterfaceDeclaration (PR [#3170](https://github.com/javaparser/javaparser/pull/3170) by [@4everTheOne](https://github.com/4everTheOne)) +* Added additional tests to cover isAssignableBy method in JavassistClassDeclaration (PR [#3169](https://github.com/javaparser/javaparser/pull/3169) by [@4everTheOne](https://github.com/4everTheOne)) + +### Changed + +* Update changelog (PR [#3178](https://github.com/javaparser/javaparser/pull/3178) by [@MysterAitch](https://github.com/MysterAitch)) +* Minor performance improvement on getCanonicalName method call (PR [#3166](https://github.com/javaparser/javaparser/pull/3166) by [@jlerbsc](https://github.com/jlerbsc)) + +### Fixed + +* Fix Issue #1950 Unambigous ambiguity call with generics and lambda's (PR [#3168](https://github.com/javaparser/javaparser/pull/3168) by [@jlerbsc](https://github.com/jlerbsc)) +* Refactor the javassist implementation to delegate to the typesolver instead of using its own classpool (PR [#3167](https://github.com/javaparser/javaparser/pull/3167) by [@maartenc](https://github.com/maartenc)) +* Fixed name resolution in casted lambda expressions (PR [#3165](https://github.com/javaparser/javaparser/pull/3165) by [@maartenc](https://github.com/maartenc)) +* Fix issue #3159 JavaParserSymbolDeclaration is used to represent variables, but #isVariable() always returns false (PR [#3160](https://github.com/javaparser/javaparser/pull/3160) by [@jlerbsc](https://github.com/jlerbsc)) +* Fix wrong author attribution in changelog for #3072 (PR [#3155](https://github.com/javaparser/javaparser/pull/3155) by [@Col-E](https://github.com/Col-E)) +* Fixed #3136 - ThisExpr isn't resolved correctly when it is in the scope of an ObjectCreationExpr (PR [#3137](https://github.com/javaparser/javaparser/pull/3137) by [@deadlocklogic](https://github.com/deadlocklogic)) +* Fix race condition in JavaParserTypeSolver (PR [#3091](https://github.com/javaparser/javaparser/pull/3091) by [@4everTheOne](https://github.com/4everTheOne)) + +### Developer Changes + +* Publish to OSSRH rather than Bintray (PR [#3180](https://github.com/javaparser/javaparser/pull/3180) by [@MysterAitch](https://github.com/MysterAitch)) +* Remove unused JUnit Pioneer dependency (PR [#3179](https://github.com/javaparser/javaparser/pull/3179) by [@MysterAitch](https://github.com/MysterAitch)) +* Verify builds test correctly under JDK16 (PR [#3175](https://github.com/javaparser/javaparser/pull/3175) by [@MysterAitch](https://github.com/MysterAitch)) +* update renovate to include "dependencies" label on PRs (PR [#3174](https://github.com/javaparser/javaparser/pull/3174) by [@MysterAitch](https://github.com/MysterAitch)) +* chore(deps): update dependency com.google.guava:guava to v30.1.1-jre (PR [#3172](https://github.com/javaparser/javaparser/pull/3172) by [@renovate[bot]](https://github.com/apps/renovate)) + +### :heart: Contributors + +Thank You to all contributors who worked on this release! + +* [@maartenc](https://github.com/maartenc) +* [@MysterAitch](https://github.com/MysterAitch) +* [@jlerbsc](https://github.com/jlerbsc) +* [@deadlocklogic](https://github.com/deadlocklogic) +* [@4everTheOne](https://github.com/4everTheOne) +* [@Col-E](https://github.com/Col-E) + + + +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`) + (PR [#3124](https://github.com/javaparser/javaparser/pull/3124), by [@4everTheOne](https://github.com/4everTheOne)) +* Performance improvement on ResolvedReferenceTypeDeclaration.isJavaLangObject() + (PR [#3125](https://github.com/javaparser/javaparser/pull/3125), by [@jlerbsc](https://github.com/jlerbsc)) +* Optimization to avoid systematically creating a class from javassist when the class has already been created + (PR [#3126](https://github.com/javaparser/javaparser/pull/3126), by [@jlerbsc](https://github.com/jlerbsc)) +* Bump jbehave-core from 4.8.1 to 4.8.2 + (PR [#3043](https://github.com/javaparser/javaparser/pull/3043), by [@dependabot](https://github.com/dependabot)) +* Bump assertj-core from 3.18.1 to 3.19.0 + (PR [#3047](https://github.com/javaparser/javaparser/pull/3047), by [@dependabot](https://github.com/dependabot)) +* Bump okhttp from 4.9.0 to 4.9.1 + (PR [#3054](https://github.com/javaparser/javaparser/pull/3054), by [@dependabot](https://github.com/dependabot)) +* Bump actions/cache from v2 to v2.1.4 + (PR [#3070](https://github.com/javaparser/javaparser/pull/3070), by [@dependabot](https://github.com/dependabot)) +* Bump mockito-core from 3.6.28 to 3.8.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 + (PR [#3082](https://github.com/javaparser/javaparser/pull/3082), by [@mernst](https://github.com/mernst)) +* Update readme with correct Java support versions + (PR [#3096](https://github.com/javaparser/javaparser/pull/3096), by [@MaartenGDev](https://github.com/MaartenGDev)) +* 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 + (PR [#2971](https://github.com/javaparser/javaparser/pull/2971), by [@jlerbsc](https://github.com/jlerbsc)) +* Major update for pretty print, adding interfaces for printer configuration, printer, ... and deprecated old PrettyPrinter API + (PR [#2974](https://github.com/javaparser/javaparser/pull/2974), by [@jlerbsc](https://github.com/jlerbsc)) +* Adding method descriptor resolution closes #2059 + (PR [#2976](https://github.com/javaparser/javaparser/pull/2976), by [@jlerbsc](https://github.com/jlerbsc)) +* Adding management of the poly and standalone expression + (PR [#2994](https://github.com/javaparser/javaparser/pull/2994), by [@jlerbsc](https://github.com/jlerbsc)) +* Add test case for issue #1770 UnaryExpr failing to resolve BITWISE_COMPLEMENT operator + (PR [#3005](https://github.com/javaparser/javaparser/pull/3005), by [@jlerbsc](https://github.com/jlerbsc)) +* Created additional validators to differentiate between enabling standard and preview features + (PR [#3015](https://github.com/javaparser/javaparser/pull/3015), by [@MysterAitch](https://github.com/MysterAitch)) +* Added additional tests to TypeSolvers + (PR [#3046](https://github.com/javaparser/javaparser/pull/3046), by [@4everTheOne](https://github.com/4everTheOne)) +* Improved JavaParserTypeVariableDeclaration tests + (PR [#3059](https://github.com/javaparser/javaparser/pull/3059), by [@4everTheOne](https://github.com/4everTheOne)) +* Improved coverage for resolved declarations and fixed inconsistencies between them + (PR [#3062](https://github.com/javaparser/javaparser/pull/3062), by [@4everTheOne](https://github.com/4everTheOne)) +* Additional GenericVisitorWithDefaults and VoidVisitorWithDefaults tests + (PR [#3067](https://github.com/javaparser/javaparser/pull/3067), by [@4everTheOne](https://github.com/4everTheOne)) +* Additional tests for hash code visitors + (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) + (PR [#2970](https://github.com/javaparser/javaparser/pull/2970), by [@jlerbsc](https://github.com/jlerbsc)) +* Minor refactoring moving Indentation class to configuration package - preparation for other refactoring on Printer + (PR [#2972](https://github.com/javaparser/javaparser/pull/2972), by [@jlerbsc](https://github.com/jlerbsc)) +* Bump guava from 30.0-jre to 30.1-jre + (PR [#2977](https://github.com/javaparser/javaparser/pull/2977), by [@dependabot](https://github.com/dependabot)) +* Refactoring: relocation of boxing/unboxing methods + (PR [#2983](https://github.com/javaparser/javaparser/pull/2983), by [@jlerbsc](https://github.com/jlerbsc)) +* Improve boxing/unboxing unit tests and remove useless code in isUnbox... + (PR [#2984](https://github.com/javaparser/javaparser/pull/2984), by [@jlerbsc](https://github.com/jlerbsc)) +* Bump jbehave-core from 4.7 to 4.8.1 + (PR [#2989](https://github.com/javaparser/javaparser/pull/2989), by [@dependabot](https://github.com/dependabot)) +* Add JVM memory settings for surefire (seems that forked mode is the default running mode) + (PR [#2999](https://github.com/javaparser/javaparser/pull/2999), by [@jlerbsc](https://github.com/jlerbsc)) +* Move unit test Issue2592Test because it's not related to symbol solver + (PR [#3000](https://github.com/javaparser/javaparser/pull/3000), by [@jlerbsc](https://github.com/jlerbsc)) +* Manage memory on test suite (clear internal cache to release memory) + (PR [#3001](https://github.com/javaparser/javaparser/pull/3001), by [@jlerbsc](https://github.com/jlerbsc)) +* Remove the PhantomNodeLogic that generates memory issues when LexicalPreservingPrinter is used. Phantom node is now an attribut of each node. This is an optimization of the JP memory usage. + (PR [#3002](https://github.com/javaparser/javaparser/pull/3002), by [@jlerbsc](https://github.com/jlerbsc)) +* Make the visit order of ModifierVisitor more consistent. + (PR [#3011](https://github.com/javaparser/javaparser/pull/3011), by [@mernst](https://github.com/mernst)) +* Link to the specification, not to a random blog. + (PR [#3013](https://github.com/javaparser/javaparser/pull/3013), by [@mernst](https://github.com/mernst)) +* Minor refactoring change call to getScope().isPresent() to hasScope() + (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 + (PR [#2981](https://github.com/javaparser/javaparser/pull/2981), by [@jlerbsc](https://github.com/jlerbsc)) +* Partially fix the issue #1743 ConditionalExpr resolves to wrong type + (PR [#2982](https://github.com/javaparser/javaparser/pull/2982), by [@jlerbsc](https://github.com/jlerbsc)) +* Partially fix issue #1743 ConditionalExpr resolves to wrong type - trying to manage reference condition expression but lub (least upper bound) function is not yet implemented + (PR [#3004](https://github.com/javaparser/javaparser/pull/3004), by [@jlerbsc](https://github.com/jlerbsc)) +* Issue #2987 StackOverflow error + (PR [#3006](https://github.com/javaparser/javaparser/pull/3006), by [@jlerbsc](https://github.com/jlerbsc)) +* Issue #1774 Ensure the correct type is calculated for all binary expressions and add unary primitive promotion + (PR [#3007](https://github.com/javaparser/javaparser/pull/3007), by [@jlerbsc](https://github.com/jlerbsc)) +* Issue #2995 Cannot resolve ClassOrInterfaceType of nested ObjectCreationExpr + (PR [#3019](https://github.com/javaparser/javaparser/pull/3019), by [@jlerbsc](https://github.com/jlerbsc)) +* Issue #1634 Missing EOL when add imports if the class not exist imports before + (PR [#3020](https://github.com/javaparser/javaparser/pull/3020), by [@jlerbsc](https://github.com/jlerbsc)) +* Issue #3024 methodCallExpr.resolve() StackOverflowError + (PR [#3025](https://github.com/javaparser/javaparser/pull/3025), by [@jlerbsc](https://github.com/jlerbsc)) +* Issue #3027 Unable to parse class with generic parameter using JavaParserTypeSolver + (PR [#3029](https://github.com/javaparser/javaparser/pull/3029), by [@jlerbsc](https://github.com/jlerbsc)) +* Issue #3030 NoSuchElementException when solving type + (PR [#3031](https://github.com/javaparser/javaparser/pull/3031), by [@4everTheOne](https://github.com/4everTheOne)) +* Issue 3028 -- Changed MethodResolutionLogic to deal with multiple candidates with varargs when varargs have not been specified in the call. + (PR [#3032](https://github.com/javaparser/javaparser/pull/3032), by [@greggers123](https://github.com/greggers123)) +* Issue #1834 Improving annotation support: Implement ResolvedAnnotationDeclaration#getDefaultValue() + (PR [#3055](https://github.com/javaparser/javaparser/pull/3055), by [@jlerbsc](https://github.com/jlerbsc)) +* Issue #3057 Removed redundant definition of method to inherit from super + (PR [#3058](https://github.com/javaparser/javaparser/pull/3058), by [@4everTheOne](https://github.com/4everTheOne)) +* Issue #3074 Unable to delete .jar files after parsing + (PR [#3075](https://github.com/javaparser/javaparser/pull/3075), by [@jlerbsc](https://github.com/jlerbsc)) +* 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 + (PR [#2946](https://github.com/javaparser/javaparser/pull/2946), by [@jlerbsc](https://github.com/jlerbsc)) +* Added Pattern Matching for instanceof (Java 14 preview, Java 15 second preview, Java 16 targeted release) + (PR [#2654](https://github.com/javaparser/javaparser/pull/2654), by [@MysterAitch](https://github.com/MysterAitch)) +* 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 converted to a user-facing String + (PR [#2949](https://github.com/javaparser/javaparser/pull/2949), by [@jlerbsc](https://github.com/jlerbsc)) +* Adding interface Printable for printer + (PR [#2950](https://github.com/javaparser/javaparser/pull/2950), by [@jlerbsc](https://github.com/jlerbsc)) +* Minor refactoring in ResolvedReferenceType and add corresponding tests + (PR [#2955](https://github.com/javaparser/javaparser/pull/2955), by [@jlerbsc](https://github.com/jlerbsc)) +* Tweak the property generator to add imports when generating and improve the typecastinggenerator's error message + (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 + (PR [#2930](https://github.com/javaparser/javaparser/pull/2930), by [@jlerbsc](https://github.com/jlerbsc)) +* Issue 2909 try different bottom / up and try with type solver strategies + (PR [#2931](https://github.com/javaparser/javaparser/pull/2931), by [@jlerbsc](https://github.com/jlerbsc)) +* Issue 2936 Triggering observer notifications for the NodeList iterator + (PR [#2938](https://github.com/javaparser/javaparser/pull/2938), by [@MysterAitch](https://github.com/MysterAitch)) +* Issue 2065 Problem resolving type of lambda with Math method invocation inside + (PR [#2945](https://github.com/javaparser/javaparser/pull/2945), by [@jlerbsc](https://github.com/jlerbsc)) +* Issue 2740 Issue related to a method call in an anonymous class on a field with a private visibility + (PR [#2947](https://github.com/javaparser/javaparser/pull/2947), by [@jlerbsc](https://github.com/jlerbsc)) +* Issue 2951 Cannot solve function with List argument defined in jar + (PR [#2952](https://github.com/javaparser/javaparser/pull/2952), by [@qzchenwl](https://github.com/qzchenwl)) +* Issue 2781 Resolve Stack overflow occurs when the name of the interface implemented by the class is the same as the name of the internal class + (PR [#2956](https://github.com/javaparser/javaparser/pull/2956), by [@jlerbsc](https://github.com/jlerbsc)) +* Issue 2953 UnsolvedSymbolException throw when resolving method in enum class implement in interface by default. + (PR [#2954](https://github.com/javaparser/javaparser/pull/2954), by [@qzchenwl](https://github.com/qzchenwl)) +* Fixed MethodCallExprContext generic parameter issue. (NullType must not fail matchTypeParameters) + (PR [#2939](https://github.com/javaparser/javaparser/pull/2939), by [@zcbbpo](https://github.com/zcbbpo)) +* Issue 2943 UnsolvedSymbolException thrown on `Stream.()` + (PR [#2961](https://github.com/javaparser/javaparser/pull/2961), by [@qzchenwl](https://github.com/qzchenwl)) +* 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 + (PR [#2918](https://github.com/javaparser/javaparser/pull/2918), by [@jlerbsc](https://github.com/jlerbsc)) +* Issue 2290 Removing the second instance of a cloned statement within a block fails + (PR [#2892](https://github.com/javaparser/javaparser/pull/2892), by [@jlerbsc](https://github.com/jlerbsc)) +* Issue 2393 Apply difference in node text after if condition replacement + (PR [#2895](https://github.com/javaparser/javaparser/pull/2895), by [@jlerbsc](https://github.com/jlerbsc)) +* Issue 2406 Symbol solver fails to solve generic array type + (PR [#2896](https://github.com/javaparser/javaparser/pull/2896), by [@jlerbsc](https://github.com/jlerbsc)) +* Issue 2489 SymbolSolver choosing wrong method after resolving + (PR [#2898](https://github.com/javaparser/javaparser/pull/2898), by [@jlerbsc](https://github.com/jlerbsc)) +* Issue 2062 Type inference issue for method arguments + (PR [#2900](https://github.com/javaparser/javaparser/pull/2900), by [@jlerbsc](https://github.com/jlerbsc)) +* Fix LOOKAHEAD for ReferenceType + (PR [#2904](https://github.com/javaparser/javaparser/pull/2904), by [@mernst](https://github.com/mernst)) +* Issue 2578 Orphaned Comments exist but not printed on unrelated change to AST + (PR [#2916](https://github.com/javaparser/javaparser/pull/2916), by [@jlerbsc](https://github.com/jlerbsc)) +* Issue 2909 Unexpected result when solving an outer class reference + (PR [#2914](https://github.com/javaparser/javaparser/pull/2914), by [@jlerbsc](https://github.com/jlerbsc)) +* Issue 2909 Improving how to resolve inner classes + (PR [#2920](https://github.com/javaparser/javaparser/pull/2920), by [@jlerbsc](https://github.com/jlerbsc)) + (PR [#2921](https://github.com/javaparser/javaparser/pull/2921), by [@jlerbsc](https://github.com/jlerbsc)) +* Ensure spaces between annotations and types for lexical-preserving printing + (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) +* Issue 2613 Auto update the version in the readme + (PR [#2903](https://github.com/javaparser/javaparser/pull/2903), by [@mysteraitch](https://github.com/mysteraitch)) +* Fix jacoco and enable codecov.io action + (PR [#2906](https://github.com/javaparser/javaparser/pull/2906), by [@mysteraitch](https://github.com/mysteraitch)) +* Minor refactoring of binary numeric promotion + (PR [#2915](https://github.com/javaparser/javaparser/pull/2915), by [@jlerbsc](https://github.com/jlerbsc)) +* Testcases for logical and/or + (PR [#2907](https://github.com/javaparser/javaparser/pull/2907), by [@mysteraitch](https://github.com/mysteraitch)) +* Format and document the grammar + (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), + [#2842](https://github.com/javaparser/javaparser/pull/2842), + [#2843](https://github.com/javaparser/javaparser/pull/2843), + [#2852](https://github.com/javaparser/javaparser/pull/2852), + [#2853](https://github.com/javaparser/javaparser/pull/2853), + [#2854](https://github.com/javaparser/javaparser/pull/2854), + [#2855](https://github.com/javaparser/javaparser/pull/2855), + [#2867](https://github.com/javaparser/javaparser/pull/2867), + [#2868](https://github.com/javaparser/javaparser/pull/2868), + [#2862](https://github.com/javaparser/javaparser/pull/2862), + [#2873](https://github.com/javaparser/javaparser/pull/2873), + by [@jlerbsc](https://github.com/jlerbsc) + ) +* ADDED: Added helper method to `ResolvedPrimitiveType.java` which checks if it is a boolean + (PR [#2856](https://github.com/javaparser/javaparser/pull/2856), by [@jlerbsc](https://github.com/jlerbsc)) +* ADDED: Added helper method to `ResolvedPrimitiveType.java` which returns all numeric types + (PR [#2858](https://github.com/javaparser/javaparser/pull/2858), by [@jlerbsc](https://github.com/jlerbsc)) +* ADDED/CHANGED: Minor refactoring - formatting code and adding convenient methods to `TypeHelper` and `ResolvedPrimitveType` + (PR [#2860](https://github.com/javaparser/javaparser/pull/2860), by [@jlerbsc](https://github.com/jlerbsc)) +* ADDED: Allow the symbol resolver for a `SymbolSolverCollectionStrategy` to be set via the given parser configuration + (PR [#2864](https://github.com/javaparser/javaparser/pull/2864), by [@jlerbsc](https://github.com/jlerbsc)) +* FIXED: `MethodResolutionLogic.findMostApplicable` not return correct symbol reference when resolving overloaded method + (PR [#2866](https://github.com/javaparser/javaparser/pull/2866), by [@jlerbsc](https://github.com/jlerbsc)) +* FIXED: Updated `AbstractSymbolResolutionTest.java` with better `@BeforeEach`/`@AfterEach` + (PR [#2871](https://github.com/javaparser/javaparser/pull/2871), by [@jlerbsc](https://github.com/jlerbsc)) +* FIXED: `TypeResolver` fails on method with args to static imported fields + (PR [#2872](https://github.com/javaparser/javaparser/pull/2872), by [@jlerbsc](https://github.com/jlerbsc)) +* FIXED: Fix issue Resolution error for non-generic constructor if generic constructor declared + (PR [#2874](https://github.com/javaparser/javaparser/pull/2874), by [@jlerbsc](https://github.com/jlerbsc)) +* FIXED: Fix issue Fails to calculate the type of a generic return type constructed from a Primitive type + (PR [#2875](https://github.com/javaparser/javaparser/pull/2875), by [@jlerbsc](https://github.com/jlerbsc)) +* FIXED: Fix issue Can't get qualified signature of a resolved method inside a Constant Enum declaration + (PR [#2876](https://github.com/javaparser/javaparser/pull/2876), by [@jlerbsc](https://github.com/jlerbsc)) +* FIXED: Fix issue Constructor resolution error for overloaded variadic constructor + (PR [#2877](https://github.com/javaparser/javaparser/pull/2877), by [@jlerbsc](https://github.com/jlerbsc)) +* FIXED: Fix issue Unable to find the constructor declaration when the argument list contains multiple `Optional.empty()` for different `Optional` + (PR [#2880](https://github.com/javaparser/javaparser/pull/2880), by [@jlerbsc](https://github.com/jlerbsc)) +* 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) + +There are two breaking changes within this release. +If you would like assistance with upgrading, get in touch. + +* FIXED: Edits to the value of a string value are now correctly handled for use with Lexical Preservation + (PR [#2646](https://github.com/javaparser/javaparser/pull/2646), by [@lemoncurry](https://github.com/lemoncurry)) +* FIXED: Edits to the value of other literal values also now handled + (PR [#2679](https://github.com/javaparser/javaparser/pull/2679), by [@MysterAitch](https://github.com/MysterAitch)) +* BREAKING CHANGE: Tokens relating to literal values now have the category of `JavaToken.Category.LITERAL` (previously `JavaToken.Category.KEYWORD`) + (PR [#2679](https://github.com/javaparser/javaparser/pull/2679), by [@MysterAitch](https://github.com/MysterAitch)) +* FIXED: Add symbol solver support for variadic parameters given zero or more than one argument, and when an array is given + (PR [#2675](https://github.com/javaparser/javaparser/pull/2675), by [@hfreeb](https://github.com/hfreeb)) +* CHANGED: Added the keyword `synchronized` to `JavaParserFacade#get`. This is specifically in response to #2668 - JavaParser is not otherwise threadsafe. + (PR [#2694](https://github.com/javaparser/javaparser/pull/2694), by [@MysterAitch](https://github.com/MysterAitch)) +* BREAKING CHANGE: The following methods now return `Optional<>` _(as do all classes which implement/extend them)_: + `ResolvedClassDeclaration#getSuperClass()`, + `ResolvedReferenceType#getTypeDeclaration()`. + _Note that Converting to use optional should be as simple as adding `.get()`, given that any cases where returning `Optional.empty()` causes problems would have also previously triggered a `NullPointerException`. + You might also use `.orElseThrow()`._ + (PR [#2693](https://github.com/javaparser/javaparser/pull/2693), by [@MysterAitch](https://github.com/MysterAitch)) +* CHANGED: Added some temporary logic to allow tests to use slightly different expected results based on the version of java used _(e.g. `java.lang.Object.registerNatives()` removed in JDK14)_ + (PR [#2637](https://github.com/javaparser/javaparser/pull/2637), by [@EFregnan](https://github.com/EFregnan)) +* FIXED: Fix resolving overloaded methods of external types + (PR [#2687](https://github.com/javaparser/javaparser/pull/2687), by [@maartenc](https://github.com/maartenc)) +* FIXED: Fix resolving method references on expressions other than ReferenceType::methodname + (PR [#2674](https://github.com/javaparser/javaparser/pull/2674), by [@maartenc](https://github.com/maartenc)) + + + +Version 3.15.22 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/173?closed=1) +* REVERT: Rollback of upgrade to `ph-javacc-maven-plugin` from v4.1.3 to v4.1.2 + _(this undoes the transitive dependency update `parser-generator-cc` from v1.1.2 to v1.1.1, which appears to have isuse with handling tokens longer than the buffer length)_ + ([#2646](https://github.com/javaparser/javaparser/pull/2646)) +* ADDED: Support resolving an enum's `valueOf` method + ([#2652](https://github.com/javaparser/javaparser/pull/2652)) +* FIXED: Fixed build warning -- bnd-maven-plugin flagging missing id + ([#2605](https://github.com/javaparser/javaparser/pull/2605)) +* FIXED: Fixed cases where nodes added after a trailing comment would incorrectly be added to the same line (thus be part of the comment) + ([#2646](https://github.com/javaparser/javaparser/pull/2646)) +* 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) + +* DEPRECATED: Deprecated and documented `JarTypeSolver#getJarTypeSolver(String)`, with a view to later removal. + ([#2598](https://github.com/javaparser/javaparser/pull/2598)) + ([#2622](https://github.com/javaparser/javaparser/pull/2622)) +* FIXED: Fix issue #2552 : UnsupportedOperationException caused by resolving inner annotation + ([#2553](https://github.com/javaparser/javaparser/pull/2553)) +* FIXED: Parents of `NodeList`s now correctly retain their parent when a child is replaced + ([#2594](https://github.com/javaparser/javaparser/pull/2594)) +* FIXED: Fix JavaParserClassDeclaration canBeAssignedTo() to not cause a recursion when a node is its own parent (e.g. `java.lang.Object`) + ([#2608](https://github.com/javaparser/javaparser/pull/2608)) +* FIXED: Fix replacing an expression preceded by a comment (`LexicalPreservation` would previously throw an `UnsupportedOperation`) + ([#2611](https://github.com/javaparser/javaparser/pull/2611)) +* FIXED: The collection strategies now correctly take into account the parser configuration that is passed in via the constructor. + ([#2619](https://github.com/javaparser/javaparser/pull/2619)) + + +Version 3.15.20 +------------------ +_skipped_ + +Version 3.15.19 +------------------ +_skipped_ + +Version 3.15.18 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/170?closed=1) + +* 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. +* 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)) + - It is believed that there are no changes to behaviour, but if you do see anything please do reach out. + - See some additional commentary/thoughts in #2502 +* FIXED: Resolving super methodcalls in anonymous inner classes (fixes #1962) + ([#2585](https://github.com/javaparser/javaparser/pull/2585)) +* ADDED: `NodeList#getFirst(): Optional` + ([#2502](https://github.com/javaparser/javaparser/pull/2502)) +* ADDED: `NodeList#getLast(): Optional` + ([#2502](https://github.com/javaparser/javaparser/pull/2502)) + +Version 3.15.17 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/169?closed=1) + +* CHANGED: Merged symbol solver modules, for java 9 module compatibility + ([#2564](https://github.com/javaparser/javaparser/pull/2564)) +* CHANGED: Renamed the pretty printer configuration option `isSpacesBetweenOperators` to `isSpaceAroundOperators` + ([#2555](https://github.com/javaparser/javaparser/pull/2555)) + +Version 3.15.16 +------------------ +_Version skipped_ + +Version 3.15.15 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/168?closed=1) + +* Often requested, finally implemented by [ReallyLiri](https://github.com/ReallyLiri): +configurable cache sizes for the symbol solver. + +Version 3.15.14 (buggy) +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/167?closed=1) + +* a suggestion for a new Javadoc parsing API was merged too quickly, +causing issues parsing Javadoc while parsing Java normally. + +Version 3.15.13 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/166?closed=1) + +Version 3.15.12 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/165?closed=1) + +Version 3.15.11 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/164?closed=1) + +Version 3.15.10 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/163?closed=1) + +Version 3.15.9 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/161?closed=1) + +Version 3.15.8 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/160?closed=1) + +Version 3.15.7 +------------------ +* BREAKING: Range.overlapsWith works slightly different now. + +[issues resolved](https://github.com/javaparser/javaparser/milestone/162?closed=1) + +Version 3.15.6 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/159?closed=1) + +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.) + +[issues resolved](https://github.com/javaparser/javaparser/milestone/158?closed=1) + +Version 3.15.4 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/157?closed=1) + +Version 3.15.3 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/156?closed=1) + +Version 3.15.2 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/155?closed=1) + +Version 3.15.1 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/154?closed=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) + +Version 3.14.16 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/152?closed=1) + +Version 3.14.159265359 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/151?closed=1) + +Version 3.14.14 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/150?closed=1) + +Version 3.14.13 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/149?closed=1) + +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. + +[issues resolved](https://github.com/javaparser/javaparser/milestone/148?closed=1) + +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. + +[issues resolved](https://github.com/javaparser/javaparser/milestone/147?closed=1) + +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. +This means the token numbers have changed, and this affects serialization. +If you rely on serialized tokens, be sure to deserialize with your current version and serialize with this version. +- Java 13: `TextBlockLiteralExpr` has been added. +- This release is broken because no identifier called `yield` can be used. + +[issues resolved](https://github.com/javaparser/javaparser/milestone/146?closed=1) + +Version 3.14.9 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/145?closed=1) + +Version 3.14.8 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/144?closed=1) + +Version 3.14.7 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/143?closed=1) + +Version 3.14.6 (oops, failed) +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/142?closed=1) + +Version 3.14.5 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/141?closed=1) + +Version 3.14.4 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/140?closed=1) + +Version 3.14.3 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/139?closed=1) + +Version 3.14.2 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/138?closed=1) + +Version 3.14.1 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/137?closed=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. + +[issues resolved](https://github.com/javaparser/javaparser/milestone/136?closed=1) + +Version 3.13.10 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/135?closed=1) + +Version 3.13.9 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/134?closed=1) + +Version 3.13.8 (failed) +------------------ +(release failed) + +Version 3.13.7 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/133?closed=1) + +Version 3.13.6 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/132?closed=1) + +Version 3.13.5 +------------------ +* "BREAKING": `ReferenceType.getDirectAncestors()` no longer returns `java.lang.Object` when called on a `ReferenceType` of `java.lang.Object`. +This remedies infinite recursions in certain edge cases. If you relied on the old behavior, you have to add a `ReferenceType` instance of `java.lang.Object` +to the List returned by `ReferenceType.getDirectAncestors()` yourself. + +[issues resolved](https://github.com/javaparser/javaparser/milestone/131?closed=1) + +Version 3.13.4 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/130?closed=1) + +Version 3.13.3 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/129?closed=1) + +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) + +Version 3.13.1 (buggy!) +------------------ +* Slightly breaking: most parameters to Log methods now take consumers to avoid evaluating them when not necessary. + +[issues resolved](https://github.com/javaparser/javaparser/milestone/127?closed=1) + +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. + +[issues resolved](https://github.com/javaparser/javaparser/milestone/124?closed=1) + +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`, +but a `NodeList label`. +* This completes *parsing* support for Java 12. +Symbol resolution is still to be done. + +[issues resolved](https://github.com/javaparser/javaparser/milestone/123?closed=1) + +Version 3.10.2 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/122?closed=1) + +Version 3.10.1 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/121?closed=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`. +This is to prepare for Java 12 switch expressions. +You can find the details in the Javadoc. + +[issues resolved](https://github.com/javaparser/javaparser/milestone/120?closed=1) + +Version 3.9.1 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/119?closed=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. +This has now been corrected in [PR 1975](https://github.com/javaparser/javaparser/pull/1975). + +[issues resolved](https://github.com/javaparser/javaparser/milestone/118?closed=1) + +Version 3.8.3 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/117?closed=1) + +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) + +Version 3.8.1 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/114?closed=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) + +[issues resolved](https://github.com/javaparser/javaparser/milestone/115?closed=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` + +[issues resolved](https://github.com/javaparser/javaparser/milestone/112?closed=1) + +Version 3.6.27 +------------------ +* The Json serialization now serializes more fields, +which *should* not impact existing code. + +[issues resolved](https://github.com/javaparser/javaparser/milestone/111?closed=1) + +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. + +[issues resolved](https://github.com/javaparser/javaparser/milestone/110?closed=1) + +Version 3.6.25 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/109?closed=1) + +Version 3.6.24 +------------------ +* `findAncestor(type, predicate)` is now available + +[issues resolved](https://github.com/javaparser/javaparser/milestone/108?closed=1) + +Version 3.6.23 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/107?closed=1) + +Version 3.6.22 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/106?closed=1) + +Version 3.6.21 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/105?closed=1) + +Version 3.6.20 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/104?closed=1) + +Version 3.6.19 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/103?closed=1) + +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. + +[issues resolved](https://github.com/javaparser/javaparser/milestone/101?closed=1) + +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. + +[issues resolved](https://github.com/javaparser/javaparser/milestone/100?closed=1) + +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. + +[issues resolved](https://github.com/javaparser/javaparser/milestone/99?closed=1) + +Version 3.6.15 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/98?closed=1) + +Version 3.6.14 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/97?closed=1) + +Version 3.6.13 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/96?closed=1) +* JavaParserFacade.getType now can also handle NameExpr referring to types +while before they were not supported. +See [issue #1491](https://github.com/javaparser/javaparser/issues/1491#issuecomment-403277963) + +Version 3.6.12 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/95?closed=1) + +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) + +Version 3.6.9 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/93?closed=1) + +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. + +Version 3.6.7 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/91?closed=1) + +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 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/88?closed=1) + +Version 3.6.3 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/87?closed=1) + +Version 3.6.2 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/86?closed=1) + +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 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/82?closed=1) + +Version 3.5.18 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/81?closed=1) + +Version 3.5.17 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/80?closed=1) + +Version 3.5.16 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/79?closed=1) + +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) + +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. +Thanks stephenramthun ! + +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. +* Enums will now get their constants aligned vertically if there are more than five. +* You can now convert between `AssignExpr.Operator` and `AssignExpr.Operator` if you like. + +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. + +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 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/70?closed=1) + +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. + +Version 3.5.5 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/68?closed=1) +* SourceRoot is now silent by default - look at the Log class if you want to change that. +* BETA: the below work on Java Symbol Solver is still ongoing. + +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. + +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. +* Receiver parameters are now well-supported instead of being a hack. See [issue 1194](https://github.com/javaparser/javaparser/pull/1194) for a description. +* BETA: the below work on Java Symbol Solver is still ongoing. + +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 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/61?closed=1) +* BETA: we're still doing work to integrate parts of [Java Symbol Solver](https://github.com/javaparser/javasymbolsolver) to simplify its API. +* `VisitorMap` is joined by `VisitorSet` and `VisitorList`, +for when you want to store `Node`s in collection but don't want its default equals/hascode behaviour + +Version 3.4.2 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/60?closed=1) +* BETA: we're doing work to integrate parts of [Java Symbol Solver](https://github.com/javaparser/javasymbolsolver) to simplify its API. +* JDK 9 will compile JavaParser now. +* [An official sample Maven setup](https://github.com/javaparser/javaparser-maven-sample) was added. + +Version 3.4.1 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/59?closed=1) +* Two visitors were added: `NoCommentEqualsVisitor` and `NoCommentHashCodeVisitor` - +as the name implies you can use these to compare nodes without considering comments. +Thanks Ryan Beckett! +* `isSomeType()` methods have been added for many types that help avoid `instanceof`. +* `asSomeType()` methods have been added for many types that help avoid casting to that type. +* `ifSomeType()` methods have been added for many types, giving a nice functional way of doing if-is-type-then-cast-to-type-then-use. +* The `LexicalPreservingPrinter` had its API changed a little: setup and printing are now separate things, +so you don't have to drag an instance of `LexicalPreservingPrinter` through your code anymore. +* `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) +* BREAKING: We missed a Java 9 feature which is now on board: try with resources can now refer to a resource declared outside of the statement. +This means that the node type you get for those resources is now `Expression` instead of `VariableDeclarationExpr`. +For Java 8 and below you can simply cast it to `VariableDeclarationExpr` again. +See also the Javadoc for `TryStmt`. +* You can now inspect the AST by exporting it to XML, JSON, YAML, or a Graphviz's dot diagram, thanks to Ryan Beckett! +* `GenericVisitorWithDefaults` and `VoidVisitorWithDefaults` were added which function like empty visitors, +but all the visit methods call a default method by default. +* Annotation support was cleaned up, adding some obscure locations where you can have annotations. +* `EnumDeclaration` regained its constructor builder methods. They were accidentally lost around 3.2.2. +* `ArrayType` now has an `origin` field which indicates in which position the array brackets were found. + +Version 3.3.5 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/57?closed=1) + +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 ! +* JavaCC was upgraded to 7.0.2 +* A new option for the pretty printer was added. +You can now wrap-and-column-align parameters of method calls. +Thank you @tarilabs ! + +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. +* `enum` and `strictfp` can now be used as identifiers on lower Java versions. + +Version 3.2.12 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/51?closed=1) + +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 +------------------ +Scrapped due to release problem. + +Version 3.2.8 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/48?closed=1) +* Added `isInnerClass()` that checks if a `ClassOrInterfaceDeclaration` is an inner class (note: this is different from a nested class!) +* @ryan-beckett contributed a huge [Eclipse setup guide](https://github.com/javaparser/javaparser/wiki/Eclipse-Project-Setup-Guide) + +Version 3.2.7 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/47?closed=1) +* We now recover from some parse errors! [Here is an article](https://matozoid.github.io/2017/06/11/parse-error-recovery.html) + +Version 3.2.6 +------------------ +[issues resolved](https://github.com/javaparser/javaparser/milestone/46?closed=1) +* `EmptyMemberDeclaration` is gone! +It was deprecated for a while because it was in the AST, but doesn't have any meaning in a Java program. +`EmptyStmt` was also deprecated, but that has been reverted. +This node *does* have meaning. + +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` +* API BREAKING: every node now points to its start and end token. +Some of the API has started returning `TokenRange` instead of `Range` - you can call `toRange` to get the old object type. +We may still change the naming of some of this code in the following month. + +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. +* `FieldAccessExpr.scope` is now a required property. +You might find some `get()`s in your code that are no longer necessary. +* `ReferenceType` no longer has a type parameter, so every `ReferenceType` can be replaced by `ReferenceType` now. + +Version 3.2.3 +------------------ +* 907 906 905 903 911 910 909 908 smaller improvements and fixes + +Version 3.2.2 +------------------ +Beta: `TreeStructureVisitor`. + +* 770 902 904 901 smaller improvements and fixes + +Version 3.2.1 +------------------ +Beta: `TreeStructureVisitor`. + +* Maven dependencies were updated to their latest versions +* 890 the concept of "method signature" now exists in JavaParser +* 896 891 889 887 882 789 smaller improvements and fixes + +Version 3.2.0 +------------------ +The lexical preservation code is stable! + +Beta: `TreeStructureVisitor`. + +* 885 884 879 878 smaller improvements and fixes + +Version 3.1.4 +------------------ +This is the first version to parse Java 9. + +Beta: `TreeStructureVisitor`, and `LexicalPreservingPrinter`. + +* 872 873 874 787 Remaining Java 9 work. + +Version 3.1.3 +------------------ +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()); +``` + +* 862 552 "_" is an illegal identifier on source level 9. +* 869 867 109 855 857 smaller improvements and fixes + +Version 3.1.2 +------------------ +Beta: `TreeStructureVisitor`, `ConcreteSyntaxModel`, and `LexicalPreservingPrinter`. + +* 594 849 831 a validation framework was introduced to inform about problems in the AST without needing to change the grammar, +and without requiring parsing code. +It is open for extension by users. +* 852 853 826 832 846 839 smaller improvements and fixes + +Version 3.1.1 +------------------ +Beta: `TreeStructureVisitor`, `ConcreteSyntaxModel`, and `LexicalPreservingPrinter`. + +* 654 124 lexical preservation (printing source code with the same formatting it had when parsing) has been added. + Thank you @ftomassetti for a lot of work! +* 554 800 first (big) step towards Java 9 support: JavaParser can read project Jigsaw module definitions. +* 795 786 751 extend the TreeVisitor with more traversal options. Thanks @ryan-beckett! +* 791 `GenericListVisitorAdapter` has been added which collects its results in a list. Thanks @Gottox! +* 815 798 797 813 clean up Problem text +* 819 818 817 816 441 809 808 807 fix various absurd annotation related issues. +* 777 805 802 796 790 792 793 781 784 785 783 782 779 357 799 763 smaller improvements and fixes + +Version 3.1.0 +------------------ +Beta: `TreeStructureVisitor` and `ConcreteSyntaxModel`. + +* 705 755 Add the concrete syntax model, which will give you information about the exact syntax a certain nodes matches. + +* 777 smaller improvements and fixes + +Version 3.1.0-beta.2 +------------------ +This version is a beta because `TreeStructureVisitor` is not in its definite state yet. + +* 762 761 772 merge `javaparser-metamodel` and `javaparser-generator-utils` into `javaparser-core`. +* 766 the `ModifierVisitor` is now created by a code generator. Its behaviour has been made logical, and may give different results than before. +* 755 `ConstructorDeclaration` and `MethodDeclaration` now share a parent: `CallableDeclaration` +* 687 759 773 769 768 767 765 759 smaller improvements and fixes + +Version 3.1.0-beta.1 +------------------ +This version is a beta because there are a lot of new features that may still change. + +This version needs a minor version increase because of a backwards compatability issue: +* 719 `getJavadoc`, `getJavadocComment` and `getComment` could return null. Our promise was to return `Optional`, so 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` +* 353 365 visitors are no longer hand made, they are now generated from the metamodel. This should make them 100% reliable. +Affected visitors are: `GenericVisitorAdapter`, `EqualsVisitor`, `VoidVisitorAdapter`, `VoidVisitor`, `GenericVisitor`, `HashCodeVisitor`, `CloneVisitor`. + +If you want to generate your own visitors, you can use the `VisitorGenerator` class from `javaparser-core-generators` + +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"* +* 707 706 improve range of array types and levels +* 709 smaller improvements and fixes + +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 +* 659 The pretty printer can now take customized visitors +* 650 671 672 674 524 smaller improvements and fixes + +Version 3.0.0-RC.3 +------------------ +* 639 622 632 657 656 652 653 647 648 645 194 643 630 624 628 627 626 625 623 cleanups, small fixes, and general housekeeping + +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 +* 615 support for arrays has once more been changed. See [the issue](https://github.com/javaparser/javaparser/issues/592) +* 580 453 380 618 580 611 610 424 608 smaller improvements and fixes + +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 +------------------ +* 403 358 549 Make all names nodes: either SimpleName or Name. This makes every name in the AST visitable. NameExpr is now a wrapper to use SimpleName in an expression. +* 516 536 use Optional<> for return values. +* 556 557 558 550 small improvements and fixes. +* 560 559 make nodes observable. + +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 +* 525 495 520 bug fix + +Version 3.0.0-alpha.6 +------------------ +* 503 modified ImportDeclaration hierarchy to have getters for static and "asterisk" again +* 506 bug fix + +Version 3.0.0-alpha.5 +------------------ +* 451 null is no longer allowed in the AST. [See last post in issue](https://github.com/javaparser/javaparser/issues/451) +* 501 421 420 316 use a special type of list for nodes: NodeList. [See last post in issue](https://github.com/javaparser/javaparser/issues/421) + +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) +* 452 355 474 494 various improvements +* 493 492 485 Simplify the JavaParser interface + +Version 3.0.0-alpha.3 +------------------ +* 112 237 466 465 461 460 458 457 fundamentally changes how we deal with arrays. [It is explained in the last post here](https://github.com/javaparser/javaparser/issues/237) +* 472 456 makes the "data" field on every node more structured. +* 477 468 refactor TypeArguments. You will find that TypeArguments is no longer a type, it is just a list in some nodes. +* 482 adds the "nodeTypes" packages to the osgi export. +* 479 476 makes all setters on nodes return this so they become chainable. +* 473 437 clean up CloneVisitor. + +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 +* 418 417 411 408 bugs +* 367 420 407 402 various cleanups + +Version 2.5.1 +------------- +* 394 OSGi manifest added +* 391 fix ModifierVisitor NullPointerException bug +* 385 a few new parse methods +* 386 fix dumping an empty import (a single ; after the package declaration) + +Version 2.5.0 +------------- +API breaking changes: + +* 191: moved TreeVisitor to visitor package +* 368, 162, 303, 302, 360: use correct type in some places. +* 371: code is now compiled with Java 8 +* 342, 331: ModifierVisitorAdapter detects and removes broken nodes +* 328, 270: upgrade JavaCC (use TokenMgrException now) +Other changes: + +* 297: enable access to tokens. +* 341, 361: node positions are now OO +* 211, 373: escaping of \n \r for string literals +* 336, 276, 141: JavaDoc support now works +* 337, 281: reorganize the stream reading code +* 343, 309, 332, 57: take advantage of common interfaces +* 329, 326, 327: deal with platform issues +* 163, 236, 252, 296, 269, 339, 321, 322, 252, 253, 293, 295: various fixes +* 310, 311, 313, 301, 294: some code clean-ups + +Version 2.4.0 +------------- +* several fixes in DumpVisitor for bugs due to lazy initialization +* make TypeDeclaration implements DocumentableNode directly +* TypedNode interface introduced +* introduce MultiBoundType +* refactored IntersectionType and UnionType +* refactored CatchClause +* parsing annotations in throws declarations +* parse orphan semicolons in import statements +* added PackageDeclaration.getPackageName +* solved issue with newlines in string literals +* fixed handling of UnknownType in EqualsVisitor +* improvements to CommentsParser +* removing old grammar + +Version 2.3.0 +------------- +* ClassOrInterfaceType implements NamedNode +* DumpVisitor can now be extended +* Improved documentation +* AST: lists are now lazy initialized + +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) +* Bugfixes + * [#79 Fix NPE in `ConstructorDeclaration.getDeclarationAsString`](https://github.com/javaparser/javaparser/pull/79) + * [#86 Add missing functions to ModifierVisitorAdapter](https://github.com/javaparser/javaparser/pull/86) + * [#82 set LambdaExpr as parent of its child nodes](https://github.com/javaparser/javaparser/issues/82) + * [#87 implement `setJavadoc` and `getJavadoc` at various classes](https://github.com/javaparser/javaparser/issues/87) + * [#96 Fixed encoding issue in `Javaparser.parse`](https://github.com/javaparser/javaparser/pull/96) + * [#85 Casting a lambda expression causes a parsing failure](https://github.com/javaparser/javaparser/issues/85) + * [#88 `MethodReferenceExpr` and `TypeExpr` don't set themselves as parents](https://github.com/javaparser/javaparser/issues/88) +* Internal + * [#89 CommentsParser.State contains unused fields](https://github.com/javaparser/javaparser/issues/89) + * Switched from drone.io to [Travis](https://travis-ci.org/javaparser/javaparser) + * [#105 Enforce compiling the library for a certain Java version](https://github.com/javaparser/javaparser/pull/105) + +[Code changes](https://github.com/javaparser/javaparser/compare/javaparser-parent-2.0.0...master) + +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 + +Version 1.0.7 (2009-04-12) +------------- +* Issue 19 fixed: +* Tests changed to run with junit 4 + +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 + +Version 1.0.5 (2008-10-26) +------------- +* Created simplified constructors in the nodes of the AST (without positional arguments) +* Created ASTHelper class with some helpful methods (more methods are still needed) + +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 +* The methods get/setAnnotations() from all BodyDeclaration subclasses were pushed down to BodyDeclaration class + +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 +* Corrected bug when parsing in multithread: + * JavaParser.setCacheParser(false) must be called before to use the parser concurrent + +2008-06-19 +------------- +* No code changes, added binary distribution to download page + +2008-06-11 +------------- +* Bug corrected: NPE in VoidVisitorAdapter + * 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/ + +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(). + +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 + * 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 + +2007-03-09 +------------- +* Long and Integer literal MIN_VALUE bug + +2007-02-24 +------------- +* '\0' bug fixed + +2007-02-01 +------------- +* Many bug fixes +* Added line/column to nodes diff --git a/codecov.yml b/codecov.yml new file mode 100644 index 0000000..4755d38 --- /dev/null +++ b/codecov.yml @@ -0,0 +1,90 @@ +codecov: + require_ci_to_pass: true + + +coverage: + + ## Configure decimal places, rounding, and the colour ranges used: + ## https://docs.codecov.com/docs/coverage-configuration + precision: 3 + round: down + range: "70...90" # Colour range - 70% coverage (and below) is solid red, 90% coverage (and above) is solid green. + + + ## These statuses show at the bottom of the PR. + ## Split the coverage reporting into sub-projects. + ## https://docs.codecov.io/docs/commit-status + ## https://docs.codecov.io/docs/codecovyml-reference#coveragestatus + status: + + ## Status configuration of the whole project + project: + + whole_project: ## Whole project (note no flags specified) + target: auto ## Increase overall coverage on each pull request (compared to the previous base commit) + threshold: 0.5% ## Flexibility in allowing a minor drop in coverage + + javaparser-core: ## Just JavaParser Core + target: auto ## Increase overall coverage on each pull request (compared to the previous base commit) + threshold: 0.5% ## Flexibility in allowing a minor drop in coverage + ## TBC: Unclear if setting flags AND paths is redundant + flags: + - javaparser-core + paths: + - javaparser-core/src/main/java* + - javaparser-core-testing/src/test/java* + - javaparser-core-testing-bdd/src/test/java* + + javaparser-symbol-solver: ## Just the Symbol Solver + target: auto ## Increase overall coverage on each pull request (compared to the previous base commit) + threshold: 0.5% ## Flexibility in allowing a minor drop in coverage + ## TBC: Unclear if setting flags AND paths is redundant + flags: + - javaparser-symbol-solver + paths: + - javaparser-symbol-solver-core/src/main/java* + - javaparser-symbol-solver-testing/src/test/java* + + ## Status configuration of ONLY the changed lines + patch: + + + +## Configuration of the comments that get added to PRs +comment: + layout: "reach,diff,flags,files,footer" + behavior: default + require_changes: false + ### Do not comment on the PR until coverage reports for all builds has been received + ### Note: 54 = three OSs (mac, windows, ubuntu) x nine java levels (8,9,10,11,12,13,14,15,16) x two modules (jp-core, jss) + after_n_builds: 54 + + +## Flags defined elsewhere MUST also be defined here (required for GitHub PR checks information) +flags: + javaparser-core: + paths: + - javaparser-core/src/main/java* + - javaparser-core-testing/src/test/java* + - javaparser-core-testing-bdd/src/test/java* + carryforward: false + javaparser-symbol-solver: + paths: + - javaparser-symbol-solver-core/src/main/java* + - javaparser-symbol-solver-testing/src/test/java* + carryforward: false + + +# ## New section re: flags +# ## No individual flags are added to YAML and flag names are automatically ingested from the Uploader +# ## https://docs.codecov.com/docs/flags +# flag_management: +# default_rules: +# carryforward: false + + +ignore: + - "/javaparser-core/src/main/java-templates/**" ## This source is ... +# - "/javaparser-core/src/main/javacc-support/**" ## This source is generated by JavaCC + - "/javaparser-symbol-solver-testing/src/test/test_sourcecode/**" ## This source is used as inputs to test cases + diff --git a/debian/README.source b/debian/README.source new file mode 100644 index 0000000..f23086f --- /dev/null +++ b/debian/README.source @@ -0,0 +1,9 @@ +This package uses a version control system as described in +http://wiki.debian.org/Java/JavaVcs and the pages linked from there. + +It contains the upstream source within the VCS upstream branch. +Upstream versions are tagged as upstream/. + +The original tarball was repackaged, because it was distributed in there +zip format. Use debian/rules get-orig-source to repeat the repackaging. + diff --git a/debian/changelog b/debian/changelog index bad88e2..38b9a00 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,5 +1,62 @@ -template-repository (1.0-1) unstable; urgency=medium +javaparser (3.25.10+dfsg-1) unstable; urgency=medium - * Initial release + * Team upload + * New upstream version 3.25.10+dfsg + * Refreshing patches + * Raising Standards version to 4.7.0 (no change) + * Repacking with +dfsg suffix + * Changing the Maven coordinates of javacc in a patch instead of the + d/maven.rules mechanism + * Ignoring the jacoco plugin during the build + * Set upstream metadata fields: Repository-Browse. - -- Tsic404 Sat, 28 Jan 2023 13:46:49 +0800 + -- Pierre Gruet Wed, 24 Apr 2024 22:05:32 +0200 + +javaparser (3.16.3-2) unstable; urgency=medium + + * Team upload. + * Removing repeated @Deprecated annotations in generated sources + (Closes: #1011814) + * Raising d/watch version to 4 + * Marking the binary package as Multi-arch: foreign + * Trim trailing whitespace. + * Use secure copyright file specification URI. + * Use secure URI in Homepage field. + * Set upstream metadata fields: Bug-Database, Bug-Submit, Repository, + Repository-Browse. + + -- Pierre Gruet Wed, 07 Sep 2022 06:59:57 +0200 + +javaparser (3.16.3-1) unstable; urgency=medium + + * Team upload. + * New upstream release (Closes: 901371) + - Depend on javacc (>= 6.0) + - New dependency on libtemplating-maven-plugin-java + * Standards-Version updated to 4.6.1 + * Switch to debhelper level 13 + * Removed the -java-doc package + * Use salsa.debian.org Vcs-* URLs + * Remove the jar files from the upstream tarball + + -- Emmanuel Bourg Mon, 16 May 2022 08:16:36 +0200 + +javaparser (1.0.11-1) unstable; urgency=medium + + * Team upload. + * New upstream release + * Build with maven-debian-helper instead of javahelper + * Standards-Version updated to 4.0.0 + * Switch to debhelper level 10 + * Use secure Vcs-* URLs + * Updated the Homepage field + * Track and download the new releases from GitHub + * Updated the Format URI in debian/copyright + + -- Emmanuel Bourg Mon, 03 Jul 2017 10:40:15 +0200 + +javaparser (1.0.8-1) unstable; urgency=low + + * Initial release. (Closes: #711109) + + -- Benjamin Mesing Wed, 23 Oct 2013 21:14:08 +0200 diff --git a/debian/compat b/debian/compat deleted file mode 100644 index b4de394..0000000 --- a/debian/compat +++ /dev/null @@ -1 +0,0 @@ -11 diff --git a/debian/control b/debian/control index cb7c4a0..9a440b5 100644 --- a/debian/control +++ b/debian/control @@ -1,15 +1,35 @@ -Source: template-repository -Section: unknown +Source: javaparser +Section: java Priority: optional -Maintainer: Tsic404 -Build-Depends: debhelper (>= 11) -Standards-Version: 4.1.3 -Homepage: https://github.com/deepin-community/template-repository -#Vcs-Browser: https://salsa.debian.org/debian/deepin-community-template-repository -#Vcs-Git: https://salsa.debian.org/debian/deepin-community-template-repository.git +Maintainer: Debian Java Maintainers +Uploaders: Benjamin Mesing +Build-Depends: + debhelper-compat (= 13), + javacc (>= 6.0), + libbuild-helper-maven-plugin-java, + libexec-maven-plugin-java, + libjavacc-maven-plugin-java, + libtemplating-maven-plugin-java, + maven-debian-helper +Standards-Version: 4.7.0 +Vcs-Git: https://salsa.debian.org/java-team/javaparser.git +Vcs-Browser: https://salsa.debian.org/java-team/javaparser +Homepage: https://javaparser.org -Package: template-repository -Architecture: any -Depends: ${shlibs:Depends}, ${misc:Depends} -Description: - +Package: libjavaparser-java +Architecture: all +Depends: ${maven:Depends}, ${misc:Depends} +Recommends: ${maven:OptionalDepends} +Multi-Arch: foreign +Description: Java library for parsing Java 7 + The library features abstract syntax tree (AST) generation and supports + the visitor pattern. The AST records the source code structure, javadoc + and comments. It is also possible to change the AST nodes or create new + ones to modify the source code. + . + Main features are: + * light weight + * good performance + * easy to use + * AST can be modified + * AST can be created from scratc diff --git a/debian/copyright b/debian/copyright index f5c805e..a113896 100644 --- a/debian/copyright +++ b/debian/copyright @@ -1,22 +1,19 @@ Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ -Upstream-Name: template-repository -Source: https://github.com/deepin-community/template-repository +Upstream-Name: javaparser +Upstream-Contact: Júlio Vilmar Gesser +Source: https://github.com/javaparser/javaparser +Files-Excluded: *.jar + *.aar Files: * -Copyright: 2023 Tsic404 -License: GPL-2+ - This package is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - . - This package 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 General Public License for more details. - . - You should have received a copy of the GNU General Public License - along with this program. If not, see - . - On Debian systems, the complete text of the GNU General - Public License version 2 can be found in "/usr/share/common-licenses/GPL-2". +Copyright: 2007, Júlio Vilmar Gesser +License: LGPL-3+ + +Files: debian/* +Copyright: 2013, Benjamin Mesing +License: LGPL-3+ + +License: LGPL-3+ + LGPL license 3.0 or any later version of that license. + On Debian GNU/Linux system you can find the complete text of the + license in '/usr/share/common-licenses/LGPL-3' diff --git a/debian/libjavaparser-java.poms b/debian/libjavaparser-java.poms new file mode 100644 index 0000000..e403133 --- /dev/null +++ b/debian/libjavaparser-java.poms @@ -0,0 +1,9 @@ +pom.xml --no-parent +javaparser-core/pom.xml --has-package-version --java-lib +javaparser-core-generators/pom.xml --ignore +javaparser-core-metamodel-generator/pom.xml --ignore +javaparser-core-serialization/pom.xml --ignore +javaparser-core-testing/pom.xml --ignore +javaparser-core-testing-bdd/pom.xml --ignore +javaparser-symbol-solver-core/pom.xml --ignore +javaparser-symbol-solver-testing/pom.xml --ignore diff --git a/debian/maven.ignoreRules b/debian/maven.ignoreRules new file mode 100644 index 0000000..3fbd462 --- /dev/null +++ b/debian/maven.ignoreRules @@ -0,0 +1,6 @@ + +biz.aQute.bnd bnd-maven-plugin +org.apache.maven.plugins maven-jar-plugin +org.apache.maven.plugins maven-source-plugin +org.codehaus.mojo extra-enforcer-rules +org.jacoco jacoco-maven-plugin * * * * diff --git a/debian/maven.rules b/debian/maven.rules new file mode 100644 index 0000000..d6696a1 --- /dev/null +++ b/debian/maven.rules @@ -0,0 +1 @@ +junit junit * s/.*/4.x/ * * diff --git a/debian/patches/javacc_coordinates.patch b/debian/patches/javacc_coordinates.patch new file mode 100644 index 0000000..26c0593 --- /dev/null +++ b/debian/patches/javacc_coordinates.patch @@ -0,0 +1,35 @@ +Description: providing the Maven coordinates of the Debian-packaged javacc + I don't understand why, but the standard debian/maven.rules mechanism does not + allow one to recover the good coordinates. +Author: Pierre Gruet +Forwarded: not-needed +Last-Update: 2024-04-24 + +--- a/javaparser-core/pom.xml ++++ b/javaparser-core/pom.xml +@@ -31,8 +31,8 @@ + + + +- com.helger.maven +- ph-javacc-maven-plugin ++ org.codehaus.mojo ++ javacc-maven-plugin + + + javacc +--- a/pom.xml ++++ b/pom.xml +@@ -195,9 +195,9 @@ + + + +- com.helger.maven +- ph-javacc-maven-plugin +- 4.1.5 ++ org.codehaus.mojo ++ javacc-maven-plugin ++ 2.6 + + + org.apache.maven.plugins diff --git a/debian/patches/series b/debian/patches/series new file mode 100644 index 0000000..aaeb76e --- /dev/null +++ b/debian/patches/series @@ -0,0 +1 @@ +javacc_coordinates.patch diff --git a/debian/upstream/metadata b/debian/upstream/metadata new file mode 100644 index 0000000..4fefb13 --- /dev/null +++ b/debian/upstream/metadata @@ -0,0 +1,5 @@ +--- +Bug-Database: https://github.com/javaparser/javaparser/issues +Bug-Submit: https://github.com/javaparser/javaparser/issues/new +Repository: https://github.com/javaparser/javaparser.git +Repository-Browse: https://github.com/javaparser/javaparser diff --git a/debian/watch b/debian/watch new file mode 100644 index 0000000..2d682ae --- /dev/null +++ b/debian/watch @@ -0,0 +1,3 @@ +version=4 +opts="mode=git,repack,repacksuffix=+dfsg,dversionmangle=s/+dfsg//,compression=xz" \ +https://github.com/javaparser/javaparser refs/tags/javaparser(?:-parent)?-([\d\.]+) diff --git a/dev-files/JavaParser-CheckStyle.xml b/dev-files/JavaParser-CheckStyle.xml new file mode 100644 index 0000000..534866b --- /dev/null +++ b/dev-files/JavaParser-CheckStyle.xml @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/dev-files/JavaParser-eclipse.xml b/dev-files/JavaParser-eclipse.xml new file mode 100644 index 0000000..853811c --- /dev/null +++ b/dev-files/JavaParser-eclipse.xml @@ -0,0 +1,295 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/dev-files/JavaParser-idea.xml b/dev-files/JavaParser-idea.xml new file mode 100644 index 0000000..fd90eed --- /dev/null +++ b/dev-files/JavaParser-idea.xml @@ -0,0 +1,38 @@ + + + diff --git a/dev-files/settings.xml b/dev-files/settings.xml new file mode 100644 index 0000000..5522172 --- /dev/null +++ b/dev-files/settings.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + ossrh + ${env.MAVEN_OSSRH_USERNAME} + ${env.MAVEN_OSSRH_PASSWORD} + + + + + + ossrh + + true + + + + gpg + ${env.MAVEN_GPG_KEYNAME} + ${env.MAVEN_GPG_PASSPHRASE} + + + + + diff --git a/doc/component_diagram.puml b/doc/component_diagram.puml new file mode 100644 index 0000000..2a219aa --- /dev/null +++ b/doc/component_diagram.puml @@ -0,0 +1,29 @@ +@startuml +node core { + [Java parser] <-- [AST] + [Javadoc parser] + [AST] <-- [lexical preserving printer] + [AST] <-- [concrete syntax model] + [concrete syntax model] <-- [lexical preserving printer] + events <-- [lexical preserving printer] + [AST] <-- [comments inserter] + [AST] <-- [visitors] + [AST] <-- [meta model] + [AST] <-- [pretty printer] + [visitors] <-- [pretty printer] + [AST] - symbol_resolution + [AST] - events + [visitors] <-- [code generators] + [AST] <-- [code generators] + [meta model] <-- [code generators] + [AST] <-- [JSON (de)serializer] + [Java parser] <- [source root] +} +node symbol-solver { + [AST] <- [model] + symbol_resolution <- [model] + [model] <-- [core] + [model] <-- [logic] + [logic] <-- [core] +} +@enduml \ No newline at end of file diff --git a/doc/readme.md b/doc/readme.md new file mode 100644 index 0000000..01c069d --- /dev/null +++ b/doc/readme.md @@ -0,0 +1,132 @@ + + + +# JavaParser + +[![Maven Central](https://img.shields.io/maven-central/v/com.github.javaparser/javaparser-core.svg)](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22com.github.javaparser%22%20AND%20a%3A%22javaparser-core%22) +[![Build Status](https://travis-ci.org/javaparser/javaparser.svg?branch=master)](https://travis-ci.org/javaparser/javaparser) +[![Coverage Status](https://codecov.io/gh/javaparser/javaparser/branch/master/graphs/badge.svg?branch=master)](https://app.codecov.io/gh/javaparser/javaparser?branch=master) +[![Join the chat at https://gitter.im/javaparser/javaparser](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/javaparser/javaparser?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +[![License LGPL-3/Apache-2.0](https://img.shields.io/badge/license-LGPL--3%2FApache--2.0-blue.svg)](LICENSE) +[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.2667378.svg)](https://doi.org/10.5281/zenodo.2667378) + + +This project contains a set of libraries implementing a Java 1.0 - Java 15 Parser with advanced analysis functionalities. This includes preview features to Java 13, with Java 14 preview features work-in-progress. + +Our main site is at [JavaParser.org](http://javaparser.org) + +## Setup + +The project binaries are available in Maven Central. + +We strongly advise users to adopt Maven, Gradle or another build system for their projects. +If you are not familiar with them we suggest taking a look at the maven quickstart projects +([javaparser-maven-sample](https://github.com/javaparser/javaparser-maven-sample), +[javasymbolsolver-maven-sample](https://github.com/javaparser/javasymbolsolver-maven-sample)). + +Just add the following to your maven configuration or tailor to your own dependency management system. + +[Please refer to the Migration Guide when upgrading from 2.5.1 to 3.0.0+](https://github.com/javaparser/javaparser/wiki/Migration-Guide) + +**Maven**: + +```xml + + com.github.javaparser + javaparser-symbol-solver-core + ${project.version} + +``` + +**Gradle**: + +``` +implementation 'com.github.javaparser:javaparser-symbol-solver-core:${project.version}' +``` + +Since Version 3.5.10, the JavaParser project includes the JavaSymbolSolver. +While JavaParser generates an Abstract Syntax Tree, JavaSymbolSolver analyzes that AST and is able to find +the relation between an element and its declaration (e.g. for a variable name it could be a parameter of a method, providing information about its type, position in the AST, ect). + +Using the dependency above will add both JavaParser and JavaSymbolSolver to your project. If you only need the core functionality of parsing Java source code in order to traverse and manipulate the generated AST, you can reduce your projects boilerplate by only including JavaParser to your project: + +**Maven**: + +```xml + + com.github.javaparser + javaparser-core + ${project.version} + +``` + +**Gradle**: + +``` +implementation 'com.github.javaparser:javaparser-core:${project.version}' +``` + +Since version 3.6.17 the AST can be serialized to JSON. +There is a separate module for this: + +**Maven**: + +```xml + + com.github.javaparser + javaparser-core-serialization + ${project.version} + +``` + +**Gradle**: + +``` +implementation 'com.github.javaparser:javaparser-core-serialization:${project.version}' +``` + +## How To Compile Sources + +If you checked out the project's source code from GitHub, you can build the project with maven using: +``` +mvnw clean install +``` + +If you want to generate the packaged jar files from the source files, you run the following maven command: +``` +mvnw package +``` + +**NOTE** the jar files for the two modules can be found in: +- `javaparser/javaparser-core/target/javaparser-core-\.jar` +- `javaparser-symbol-solver-core/target/javaparser-symbol-solver-core-\.jar` + +If you checkout the sources and want to view the project in an IDE, it is best to first generate some of the source files; +otherwise you will get many compilation complaints in the IDE. (`mvnw clean install` already does this for you.) + +``` +mvnw javacc:javacc +``` + +If you modify the code of the AST nodes, specifically if you add or remove fields or node classes, +the code generators will update a lot of code for you. +The `run_metamodel_generator.sh` script will rebuild the metamodel, +which is used by the code generators which are run by `run_core_generators.sh` +Make sure that `javaparser-core` at least compiles before you run these. + +**Note**: for Eclipse IDE follow the steps described in the wiki: https://github.com/javaparser/javaparser/wiki/Eclipse-Project-Setup-Guide + +## More information + +#### [JavaParser.org](https://javaparser.org) is the main information site. + +## License + +JavaParser is available either under the terms of the LGPL License or the Apache License. You as the user are entitled to choose the terms under which adopt JavaParser. + +For details about the LGPL License please refer to [LICENSE.LGPL](ttps://github.com/javaparser/javaparser/blob/master/LICENSE.LGPL). + +For details about the Apache License please refer to [LICENSE.APACHE](ttps://github.com/javaparser/javaparser/blob/master/LICENSE.APACHE). diff --git a/javaparser-core-generators/pom.xml b/javaparser-core-generators/pom.xml new file mode 100644 index 0000000..6b42363 --- /dev/null +++ b/javaparser-core-generators/pom.xml @@ -0,0 +1,55 @@ + + + + javaparser-parent + com.github.javaparser + 3.25.10 + + 4.0.0 + + javaparser-core-generators + A code generator framework, and the generators for javaparser-core + + + + com.github.javaparser + javaparser-core + ${project.version} + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + run-generators + + + + org.codehaus.mojo + exec-maven-plugin + + + generate-javaparser-core + test + + java + + + + + test + com.github.javaparser.generator.core.CoreGenerator + + ${project.basedir} + + + + + + + + diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/CompilationUnitGenerator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/CompilationUnitGenerator.java new file mode 100644 index 0000000..780db18 --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/CompilationUnitGenerator.java @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator; + +import com.github.javaparser.ParseResult; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.utils.SourceRoot; + +import java.util.List; + +public abstract class CompilationUnitGenerator extends Generator { + + protected CompilationUnitGenerator(SourceRoot sourceRoot) { + super(sourceRoot); + } + + @Override + public void generate() throws Exception { + List> parsedCus = sourceRoot.tryToParse(); + for (ParseResult cu : parsedCus) { + cu.ifSuccessful(this::generateCompilationUnit); + } + } + + protected abstract void generateCompilationUnit(CompilationUnit compilationUnit); + +} diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/Generator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/Generator.java new file mode 100644 index 0000000..9a1618e --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/Generator.java @@ -0,0 +1,125 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator; + +import com.github.javaparser.ast.Generated; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.body.CallableDeclaration; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.expr.StringLiteralExpr; +import com.github.javaparser.ast.nodeTypes.NodeWithAnnotations; +import com.github.javaparser.utils.SourceRoot; + +import java.util.List; + +import static com.github.javaparser.ast.NodeList.toNodeList; +import static com.github.javaparser.utils.CodeGenerationUtils.f; + +/** + * A general pattern that the generators in this module will follow. + */ +public abstract class Generator { + protected final SourceRoot sourceRoot; + + protected Generator(SourceRoot sourceRoot) { + this.sourceRoot = sourceRoot; + } + + public abstract void generate() throws Exception; + + protected > void annotateGenerated(T node) { + annotate(node, Generated.class, new StringLiteralExpr(getClass().getName())); + } + + protected > void annotateSuppressWarnings(T node) { + annotate(node, SuppressWarnings.class, new StringLiteralExpr("unchecked")); + } + + protected void annotateOverridden(MethodDeclaration method) { + annotate(method, Override.class, null); + } + + private > void annotate(T node, Class annotation, Expression content) { + node.setAnnotations( + node.getAnnotations().stream() + .filter(a -> !a.getNameAsString().equals(annotation.getSimpleName())) + .collect(toNodeList())); + + if (content != null) { + node.addSingleMemberAnnotation(annotation.getSimpleName(), content); + } else { + node.addMarkerAnnotation(annotation.getSimpleName()); + } + node.tryAddImportToParentCompilationUnit(annotation); + } + + /** + * Utility method that looks for a method or constructor with an identical signature as "callable" and replaces it + * with callable. If not found, adds callable. When the new callable has no javadoc, any old javadoc will be kept. + */ + protected void addOrReplaceWhenSameSignature(ClassOrInterfaceDeclaration containingClassOrInterface, CallableDeclaration callable) { + addMethod(containingClassOrInterface, callable, () -> containingClassOrInterface.addMember(callable)); + } + + /** + * Utility method that looks for a method or constructor with an identical signature as "callable" and replaces it + * with callable. If not found, fails. When the new callable has no javadoc, any old javadoc will be kept. The + * method or constructor is annotated with the generator class. + */ + protected void replaceWhenSameSignature(ClassOrInterfaceDeclaration containingClassOrInterface, CallableDeclaration callable) { + addMethod(containingClassOrInterface, callable, + () -> { + throw new AssertionError(f("Wanted to regenerate a method with signature %s in %s, but it wasn't there.", callable.getSignature(), containingClassOrInterface.getNameAsString())); + }); + } + + private void addMethod( + ClassOrInterfaceDeclaration containingClassOrInterface, + CallableDeclaration callable, + Runnable onNoExistingMethod) { + List> existingCallables = containingClassOrInterface.getCallablesWithSignature(callable.getSignature()); + if (existingCallables.isEmpty()) { + onNoExistingMethod.run(); + return; + } + if (existingCallables.size() > 1) { + throw new AssertionError(f("Wanted to regenerate a method with signature %s in %s, but found more than one.", callable.getSignature(), containingClassOrInterface.getNameAsString())); + } + final CallableDeclaration existingCallable = existingCallables.get(0); + callable.setJavadocComment(callable.getJavadocComment().orElseGet(() -> existingCallable.getJavadocComment().orElse(null))); + annotateGenerated(callable); + containingClassOrInterface.getMembers().replace(existingCallable, callable); + } + + /** + * Removes all methods from containingClassOrInterface that have the same signature as callable. This is not used by + * any code, but it is useful when changing a generator and you need to get rid of a set of outdated methods. + */ + protected void removeMethodWithSameSignature(ClassOrInterfaceDeclaration containingClassOrInterface, CallableDeclaration callable) { + for (CallableDeclaration existingCallable : containingClassOrInterface.getCallablesWithSignature(callable.getSignature())) { + containingClassOrInterface.remove(existingCallable); + } + } + +} diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/NodeGenerator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/NodeGenerator.java new file mode 100644 index 0000000..ce991da --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/NodeGenerator.java @@ -0,0 +1,83 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.metamodel.BaseNodeMetaModel; +import com.github.javaparser.metamodel.JavaParserMetaModel; +import com.github.javaparser.utils.Log; +import com.github.javaparser.utils.Pair; +import com.github.javaparser.utils.SourceRoot; + +import java.util.Arrays; + +/** + * Makes it easier to generate code in the core AST nodes. The generateNode method will get every node type passed to + * it, ready for modification. + */ +public abstract class NodeGenerator extends Generator { + protected NodeGenerator(SourceRoot sourceRoot) { + super(sourceRoot); + } + + public final void generate() throws Exception { + Log.info("Running %s", () -> getClass().getSimpleName()); + for (BaseNodeMetaModel nodeMetaModel : JavaParserMetaModel.getNodeMetaModels()) { + Pair result = parseNode(nodeMetaModel); + generateNode(nodeMetaModel, result.a, result.b); + } + after(); + } + + protected Pair parseNode(BaseNodeMetaModel nodeMetaModel) { + CompilationUnit nodeCu = sourceRoot.parse(nodeMetaModel.getPackageName(), nodeMetaModel.getTypeName() + ".java"); + ClassOrInterfaceDeclaration nodeCoid = nodeCu.getClassByName(nodeMetaModel.getTypeName()).orElseThrow(() -> new AssertionError("Can't find class")); + return new Pair<>(nodeCu, nodeCoid); + } + + /** + * Annotate a method with the {@link Override} annotation, if it overrides other method. + * + * @param nodeMetaModel The current meta model. + * @param methodDeclaration The method declaration. + */ + protected void annotateWhenOverridden(BaseNodeMetaModel nodeMetaModel, MethodDeclaration methodDeclaration) { + Class type = nodeMetaModel.getType(); + Class superClass = type.getSuperclass(); + + boolean isOverriding = Arrays.stream(superClass.getMethods()) + .filter(m -> m.getName().equals(methodDeclaration.getNameAsString())) + .anyMatch(m -> m.getParameters().length == methodDeclaration.getParameters().size()); + if (isOverriding) { + annotateOverridden(methodDeclaration); + } + } + + protected void after() throws Exception { + + } + + protected abstract void generateNode(BaseNodeMetaModel nodeMetaModel, CompilationUnit nodeCu, ClassOrInterfaceDeclaration nodeCoid) throws Exception; +} diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/VisitorGenerator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/VisitorGenerator.java new file mode 100644 index 0000000..4505503 --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/VisitorGenerator.java @@ -0,0 +1,103 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.expr.MarkerAnnotationExpr; +import com.github.javaparser.ast.expr.Name; +import com.github.javaparser.metamodel.BaseNodeMetaModel; +import com.github.javaparser.metamodel.JavaParserMetaModel; +import com.github.javaparser.utils.Log; +import com.github.javaparser.utils.SourceRoot; + +import java.util.Optional; + +import static com.github.javaparser.ast.Modifier.Keyword.PUBLIC; + +/** + * Makes it easier to generate visitor classes. + * It will create missing visit methods on the fly, + * and will ask you to fill in the bodies of the visit methods. + */ +public abstract class VisitorGenerator extends Generator { + private final String pkg; + private final String visitorClassName; + private final String returnType; + private final String argumentType; + private final boolean createMissingVisitMethods; + + protected VisitorGenerator(SourceRoot sourceRoot, String pkg, String visitorClassName, String returnType, String argumentType, boolean createMissingVisitMethods) { + super(sourceRoot); + this.pkg = pkg; + this.visitorClassName = visitorClassName; + this.returnType = returnType; + this.argumentType = argumentType; + this.createMissingVisitMethods = createMissingVisitMethods; + } + + public final void generate() throws Exception { + Log.info("Running %s", () -> getClass().getSimpleName()); + + final CompilationUnit compilationUnit = sourceRoot.tryToParse(pkg, visitorClassName + ".java").getResult().get(); + + Optional visitorClassOptional = compilationUnit.getClassByName(visitorClassName); + if (!visitorClassOptional.isPresent()) { + visitorClassOptional = compilationUnit.getInterfaceByName(visitorClassName); + } + final ClassOrInterfaceDeclaration visitorClass = visitorClassOptional.get(); + + JavaParserMetaModel.getNodeMetaModels().stream() + .filter((baseNodeMetaModel) -> !baseNodeMetaModel.isAbstract()) + .forEach(node -> generateVisitMethodForNode(node, visitorClass, compilationUnit)); + after(); + } + + protected void after() throws Exception { + + } + + private void generateVisitMethodForNode(BaseNodeMetaModel node, ClassOrInterfaceDeclaration visitorClass, CompilationUnit compilationUnit) { + final Optional existingVisitMethod = visitorClass.getMethods().stream() + .filter(m -> "visit".equals(m.getNameAsString())) + .filter(m -> m.getParameter(0).getType().toString().equals(node.getTypeName())) + .findFirst(); + + if (existingVisitMethod.isPresent()) { + generateVisitMethodBody(node, existingVisitMethod.get(), compilationUnit); + } else if (createMissingVisitMethods) { + MethodDeclaration newVisitMethod = visitorClass.addMethod("visit") + .addParameter(node.getTypeNameGenerified(), "n") + .addParameter(argumentType, "arg") + .setType(returnType); + if (!visitorClass.isInterface()) { + newVisitMethod + .addAnnotation(new MarkerAnnotationExpr(new Name("Override"))) + .addModifier(PUBLIC); + } + generateVisitMethodBody(node, newVisitMethod, compilationUnit); + } + } + + protected abstract void generateVisitMethodBody(BaseNodeMetaModel node, MethodDeclaration visitMethod, CompilationUnit compilationUnit); +} diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/CoreGenerator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/CoreGenerator.java new file mode 100644 index 0000000..fcb3d13 --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/CoreGenerator.java @@ -0,0 +1,104 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.core; + +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.StaticJavaParser; +import com.github.javaparser.generator.core.node.*; +import com.github.javaparser.generator.core.other.BndGenerator; +import com.github.javaparser.generator.core.other.TokenKindGenerator; +import com.github.javaparser.generator.core.quality.NotNullGenerator; +import com.github.javaparser.generator.core.visitor.*; +import com.github.javaparser.utils.Log; +import com.github.javaparser.utils.SourceRoot; + +import java.nio.file.Path; +import java.nio.file.Paths; + +import static com.github.javaparser.ParserConfiguration.LanguageLevel.RAW; + +/** + * Generates all generated visitors in the javaparser-core module. + * Suggested usage is by running the run_core_generators.sh script. + * You may want to run_metamodel_generator.sh before that. + */ +public class CoreGenerator { + private static final ParserConfiguration parserConfiguration = new ParserConfiguration() + .setLanguageLevel(RAW) +// .setStoreTokens(false) +// .setAttributeComments(false) +// .setLexicalPreservationEnabled(true) + ; + + public static void main(String[] args) throws Exception { + if (args.length != 1) { + throw new RuntimeException("Need 1 parameter: the JavaParser source checkout root directory."); + } + Log.setAdapter(new Log.StandardOutStandardErrorAdapter()); + final Path root = Paths.get(args[0], "..", "javaparser-core", "src", "main", "java"); + final SourceRoot sourceRoot = new SourceRoot(root, parserConfiguration) +// .setPrinter(LexicalPreservingPrinter::print) + ; + StaticJavaParser.setConfiguration(parserConfiguration); + + final Path generatedJavaCcRoot = Paths.get(args[0], "..", "javaparser-core", "target", "generated-sources", "javacc"); + final SourceRoot generatedJavaCcSourceRoot = new SourceRoot(generatedJavaCcRoot, parserConfiguration) +// .setPrinter(LexicalPreservingPrinter::print) + ; + + new CoreGenerator().run(sourceRoot, generatedJavaCcSourceRoot); + + sourceRoot.saveAll(); + } + + private void run(SourceRoot sourceRoot, SourceRoot generatedJavaCcSourceRoot) throws Exception { + new TypeCastingGenerator(sourceRoot).generate(); + new GenericListVisitorAdapterGenerator(sourceRoot).generate(); + new GenericVisitorAdapterGenerator(sourceRoot).generate(); + new GenericVisitorWithDefaultsGenerator(sourceRoot).generate(); + new EqualsVisitorGenerator(sourceRoot).generate(); + new ObjectIdentityEqualsVisitorGenerator(sourceRoot).generate(); + new NoCommentEqualsVisitorGenerator(sourceRoot).generate(); + new VoidVisitorAdapterGenerator(sourceRoot).generate(); + new VoidVisitorGenerator(sourceRoot).generate(); + new VoidVisitorWithDefaultsGenerator(sourceRoot).generate(); + new GenericVisitorGenerator(sourceRoot).generate(); + new HashCodeVisitorGenerator(sourceRoot).generate(); + new ObjectIdentityHashCodeVisitorGenerator(sourceRoot).generate(); + new NoCommentHashCodeVisitorGenerator(sourceRoot).generate(); + new CloneVisitorGenerator(sourceRoot).generate(); + new ModifierVisitorGenerator(sourceRoot).generate(); + + new PropertyGenerator(sourceRoot).generate(); + new RemoveMethodGenerator(sourceRoot).generate(); + new ReplaceMethodGenerator(sourceRoot).generate(); + new CloneGenerator(sourceRoot).generate(); + new GetMetaModelGenerator(sourceRoot).generate(); + new MainConstructorGenerator(sourceRoot).generate(); + new NodeModifierGenerator(sourceRoot).generate(); + new AcceptGenerator(sourceRoot).generate(); + new TokenKindGenerator(sourceRoot, generatedJavaCcSourceRoot).generate(); + new BndGenerator(sourceRoot).generate(); + + new NotNullGenerator(sourceRoot).generate(); + } +} diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/AcceptGenerator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/AcceptGenerator.java new file mode 100644 index 0000000..55015f0 --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/AcceptGenerator.java @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.core.node; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.visitor.GenericVisitor; +import com.github.javaparser.ast.visitor.VoidVisitor; +import com.github.javaparser.generator.NodeGenerator; +import com.github.javaparser.metamodel.BaseNodeMetaModel; +import com.github.javaparser.utils.SourceRoot; + +import static com.github.javaparser.StaticJavaParser.parseBodyDeclaration; + +public class AcceptGenerator extends NodeGenerator { + private final MethodDeclaration genericAccept; + private final MethodDeclaration voidAccept; + + public AcceptGenerator(SourceRoot sourceRoot) { + super(sourceRoot); + genericAccept = parseBodyDeclaration("@Override public R accept(final GenericVisitor v, final A arg) { return v.visit(this, arg); }").asMethodDeclaration(); + voidAccept = parseBodyDeclaration("@Override public void accept(final VoidVisitor v, final A arg) { v.visit(this, arg); }").asMethodDeclaration(); + } + + @Override + protected void generateNode(BaseNodeMetaModel nodeMetaModel, CompilationUnit nodeCu, ClassOrInterfaceDeclaration nodeCoid) { + if(nodeMetaModel.isAbstract()){ + return; + } + nodeCu.addImport(GenericVisitor.class); + nodeCu.addImport(VoidVisitor.class); + addOrReplaceWhenSameSignature(nodeCoid, genericAccept); + addOrReplaceWhenSameSignature(nodeCoid, voidAccept); + } +} diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/CloneGenerator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/CloneGenerator.java new file mode 100644 index 0000000..7cb0123 --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/CloneGenerator.java @@ -0,0 +1,50 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.core.node; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.visitor.CloneVisitor; +import com.github.javaparser.generator.NodeGenerator; +import com.github.javaparser.metamodel.BaseNodeMetaModel; +import com.github.javaparser.utils.SourceRoot; + +import static com.github.javaparser.StaticJavaParser.parseBodyDeclaration; +import static com.github.javaparser.utils.CodeGenerationUtils.f; + +public class CloneGenerator extends NodeGenerator { + public CloneGenerator(SourceRoot sourceRoot) { + super(sourceRoot); + } + + @Override + protected void generateNode(BaseNodeMetaModel nodeMetaModel, CompilationUnit nodeCu, ClassOrInterfaceDeclaration nodeCoid) { + nodeCu.addImport(CloneVisitor.class); + MethodDeclaration cloneMethod = (MethodDeclaration) parseBodyDeclaration(f( + "@Override public %s clone() { return (%s) accept(new CloneVisitor(), null); }", + nodeMetaModel.getTypeNameGenerified(), + nodeMetaModel.getTypeNameGenerified() + )); + addOrReplaceWhenSameSignature(nodeCoid, cloneMethod); + } +} diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/GetMetaModelGenerator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/GetMetaModelGenerator.java new file mode 100644 index 0000000..3c5829b --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/GetMetaModelGenerator.java @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.core.node; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.generator.NodeGenerator; +import com.github.javaparser.metamodel.BaseNodeMetaModel; +import com.github.javaparser.metamodel.JavaParserMetaModel; +import com.github.javaparser.utils.SourceRoot; + +import static com.github.javaparser.StaticJavaParser.parseBodyDeclaration; +import static com.github.javaparser.utils.CodeGenerationUtils.f; + +public class GetMetaModelGenerator extends NodeGenerator { + public GetMetaModelGenerator(SourceRoot sourceRoot) { + super(sourceRoot); + } + + @Override + protected void generateNode(BaseNodeMetaModel nodeMetaModel, CompilationUnit nodeCu, ClassOrInterfaceDeclaration nodeCoid) { + final MethodDeclaration getMetaModelMethod = (MethodDeclaration) parseBodyDeclaration(f("%s public %s getMetaModel() { return JavaParserMetaModel.%s; }", + nodeMetaModel.isRootNode() ? "" : "@Override", + nodeMetaModel.getClass().getSimpleName(), + nodeMetaModel.getMetaModelFieldName())); + + addOrReplaceWhenSameSignature(nodeCoid, getMetaModelMethod); + nodeCu.addImport(nodeMetaModel.getClass().getName()); + nodeCu.addImport(JavaParserMetaModel.class); + } +} diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/MainConstructorGenerator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/MainConstructorGenerator.java new file mode 100644 index 0000000..6ff9946 --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/MainConstructorGenerator.java @@ -0,0 +1,75 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.core.node; + +import com.github.javaparser.TokenRange; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.ConstructorDeclaration; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.generator.NodeGenerator; +import com.github.javaparser.metamodel.BaseNodeMetaModel; +import com.github.javaparser.metamodel.PropertyMetaModel; +import com.github.javaparser.utils.SeparatedItemStringBuilder; +import com.github.javaparser.utils.SourceRoot; + +import static com.github.javaparser.StaticJavaParser.parseExplicitConstructorInvocationStmt; +import static com.github.javaparser.utils.CodeGenerationUtils.f; + +public class MainConstructorGenerator extends NodeGenerator { + public MainConstructorGenerator(SourceRoot sourceRoot) { + super(sourceRoot); + } + + @Override + protected void generateNode(BaseNodeMetaModel nodeMetaModel, CompilationUnit nodeCu, ClassOrInterfaceDeclaration nodeCoid) { + if (nodeMetaModel.is(Node.class)) { + return; + } + ConstructorDeclaration constructor = new ConstructorDeclaration() + .setPublic(true) + .setName(nodeCoid.getNameAsString()) + .addParameter(TokenRange.class, "tokenRange") + .setJavadocComment("\n * This constructor is used by the parser and is considered private.\n "); + + BlockStmt body = constructor.getBody(); + + SeparatedItemStringBuilder superCall = new SeparatedItemStringBuilder("super(", ", ", ");"); + superCall.append("tokenRange"); + for (PropertyMetaModel parameter : nodeMetaModel.getConstructorParameters()) { + constructor.addParameter(parameter.getTypeNameForSetter(), parameter.getName()); + if (nodeMetaModel.getDeclaredPropertyMetaModels().contains(parameter)) { + body.addStatement(f("%s(%s);", parameter.getSetterMethodName(), parameter.getName())); + } else { + superCall.append(parameter.getName()); + } + } + + body.getStatements().addFirst(parseExplicitConstructorInvocationStmt(superCall.toString())); + + body.addStatement("customInitialization();"); + + addOrReplaceWhenSameSignature(nodeCoid, constructor); + nodeCu.addImport(TokenRange.class); + } +} diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/NodeModifierGenerator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/NodeModifierGenerator.java new file mode 100644 index 0000000..d8fc808 --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/NodeModifierGenerator.java @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.core.node; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.generator.NodeGenerator; +import com.github.javaparser.metamodel.BaseNodeMetaModel; +import com.github.javaparser.utils.SourceRoot; + +public class NodeModifierGenerator extends NodeGenerator { + public NodeModifierGenerator(SourceRoot sourceRoot) { + super(sourceRoot); + } + + @Override + protected void generateNode(BaseNodeMetaModel nodeMetaModel, CompilationUnit nodeCu, ClassOrInterfaceDeclaration nodeCoid) { + nodeCoid + .setFinal(false) + .setPublic(true); + } +} diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/PropertyGenerator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/PropertyGenerator.java new file mode 100644 index 0000000..7d73980 --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/PropertyGenerator.java @@ -0,0 +1,177 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.core.node; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.EnumConstantDeclaration; +import com.github.javaparser.ast.body.EnumDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.observer.ObservableProperty; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.generator.NodeGenerator; +import com.github.javaparser.generator.core.utils.CodeUtils; +import com.github.javaparser.metamodel.BaseNodeMetaModel; +import com.github.javaparser.metamodel.JavaParserMetaModel; +import com.github.javaparser.metamodel.PropertyMetaModel; +import com.github.javaparser.utils.SourceRoot; + +import java.util.*; + +import static com.github.javaparser.StaticJavaParser.parseType; +import static com.github.javaparser.ast.Modifier.Keyword.FINAL; +import static com.github.javaparser.ast.Modifier.Keyword.PUBLIC; +import static com.github.javaparser.ast.Modifier.createModifierList; +import static com.github.javaparser.utils.CodeGenerationUtils.f; +import static com.github.javaparser.utils.Utils.camelCaseToScreaming; + +public class PropertyGenerator extends NodeGenerator { + + private final Map declaredProperties = new HashMap<>(); + private final Map derivedProperties = new HashMap<>(); + + public PropertyGenerator(SourceRoot sourceRoot) { + super(sourceRoot); + } + + @Override + protected void generateNode(BaseNodeMetaModel nodeMetaModel, CompilationUnit nodeCu, ClassOrInterfaceDeclaration nodeCoid) { + for (PropertyMetaModel property : nodeMetaModel.getDeclaredPropertyMetaModels()) { + generateGetter(nodeMetaModel, nodeCoid, property); + generateSetter(nodeMetaModel, nodeCoid, property); + } + nodeMetaModel.getDerivedPropertyMetaModels().forEach(p -> derivedProperties.put(p.getName(), p)); + } + + private void generateSetter(BaseNodeMetaModel nodeMetaModel, ClassOrInterfaceDeclaration nodeCoid, PropertyMetaModel property) { + // Ensure the relevant imports have been added for the methods/annotations used + nodeCoid.findCompilationUnit().get().addImport(ObservableProperty.class); + + final String name = property.getName(); + // Fill body + final String observableName = camelCaseToScreaming(name.startsWith("is") ? name.substring(2) : name); + declaredProperties.put(observableName, property); + + if (property == JavaParserMetaModel.nodeMetaModel.commentPropertyMetaModel) { + // Node.comment has a very specific setter that we shouldn't overwrite. + return; + } + + final MethodDeclaration setter = new MethodDeclaration(createModifierList(PUBLIC), parseType(property.getContainingNodeMetaModel().getTypeNameGenerified()), property.getSetterMethodName()); + annotateWhenOverridden(nodeMetaModel, setter); + if (property.getContainingNodeMetaModel().hasWildcard()) { + setter.setType(parseType("T")); + } + setter.addAndGetParameter(property.getTypeNameForSetter(), property.getName()) + .addModifier(FINAL); + + final BlockStmt body = setter.getBody().get(); + body.getStatements().clear(); + + if (property.isRequired()) { + Class type = property.getType(); + if (property.isNonEmpty() && property.isSingular()) { + nodeCoid.findCompilationUnit().get().addImport("com.github.javaparser.utils.Utils.assertNonEmpty", true, false); + body.addStatement(f("assertNonEmpty(%s);", name)); + } else if (type != boolean.class && type != int.class) { + nodeCoid.findCompilationUnit().get().addImport("com.github.javaparser.utils.Utils.assertNotNull", true, false); + body.addStatement(f("assertNotNull(%s);", name)); + } + } + + // Check if the new value is the same as the old value + String returnValue = CodeUtils.castValue("this", setter.getType(), nodeMetaModel.getTypeName()); + body.addStatement(f("if (%s == this.%s) { return %s; }", name, name, returnValue)); + + body.addStatement(f("notifyPropertyChange(ObservableProperty.%s, this.%s, %s);", observableName, name, name)); + if (property.isNode()) { + body.addStatement(f("if (this.%s != null) this.%s.setParentNode(null);", name, name)); + } + body.addStatement(f("this.%s = %s;", name, name)); + if (property.isNode()) { + body.addStatement(f("setAsParentNodeOf(%s);", name)); + } + if (property.getContainingNodeMetaModel().hasWildcard()) { + body.addStatement(f("return (T) this;")); + } else { + body.addStatement(f("return this;")); + } + addOrReplaceWhenSameSignature(nodeCoid, setter); + if (property.getContainingNodeMetaModel().hasWildcard()) { + annotateSuppressWarnings(setter); + } + } + + private void generateGetter(BaseNodeMetaModel nodeMetaModel, ClassOrInterfaceDeclaration nodeCoid, PropertyMetaModel property) { + final MethodDeclaration getter = new MethodDeclaration(createModifierList(PUBLIC), parseType(property.getTypeNameForGetter()), property.getGetterMethodName()); + annotateWhenOverridden(nodeMetaModel, getter); + final BlockStmt body = getter.getBody().get(); + body.getStatements().clear(); + if (property.isOptional()) { + // Ensure imports have been included. + nodeCoid.findCompilationUnit().get().addImport(Optional.class); + body.addStatement(f("return Optional.ofNullable(%s);", property.getName())); + } else { + body.addStatement(f("return %s;", property.getName())); + } + addOrReplaceWhenSameSignature(nodeCoid, getter); + } + + private void generateObservableProperty(EnumDeclaration observablePropertyEnum, PropertyMetaModel property, boolean derived) { + boolean isAttribute = !Node.class.isAssignableFrom(property.getType()); + String name = property.getName(); + String constantName = camelCaseToScreaming(name.startsWith("is") ? name.substring(2) : name); + EnumConstantDeclaration enumConstantDeclaration = observablePropertyEnum.addEnumConstant(constantName); + if (isAttribute) { + enumConstantDeclaration.addArgument("Type.SINGLE_ATTRIBUTE"); + } else { + if (property.isNodeList()) { + enumConstantDeclaration.addArgument("Type.MULTIPLE_REFERENCE"); + } else { + enumConstantDeclaration.addArgument("Type.SINGLE_REFERENCE"); + } + } + if (derived) { + enumConstantDeclaration.addArgument("true"); + } + } + + @Override + protected void after() throws Exception { + CompilationUnit observablePropertyCu = sourceRoot.tryToParse("com.github.javaparser.ast.observer", "ObservableProperty.java").getResult().get(); + EnumDeclaration observablePropertyEnum = observablePropertyCu.getEnumByName("ObservableProperty").get(); + observablePropertyEnum.getEntries().clear(); + List observablePropertyNames = new LinkedList<>(declaredProperties.keySet()); + observablePropertyNames.sort(String::compareTo); + for (String propName : observablePropertyNames) { + generateObservableProperty(observablePropertyEnum, declaredProperties.get(propName), false); + } + List derivedPropertyNames = new LinkedList<>(derivedProperties.keySet()); + derivedPropertyNames.sort(String::compareTo); + for (String propName : derivedPropertyNames) { + generateObservableProperty(observablePropertyEnum, derivedProperties.get(propName), true); + } + observablePropertyEnum.addEnumConstant("RANGE"); + observablePropertyEnum.addEnumConstant("COMMENTED_NODE"); + } +} diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/RemoveMethodGenerator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/RemoveMethodGenerator.java new file mode 100644 index 0000000..e10c9a2 --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/RemoveMethodGenerator.java @@ -0,0 +1,113 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.core.node; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.generator.NodeGenerator; +import com.github.javaparser.metamodel.BaseNodeMetaModel; +import com.github.javaparser.metamodel.PropertyMetaModel; +import com.github.javaparser.utils.SourceRoot; + +import static com.github.javaparser.StaticJavaParser.parseBodyDeclaration; +import static com.github.javaparser.utils.CodeGenerationUtils.f; +import static com.github.javaparser.utils.Utils.capitalize; + + +public class RemoveMethodGenerator extends NodeGenerator { + public RemoveMethodGenerator(SourceRoot sourceRoot) { + super(sourceRoot); + } + + @Override + protected void generateNode(BaseNodeMetaModel nodeMetaModel, CompilationUnit nodeCu, ClassOrInterfaceDeclaration nodeCoid) { + MethodDeclaration removeNodeMethod = (MethodDeclaration) parseBodyDeclaration("public boolean remove(Node node) {}"); + nodeCu.addImport(Node.class); + annotateWhenOverridden(nodeMetaModel, removeNodeMethod); + + final BlockStmt body = removeNodeMethod.getBody().get(); + + body.addStatement("if (node == null) { return false; }"); + int numberPropertiesDeclared = 0; + for (PropertyMetaModel property : nodeMetaModel.getDeclaredPropertyMetaModels()) { + if (!property.isNode()) { + continue; + } + String check; + if (property.isNodeList()) { + check = nodeListCheck(property); + } else { + if (property.isRequired()) { + continue; + } + String removeAttributeMethodName = generateRemoveMethodForAttribute(nodeCoid, nodeMetaModel, property); + check = attributeCheck(property, removeAttributeMethodName); + } + if (property.isOptional()) { + check = f("if (%s != null) { %s }", property.getName(), check); + } + body.addStatement(check); + numberPropertiesDeclared++; + } + if (nodeMetaModel.getSuperNodeMetaModel().isPresent()) { + body.addStatement("return super.remove(node);"); + } else { + body.addStatement("return false;"); + } + + if (!nodeMetaModel.isRootNode() && numberPropertiesDeclared == 0) { + removeMethodWithSameSignature(nodeCoid, removeNodeMethod); + } else { + addOrReplaceWhenSameSignature(nodeCoid, removeNodeMethod); + } + } + + private String attributeCheck(PropertyMetaModel property, String removeAttributeMethodName) { + return f("if (node == %s) {" + + " %s();" + + " return true;\n" + + "}", property.getName(), removeAttributeMethodName); + } + + private String nodeListCheck(PropertyMetaModel property) { + return f("for (int i = 0; i < %s.size(); i++) {" + + " if (%s.get(i) == node) {" + + " %s.remove(i);" + + " return true;" + + " }" + + "}", property.getName(), property.getName(), property.getName()); + } + + private String generateRemoveMethodForAttribute(ClassOrInterfaceDeclaration nodeCoid, BaseNodeMetaModel nodeMetaModel, PropertyMetaModel property) { + final String methodName = "remove" + capitalize(property.getName()); + final MethodDeclaration removeMethod = (MethodDeclaration) parseBodyDeclaration(f("public %s %s() {}", nodeMetaModel.getTypeName(), methodName)); + + final BlockStmt block = removeMethod.getBody().get(); + block.addStatement(f("return %s((%s) null);", property.getSetterMethodName(), property.getTypeNameForSetter())); + + addOrReplaceWhenSameSignature(nodeCoid, removeMethod); + return methodName; + } +} diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/ReplaceMethodGenerator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/ReplaceMethodGenerator.java new file mode 100644 index 0000000..acef16e --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/ReplaceMethodGenerator.java @@ -0,0 +1,97 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.core.node; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.generator.NodeGenerator; +import com.github.javaparser.metamodel.BaseNodeMetaModel; +import com.github.javaparser.metamodel.PropertyMetaModel; +import com.github.javaparser.utils.SourceRoot; + +import static com.github.javaparser.StaticJavaParser.parseBodyDeclaration; +import static com.github.javaparser.utils.CodeGenerationUtils.f; + +public class ReplaceMethodGenerator extends NodeGenerator { + public ReplaceMethodGenerator(SourceRoot sourceRoot) { + super(sourceRoot); + } + + @Override + protected void generateNode(BaseNodeMetaModel nodeMetaModel, CompilationUnit nodeCu, ClassOrInterfaceDeclaration nodeCoid) { + MethodDeclaration replaceNodeMethod = (MethodDeclaration) parseBodyDeclaration("public boolean replace(Node node, Node replacementNode) {}"); + nodeCu.addImport(Node.class); + annotateWhenOverridden(nodeMetaModel, replaceNodeMethod); + + final BlockStmt body = replaceNodeMethod.getBody().get(); + + body.addStatement("if (node == null) { return false; }"); + + int numberPropertiesDeclared = 0; + for (PropertyMetaModel property : nodeMetaModel.getDeclaredPropertyMetaModels()) { + if (!property.isNode()) { + continue; + } + String check; + if (property.isNodeList()) { + check = nodeListCheck(property); + } else { + check = attributeCheck(property, property.getSetterMethodName()); + } + if (property.isOptional()) { + check = f("if (%s != null) { %s }", property.getName(), check); + } + body.addStatement(check); + numberPropertiesDeclared++; + } + if (nodeMetaModel.getSuperNodeMetaModel().isPresent()) { + body.addStatement("return super.replace(node, replacementNode);"); + } else { + body.addStatement("return false;"); + } + + if (!nodeMetaModel.isRootNode() && numberPropertiesDeclared == 0) { + removeMethodWithSameSignature(nodeCoid, replaceNodeMethod); + } else { + addOrReplaceWhenSameSignature(nodeCoid, replaceNodeMethod); + } + } + + private String attributeCheck(PropertyMetaModel property, String attributeSetterName) { + return f("if (node == %s) {" + + " %s((%s) replacementNode);" + + " return true;\n" + + "}", property.getName(), attributeSetterName, property.getTypeName()); + } + + private String nodeListCheck(PropertyMetaModel property) { + return f("for (int i = 0; i < %s.size(); i++) {" + + " if (%s.get(i) == node) {" + + " %s.set(i, (%s) replacementNode);" + + " return true;" + + " }" + + "}", property.getName(), property.getName(), property.getName(), property.getTypeName()); + } +} diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/TypeCastingGenerator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/TypeCastingGenerator.java new file mode 100644 index 0000000..de6291b --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/node/TypeCastingGenerator.java @@ -0,0 +1,131 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.core.node; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.generator.NodeGenerator; +import com.github.javaparser.metamodel.BaseNodeMetaModel; +import com.github.javaparser.metamodel.JavaParserMetaModel; +import com.github.javaparser.utils.Pair; +import com.github.javaparser.utils.SourceRoot; + +import java.util.Optional; +import java.util.Set; +import java.util.function.Consumer; + +import static com.github.javaparser.StaticJavaParser.parseBodyDeclaration; +import static com.github.javaparser.utils.CodeGenerationUtils.f; +import static com.github.javaparser.utils.Utils.set; + +public class TypeCastingGenerator extends NodeGenerator { + private final Set baseNodes = set( + JavaParserMetaModel.statementMetaModel, + JavaParserMetaModel.expressionMetaModel, + JavaParserMetaModel.typeMetaModel, + JavaParserMetaModel.moduleDirectiveMetaModel, + JavaParserMetaModel.bodyDeclarationMetaModel, + JavaParserMetaModel.commentMetaModel + ); + + public TypeCastingGenerator(SourceRoot sourceRoot) { + super(sourceRoot); + } + + @Override + protected void generateNode(BaseNodeMetaModel nodeMetaModel, CompilationUnit nodeCu, ClassOrInterfaceDeclaration nodeCoid) throws Exception { + Pair baseCode = null; + for (BaseNodeMetaModel baseNode : baseNodes) { + if(nodeMetaModel == baseNode) { + // We adjust the base models from the child nodes, + // so we don't do anything when we *are* the base model. + return; + } + if (nodeMetaModel.isInstanceOfMetaModel(baseNode)) { + baseCode = parseNode(baseNode); + } + } + + if (baseCode == null) { + // Node is not a child of one of the base nodes, so we don't want to generate this method for it. + return; + } + + final String typeName = nodeMetaModel.getTypeName(); + final ClassOrInterfaceDeclaration baseCoid = baseCode.b; + final CompilationUnit baseCu = baseCode.a; + + generateIsType(nodeMetaModel, baseCu, nodeCoid, baseCoid, typeName); + generateAsType(nodeMetaModel, baseCu, nodeCoid, baseCoid, typeName); + generateToType(nodeMetaModel, nodeCu, baseCu, nodeCoid, baseCoid, typeName); + generateIfType(nodeMetaModel, nodeCu, baseCu, nodeCoid, baseCoid, typeName); + } + + private void generateAsType(BaseNodeMetaModel nodeMetaModel, CompilationUnit baseCu, ClassOrInterfaceDeclaration nodeCoid, ClassOrInterfaceDeclaration baseCoid, String typeName) { + baseCu.addImport("com.github.javaparser.utils.CodeGenerationUtils.f", true, false); + + final MethodDeclaration asTypeBaseMethod = (MethodDeclaration) parseBodyDeclaration(f("public %s as%s() { throw new IllegalStateException(f(\"%%s is not %s, it is %%s\", this, this.getClass().getSimpleName())); }", typeName, typeName, typeName)); + final MethodDeclaration asTypeNodeMethod = (MethodDeclaration) parseBodyDeclaration(f("@Override public %s as%s() { return this; }", typeName, typeName)); + + annotateWhenOverridden(nodeMetaModel, asTypeNodeMethod); + + addOrReplaceWhenSameSignature(baseCoid, asTypeBaseMethod); + addOrReplaceWhenSameSignature(nodeCoid, asTypeNodeMethod); + } + + private void generateToType(BaseNodeMetaModel nodeMetaModel, CompilationUnit nodeCu, CompilationUnit baseCu, ClassOrInterfaceDeclaration nodeCoid, ClassOrInterfaceDeclaration baseCoid, String typeName) { + baseCu.addImport(Optional.class); + nodeCu.addImport(Optional.class); + + final MethodDeclaration toTypeBaseMethod = (MethodDeclaration) parseBodyDeclaration(f("public Optional<%s> to%s() { return Optional.empty(); }", typeName, typeName, typeName)); + final MethodDeclaration toTypeNodeMethod = (MethodDeclaration) parseBodyDeclaration(f("@Override public Optional<%s> to%s() { return Optional.of(this); }", typeName, typeName)); + + annotateWhenOverridden(nodeMetaModel, toTypeNodeMethod); + + addOrReplaceWhenSameSignature(baseCoid, toTypeBaseMethod); + addOrReplaceWhenSameSignature(nodeCoid, toTypeNodeMethod); + } + + private void generateIfType(BaseNodeMetaModel nodeMetaModel, CompilationUnit nodeCu, CompilationUnit baseCu, ClassOrInterfaceDeclaration nodeCoid, ClassOrInterfaceDeclaration baseCoid, String typeName) { + baseCu.addImport(Consumer.class); + nodeCu.addImport(Consumer.class); + + final MethodDeclaration ifTypeBaseMethod = (MethodDeclaration) parseBodyDeclaration(f("public void if%s(Consumer<%s> action) { }", typeName, typeName)); + final MethodDeclaration ifTypeNodeMethod = (MethodDeclaration) parseBodyDeclaration(f("public void if%s(Consumer<%s> action) { action.accept(this); }", typeName, typeName)); + + annotateWhenOverridden(nodeMetaModel, ifTypeNodeMethod); + + addOrReplaceWhenSameSignature(baseCoid, ifTypeBaseMethod); + addOrReplaceWhenSameSignature(nodeCoid, ifTypeNodeMethod); + } + + private void generateIsType(BaseNodeMetaModel nodeMetaModel, CompilationUnit baseCu, ClassOrInterfaceDeclaration nodeCoid, ClassOrInterfaceDeclaration baseCoid, String typeName) { + final MethodDeclaration baseIsTypeMethod = (MethodDeclaration) parseBodyDeclaration(f("public boolean is%s() { return false; }", typeName)); + final MethodDeclaration overriddenIsTypeMethod = (MethodDeclaration) parseBodyDeclaration(f("@Override public boolean is%s() { return true; }", typeName)); + + annotateWhenOverridden(nodeMetaModel, overriddenIsTypeMethod); + + addOrReplaceWhenSameSignature(nodeCoid, overriddenIsTypeMethod); + addOrReplaceWhenSameSignature(baseCoid, baseIsTypeMethod); + } +} diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/other/BndGenerator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/other/BndGenerator.java new file mode 100644 index 0000000..f82a8ea --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/other/BndGenerator.java @@ -0,0 +1,78 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.core.other; + +import com.github.javaparser.generator.Generator; +import com.github.javaparser.utils.Log; +import com.github.javaparser.utils.SourceRoot; + +import java.io.File; +import java.io.IOException; +import java.io.Writer; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.stream.Stream; + +/** + * Generates the bnd.bnd file in javaparser-core. + */ +public class BndGenerator extends Generator { + + public BndGenerator(SourceRoot sourceRoot) { + super(sourceRoot); + } + + @Override + public void generate() throws IOException { + Log.info("Running %s", () -> getClass().getSimpleName()); + Path root = sourceRoot.getRoot(); + Path projectRoot = root.getParent().getParent().getParent(); + String lineSeparator = System.getProperty("line.separator"); + try (Stream stream = Files.walk(root)) { + String packagesList = stream + .filter(Files::isRegularFile) + .map(path -> getPackageName(root, path)) + .distinct() + .sorted() + .reduce(null, (packageList, packageName) -> + concatPackageName(packageName, packageList, lineSeparator)); + Path output = projectRoot.resolve("bnd.bnd"); + try(Writer writer = Files.newBufferedWriter(output)) { + Path templateFile = projectRoot.resolve("bnd.bnd.template"); + String template = new String(Files.readAllBytes(templateFile), StandardCharsets.UTF_8); + writer.write(template.replace("{exportedPackages}", packagesList)); + } + Log.info("Written " + output); + } + } + + private String concatPackageName(String packageName, String packageList, String lineSeparator) { + return (packageList == null ? + ("\\" + lineSeparator) : + (packageList + ", \\" + lineSeparator)) + " " + packageName; + } + + private static String getPackageName(Path root, Path path) { + return root.relativize(path.getParent()).toString().replace(File.separatorChar, '.'); + } +} diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/other/GrammarLetterGenerator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/other/GrammarLetterGenerator.java new file mode 100644 index 0000000..8affb4b --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/other/GrammarLetterGenerator.java @@ -0,0 +1,75 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.core.other; + +import java.util.function.Function; + +/** + * Prints the LETTER and PART_LETTER tokens. They should be inserted into the grammar manually. + */ +public class GrammarLetterGenerator { + public static void main(String[] args) { + generate("LETTER", c -> Character.isJavaIdentifierStart(c) || Character.isHighSurrogate((char) (int) c) || Character.isLowSurrogate((char) (int) c)); + generate("PART_LETTER", c -> Character.isJavaIdentifierPart(c) || Character.isHighSurrogate((char) (int) c) || Character.isLowSurrogate((char) (int) c)); + } + + private static void generate(String tokenName, Function f) { + final String indent = " "; + System.out.println(" < #" + tokenName + ": ["); + System.out.print(indent); + int nltime = 0; + int i = 0; + while (i < 0x10000) { + while (!f.apply(i) && i < 0x10000) { + i++; + } + String start = format(i); + while (f.apply(i) && i < 0x10000) { + i++; + } + String end = format(i - 1); + if (i >= 0x10000) { + break; + } + if (start.equals(end)) { + nltime++; + System.out.print(start + ", "); + } else { + nltime += 2; + System.out.print(start + "-" + end + ", "); + } + if (nltime >= 10) { + nltime = 0; + System.out.println(); + System.out.print(indent); + } + } + // Too lazy to remove the final illegal comma. + System.out.println("]"); + System.out.println(" | "); + System.out.println(" >"); + } + + private static String format(int i) { + return String.format("\"\\u%04x\"", i); + } +} diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/other/TokenKindGenerator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/other/TokenKindGenerator.java new file mode 100644 index 0000000..3989e33 --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/other/TokenKindGenerator.java @@ -0,0 +1,92 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.core.other; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.BodyDeclaration; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.EnumConstantDeclaration; +import com.github.javaparser.ast.body.EnumDeclaration; +import com.github.javaparser.ast.expr.IntegerLiteralExpr; +import com.github.javaparser.ast.stmt.ReturnStmt; +import com.github.javaparser.ast.stmt.SwitchEntry; +import com.github.javaparser.ast.stmt.SwitchStmt; +import com.github.javaparser.generator.Generator; +import com.github.javaparser.utils.Log; +import com.github.javaparser.utils.SourceRoot; + +/** + * Generates the TokenKind enum from {@link com.github.javaparser.GeneratedJavaParserConstants} + */ +public class TokenKindGenerator extends Generator { + private final SourceRoot generatedJavaCcSourceRoot; + + public TokenKindGenerator(SourceRoot sourceRoot, SourceRoot generatedJavaCcSourceRoot) { + super(sourceRoot); + this.generatedJavaCcSourceRoot = generatedJavaCcSourceRoot; + } + + @Override + public void generate() { + Log.info("Running %s", () -> getClass().getSimpleName()); + + final CompilationUnit javaTokenCu = sourceRoot.parse("com.github.javaparser", "JavaToken.java"); + final ClassOrInterfaceDeclaration javaToken = javaTokenCu.getClassByName("JavaToken").orElseThrow(() -> new AssertionError("Can't find class in java file.")); + final EnumDeclaration kindEnum = javaToken.findFirst(EnumDeclaration.class, e -> "Kind".equals(e.getNameAsString())).orElseThrow(() -> new AssertionError("Can't find class in java file.")); + + kindEnum.getEntries().clear(); + annotateGenerated(kindEnum); + + final SwitchStmt valueOfSwitch = kindEnum.findFirst(SwitchStmt.class).orElseThrow(() -> new AssertionError("Can't find valueOf switch.")); + valueOfSwitch.findAll(SwitchEntry.class).stream().filter(e -> e.getLabels().isNonEmpty()).forEach(Node::remove); + + final CompilationUnit constantsCu = generatedJavaCcSourceRoot.parse("com.github.javaparser", "GeneratedJavaParserConstants.java"); + final ClassOrInterfaceDeclaration constants = constantsCu.getInterfaceByName("GeneratedJavaParserConstants").orElseThrow(() -> new AssertionError("Can't find class in java file.")); + for (BodyDeclaration member : constants.getMembers()) { + member.toFieldDeclaration() + .filter(field -> { + String javadoc = field.getJavadocComment().get().getContent(); + return javadoc.contains("RegularExpression Id") || javadoc.contains("End of File"); + }) + .map(field -> field.getVariable(0)) + .ifPresent(var -> { + final String name = var.getNameAsString(); + final IntegerLiteralExpr kind = var.getInitializer().get().asIntegerLiteralExpr(); + generateEnumEntry(kindEnum, name, kind); + generateValueOfEntry(valueOfSwitch, name, kind); + }); + } + } + + private void generateValueOfEntry(SwitchStmt valueOfSwitch, String name, IntegerLiteralExpr kind) { + final SwitchEntry entry = new SwitchEntry(new NodeList<>(kind), SwitchEntry.Type.STATEMENT_GROUP, new NodeList<>(new ReturnStmt(name))); + valueOfSwitch.getEntries().addFirst(entry); + } + + private void generateEnumEntry(EnumDeclaration kindEnum, String name, IntegerLiteralExpr kind) { + final EnumConstantDeclaration enumEntry = new EnumConstantDeclaration(name); + enumEntry.getArguments().add(kind); + kindEnum.addEntry(enumEntry); + } +} diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/quality/NotNullGenerator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/quality/NotNullGenerator.java new file mode 100644 index 0000000..74fee76 --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/quality/NotNullGenerator.java @@ -0,0 +1,208 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.core.quality; + +import com.github.javaparser.StaticJavaParser; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.CallableDeclaration; +import com.github.javaparser.ast.body.ConstructorDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.body.Parameter; +import com.github.javaparser.ast.expr.AnnotationExpr; +import com.github.javaparser.ast.expr.MethodCallExpr; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.ast.stmt.ExplicitConstructorInvocationStmt; +import com.github.javaparser.ast.stmt.ExpressionStmt; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.generator.CompilationUnitGenerator; +import com.github.javaparser.quality.NotNull; +import com.github.javaparser.quality.Preconditions; +import com.github.javaparser.utils.SourceRoot; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static com.github.javaparser.utils.CodeGenerationUtils.f; + +/** + * Generator to process annotations {@link com.github.javaparser.quality.NotNull}. + */ +public class NotNullGenerator extends CompilationUnitGenerator { + + public NotNullGenerator(SourceRoot sourceRoot) { + super(sourceRoot); + } + + @Override + public void generateCompilationUnit(CompilationUnit compilationUnit) { + compilationUnit.findAll(ConstructorDeclaration.class).forEach(this::generateQualityForConstructor); + compilationUnit.findAll(MethodDeclaration.class).forEach(this::generateQualityForMethod); + } + + /** + * Generate the pre conditions based on the method parameters. + *
+ * If parameters are annotated with {@link com.github.javaparser.quality.NotNull} and a {@code null} is + * passed, the method should throw an {@link IllegalArgumentException}. + *
+ * If annotated with {@link com.github.javaparser.quality.Nullable}, other annotation or none, nothing should be + * changed. + * + * @param methodDeclaration The method declaration to generate. + */ + protected void generateQualityForMethod(MethodDeclaration methodDeclaration) { + methodDeclaration.getBody().ifPresent(blockStmt -> + generateQualityForParameter(methodDeclaration, methodDeclaration.getParameters(), blockStmt)); + } + + /** + * Generate the pre conditions based on the constructor parameters. + *
+ * If parameters are annotated with {@link com.github.javaparser.quality.NotNull} and a {@code null} is + * passed, the method should throw an {@link IllegalArgumentException}. + *
+ * If annotated with {@link com.github.javaparser.quality.Nullable}, other annotation or none, nothing should be + * changed. + * + * @param constructorDeclaration The constructor declaration to generate. + */ + protected void generateQualityForConstructor(ConstructorDeclaration constructorDeclaration) { + generateQualityForParameter(constructorDeclaration, constructorDeclaration.getParameters(), constructorDeclaration.getBody()); + } + + /** + * Generate the pre conditions for the parameters. + *
+ * If parameters are annotated with {@link com.github.javaparser.quality.NotNull} and a {@code null} is + * passed, the method should throw an {@link IllegalArgumentException}. + *
+ * If annotated with {@link com.github.javaparser.quality.Nullable}, other annotation or none, nothing should be + * changed. + * + * @param callableDeclaration The declaration where the parameters belong. + * @param parameters The list of parameters. + * @param blockStmt The block where the assertions should be added. + * + * @param The callable declaration type. + */ + protected > + void generateQualityForParameter(N callableDeclaration, NodeList parameters, BlockStmt blockStmt) { + + List assertions = new ArrayList<>(); + + for (Parameter parameter : parameters) { + Optional nonNullAnnotation = parameter.getAnnotationByClass(NotNull.class); + if (nonNullAnnotation.isPresent()) { + assertions.add(createAssertion(parameter)); + } + } + + insertAssertionsInBlock(callableDeclaration, blockStmt, assertions); + } + + /** + * Create assertion for the parameters. + * + * @param parameter The parameter to create the assertion. + * + * @return The assertion to be added to the code. + */ + private Statement createAssertion(Parameter parameter) { + + parameter.tryAddImportToParentCompilationUnit(Preconditions.class); + return StaticJavaParser.parseStatement( + f("Preconditions.checkNotNull(%s, \"Parameter %s can't be null.\");", parameter.getNameAsString(), + parameter.getNameAsString()) + ); + } + + /** + * Insert the assertions into the block. + * + * @param callableDeclaration The declaration where the parameters belong. + * @param blockStmt The block where the assertions should be added. + * @param assertions The list of assertions to be inserted. + * + * @param The callable declaration type. + */ + private > + void insertAssertionsInBlock(N callableDeclaration, BlockStmt blockStmt, List assertions) { + + // If there's nothing to add, just ignore + if (assertions.isEmpty()) + return; + + int position = 0; + NodeList statements = blockStmt.getStatements(); + + // When the callable is a constructor we must check if is a ExplicitConstructorInvocationStmt. + if (callableDeclaration.isConstructorDeclaration()) { + Optional optionalFirstStatement = statements.getFirst(); + if (optionalFirstStatement.isPresent()) { + + // Check if the first item is a "super" expr. If it's then we add the assertions after it. + Statement firstStatement = optionalFirstStatement.get(); + if (firstStatement instanceof ExplicitConstructorInvocationStmt) { + position = 1; + } + } + } + + // Register assertions + for (int i = 0 ; i < assertions.size() ; i++) { + Statement assertion = assertions.get(i); + + Optional optOldStmt = getSimilarAssertionInBlock(assertion, blockStmt); + + if (optOldStmt.isPresent()) { + optOldStmt.get().replace(assertion); + } else { + blockStmt.addStatement(position + i, assertion); + } + } + } + + private Optional getSimilarAssertionInBlock(Statement assertion, BlockStmt blockStmt) { + + MethodCallExpr assertionCall = assertion.asExpressionStmt().getExpression().asMethodCallExpr(); + List methodCallExpressions = blockStmt.findAll(MethodCallExpr.class); + + for (MethodCallExpr blockMethodCall : methodCallExpressions) { + + // Check if the method calls name match + if ( + blockMethodCall.getNameAsExpression().equals(assertionCall.getNameAsExpression()) && + blockMethodCall.getScope().equals(assertionCall.getScope()) && + blockMethodCall.getArguments().size() == 2 && + blockMethodCall.getArguments().get(0).equals(assertionCall.getArgument(0)) + ) { + return blockMethodCall.findAncestor(ExpressionStmt.class); + } + + } + // TODO: + return Optional.empty(); + } + +} 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 new file mode 100644 index 0000000..c54a994 --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/utils/CodeUtils.java @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.core.utils; + +import com.github.javaparser.ast.type.Type; + +public final class CodeUtils { + + private CodeUtils() { + // This constructor is used to hide the public one + } + + /** + * Cast the value if the current type doesn't match the required type. + *
+ * Given the following example: + * + * int withoutCast = 1; + * double withCast = (double) 1; + * + * The variable withoutCast doesn't need to be casted, since we have int as required type and int as value type. + * While in the variable withCast we have double as required type and int as value type. + * + * @param value The value to be returned. + * @param requiredType The expected type to be casted if needed. + * @param valueType The type of the value to be returned. + * + * @return The value casted if needed. + */ + public static String castValue(String value, Type requiredType, String valueType) { + String requiredTypeName = requiredType.asString(); + + if (requiredTypeName.equals(valueType)) + return value; + return String.format("(%s) %s", requiredTypeName, value); + } + +} diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/CloneVisitorGenerator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/CloneVisitorGenerator.java new file mode 100644 index 0000000..e3036ba --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/CloneVisitorGenerator.java @@ -0,0 +1,86 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.core.visitor; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.generator.VisitorGenerator; +import com.github.javaparser.metamodel.BaseNodeMetaModel; +import com.github.javaparser.metamodel.CompilationUnitMetaModel; +import com.github.javaparser.metamodel.PropertyMetaModel; +import com.github.javaparser.utils.SeparatedItemStringBuilder; +import com.github.javaparser.utils.SourceRoot; + +import static com.github.javaparser.utils.CodeGenerationUtils.f; + +/** + * Generates JavaParser's CloneVisitor. + */ +public class CloneVisitorGenerator extends VisitorGenerator { + public CloneVisitorGenerator(SourceRoot sourceRoot) { + super(sourceRoot, "com.github.javaparser.ast.visitor", "CloneVisitor", "Visitable", "Object", true); + } + + @Override + protected void generateVisitMethodBody(BaseNodeMetaModel node, MethodDeclaration visitMethod, CompilationUnit compilationUnit) { + visitMethod.getParameters().forEach(p -> p.setFinal(true)); + + BlockStmt body = visitMethod.getBody().get(); + body.getStatements().clear(); + + for (PropertyMetaModel field : node.getAllPropertyMetaModels()) { + final String getter = field.getGetterMethodName() + "()"; + if (field.getNodeReference().isPresent()) { + if (field.isOptional() && field.isNodeList()) { + body.addStatement(f("NodeList<%s> %s = cloneList(n.%s.orElse(null), arg);", field.getTypeNameGenerified(), field.getName(), getter)); + } else if (field.isNodeList()) { + body.addStatement(f("NodeList<%s> %s = cloneList(n.%s, arg);", field.getTypeNameGenerified(), field.getName(), getter)); + } else { + body.addStatement(f("%s %s = cloneNode(n.%s, arg);", field.getTypeNameGenerified(), field.getName(), getter)); + } + } + } + + SeparatedItemStringBuilder builder = new SeparatedItemStringBuilder(f("%s r = new %s(", node.getTypeNameGenerified(), node.getTypeNameGenerified()), ",", ");"); + builder.append("n.getTokenRange().orElse(null)"); + for (PropertyMetaModel field : node.getConstructorParameters()) { + if ("comment".equals(field.getName())) { + continue; + } + if (field.getNodeReference().isPresent()) { + builder.append(field.getName()); + } else { + builder.append(f("n.%s()", field.getGetterMethodName())); + } + } + + body.addStatement(builder.toString()); + if(node instanceof CompilationUnitMetaModel) { + body.addStatement("n.getStorage().ifPresent(s -> r.setStorage(s.getPath(), s.getEncoding()));"); + } + body.addStatement("r.setComment(comment);"); + body.addStatement("n.getOrphanComments().stream().map(Comment::clone).forEach(r::addOrphanComment);"); + body.addStatement("copyData(n, r);"); + body.addStatement("return r;"); + } +} diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/EqualsVisitorGenerator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/EqualsVisitorGenerator.java new file mode 100644 index 0000000..23ea256 --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/EqualsVisitorGenerator.java @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.core.visitor; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.generator.VisitorGenerator; +import com.github.javaparser.metamodel.BaseNodeMetaModel; +import com.github.javaparser.metamodel.PropertyMetaModel; +import com.github.javaparser.utils.SourceRoot; + +import static com.github.javaparser.utils.CodeGenerationUtils.f; + +/** + * Generates JavaParser's EqualsVisitor. + */ +public class EqualsVisitorGenerator extends VisitorGenerator { + public EqualsVisitorGenerator(SourceRoot sourceRoot) { + super(sourceRoot, "com.github.javaparser.ast.visitor", "EqualsVisitor", "Boolean", "Visitable", true); + } + + @Override + protected void generateVisitMethodBody(BaseNodeMetaModel node, MethodDeclaration visitMethod, CompilationUnit compilationUnit) { + visitMethod.getParameters().forEach(p -> p.setFinal(true)); + + BlockStmt body = visitMethod.getBody().get(); + body.getStatements().clear(); + + body.addStatement(f("final %s n2 = (%s) arg;", node.getTypeName(), node.getTypeName())); + + for (PropertyMetaModel field : node.getAllPropertyMetaModels()) { + final String getter = field.getGetterMethodName() + "()"; + if (field.getNodeReference().isPresent()) { + if (field.isNodeList()) { + body.addStatement(f("if (!nodesEquals(n.%s, n2.%s)) return false;", getter, getter)); + } else { + body.addStatement(f("if (!nodeEquals(n.%s, n2.%s)) return false;", getter, getter)); + } + } else { + body.addStatement(f("if (!objEquals(n.%s, n2.%s)) return false;", getter, getter)); + } + } + if (body.getStatements().size() == 1) { + // Only the cast line was added, but nothing is using it, so remove it again. + body.getStatements().clear(); + } + body.addStatement("return true;"); + } +} diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/GenericListVisitorAdapterGenerator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/GenericListVisitorAdapterGenerator.java new file mode 100644 index 0000000..67e76d6 --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/GenericListVisitorAdapterGenerator.java @@ -0,0 +1,77 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.core.visitor; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.generator.VisitorGenerator; +import com.github.javaparser.metamodel.BaseNodeMetaModel; +import com.github.javaparser.metamodel.PropertyMetaModel; +import com.github.javaparser.utils.SourceRoot; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static com.github.javaparser.utils.CodeGenerationUtils.f; + +/** + * Generates JavaParser's GenericListVisitorAdapter. + */ +public class GenericListVisitorAdapterGenerator extends VisitorGenerator { + public GenericListVisitorAdapterGenerator(SourceRoot sourceRoot) { + super(sourceRoot, "com.github.javaparser.ast.visitor", "GenericListVisitorAdapter", "List", "A", true); + } + + @Override + protected void generateVisitMethodBody(BaseNodeMetaModel node, MethodDeclaration visitMethod, CompilationUnit compilationUnit) { + visitMethod.getParameters().forEach(p -> p.setFinal(true)); + + BlockStmt body = visitMethod.getBody().get(); + body.getStatements().clear(); + body.addStatement("List result = new ArrayList<>();"); + body.addStatement("List tmp;"); + + final String resultCheck = "if (tmp != null) result.addAll(tmp);"; + + for (PropertyMetaModel field : node.getAllPropertyMetaModels()) { + final String getter = field.getGetterMethodName() + "()"; + if (field.getNodeReference().isPresent()) { + if (field.isOptional()) { + body.addStatement(f("if (n.%s.isPresent()) {" + + " tmp = n.%s.get().accept(this, arg);" + + " %s" + + "}", getter, getter, resultCheck)); + } else { + body.addStatement(f("{ tmp = n.%s.accept(this, arg); %s }", getter, resultCheck)); + } + } + } + body.addStatement("return result;"); + Arrays.stream(new Class[] {List.class, ArrayList.class}).filter(c -> + compilationUnit.getImports().stream().noneMatch( + i -> c.getName().equals(i.getName().asString()) + ) + ).forEach(compilationUnit::addImport); + } +} diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/GenericVisitorAdapterGenerator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/GenericVisitorAdapterGenerator.java new file mode 100644 index 0000000..202653c --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/GenericVisitorAdapterGenerator.java @@ -0,0 +1,68 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.core.visitor; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.generator.VisitorGenerator; +import com.github.javaparser.metamodel.BaseNodeMetaModel; +import com.github.javaparser.metamodel.PropertyMetaModel; +import com.github.javaparser.utils.SourceRoot; + +import static com.github.javaparser.utils.CodeGenerationUtils.f; + +/** + * Generates JavaParser's VoidVisitorAdapter. + */ +public class GenericVisitorAdapterGenerator extends VisitorGenerator { + public GenericVisitorAdapterGenerator(SourceRoot sourceRoot) { + super(sourceRoot, "com.github.javaparser.ast.visitor", "GenericVisitorAdapter", "R", "A", true); + } + + @Override + protected void generateVisitMethodBody(BaseNodeMetaModel node, MethodDeclaration visitMethod, CompilationUnit compilationUnit) { + visitMethod.getParameters().forEach(p -> p.setFinal(true)); + + BlockStmt body = visitMethod.getBody().get(); + body.getStatements().clear(); + + body.addStatement("R result;"); + + final String resultCheck = "if (result != null) return result;"; + + for (PropertyMetaModel field : node.getAllPropertyMetaModels()) { + final String getter = field.getGetterMethodName() + "()"; + if (field.getNodeReference().isPresent()) { + if (field.isOptional()) { + body.addStatement(f("if (n.%s.isPresent()) {" + + " result = n.%s.get().accept(this, arg);" + + " %s" + + "}", getter, getter, resultCheck)); + } else { + body.addStatement(f("{ result = n.%s.accept(this, arg); %s }", getter, resultCheck)); + } + } + } + body.addStatement("return null;"); + } +} diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/GenericVisitorGenerator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/GenericVisitorGenerator.java new file mode 100644 index 0000000..3c2b822 --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/GenericVisitorGenerator.java @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.core.visitor; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.generator.VisitorGenerator; +import com.github.javaparser.metamodel.BaseNodeMetaModel; +import com.github.javaparser.utils.SourceRoot; + +/** + * Generates JavaParser's GenericVisitor. + */ +public class GenericVisitorGenerator extends VisitorGenerator { + public GenericVisitorGenerator(SourceRoot sourceRoot) { + super(sourceRoot, "com.github.javaparser.ast.visitor", "GenericVisitor", "R", "A", true); + } + + @Override + protected void generateVisitMethodBody(BaseNodeMetaModel node, MethodDeclaration visitMethod, CompilationUnit compilationUnit) { + visitMethod.getParameters().forEach(p -> p.setFinal(false)); + + visitMethod.setBody(null); + } +} diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/GenericVisitorWithDefaultsGenerator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/GenericVisitorWithDefaultsGenerator.java new file mode 100644 index 0000000..1dd02d3 --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/GenericVisitorWithDefaultsGenerator.java @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.core.visitor; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.generator.VisitorGenerator; +import com.github.javaparser.metamodel.BaseNodeMetaModel; +import com.github.javaparser.utils.SourceRoot; + +/** + * Generates JavaParser's GenericVisitorWithDefaults. + */ +public class GenericVisitorWithDefaultsGenerator extends VisitorGenerator { + public GenericVisitorWithDefaultsGenerator(SourceRoot sourceRoot) { + super(sourceRoot, "com.github.javaparser.ast.visitor", "GenericVisitorWithDefaults", "R", "A", true); + } + + @Override + protected void generateVisitMethodBody(BaseNodeMetaModel node, MethodDeclaration visitMethod, CompilationUnit compilationUnit) { + visitMethod.getParameters().forEach(p -> p.setFinal(true)); + + BlockStmt body = visitMethod.getBody().get(); + body.getStatements().clear(); + + body.addStatement("return defaultAction(n, arg);"); + } +} diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/HashCodeVisitorGenerator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/HashCodeVisitorGenerator.java new file mode 100644 index 0000000..1d9265f --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/HashCodeVisitorGenerator.java @@ -0,0 +1,80 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.core.visitor; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.generator.VisitorGenerator; +import com.github.javaparser.metamodel.BaseNodeMetaModel; +import com.github.javaparser.metamodel.PropertyMetaModel; +import com.github.javaparser.utils.SeparatedItemStringBuilder; +import com.github.javaparser.utils.SourceRoot; + +import java.util.List; + +import static com.github.javaparser.StaticJavaParser.parseStatement; + +/** + * Generates JavaParser's HashCodeVisitor. + */ +public class HashCodeVisitorGenerator extends VisitorGenerator { + public HashCodeVisitorGenerator(SourceRoot sourceRoot) { + super(sourceRoot, "com.github.javaparser.ast.visitor", "HashCodeVisitor", "Integer", "Void", true); + } + + @Override + protected void generateVisitMethodBody(BaseNodeMetaModel node, MethodDeclaration visitMethod, CompilationUnit compilationUnit) { + visitMethod.getParameters().forEach(p -> p.setFinal(true)); + + final BlockStmt body = visitMethod.getBody().get(); + body.getStatements().clear(); + + final SeparatedItemStringBuilder builder = new SeparatedItemStringBuilder("return ", "* 31 +", ";"); + final List propertyMetaModels= node.getAllPropertyMetaModels(); + if (propertyMetaModels.isEmpty()) { + builder.append("0"); + } else { + for (PropertyMetaModel field : propertyMetaModels) { + final String getter = field.getGetterMethodName() + "()"; + // Is this field another AST node? Visit it. + if (field.getNodeReference().isPresent()) { + if (field.isOptional()) { + builder.append("(n.%s.isPresent()? n.%s.get().accept(this, arg):0)", getter, getter); + } else { + builder.append("(n.%s.accept(this, arg))", getter); + } + } else { + Class type = field.getType(); + if (type.equals(boolean.class)) { + builder.append("(n.%s?1:0)", getter); + } else if (type.equals(int.class)) { + builder.append("n.%s", getter); + } else { + builder.append("(n.%s.hashCode())", getter); + } + } + } + } + body.addStatement(parseStatement(builder.toString())); + } +} diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/ModifierVisitorGenerator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/ModifierVisitorGenerator.java new file mode 100644 index 0000000..fb4b6c2 --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/ModifierVisitorGenerator.java @@ -0,0 +1,124 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.core.visitor; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.expr.BinaryExpr; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.generator.VisitorGenerator; +import com.github.javaparser.metamodel.BaseNodeMetaModel; +import com.github.javaparser.metamodel.PropertyMetaModel; +import com.github.javaparser.utils.SeparatedItemStringBuilder; +import com.github.javaparser.utils.SourceRoot; + +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.stream.Collectors; + +import static com.github.javaparser.utils.CodeGenerationUtils.f; + +public class ModifierVisitorGenerator extends VisitorGenerator { + public ModifierVisitorGenerator(SourceRoot sourceRoot) { + super(sourceRoot, "com.github.javaparser.ast.visitor", "ModifierVisitor", "Visitable", "A", true); + } + + @Override + protected void generateVisitMethodBody(BaseNodeMetaModel node, MethodDeclaration visitMethod, CompilationUnit compilationUnit) { + visitMethod.getParameters().forEach(p -> p.setFinal(true)); + + BlockStmt body = visitMethod.getBody().get(); + body.getStatements().clear(); + + // FIXME: Bit of a hacky way to get this fixed order, and then have everything else (note this list is reversed) + List order = Arrays.asList( +// "comment", "name", "members", "parameters", "name", + "modifiers", "annotations" + ); + List sortedPropertyMetaModels = node.getAllPropertyMetaModels() + .stream() + .sorted(Comparator + .comparingInt((PropertyMetaModel o) -> order.indexOf(o.getName())).reversed() +// .thenComparing(PropertyMetaModel::getName) + ) + .collect(Collectors.toList()); + + // + sortedPropertyMetaModels.forEach(property -> extracted(body, property)); + + // + if (node.is(BinaryExpr.class)) { + body.addStatement("if (left == null) return right;"); + body.addStatement("if (right == null) return left;"); + } else { + final SeparatedItemStringBuilder collapseCheck = new SeparatedItemStringBuilder("if(", "||", ") return null;"); + sortedPropertyMetaModels.forEach(property -> { + if (property.isRequired() && property.isNode()) { + if (property.isNodeList()) { + if (property.isNonEmpty()) { + collapseCheck.append(f("%s.isEmpty()", property.getName())); + } + } else { + collapseCheck.append(f("%s==null", property.getName())); + } + } + }); + if (collapseCheck.hasItems()) { + body.addStatement(collapseCheck.toString()); + } + } + + // + sortedPropertyMetaModels.forEach(property -> { + if (property.isNode()) { + body.addStatement(f("n.%s(%s);", property.getSetterMethodName(), property.getName())); + } + }); + + // + body.addStatement("return n;"); + } + + private void extracted(BlockStmt body, PropertyMetaModel property) { + if (property.isNode()) { + if (property.isNodeList()) { + body.addStatement(f("NodeList<%s> %s = modifyList(n.%s(), arg);", + property.getTypeNameGenerified(), + property.getName(), + property.getGetterMethodName())); + } else if (property.isOptional()) { + body.addStatement(f("%s %s = n.%s().map(s -> (%s) s.accept(this, arg)).orElse(null);", + property.getTypeNameGenerified(), + property.getName(), + property.getGetterMethodName(), + property.getTypeNameGenerified())); + } else { + body.addStatement(f("%s %s = (%s) n.%s().accept(this, arg);", + property.getTypeNameGenerified(), + property.getName(), + property.getTypeNameGenerified(), + property.getGetterMethodName())); + } + } + } +} diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/NoCommentEqualsVisitorGenerator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/NoCommentEqualsVisitorGenerator.java new file mode 100644 index 0000000..104ea2e --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/NoCommentEqualsVisitorGenerator.java @@ -0,0 +1,76 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.core.visitor; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.generator.VisitorGenerator; +import com.github.javaparser.metamodel.BaseNodeMetaModel; +import com.github.javaparser.metamodel.JavaParserMetaModel; +import com.github.javaparser.metamodel.PropertyMetaModel; +import com.github.javaparser.utils.SourceRoot; + +import static com.github.javaparser.utils.CodeGenerationUtils.f; + +public class NoCommentEqualsVisitorGenerator extends VisitorGenerator { + + public NoCommentEqualsVisitorGenerator(SourceRoot sourceRoot) { + super(sourceRoot, "com.github.javaparser.ast.visitor", "NoCommentEqualsVisitor", "Boolean", "Visitable", true); + } + + @Override + protected void generateVisitMethodBody(BaseNodeMetaModel node, MethodDeclaration visitMethod, + CompilationUnit compilationUnit) { + visitMethod.getParameters().forEach(p -> p.setFinal(true)); + + BlockStmt body = visitMethod.getBody().get(); + body.getStatements().clear(); + + if (!(node.equals(JavaParserMetaModel.lineCommentMetaModel) + || node.equals(JavaParserMetaModel.blockCommentMetaModel) + || node.equals(JavaParserMetaModel.javadocCommentMetaModel))) { + + body.addStatement(f("final %s n2 = (%s) arg;", node.getTypeName(), node.getTypeName())); + + for (PropertyMetaModel field : node.getAllPropertyMetaModels()) { + final String getter = field.getGetterMethodName() + "()"; + if (field.equals(JavaParserMetaModel.nodeMetaModel.commentPropertyMetaModel)) + continue; + if (field.getNodeReference().isPresent()) { + if (field.isNodeList()) { + body.addStatement(f("if (!nodesEquals(n.%s, n2.%s)) return false;", getter, getter)); + } else { + body.addStatement(f("if (!nodeEquals(n.%s, n2.%s)) return false;", getter, getter)); + } + } else { + body.addStatement(f("if (!objEquals(n.%s, n2.%s)) return false;", getter, getter)); + } + } + if (body.getStatements().size() == 1) { + // Only the cast line was added, but nothing is using it, so remove it again. + body.getStatements().clear(); + } + } + body.addStatement("return true;"); + } +} 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 new file mode 100644 index 0000000..b7e4169 --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/NoCommentHashCodeVisitorGenerator.java @@ -0,0 +1,89 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.core.visitor; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.generator.VisitorGenerator; +import com.github.javaparser.metamodel.BaseNodeMetaModel; +import com.github.javaparser.metamodel.JavaParserMetaModel; +import com.github.javaparser.metamodel.PropertyMetaModel; +import com.github.javaparser.utils.SeparatedItemStringBuilder; +import com.github.javaparser.utils.SourceRoot; + +import java.util.List; + +import static com.github.javaparser.StaticJavaParser.parseStatement; + +public class NoCommentHashCodeVisitorGenerator extends VisitorGenerator { + + public NoCommentHashCodeVisitorGenerator(SourceRoot sourceRoot) { + super(sourceRoot, "com.github.javaparser.ast.visitor", "NoCommentHashCodeVisitor", "Integer", "Void", true); + } + + @Override + protected void generateVisitMethodBody(BaseNodeMetaModel node, MethodDeclaration visitMethod, + CompilationUnit compilationUnit) { + visitMethod.getParameters().forEach(p -> p.setFinal(true)); + + final BlockStmt body = visitMethod.getBody().get(); + body.getStatements().clear(); + + final SeparatedItemStringBuilder builder = new SeparatedItemStringBuilder("return ", "* 31 +", ";"); + final List propertyMetaModels = node.getAllPropertyMetaModels(); + if (node.equals(JavaParserMetaModel.lineCommentMetaModel) + || node.equals(JavaParserMetaModel.blockCommentMetaModel) + || node.equals(JavaParserMetaModel.javadocCommentMetaModel) || propertyMetaModels.isEmpty()) { + builder.append("0"); + } else { + for (PropertyMetaModel field : propertyMetaModels) { + final String getter = field.getGetterMethodName() + "()"; + if (field.equals(JavaParserMetaModel.nodeMetaModel.commentPropertyMetaModel)) { + if (propertyMetaModels.size() == 1) { + builder.append("0"); + break; + } + continue; + } + // Is this field another AST node? Visit it. + if (field.getNodeReference().isPresent()) { + if (field.isOptional()) { + builder.append("(n.%s.isPresent()? n.%s.get().accept(this, arg):0)", getter, getter); + } else { + builder.append("(n.%s.accept(this, arg))", getter); + } + } else { + Class type = field.getType(); + if (type.equals(boolean.class)) { + builder.append("(n.%s?1:0)", getter); + } else if (type.equals(int.class)) { + builder.append("n.%s", getter); + } else { + builder.append("(n.%s.hashCode())", getter); + } + } + } + } + body.addStatement(parseStatement(builder.toString())); + } +} diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/ObjectIdentityEqualsVisitorGenerator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/ObjectIdentityEqualsVisitorGenerator.java new file mode 100644 index 0000000..066bdd8 --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/ObjectIdentityEqualsVisitorGenerator.java @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.core.visitor; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.generator.VisitorGenerator; +import com.github.javaparser.metamodel.BaseNodeMetaModel; +import com.github.javaparser.utils.SourceRoot; + +/** + * Generates JavaParser's ObjectIdentityEqualsVisitor. + */ +public class ObjectIdentityEqualsVisitorGenerator extends VisitorGenerator { + public ObjectIdentityEqualsVisitorGenerator(SourceRoot sourceRoot) { + super(sourceRoot, "com.github.javaparser.ast.visitor", "ObjectIdentityEqualsVisitor", "Boolean", "Visitable", true); + } + + @Override + protected void generateVisitMethodBody(BaseNodeMetaModel node, MethodDeclaration visitMethod, CompilationUnit compilationUnit) { + visitMethod.getParameters().forEach(p -> p.setFinal(true)); + + BlockStmt body = visitMethod.getBody().get(); + body.getStatements().clear(); + + body.addStatement("return n == arg;"); + } +} diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/ObjectIdentityHashCodeVisitorGenerator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/ObjectIdentityHashCodeVisitorGenerator.java new file mode 100644 index 0000000..8081bc3 --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/ObjectIdentityHashCodeVisitorGenerator.java @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.core.visitor; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.generator.VisitorGenerator; +import com.github.javaparser.metamodel.BaseNodeMetaModel; +import com.github.javaparser.utils.SourceRoot; + +/** + * Generates JavaParser's ObjectIdentityHashCodeVisitor. + */ +public class ObjectIdentityHashCodeVisitorGenerator extends VisitorGenerator { + public ObjectIdentityHashCodeVisitorGenerator(SourceRoot sourceRoot) { + super(sourceRoot, "com.github.javaparser.ast.visitor", "ObjectIdentityHashCodeVisitor", "Integer", "Void", true); + } + + @Override + protected void generateVisitMethodBody(BaseNodeMetaModel node, MethodDeclaration visitMethod, CompilationUnit compilationUnit) { + visitMethod.getParameters().forEach(p -> p.setFinal(true)); + + final BlockStmt body = visitMethod.getBody().get(); + body.getStatements().clear(); + body.addStatement("return n.hashCode();"); + } +} diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/VoidVisitorAdapterGenerator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/VoidVisitorAdapterGenerator.java new file mode 100644 index 0000000..d1cc8d3 --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/VoidVisitorAdapterGenerator.java @@ -0,0 +1,64 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.core.visitor; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.generator.VisitorGenerator; +import com.github.javaparser.metamodel.BaseNodeMetaModel; +import com.github.javaparser.metamodel.PropertyMetaModel; +import com.github.javaparser.utils.SourceRoot; + +import static com.github.javaparser.utils.CodeGenerationUtils.f; + +/** + * Generates JavaParser's VoidVisitorAdapter. + */ +public class VoidVisitorAdapterGenerator extends VisitorGenerator { + public VoidVisitorAdapterGenerator(SourceRoot sourceRoot) { + super(sourceRoot, "com.github.javaparser.ast.visitor", "VoidVisitorAdapter", "void", "A", true); + } + + @Override + protected void generateVisitMethodBody(BaseNodeMetaModel node, MethodDeclaration visitMethod, CompilationUnit compilationUnit) { + visitMethod.getParameters().forEach(p -> p.setFinal(true)); + + BlockStmt body = visitMethod.getBody().get(); + body.getStatements().clear(); + + for (PropertyMetaModel field : node.getAllPropertyMetaModels()) { + final String getter = field.getGetterMethodName() + "()"; + if (field.getNodeReference().isPresent()) { + if (field.isOptional() && field.isNodeList()) { + body.addStatement(f("n.%s.ifPresent( l -> l.forEach( v -> v.accept(this, arg)));", getter)); + } else if (field.isOptional()) { + body.addStatement(f("n.%s.ifPresent(l -> l.accept(this, arg));", getter)); + } else if (field.isNodeList()) { + body.addStatement(f("n.%s.forEach(p -> p.accept(this, arg));", getter)); + } else { + body.addStatement(f("n.%s.accept(this, arg);", getter)); + } + } + } + } +} diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/VoidVisitorGenerator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/VoidVisitorGenerator.java new file mode 100644 index 0000000..a4fefe1 --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/VoidVisitorGenerator.java @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.core.visitor; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.generator.VisitorGenerator; +import com.github.javaparser.metamodel.BaseNodeMetaModel; +import com.github.javaparser.utils.SourceRoot; + +/** + * Generates JavaParser's VoidVisitor. + */ +public class VoidVisitorGenerator extends VisitorGenerator { + public VoidVisitorGenerator(SourceRoot sourceRoot) { + super(sourceRoot, "com.github.javaparser.ast.visitor", "VoidVisitor", "void", "A", true); + } + + @Override + protected void generateVisitMethodBody(BaseNodeMetaModel node, MethodDeclaration visitMethod, CompilationUnit compilationUnit) { + visitMethod.getParameters().forEach(p -> p.setFinal(false)); + + visitMethod.setBody(null); + } +} diff --git a/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/VoidVisitorWithDefaultsGenerator.java b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/VoidVisitorWithDefaultsGenerator.java new file mode 100644 index 0000000..8a36f47 --- /dev/null +++ b/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/visitor/VoidVisitorWithDefaultsGenerator.java @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.core.visitor; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.generator.VisitorGenerator; +import com.github.javaparser.metamodel.BaseNodeMetaModel; +import com.github.javaparser.utils.SourceRoot; + +/** + * Generates JavaParser's VoidVisitorWithDefaults. + */ +public class VoidVisitorWithDefaultsGenerator extends VisitorGenerator { + public VoidVisitorWithDefaultsGenerator(SourceRoot sourceRoot) { + super(sourceRoot, "com.github.javaparser.ast.visitor", "VoidVisitorWithDefaults", "void", "A", true); + } + + @Override + protected void generateVisitMethodBody(BaseNodeMetaModel node, MethodDeclaration visitMethod, CompilationUnit compilationUnit) { + visitMethod.getParameters().forEach(p -> p.setFinal(true)); + + BlockStmt body = visitMethod.getBody().get(); + body.getStatements().clear(); + + body.addStatement("defaultAction(n, arg);"); + } +} diff --git a/javaparser-core-generators/src/test/java/com/github/javaparser/generator/core/quality/NotNullGeneratorTest.java b/javaparser-core-generators/src/test/java/com/github/javaparser/generator/core/quality/NotNullGeneratorTest.java new file mode 100644 index 0000000..a35f239 --- /dev/null +++ b/javaparser-core-generators/src/test/java/com/github/javaparser/generator/core/quality/NotNullGeneratorTest.java @@ -0,0 +1,81 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.core.quality; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.printer.DefaultPrettyPrinter; +import com.github.javaparser.utils.SourceRoot; +import org.junit.jupiter.api.Test; + +import java.io.File; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + +class NotNullGeneratorTest { + + @Test + void testExecutionOfGenerator() throws Exception { + + // Setup the + String resourcesFolderPath = getClass().getCanonicalName().replace(".", File.separator); + + String basePath = Paths.get("src", "test", "resources").toString(); + Path originalFile = Paths.get(basePath, resourcesFolderPath, "original"); + Path expectedFile = Paths.get(basePath, resourcesFolderPath, "expected"); + + SourceRoot originalSources = new SourceRoot(originalFile); + SourceRoot expectedSources = new SourceRoot(expectedFile); + expectedSources.tryToParse(); + + // Generate the information + new NotNullGenerator(originalSources).generate(); + + List editedSourceCus = originalSources.getCompilationUnits(); + List expectedSourcesCus = expectedSources.getCompilationUnits(); + assertEquals(expectedSourcesCus.size(), editedSourceCus.size()); + + // Check if all the files match the expected result + for (int i = 0 ; i < editedSourceCus.size() ; i++) { + + DefaultPrettyPrinter printer = new DefaultPrettyPrinter(); + String expectedCode = printer.print(expectedSourcesCus.get(i)); + String editedCode = printer.print(editedSourceCus.get(i)); + + if (!expectedCode.equals(editedCode)) { + System.out.println("Expected:"); + System.out.println("####"); + System.out.println(expectedSourcesCus.get(i)); + System.out.println("####"); + System.out.println("Actual:"); + System.out.println("####"); + System.out.println(editedSourceCus.get(i)); + System.out.println("####"); + fail("Actual code doesn't match with the expected code."); + } + } + } + +} diff --git a/javaparser-core-generators/src/test/java/com/github/javaparser/generator/core/utils/CodeUtilsTest.java b/javaparser-core-generators/src/test/java/com/github/javaparser/generator/core/utils/CodeUtilsTest.java new file mode 100644 index 0000000..bfba996 --- /dev/null +++ b/javaparser-core-generators/src/test/java/com/github/javaparser/generator/core/utils/CodeUtilsTest.java @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.core.utils; + +import com.github.javaparser.StaticJavaParser; +import com.github.javaparser.ast.type.PrimitiveType; +import com.github.javaparser.ast.type.Type; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.generator.core.utils.CodeUtils.castValue; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class CodeUtilsTest { + + private static final String RETURN_VALUE = "this"; + + @Test + void castReturnValue_whenAValueMatchesTheExpectedTypeNoCastIsNeeded() { + Type returnType = PrimitiveType.booleanType(); + Type valueType = PrimitiveType.booleanType(); + + assertEquals(RETURN_VALUE, castValue(RETURN_VALUE, returnType, valueType.asString())); + } + + @Test + void castReturnValue_whenAValueIsNotAssignedByReturnShouldBeCasted() { + Type returnType = StaticJavaParser.parseType("String"); + Type valueType = StaticJavaParser.parseType("Object"); + + assertEquals(String.format("(%s) %s", returnType, RETURN_VALUE), castValue(RETURN_VALUE, returnType, valueType.asString())); + } + +} diff --git a/javaparser-core-generators/src/test/resources/com/github/javaparser/generator/core/quality/NotNullGeneratorTest/expected/ConstructorParameterTest.java b/javaparser-core-generators/src/test/resources/com/github/javaparser/generator/core/quality/NotNullGeneratorTest/expected/ConstructorParameterTest.java new file mode 100644 index 0000000..15bfffa --- /dev/null +++ b/javaparser-core-generators/src/test/resources/com/github/javaparser/generator/core/quality/NotNullGeneratorTest/expected/ConstructorParameterTest.java @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2021 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.example; + +import com.github.javaparser.quality.NotNull; +import com.github.javaparser.quality.Nullable; +import com.github.javaparser.quality.Preconditions; + +class ConstructorParameterTest { + + private final String a; + + private final String b; + + private final String c; + + public ConstructorParameterTest(@NotNull String notNullString, @Nullable String nullableString, String otherString) { + Preconditions.checkNotNull(notNullString, "Parameter notNullString can't be null."); + this.a = notNullString; + this.b = nullableString; + this.c = otherString; + } +} diff --git a/javaparser-core-generators/src/test/resources/com/github/javaparser/generator/core/quality/NotNullGeneratorTest/expected/ConstructorParameterWithSuperTest.java b/javaparser-core-generators/src/test/resources/com/github/javaparser/generator/core/quality/NotNullGeneratorTest/expected/ConstructorParameterWithSuperTest.java new file mode 100644 index 0000000..43649c6 --- /dev/null +++ b/javaparser-core-generators/src/test/resources/com/github/javaparser/generator/core/quality/NotNullGeneratorTest/expected/ConstructorParameterWithSuperTest.java @@ -0,0 +1,36 @@ +import com.github.javaparser.quality.NotNull; +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2021 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. + */ +import com.github.javaparser.quality.Preconditions; + +class A { + + public A(String a) { + } +} + +class B { + + public B(@NotNull String c) { + super("ok"); + Preconditions.checkNotNull(c, "Parameter c can't be null."); + } +} diff --git a/javaparser-core-generators/src/test/resources/com/github/javaparser/generator/core/quality/NotNullGeneratorTest/expected/MethodParameterRerunTest.java b/javaparser-core-generators/src/test/resources/com/github/javaparser/generator/core/quality/NotNullGeneratorTest/expected/MethodParameterRerunTest.java new file mode 100644 index 0000000..22e149e --- /dev/null +++ b/javaparser-core-generators/src/test/resources/com/github/javaparser/generator/core/quality/NotNullGeneratorTest/expected/MethodParameterRerunTest.java @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2021 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. + */ + +import com.github.javaparser.quality.NotNull; +import com.github.javaparser.quality.Preconditions; + +class A { + + public void method(@NotNull String notNull, @NotNull String secondNotNull) { + Preconditions.checkNotNull(notNull, "Parameter notNull can't be null."); + Preconditions.checkNotNull(secondNotNull, "Parameter secondNotNull can't be null."); + } +} diff --git a/javaparser-core-generators/src/test/resources/com/github/javaparser/generator/core/quality/NotNullGeneratorTest/expected/MethodParameterTest.java b/javaparser-core-generators/src/test/resources/com/github/javaparser/generator/core/quality/NotNullGeneratorTest/expected/MethodParameterTest.java new file mode 100644 index 0000000..5c5ba8e --- /dev/null +++ b/javaparser-core-generators/src/test/resources/com/github/javaparser/generator/core/quality/NotNullGeneratorTest/expected/MethodParameterTest.java @@ -0,0 +1,33 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2021 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. + */ + +import com.github.javaparser.quality.NotNull; +import com.github.javaparser.quality.Preconditions; + +class A { + + public void method(@NotNull String notNull) { + Preconditions.checkNotNull(notNull, "Parameter notNull can't be null."); + } + + public void method(int age) { + } +} diff --git a/javaparser-core-generators/src/test/resources/com/github/javaparser/generator/core/quality/NotNullGeneratorTest/original/ConstructorParameterTest.java b/javaparser-core-generators/src/test/resources/com/github/javaparser/generator/core/quality/NotNullGeneratorTest/original/ConstructorParameterTest.java new file mode 100644 index 0000000..9f9a593 --- /dev/null +++ b/javaparser-core-generators/src/test/resources/com/github/javaparser/generator/core/quality/NotNullGeneratorTest/original/ConstructorParameterTest.java @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2021 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.example; + +import com.github.javaparser.quality.NotNull; +import com.github.javaparser.quality.Nullable; + +class ConstructorParameterTest { + + private final String a; + private final String b; + private final String c; + + public ConstructorParameterTest(@NotNull String notNullString, @Nullable String nullableString, + String otherString) { + this.a = notNullString; + this.b = nullableString; + this.c = otherString; + } + +} diff --git a/javaparser-core-generators/src/test/resources/com/github/javaparser/generator/core/quality/NotNullGeneratorTest/original/ConstructorParameterWithSuperTest.java b/javaparser-core-generators/src/test/resources/com/github/javaparser/generator/core/quality/NotNullGeneratorTest/original/ConstructorParameterWithSuperTest.java new file mode 100644 index 0000000..2938191 --- /dev/null +++ b/javaparser-core-generators/src/test/resources/com/github/javaparser/generator/core/quality/NotNullGeneratorTest/original/ConstructorParameterWithSuperTest.java @@ -0,0 +1,34 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2021 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. + */ + +import com.github.javaparser.quality.NotNull; + +class A { + public A(String a) {} +} + +class B { + + public B(@NotNull String c) { + super("ok"); + } + +} diff --git a/javaparser-core-generators/src/test/resources/com/github/javaparser/generator/core/quality/NotNullGeneratorTest/original/MethodParameterRerunTest.java b/javaparser-core-generators/src/test/resources/com/github/javaparser/generator/core/quality/NotNullGeneratorTest/original/MethodParameterRerunTest.java new file mode 100644 index 0000000..30ce35b --- /dev/null +++ b/javaparser-core-generators/src/test/resources/com/github/javaparser/generator/core/quality/NotNullGeneratorTest/original/MethodParameterRerunTest.java @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2021 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. + */ + +import com.github.javaparser.quality.NotNull; +import com.github.javaparser.quality.Preconditions; + +class A { + + public void method(@NotNull String notNull, @NotNull String secondNotNull) { + Preconditions.checkNotNull(notNull, "This was aan old message."); + Preconditions.checkNotNull(secondNotNull, "Parameter secondNotNull can't be null."); + } +} diff --git a/javaparser-core-generators/src/test/resources/com/github/javaparser/generator/core/quality/NotNullGeneratorTest/original/MethodParameterTest.java b/javaparser-core-generators/src/test/resources/com/github/javaparser/generator/core/quality/NotNullGeneratorTest/original/MethodParameterTest.java new file mode 100644 index 0000000..f66e0b9 --- /dev/null +++ b/javaparser-core-generators/src/test/resources/com/github/javaparser/generator/core/quality/NotNullGeneratorTest/original/MethodParameterTest.java @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2021 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. + */ + +import com.github.javaparser.quality.NotNull; +import com.github.javaparser.quality.Preconditions; + +class A { + + public void method(@NotNull String notNull) {} + + public void method(int age) {} + +} diff --git a/javaparser-core-metamodel-generator/pom.xml b/javaparser-core-metamodel-generator/pom.xml new file mode 100644 index 0000000..9d61e52 --- /dev/null +++ b/javaparser-core-metamodel-generator/pom.xml @@ -0,0 +1,63 @@ + + + + javaparser-parent + com.github.javaparser + 3.25.10 + + 4.0.0 + + javaparser-core-metamodel-generator + The tool that generates the code in the javaparser-metamodel module + + + + com.github.javaparser + javaparser-core + ${project.version} + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + true + + + + + + + + run-generators + + + + org.codehaus.mojo + exec-maven-plugin + + + generate-javaparser-metamodel + test + + java + + + + + test + com.github.javaparser.generator.metamodel.MetaModelGenerator + + ${project.basedir} + + + + + + + + diff --git a/javaparser-core-metamodel-generator/src/main/java/com/github/javaparser/generator/AbstractGenerator.java b/javaparser-core-metamodel-generator/src/main/java/com/github/javaparser/generator/AbstractGenerator.java new file mode 100644 index 0000000..35c97ae --- /dev/null +++ b/javaparser-core-metamodel-generator/src/main/java/com/github/javaparser/generator/AbstractGenerator.java @@ -0,0 +1,343 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator; + +import com.github.javaparser.ParseResult; +import com.github.javaparser.Problem; +import com.github.javaparser.StaticJavaParser; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Generated; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.comments.Comment; +import com.github.javaparser.ast.comments.JavadocComment; +import com.github.javaparser.ast.expr.AnnotationExpr; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.expr.StringLiteralExpr; +import com.github.javaparser.ast.nodeTypes.NodeWithAnnotations; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.ast.stmt.SwitchStmt; +import com.github.javaparser.printer.lexicalpreservation.LexicalPreservingPrinter; +import com.github.javaparser.utils.Log; +import com.github.javaparser.utils.SourceRoot; + +import java.io.IOException; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import static com.github.javaparser.ast.NodeList.toNodeList; +import static com.github.javaparser.utils.CodeGenerationUtils.f; + +/** + * A general pattern that the generators in this module will follow. + */ +public abstract class AbstractGenerator { + + protected static final String COPYRIGHT_NOTICE_JP_CORE = "\n" + + " * Copyright (C) 2007-2010 Júlio Vilmar Gesser.\n" + + " * Copyright (C) 2011, 2013-2024 The JavaParser Team.\n" + + " *\n" + + " * This file is part of JavaParser.\n" + + " *\n" + + " * JavaParser can be used either under the terms of\n" + + " * a) the GNU Lesser General Public License as published by\n" + + " * the Free Software Foundation, either version 3 of the License, or\n" + + " * (at your option) any later version.\n" + + " * b) the terms of the Apache License\n" + + " *\n" + + " * You should have received a copy of both licenses in LICENCE.LGPL and\n" + + " * LICENCE.APACHE. Please refer to those files for details.\n" + + " *\n" + + " * JavaParser is distributed in the hope that it will be useful,\n" + + " * but WITHOUT ANY WARRANTY; without even the implied warranty of\n" + + " * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" + + " * GNU Lesser General Public License for more details.\n" + + " "; + + protected static final String COPYRIGHT_NOTICE_JP_SS = "\n" + + " * Copyright (C) 2015-2016 Federico Tomassetti\n" + + " * Copyright (C) 2017-2024 The JavaParser Team.\n" + + " *\n" + + " * This file is part of JavaParser.\n" + + " *\n" + + " * JavaParser can be used either under the terms of\n" + + " * a) the GNU Lesser General Public License as published by\n" + + " * the Free Software Foundation, either version 3 of the License, or\n" + + " * (at your option) any later version.\n" + + " * b) the terms of the Apache License\n" + + " *\n" + + " * You should have received a copy of both licenses in LICENCE.LGPL and\n" + + " * LICENCE.APACHE. Please refer to those files for details.\n" + + " *\n" + + " * JavaParser is distributed in the hope that it will be useful,\n" + + " * but WITHOUT ANY WARRANTY; without even the implied warranty of\n" + + " * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" + + " * GNU Lesser General Public License for more details.\n" + + " "; + + protected final SourceRoot sourceRoot; + + protected AbstractGenerator(SourceRoot sourceRoot) { + this.sourceRoot = sourceRoot; + } + + private void addOrReplaceMethod( + ClassOrInterfaceDeclaration containingClassOrInterface, + CallableDeclaration callable, + Runnable onNoExistingMethod + ) { + List> existingMatchingCallables = containingClassOrInterface.getCallablesWithSignature(callable.getSignature()); + if (existingMatchingCallables.isEmpty()) { + // A matching callable exists -- will now normally add/insert. + onNoExistingMethod.run(); + } else { + // A matching callable doe NOT exist -- will now normally replace. + if (existingMatchingCallables.size() > 1) { + throw new AssertionError(f("Wanted to regenerate a method with signature %s in %s, but found more than one, and unable to disambiguate.", callable.getSignature(), containingClassOrInterface.getNameAsString())); + } + + final CallableDeclaration existingCallable = existingMatchingCallables.get(0); + + // Attempt to retain any existing javadoc. + + // TODO: Confirm what is done with normal comments... + Optional callableJavadocComment = callable.getJavadocComment(); + Optional existingCallableJavadocComment = existingCallable.getJavadocComment(); + + Optional callableComment = callable.getComment(); + Optional existingCallableComment = existingCallable.getComment(); + + callable.setComment(callableComment.orElseGet(() -> existingCallable.getComment().orElse(null))); +// callable.setJavadocComment(callableJavadocComment.orElse(existingCallableJavadocComment.orElse(null))); + + // Mark the method as having been fully/partially generated. + annotateGenerated(callable); + + if (callable.isMethodDeclaration()) { + // We want the methods that we generate/insert to be pretty printed. + MethodDeclaration prettyMethodDeclaration = prettyPrint(callable.asMethodDeclaration(), " "); + + // Do the replacement. + containingClassOrInterface.getMembers().replace(existingCallable, prettyMethodDeclaration); + } else { + // TODO: Unable to parse a constructor directly...? + + // Do the replacement. + containingClassOrInterface.getMembers().replace(existingCallable, callable); + } + } + } + + /** + * Utility method that looks for a method or constructor with an identical signature as "callable" and replaces it + * with callable. If not found, adds callable. When the new callable has no javadoc, any old javadoc will be kept. + */ + protected void addOrReplaceWhenSameSignature(ClassOrInterfaceDeclaration containingClassOrInterface, CallableDeclaration callable) { + addOrReplaceMethod( + containingClassOrInterface, + callable, + () -> { + annotateGenerated(callable); + containingClassOrInterface.addMember(callable); + } + ); + } + + protected void after() throws Exception { + } + + /** + * @param node The node to which the annotation will be added. + * @param annotation The annotation to be added to the given node. + * @param content Where an annotation has content, it is passed here (otherwise null). + * @param Only accept nodes which accept annotations. + */ + private > void annotate(T node, Class annotation, Expression content) { + NodeList annotations = node.getAnnotations() + .stream() + .filter(a -> !a.getNameAsString().equals(annotation.getSimpleName())) + .collect(toNodeList()); + + node.setAnnotations(annotations); + + if (content != null) { + node.addSingleMemberAnnotation(annotation.getSimpleName(), content); + } else { + node.addMarkerAnnotation(annotation.getSimpleName()); + } + + // The annotation class will normally need to be imported. + node.tryAddImportToParentCompilationUnit(annotation); + } + + /** + * @param node The node to which the {@code @Annotated} annotation will be added. + * @param + */ + protected > void annotateGenerated(T node) { + annotate(node, Generated.class, new StringLiteralExpr(getClass().getName())); + } + + protected > void removeAnnotation(T node, Class annotation) { + node.getAnnotations().removeIf(annotationExpr -> + annotationExpr.getName().asString().equals( + annotation.getSimpleName() + ) + ); + + node.findAncestor(CompilationUnit.class).ifPresent(compilationUnit -> { + removeAnnotationImportIfUnused(compilationUnit, annotation); + }); + + } + + protected > void removeGenerated(T node) { + removeAnnotation(node, Generated.class); + } + + protected void removeAnnotationImportIfUnused(CompilationUnit compilationUnit, Class annotation) { + + List staleAnnotations = compilationUnit + .findAll(AnnotationExpr.class) + .stream() + .filter(annotationExpr -> + annotationExpr.getName().asString().equals( + annotation.getSimpleName() + ) + ) + .collect(Collectors.toList()); + + if (staleAnnotations.isEmpty()) { + // If there are no usages of this annotation, remove the import. + boolean isRemoved = compilationUnit.getImports().removeIf(importDeclaration -> { + return importDeclaration.getNameAsString().equals(annotation.getCanonicalName()); + }); + } + } + + /** + * @param method The node to which the {@code @Override} annotation will be added. + */ + protected void annotateOverridden(MethodDeclaration method) { + annotate(method, Override.class, null); + } + + /** + * @param node The node to which the {@code @SuppressWarnings} annotation will be added. + * @param Only accept nodes which accept annotations. + */ + protected > void annotateSuppressWarnings(T node, String warningType) { + annotate(node, SuppressWarnings.class, new StringLiteralExpr(warningType)); + } + + /** + * Removes all methods from containingClassOrInterface that have the same signature as callable. + * This is not currently used directly by any current generators, but may be useful when changing a generator + * and you need to get rid of a set of outdated methods. + */ + protected void removeMethodWithSameSignature(ClassOrInterfaceDeclaration containingClassOrInterface, CallableDeclaration callable) { + for (CallableDeclaration existingCallable : containingClassOrInterface.getCallablesWithSignature(callable.getSignature())) { + containingClassOrInterface.remove(existingCallable); + } + } + + /** + * Utility method that looks for a method or constructor with an identical signature as "callable" and replaces it + * with callable. If not found, fails. When the new callable has no javadoc, any old javadoc will be kept. The + * method or constructor is annotated with the generator class. + */ + protected void replaceWhenSameSignature(ClassOrInterfaceDeclaration containingClassOrInterface, CallableDeclaration callable) { + addOrReplaceMethod( + containingClassOrInterface, + callable, + () -> { + throw new AssertionError(f("Wanted to regenerate a method with signature %s in %s, but it wasn't there.", callable.getSignature(), containingClassOrInterface.getNameAsString())); + } + ); + } + + + protected List getParsedCompilationUnitsFromSourceRoot(SourceRoot sourceRoot) throws IOException { + List cus = sourceRoot.getCompilationUnits(); + List> parseResults = sourceRoot.tryToParse(); + + boolean allParsed = parseResults.stream().allMatch(ParseResult::isSuccessful); + if (!allParsed) { + List> problemResults = parseResults.stream().filter(compilationUnitParseResult -> !compilationUnitParseResult.isSuccessful()).collect(Collectors.toList()); + for (int i = 0; i < problemResults.size(); i++) { + ParseResult parseResult = problemResults.get(i); + List problems = parseResult.getProblems(); + Log.info(""); + Log.info("Problems (" + (i + 1) + " of " + problemResults.size() + "): "); + Log.info(problems.toString()); + } + + throw new IllegalStateException("Expected all files to parse."); + } + + Log.info("parseResults.size() = " + parseResults.size()); + + return parseResults.stream() + .map(ParseResult::getResult) + .map(Optional::get) + .collect(Collectors.toList()); + } + + + protected MethodDeclaration prettyPrint(MethodDeclaration methodDeclaration) { + return prettyPrint(methodDeclaration, ""); + } + protected MethodDeclaration prettyPrint(MethodDeclaration methodDeclaration, String indent) { + String methodDeclarationString = indent + methodDeclaration.toString().replaceAll("(\\R)", "$1" + indent); + MethodDeclaration prettyMethodDeclaration = StaticJavaParser.parseMethodDeclaration(methodDeclarationString); + + return prettyMethodDeclaration; + } + + protected EnumDeclaration prettyPrint(EnumDeclaration enumDeclaration) { + return prettyPrint(enumDeclaration, ""); + } + protected EnumDeclaration prettyPrint(EnumDeclaration enumDeclaration, String indent) { + String enumDeclarationString = indent + enumDeclaration.toString().replaceAll("(\\R)", "$1" + indent); + TypeDeclaration prettyEnumDeclaration = StaticJavaParser.parseTypeDeclaration(enumDeclarationString); + + LexicalPreservingPrinter.setup(prettyEnumDeclaration); + + // We know that it is an enum declaration. + return prettyEnumDeclaration.asEnumDeclaration(); + } + + protected SwitchStmt prettyPrint(SwitchStmt switchStmt) { + return prettyPrint(switchStmt, ""); + } + protected SwitchStmt prettyPrint(SwitchStmt switchStmt, String indent) { + String switchStmtString = indent + switchStmt.toString().replaceAll("(\\R)", "$1" + indent); + Statement prettySwitchStmt = StaticJavaParser.parseStatement(switchStmtString); + + LexicalPreservingPrinter.setup(prettySwitchStmt); + + // We know that it is an switch statement. + return prettySwitchStmt.asSwitchStmt(); + } +} diff --git a/javaparser-core-metamodel-generator/src/main/java/com/github/javaparser/generator/metamodel/AstTypeAnalysis.java b/javaparser-core-metamodel-generator/src/main/java/com/github/javaparser/generator/metamodel/AstTypeAnalysis.java new file mode 100644 index 0000000..5c7a864 --- /dev/null +++ b/javaparser-core-metamodel-generator/src/main/java/com/github/javaparser/generator/metamodel/AstTypeAnalysis.java @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.metamodel; + +import com.github.javaparser.ast.NodeList; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.lang.reflect.TypeVariable; +import java.lang.reflect.WildcardType; +import java.util.Optional; + +import static java.lang.reflect.Modifier.isAbstract; + +/** + * A hacky thing that collects flags we need from AST types to generate the metamodel. + */ +class AstTypeAnalysis { + final boolean isAbstract; + boolean isOptional = false; + boolean isNodeList = false; + boolean isSelfType = false; + Class innerType; + + AstTypeAnalysis(Type type) { + if (type instanceof Class) { + TypeVariable>[] typeParameters = ((Class) type).getTypeParameters(); + if (typeParameters.length > 0) { + isSelfType = true; + } + } else { + while (type instanceof ParameterizedType) { + ParameterizedType t = (ParameterizedType) type; + Type currentOuterType = t.getRawType(); + if (currentOuterType == NodeList.class) { + isNodeList = true; + } + if (currentOuterType == Optional.class) { + isOptional = true; + } + + if (t.getActualTypeArguments()[0] instanceof WildcardType) { + type = t.getRawType(); + isSelfType = true; + break; + } + type = t.getActualTypeArguments()[0]; + } + } + innerType = (Class) type; + isAbstract = isAbstract(innerType.getModifiers()); + } +} diff --git a/javaparser-core-metamodel-generator/src/main/java/com/github/javaparser/generator/metamodel/InitializeConstructorParametersStatementsGenerator.java b/javaparser-core-metamodel-generator/src/main/java/com/github/javaparser/generator/metamodel/InitializeConstructorParametersStatementsGenerator.java new file mode 100644 index 0000000..56da7da --- /dev/null +++ b/javaparser-core-metamodel-generator/src/main/java/com/github/javaparser/generator/metamodel/InitializeConstructorParametersStatementsGenerator.java @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.metamodel; + +import com.github.javaparser.ast.AllFieldsConstructor; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.stmt.Statement; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; + +import static com.github.javaparser.StaticJavaParser.parseStatement; +import static com.github.javaparser.generator.metamodel.MetaModelGenerator.nodeMetaModelFieldName; +import static com.github.javaparser.generator.metamodel.MetaModelGenerator.propertyMetaModelFieldName; +import static com.github.javaparser.utils.CodeGenerationUtils.f; + +class InitializeConstructorParametersStatementsGenerator { + void generate(Class nodeClass, NodeList initializeConstructorParametersStatements) { + if (nodeClass == Node.class) { + return; + } + Constructor constructor = findAllFieldsConstructor(nodeClass); + for (java.lang.reflect.Parameter parameter : constructor.getParameters()) { + Field field = findFieldInClass(nodeClass, parameter.getName()); + + String addFieldStatement = f("%s.getConstructorParameters().add(%s.%s);", + nodeMetaModelFieldName(nodeClass), + nodeMetaModelFieldName(field.getDeclaringClass()), + propertyMetaModelFieldName(field)); + + initializeConstructorParametersStatements.add(parseStatement(addFieldStatement)); + } + } + + private Field findFieldInClass(Class nodeClass, String name) { + Class searchClass = nodeClass; + do { + for (Field field : searchClass.getDeclaredFields()) { + if (field.getName().equals(name)) { + return field; + } + } + searchClass = searchClass.getSuperclass(); + } while (searchClass != null); + throw new AssertionError(f("Couldn't find constructor parameter %s as a field, class %s", name, nodeClass.getSimpleName())); + } + + private Constructor findAllFieldsConstructor(Class nodeClass) { + for (Constructor constructor : nodeClass.getDeclaredConstructors()) { + for (Annotation annotation : constructor.getAnnotations()) { + if (annotation.annotationType() == AllFieldsConstructor.class) { + return constructor; + } + } + } + throw new AssertionError(f("Node class %s has no constructor annotated with @AllFieldsConstructor", nodeClass.getSimpleName())); + } +} diff --git a/javaparser-core-metamodel-generator/src/main/java/com/github/javaparser/generator/metamodel/InitializePropertyMetaModelsStatementsGenerator.java b/javaparser-core-metamodel-generator/src/main/java/com/github/javaparser/generator/metamodel/InitializePropertyMetaModelsStatementsGenerator.java new file mode 100644 index 0000000..297467a --- /dev/null +++ b/javaparser-core-metamodel-generator/src/main/java/com/github/javaparser/generator/metamodel/InitializePropertyMetaModelsStatementsGenerator.java @@ -0,0 +1,98 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.metamodel; + +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.metamodel.NonEmptyProperty; +import com.github.javaparser.metamodel.OptionalProperty; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; + +import static com.github.javaparser.StaticJavaParser.parseStatement; +import static com.github.javaparser.ast.Modifier.Keyword.PUBLIC; +import static com.github.javaparser.generator.metamodel.MetaModelGenerator.isNode; +import static com.github.javaparser.generator.metamodel.MetaModelGenerator.nodeMetaModelName; +import static com.github.javaparser.utils.CodeGenerationUtils.*; +import static com.github.javaparser.utils.Utils.decapitalize; + +class InitializePropertyMetaModelsStatementsGenerator { + void generate(Field field, ClassOrInterfaceDeclaration nodeMetaModelClass, String nodeMetaModelFieldName, NodeList initializePropertyMetaModelsStatements) { + final AstTypeAnalysis fieldTypeAnalysis = new AstTypeAnalysis(field.getGenericType()); + + final Class fieldType = fieldTypeAnalysis.innerType; + final String typeName = fieldType.getTypeName().replace('$', '.'); + final String propertyMetaModelFieldName = field.getName() + "PropertyMetaModel"; + nodeMetaModelClass.addField("PropertyMetaModel", propertyMetaModelFieldName, PUBLIC); + final String propertyInitializer = f("new PropertyMetaModel(%s, \"%s\", %s.class, %s, %s, %s, %s, %s)", + nodeMetaModelFieldName, + field.getName(), + typeName, + optionalOf(decapitalize(nodeMetaModelName(fieldType)), isNode(fieldType)), + isOptional(field), + isNonEmpty(field), + fieldTypeAnalysis.isNodeList, + fieldTypeAnalysis.isSelfType); + final String fieldSetting = f("%s.%s=%s;", nodeMetaModelFieldName, propertyMetaModelFieldName, propertyInitializer); + final String fieldAddition = f("%s.getDeclaredPropertyMetaModels().add(%s.%s);", nodeMetaModelFieldName, nodeMetaModelFieldName, propertyMetaModelFieldName); + + initializePropertyMetaModelsStatements.add(parseStatement(fieldSetting)); + initializePropertyMetaModelsStatements.add(parseStatement(fieldAddition)); + } + + void generateDerivedProperty(Method method, ClassOrInterfaceDeclaration nodeMetaModelClass, String nodeMetaModelFieldName, NodeList initializePropertyMetaModelsStatements) { + final AstTypeAnalysis returnTypeAnalysis = new AstTypeAnalysis(method.getGenericReturnType()); + + final Class innermostReturnType = returnTypeAnalysis.innerType; + final String typeName = innermostReturnType.getTypeName().replace('$', '.'); + final String propertyMetaModelFieldName = getterToPropertyName(method.getName()) + "PropertyMetaModel"; + nodeMetaModelClass.addField("PropertyMetaModel", propertyMetaModelFieldName, PUBLIC); + final String propertyInitializer = f("new PropertyMetaModel(%s, \"%s\", %s.class, %s, %s, %s, %s, %s)", + nodeMetaModelFieldName, + getterToPropertyName(method.getName()), + typeName, + optionalOf(decapitalize(nodeMetaModelName(innermostReturnType)), isNode(innermostReturnType)), + returnTypeAnalysis.isOptional, + isNonEmpty(method), + returnTypeAnalysis.isNodeList, + returnTypeAnalysis.isSelfType); + final String fieldSetting = f("%s.%s=%s;", nodeMetaModelFieldName, propertyMetaModelFieldName, propertyInitializer); + final String fieldAddition = f("%s.getDerivedPropertyMetaModels().add(%s.%s);", nodeMetaModelFieldName, nodeMetaModelFieldName, propertyMetaModelFieldName); + + initializePropertyMetaModelsStatements.add(parseStatement(fieldSetting)); + initializePropertyMetaModelsStatements.add(parseStatement(fieldAddition)); + } + + private boolean isNonEmpty(Field field) { + return field.isAnnotationPresent(NonEmptyProperty.class); + } + + private boolean isNonEmpty(Method method) { + return method.isAnnotationPresent(NonEmptyProperty.class); + } + + private boolean isOptional(Field field) { + return field.isAnnotationPresent(OptionalProperty.class); + } +} diff --git a/javaparser-core-metamodel-generator/src/main/java/com/github/javaparser/generator/metamodel/MetaModelGenerator.java b/javaparser-core-metamodel-generator/src/main/java/com/github/javaparser/generator/metamodel/MetaModelGenerator.java new file mode 100644 index 0000000..606b09b --- /dev/null +++ b/javaparser-core-metamodel-generator/src/main/java/com/github/javaparser/generator/metamodel/MetaModelGenerator.java @@ -0,0 +1,283 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.metamodel; + +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.StaticJavaParser; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.CompactConstructorDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.generator.AbstractGenerator; +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; +import com.github.javaparser.utils.SourceRoot; + +import java.lang.reflect.Field; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +import static com.github.javaparser.utils.Utils.decapitalize; + +public class MetaModelGenerator extends AbstractGenerator { + + static final String BASE_NODE_META_MODEL = "BaseNodeMetaModel"; + static final String METAMODEL_PACKAGE = "com.github.javaparser.metamodel"; + + /** + * Note that order of this list is manually set and maintained. + */ + private static final List> ALL_NODE_CLASSES = new ArrayList>() {{ + /* Base classes go first, so we don't have to do any sorting to make sure + generated classes can refer to their base generated classes without + being afraid those are not initialized yet. */ + + // Fully qualified names used to make logical groupings (somewhat) more explicit. + + // + add(com.github.javaparser.ast.Node.class); + + add(com.github.javaparser.ast.body.BodyDeclaration.class); + add(com.github.javaparser.ast.body.CallableDeclaration.class); + add(com.github.javaparser.ast.expr.Expression.class); + add(com.github.javaparser.ast.stmt.Statement.class); + add(com.github.javaparser.ast.type.Type.class); + + add(com.github.javaparser.ast.expr.AnnotationExpr.class); + add(com.github.javaparser.ast.type.ReferenceType.class); + add(com.github.javaparser.ast.body.TypeDeclaration.class); + + add(com.github.javaparser.ast.expr.LiteralExpr.class); + add(com.github.javaparser.ast.expr.LiteralStringValueExpr.class); + add(com.github.javaparser.ast.expr.StringLiteralExpr.class); + + add(com.github.javaparser.ast.modules.ModuleDeclaration.class); + add(com.github.javaparser.ast.modules.ModuleDirective.class); + + // + add(com.github.javaparser.ast.ArrayCreationLevel.class); + add(com.github.javaparser.ast.CompilationUnit.class); + add(com.github.javaparser.ast.ImportDeclaration.class); + add(com.github.javaparser.ast.Modifier.class); + add(com.github.javaparser.ast.PackageDeclaration.class); + + // + add(com.github.javaparser.ast.body.AnnotationDeclaration.class); + add(com.github.javaparser.ast.body.AnnotationMemberDeclaration.class); + add(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration.class); + add(com.github.javaparser.ast.body.ConstructorDeclaration.class); + add(com.github.javaparser.ast.body.EnumConstantDeclaration.class); + add(com.github.javaparser.ast.body.EnumDeclaration.class); + add(com.github.javaparser.ast.body.FieldDeclaration.class); + add(com.github.javaparser.ast.body.InitializerDeclaration.class); + add(com.github.javaparser.ast.body.MethodDeclaration.class); + add(com.github.javaparser.ast.body.Parameter.class); + add(com.github.javaparser.ast.body.ReceiverParameter.class); + add(com.github.javaparser.ast.body.RecordDeclaration.class); + add(CompactConstructorDeclaration.class); + add(com.github.javaparser.ast.body.VariableDeclarator.class); + + add(com.github.javaparser.ast.comments.Comment.class); // First, as it is the base of other comment types + add(com.github.javaparser.ast.comments.BlockComment.class); + add(com.github.javaparser.ast.comments.JavadocComment.class); + add(com.github.javaparser.ast.comments.LineComment.class); + + add(com.github.javaparser.ast.expr.ArrayAccessExpr.class); + add(com.github.javaparser.ast.expr.ArrayCreationExpr.class); + add(com.github.javaparser.ast.expr.ArrayInitializerExpr.class); + add(com.github.javaparser.ast.expr.AssignExpr.class); + add(com.github.javaparser.ast.expr.BinaryExpr.class); + add(com.github.javaparser.ast.expr.BooleanLiteralExpr.class); + add(com.github.javaparser.ast.expr.CastExpr.class); + add(com.github.javaparser.ast.expr.CharLiteralExpr.class); + add(com.github.javaparser.ast.expr.ClassExpr.class); + add(com.github.javaparser.ast.expr.ConditionalExpr.class); + add(com.github.javaparser.ast.expr.DoubleLiteralExpr.class); + add(com.github.javaparser.ast.expr.EnclosedExpr.class); + add(com.github.javaparser.ast.expr.FieldAccessExpr.class); + add(com.github.javaparser.ast.expr.InstanceOfExpr.class); + add(com.github.javaparser.ast.expr.IntegerLiteralExpr.class); + add(com.github.javaparser.ast.expr.LambdaExpr.class); + add(com.github.javaparser.ast.expr.LongLiteralExpr.class); + add(com.github.javaparser.ast.expr.MarkerAnnotationExpr.class); + add(com.github.javaparser.ast.expr.MemberValuePair.class); + add(com.github.javaparser.ast.expr.MethodCallExpr.class); + add(com.github.javaparser.ast.expr.MethodReferenceExpr.class); + add(com.github.javaparser.ast.expr.NameExpr.class); + add(com.github.javaparser.ast.expr.Name.class); + add(com.github.javaparser.ast.expr.NormalAnnotationExpr.class); + add(com.github.javaparser.ast.expr.NullLiteralExpr.class); + add(com.github.javaparser.ast.expr.ObjectCreationExpr.class); + add(com.github.javaparser.ast.expr.PatternExpr.class); + add(com.github.javaparser.ast.expr.SingleMemberAnnotationExpr.class); + add(com.github.javaparser.ast.expr.SimpleName.class); + add(com.github.javaparser.ast.expr.SuperExpr.class); + add(com.github.javaparser.ast.expr.SwitchExpr.class); + add(com.github.javaparser.ast.expr.TextBlockLiteralExpr.class); + add(com.github.javaparser.ast.expr.ThisExpr.class); + add(com.github.javaparser.ast.expr.TypeExpr.class); + add(com.github.javaparser.ast.expr.UnaryExpr.class); + add(com.github.javaparser.ast.expr.VariableDeclarationExpr.class); + + add(com.github.javaparser.ast.stmt.AssertStmt.class); + add(com.github.javaparser.ast.stmt.BlockStmt.class); + add(com.github.javaparser.ast.stmt.BreakStmt.class); + add(com.github.javaparser.ast.stmt.CatchClause.class); + add(com.github.javaparser.ast.stmt.ContinueStmt.class); + add(com.github.javaparser.ast.stmt.DoStmt.class); + add(com.github.javaparser.ast.stmt.EmptyStmt.class); + add(com.github.javaparser.ast.stmt.ExplicitConstructorInvocationStmt.class); + add(com.github.javaparser.ast.stmt.ExpressionStmt.class); + add(com.github.javaparser.ast.stmt.ForEachStmt.class); + add(com.github.javaparser.ast.stmt.ForStmt.class); + add(com.github.javaparser.ast.stmt.IfStmt.class); + add(com.github.javaparser.ast.stmt.LabeledStmt.class); + add(com.github.javaparser.ast.stmt.LocalClassDeclarationStmt.class); + add(com.github.javaparser.ast.stmt.LocalRecordDeclarationStmt.class); + add(com.github.javaparser.ast.stmt.ReturnStmt.class); + add(com.github.javaparser.ast.stmt.SwitchEntry.class); + add(com.github.javaparser.ast.stmt.SwitchStmt.class); + add(com.github.javaparser.ast.stmt.SynchronizedStmt.class); + add(com.github.javaparser.ast.stmt.ThrowStmt.class); + add(com.github.javaparser.ast.stmt.TryStmt.class); + add(com.github.javaparser.ast.stmt.UnparsableStmt.class); + add(com.github.javaparser.ast.stmt.WhileStmt.class); + add(com.github.javaparser.ast.stmt.YieldStmt.class); + + add(com.github.javaparser.ast.type.ArrayType.class); + add(com.github.javaparser.ast.type.ClassOrInterfaceType.class); + add(com.github.javaparser.ast.type.IntersectionType.class); + add(com.github.javaparser.ast.type.PrimitiveType.class); + add(com.github.javaparser.ast.type.TypeParameter.class); + add(com.github.javaparser.ast.type.UnionType.class); + add(com.github.javaparser.ast.type.UnknownType.class); + add(com.github.javaparser.ast.type.VarType.class); + add(com.github.javaparser.ast.type.VoidType.class); + add(com.github.javaparser.ast.type.WildcardType.class); + + add(com.github.javaparser.ast.modules.ModuleExportsDirective.class); + add(com.github.javaparser.ast.modules.ModuleOpensDirective.class); + add(com.github.javaparser.ast.modules.ModuleProvidesDirective.class); + add(com.github.javaparser.ast.modules.ModuleRequiresDirective.class); + add(com.github.javaparser.ast.modules.ModuleUsesDirective.class); + }}; + + public MetaModelGenerator(SourceRoot sourceRoot) { + super(sourceRoot); + } + + public static void main(String[] args) throws Exception { + if (args.length != 1) { + throw new RuntimeException("Need 1 parameter: the JavaParser source checkout root directory."); + } + final Path root = Paths.get(args[0], "..", "javaparser-core", "src", "main", "java"); + final ParserConfiguration parserConfiguration = new ParserConfiguration() + .setLanguageLevel(ParserConfiguration.LanguageLevel.RAW) + .setStoreTokens(false); + final SourceRoot sourceRoot = new SourceRoot(root, parserConfiguration); + PrinterConfiguration config = new DefaultPrinterConfiguration().addOption(new DefaultConfigurationOption(ConfigOption.END_OF_LINE_CHARACTER, ("\n"))); + Printer printer = new DefaultPrettyPrinter(config); + sourceRoot.setPrinter(printer::print); + StaticJavaParser.setConfiguration(parserConfiguration); + + new MetaModelGenerator(sourceRoot).generate(); + + sourceRoot.saveAll(); + } + + public void generate() throws Exception { + final CompilationUnit javaParserMetaModelCu = sourceRoot.parse(METAMODEL_PACKAGE, "JavaParserMetaModel.java"); + javaParserMetaModelCu.setBlockComment(COPYRIGHT_NOTICE_JP_CORE); + + generateNodeMetaModels(javaParserMetaModelCu, sourceRoot); + } + + private void generateNodeMetaModels(CompilationUnit javaParserMetaModelCu, SourceRoot sourceRoot) throws NoSuchMethodException { + final ClassOrInterfaceDeclaration metaModelCoid = javaParserMetaModelCu.getClassByName("JavaParserMetaModel").get(); + + // Initialiser methods + final MethodDeclaration initializeNodeMetaModelsMethod = metaModelCoid.getMethodsByName("initializeNodeMetaModels").get(0); + final MethodDeclaration initializePropertyMetaModelsMethod = metaModelCoid.getMethodsByName("initializePropertyMetaModels").get(0); + final MethodDeclaration initializeConstructorParametersVariable = metaModelCoid.getMethodsByName("initializeConstructorParameters").get(0); + + // Ensure annotation `@Generated` is added to indicate the contents of each are generated. + annotateGenerated(initializeNodeMetaModelsMethod); + annotateGenerated(initializePropertyMetaModelsMethod); + annotateGenerated(initializeConstructorParametersVariable); + + // Empty the body of the initialiser methods, to be (re-)generated below. + final NodeList initializeNodeMetaModelsStatements = initializeNodeMetaModelsMethod.getBody().get().getStatements(); + final NodeList initializePropertyMetaModelsStatements = initializePropertyMetaModelsMethod.getBody().get().getStatements(); + final NodeList initializeConstructorParametersStatements = initializeConstructorParametersVariable.getBody().get().getStatements(); + initializeNodeMetaModelsStatements.clear(); + initializePropertyMetaModelsStatements.clear(); + initializeConstructorParametersStatements.clear(); + + // Remove fields, to be (re-)generated below. + metaModelCoid.getFields().stream() + .filter(f -> f.getVariable(0).getNameAsString().endsWith("MetaModel")) + .forEach(Node::remove); + + // Do the generation of each node metamodel class. + final NodeMetaModelGenerator nodeMetaModelGenerator = new NodeMetaModelGenerator(sourceRoot); + for (Class nodeClass : ALL_NODE_CLASSES) { + nodeMetaModelGenerator.generate( + nodeClass, + metaModelCoid, + initializeNodeMetaModelsStatements, + initializePropertyMetaModelsStatements, + initializeConstructorParametersStatements, + sourceRoot + ); + } + + // TODO: Document why sorting occurs. + initializeNodeMetaModelsStatements.sort(Comparator.comparing(Node::toString)); + } + + static boolean isNode(Class c) { + return Node.class.isAssignableFrom(c); + } + + static String nodeMetaModelName(Class c) { + return c.getSimpleName() + "MetaModel"; + } + + static String propertyMetaModelFieldName(Field field) { + return field.getName() + "PropertyMetaModel"; + } + + static String nodeMetaModelFieldName(Class nodeClass) { + return decapitalize(nodeMetaModelName(nodeClass)); + } + +} diff --git a/javaparser-core-metamodel-generator/src/main/java/com/github/javaparser/generator/metamodel/NodeMetaModelGenerator.java b/javaparser-core-metamodel-generator/src/main/java/com/github/javaparser/generator/metamodel/NodeMetaModelGenerator.java new file mode 100644 index 0000000..8838d09 --- /dev/null +++ b/javaparser-core-metamodel-generator/src/main/java/com/github/javaparser/generator/metamodel/NodeMetaModelGenerator.java @@ -0,0 +1,185 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.generator.metamodel; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.generator.AbstractGenerator; +import com.github.javaparser.metamodel.DerivedProperty; +import com.github.javaparser.metamodel.InternalProperty; +import com.github.javaparser.utils.SourceRoot; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.*; + +import static com.github.javaparser.StaticJavaParser.*; +import static com.github.javaparser.ast.Modifier.Keyword.*; +import static com.github.javaparser.utils.CodeGenerationUtils.f; +import static com.github.javaparser.utils.CodeGenerationUtils.optionalOf; +import static com.github.javaparser.utils.Utils.decapitalize; + +public class NodeMetaModelGenerator extends AbstractGenerator { + + private final InitializePropertyMetaModelsStatementsGenerator initializePropertyMetaModelsStatementsGenerator = new InitializePropertyMetaModelsStatementsGenerator(); + private final InitializeConstructorParametersStatementsGenerator initializeConstructorParametersStatementsGenerator = new InitializeConstructorParametersStatementsGenerator(); + + public static final String GENERATED_CLASS_COMMENT = "" + + "This file, class, and its contents are completely generated based on:" + + "\n
    " + + "\n
  • The contents and annotations within the package `com.github.javaparser.ast`, and
  • " + + "\n
  • `ALL_NODE_CLASSES` within the class `com.github.javaparser.generator.metamodel.MetaModelGenerator`.
  • " + + "\n
" + + "\n" + + "\nFor this reason, any changes made directly to this file will be overwritten the next time generators are run." + + ""; + + private static final String GENERATED_JAVADOC_COMMENT = "Warning: The content of this class is partially or completely generated - manual edits risk being overwritten."; + + protected NodeMetaModelGenerator(SourceRoot sourceRoot) { + super(sourceRoot); + } + + public void generate(Class nodeClass, ClassOrInterfaceDeclaration metaModelCoid, NodeList initializeNodeMetaModelsStatements, NodeList initializePropertyMetaModelsStatements, NodeList initializeConstructorParametersStatements, SourceRoot sourceRoot) throws NoSuchMethodException { + metaModelCoid.setJavadocComment(GENERATED_JAVADOC_COMMENT); + + final AstTypeAnalysis typeAnalysis = new AstTypeAnalysis(nodeClass); + + final String className = MetaModelGenerator.nodeMetaModelName(nodeClass); + final String nodeMetaModelFieldName = decapitalize(className); + metaModelCoid.getFieldByName(nodeMetaModelFieldName).ifPresent(Node::remove); + + initializeNodeMetaModelsStatements.add(parseStatement(f("nodeMetaModels.add(%s);", nodeMetaModelFieldName))); + this.initializeConstructorParametersStatementsGenerator.generate(nodeClass, initializeConstructorParametersStatements); + + final Class superclass = nodeClass.getSuperclass(); + final String superNodeMetaModel = MetaModelGenerator.nodeMetaModelName(superclass); + final boolean isRootNode = !MetaModelGenerator.isNode(superclass); + + final FieldDeclaration nodeField = metaModelCoid.addField(className, nodeMetaModelFieldName, PUBLIC, STATIC, FINAL); + annotateGenerated(nodeField); + nodeField.getVariable(0).setInitializer( + parseExpression( + f("new %s(%s)", + className, + optionalOf(decapitalize(superNodeMetaModel), !isRootNode)) + ) + ); + + + // The node-specific metamodel file + final CompilationUnit classMetaModelJavaFile = new CompilationUnit(MetaModelGenerator.METAMODEL_PACKAGE); + classMetaModelJavaFile.setBlockComment(COPYRIGHT_NOTICE_JP_CORE); + classMetaModelJavaFile.addImport(Optional.class); + classMetaModelJavaFile.addImport(nodeClass); + + // + final ClassOrInterfaceDeclaration nodeMetaModelClass = classMetaModelJavaFile.addClass(className, PUBLIC); + annotateGenerated(nodeMetaModelClass); + nodeMetaModelClass.setJavadocComment(GENERATED_CLASS_COMMENT); + + if (isRootNode) { + nodeMetaModelClass.addExtendedType(MetaModelGenerator.BASE_NODE_META_MODEL); + } else { + nodeMetaModelClass.addExtendedType(superNodeMetaModel); + } + + // Constructors + final ConstructorDeclaration classMMConstructor = nodeMetaModelClass + .addConstructor() + .addParameter( + f("Optional<%s>", MetaModelGenerator.BASE_NODE_META_MODEL), + f("super%s", MetaModelGenerator.BASE_NODE_META_MODEL) + ); + classMMConstructor + .getBody() + .addStatement( + parseExplicitConstructorInvocationStmt(f("super(super%s, %s.class, \"%s\", \"%s\", %s, %s);", + MetaModelGenerator.BASE_NODE_META_MODEL, + nodeClass.getSimpleName(), + nodeClass.getSimpleName(), + nodeClass.getPackage().getName(), + typeAnalysis.isAbstract, + typeAnalysis.isSelfType + )) + ); + annotateGenerated(classMMConstructor); + + // ?Abstract protected constructor? + if (typeAnalysis.isAbstract) { + classMetaModelJavaFile.addImport(Node.class); + BodyDeclaration bodyDeclaration = parseBodyDeclaration(f( + "protected %s(Optional<%s> superNodeMetaModel, Class type, String name, String packageName, boolean isAbstract, boolean hasWildcard) {" + + "super(superNodeMetaModel, type, name, packageName, isAbstract, hasWildcard);" + + " }", + className, + MetaModelGenerator.BASE_NODE_META_MODEL + )); + annotateGenerated(bodyDeclaration); + nodeMetaModelClass.addMember(bodyDeclaration); + } + + // Fields, sorted by name. + final List fields = new ArrayList<>(Arrays.asList(nodeClass.getDeclaredFields())); + fields.sort(Comparator.comparing(Field::getName)); + for (Field field : fields) { + if (this.fieldShouldBeIgnored(field)) { + continue; + } + + this.initializePropertyMetaModelsStatementsGenerator.generate(field, nodeMetaModelClass, nodeMetaModelFieldName, initializePropertyMetaModelsStatements); + } + + // Methods, sorted by name. + final List methods = new ArrayList<>(Arrays.asList(nodeClass.getMethods())); + methods.sort(Comparator.comparing(Method::getName)); + for (Method method : methods) { + if (method.isAnnotationPresent(DerivedProperty.class)) { + this.initializePropertyMetaModelsStatementsGenerator.generateDerivedProperty(method, nodeMetaModelClass, nodeMetaModelFieldName, initializePropertyMetaModelsStatements); + } + } + + + this.moveStaticInitializeToTheEndOfTheClassBecauseWeNeedTheFieldsToInitializeFirst(metaModelCoid); + + // Add the file to the source root, enabling it to be saved later. + sourceRoot.add(MetaModelGenerator.METAMODEL_PACKAGE, className + ".java", classMetaModelJavaFile); + } + + private void moveStaticInitializeToTheEndOfTheClassBecauseWeNeedTheFieldsToInitializeFirst(ClassOrInterfaceDeclaration metaModelCoid) { + for (BodyDeclaration m : metaModelCoid.getMembers()) { + if (m instanceof InitializerDeclaration) { + m.remove(); + metaModelCoid.addMember(m); + return; + } + } + } + + private boolean fieldShouldBeIgnored(Field reflectionField) { + return java.lang.reflect.Modifier.isStatic(reflectionField.getModifiers()) || + reflectionField.isAnnotationPresent(InternalProperty.class); + } +} diff --git a/javaparser-core-serialization/pom.xml b/javaparser-core-serialization/pom.xml new file mode 100644 index 0000000..6f64d24 --- /dev/null +++ b/javaparser-core-serialization/pom.xml @@ -0,0 +1,71 @@ + + + javaparser-parent + com.github.javaparser + 3.25.10 + + 4.0.0 + + javaparser-core-serialization + Serializers for the JavaParser AST. + + + + GNU Lesser General Public License + http://www.gnu.org/licenses/lgpl-3.0.html + repo + + + Apache License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + A business-friendly OSS license + + + + + 1.8 + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + com.github.javaparser.core.serialization + + + + + + + + + + + org.junit.jupiter + junit-jupiter-engine + + + com.github.javaparser + javaparser-core + ${project.version} + + + jakarta.json + jakarta.json-api + 2.1.3 + + + + org.eclipse.parsson + parsson + 1.1.5 + test + + + + diff --git a/javaparser-core-serialization/src/main/java/com/github/javaparser/serialization/JavaParserJsonDeserializer.java b/javaparser-core-serialization/src/main/java/com/github/javaparser/serialization/JavaParserJsonDeserializer.java new file mode 100644 index 0000000..f2192ad --- /dev/null +++ b/javaparser-core-serialization/src/main/java/com/github/javaparser/serialization/JavaParserJsonDeserializer.java @@ -0,0 +1,208 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.serialization; + +import com.github.javaparser.*; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.comments.Comment; +import com.github.javaparser.metamodel.BaseNodeMetaModel; +import com.github.javaparser.metamodel.PropertyMetaModel; +import com.github.javaparser.utils.Log; + +import jakarta.json.JsonArray; +import jakarta.json.JsonObject; +import jakarta.json.JsonReader; +import jakarta.json.JsonValue; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +import static com.github.javaparser.ast.NodeList.toNodeList; +import static com.github.javaparser.metamodel.JavaParserMetaModel.getNodeMetaModel; +import static com.github.javaparser.serialization.JavaParserJsonSerializer.*; + +/** + * Deserializes the JSON file that was built by {@link JavaParserJsonSerializer}. + */ +public class JavaParserJsonDeserializer { + /** + * Deserializes json, contained by JsonReader, into AST node. + * The root node and all its child nodes will be deserialized. + * @param reader json-p reader (object-level reader,
see their docs) + * @return the root level deserialized node + */ + public Node deserializeObject(JsonReader reader) { + Log.info("Deserializing JSON to Node."); + JsonObject jsonObject = reader.readObject(); + return deserializeObject(jsonObject); + } + + /** + * Recursive depth-first deserializing method that creates a Node instance from JsonObject. + * + * @param nodeJson json object at current level containg values as properties + * @return deserialized node including all children. + * @implNote the Node instance will be constructed by the properties defined in the meta model. + * Non meta properties will be set after Node is instantiated. + * @implNote comment is included in the propertyKey meta model, but not set when constructing the Node instance. + * That is, comment is not included in the constructor propertyKey list, and therefore needs to be set + * after constructing the node. + * See {@link com.github.javaparser.metamodel.BaseNodeMetaModel#construct(Map)} how the node is contructed + */ + private Node deserializeObject(JsonObject nodeJson) { + try { + String serializedNodeType = nodeJson.getString(JsonNode.CLASS.propertyKey); + BaseNodeMetaModel nodeMetaModel = getNodeMetaModel(Class.forName(serializedNodeType)) + .orElseThrow(() -> new IllegalStateException("Trying to deserialize an unknown node type: " + serializedNodeType)); + Map parameters = new HashMap<>(); + Map deferredJsonValues = new HashMap<>(); + + for (String name : nodeJson.keySet()) { + if (name.equals(JsonNode.CLASS.propertyKey)) { + continue; + } + + Optional optionalPropertyMetaModel = nodeMetaModel.getAllPropertyMetaModels().stream() + .filter(mm -> mm.getName().equals(name)) + .findFirst(); + if (!optionalPropertyMetaModel.isPresent()) { + deferredJsonValues.put(name, nodeJson.get(name)); + continue; + } + + PropertyMetaModel propertyMetaModel = optionalPropertyMetaModel.get(); + if (propertyMetaModel.isNodeList()) { + JsonArray nodeListJson = nodeJson.getJsonArray(name); + parameters.put(name, deserializeNodeList(nodeListJson)); + } else if (propertyMetaModel.isNode()) { + parameters.put(name, deserializeObject(nodeJson.getJsonObject(name))); + } else { + Class type = propertyMetaModel.getType(); + if (type == String.class) { + parameters.put(name, nodeJson.getString(name)); + } else if (type == boolean.class) { + parameters.put(name, Boolean.parseBoolean(nodeJson.getString(name))); + } else if (Enum.class.isAssignableFrom(type)) { + parameters.put(name, Enum.valueOf((Class) type, nodeJson.getString(name))); + } else { + throw new IllegalStateException("Don't know how to convert: " + type); + } + } + } + + Node node = nodeMetaModel.construct(parameters); + // COMMENT is in the propertyKey meta model, but not required as constructor parameter. + // Set it after construction + if (parameters.containsKey(JsonNode.COMMENT.propertyKey)) { + node.setComment((Comment)parameters.get(JsonNode.COMMENT.propertyKey)); + } + + for (String name : deferredJsonValues.keySet()) { + if (!readNonMetaProperties(name, deferredJsonValues.get(name), node)) { + throw new IllegalStateException("Unknown propertyKey: " + nodeMetaModel.getQualifiedClassName() + "." + name); + } + } + setSymbolResolverIfCompilationUnit(node); + + return node; + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } + } + + private NodeList deserializeNodeList(JsonArray nodeListJson) { + return nodeListJson.stream().map(nodeJson -> deserializeObject((JsonObject) nodeJson)).collect(toNodeList()); + } + + /** + * Reads properties from json not included in meta model (i.e., RANGE and TOKEN_RANGE). + * When read, it sets the deserialized value to the node instance. + * @param name propertyKey name for json value + * @param jsonValue json value that needs to be deserialized for this propertyKey + * @param node instance to which the deserialized value will be set to + * @return true if propertyKey is read from json and set to Node instance + */ + protected boolean readNonMetaProperties(String name, JsonValue jsonValue, Node node) { + return readRange(name, jsonValue, node) + || readTokenRange(name, jsonValue, node); + } + + protected boolean readRange(String name, JsonValue jsonValue, Node node) { + if (name.equals(JsonNode.RANGE.propertyKey)) { + JsonObject jsonObject = (JsonObject)jsonValue; + Position begin = new Position( + jsonObject.getInt(JsonRange.BEGIN_LINE.propertyKey), + jsonObject.getInt(JsonRange.BEGIN_COLUMN.propertyKey) + ); + Position end = new Position( + jsonObject.getInt(JsonRange.END_LINE.propertyKey), + jsonObject.getInt(JsonRange.END_COLUMN.propertyKey) + ); + node.setRange(new Range(begin, end)); + return true; + } + return false; + } + + protected boolean readTokenRange(String name, JsonValue jsonValue, Node node) { + if (name.equals(JsonNode.TOKEN_RANGE.propertyKey)) { + JsonObject jsonObject = (JsonObject)jsonValue; + JavaToken begin = readToken( + JsonTokenRange.BEGIN_TOKEN.propertyKey, jsonObject + ); + JavaToken end = readToken( + JsonTokenRange.END_TOKEN.propertyKey, jsonObject + ); + node.setTokenRange(new TokenRange(begin, end)); + return true; + } + return false; + } + + protected JavaToken readToken(String name, JsonObject jsonObject) { + JsonObject tokenJson = jsonObject.getJsonObject(name); + return new JavaToken( + tokenJson.getInt(JsonToken.KIND.propertyKey), + tokenJson.getString(JsonToken.TEXT.propertyKey) + ); + } + + /** + * This method sets symbol resolver to Node if it is an instance of CompilationUnit + * and a SymbolResolver is configured in the static configuration. This is necessary to be able to resolve symbols + * within the cu after deserialization. Normally, when parsing java with JavaParser, the symbol resolver is injected + * to the cu as a data element with key SYMBOL_RESOLVER_KEY. + * @param node instance to which symbol resolver will be set to when instance of a Compilation Unit + * @see com.github.javaparser.ast.Node#SYMBOL_RESOLVER_KEY + * @see com.github.javaparser.ParserConfiguration#ParserConfiguration() + */ + private void setSymbolResolverIfCompilationUnit(Node node) { + if (node instanceof CompilationUnit && StaticJavaParser.getConfiguration().getSymbolResolver().isPresent()) { + CompilationUnit cu = (CompilationUnit)node; + cu.setData(Node.SYMBOL_RESOLVER_KEY, StaticJavaParser.getConfiguration().getSymbolResolver().get()); + } + } + + +} diff --git a/javaparser-core-serialization/src/main/java/com/github/javaparser/serialization/JavaParserJsonSerializer.java b/javaparser-core-serialization/src/main/java/com/github/javaparser/serialization/JavaParserJsonSerializer.java new file mode 100644 index 0000000..d468069 --- /dev/null +++ b/javaparser-core-serialization/src/main/java/com/github/javaparser/serialization/JavaParserJsonSerializer.java @@ -0,0 +1,203 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.serialization; + +import com.github.javaparser.JavaToken; +import com.github.javaparser.Range; +import com.github.javaparser.TokenRange; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.metamodel.BaseNodeMetaModel; +import com.github.javaparser.metamodel.JavaParserMetaModel; +import com.github.javaparser.metamodel.PropertyMetaModel; +import com.github.javaparser.utils.Log; + +import jakarta.json.stream.JsonGenerator; + +import static com.github.javaparser.utils.Utils.decapitalize; +import static java.util.Objects.requireNonNull; + +/** + * Serializes an AST or a partial AST to JSON. + */ +public class JavaParserJsonSerializer { + + /** + * Serializes node and all its children into json. Any node siblings will be ignored. + * + * @param node the node that will be the root level json object + * @param generator the json-p generator for writing the json + * @see json-p + */ + public void serialize(Node node, JsonGenerator generator) { + requireNonNull(node); + Log.info("Serializing Node to JSON."); + try { + serialize(null, node, generator); + } finally { + generator.close(); + } + } + + /** + * Recursive depth-first method that serializes nodes into json + * + * @param nodeName nullable String. If null, it is the root object, otherwise it is the property key for the object + * @param node the current node to be serialized + * @param generator the json-p generator for writing the json + */ + + private void serialize(String nodeName, Node node, JsonGenerator generator) { + requireNonNull(node); + BaseNodeMetaModel nodeMetaModel = JavaParserMetaModel.getNodeMetaModel(node.getClass()).orElseThrow(() -> new IllegalStateException("Unknown Node: " + node.getClass())); + + if (nodeName == null) { + generator.writeStartObject(); + } else { + generator.writeStartObject(nodeName); + } + generator.write(JsonNode.CLASS.propertyKey, node.getClass().getName()); + this.writeNonMetaProperties(node, generator); + for (PropertyMetaModel propertyMetaModel : nodeMetaModel.getAllPropertyMetaModels()) { + String name = propertyMetaModel.getName(); + Object value = propertyMetaModel.getValue(node); + if (value != null) { + if (propertyMetaModel.isNodeList()) { + NodeList list = (NodeList) value; + generator.writeStartArray(name); + for (Node n : list) { + serialize(null, n, generator); + } + generator.writeEnd(); + } else if (propertyMetaModel.isNode()) { + serialize(name, (Node) value, generator); + } else { + generator.write(name, value.toString()); + } + } + } + generator.writeEnd(); + } + + /*** + * This method writes json for properties not included in meta model (i.e., RANGE and TOKEN_RANGE). + * This method could be overriden so that - for example - tokens are not written to json to save space + * + * @see com.github.javaparser.metamodel.BaseNodeMetaModel#getAllPropertyMetaModels() + */ + + protected void writeNonMetaProperties(Node node, JsonGenerator generator) { + this.writeRange(node, generator); + this.writeTokens(node, generator); + } + + protected void writeRange(Node node, JsonGenerator generator) { + if (node.hasRange()) { + Range range = node.getRange().get(); + generator.writeStartObject(JsonNode.RANGE.propertyKey); + generator.write(JsonRange.BEGIN_LINE.propertyKey, range.begin.line); + generator.write(JsonRange.BEGIN_COLUMN.propertyKey, range.begin.column); + generator.write(JsonRange.END_LINE.propertyKey, range.end.line); + generator.write(JsonRange.END_COLUMN.propertyKey, range.end.column); + generator.writeEnd(); + } + } + + protected void writeTokens(Node node, JsonGenerator generator) { + if (node.getTokenRange().isPresent()) { + TokenRange tokenRange = node.getTokenRange().get(); + generator.writeStartObject(JsonNode.TOKEN_RANGE.propertyKey); + writeToken(JsonTokenRange.BEGIN_TOKEN.propertyKey, tokenRange.getBegin(), generator); + writeToken(JsonTokenRange.END_TOKEN.propertyKey, tokenRange.getEnd(), generator); + generator.writeEnd(); + } + } + + protected void writeToken(String name, JavaToken token, JsonGenerator generator) { + generator.writeStartObject(name); + generator.write(JsonToken.KIND.propertyKey, token.getKind()); + generator.write(JsonToken.TEXT.propertyKey, token.getText()); + generator.writeEnd(); + } + + /** + * excludes properties from meta model (except comment) + **/ + public enum JsonNode { + RANGE("range"), + TOKEN_RANGE("tokenRange"), + COMMENT(decapitalize(JavaParserMetaModel.commentMetaModel.getTypeName())), + CLASS("!"); + final String propertyKey; + + JsonNode(String p) { + this.propertyKey = p; + } + + public String toString() { + return this.propertyKey; + } + } + + public enum JsonRange { + BEGIN_LINE("beginLine"), + BEGIN_COLUMN("beginColumn"), + END_LINE("endLine"), + END_COLUMN("endColumn"); + final String propertyKey; + + JsonRange(String p) { + this.propertyKey = p; + } + + public String toString() { + return this.propertyKey; + } + } + + public enum JsonTokenRange { + BEGIN_TOKEN("beginToken"), + END_TOKEN("endToken"); + final String propertyKey; + + JsonTokenRange(String p) { + this.propertyKey = p; + } + + public String toString() { + return this.propertyKey; + } + } + + public enum JsonToken { + TEXT("text"), + KIND("kind"); + final String propertyKey; + + JsonToken(String p) { + this.propertyKey = p; + } + + public String toString() { + return this.propertyKey; + } + } +} diff --git a/javaparser-core-serialization/src/test/java/com/github/javaparser/serialization/JavaParserJsonDeserializerTest.java b/javaparser-core-serialization/src/test/java/com/github/javaparser/serialization/JavaParserJsonDeserializerTest.java new file mode 100644 index 0000000..bef9fb4 --- /dev/null +++ b/javaparser-core-serialization/src/test/java/com/github/javaparser/serialization/JavaParserJsonDeserializerTest.java @@ -0,0 +1,235 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.serialization; + +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.Range; +import com.github.javaparser.StaticJavaParser; +import com.github.javaparser.TokenRange; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.comments.Comment; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.type.Type; +import com.github.javaparser.javadoc.Javadoc; +import com.github.javaparser.javadoc.JavadocBlockTag; +import com.github.javaparser.resolution.SymbolResolver; +import com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration; +import com.github.javaparser.resolution.types.ResolvedType; +import com.github.javaparser.utils.LineSeparator; + +import jakarta.json.Json; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Test; + +import java.io.StringReader; + +import static com.github.javaparser.StaticJavaParser.*; +import static com.github.javaparser.serialization.JavaParserJsonSerializerTest.serialize; +import static com.github.javaparser.utils.Utils.normalizeEolInTextBlock; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class JavaParserJsonDeserializerTest { + private final JavaParserJsonDeserializer deserializer = new JavaParserJsonDeserializer(); + + @Test + void simpleTest() { + CompilationUnit cu = parse("public class X{} class Z{}"); + String serialized = serialize(cu, false); + + Node deserialized = deserializer.deserializeObject(Json.createReader(new StringReader(serialized))); + + assertEqualsStringIgnoringEol("public class X {\n}\n\nclass Z {\n}\n", deserialized.toString()); + assertEquals(cu.hashCode(), deserialized.hashCode()); + } + + @Test + void testRawType() { + Type type = parseType("Blub"); + String serialized = serialize(type, false); + + Node deserialized = deserializer.deserializeObject(Json.createReader(new StringReader(serialized))); + + assertEqualsStringIgnoringEol("Blub", deserialized.toString()); + assertEquals(type.hashCode(), deserialized.hashCode()); + } + + @Test + void testDiamondType() { + Type type = parseType("Blub<>"); + String serialized = serialize(type, false); + + Node deserialized = deserializer.deserializeObject(Json.createReader(new StringReader(serialized))); + + assertEqualsStringIgnoringEol("Blub<>", deserialized.toString()); + assertEquals(type.hashCode(), deserialized.hashCode()); + } + + @Test + void testGenerics() { + Type type = parseType("Blub"); + String serialized = serialize(type, false); + + Node deserialized = deserializer.deserializeObject(Json.createReader(new StringReader(serialized))); + + assertEqualsStringIgnoringEol("Blub", deserialized.toString()); + assertEquals(type.hashCode(), deserialized.hashCode()); + } + + @Test + void testOperator() { + Expression expr = parseExpression("1+1"); + String serialized = serialize(expr, false); + + Node deserialized = deserializer.deserializeObject(Json.createReader(new StringReader(serialized))); + + assertEqualsStringIgnoringEol("1 + 1", deserialized.toString()); + assertEquals(expr.hashCode(), deserialized.hashCode()); + } + + @Test + void testPrimitiveType() { + Type type = parseType("int"); + String serialized = serialize(type, false); + + Node deserialized = deserializer.deserializeObject(Json.createReader(new StringReader(serialized))); + + assertEqualsStringIgnoringEol("int", deserialized.toString()); + assertEquals(type.hashCode(), deserialized.hashCode()); + } + + @Test + void testComment() { + CompilationUnit cu = parse("/* block comment */\npublic class X{ \n // line comment\npublic void test() {}\n}"); + String serialized = serialize(cu, false); + + CompilationUnit deserialized = (CompilationUnit) deserializer.deserializeObject(Json.createReader(new StringReader(serialized))); + ClassOrInterfaceDeclaration classXDeclaration = deserialized.getClassByName("X").get(); + assertTrue(classXDeclaration.getComment().isPresent()); + + Comment comment = classXDeclaration.getComment().get(); + assertEquals("com.github.javaparser.ast.comments.BlockComment", comment.getClass().getName()); + assertEquals(" block comment ", comment.getContent()); + + MethodDeclaration methodDeclaration = classXDeclaration.getMethods().get(0); + assertTrue(methodDeclaration.getComment().isPresent()); + assertEquals("com.github.javaparser.ast.comments.LineComment", methodDeclaration.getComment().get().getClass().getName()); + assertEquals(" line comment", methodDeclaration.getComment().get().getContent()); + } + + @Test + void testJavaDocComment() { + CompilationUnit cu = parse("public class X{ " + + " /**\n" + + " * Woke text.\n" + + " * @param a blub\n" + + " * @return true \n" + + " */" + + " public boolean test(int a) { return true; }\n" + + "}"); + String serialized = serialize(cu, false); + + CompilationUnit deserialized = (CompilationUnit) deserializer.deserializeObject(Json.createReader(new StringReader(serialized))); + ClassOrInterfaceDeclaration classDeclaration = deserialized.getClassByName("X").get(); + MethodDeclaration methodDeclaration = classDeclaration.getMethods().get(0); + assertTrue(methodDeclaration.getJavadoc().isPresent()); + Javadoc javadoc = methodDeclaration.getJavadoc().get(); + + JavadocBlockTag paramBlockTag = javadoc.getBlockTags().get(0); + assertEquals("param", paramBlockTag.getTagName()); + assertEquals("blub", paramBlockTag.getContent().toText()); + + JavadocBlockTag returnBlockTag = javadoc.getBlockTags().get(1); + assertEquals("return", returnBlockTag.getTagName()); + assertEquals("true", returnBlockTag.getContent().toText()); + } + + @Test + void testNonMetaProperties() { + CompilationUnit cu = parse("public class X{} class Z{}"); + String serialized = serialize(cu, false); + + CompilationUnit deserialized = (CompilationUnit) deserializer.deserializeObject(Json.createReader(new StringReader(serialized))); + + assertTrue(deserialized.hasRange()); + Range range = deserialized.getRange().get(); + assertEquals(1, range.begin.line); + assertEquals(1, range.begin.line); + assertEquals(26, range.end.column); + + assertTrue(deserialized.getTokenRange().isPresent()); + TokenRange tokenRange = deserialized.getTokenRange().get(); + assertEquals("public", tokenRange.getBegin().getText()); + assertEquals("", tokenRange.getEnd().getText()); + } + + @Test + void testAttachingSymbolResolver() { + SymbolResolver stubResolver = new SymbolResolver() { + @Override + public T resolveDeclaration(Node node, Class resultClass) { + return null; + } + + @Override + public T toResolvedType(Type javaparserType, Class resultClass) { + return null; + } + + @Override + public ResolvedType calculateType(Expression expression) { + return null; + } + + @Override + public ResolvedReferenceTypeDeclaration toTypeDeclaration(Node node) { + return null; + } + }; + StaticJavaParser.getConfiguration().setSymbolResolver(stubResolver); + CompilationUnit cu = parse("public class X{} class Z{}"); + String serialized = serialize(cu, false); + + CompilationUnit deserialized = (CompilationUnit) deserializer.deserializeObject(Json.createReader(new StringReader(serialized))); + assertTrue(deserialized.containsData(Node.SYMBOL_RESOLVER_KEY)); + assertEquals(stubResolver, deserialized.getData(Node.SYMBOL_RESOLVER_KEY)); + } + + @AfterAll + static void clearConfiguration() { + StaticJavaParser.setConfiguration(new ParserConfiguration()); + } + + /** + * Assert that "actual" equals "expected", and that any EOL characters in "actual" are correct for the platform. + */ + private static void assertEqualsStringIgnoringEol(String expected, String actual) { + assertEquals( + normalizeEolInTextBlock(expected, LineSeparator.ARBITRARY), + normalizeEolInTextBlock(actual, LineSeparator.ARBITRARY) + ); + } + +} diff --git a/javaparser-core-serialization/src/test/java/com/github/javaparser/serialization/JavaParserJsonSerializerTest.java b/javaparser-core-serialization/src/test/java/com/github/javaparser/serialization/JavaParserJsonSerializerTest.java new file mode 100644 index 0000000..d56b093 --- /dev/null +++ b/javaparser-core-serialization/src/test/java/com/github/javaparser/serialization/JavaParserJsonSerializerTest.java @@ -0,0 +1,62 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.serialization; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; + +import jakarta.json.Json; +import jakarta.json.stream.JsonGenerator; +import jakarta.json.stream.JsonGeneratorFactory; + +import org.junit.jupiter.api.Test; + +import java.io.StringWriter; +import java.util.HashMap; +import java.util.Map; + +import static com.github.javaparser.StaticJavaParser.parse; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class JavaParserJsonSerializerTest { + @Test + void test() { + CompilationUnit cu = parse("class X{java.util.Y y;}"); + + String serialized = serialize(cu, false); + + assertEquals("{\"!\":\"com.github.javaparser.ast.CompilationUnit\",\"range\":{\"beginLine\":1,\"beginColumn\":1,\"endLine\":1,\"endColumn\":23},\"tokenRange\":{\"beginToken\":{\"kind\":19,\"text\":\"class\"},\"endToken\":{\"kind\":0,\"text\":\"\"}},\"imports\":[],\"types\":[{\"!\":\"com.github.javaparser.ast.body.ClassOrInterfaceDeclaration\",\"range\":{\"beginLine\":1,\"beginColumn\":1,\"endLine\":1,\"endColumn\":23},\"tokenRange\":{\"beginToken\":{\"kind\":19,\"text\":\"class\"},\"endToken\":{\"kind\":103,\"text\":\"}\"}},\"extendedTypes\":[],\"implementedTypes\":[],\"isInterface\":\"false\",\"permittedTypes\":[],\"typeParameters\":[],\"members\":[{\"!\":\"com.github.javaparser.ast.body.FieldDeclaration\",\"range\":{\"beginLine\":1,\"beginColumn\":9,\"endLine\":1,\"endColumn\":22},\"tokenRange\":{\"beginToken\":{\"kind\":97,\"text\":\"java\"},\"endToken\":{\"kind\":106,\"text\":\";\"}},\"modifiers\":[],\"variables\":[{\"!\":\"com.github.javaparser.ast.body.VariableDeclarator\",\"range\":{\"beginLine\":1,\"beginColumn\":21,\"endLine\":1,\"endColumn\":21},\"tokenRange\":{\"beginToken\":{\"kind\":97,\"text\":\"y\"},\"endToken\":{\"kind\":97,\"text\":\"y\"}},\"name\":{\"!\":\"com.github.javaparser.ast.expr.SimpleName\",\"range\":{\"beginLine\":1,\"beginColumn\":21,\"endLine\":1,\"endColumn\":21},\"tokenRange\":{\"beginToken\":{\"kind\":97,\"text\":\"y\"},\"endToken\":{\"kind\":97,\"text\":\"y\"}},\"identifier\":\"y\"},\"type\":{\"!\":\"com.github.javaparser.ast.type.ClassOrInterfaceType\",\"range\":{\"beginLine\":1,\"beginColumn\":9,\"endLine\":1,\"endColumn\":19},\"tokenRange\":{\"beginToken\":{\"kind\":97,\"text\":\"java\"},\"endToken\":{\"kind\":97,\"text\":\"Y\"}},\"name\":{\"!\":\"com.github.javaparser.ast.expr.SimpleName\",\"range\":{\"beginLine\":1,\"beginColumn\":19,\"endLine\":1,\"endColumn\":19},\"tokenRange\":{\"beginToken\":{\"kind\":97,\"text\":\"Y\"},\"endToken\":{\"kind\":97,\"text\":\"Y\"}},\"identifier\":\"Y\"},\"scope\":{\"!\":\"com.github.javaparser.ast.type.ClassOrInterfaceType\",\"range\":{\"beginLine\":1,\"beginColumn\":9,\"endLine\":1,\"endColumn\":17},\"tokenRange\":{\"beginToken\":{\"kind\":97,\"text\":\"java\"},\"endToken\":{\"kind\":97,\"text\":\"util\"}},\"name\":{\"!\":\"com.github.javaparser.ast.expr.SimpleName\",\"range\":{\"beginLine\":1,\"beginColumn\":14,\"endLine\":1,\"endColumn\":17},\"tokenRange\":{\"beginToken\":{\"kind\":97,\"text\":\"util\"},\"endToken\":{\"kind\":97,\"text\":\"util\"}},\"identifier\":\"util\"},\"scope\":{\"!\":\"com.github.javaparser.ast.type.ClassOrInterfaceType\",\"range\":{\"beginLine\":1,\"beginColumn\":9,\"endLine\":1,\"endColumn\":12},\"tokenRange\":{\"beginToken\":{\"kind\":97,\"text\":\"java\"},\"endToken\":{\"kind\":97,\"text\":\"java\"}},\"name\":{\"!\":\"com.github.javaparser.ast.expr.SimpleName\",\"range\":{\"beginLine\":1,\"beginColumn\":9,\"endLine\":1,\"endColumn\":12},\"tokenRange\":{\"beginToken\":{\"kind\":97,\"text\":\"java\"},\"endToken\":{\"kind\":97,\"text\":\"java\"}},\"identifier\":\"java\"},\"annotations\":[]},\"annotations\":[]},\"annotations\":[]}}],\"annotations\":[]}],\"modifiers\":[],\"name\":{\"!\":\"com.github.javaparser.ast.expr.SimpleName\",\"range\":{\"beginLine\":1,\"beginColumn\":7,\"endLine\":1,\"endColumn\":7},\"tokenRange\":{\"beginToken\":{\"kind\":97,\"text\":\"X\"},\"endToken\":{\"kind\":97,\"text\":\"X\"}},\"identifier\":\"X\"},\"annotations\":[]}]}", serialized); + } + + static String serialize(Node node, boolean prettyPrint) { + Map config = new HashMap<>(); + if (prettyPrint) { + config.put(JsonGenerator.PRETTY_PRINTING, null); + } + JsonGeneratorFactory generatorFactory = Json.createGeneratorFactory(config); + JavaParserJsonSerializer serializer = new JavaParserJsonSerializer(); + StringWriter jsonWriter = new StringWriter(); + try (JsonGenerator generator = generatorFactory.createGenerator(jsonWriter)) { + serializer.serialize(node, generator); + } + return jsonWriter.toString(); + } +} diff --git a/javaparser-core-testing-bdd/pom.xml b/javaparser-core-testing-bdd/pom.xml new file mode 100644 index 0000000..7cae9d4 --- /dev/null +++ b/javaparser-core-testing-bdd/pom.xml @@ -0,0 +1,132 @@ + + + javaparser-parent + com.github.javaparser + 3.25.10 + + 4.0.0 + + javaparser-core-testing-bdd + The BDD test suite for javaparser-core + + + + GNU Lesser General Public License + http://www.gnu.org/licenses/lgpl-3.0.html + repo + + + Apache License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + A business-friendly OSS license + + + + + + + org.jacoco + jacoco-maven-plugin + + + jacoco-initialize + + prepare-agent + + + + jacoco-report + test + + report + + + + + + maven-resources-plugin + + + copy-javaparser-core-classes + test-compile + + copy-resources + + + UTF-8 + ${basedir}/target/classes + + + ../javaparser-core/target/classes + false + + + + + + copy-javaparser-core-generated-sources + test-compile + + copy-resources + + + UTF-8 + ${basedir}/target/generated-sources/ + + + ../javaparser-core/target/generated-sources + false + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + true + + + + org.apache.maven.plugins + maven-surefire-plugin + + plain + true + + + + + + + com.github.javaparser + javaparser-core + ${project.version} + test + + + org.junit.jupiter + junit-jupiter-engine + + + org.junit.vintage + junit-vintage-engine + + + org.jbehave + jbehave-core + 5.2.0 + test + + + org.hamcrest + hamcrest + 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 new file mode 100644 index 0000000..df29a5d --- /dev/null +++ b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/BasicJBehaveTest.java @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + + +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; + +import java.util.List; + +import static org.jbehave.core.io.CodeLocations.codeLocationFromClass; + +abstract class BasicJBehaveTest extends JUnitStories { + + private final String storiesPath; + + BasicJBehaveTest(String storiesPath) { + this.storiesPath = storiesPath; + JUnit4StoryRunner.recommendedControls(configuredEmbedder()); + } + + @Override + public final Configuration configuration() { + return new MostUsefulConfiguration() + // where to find the stories + .useStoryLoader(new LoadFromClasspath(this.getClass())) + // Fails if Steps are not implemented + .usePendingStepStrategy(new FailingUponPendingStep()) + // CONSOLE and HTML reporting + .useStoryReporterBuilder(new StoryReporterBuilder().withDefaultFormats() + .withFormats(Format.CONSOLE, Format.HTML)); + } + + @Override + public final List storyPaths() { + return new StoryFinder().findPaths(codeLocationFromClass(this.getClass()), storiesPath, ""); + } + +} 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 new file mode 100644 index 0000000..b421b59 --- /dev/null +++ b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/CommentParsingTest.java @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.steps.CommentParsingSteps; +import org.jbehave.core.junit.JUnit4StoryRunner; +import org.jbehave.core.steps.InjectableStepsFactory; +import org.jbehave.core.steps.InstanceStepsFactory; +import org.junit.runner.RunWith; + +@RunWith(JUnit4StoryRunner.class) +public class CommentParsingTest extends BasicJBehaveTest { + + @Override + public InjectableStepsFactory stepsFactory() { + return new InstanceStepsFactory(configuration(), new CommentParsingSteps()); + } + + public CommentParsingTest() { + super("**/comment*.story"); + } +} + 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 new file mode 100644 index 0000000..7072ab7 --- /dev/null +++ b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/ComparingTest.java @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.steps.ComparingSteps; +import com.github.javaparser.steps.SharedSteps; +import org.jbehave.core.junit.JUnit4StoryRunner; +import org.jbehave.core.steps.InjectableStepsFactory; +import org.jbehave.core.steps.InstanceStepsFactory; +import org.junit.runner.RunWith; + +import java.util.HashMap; +import java.util.Map; + +@RunWith(JUnit4StoryRunner.class) +public class ComparingTest extends BasicJBehaveTest { + + @Override + public InjectableStepsFactory stepsFactory() { + Map state = new HashMap<>(); + + return new InstanceStepsFactory(configuration(), + new SharedSteps(state), + new ComparingSteps()); + } + + public ComparingTest() { + super("**/comparing*.story"); + } +} + + 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 new file mode 100644 index 0000000..559ae9b --- /dev/null +++ b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/ManipulationTest.java @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.steps.ManipulationSteps; +import com.github.javaparser.steps.SharedSteps; +import org.jbehave.core.junit.JUnit4StoryRunner; +import org.jbehave.core.steps.InjectableStepsFactory; +import org.jbehave.core.steps.InstanceStepsFactory; +import org.junit.runner.RunWith; + +import java.util.HashMap; +import java.util.Map; + +@RunWith(JUnit4StoryRunner.class) +public class ManipulationTest extends BasicJBehaveTest { + + @Override + public InjectableStepsFactory stepsFactory() { + Map state = new HashMap<>(); + + return new InstanceStepsFactory(configuration(), + new SharedSteps(state), + new ManipulationSteps(state)); + } + + public ManipulationTest() { + super("**/manipulation*.story"); + } +} 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 new file mode 100644 index 0000000..3e73bad --- /dev/null +++ b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/ParsingTest.java @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.steps.ParsingSteps; +import com.github.javaparser.steps.SharedSteps; +import org.jbehave.core.junit.JUnit4StoryRunner; +import org.jbehave.core.steps.InjectableStepsFactory; +import org.jbehave.core.steps.InstanceStepsFactory; +import org.junit.runner.RunWith; + +import java.util.HashMap; +import java.util.Map; + +@RunWith(JUnit4StoryRunner.class) +public class ParsingTest extends BasicJBehaveTest { + + @Override + public InjectableStepsFactory stepsFactory() { + Map state = new HashMap<>(); + + return new InstanceStepsFactory(configuration(), + new SharedSteps(state), + new ParsingSteps(state)); + } + + public ParsingTest() { + super("**/parsing*.story"); + } +} + + 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 new file mode 100644 index 0000000..615794b --- /dev/null +++ b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/PositionRangeTest.java @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.steps.PositionRangeSteps; +import com.github.javaparser.steps.SharedSteps; +import org.jbehave.core.junit.JUnit4StoryRunner; +import org.jbehave.core.steps.InjectableStepsFactory; +import org.jbehave.core.steps.InstanceStepsFactory; +import org.junit.runner.RunWith; + +import java.util.HashMap; +import java.util.Map; + +@RunWith(JUnit4StoryRunner.class) +public class PositionRangeTest extends BasicJBehaveTest { + + @Override + public InjectableStepsFactory stepsFactory() { + Map state = new HashMap<>(); + + return new InstanceStepsFactory(configuration(), + new SharedSteps(state), + new PositionRangeSteps()); + } + + public PositionRangeTest() { + super("**/position_range*.story"); + } +} + + 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 new file mode 100644 index 0000000..cf98815 --- /dev/null +++ b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/PrettyPrintingTest.java @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.steps.PrettyPrintingSteps; +import org.jbehave.core.junit.JUnit4StoryRunner; +import org.jbehave.core.steps.InjectableStepsFactory; +import org.jbehave.core.steps.InstanceStepsFactory; +import org.junit.runner.RunWith; + +@RunWith(JUnit4StoryRunner.class) +public class PrettyPrintingTest extends BasicJBehaveTest { + + @Override + public InjectableStepsFactory stepsFactory() { + return new InstanceStepsFactory(configuration(), new PrettyPrintingSteps()); + } + + public PrettyPrintingTest() { + super("**/pretty_printing*.story"); + } +} + diff --git a/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/TestUtils.java b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/TestUtils.java new file mode 100644 index 0000000..10c9e97 --- /dev/null +++ b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/TestUtils.java @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import java.io.InputStream; + +public class TestUtils { + + public static InputStream getSampleStream(String sampleName) { + InputStream is = TestUtils.class.getClassLoader().getResourceAsStream("com/github/javaparser/samples/" + + sampleName + ".java"); + if (is == null) { + throw new RuntimeException("Example not found, check your test. Sample name: " + sampleName); + } + return is; + } + +} 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 new file mode 100644 index 0000000..5ef26e1 --- /dev/null +++ b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/VisitorTest.java @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.steps.SharedSteps; +import com.github.javaparser.steps.VisitorSteps; +import org.jbehave.core.junit.JUnit4StoryRunner; +import org.jbehave.core.steps.InjectableStepsFactory; +import org.jbehave.core.steps.InstanceStepsFactory; +import org.junit.runner.RunWith; + +import java.util.HashMap; +import java.util.Map; + +@RunWith(JUnit4StoryRunner.class) +public class VisitorTest extends BasicJBehaveTest { + + @Override + public InjectableStepsFactory stepsFactory() { + Map state = new HashMap<>(); + return new InstanceStepsFactory(configuration(), + new SharedSteps(state), + new VisitorSteps(state)); + } + + public VisitorTest() { + super("**/visitor*.story"); + } +} + + + diff --git a/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/CommentParsingSteps.java b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/CommentParsingSteps.java new file mode 100644 index 0000000..d61864d --- /dev/null +++ b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/CommentParsingSteps.java @@ -0,0 +1,432 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.steps; + +import com.github.javaparser.*; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.comments.*; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.expr.IntegerLiteralExpr; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.ast.stmt.ExpressionStmt; +import com.github.javaparser.ast.type.PrimitiveType; +import com.github.javaparser.printer.PrettyPrinter; +import com.github.javaparser.printer.Printer; +import com.github.javaparser.printer.configuration.PrettyPrinterConfiguration; +import org.jbehave.core.annotations.Alias; +import org.jbehave.core.annotations.Given; +import org.jbehave.core.annotations.Then; +import org.jbehave.core.annotations.When; +import org.jbehave.core.model.ExamplesTable; +import org.jbehave.core.steps.Parameters; + +import java.nio.charset.Charset; +import java.util.Iterator; +import java.util.Set; + +import static com.github.javaparser.ParseStart.COMPILATION_UNIT; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.Range.range; +import static com.github.javaparser.steps.SharedSteps.getMemberByTypeAndPosition; +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.text.IsEqualCompressingWhiteSpace.equalToCompressingWhiteSpace; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + +public class CommentParsingSteps { + + private CompilationUnit compilationUnit; + private CommentsCollection commentsCollection; + private String sourceUnderTest; + private ParserConfiguration configuration = new ParserConfiguration(); + private Printer prettyPrinter = new PrettyPrinter(new PrettyPrinterConfiguration()); + + @Given("the class:$classSrc") + public void givenTheClass(String classSrc) { + this.sourceUnderTest = classSrc.trim(); + } + + @When("read sample \"$sampleName\" using encoding \"$encoding\"") + public void givenTheClassWithEncoding(String sampleName, String encoding) { + sourceUnderTest = null; + ParseResult parseResult = new JavaParser(new ParserConfiguration()).parse( + COMPILATION_UNIT, + provider( + TestUtils.getSampleStream(sampleName), + Charset.forName(encoding))); + commentsCollection = parseResult.getCommentsCollection().orElse(new CommentsCollection()); + } + + @When("the class is parsed by the comment parser") + public void whenTheClassIsParsedByTheCommentParser() { + ParseResult parseResult = new JavaParser(new ParserConfiguration()).parse(COMPILATION_UNIT, provider(sourceUnderTest)); + commentsCollection = parseResult.getCommentsCollection().orElse(new CommentsCollection()); + } + + @When("the do not consider annotations as node start for code attribution is $value on the Java parser") + public void whenTheDoNotConsiderAnnotationsAsNodeStartForCodeAttributionIsTrueOnTheJavaParser(boolean value) { + configuration.setIgnoreAnnotationsWhenAttributingComments(value); + } + + @When("the do not assign comments preceding empty lines is $value on the Java parser") + public void whenTheDoNotAssignCommentsPrecedingEmptyLinesIsTrueOnTheJavaParser(boolean value) { + configuration.setDoNotAssignCommentsPrecedingEmptyLines(value); + } + + @When("the class is parsed by the Java parser") + public void whenTheClassIsParsedByTheJavaParser() { + ParseResult result = new JavaParser(configuration).parse(COMPILATION_UNIT, provider(sourceUnderTest)); + compilationUnit = result.getResult().get(); + } + + @Then("the Java parser cannot parse it because of an error") + public void javaParserCannotParseBecauseOfLexicalErrors() { + ParseResult result = new JavaParser(configuration).parse(COMPILATION_UNIT, provider(sourceUnderTest)); + if (result.isSuccessful()) { + fail("Lexical error expected"); + } + } + + @Then("the total number of comments is $expectedCount") + public void thenTheTotalNumberOfCommentsIs(int expectedCount) { + assertThat(commentsCollection.size(), is(expectedCount)); + } + + private T getCommentAt(Set set, int index) { + Iterator iterator = set.iterator(); + T comment = null; + while (index >= 0) { + comment = iterator.next(); + index--; + } + return comment; + } + + @Then("line comment $position is \"$expectedContent\"") + public void thenLineCommentIs(int position, String expectedContent) { + LineComment lineCommentUnderTest = getCommentAt(commentsCollection.getLineComments(), position - 1); + + assertThat(lineCommentUnderTest.getContent(), is(expectedContent)); + } + + @Then("block comment $position is \"$expectedContent\"") + public void thenBlockCommentIs(int position, String expectedContent) { + BlockComment lineCommentUnderTest = getCommentAt(commentsCollection.getBlockComments(), position - 1); + + assertThat(lineCommentUnderTest.getContent(), is(equalToCompressingWhiteSpace(expectedContent))); + } + + @Then("Javadoc comment $position is \"$expectedContent\"") + public void thenJavadocCommentIs(int position, String expectedContent) { + JavadocComment commentUnderTest = getCommentAt(commentsCollection.getJavadocComments(), position - 1); + + assertThat(commentUnderTest.getContent(), is(equalToCompressingWhiteSpace(expectedContent))); + } + + @Then("the line comments have the following positions: $table") + public void thenTheLineCommentsHaveTheFollowingPositions(ExamplesTable examplesTable) { + int index = 0; + for (Parameters exampleRow : examplesTable.getRowsAsParameters()) { + Comment expectedLineComment = toComment(exampleRow, new LineComment()); + Comment lineCommentUnderTest = getCommentAt(commentsCollection.getLineComments(), index); + + Range underTestRange = lineCommentUnderTest.getRange().get(); + Range expectedRange = expectedLineComment.getRange().get(); + + assertThat(underTestRange.begin.line, is(expectedRange.begin.line)); + assertThat(underTestRange.begin.column, is(expectedRange.begin.column)); + assertThat(underTestRange.end.line, is(expectedRange.end.line)); + assertThat(underTestRange.end.column, is(expectedRange.end.column)); + index++; + } + } + + @Then("the block comments have the following positions: $table") + public void thenTheBlockCommentsHaveTheFollowingPositions(ExamplesTable examplesTable) { + int index = 0; + for (Parameters exampleRow : examplesTable.getRowsAsParameters()) { + Comment expectedLineComment = toComment(exampleRow, new BlockComment()); + Comment lineCommentUnderTest = getCommentAt(commentsCollection.getBlockComments(), index); + + Range underTestRange = lineCommentUnderTest.getRange().get(); + Range expectedRange = expectedLineComment.getRange().get(); + + assertThat(underTestRange.begin.line, is(expectedRange.begin.line)); + assertThat(underTestRange.begin.column, is(expectedRange.begin.column)); + assertThat(underTestRange.end.line, is(expectedRange.end.line)); + assertThat(underTestRange.end.column, is(expectedRange.end.column)); + index++; + } + } + + @Then("the Javadoc comments have the following positions: $table") + public void thenTheJavadocCommentsHaveTheFollowingPositions(ExamplesTable examplesTable) { + int index = 0; + for (Parameters exampleRow : examplesTable.getRowsAsParameters()) { + Comment expectedLineComment = toComment(exampleRow, new BlockComment()); + Comment lineCommentUnderTest = getCommentAt(commentsCollection.getJavadocComments(), index); + + Range underTestRange = lineCommentUnderTest.getRange().get(); + Range expectedRange = expectedLineComment.getRange().get(); + + assertThat(underTestRange.begin.line, is(expectedRange.begin.line)); + assertThat(underTestRange.begin.column, is(expectedRange.begin.column)); + assertThat(underTestRange.end.line, is(expectedRange.end.line)); + assertThat(underTestRange.end.column, is(expectedRange.end.column)); + index++; + } + } + + @Then("it is printed as:$src") + public void isPrintedAs(String src) { + assertThat(prettyPrinter.print(compilationUnit).trim(), is(src.trim())); + } + + @Then("the compilation unit is not commented") + public void thenTheCompilationUnitIsNotCommented() { + assertEquals(false, compilationUnit.getComment().isPresent()); + } + + @Then("the compilation is commented \"$expectedContent\"") + public void thenTheCompilationIsCommentedCompilationUnitComment(String expectedContent) { + assertThat(compilationUnit.getComment().get().getContent(), is(expectedContent)); + } + + @Then("the compilation unit has $expectedCount contained comments") + public void thenTheCompilationUnitHasContainedComments(int expectedCount) { + assertThat(compilationUnit.getComments().size(), is(expectedCount)); + } + + @Then("the compilation unit has $expectedCount orphan comments") + public void thenTheCompilationUnitHasExpectedCountOrphanComments(int expectedCount) { + assertThat(compilationUnit.getOrphanComments().size(), is(expectedCount)); + } + + @Then("the compilation unit orphan comment $position is \"$expectedContent\"") + public void thenTheCompilationUnitOrphanCommentIs(int position, String expectedContent) { + Comment commentUnderTest = compilationUnit.getOrphanComments().get(position - 1); + assertThat(commentUnderTest.getContent(), is(equalToCompressingWhiteSpace(expectedContent))); + } + + @Then("comment $commentPosition in compilation unit is not an orphan") + public void thenCommentInCompilationUnitIsNotAnOrphan(int commentPosition) { + Comment commentUnderTest = compilationUnit.getAllContainedComments().get(commentPosition - 1); + assertThat(commentUnderTest.isOrphan(), is(false)); + } + + @Then("comment $commentPosition in compilation unit is an orphan") + public void thenCommentInCompilationUnitIsAnOrphan(int commentPosition) { + Comment commentUnderTest = compilationUnit.getAllContainedComments().get(commentPosition - 1); + assertThat(commentUnderTest.isOrphan(), is(true)); + } + + @Then("comment $commentPosition in compilation unit is \"$expectedContent\"") + public void thenCommentInCompilationUnitIs(int position, String expectedContent) { + Comment commentUnderTest = compilationUnit.getAllContainedComments().get(position - 1); + assertThat(commentUnderTest.getContent(), is(equalToCompressingWhiteSpace(expectedContent))); + } + + @Then("class $position is not commented") + public void thenClassIsNotCommented(int position) { + TypeDeclaration classUnderTest = compilationUnit.getType(position - 1); + assertEquals(false, classUnderTest.getComment().isPresent()); + } + + @Then("class $position is commented \"$expectedContent\"") + public void thenClassIsCommented(int position, String expectedContent) { + TypeDeclaration classUnderTest = compilationUnit.getType(position - 1); + assertThat(classUnderTest.getComment().get().getContent(), is(expectedContent)); + } + + @Then("class $position has $expectedCount total contained comments") + public void thenClassHasTotalContainedComments(int position, int expectedCount) { + TypeDeclaration classUnderTest = compilationUnit.getType(position - 1); + assertThat(classUnderTest.getAllContainedComments().size(), is(expectedCount)); + } + + @Then("class $position has $expectedCount orphan comment") + @Alias("class $position has $expectedCount orphan comments") + public void thenClassHasOrphanComments(int position, int expectedCount) { + TypeDeclaration classUnderTest = compilationUnit.getType(position - 1); + assertThat(classUnderTest.getOrphanComments().size(), is(expectedCount)); + } + + @Then("class $classPosition orphan comment $commentPosition is \"$expectedContent\"") + public void thenClassOrphanCommentIs(int classPosition, int commentPosition, String expectedContent) { + TypeDeclaration classUnderTest = compilationUnit.getType(classPosition - 1); + Comment commentUnderTest = classUnderTest.getOrphanComments().get(commentPosition - 1); + assertThat(commentUnderTest.getContent(), is(equalToCompressingWhiteSpace(expectedContent))); + } + + @Then("method $methodPosition in class $classPosition is commented \"$expectedContent\"") + public void thenMethodInClassIsCommented(int methodPosition, int classPosition, String expectedContent) { + TypeDeclaration classUnderTest = compilationUnit.getType(classPosition - 1); + MethodDeclaration methodUnderTest = getMemberByTypeAndPosition(classUnderTest, methodPosition - 1, + MethodDeclaration.class); + assertThat(methodUnderTest.getComment().get().getContent(), equalToCompressingWhiteSpace(expectedContent)); + } + + @Then("method $methodPosition in class $classPosition has $expectedCount total contained comments") + public void thenMethodInClassHasTotalContainedComments(int methodPosition, int classPosition, int expectedCount) { + TypeDeclaration classUnderTest = compilationUnit.getType(classPosition - 1); + MethodDeclaration methodUnderTest = getMemberByTypeAndPosition(classUnderTest, methodPosition - 1, + MethodDeclaration.class); + assertThat(methodUnderTest.getAllContainedComments().size(), is(expectedCount)); + } + + @Then("comment $commentPosition in method $methodPosition in class $classPosition is \"$expectedContent\"") + public void thenCommentInMethodInClassIs(int commentPosition, int methodPosition, int classPosition, String expectedContent) { + TypeDeclaration classUnderTest = compilationUnit.getType(classPosition - 1); + MethodDeclaration methodUnderTest = getMemberByTypeAndPosition(classUnderTest, methodPosition - 1, + MethodDeclaration.class); + Comment commentUnderTest = methodUnderTest.getAllContainedComments().get(commentPosition - 1); + assertThat(commentUnderTest.getContent(), is(equalToCompressingWhiteSpace(expectedContent))); + } + + @Then("method $methodPosition in class $classPosition has $expectedCount orphan comments") + public void thenMethodInClassHasOrphanComments(int methodPosition, int classPosition, int expectedCount) { + TypeDeclaration classUnderTest = compilationUnit.getType(classPosition - 1); + MethodDeclaration methodUnderTest = getMemberByTypeAndPosition(classUnderTest, methodPosition - 1, + MethodDeclaration.class); + assertThat(methodUnderTest.getOrphanComments().size(), is(expectedCount)); + } + + @Then("block statement in method $methodPosition in class $classPosition has $expectedCount total contained comments") + public void thenBlockStatementInMethodInClassHasTotalContainedComments(int methodPosition, int classPosition, int expectedCount) { + TypeDeclaration classUnderTest = compilationUnit.getType(classPosition - 1); + MethodDeclaration methodUnderTest = getMemberByTypeAndPosition(classUnderTest, methodPosition - 1, + MethodDeclaration.class); + BlockStmt blockStmtUnderTest = methodUnderTest.getBody().orElse(null); + assertThat(blockStmtUnderTest.getAllContainedComments().size(), is(expectedCount)); + } + + @Then("block statement in method $methodPosition in class $classPosition has $expectedCount orphan comments") + public void thenBlockStatementInMethodInClassHasOrphanComments(int methodPosition, int classPosition, int expectedCount) { + TypeDeclaration classUnderTest = compilationUnit.getType(classPosition - 1); + MethodDeclaration methodUnderTest = getMemberByTypeAndPosition(classUnderTest, methodPosition - 1, + MethodDeclaration.class); + BlockStmt blockStmtUnderTest = methodUnderTest.getBody().orElse(null); + assertThat(blockStmtUnderTest.getOrphanComments().size(), is(expectedCount)); + } + + @Then("block statement in method $methodPosition in class $classPosition orphan comment $commentPosition is \"$expectedContent\"") + public void thenBlockStatementInMethodInClassIs(int methodPosition, int classPosition, int commentPosition, String expectedContent) { + TypeDeclaration classUnderTest = compilationUnit.getType(classPosition - 1); + MethodDeclaration methodUnderTest = getMemberByTypeAndPosition(classUnderTest, methodPosition - 1, + MethodDeclaration.class); + BlockStmt blockStmtUnderTest = methodUnderTest.getBody().orElse(null); + Comment commentUnderTest = blockStmtUnderTest.getOrphanComments().get(commentPosition - 1); + assertThat(commentUnderTest.getContent(), is(equalToCompressingWhiteSpace(expectedContent))); + } + + @Then("type of method $methodPosition in class $classPosition is commented \"$expectedContent\"") + public void thenTypeOfMethodInClassIsCommented(int methodPosition, int classPosition, String expectedContent) { + TypeDeclaration classUnderTest = compilationUnit.getType(classPosition - 1); + MethodDeclaration methodUnderTest = getMemberByTypeAndPosition(classUnderTest, methodPosition - 1, + MethodDeclaration.class); + Comment commentUnderTest = methodUnderTest.getType().getComment().get(); + assertThat(commentUnderTest.getContent(), is(equalToCompressingWhiteSpace(expectedContent))); + } + + @Then("field $fieldPosition in class $classPosition contains $expectedCount comments") + public void thenFieldInClassContainsComments(int fieldPosition, int classPosition, int expectedCount) { + TypeDeclaration classUnderTest = compilationUnit.getType(classPosition - 1); + FieldDeclaration fieldUnderTest = getMemberByTypeAndPosition(classUnderTest, fieldPosition - 1, + FieldDeclaration.class); + assertThat(fieldUnderTest.getAllContainedComments().size(), is(expectedCount)); + } + + @Then("field $fieldPosition in class $classPosition is not commented") + public void thenFieldInClassIsNotCommented(int fieldPosition, int classPosition) { + TypeDeclaration classUnderTest = compilationUnit.getType(classPosition - 1); + FieldDeclaration fieldUnderTest = getMemberByTypeAndPosition(classUnderTest, fieldPosition - 1, + FieldDeclaration.class); + assertEquals(false, fieldUnderTest.getComment().isPresent()); + } + + @Then("field $fieldPosition in class $classPosition is commented \"$expectedContent\"") + public void thenFieldInClassIsCommented(int fieldPosition, int classPosition, String expectedContent) { + TypeDeclaration classUnderTest = compilationUnit.getType(classPosition - 1); + FieldDeclaration fieldUnderTest = getMemberByTypeAndPosition(classUnderTest, fieldPosition - 1, + FieldDeclaration.class); + Comment commentUnderTest = fieldUnderTest.getComment().get(); + assertThat(commentUnderTest.getContent(), is(equalToCompressingWhiteSpace(expectedContent))); + } + + @Then("variable $variablePosition value of field $fieldPosition in class $classPosition is commented \"$expectedContent\"") + public void thenVariableValueOfFieldInClassIsCommented(int variablePosition, int fieldPosition, int classPosition, String expectedContent) { + TypeDeclaration classUnderTest = compilationUnit.getType(classPosition - 1); + FieldDeclaration fieldUnderTest = getMemberByTypeAndPosition(classUnderTest, fieldPosition - 1, + FieldDeclaration.class); + VariableDeclarator variableUnderTest = fieldUnderTest.getVariable(variablePosition - 1); + Expression valueUnderTest = variableUnderTest.getInitializer().orElse(null); + Comment commentUnderTest = valueUnderTest.getComment().get(); + assertThat(commentUnderTest.getContent(), is(expectedContent)); + } + + @Then("comment $commentPosition in compilation unit parent is ClassOrInterfaceDeclaration") + public void thenCommentInCompilationUnitParentIsClassOrInterfaceDeclaration(int commentPosition) { + Comment commentUnderTest = compilationUnit.getAllContainedComments().get(commentPosition - 1); + assertThat(commentUnderTest.getParentNode().get(), instanceOf(ClassOrInterfaceDeclaration.class)); + } + + @Then("comment $commentPosition in compilation unit commented node is ClassOrInterfaceDeclaration") + public void thenCommentInCompilationUnitCommentedNodeIsClassOrInterfaceDeclaration(int commentPosition) { + Comment commentUnderTest = compilationUnit.getAllContainedComments().get(commentPosition - 1); + assertThat(commentUnderTest.getCommentedNode().get(), instanceOf(ClassOrInterfaceDeclaration.class)); + } + + @Then("comment $commentPosition in compilation unit commented node is FieldDeclaration") + public void thenCommentInCompilationUnitCommentedNodeIsFieldDeclaration(int commentPosition) { + Comment commentUnderTest = compilationUnit.getAllContainedComments().get(commentPosition - 1); + assertThat(commentUnderTest.getCommentedNode().get(), instanceOf(FieldDeclaration.class)); + } + + @Then("comment $commentPosition in compilation unit commented node is IntegerLiteralExpr") + public void thenCommentInCompilationUnitCommentedNodeIsIntegerLiteralExpr(int commentPosition) { + Comment commentUnderTest = compilationUnit.getAllContainedComments().get(commentPosition - 1); + assertThat(commentUnderTest.getCommentedNode().get(), instanceOf(IntegerLiteralExpr.class)); + } + + @Then("comment $commentPosition in compilation unit commented node is ExpressionStmt") + public void thenCommentInCompilationUnitCommentedNodeIsIntegerExpressionStmt(int commentPosition) { + Comment commentUnderTest = compilationUnit.getAllContainedComments().get(commentPosition - 1); + assertThat(commentUnderTest.getCommentedNode().get(), instanceOf(ExpressionStmt.class)); + } + + @Then("comment $commentPosition in compilation unit commented node is PrimitiveType") + public void thenCommentInCompilationUnitCommentedNodeIsIntegerPrimitiveType(int commentPosition) { + Comment commentUnderTest = compilationUnit.getAllContainedComments().get(commentPosition - 1); + assertThat(commentUnderTest.getCommentedNode().get(), instanceOf(PrimitiveType.class)); + } + + private Comment toComment(Parameters row, Comment comment) { + comment.setRange(range(Integer.parseInt(row.values().get("beginLine")), + Integer.parseInt(row.values().get("beginColumn")), + Integer.parseInt(row.values().get("endLine")), + Integer.parseInt(row.values().get("endColumn")))); + return comment; + } +} diff --git a/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/ComparingSteps.java b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/ComparingSteps.java new file mode 100644 index 0000000..9a09e92 --- /dev/null +++ b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/ComparingSteps.java @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.steps; + +import com.github.javaparser.ast.CompilationUnit; +import org.jbehave.core.annotations.Given; +import org.jbehave.core.annotations.Then; + +import static com.github.javaparser.StaticJavaParser.parse; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +public class ComparingSteps { + + private CompilationUnit first; + private CompilationUnit second; + + /* + * Given steps + */ + + @Given("the first class:$classSrc") + public void givenTheFirstClass(String classSrc) { + this.first = parse(classSrc.trim()); + } + + @Given("the second class:$classSrc") + public void givenTheSecondClass(String classSrc) { + this.second = parse(classSrc.trim()); + } + + /* + * Then steps + */ + + @Then("they are equals") + public void thenTheyAreEquals() { + assertThat(first, is(equalTo(second))); + } + +} diff --git a/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/ExistenceOfParentNodeVerifier.java b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/ExistenceOfParentNodeVerifier.java new file mode 100644 index 0000000..69b6089 --- /dev/null +++ b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/ExistenceOfParentNodeVerifier.java @@ -0,0 +1,551 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.steps; + +import com.github.javaparser.HasParentNode; +import com.github.javaparser.ast.ArrayCreationLevel; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.PackageDeclaration; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.comments.BlockComment; +import com.github.javaparser.ast.comments.JavadocComment; +import com.github.javaparser.ast.comments.LineComment; +import com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.stmt.*; +import com.github.javaparser.ast.type.*; +import com.github.javaparser.ast.visitor.VoidVisitorAdapter; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.core.Is.is; + +/** + * The ExistenceOfParentNodeVerifier verifies that each node of the compilation unit has a parent set. + */ +class ExistenceOfParentNodeVerifier { + + public void verify(CompilationUnit compilationUnit) throws AssertionError { + new Verifier().visit(compilationUnit, null); + } + + private static class Verifier extends VoidVisitorAdapter { + private static void assertParentIsSet(HasParentNode n) { + assertThat(n + " has no parent set!", n.getParentNode().orElse(null), is(notNullValue())); + } + + @Override + public void visit(AnnotationDeclaration n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(AnnotationMemberDeclaration n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ArrayAccessExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ArrayCreationExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ArrayInitializerExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(AssertStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(AssignExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(BinaryExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(BlockComment n, Void arg) { + super.visit(n, arg); + } + + @Override + public void visit(BlockStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(BooleanLiteralExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(BreakStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(CastExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(CatchClause n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(CharLiteralExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ClassExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ClassOrInterfaceDeclaration n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ClassOrInterfaceType n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(CompilationUnit n, Void arg) { + super.visit(n, arg); + } + + @Override + public void visit(ConditionalExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ConstructorDeclaration n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ContinueStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(DoStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(DoubleLiteralExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(EmptyStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(EnclosedExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(EnumConstantDeclaration n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(EnumDeclaration n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ExplicitConstructorInvocationStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ExpressionStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(FieldAccessExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(FieldDeclaration n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ForEachStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ForStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(IfStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(InitializerDeclaration n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(InstanceOfExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(IntegerLiteralExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(JavadocComment n, Void arg) { + super.visit(n, arg); + } + + @Override + public void visit(LabeledStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(LineComment n, Void arg) { + super.visit(n, arg); + } + + @Override + public void visit(LambdaExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(LongLiteralExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(MarkerAnnotationExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(MemberValuePair n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(MethodCallExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(MethodDeclaration n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(MethodReferenceExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(NameExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(NormalAnnotationExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(NullLiteralExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ObjectCreationExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(PackageDeclaration n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(Parameter n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(PrimitiveType n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(Name n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(SimpleName n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ArrayType n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ArrayCreationLevel n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(IntersectionType n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(UnionType n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ReturnStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(SingleMemberAnnotationExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(StringLiteralExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(SuperExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(SwitchEntry n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(SwitchStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(SynchronizedStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ThisExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ThrowStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(TryStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(LocalClassDeclarationStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(LocalRecordDeclarationStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(TypeExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(NodeList n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(TypeParameter n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(UnaryExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(UnknownType n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(VariableDeclarationExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(VariableDeclarator n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(VoidType n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(WhileStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(WildcardType n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + } + +} diff --git a/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/ManipulationSteps.java b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/ManipulationSteps.java new file mode 100644 index 0000000..a8c10f0 --- /dev/null +++ b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/ManipulationSteps.java @@ -0,0 +1,285 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.steps; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.PackageDeclaration; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.body.Parameter; +import com.github.javaparser.ast.body.TypeDeclaration; +import com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.ast.stmt.TryStmt; +import com.github.javaparser.ast.type.VoidType; +import com.github.javaparser.ast.visitor.VoidVisitorAdapter; +import org.jbehave.core.annotations.Alias; +import org.jbehave.core.annotations.Given; +import org.jbehave.core.annotations.Then; +import org.jbehave.core.annotations.When; + +import java.util.Map; + +import static com.github.javaparser.StaticJavaParser.*; +import static com.github.javaparser.ast.Modifier.Keyword.PUBLIC; +import static com.github.javaparser.ast.Modifier.createModifierList; +import static com.github.javaparser.ast.Modifier.staticModifier; +import static com.github.javaparser.ast.NodeList.nodeList; +import static com.github.javaparser.ast.type.PrimitiveType.intType; +import static com.github.javaparser.steps.SharedSteps.getMethodByPositionAndClassPosition; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +public class ManipulationSteps { + + /* Fields used to maintain step state within this step class */ + private BlockStmt blockStmt; + private Statement statement; + private TryStmt tryStmt; + private NodeList variableDeclarationExprList; + private ChangeMethodNameToUpperCaseVisitor changeMethodNameToUpperCaseVisitor; + private AddNewIntParameterCalledValueVisitor addNewIntParameterCalledValueVisitor; + + /* Map that maintains shares state across step classes. If manipulating the objects in the map you must update the state */ + private Map state; + + public ManipulationSteps(Map state) { + this.state = state; + } + + @Given("a BlockStmt") + public void givenABlockStatement() { + blockStmt = new BlockStmt(); + } + + @Given("a Statement") + public void givenAStatement() { + statement = null; + } + + @Given("a TryStmt") + public void givenATryStmt() { + tryStmt = new TryStmt(); + } + + @Given("a List of VariableDeclarations") + public void givenAListOfVariableDeclarations() { + variableDeclarationExprList = new NodeList<>(); + variableDeclarationExprList.add(new VariableDeclarationExpr()); + variableDeclarationExprList.add(new VariableDeclarationExpr()); + } + + @Given("a ChangeNameToUpperCaseVisitor") + public void givenAChangeNameToUpperCaseVisitor() { + changeMethodNameToUpperCaseVisitor = new ChangeMethodNameToUpperCaseVisitor(); + } + + @Given("a AddNewIntParameterCalledValueVisitor") + public void givenAAddNewParameterCalledValueVisitor() { + addNewIntParameterCalledValueVisitor = new AddNewIntParameterCalledValueVisitor(); + } + + @When("is the String \"$value\" is parsed by the JavaParser using parseBlock") + public void whenIsTheStringIsParsedByTheJavaParser(String value) { + blockStmt = parseBlock(value); + } + + @When("is the String \"$value\" is parsed by the JavaParser using parseStatement") + public void whenIsTheStringIsParsedByTheJavaParserUsingParseStatement(String value) { + statement = parseStatement(value); + } + + @When("the List of VariableDeclarations are set as the resources on TryStmt") + public void whenTheListOfVariableDeclarationsAreSetAsTheResourcesOnTryStmt() { + tryStmt.setResources(variableDeclarationExprList); + } + + @When("empty list is set as the resources on TryStmt") + public void whenNullIsSetAsTheResourcesOnTryStmt() { + tryStmt.setResources(new NodeList<>()); + } + + @When("the package declaration is set to \"$packageName\"") + public void whenThePackageDeclarationIsSetTo(String packageName) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + compilationUnit.setPackageDeclaration(new PackageDeclaration(parseName(packageName))); + state.put("cu1", compilationUnit); + } + + @When("a public class called \"$className\" is added to the CompilationUnit") + public void whenAClassCalledIsAddedToTheCompilationUnit(String className) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + TypeDeclaration type = new ClassOrInterfaceDeclaration(createModifierList(PUBLIC), false, "CreateClass"); + compilationUnit.setTypes(nodeList(type)); + state.put("cu1", compilationUnit); + } + + @When("a public static method called \"$methodName\" returning void is added to class $position in the compilation unit") + public void whenAStaticMethodCalledReturningIsAddedToClassInTheCompilationUnit(String methodName, int position) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + TypeDeclaration type = compilationUnit.getType(position - 1); + NodeList modifiers = createModifierList(PUBLIC); + MethodDeclaration method = new MethodDeclaration(modifiers, new VoidType(), methodName); + modifiers.add(staticModifier()); + method.setModifiers(modifiers); + type.addMember(method); + state.put("cu1", compilationUnit); + } + + @When("$typeName varargs called \"$parameterName\" are added to method $methodPosition in class $classPosition") + public void whenVarargsCalledAreAddedToMethodInClass(String typeName, String parameterName, int methodPosition, int classPosition) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + getMethodByPositionAndClassPosition(compilationUnit, methodPosition, classPosition) + .addAndGetParameter(typeName, parameterName) + .setVarArgs(true); + } + + @When("a BlockStmt is added to method $methodPosition in class $classPosition") + public void whenABlockStmtIsAddedToMethodInClass(int methodPosition, int classPosition) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + MethodDeclaration method = getMethodByPositionAndClassPosition(compilationUnit, methodPosition, classPosition); + method.setBody(new BlockStmt()); + } + + @When("$className.$fieldName.$methodName(\"$stringValue\"); is added to the body of method $methodPosition in class $classPosition") + public void whenHelloWorldIsAddedToTheBodyOfMethodInClass(String className, String fieldName, String methodName, String stringValue, + int methodPosition, int classPosition) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + MethodDeclaration method = getMethodByPositionAndClassPosition(compilationUnit, methodPosition, classPosition); + NameExpr clazz = new NameExpr(className); + FieldAccessExpr field = new FieldAccessExpr(clazz, fieldName); + MethodCallExpr call = new MethodCallExpr(field, methodName); + call.addArgument(new StringLiteralExpr(stringValue)); + method.getBody().get().addStatement(call); + } + + @When("method $methodPosition in class $classPosition has it's name converted to uppercase") + public void whenMethodInClassHasItsNameConvertedToUppercase(int methodPosition, int classPosition) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + MethodDeclaration method = getMethodByPositionAndClassPosition(compilationUnit, methodPosition, classPosition); + method.setName(method.getNameAsString().toUpperCase()); + } + + @When("method $methodPosition in class $classPosition has an int parameter called \"$paramName\" added") + public void whenMethodInClassHasAnIntArgumentCalledAdded(int methodPosition, int classPosition, String paramName) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + MethodDeclaration method = getMethodByPositionAndClassPosition(compilationUnit, methodPosition, classPosition); + method.addParameter(intType(), paramName); + } + + @When("the compilation unit is cloned") + public void whenTheCompilationUnitIsCloned() { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + state.put("cu1", compilationUnit.clone()); + } + + @When("the ChangeNameToUpperCaseVisitor visits to compilation unit") + public void whenTheVisitorVisitsToCompilationUnit() { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + changeMethodNameToUpperCaseVisitor.visit(compilationUnit, null); + state.put("cu1", compilationUnit); + } + + @When("the AddNewIntParameterCalledValueVisitor visits to compilation unit") + public void whenTheAddNewParameterCalledValueVisitorVisitsToCompilationUnit() { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + addNewIntParameterCalledValueVisitor.visit(compilationUnit, null); + state.put("cu1", compilationUnit); + } + + @Then("is not equal to null") + public void thenIsNotEqualToNull() { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + assertNotEquals(compilationUnit, null); + } + + @Then("is not equal to $value") + public void thenIsNotEqualTo(String value) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + assertNotEquals(compilationUnit, value); + } + + @Then("Statement $position in BlockStmt toString is \"$expectedContent\"") + public void thenTheBlockStmtContentIs(int position, String expectedContent) { + Statement statementUnderTest = blockStmt.getStatement(position - 1); + assertThat(statementUnderTest.toString(), is(expectedContent)); + } + + @Then("Statement toString is \"$expectedContent\"") + public void thenStatementToStringIsxXy(String expectedContent) { + assertThat(statement.toString(), is(expectedContent)); + } + + @Then("all the VariableDeclarations parent is the TryStmt") + public void thenAllTheVariableDeclarationsParentIsTheTryStmt() { + variableDeclarationExprList.forEach(expr -> assertThat(expr.getParentNode().get(), is(tryStmt))); + } + + @Then("the TryStmt has no child nodes") + public void thenTheTryStmtHasNotChildNodes() { + assertThat(tryStmt.getChildNodes().size(), is(0)); + } + + @Then("method $methodPosition in class $classPosition has the name \"$expectedName\"") + public void thenMethodInClassHasTheName(int methodPosition, int classPosition, String expectedName) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + MethodDeclaration method = getMethodByPositionAndClassPosition(compilationUnit, methodPosition, classPosition); + assertThat(method.getNameAsString(), is(expectedName)); + } + + @Then("method $methodPosition in class $classPosition has $expectedCount parameters") + @Alias("method $methodPosition in class $classPosition has $expectedCount parameter") + public void thenMethodInClassHasArguments(int methodPosition, int classPosition, int expectedCount) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + MethodDeclaration method = getMethodByPositionAndClassPosition(compilationUnit, methodPosition, classPosition); + + assertThat(method.getParameters().size(), is(expectedCount)); + } + + @Then("method $methodPosition in class $classPosition parameter $parameterPosition is type int called \"$expectedName\"") + public void thenMethodInClassParameterIsTypeIntCalled(int methodPosition, int classPosition, int parameterPosition, String expectedName) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + MethodDeclaration method = getMethodByPositionAndClassPosition(compilationUnit, methodPosition, classPosition); + Parameter parameter = method.getParameter(parameterPosition - 1); + assertThat(parameter.getType(), is(intType())); + assertThat(parameter.getNameAsString(), is(expectedName)); + } + + private static class ChangeMethodNameToUpperCaseVisitor extends VoidVisitorAdapter { + @Override + public void visit(MethodDeclaration n, Void arg) { + n.setName(n.getNameAsString().toUpperCase()); + } + } + + private static class AddNewIntParameterCalledValueVisitor extends VoidVisitorAdapter { + @Override + public void visit(MethodDeclaration n, Void arg) { + n.addParameter(intType(), "value"); + } + } +} + diff --git a/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/ParsingSteps.java b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/ParsingSteps.java new file mode 100644 index 0000000..38c059b --- /dev/null +++ b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/ParsingSteps.java @@ -0,0 +1,344 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.steps; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.PackageDeclaration; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.ast.stmt.ExpressionStmt; +import com.github.javaparser.ast.stmt.ReturnStmt; +import com.github.javaparser.ast.stmt.Statement; +import org.jbehave.core.annotations.Given; +import org.jbehave.core.annotations.Then; +import org.jbehave.core.annotations.When; + +import java.util.List; +import java.util.Map; + +import static com.github.javaparser.ParseStart.COMPILATION_UNIT; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.steps.SharedSteps.getMemberByTypeAndPosition; +import static com.github.javaparser.steps.SharedSteps.getMethodByPositionAndClassPosition; +import static java.lang.String.format; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsNull.notNullValue; +import static org.junit.jupiter.api.Assertions.*; + +public class ParsingSteps { + + private Map state; + + public ParsingSteps(Map state) { + this.state = state; + } + + private String sourceUnderTest; + + /* + * Given steps + */ + + @Given("the class:$classSrc") + public void givenTheClass(String classSrc) { + this.sourceUnderTest = classSrc.trim(); + } + + + /* + * When steps + */ + + @When("I take the ArrayCreationExpr") + public void iTakeTheArrayCreationExpr() { + setSelectedNodeFromCompilationUnit(ArrayCreationExpr.class); + } + + @When("I take the PackageDeclaration") + public void iTakeThePackageDeclaration() { + setSelectedNodeFromCompilationUnit(PackageDeclaration.class); + } + + @When("I take the ObjectCreationExpr") + public void iTakeTheObjectCreationExpr() throws ClassNotFoundException { + setSelectedNodeFromCompilationUnit(ObjectCreationExpr.class); + } + + /* + * Then steps + */ + + @Then("constructor $constructorPosition in class $classPosition declaration as a String is \"$expectedString\"") + public void thenTheConstructorDeclarationAsAStringIs(int constructorPosition, int classPosition, String expectedString) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + ClassOrInterfaceDeclaration clazz = (ClassOrInterfaceDeclaration) compilationUnit.getType(classPosition - 1); + ConstructorDeclaration constructor = (ConstructorDeclaration) clazz.getMember(constructorPosition - 1); + assertThat(constructor.getDeclarationAsString(), is(expectedString)); + } + + @Then("constructor $constructorPosition in class $classPosition declaration short form as a String is \"$expectedString\"") + public void thenConstructorInClassDeclarationShortFormAsAStringIs(int constructorPosition, int classPosition, String expectedString) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + ClassOrInterfaceDeclaration clazz = (ClassOrInterfaceDeclaration) compilationUnit.getType(classPosition - 1); + ConstructorDeclaration constructor = (ConstructorDeclaration) clazz.getMember(constructorPosition - 1); + assertThat(constructor.getDeclarationAsString(false, false), is(expectedString)); + } + + @Then("method $methodPosition in class $classPosition declaration as a String is \"$expectedString\"") + public void thenMethod1InClass1DeclarationAsAStringIs(int methodPosition, int classPosition, String expectedString) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + ClassOrInterfaceDeclaration clazz = (ClassOrInterfaceDeclaration) compilationUnit.getType(classPosition - 1); + MethodDeclaration method = (MethodDeclaration) clazz.getMember(methodPosition - 1); + assertThat(method.getDeclarationAsString(), is(expectedString)); + } + + @Then("method $methodPosition in class $classPosition declaration as a String short form is \"$expectedString\"") + public void thenMethodInClassDeclarationAsAStringShortFormIs(int methodPosition, int classPosition, String expectedString) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + ClassOrInterfaceDeclaration clazz = (ClassOrInterfaceDeclaration) compilationUnit.getType(classPosition - 1); + MethodDeclaration method = (MethodDeclaration) clazz.getMember(methodPosition - 1); + assertThat(method.getDeclarationAsString(false, false), is(expectedString)); + } + + @Then("field $fieldPosition in class $classPosition contains annotation $annotationPosition value is \"$expectedValue\"") + public void thenFieldInClassContainsAnnotationValueIs(int fieldPosition, int classPosition, int annotationPosition, String expectedValue) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + + TypeDeclaration classUnderTest = compilationUnit.getType(classPosition - 1); + FieldDeclaration fieldUnderTest = getMemberByTypeAndPosition(classUnderTest, fieldPosition - 1, + FieldDeclaration.class); + AnnotationExpr annotationUnderTest = fieldUnderTest.getAnnotation(annotationPosition - 1); + assertThat(annotationUnderTest.getChildNodes().get(1).toString(), is(expectedValue)); + } + + @Then("lambda in statement $statementPosition in method $methodPosition in class $classPosition is called $expectedName") + public void thenLambdaInClassIsCalled(int statementPosition, int methodPosition, int classPosition, String expectedName) { + Statement statement = getStatementInMethodInClass(statementPosition, methodPosition, classPosition); + VariableDeclarationExpr expression = (VariableDeclarationExpr) ((ExpressionStmt) statement).getExpression(); + VariableDeclarator variableDeclarator = expression.getVariable(0); + assertThat(variableDeclarator.getNameAsString(), is(expectedName)); + } + + @Then("lambda in statement $statementPosition in method $methodPosition in class $classPosition body is \"$expectedBody\"") + public void thenLambdaInStatementInMethodInClassBody(int statementPosition, int methodPosition, int classPosition, + String expectedBody) { + LambdaExpr lambdaExpr = getLambdaExprInStatementInMethodInClass(statementPosition, methodPosition, classPosition); + assertThat(lambdaExpr.getBody().toString(), is(expectedBody)); + } + + @Then("lambda in method call in statement $statementPosition in method $methodPosition in class $classPosition body is \"$expectedBody\"") + public void thenLambdaInMethodCallInStatementInMethodInClassBody(int statementPosition, int methodPosition, int classPosition, + String expectedBody) { + ExpressionStmt statement = getStatementInMethodInClass(statementPosition, methodPosition, classPosition).asExpressionStmt(); + VariableDeclarationExpr variableDeclarationExpr = statement.getExpression().asVariableDeclarationExpr(); + VariableDeclarator variableDeclarator = variableDeclarationExpr.getVariable(0); + MethodCallExpr methodCallExpr = (MethodCallExpr) variableDeclarator.getInitializer().orElse(null); + CastExpr castExpr = methodCallExpr.getArgument(0).asCastExpr(); + LambdaExpr lambdaExpr = castExpr.getExpression().asLambdaExpr(); + assertThat(lambdaExpr.getBody().toString(), is(expectedBody)); + } + + @Then("lambda in statement $statementPosition in method $methodPosition in class $classPosition block statement is null") + public void thenLambdaInStatementInMethodInClassBlockStatementIsNull(int statementPosition, int methodPosition, int classPosition) { + LambdaExpr lambdaExpr = getLambdaExprInStatementInMethodInClass(statementPosition, methodPosition, classPosition); + BlockStmt blockStmt = lambdaExpr.getBody().asBlockStmt(); + assertEquals(true, blockStmt.getStatements().isEmpty()); + } + + @Then("lambda in statement $statementPosition in method $methodPosition in class $classPosition has parameters with non-null type") + public void thenLambdaInStatementInMethodInClassHasParametersWithNonNullType(int statementPosition, int methodPosition, int classPosition) { + LambdaExpr lambdaExpr = getLambdaExprInStatementInMethodInClass(statementPosition, methodPosition, classPosition); + for (Parameter parameter : lambdaExpr.getParameters()) { + assertThat(parameter.getType(), is(notNullValue())); + } + } + + @Then("lambda in statement $statementPosition in method $methodPosition in class $classPosition block statement is \"$expectedBody\"") + public void thenLambdaInStatementInMethodInClassBlockStatement(int statementPosition, int methodPosition, int classPosition, + String expectedBody) { + LambdaExpr lambdaExpr = getLambdaExprInStatementInMethodInClass(statementPosition, methodPosition, classPosition); + BlockStmt blockStmt = lambdaExpr.getBody().asBlockStmt(); + Statement lambdaStmt = blockStmt.getStatement(0); + assertThat(lambdaStmt.toString(), is(expectedBody)); + } + + @Then("lambda in statement $statementPosition in method $methodPosition in class $classPosition is parent of contained body") + public void thenLambdaInStatementInMethodInClassIsParentOfContainedBody(int statementPosition, int methodPosition, int classPosition) { + LambdaExpr lambdaExpr = getLambdaExprInStatementInMethodInClass(statementPosition, methodPosition, classPosition); + Statement body = lambdaExpr.getBody(); + assertThat(body.getParentNode().get(), is(lambdaExpr)); + } + + @Then("lambda in statement $statementPosition in method $methodPosition in class $classPosition is parent of contained parameter") + public void thenLambdaInStatementInMethodInClassIsParentOfContainedParameter(int statementPosition, int methodPosition, int classPosition) { + LambdaExpr lambdaExpr = getLambdaExprInStatementInMethodInClass(statementPosition, methodPosition, classPosition); + Parameter parameter = lambdaExpr.getParameter(0); + assertThat(parameter.getParentNode().get(), is(lambdaExpr)); + } + + @Then("method reference in statement $statementPosition in method $methodPosition in class $classPosition scope is $expectedName") + public void thenMethodReferenceInStatementInMethodInClassIsScope(int statementPosition, int methodPosition, + int classPosition, String expectedName) { + ExpressionStmt statementUnderTest = getStatementInMethodInClass(statementPosition, methodPosition, classPosition).asExpressionStmt(); + assertEquals(1, statementUnderTest.findAll(MethodReferenceExpr.class).size()); + MethodReferenceExpr methodReferenceUnderTest = statementUnderTest.findFirst(MethodReferenceExpr.class).get(); + assertThat(methodReferenceUnderTest.getScope().toString(), is(expectedName)); + } + + @Then("method reference in statement $statementPosition in method $methodPosition in class $classPosition identifier is $expectedName") + public void thenMethodReferenceInStatementInMethodInClassIdentifierIsCompareByAge(int statementPosition, int methodPosition, + int classPosition, String expectedName) { + Statement statementUnderTest = getStatementInMethodInClass(statementPosition, methodPosition, classPosition); + assertEquals(1, statementUnderTest.findAll(MethodReferenceExpr.class).size()); + MethodReferenceExpr methodReferenceUnderTest = statementUnderTest.findFirst(MethodReferenceExpr.class).get(); + assertThat(methodReferenceUnderTest.getIdentifier(), is(expectedName)); + } + + @Then("method $methodPosition class $classPosition is a default method") + public void thenMethodClassIsADefaultMethod(int methodPosition, int classPosition) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + MethodDeclaration methodUnderTest = getMethodByPositionAndClassPosition(compilationUnit, + methodPosition, classPosition); + assertThat(methodUnderTest.isDefault(), is(true)); + } + + @Then("method $methodPosition class $classPosition is not a default method") + public void thenMethodClassIsNotADefaultMethod(int methodPosition, int classPosition) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + MethodDeclaration methodUnderTest = getMethodByPositionAndClassPosition(compilationUnit, + methodPosition, classPosition); + assertThat(methodUnderTest.isDefault(), is(false)); + } + + private Statement getStatementInMethodInClass(int statementPosition, int methodPosition, int classPosition) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + MethodDeclaration method = getMethodByPositionAndClassPosition(compilationUnit, methodPosition, classPosition); + return method.getBody().get().getStatement(statementPosition - 1); + } + + private LambdaExpr getLambdaExprInStatementInMethodInClass(int statementPosition, int methodPosition, int classPosition) { + Statement statement = getStatementInMethodInClass(statementPosition, methodPosition, classPosition); + VariableDeclarationExpr expression = ((ExpressionStmt) statement).getExpression().asVariableDeclarationExpr(); + VariableDeclarator variableDeclarator = expression.getVariable(0); + return (LambdaExpr) variableDeclarator.getInitializer().orElse(null); + } + + @Then("all nodes refer to their parent") + public void allNodesReferToTheirParent() { + assertAllNodesOfTheCompilationUnitHaveTheirParentSet("cu1"); + } + + @Then("all nodes of the second compilation unit refer to their parent") + public void thenAllNodesOfTheSecondCompilationUnitReferToTheirParent() { + assertAllNodesOfTheCompilationUnitHaveTheirParentSet("cu2"); + } + + private void assertAllNodesOfTheCompilationUnitHaveTheirParentSet(String stateKey) { + CompilationUnit compilationUnit = (CompilationUnit) state.get(stateKey); + ExistenceOfParentNodeVerifier parentVerifier = new ExistenceOfParentNodeVerifier(); + parentVerifier.verify(compilationUnit); + } + + @Then("ThenExpr in the conditional expression of the statement $statementPosition in method $methodPosition in class $classPosition is LambdaExpr") + public void thenLambdaInConditionalExpressionInMethodInClassIsParentOfContainedParameter(int statementPosition, int methodPosition, int classPosition) { + ReturnStmt returnStmt = getStatementInMethodInClass(statementPosition, methodPosition, classPosition).asReturnStmt(); + ConditionalExpr conditionalExpr = (ConditionalExpr) returnStmt.getExpression().orElse(null); + assertThat(conditionalExpr.getElseExpr().getClass().getName(), is(LambdaExpr.class.getName())); + } + + @Then("the begin line is $line") + public void thenTheBeginLineIs(int line) { + Node node = (Node) state.get("selectedNode"); + assertEquals(line, node.getBegin().get().line); + } + + @Then("the begin column is $column") + public void thenTheBeginColumnIs(int column) { + Node node = (Node) state.get("selectedNode"); + assertEquals(column, node.getBegin().get().column); + } + + @Then("the end line is $line") + public void thenTheEndLineIs(int line) { + Node node = (Node) state.get("selectedNode"); + assertEquals(line, node.getEnd().get().line); + } + + @Then("the end column is $column") + public void thenTheEndColumnIs(int column) { + Node node = (Node) state.get("selectedNode"); + assertEquals(column, node.getEnd().get().column); + } + + @Then("no errors are reported") + public void thenNoErrorsAreReported() { + // this is present just for readability in the scenario specification + // if the code is not parsed then exceptions are thrown before reaching this step + } + + @Then("the package name is $package") + public void thenThePackageNameIs(String expected) { + PackageDeclaration node = (PackageDeclaration) state.get("selectedNode"); + assertEquals(expected, node.getNameAsString()); + assertEquals(expected, node.getName().toString()); + } + + @Then("the type's diamond operator flag should be $expectedValue") + public void thenTheUsesDiamondOperatorShouldBeBooleanAsString(boolean expectedValue) { + ObjectCreationExpr expr = (ObjectCreationExpr) state.get("selectedNode"); + assertEquals(expectedValue, expr.getType().isUsingDiamondOperator()); + } + + @Then("the Java parser cannot parse it because of an error") + public void javaParserCannotParseBecauseOfLexicalErrors() { + ParseResult result = new JavaParser().parse(COMPILATION_UNIT, provider(sourceUnderTest)); + if (result.isSuccessful()) { + fail("Lexical error expected"); + } + } + + @Then("the assignExpr produced doesn't have a null target") + public void thenTheAssignExprProducedDoesntHaveANullTarget() { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + ClassOrInterfaceDeclaration classDeclaration = compilationUnit.getType(0).asClassOrInterfaceDeclaration(); + ConstructorDeclaration ctor = classDeclaration.getMember(1).asConstructorDeclaration(); + ExpressionStmt assignStmt = ctor.getBody().getStatement(0).asExpressionStmt(); + AssignExpr assignExpr = assignStmt.getExpression().asAssignExpr(); + assertNotNull(assignExpr.getTarget()); + assertEquals(NameExpr.class, assignExpr.getTarget().getClass()); + assertEquals(assignExpr.getTarget().asNameExpr().getNameAsString(), "mString"); + } + + private void setSelectedNodeFromCompilationUnit(Class nodeType) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + List nodes = compilationUnit.findAll(nodeType); + if (nodes.size() != 1) { + throw new RuntimeException(format("Exactly one %s expected", nodeType.getSimpleName())); + } + state.put("selectedNode", nodes.get(0)); + } +} diff --git a/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/PositionRangeSteps.java b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/PositionRangeSteps.java new file mode 100644 index 0000000..9ca8969 --- /dev/null +++ b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/PositionRangeSteps.java @@ -0,0 +1,128 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.steps; + +import com.github.javaparser.Position; +import com.github.javaparser.Range; +import org.jbehave.core.annotations.BeforeScenario; +import org.jbehave.core.annotations.Given; +import org.jbehave.core.annotations.Then; +import org.jbehave.core.annotations.When; + +import static com.github.javaparser.Range.range; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class PositionRangeSteps { + + private Position position; + private Position secondPosition; + private Range range; + private Range secondRange; + + @BeforeScenario + public void reset() { + position = null; + secondPosition = null; + range = null; + secondRange = null; + } + /* + * Given steps + */ + + @Given("the position $line, $column") + public void givenThePosition(int line, int column) { + this.position = new Position(line, column); + } + + @Given("the range $line1, $column1 - $line2, $column2") + public void givenTheRange(int line1, int column1, int line2, int column2) { + this.range = range(line1, column1, line2, column2); + } + + /* + * When steps + */ + + @When("I compare to position $line, $column") + public void iCompareToPosition(int line, int column) { + secondPosition = new Position(line, column); + } + + @When("I compare to range $line1, $column1 - $line2, $column2") + public void whenICompareToRange(int line1, int column1, int line2, int column2) { + this.secondRange = range(line1, column1, line2, column2); + } + + /* + * Then steps + */ + + @Then("the positions are equal") + public void thenThePositionsAreEqual() { + assertTrue(position.equals(secondPosition)); + } + + @Then("it is after the {first|} position") + public void thenItIsAfterTheFirstPosition() { + if (secondPosition != null) { + assertTrue(secondPosition.isAfter(position)); + } else { + assertTrue(secondRange.isAfter(position)); + } + } + + @Then("it is before the {first|} position") + public void thenItIsBeforeTheFirstPosition() { + if (secondPosition != null) { + assertTrue(secondPosition.isBefore(position)); + } else { + assertTrue(secondRange.isBefore(position)); + } + } + + @Then("the positions are not equal") + public void thenThePositionsAreNotEqual() { + assertFalse(position.equals(secondPosition)); + } + + @Then("it is not after the {first|} position") + public void thenItIsNotAfterTheFirstPosition() { + assertFalse(secondPosition.isAfter(position)); + } + + @Then("it is not before the {first|} position") + public void thenItIsNotBeforeTheFirstPosition() { + assertFalse(secondPosition.isBefore(position)); + } + + @Then("the ranges are equal") + public void theRangesAreEqual() { + assertTrue(range.equals(secondRange)); + } + + @Then("it is contained in the first range") + public void itIsContainedInTheFirstRange() { + assertTrue(range.contains(secondRange)); + } +} diff --git a/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/PrettyPrintingSteps.java b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/PrettyPrintingSteps.java new file mode 100644 index 0000000..8a536b7 --- /dev/null +++ b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/PrettyPrintingSteps.java @@ -0,0 +1,112 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.steps; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.visitor.ModifierVisitor; +import org.jbehave.core.annotations.Given; +import org.jbehave.core.annotations.Then; +import org.jbehave.core.annotations.When; + +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.net.URISyntaxException; +import java.net.URL; + +import static com.github.javaparser.StaticJavaParser.*; +import static com.github.javaparser.utils.Utils.readerToString; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class PrettyPrintingSteps { + + private Node resultNode; + private String sourceUnderTest; + + @Given("the {class|compilation unit|expression|block|statement|import|annotation|body|class body|interface body}:$classSrc") + public void givenTheClass(String classSrc) { + this.sourceUnderTest = classSrc.trim(); + } + + @Given("the {class|compilation unit|expression|block|statement|import|annotation|body|class body|interface body} in the file \"$classFile\"") + public void givenTheClassInTheFile(String classFile) throws URISyntaxException, IOException { + URL url = getClass().getResource("../samples/" + classFile); + sourceUnderTest = readerToString(new FileReader(new File(url.toURI()))).trim(); + } + + @When("the {class|compilation unit} is parsed by the Java parser") + public void whenTheClassIsParsedByTheJavaParser() { + resultNode = parse(sourceUnderTest); + } + + @When("the expression is parsed by the Java parser") + public void whenTheExpressionIsParsedByTheJavaParser() { + resultNode = parseExpression(sourceUnderTest); + } + + @When("the block is parsed by the Java parser") + public void whenTheBlockIsParsedByTheJavaParser() { + resultNode = parseBlock(sourceUnderTest); + } + + @When("the statement is parsed by the Java parser") + public void whenTheStatementIsParsedByTheJavaParser() { + resultNode = parseStatement(sourceUnderTest); + } + + @When("the import is parsed by the Java parser") + public void whenTheImportIsParsedByTheJavaParser() { + resultNode = parseImport(sourceUnderTest); + } + + @When("the annotation is parsed by the Java parser") + public void whenTheAnnotationIsParsedByTheJavaParser() { + resultNode = parseAnnotation(sourceUnderTest); + } + + @When("the annotation body declaration is parsed by the Java parser") + public void whenTheBodyDeclarationIsParsedByTheJavaParser() { + resultNode = parseAnnotationBodyDeclaration(sourceUnderTest); + } + + @When("the class body declaration is parsed by the Java parser") + public void whenTheClassBodyDeclarationIsParsedByTheJavaParser() { + resultNode = parseBodyDeclaration(sourceUnderTest); + } + + @When("the interface body declaration is parsed by the Java parser") + public void whenTheInterfaceBodyDeclarationIsParsedByTheJavaParser() { + resultNode = parseBodyDeclaration(sourceUnderTest); + } + + @When("the class is visited by an empty ModifierVisitorAdapter") + public void whenTheClassIsVisitedByAnEmptyModifierVisitorAdapter() { + (new ModifierVisitor() { + }).visit((CompilationUnit) resultNode, null); + } + + @Then("it is printed as:$src") + public void isPrintedAs(String src) { + assertEquals(src.trim(), resultNode.toString().trim()); + } +} diff --git a/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/SharedSteps.java b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/SharedSteps.java new file mode 100644 index 0000000..73ae736 --- /dev/null +++ b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/SharedSteps.java @@ -0,0 +1,163 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.steps; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.BodyDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.body.TypeDeclaration; +import org.hamcrest.CoreMatchers; +import org.jbehave.core.annotations.Given; +import org.jbehave.core.annotations.Then; +import org.jbehave.core.annotations.When; + +import java.io.File; +import java.io.IOException; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.Map; + +import static com.github.javaparser.StaticJavaParser.parse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.hamcrest.core.IsNot.not; +import static org.hamcrest.text.IsEqualCompressingWhiteSpace.equalToCompressingWhiteSpace; + +public class SharedSteps { + + /* Map that maintains shares state across step classes. If manipulating the objects in the map you must update the state */ + private Map state; + + public SharedSteps(Map state) { + this.state = state; + } + + /* + * Given steps + */ + + @Given("a CompilationUnit") + public void givenACompilationUnit() { + state.put("cu1", new CompilationUnit()); + } + + @Given("a second CompilationUnit") + public void givenASecondCompilationUnit() { + state.put("cu2", new CompilationUnit()); + } + + /* + * When steps + */ + + @When("the following source is parsed:$classSrc") + public void whenTheFollowingSourceIsParsed(String classSrc) { + state.put("cu1", parse(classSrc.trim())); + } + + @When("the following source is parsed (trimming space):$classSrc") + public void whenTheFollowingSourceIsParsedTrimmingSpace(String classSrc) { + state.put("cu1", parse(classSrc.trim())); + } + + @When("the following sources is parsed by the second CompilationUnit:$classSrc") + public void whenTheFollowingSourcesIsParsedBytTheSecondCompilationUnit(String classSrc) { + state.put("cu2", parse(classSrc.trim())); + } + + @When("file \"$fileName\" is parsed") + public void whenTheJavaFileIsParsed(String fileName) throws IOException, URISyntaxException { + URL url = getClass().getResource("../samples/" + fileName); + CompilationUnit compilationUnit = parse(new File(url.toURI())); + state.put("cu1", compilationUnit); + } + + @Then("the CompilationUnit is equal to the second CompilationUnit") + public void thenTheCompilationUnitIsEqualToTheSecondCompilationUnit() { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + CompilationUnit compilationUnit2 = (CompilationUnit) state.get("cu2"); + + assertThat(compilationUnit, is(equalTo(compilationUnit2))); + } + + @Then("the CompilationUnit has the same hashcode to the second CompilationUnit") + public void thenTheCompilationUnitHasTheSameHashcodeToTheSecondCompilationUnit() { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + CompilationUnit compilationUnit2 = (CompilationUnit) state.get("cu2"); + + assertThat(compilationUnit.hashCode(), is(equalTo(compilationUnit2.hashCode()))); + } + + @Then("the CompilationUnit is not equal to the second CompilationUnit") + public void thenTheCompilationUnitIsNotEqualToTheSecondCompilationUnit() { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + CompilationUnit compilationUnit2 = (CompilationUnit) state.get("cu2"); + + assertThat(compilationUnit, not(equalTo(compilationUnit2))); + } + + @Then("the CompilationUnit has a different hashcode to the second CompilationUnit") + public void thenTheCompilationUnitHasADifferentHashcodeToTheSecondCompilationUnit() { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + CompilationUnit compilationUnit2 = (CompilationUnit) state.get("cu2"); + + assertThat(compilationUnit.hashCode(), not(equalTo(compilationUnit2.hashCode()))); + } + + @Then("the expected source should be:$classSrc") + public void thenTheExpectedSourcesShouldBe(String classSrc) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + assertThat(compilationUnit.toString(), CoreMatchers.is(equalToCompressingWhiteSpace(classSrc))); + } + + public static > T getMemberByTypeAndPosition(TypeDeclaration typeDeclaration, int position, Class typeClass) { + int typeCount = 0; + for (BodyDeclaration declaration : typeDeclaration.getMembers()) { + if (declaration.getClass().equals(typeClass)) { + if (typeCount == position) { + return (T) declaration; + } + typeCount++; + } + } + throw new IllegalArgumentException("No member " + typeClass + " at position: " + position); + } + + public static MethodDeclaration getMethodByPositionAndClassPosition(CompilationUnit compilationUnit, + int methodPosition, int classPosition) { + TypeDeclaration type = compilationUnit.getType(classPosition - 1); + + int memberCount = 0; + int methodCount = 0; + for (BodyDeclaration bodyDeclaration : type.getMembers()) { + if (bodyDeclaration instanceof MethodDeclaration) { + if (methodCount == methodPosition - 1) { + return (MethodDeclaration) type.getMember(memberCount); + } + methodCount++; + } + memberCount++; + } + throw new IllegalArgumentException("Method not found at position " + methodPosition + "in class " + classPosition); + } +} diff --git a/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/VisitorSteps.java b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/VisitorSteps.java new file mode 100644 index 0000000..5894711 --- /dev/null +++ b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/steps/VisitorSteps.java @@ -0,0 +1,171 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.steps; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.Parameter; +import com.github.javaparser.ast.body.VariableDeclarator; +import com.github.javaparser.ast.visitor.CloneVisitor; +import com.github.javaparser.ast.visitor.GenericListVisitorAdapter; +import com.github.javaparser.ast.visitor.GenericVisitorAdapter; +import com.github.javaparser.ast.visitor.VoidVisitorAdapter; +import com.github.javaparser.visitors.PositionTestVisitor; +import org.jbehave.core.annotations.Given; +import org.jbehave.core.annotations.Then; +import org.jbehave.core.annotations.When; + +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +public class VisitorSteps { + + /* Fields used to maintain step state within this step class */ + private VoidVisitorAdapter> toUpperCaseVariableNameVisitor; + private VoidVisitorAdapter> collectVariableNameVisitor; + private PositionTestVisitor positionTestVisitor; + private GenericVisitorAdapter nameReturningVisitor; + private GenericListVisitorAdapter allNameReturningVisitor; + private AtomicReference collectedVariableName; + private String returnedVariableName; + private List returnedVariableNames; + + /* Map that maintains shares state across step classes. If manipulating the objects in the map you must update the state */ + private Map state; + + public VisitorSteps(Map state) { + this.state = state; + } + + @Given("a VoidVisitorAdapter with a visit method that changes variable names to uppercase") + public void givenAVoidVisitorAdapterWithAVisitMethodThatChangesVariableNamesToUppercase() { + toUpperCaseVariableNameVisitor = new VoidVisitorAdapter>() { + @Override + public void visit(VariableDeclarator n, AtomicReference arg) { + n.setName(n.getNameAsString().toUpperCase()); + } + }; + } + + @Given("a VoidVisitorAdapter with a visit method and collects the variable names") + public void givenAVoidVisitorAdapterWithAVisitMethodThatCollectsTheVariableName() { + collectVariableNameVisitor = new VoidVisitorAdapter>() { + @Override + public void visit(VariableDeclarator n, AtomicReference arg) { + arg.set(arg.get() + n.getName() + ";"); + } + + @Override + public void visit(Parameter n, AtomicReference arg) { + arg.set(arg.get() + n.getName() + ";"); + } + }; + } + + @Given("a GenericVisitorAdapter with a visit method that returns variable names") + public void givenAGenericVisitorAdapterWithAVisitMethodThatReturnsVariableNames() { + nameReturningVisitor = new GenericVisitorAdapter() { + @Override + public String visit(VariableDeclarator n, Void arg) { + return n.getNameAsString(); + } + }; + } + + @Given("a GenericListVisitorAdapter with a visit method that returns all variable names") + public void givenAGenericListVisitorAdapterWithAVisitMethodThatReturnsAllVariableNames() { + allNameReturningVisitor = new GenericListVisitorAdapter() { + @Override + public List visit(VariableDeclarator n, Void arg) { + return Collections.singletonList(n.getNameAsString()); + } + }; + } + + @Given("a VoidVisitorAdapter with a visit method that asserts sensible line positions") + public void givenAVoidVisitorAdapterWithAVisitMethodThatAssertsSensibleLinePositions() { + positionTestVisitor = new PositionTestVisitor(); + } + + @When("the CompilationUnit is cloned to the second CompilationUnit") + public void whenTheSecondCompilationUnitIsCloned() { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + CompilationUnit compilationUnit2 = (CompilationUnit) compilationUnit.accept(new CloneVisitor(), null); + state.put("cu2", compilationUnit2); + } + + @When("the CompilationUnit is visited by the to uppercase visitor") + public void whenTheCompilationUnitIsVisitedByTheVistor() { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + toUpperCaseVariableNameVisitor.visit(compilationUnit, null); + state.put("cu1", compilationUnit); + } + + @When("the CompilationUnit is visited by the variable name collector visitor") + public void whenTheCompilationUnitIsVisitedByTheVariableNameCollectorVisitor() { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + collectedVariableName = new AtomicReference<>(""); + collectVariableNameVisitor.visit(compilationUnit, collectedVariableName); + } + + @When("the CompilationUnit is visited by the visitor that returns variable names") + public void whenTheCompilationUnitIsVisitedByTheVisitorThatReturnsVariableNames() { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + returnedVariableName = nameReturningVisitor.visit(compilationUnit, null); + } + + @When("the CompilationUnit is visited by the visitor that returns all variable names") + public void whenTheCompilationUnitIsVisitedByTheVisitorThatReturnsAllVariableNames() { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + returnedVariableNames = allNameReturningVisitor.visit(compilationUnit, null); + } + + @When("the CompilationUnit is visited by the PositionTestVisitor") + public void whenTheCompilationUnitIsVisitedByThePositionTestVisitor() { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + compilationUnit.accept(positionTestVisitor, null); + } + + @Then("the collected variable name is \"$nameUnderTest\"") + public void thenTheCollectedVariableNameIs(String nameUnderTest) { + assertThat(collectedVariableName.get(), is(nameUnderTest)); + } + + @Then("the return variable name is \"$nameUnderTest\"") + public void thenTheReturnVariableNameIs(String nameUnderTest) { + assertThat(returnedVariableName, is(nameUnderTest)); + } + + @Then("the first return variable name is \"$nameUnderTest\"") + public void thenTheFirstReturnVariableNameIs(String nameUnderTest) { + assertThat(returnedVariableNames.get(0), is(nameUnderTest)); + } + + @Then("the total number of nodes visited is $expectedCount") + public void thenTheTotalNumberOfNodesVisitedIs(int expectedCount) { + assertThat(positionTestVisitor.getNumberOfNodesVisited(), is(expectedCount)); + } +} diff --git a/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/visitors/PositionTestVisitor.java b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/visitors/PositionTestVisitor.java new file mode 100644 index 0000000..f365905 --- /dev/null +++ b/javaparser-core-testing-bdd/src/test/java/com/github/javaparser/visitors/PositionTestVisitor.java @@ -0,0 +1,562 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.visitors; + +import com.github.javaparser.Position; +import com.github.javaparser.ast.ArrayCreationLevel; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.PackageDeclaration; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.comments.BlockComment; +import com.github.javaparser.ast.comments.JavadocComment; +import com.github.javaparser.ast.comments.LineComment; +import com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.stmt.*; +import com.github.javaparser.ast.type.*; +import com.github.javaparser.ast.visitor.VoidVisitorAdapter; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.lessThanOrEqualTo; +import static org.hamcrest.core.Is.is; + +public class PositionTestVisitor extends VoidVisitorAdapter { + + private int numberOfNodesVisited; + + @Override + public void visit(final AnnotationDeclaration n, final Object arg) { + doTest(n); + doTest(n.getName()); + super.visit(n, arg); + } + + @Override + public void visit(final AnnotationMemberDeclaration n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final ArrayAccessExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final ArrayCreationExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final ArrayInitializerExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final AssertStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final AssignExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final BinaryExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final BlockComment n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final BlockStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final BooleanLiteralExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final BreakStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final CastExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final CatchClause n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(LambdaExpr n, Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(MethodReferenceExpr n, Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(TypeExpr n, Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final CharLiteralExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final ClassExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final ClassOrInterfaceDeclaration n, final Object arg) { + doTest(n); + doTest(n.getName()); + super.visit(n, arg); + } + + @Override + public void visit(final ClassOrInterfaceType n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final CompilationUnit n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final ConditionalExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final ConstructorDeclaration n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final ContinueStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final DoStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final DoubleLiteralExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final EmptyStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final EnclosedExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final EnumConstantDeclaration n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final EnumDeclaration n, final Object arg) { + doTest(n); + doTest(n.getName()); + super.visit(n, arg); + } + + @Override + public void visit(final ExplicitConstructorInvocationStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final ExpressionStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final FieldAccessExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final FieldDeclaration n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final ForEachStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final ForStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final IfStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final InitializerDeclaration n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final InstanceOfExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final IntegerLiteralExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final JavadocComment n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final LabeledStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final LineComment n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final LongLiteralExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final MarkerAnnotationExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final MemberValuePair n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final MethodCallExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final MethodDeclaration n, final Object arg) { + doTest(n); + doTest(n.getName()); + super.visit(n, arg); + } + + @Override + public void visit(final NameExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final NormalAnnotationExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final NullLiteralExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final ObjectCreationExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final PackageDeclaration n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final Parameter n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final PrimitiveType n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final Name n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(SimpleName n, Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(ArrayType n, Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(ArrayCreationLevel n, Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final IntersectionType n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(UnionType n, Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final ReturnStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final SingleMemberAnnotationExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final StringLiteralExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final SuperExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final SwitchEntry n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final SwitchStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final SynchronizedStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final ThisExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final ThrowStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final TryStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final LocalClassDeclarationStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final LocalRecordDeclarationStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final TypeParameter n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final UnaryExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final VariableDeclarationExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final VariableDeclarator n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final VoidType n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final WhileStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final WildcardType n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(UnknownType n, Object arg) { + doTest(n); + super.visit(n, arg); + } + + private void doTest(final Node node) { + Position begin = node.getRange().get().begin; + Position end = node.getRange().get().end; + assertThat(begin.line, is(greaterThanOrEqualTo(0))); + assertThat(begin.column, is(greaterThanOrEqualTo(0))); + assertThat(end.line, is(greaterThanOrEqualTo(0))); + assertThat(end.column, is(greaterThanOrEqualTo(0))); + + if (begin.line == end.line) { + assertThat(begin.column, is(lessThanOrEqualTo(end.column))); + } else { + assertThat(begin.line, is(lessThanOrEqualTo(end.line))); + } + numberOfNodesVisited++; + } + + public int getNumberOfNodesVisited() { + return numberOfNodesVisited; + } +} 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 new file mode 100644 index 0000000..c3724ce --- /dev/null +++ b/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/comment_attribution_scenarios.story @@ -0,0 +1,498 @@ +Scenario: A Class With Line Comments is processed by the Java Parser + +Given the class: +package japa.parser.comments; + +public class ClassWithLineComments { + + public void aMethod(){ + // first comment + int a=0; // second comment + // third comment + // fourth comment + } +} +When the class is parsed by the Java parser +Then the compilation unit is not commented +Then the compilation unit has 0 orphan comments +Then class 1 has 4 total contained comments +Then method 1 in class 1 has 4 total contained comments +Then method 1 in class 1 has 0 orphan comments +Then block statement in method 1 in class 1 has 4 total contained comments +Then block statement in method 1 in class 1 has 3 orphan comments + + + +Scenario: A Class With Line Comments is processed by the Java Parser + +Given the class: +package japa.parser.comments; + +/**Javadoc associated with the class*/ +public class ClassWithOrphanComments { + //a first comment floating in the class + + //comment associated to the method + void foo(){ + /*comment floating inside the method*/ + } + + //a second comment floating in the class +} + +//Orphan comment inside the CompilationUnit +When the class is parsed by the Java parser +Then the compilation unit is not commented +Then the compilation unit has 6 contained comments +Then the compilation unit orphan comment 1 is "Orphan comment inside the CompilationUnit" +Then class 1 orphan comment 1 is "a first comment floating in the class" +Then class 1 orphan comment 2 is "a second comment floating in the class" +Then class 1 is commented "Javadoc associated with the class" +Then class 1 has 4 total contained comments +Then method 1 in class 1 has 0 orphan comments +Then method 1 in class 1 is commented "comment associated to the method" +Then comment 1 in method 1 in class 1 is "comment floating inside the method" +Then block statement in method 1 in class 1 orphan comment 1 is "comment floating inside the method" + + +Scenario: A Class With Orphan Comment in Class Declaration is parsed by the Java Parser + +Given the class: +class /*Comment1*/ A { + //comment2 + // comment3 + int a; + /**comment4 + * + * */ + //comment5 +} +When the class is parsed by the Java parser +Then class 1 is not commented +Then class 1 orphan comment 1 is "comment2" + + +Scenario: A Class With Line Comments in Multiple Methods is parsed by the Java Parser + +Given the class: +package japa.parser.comments; + +public class ClassWithLineCommentsInMultipleMethods { + + public void aMethod() { + // first comment + int a = 0; //second comment + // third comment + // fourth comment + } + + public void anotherMethod() { + // a unique comment + // first comment + int a = 0; //second comment + // third comment + // fourth comment + } +} +When the class is parsed by the Java parser +Then the compilation unit has 9 contained comments +Then the compilation unit has 0 orphan comments +Then class 1 is not commented +Then class 1 has 9 total contained comments +Then method 1 in class 1 has 4 total contained comments +Then method 1 in class 1 has 0 orphan comments +Then block statement in method 1 in class 1 has 4 total contained comments +Then block statement in method 1 in class 1 has 3 orphan comments +Then method 2 in class 1 has 5 total contained comments +Then method 2 in class 1 has 0 orphan comments +Then block statement in method 2 in class 1 has 5 total contained comments +Then block statement in method 2 in class 1 has 4 orphan comments + + + +Scenario: A Class With Line Comments in Multiple Methods is parsed by the Java Parser + +Given the class: +package japa.parser.comments; + +public class ClassWithLineCommentInsideBlockComment { + + /* comment to a method */ + void foo(){} + + /*// Line Comment put immediately after block comment + + //// Comment debauchery + + another orphan. + It spans over more lines */ +} +When the class is parsed by the Java parser +Then method 1 in class 1 is commented " comment to a method " +Then class 1 orphan comment 1 is "// Line Comment put immediately after block comment + + //// Comment debauchery + + another orphan. + It spans over more lines " + + + +Scenario: A Class With Line Comments on Fields is parsed by the Java Parser + +Given the class: +package japa.parser.comments; + +public class Issue43 { + //Case 1 + private String field1 = null; //field1 + + //Case 2 + private String field2 + = null; //field2 + +} +When the class is parsed by the Java parser +Then the compilation unit has 4 contained comments +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 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" + + +Scenario: Another Class With Line Comments on Fields is parsed by the Java Parser + +Given the class: +package japa.parser.comments; + +public class Issue43variant { + private String field1 = null; //field1 + + private String field2 + = null; //field2 + +} +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 1 in class 1 is commented "field1" +Then variable 1 value of field 2 in class 1 is commented "field2" + + +Scenario: A Class With Mixed Comments on Fields is parsed by the Java Parser + +Given the class: +package japa.parser.javacc; +public class Teste { + //line comment1 + int a = 0; //line comment2 + int b = 0; //line comment3 + int c = 0; /* multi-line + * comment + */ + int d = 0; /** multi-line + * javadoc */ + int e = 0; +} +//final comment +When the class is parsed by the Java parser +Then the compilation unit has 6 contained comments +Then class 1 has 5 total contained comments +Then class 1 orphan comment 1 is "line comment1" +Then field 1 in class 1 is commented "line comment2" +Then field 2 in class 1 is commented "line comment3" +Then field 3 in class 1 is not commented + + + +Scenario: Comment with a preceding line space is an orphan + +Given the class: +//comment + +class A {} +When the class is parsed by the Java parser +Then the compilation unit orphan comment 1 is "comment" + + +Scenario: Comment without a preceding line space is associated to class + +Given the class: +//comment +class A {} +When the class is parsed by the Java parser +Then class 1 is commented "comment" + + +Scenario: Comments after Javadoc are attributed to the method if flag is active + +Given the class: +class Issue40{ + @GET + @Path("original") + /** + * Return the original user. + */ + public User getOriginalUser(String userName) { + return userService.getOriginalUser(userName); + } +} +When the do not consider annotations as node start for code attribution is true on the Java parser +When the class is parsed by the Java parser +Then the compilation unit has 1 contained comments +Then comment 1 in compilation unit is not an orphan +Then method 1 in class 1 is commented "* Return the original user." + + + +Scenario: Comments after Javadoc are attributed to the method if flag is not active + +Given the class: +class Issue40{ + @GET + @Path("original") + /** + * Return the original user. + */ + public User getOriginalUser(String userName) { + return userService.getOriginalUser(userName); + } +} +When the do not consider annotations as node start for code attribution is false on the Java parser +When the class is parsed by the Java parser +Then the compilation unit has 1 contained comments +Then comment 1 in compilation unit is not an orphan +Then type of method 1 in class 1 is commented "* Return the original user." + + +Scenario: A Class With Line Comments is processed by the Java Parser + +Given the class: +/*CompilationUnitComment*/ +package japa.parser.comments; + +public class ClassWithMixedStyleComments { + // line comment + int a = 0; + // another line comment + int b = 0; + // line comment + int c = 0; + /* multi-line + comment + */ + int d = 0; + /** + * multi-line + */ + int e = 0; + // final comment +} +When the class is parsed by the Java parser +Then the compilation is commented "CompilationUnitComment" +Then class 1 is not commented +Then class 1 has 6 total contained comments +Then class 1 orphan comment 1 is " final comment" +Then field 1 in class 1 is commented " line comment" +Then field 1 in class 1 contains 0 comments +Then field 2 in class 1 is commented " another line comment" +Then field 2 in class 1 contains 0 comments +Then field 3 in class 1 is commented " line comment" +Then field 3 in class 1 contains 0 comments +Then field 4 in class 1 is commented " multi-line comment" +Then field 4 in class 1 contains 0 comments +Then field 5 in class 1 is commented " * multi-line" +Then field 5 in class 1 contains 0 comments + + +Scenario: A class with only an orphan comment is processed by the Java Parser + +Given the class: +class A { + // orphan comment" +} +When the class is parsed by the Java parser +Then the compilation unit has 1 contained comments +Then comment 1 in compilation unit is an orphan +Then comment 1 in compilation unit parent is ClassOrInterfaceDeclaration + + + +Scenario: A class with only a class comment is processed by the Java Parser + +Given the class: +/* Comment of the class */ +class A { +} +When the class is parsed by the Java parser +Then the compilation unit has 1 contained comments +Then comment 1 in compilation unit is not an orphan +Then comment 1 in compilation unit commented node is ClassOrInterfaceDeclaration + + + +Scenario: A Class With two comments at class level is processed by the Java Parser + +Given the class: +/* Orphan comment */ +/* Comment of the class */ +class A { +} +When the class is parsed by the Java parser +Then the compilation unit has 2 contained comments +Then comment 1 in compilation unit is an orphan +Then the compilation unit orphan comment 1 is "Orphan comment" +Then comment 2 in compilation unit is not an orphan +Then comment 2 in compilation unit commented node is ClassOrInterfaceDeclaration + + +Scenario: A Class has a comment associated to a field when processed by the Java Parser + +Given the class: +class A { + int a = 0; // comment associated to the field +} +When the class is parsed by the Java parser +Then the compilation unit has 1 contained comments +Then comment 1 in compilation unit is not an orphan +Then comment 1 in compilation unit commented node is FieldDeclaration + + +Scenario: A Class has a comment associated to a the literal when processed by the Java Parser + +Given the class: +class A { + int a + = 0; // comment associated to the field +} +When the class is parsed by the Java parser +Then the compilation unit has 1 contained comments +Then comment 1 in compilation unit is not an orphan +Then comment 1 in compilation unit commented node is IntegerLiteralExpr + + + +Scenario: A Class with two line comment within a method when processed by the Java Parser + +Given the class: +class A { + void foo() { + // a comment + int b; // another comment + } +} +When the class is parsed by the Java parser +Then the compilation unit has 2 contained comments +Then comment 1 in compilation unit is an orphan +Then comment 1 in compilation unit is "a comment" +Then comment 2 in compilation unit is not an orphan +Then comment 2 in compilation unit is "another comment" +Then comment 2 in compilation unit commented node is ExpressionStmt + + +Scenario: A Class with an inline comment inside a block comment is parsed by the Java Parser + +Given the class: +class A { + /* A block comment that + // Contains a line comment + */ + public static void main(String args[]) { + } +} +When the class is parsed by the Java parser +Then the compilation unit has 1 contained comments +Then comment 1 in compilation unit is "A block comment that // Contains a line comment" + + +Scenario: A Class with an inline comment inbetween annotation a method declaration is parsed Java Parser + +Given the class: +class A { + @Override + // Returns number of vowels in a name + public int countVowels(String name) { + } +} +When the class is parsed by the Java parser +Then the compilation unit has 1 contained comments +Then comment 1 in compilation unit commented node is PrimitiveType + +Scenario: We print correctly two consecutive line-comments in a class + +Given the class: +class A { + // foo + // bar + void aMethod(){} +} +When the class is parsed by the Java parser +Then it is printed as: +class A { + + // foo + // bar + void aMethod() { + } +} + +Scenario: We print correctly two consecutive line-comments in a method + +Given the class: +class A { + void aMethod(){ + // foo + // bar + int a; + } +} +When the class is parsed by the Java parser +Then it is printed as: +class A { + + void aMethod() { + // foo + // bar + int a; + } +} + +Scenario: We print correctly orphan comments in a for loop +Given the class: +class A { + public static List calcularResultadoFinal(List avaliacoes) throws SQLException, ClassNotFoundException{ + for(Avaliacao avaliacao: avaliacoes){ + // if(avaliacao.obterAprovacao()){ + // avaliacao.setResultadoFinal("Aprovado"); + // }else{ + // avaliacao.setResultadoFinal("Reprovado"); + // } + avaliacao.setEmAberto(false); + avaliacao.editar(); + } + return avaliacoes; + } +} +When the class is parsed by the Java parser +Then it is printed as: +class A { + + public static List calcularResultadoFinal(List avaliacoes) throws SQLException, ClassNotFoundException { + for (Avaliacao avaliacao : avaliacoes) { + // if(avaliacao.obterAprovacao()){ + // avaliacao.setResultadoFinal("Aprovado"); + // }else{ + // avaliacao.setResultadoFinal("Reprovado"); + // } + avaliacao.setEmAberto(false); + avaliacao.editar(); + } + return avaliacoes; + } +} diff --git a/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/comment_parsing_scenarios.story b/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/comment_parsing_scenarios.story new file mode 100644 index 0000000..bfcd5ed --- /dev/null +++ b/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/comment_parsing_scenarios.story @@ -0,0 +1,281 @@ +Scenario: A Class With Line Comments is processed by the Comments Parser + +Given the class: +package japa.parser.comments; + +public class ClassWithLineComments { + + public void aMethod(){ + // first comment + int a=0; // second comment + // third comment + // fourth comment + } +} +When the class is parsed by the comment parser +Then the total number of comments is 4 +Then line comment 1 is " first comment" +Then line comment 2 is " second comment" +Then line comment 3 is " third comment" +Then line comment 4 is " fourth comment" +Then the line comments have the following positions: +|beginLine|beginColumn|endLine|endColumn| +|6|9|6|24| +|7|18|7|34| +|8|9|8|24| +|9|9|9|25| + +Scenario: A Class With Block Comments is processed by the Comments Parser + +Given the class: +package japa.parser.comments; + +/* comment which is not attributed to the class, it floats around as an orphan */ +/* comment to a class */ +public class ClassWithBlockComments { + + /* comment to a method */ + void foo(){}; + + /* comment put randomly in class: + + another orphan. + It spans over more lines */ + +} + +/* a comment lost inside a compilation unit. It is orphan, I am sure you got this one */ +When the class is parsed by the comment parser +Then the total number of comments is 5 +Then block comment 1 is " comment which is not attributed to the class, it floats around as an orphan " +Then block comment 2 is " comment to a class " +Then block comment 3 is " comment to a method " +Then block comment 4 is " comment put randomly in class: another orphan. It spans over more lines " +Then block comment 5 is " a comment lost inside a compilation unit. It is orphan, I am sure you got this one " +Then the block comments have the following positions: +|beginLine|beginColumn|endLine|endColumn| +|3|1|3|81| +|4|1|4|24| +|7|5|7|29| +|10|5|13|31| +|17|1|17|88| + + +Scenario: A Class With Javadoc Comments is processed by the Comments Parser + +Given the class: +package japa.parser.comments; + +/** a proper javadoc comment */ +public class ClassWithJavadocComments { + + void foo(){}; + + +} +/** a floating javadoc comment */ +When the class is parsed by the comment parser +Then the total number of comments is 2 +Then Javadoc comment 1 is " a proper javadoc comment " +Then Javadoc comment 2 is " a floating javadoc comment " +Then the Javadoc comments have the following positions: +|beginLine|beginColumn|endLine|endColumn| +|3|1|3|31| +|10|1|10|33| + + + +Scenario: A Class With Orphan Comments is processed by the Comments Parser + +Given the class: +package japa.parser.comments; + +/**Javadoc associated with the class*/ +public class ClassWithOrphanComments { + //a first comment floating in the class + + //comment associated to the method + void foo(){ + /*comment floating inside the method*/ + } + + //a second comment floating in the class +} + +//Orphan comment inside the CompilationUnit +When the class is parsed by the comment parser +Then the total number of comments is 6 +Then line comment 1 is "a first comment floating in the class" +Then line comment 2 is "comment associated to the method" +Then line comment 3 is "a second comment floating in the class" +Then block comment 1 is "comment floating inside the method" +Then Javadoc comment 1 is "Javadoc associated with the class" + + +Scenario: A Class With Orphan Comments is processed by the Comments Parser + +Given the class: +/*CompilationUnitComment*/ +package japa.parser.comments; + +public class ClassWithMixedStyleComments { + // line comment + int a = 0; + // another line comment + int b = 0; + // line comment + int c = 0; + /* multi-line + comment + */ + int d = 0; + /** + * multi-line + */ + int e = 0; + // final comment +} +When the class is parsed by the comment parser +Then the total number of comments is 7 +Then the line comments have the following positions: +|beginLine|beginColumn|endLine|endColumn| +|5|5|5|19| +|7|5|7|27| +|9|5|9|19| +|19|5|19|20| +Then the block comments have the following positions: +|beginLine|beginColumn|endLine|endColumn| +|1|1|1|26| +|11|5|13|6| +Then the Javadoc comments have the following positions: +|beginLine|beginColumn|endLine|endColumn| +|15|5|17|7| + +Scenario: A method containing two consecutive line comments is parsed correctly + +Given the class: +class A { + void aMethod(){ + // foo + // bar + int a; + } +} +When the class is parsed by the comment parser +Then the total number of comments is 2 +Then line comment 1 is " foo" +Then line comment 2 is " bar" + +Scenario: Comments from a file with an non-UTF-8 encoding are parsed correctly + +When read sample "ClassInLatin1" using encoding "ISO-8859-1" +Then the total number of comments is 3 +Then line comment 2 is " A l'émej in piasì che sent dësgust." + +Scenario: Should not recognize /*/ as a comment + +Given the class: +/*/ +class Foo {} +When the class is parsed by the comment parser +Then the total number of comments is 0 + +Given the class: +/*/ +class Foo {} +Then the Java parser cannot parse it because of an error + +Scenario: Should recognize /*/ inside a block comment + +Given the class: +/* Foo /*/ +When the class is parsed by the comment parser +Then the total number of comments is 1 +Then block comment 1 is " Foo /" + +Scenario: A Class With Character Literal is processed by the Comments Parser +Given the class: +class A { + /** comment1 */ + private char c = '"'; + /** comment2 */ + private String d; +} +When the class is parsed by the comment parser +Then the total number of comments is 2 +Then Javadoc comment 1 is "comment1" +Then Javadoc comment 2 is "comment2" + +Scenario: Double slash in string does not mess up comments parsing +Given the class: +public class b { + + public void m1() { + String s = "\\"; + } + + /** + * Comment + */ + public void m2() { + return; + } +} +When the class is parsed by the comment parser +Then the total number of comments is 1 + +Scenario: Triple slash in string does not mess up comments parsing +Given the class: +public class b { + + public void m1() { + String s = "\\\" // still in string"; + } + + /** + * Comment + */ + public void m2() { + return; + } +} +When the class is parsed by the comment parser +Then the total number of comments is 1 + +Scenario: Four slashes in string does not mess up comments parsing +Given the class: +public class b { + + public void m1() { + String s = "\\\\" // out of the string"; + ; + } + + /** + * Comment + */ + public void m2() { + return; + } +} +When the class is parsed by the comment parser +Then the total number of comments is 2 + +Scenario: Five slashes in string does not mess up comments parsing +Given the class: +public class b { + + public void m1() { + String s = "\\\\\" // still in string"; + ; + } + + /** + * Comment + */ + public void m2() { + return; + } +} +When the class is parsed by the comment parser +Then the total number of comments is 1 diff --git a/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/comparing_scenarios.story b/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/comparing_scenarios.story new file mode 100644 index 0000000..fea7785 --- /dev/null +++ b/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/comparing_scenarios.story @@ -0,0 +1,19 @@ +Scenario: Compare CUs containing lambdas should not crash awfully + +Given the first class: +public class ArrayListGenericDemo { + + public static void main(String[] args) { + ArrayList data = new ArrayList(); + data.forEach( s -> System.out.println(s)); + } +} +Given the second class: +public class ArrayListGenericDemo { + + public static void main(String[] args) { + ArrayList data = new ArrayList(); + data.forEach( s -> System.out.println(s)); + } +} +Then they are equals diff --git a/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/manipulation_scenarios.story b/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/manipulation_scenarios.story new file mode 100644 index 0000000..ea28279 --- /dev/null +++ b/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/manipulation_scenarios.story @@ -0,0 +1,137 @@ +Scenario: A Node can only ever be equal to a class that extends Node + +Given a CompilationUnit +Then is not equal to null +Then is not equal to "Some String Value" + + +Scenario: A BlockStmt can be created by a provided String + +Given a BlockStmt +When is the String "{return x+y;}" is parsed by the JavaParser using parseBlock +Then Statement 1 in BlockStmt toString is "return x + y;" + + +Scenario: A Statement can be created by a provided String + +Given a Statement +When is the String "x = x+y;" is parsed by the JavaParser using parseStatement +Then Statement toString is "x = x + y;" + + +Scenario: Adding declarations to a TryStmt it is set as the parent of all provided declarations + +Given a TryStmt +Given a List of VariableDeclarations +When the List of VariableDeclarations are set as the resources on TryStmt +Then all the VariableDeclarations parent is the TryStmt + + +Scenario: Creating a complete CompilationUnit + +Given a CompilationUnit +When the package declaration is set to "japa.parser.ast.manipulation" +When a public class called "CreateClass" is added to the CompilationUnit +When a public static method called "main" returning void is added to class 1 in the compilation unit +When String varargs called "args" are added to method 1 in class 1 +When a BlockStmt is added to method 1 in class 1 +When System.out.println("Hello World!"); is added to the body of method 1 in class 1 +Then the expected source should be: +package japa.parser.ast.manipulation; + +public class CreateClass { + + public static void main(String... args) { + System.out.println("Hello World!"); + } +} + + +Scenario: Change the name of a method to be uppercase + +Given a CompilationUnit +When the following source is parsed: +package japa.parser.ast.manipulation; + +public class UpdateMethod { + + public void changeToUpperCase(){} + + public void anotherMethodToChange(){} +} +When method 1 in class 1 has it's name converted to uppercase +Then method 1 in class 1 has the name "CHANGETOUPPERCASE" + + +Scenario: Change the name of all methods to be uppercase using a visitor + +Given a CompilationUnit +When the following source is parsed: +package japa.parser.ast.manipulation; + +public class UpdateMethod { + + public void changeToUpperCase(){} + + public void anotherMethodToChange(){} +} +Given a ChangeNameToUpperCaseVisitor +When the ChangeNameToUpperCaseVisitor visits to compilation unit +Then method 1 in class 1 has the name "CHANGETOUPPERCASE" +Then method 2 in class 1 has the name "ANOTHERMETHODTOCHANGE" + + +Scenario: Add int arguments to a method + +Given a CompilationUnit +When the following source is parsed: +package japa.parser.ast.manipulation; + +public class UpdateMethod { + + public void changeToUpperCase(String parameter){} + + public void anotherMethodToChange(){} +} +When method 2 in class 1 has an int parameter called "value" added +Then method 1 in class 1 has 1 parameters +Then method 2 in class 1 has 1 parameter +Then method 2 in class 1 parameter 1 is type int called "value" + + +Scenario: Add int arguments to all methods using a visitor + +Given a CompilationUnit +When the following source is parsed: +package japa.parser.ast.manipulation; + +public class UpdateMethod { + + public void changeToUpperCase(String parameter){} + + public void anotherMethodToChange(){} +} +Given a AddNewIntParameterCalledValueVisitor +When the AddNewIntParameterCalledValueVisitor visits to compilation unit +Then method 1 in class 1 has 2 parameters +Then method 2 in class 1 has 1 parameter +Then method 1 in class 1 parameter 2 is type int called "value" +Then method 2 in class 1 parameter 1 is type int called "value" + + +Scenario: Clone a compilation unit + +Given a CompilationUnit +When the following source is parsed: +package japa.parser.ast.manipulation; + +public class UpdateMethod { + + public void changeToUpperCase(String parameter){} + + public void anotherMethodToChange(){} +} +When the compilation unit is cloned +Then method 1 in class 1 has the name "changeToUpperCase" +Then method 1 in class 1 has 1 parameters +Then method 2 in class 1 has 0 parameter \ No newline at end of file diff --git a/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/parsing_scenarios.story b/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/parsing_scenarios.story new file mode 100644 index 0000000..9f6ee24 --- /dev/null +++ b/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/parsing_scenarios.story @@ -0,0 +1,500 @@ +Scenario: Test declaration as String for constructor on parsed class + +Given a CompilationUnit +When the following source is parsed: +class ClassWithAConstructor { + protected ClassWithAConstructor(int a, String b) throws This, AndThat, AndWhatElse { + } +} +Then constructor 1 in class 1 declaration as a String is "protected ClassWithAConstructor(int a, String b) throws This, AndThat, AndWhatElse" +Then all nodes refer to their parent + + +Scenario: Test declaration as String exclusing modifiers and throws for constructor on parsed class + +Given a CompilationUnit +When the following source is parsed: +class ClassWithAConstructor { + protected ClassWithAConstructor(int a, String b) throws This, AndThat, AndWhatElse { + } +} +Then constructor 1 in class 1 declaration short form as a String is "ClassWithAConstructor(int a, String b)" +Then all nodes refer to their parent + + +Scenario: Test declaration as String exclusing modifiers and throws for method on parsed class + +Given a CompilationUnit +When the following source is parsed: +class ClassWithAMethod { + /*comment1*/ + final protected /*comment2*/ native List /*comment2*/ aMethod(int a, String b) throws /*comment3*/ This, AndThat, AndWhatElse { + + } +} +Then method 1 in class 1 declaration as a String is "protected final native List aMethod(int a, String b) throws This, AndThat, AndWhatElse" +Then all nodes refer to their parent + + +Scenario: Test declaration as String exclusing modifiers and throws for method on parsed class + +Given a CompilationUnit +When the following source is parsed: +class ClassWithAMethod { + /*comment1*/ + final protected /*comment2*/ native List /*comment2*/ aMethod(int a, String b) throws /*comment3*/ This, AndThat, AndWhatElse { + + } +} +Then method 1 in class 1 declaration as a String short form is "List aMethod(int a, String b)" +Then all nodes refer to their parent + + +Scenario: The same class source is parsed by two different compilation units and should therefore be equal + +Given a CompilationUnit +Given a second CompilationUnit +When the following source is parsed: +package japa.parser.comments; +public class ClassEquality { + + public void aMethod(){ + // first comment + int a=0; // second comment + } +} +When the following sources is parsed by the second CompilationUnit: +package japa.parser.comments; +public class ClassEquality { + + public void aMethod(){ + // first comment + int a=0; // second comment + } +} +Then the CompilationUnit is equal to the second CompilationUnit +Then the CompilationUnit has the same hashcode to the second CompilationUnit +Then all nodes refer to their parent +Then all nodes of the second compilation unit refer to their parent + + +Scenario: Two different class sources are parsed by two different compilation units and should not be equal + +Given a CompilationUnit +Given a second CompilationUnit +When the following source is parsed: +package japa.parser.comments; +public class ClassEquality { + + public void aMethod(){ + // first comment + int a=0; // second comment + } +} +When the following sources is parsed by the second CompilationUnit: +package japa.parser.comments; +public class DifferentClass { + + public void aMethod(){ + // first comment + int a=0; // second comment + } +} +Then the CompilationUnit is not equal to the second CompilationUnit +Then the CompilationUnit has a different hashcode to the second CompilationUnit +Then all nodes refer to their parent +Then all nodes of the second compilation unit refer to their parent + + +Scenario: Classes that only differ by comments should not be equal or have the same hashcode + +Given a CompilationUnit +Given a second CompilationUnit +When the following source is parsed: +package japa.parser.comments; +public class ClassEquality { + + public void aMethod(){ + // first comment + int a=0; // second comment + } +} +When the following sources is parsed by the second CompilationUnit: +package japa.parser.comments; +public class ClassEquality { + + public void aMethod(){ + // first comment + int a=0; + } +} +Then the CompilationUnit is not equal to the second CompilationUnit +Then the CompilationUnit has a different hashcode to the second CompilationUnit +Then all nodes refer to their parent +Then all nodes of the second compilation unit refer to their parent + + +Scenario: A class with a colon in the annoation value is parsed by the Java Parser + +Given a CompilationUnit +When the following source is parsed: +package japa.parser.ast; +import org.junit.Test; +public class Issue37 { + public static @interface SomeAnnotation { + String value(); + } + // Parser bug: the type of this field + @SomeAnnotation("http://someURL.org/") + protected Test test; +} +Then field 1 in class 1 contains annotation 1 value is ""http://someURL.org/"" +Then all nodes refer to their parent + + +Scenario: A class with a Lambda is parsed by the Java Parser + +Given a CompilationUnit +When the following source is parsed: +package bdd.samples; +import java.util.stream.Stream; +public class Lambdas { + + public static void main(String[] args) { + // Lambda Runnable + Runnable r1 = () -> System.out.println("Hello world!"); + Runnable r2 = () -> {}; + Runnable r3 = () -> { System.out.println("Hello world two!"); }; + + Stream stream = Stream.generate((Supplier) () -> "foo"); + } +} +Then lambda in statement 1 in method 1 in class 1 is called r1 +Then lambda in statement 2 in method 1 in class 1 is called r2 +Then lambda in statement 3 in method 1 in class 1 is called r3 +Then lambda in statement 1 in method 1 in class 1 body is "System.out.println("Hello world!");" +Then lambda in statement 2 in method 1 in class 1 block statement is null +Then lambda in statement 3 in method 1 in class 1 block statement is "System.out.println("Hello world two!");" +Then lambda in statement 1 in method 1 in class 1 is parent of contained body +Then lambda in statement 3 in method 1 in class 1 is parent of contained body +Then all nodes refer to their parent +Then lambda in method call in statement 4 in method 1 in class 1 body is ""foo";" + + +Scenario: A class with parameterized Lambdas is parsed by the Java Parser + +Given a CompilationUnit +When the following source is parsed: +package com.github.javapasrser.bdd.parsing; +import java.util.function.Function; +public class ParameterizedLambdas { + public static void main(String[] args) { + Function f1 = (Integer i) -> String.valueOf(i); + Function f2 = (i) -> String.valueOf(i); + Function f3 = i -> String.valueOf(i); + } +} +Then lambda in statement 1 in method 1 in class 1 is parent of contained parameter +Then lambda in statement 2 in method 1 in class 1 is parent of contained parameter +Then lambda in statement 3 in method 1 in class 1 is parent of contained parameter +Then lambda in statement 1 in method 1 in class 1 is parent of contained body +Then lambda in statement 2 in method 1 in class 1 is parent of contained body +Then lambda in statement 3 in method 1 in class 1 is parent of contained body +Then lambda in statement 1 in method 1 in class 1 has parameters with non-null type +Then lambda in statement 2 in method 1 in class 1 has parameters with non-null type +Then lambda in statement 3 in method 1 in class 1 has parameters with non-null type + + +Scenario: A class with multi-parameters Lambdas is parsed by the Java Parser + +Given a CompilationUnit +When the following source is parsed: +package com.github.javapasrser.bdd.parsing; +import java.util.function.Function; +public class MultiParameterizedLambdas { + public static void main(String[] args) { + BiFunction f = (a, b) -> String.valueOf(a) + String.valueOf(b); + } +} +Then lambda in statement 1 in method 1 in class 1 has parameters with non-null type + + +Scenario: A class with a method reference is parsed by the Java Parser + +Given a CompilationUnit +When the following source is parsed: +public class Person { + + String name; + LocalDate birthday; + + public void sortByAge(Person[] people){ + Arrays.sort(people, Person::compareByAge); + } + + public static int compareByAge(Person a, Person b) { + return a.birthday.compareTo(b.birthday); + } +} +Then method reference in statement 1 in method 1 in class 1 scope is Person +Then method reference in statement 1 in method 1 in class 1 identifier is compareByAge +Then all nodes refer to their parent + + +Scenario: An interface with a default method is parsed by the Java Parser + +Given a CompilationUnit +When the following source is parsed: +interface MyInterface { + default String doSomething(){ + return "implementation in an interface!"; + } + + String doSomethingElse(); +} +Then method 1 class 1 is a default method +Then method 2 class 1 is not a default method +Then all nodes refer to their parent + +Scenario: A lambda expression inside a conditional expression is parsed by the Java Parser + +Given a CompilationUnit +When the following source is parsed: +public class A{ + static Predicate isEqual(Object targetRef) { + return (null == targetRef)? Objects::isNull : object -> targetRef.equals(object); + } +} +Then ThenExpr in the conditional expression of the statement 1 in method 1 in class 1 is LambdaExpr + +Scenario: Parsing array creation expressions the positions are correct + +Given a CompilationUnit +When the following source is parsed (trimming space): +public class A{ + int[][] a = new int[][]{}; +} +When I take the ArrayCreationExpr +Then the begin line is 2 +Then the begin column is 17 +Then the end line is 2 +Then the end column is 29 + +Scenario: simple cast on lambda expression can be parsed + +Given a CompilationUnit +When the following source is parsed: +class A { + static final Comparator DATE_ORDER = + (Comparator) (date1, date2) -> { + return Long.compare(date1.toEpochDay(), date2.toEpochDay()); + }; +} +Then all nodes refer to their parent + + +Scenario: a combined cast on lambda expression can be parsed + +Given a CompilationUnit +When the following source is parsed: +class A { + static final Comparator DATE_ORDER = + (Comparator & Serializable) (date1, date2) -> { + return Long.compare(date1.toEpochDay(), date2.toEpochDay()); + }; +} +Then all nodes refer to their parent + + +Scenario: a combined cast on a literal can be parsed + +Given a CompilationUnit +When the following source is parsed: +class A { + static int a = (Comparator & Serializable) 1; +} +Then all nodes refer to their parent + + +Scenario: Parsing excess semicolons on CompilationUnit level should work +Given a CompilationUnit +When the following source is parsed: +; +package a; +; +import foo.a; +; +class A { } +; +Then no errors are reported + +Scenario: Parsing excess semicolons in an AnnotationTypeDeclaration should work +Given a CompilationUnit +When the following source is parsed: +@interface A { + ; + ; +} +Then no errors are reported + +Scenario: Classes that are thrown from a method can be annotated + +Given a CompilationUnit +When the following source is parsed: +class A { + void a() throws @Abc X { + } +} +Then no errors are reported + +Scenario: Classes that are thrown from a constructor can be annotated + +Given a CompilationUnit +When the following source is parsed: +class A { + A() throws @Abc X { + } +} +Then no errors are reported + + +Scenario: Parsing trailing semicolons inside the imports area should work + +Given a CompilationUnit +When the following source is parsed: +import foo.a;; +import foo.b; + +class A { +} +Then no errors are reported + + +Scenario: Full package name should be parsed + +Given a CompilationUnit +When the following source is parsed: +package com.github.javaparser.bdd; +class C {} +When I take the PackageDeclaration +Then the package name is com.github.javaparser.bdd + + +Scenario: Strings with unescaped newlines are illegal (issue 211) +Given the class: +class A { + public void helloWorld(String greeting, String name) { + return "hello + world"; + } +} +Then the Java parser cannot parse it because of an error + +Scenario: Chars with unescaped newlines are illegal (issue 211) +Given the class: +class A { + public void helloWorld(String greeting, String name) { + return ' +'; + } +} +Then the Java parser cannot parse it because of an error + +Scenario: Diamond Operator information is exposed + +Given a CompilationUnit +When the following source is parsed: +class A { + List args = new ArrayList<>(); +} +When I take the ObjectCreationExpr +Then the type's diamond operator flag should be true + +Scenario: Diamond Operator can be parsed also with space and comments + +Given a CompilationUnit +When the following source is parsed: +class A { + List args = new ArrayList< /*hello*/ >(); +} +When I take the ObjectCreationExpr +Then the type's diamond operator flag should be true + +Scenario: Type Arguments are not specified + +Given a CompilationUnit +When the following source is parsed: +class A { + List args = new ArrayList(); +} +When I take the ObjectCreationExpr +Then the type's diamond operator flag should be false + +Scenario: Type Arguments are specified + +Given a CompilationUnit +When the following source is parsed: +class A { + Either either = new Either(); +} +When I take the ObjectCreationExpr +Then the type's diamond operator flag should be false + +Scenario: A method reference with type arguments is parsed correctly +Given a CompilationUnit +When the following source is parsed: +class X { + void x() { + a.orElseGet( Stream::>empty ); + } +} +Then no errors are reported + +Scenario: The target of this assignExpr is not null +Given a CompilationUnit +When the following source is parsed: +public class Example { + private String mString; + public Example(String arg) { + mString = arg; + } +} +Then the assignExpr produced doesn't have a null target + +Scenario: Two comments in one line, and a unicode space +Given a CompilationUnit +When the following source is parsed: +public class Example { + Object mAvailablePrimaryConnection; + public Example(String arg) { + ​mAvailablePrimaryConnection = openConnectionLocked(mConfiguration, + true /*primaryConnection*/); // comment + } +} +Then no errors are reported + +Scenario: alternative [] placings +Given a CompilationUnit +When the following source is parsed: +class I{int[]bar(int[]x[])[]{return new int[][]{};}} +Then no errors are reported + +Scenario: try requires resources, a finally or a catch (issue 442) +Given the class: +class A { + public void helloWorld() { + try { + } + } +} +Then the Java parser cannot parse it because of an error + + +Scenario: Partially dimensioned arrays are fine +Given a CompilationUnit +When the following source is parsed: +class X { + int a = new int @A [10] @A [20] @A [] []; + int b = new int @A [] @A []{{1}}; +} +Then no errors are reported diff --git a/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/position_range_scenarios.story b/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/position_range_scenarios.story new file mode 100644 index 0000000..410e456 --- /dev/null +++ b/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/position_range_scenarios.story @@ -0,0 +1,55 @@ +Scenario: a position is equal to another position at the same place +Given the position 10, 10 +When I compare to position 10, 10 +Then the positions are equal +And it is not before the first position +And it is not after the first position + +Scenario: a position is after another position +Given the position 10, 10 +When I compare to position 20, 20 +Then it is after the first position +And the positions are not equal +And it is not before the first position + +Scenario: a position is directly after another position +Given the position 10, 10 +When I compare to position 10, 11 +Then it is after the first position +And the positions are not equal +And it is not before the first position + +Scenario: a position is before another position +Given the position 10, 10 +When I compare to position 5, 5 +Then it is before the first position +And the positions are not equal +And it is not after the first position + +Scenario: a position is directly before another position +Given the position 10, 10 +When I compare to position 10, 9 +Then it is before the first position +And the positions are not equal +And it is not after the first position + +Scenario: a range is equal to another range +Given the range 10, 10 - 20, 20 +When I compare to range 10, 10 - 20, 20 +Then the ranges are equal + +Scenario: a range is before a position +Given the position 20, 21 +When I compare to range 10, 10 - 20, 20 +Then it is before the position + +Scenario: a range is after a position +Given the position 10, 9 +When I compare to range 10, 10 - 20, 20 +Then it is after the position + +Scenario: a range is contained in another range +Given the range 10, 10 - 20, 20 +When I compare to range 11, 11 - 19, 19 +Then it is contained in the first range + diff --git a/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/pretty_printing_java_concepts.story b/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/pretty_printing_java_concepts.story new file mode 100644 index 0000000..ebcf824 --- /dev/null +++ b/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/pretty_printing_java_concepts.story @@ -0,0 +1,400 @@ +Scenario: Check a whole lot of things at once that should be separate tests + +Given the class in the file "JavaConcepts.java" +When the class is parsed by the Java parser +Then it is printed as: +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-bdd/src/test/resources/com/github/javaparser/pretty_printing_scenarios.story b/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/pretty_printing_scenarios.story new file mode 100644 index 0000000..0613443 --- /dev/null +++ b/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/pretty_printing_scenarios.story @@ -0,0 +1,520 @@ +Scenario: When printing the instantiation we should use the right amount of spaces + +Given the class: +public class A { + Object foo = new Object(); +} +When the class is parsed by the Java parser +Then it is printed as: +public class A { + + Object foo = new Object(); +} + + +Scenario: When printing the lambda expression we should use the right indentation + +Given the class: +public class B { + Runnable runnable = ()-> System.out.println("running"); + Consumer consumer = i->{ i+=1; System.out.println(i);}; +} +When the class is parsed by the Java parser +Then it is printed as: +public class B { + + Runnable runnable = () -> System.out.println("running"); + + Consumer consumer = i -> { + i += 1; + System.out.println(i); + }; +} + + +Scenario: Printing orphan comments in empty method +Given the class: +class A { + public void helloWorld(String greeting, String name) { + //sdfsdfsdf + //sdfds + /* + dgfdgfdgfdgfdgfd + */ + } +} +When the class is parsed by the Java parser +Then it is printed as: +class A { + + public void helloWorld(String greeting, String name) { + //sdfsdfsdf + //sdfds + /* + dgfdgfdgfdgfdgfd + */ + } +} + + + +Scenario: Printing orphan comments in empty method (issue 192) +Given the class: +public class StepImplementation { + @Step("A step") + public void contextStep() { + // Foo bar + } +} +When the class is parsed by the Java parser +Then it is printed as: +public class StepImplementation { + + @Step("A step") + public void contextStep() { + // Foo bar + } +} + + +Scenario: Printing orphan comments in for loop (issue 192) +Given the class: +public class StepImplementation { + public void contextStep() { + for (int i = 0; i < 5; i++) { + // foo bar + } + } +} +When the class is parsed by the Java parser +Then it is printed as: +public class StepImplementation { + + public void contextStep() { + for (int i = 0; i < 5; i++) { + // foo bar + } + } +} + + +Scenario: Printing orphan and attributed comments in for loop (issue 192) +Given the class: +public class StepImplementation { +public void contextStep() { + for (int i = 0; i < 5; i++) { + // foo bar + System.out.println(); + // another foo bar + } + } +} +When the class is parsed by the Java parser +Then it is printed as: +public class StepImplementation { + + public void contextStep() { + for (int i = 0; i < 5; i++) { + // foo bar + System.out.println(); + // another foo bar + } + } +} + + +Scenario: An empty Enum is printed correctly +Given the compilation unit: +package test; enum XYZ {} +When the class is parsed by the Java parser +Then it is printed as: +package test; + +enum XYZ { +} + +Scenario: An enum without fields has no () on its members +Given the compilation unit: +package test; enum XYZ {A,B,C} +When the class is parsed by the Java parser +Then it is printed as: +package test; + +enum XYZ { + + A, B, C +} + +Scenario: Strings with escaped newlines are parsed correctly +Given the class: +class A { + public void helloWorld(String greeting, String name) { + return "hello\nworld"; + } +} +When the class is parsed by the Java parser +Then it is printed as: +class A { + + public void helloWorld(String greeting, String name) { + return "hello\nworld"; + } +} + +Scenario: A multi-catch is printed correctly +Given the class: +class A { + public void a() { + try { + } catch (IndexOutOfBoundException | IOException e) { + } + } +} +When the class is parsed by the Java parser +Then it is printed as: +class A { + + public void a() { + try { + } catch (IndexOutOfBoundException | IOException e) { + } + } +} + +Scenario: An empty import does not fail +Given the class: +package a.b.c; + +; +When the class is parsed by the Java parser +Then it is printed as: +package a.b.c; + +Scenario: we can parse blocks +Given the block: +{ + a=2+1; + b=3+1; +} +When the block is parsed by the Java parser +Then it is printed as: +{ + a = 2 + 1; + b = 3 + 1; +} + +Scenario: we can parse statements +Given the statement: +while (true) { +} +When the statement is parsed by the Java parser +Then it is printed as: +while (true) { +} + +Scenario: we can parse static on demand imports +Given the import: +import static a.b.c.Abc.*; +When the import is parsed by the Java parser +Then it is printed as: +import static a.b.c.Abc.*; + +Scenario: we can parse static type imports +Given the import: +import static a.b.c.Abc; +When the import is parsed by the Java parser +Then it is printed as: +import static a.b.c.Abc; + +Scenario: we can parse on demand imports +Given the import: +import a.b.c.*; +When the import is parsed by the Java parser +Then it is printed as: +import a.b.c.*; + +Scenario: we can parse type imports +Given the import: +import a.b.c.Abc; +When the import is parsed by the Java parser +Then it is printed as: +import a.b.c.Abc; + +Scenario: we can parse annotations +Given the annotation: +@Abc +When the annotation is parsed by the Java parser +Then it is printed as: +@Abc + +Scenario: we can parse body declarations +Given the body: +String author(); +When the annotation body declaration is parsed by the Java parser +Then it is printed as: +String author(); + +Scenario: we can parse class body declarations +Given the body: +public int xyz() {} +When the class body declaration is parsed by the Java parser +Then it is printed as: +public int xyz() { +} + +Scenario: we can parse interface body declarations +Given the body: +int xyz(); +When the interface body declaration is parsed by the Java parser +Then it is printed as: +int xyz(); + +Scenario: It doesn't throw NPE when using a modifierVisitorAdapter +Given the class: +public class Example { + private String mString; + public Example(String arg) { + mString = arg; + } +} +When the class is parsed by the Java parser +When the class is visited by an empty ModifierVisitorAdapter +Then it is printed as: +public class Example { + + private String mString; + + public Example(String arg) { + mString = arg; + } +} + +Scenario: JavaDoc OR comment is printed, not both. +Given the class: +public class Foo { + /** This line gets duplicated */ + public void foo() { + } +} +When the class is parsed by the Java parser +Then it is printed as: +public class Foo { + + /** + * This line gets duplicated + */ + public void foo() { + } +} + +Scenario: various lamba casts (issue 418) +Given the class: +public class TestLambda { + void okMethod() { + return (ITF) () -> { + return true; + }; + } + void faliingMethod() { + testThis(check ? null : (ITF) () -> { + return true; + }); + } +} +When the class body declaration is parsed by the Java parser +Then it is printed as: +public class TestLambda { + + void okMethod() { + return (ITF) () -> { + return true; + }; + } + + void faliingMethod() { + testThis(check ? null : (ITF) () -> { + return true; + }); + } +} + +Scenario: Duplicate methods are not a parsing error (#416) +Given the class: +public class Foo { + public void foo() { + } + public void foo() { + } + public void foo() { + } +} +When the class is parsed by the Java parser +Then it is printed as: +public class Foo { + + public void foo() { + } + + public void foo() { + } + + public void foo() { + } +} + +Scenario: Both array syntaxes are supported (#416) +Given the class: +public class Foo { + public void m1(boolean[] boolArray) {} + public void m1(boolean boolArray[]) {} + public void m1(boolean[] boolArray[]) {} +} +When the class is parsed by the Java parser +Then it is printed as: +public class Foo { + + public void m1(boolean[] boolArray) { + } + + public void m1(boolean[] boolArray) { + } + + public void m1(boolean[][] boolArray) { + } +} + + +Scenario: Array parts can be annotated +Given the class: +class Foo { + void m1(@Boo boolean @Index1 [] @ Index2 [] boolArray) {} +} +When the class is parsed by the Java parser +Then it is printed as: +class Foo { + + void m1(@Boo boolean @Index1 [] @Index2 [] boolArray) { + } +} + +Scenario: Annotations are supported on annotations +Given the class: +@C @interface D { +} +When the class is parsed by the Java parser +Then it is printed as: +@C +@interface D { +} + +Scenario: Annotations are supported on interfaces +Given the class: +@C interface Abc { +} +When the class is parsed by the Java parser +Then it is printed as: +@C +interface Abc { +} + +Scenario: Annotations are supported on enums +Given the class: +@C enum Abc { +} +When the class is parsed by the Java parser +Then it is printed as: +@C +enum Abc { +} + +Scenario: Annotations are supported on classes (issue 436 is the commented part) +Given the compilation unit: +@C +public class Abc<@C A, @C X extends @C String & @C Serializable> { + + @C int @C[] @C []f; + + @C + public Abc(@C int p, List<@C ? extends Object> aa){ + @C int b; + } + public @C void a(@C int o) { +/* try { + throw new IOException(); + } catch (@C NullPointerException | @C IOException e) { + } +*/ } +} +When the compilation unit is parsed by the Java parser +Then it is printed as: +@C +public class Abc<@C A, @C X extends @C String & @C Serializable> { + + @C + int @C [] @C [] f; + + @C + public Abc(@C int p, List<@C ? extends Object> aa) { + @C + int b; + } + + @C + public void a(@C int o) { + /* try { + throw new IOException(); + } catch (@C NullPointerException | @C IOException e) { + } +*/ + } +} + + +Scenario: Annotations are supported inside catch (issue 436) +Given the compilation unit: +public class Abc { + public void a() { + try { + } catch (@C NullPointerException | @C IOException e) { + } + } +} +When the compilation unit is parsed by the Java parser +Then it is printed as: +public class Abc { + + public void a() { + try { + } catch (@C NullPointerException | @C IOException e) { + } + } +} + +Scenario: Inner class notation does not confuse annotations (#107) +Given the class: +class A extends @Ann1 B.@Ann2 C { +} +When the class is parsed by the Java parser +Then it is printed as: +class A extends @Ann1 B.@Ann2 C { +} + +Scenario: Make sure interface extends can be annotated +Given the class: +interface A extends @X B, @Y C, @Z D { +} +When the class is parsed by the Java parser +Then it is printed as: +interface A extends @X B, @Y C, @Z D { +} + +Scenario: default modifier isn't printed twice +Given the class: +interface X {default String author(){}} +When the annotation body declaration is parsed by the Java parser +Then it is printed as: +interface X { + + default String author() { + } +} diff --git a/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/samples/ClassInLatin1.java b/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/samples/ClassInLatin1.java new file mode 100644 index 0000000..096c70a --- /dev/null +++ b/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/samples/ClassInLatin1.java @@ -0,0 +1,6 @@ +// Comment in Latin1: +// A l'émej in piasì che sent dësgust. +// For the curios reader, this is Piedmontese dialect +class A { + +} \ No newline at end of file diff --git a/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/samples/JavaConcepts.java b/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/samples/JavaConcepts.java new file mode 100644 index 0000000..8e6dc92 --- /dev/null +++ b/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/samples/JavaConcepts.java @@ -0,0 +1,397 @@ +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-bdd/src/test/resources/com/github/javaparser/samples/package-info.java b/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/samples/package-info.java new file mode 100644 index 0000000..5703eb4 --- /dev/null +++ b/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/samples/package-info.java @@ -0,0 +1,5 @@ +/** + * This package contains class for doing some stuff. + */ +@C +package com.company.stuff; \ No newline at end of file diff --git a/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/visitor_scenarios.story b/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/visitor_scenarios.story new file mode 100644 index 0000000..634a9f2 --- /dev/null +++ b/javaparser-core-testing-bdd/src/test/resources/com/github/javaparser/visitor_scenarios.story @@ -0,0 +1,67 @@ +Scenario: A class that is replicated using a CloneVisitor should be equal to the source + +Given a CompilationUnit +Given a second CompilationUnit +When the following source is parsed: +package japa.parser; +public class ClassEquality { + + public void aMethod(){ + int a=0; // second comment + } +} +When the CompilationUnit is cloned to the second CompilationUnit +Then the CompilationUnit is equal to the second CompilationUnit +Then the CompilationUnit has the same hashcode to the second CompilationUnit + + +Scenario: A classes variable name is changed to uppercase VoidVisitorAdapter + +Given a CompilationUnit +Given a VoidVisitorAdapter with a visit method that changes variable names to uppercase +When the following source is parsed: +package japa.parser; +public class ToUpperClass { + private int zero = 0; +} +When the CompilationUnit is visited by the to uppercase visitor +Then the expected source should be: +package japa.parser; +public class ToUpperClass { + private int ZERO = 0; +} + +Scenario: A class with a try statement is visited using by a VoidVisitorAdapter + +Given a CompilationUnit +Given a VoidVisitorAdapter with a visit method and collects the variable names +When the following source is parsed: +package japa.parser; +public class ToUpperClass { + public void aMethod(){ + try { + int zero = 0; + }catch (Exception exception) { + } + } +} +When the CompilationUnit is visited by the variable name collector visitor +Then the collected variable name is "exception;zero;" + + +Scenario: A class with a try statement is visited using by a GenericVisitorAdapter + +Given a CompilationUnit +Given a GenericVisitorAdapter with a visit method that returns variable names +When the following source is parsed: +package japa.parser; +public class ToUpperClass { + public void aMethod(){ + try { + int zero = 0; + }catch (Exception exception) { + } + } +} +When the CompilationUnit is visited by the visitor that returns variable names +Then the return variable name is "zero" diff --git a/javaparser-core-testing/pom.xml b/javaparser-core-testing/pom.xml new file mode 100644 index 0000000..c3fb0c8 --- /dev/null +++ b/javaparser-core-testing/pom.xml @@ -0,0 +1,143 @@ + + + javaparser-parent + com.github.javaparser + 3.25.10 + + 4.0.0 + + javaparser-core-testing + The test suite for javaparser-core + + + + GNU Lesser General Public License + http://www.gnu.org/licenses/lgpl-3.0.html + repo + + + Apache License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + A business-friendly OSS license + + + + + + org.jacoco + jacoco-maven-plugin + + + jacoco-initialize + + prepare-agent + + + + jacoco-report + test + + report + + + + + + maven-resources-plugin + + + copy-javaparser-core-classes + test-compile + + copy-resources + + + UTF-8 + ${basedir}/target/classes + + + ../javaparser-core/target/classes + false + + + + + + copy-javaparser-core-generated-sources + test-compile + + copy-resources + + + UTF-8 + ${basedir}/target/generated-sources/ + + + ../javaparser-core/target/generated-sources + false + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + true + + + + org.apache.maven.plugins + maven-surefire-plugin + + plain + true + + + + + + + com.github.javaparser + javaparser-core + ${project.version} + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.jupiter + junit-jupiter-params + test + + + org.hamcrest + hamcrest + test + + + org.assertj + assertj-core + 3.25.3 + test + + + com.squareup.okhttp3 + okhttp + 4.12.0 + test + + + org.mockito + mockito-inline + + + + diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/CommentsInserterTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/CommentsInserterTest.java new file mode 100644 index 0000000..f375f9b --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/CommentsInserterTest.java @@ -0,0 +1,113 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.comments.CommentsCollection; +import com.github.javaparser.utils.TestParser; +import org.junit.jupiter.api.Test; + +import java.io.IOException; + +import static com.github.javaparser.utils.TestUtils.assertEqualToTextResourceNoEol; +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 CommentsInserterTest { + private String makeFilename(String sampleName) { + return "com/github/javaparser/issue_samples/" + sampleName + ".java.txt"; + } + + private String makeExpectedFilename(String sampleName) { + return "/com/github/javaparser/issue_samples/" + sampleName + ".java.expected.txt"; + } + + private ParseResult parseSample(String sampleName) throws IOException { + Provider p = Providers.resourceProvider(makeFilename(sampleName)); + return new JavaParser().parse(ParseStart.COMPILATION_UNIT, p); + } + + /** + * Issue: "When there is a String constant "\\" compilationUnit ignores all further comments" + */ + @Test + void issue290() throws IOException { + ParseResult result = this.parseSample("Issue290"); + CommentsCollection cc = result.getCommentsCollection().get(); + assertEquals(1, cc.getLineComments().size()); + assertEquals(1, cc.getJavadocComments().size()); + } + + @Test + void issue624() throws IOException { + this.parseSample("Issue624"); + // Should not fail + } + + @Test + void issue200EnumConstantsWithCommentsForceVerticalAlignment() { + CompilationUnit cu = TestParser.parseCompilationUnit("public enum X {" + SYSTEM_EOL + + " /** const1 javadoc */" + SYSTEM_EOL + + " BORDER_CONSTANT," + SYSTEM_EOL + + " /** const2 javadoc */" + SYSTEM_EOL + + " ANOTHER_CONSTANT" + SYSTEM_EOL + + "}"); + assertEqualsStringIgnoringEol("public enum X {\n" + + "\n" + + " /**\n" + + " * const1 javadoc\n" + + " */\n" + + " BORDER_CONSTANT,\n" + + " /**\n" + + " * const2 javadoc\n" + + " */\n" + + " ANOTHER_CONSTANT\n" + + "}\n", cu.toString()); + } + + @Test + void issue234LosingCommentsInArrayInitializerExpr() { + CompilationUnit cu = TestParser.parseCompilationUnit("@Anno(stuff={" + SYSTEM_EOL + + " // Just," + SYSTEM_EOL + + " // an," + SYSTEM_EOL + + " // example" + SYSTEM_EOL + + "})" + SYSTEM_EOL + + "class ABC {" + SYSTEM_EOL + + "" + SYSTEM_EOL + + "}"); + + assertEqualsStringIgnoringEol("@Anno(stuff = {// Just,\n" + + "// an,\n" + + "// example\n" + + "})\n" + + "class ABC {\n" + + "}\n", cu.toString()); + } + + + @Test + void issue412() throws IOException { + CompilationUnit cu = parseSample("Issue412").getResult().get(); + assertEqualToTextResourceNoEol(makeExpectedFilename("Issue412"), cu.toString()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ExpectedTokensTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ExpectedTokensTest.java new file mode 100644 index 0000000..fd49aa3 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ExpectedTokensTest.java @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.expr.CharLiteralExpr; +import com.github.javaparser.utils.ExtractingVisitors; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static com.github.javaparser.utils.TestUtils.getNodeStartingAtPosition; +import static com.github.javaparser.utils.TestUtils.parseFile; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ExpectedTokensTest { + + @Test + void testCharEscapeSequences() { + CompilationUnit compilationUnit = parseFile("/com/github/javaparser/EscapeSequences.java"); + List chars = ExtractingVisitors.extractCharLiteralExprs(compilationUnit); + assertEquals(23, chars.size()); + + assertTokenValue(chars, 7, 17, "\\\\"); + assertTokenValue(chars, 7, 23, "\\u005C\\u005C"); + assertTokenValue(chars, 7, 39, "\\u005c\\u005c"); + assertTokenValue(chars, 9, 17, "\\n"); + assertTokenValue(chars, 9, 23, "\\u005cn"); + assertTokenValue(chars, 9, 34, "\\u005Cn"); + assertTokenValue(chars, 11, 17, "\\r"); + assertTokenValue(chars, 11, 23, "\\u005cr"); + assertTokenValue(chars, 11, 34, "\\u005Cr"); + assertTokenValue(chars, 13, 17, "\\t"); + assertTokenValue(chars, 13, 23, "\\u005ct"); + assertTokenValue(chars, 13, 34, "\\u005Ct"); + assertTokenValue(chars, 15, 17, "\\b"); + assertTokenValue(chars, 15, 23, "\\u005cb"); + assertTokenValue(chars, 15, 34, "\\u005Cb"); + assertTokenValue(chars, 17, 17, "\\f"); + assertTokenValue(chars, 17, 23, "\\u005cf"); + assertTokenValue(chars, 17, 34, "\\u005Cf"); + assertTokenValue(chars, 19, 17, "\\'"); + assertTokenValue(chars, 19, 23, "\\u005c'"); + assertTokenValue(chars, 21, 17, "\\\""); + assertTokenValue(chars, 21, 23, "\\u005c\""); + assertTokenValue(chars, 21, 34, "\\u005C\""); + } + + private void assertTokenValue(List chars, int line, int col, String expectedTokenValue) { + CharLiteralExpr expr = getNodeStartingAtPosition(chars, line, col); + assertEquals(expectedTokenValue, expr.getValue(), "Node at " + line + "," + col); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/GeneratedJavaParserTokenManagerTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/GeneratedJavaParserTokenManagerTest.java new file mode 100644 index 0000000..2a141cb --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/GeneratedJavaParserTokenManagerTest.java @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; + +import static com.github.javaparser.StaticJavaParser.parseResource; + +class GeneratedJavaParserTokenManagerTest { + private String makeFilename(String sampleName) { + return "com/github/javaparser/issue_samples/" + sampleName + ".java.txt"; + } + + @Test + void issue1003() throws IOException { + parseResource(makeFilename("issue1003")); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/Issue1017Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/Issue1017Test.java new file mode 100644 index 0000000..1224b34 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/Issue1017Test.java @@ -0,0 +1,38 @@ +/* + * Copyright (C) 2013-2024 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; + +import com.github.javaparser.ast.CompilationUnit; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class Issue1017Test { + + @Test() + void test() { + String code = "class X{int x(){ a(1+1 -> 10);}}"; + + Assertions.assertThrows(ParseProblemException.class, () -> { + CompilationUnit cu = StaticJavaParser.parse(code); + }); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/Issue2482Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/Issue2482Test.java new file mode 100644 index 0000000..a174064 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/Issue2482Test.java @@ -0,0 +1,75 @@ +/* + * Copyright (C) 2013-2024 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; + +import com.github.javaparser.ast.expr.LambdaExpr; +import com.github.javaparser.ast.stmt.Statement; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Tests related to https://github.com/javaparser/javaparser/issues/2482. + */ +public class Issue2482Test { + @Test + public void commentBeforeLambda() { + LambdaExpr le = StaticJavaParser.parseExpression( + "// a comment before parent" + System.lineSeparator() + + "()->{return 1;}"); + + assertTrue(le.getComment().isPresent()); + assertTrue(le.getOrphanComments().isEmpty()); + assertEquals(0, le.getAllContainedComments().size()); + } + + @Test + public void commentBeforeBlock() { + Statement st = StaticJavaParser.parseBlock( + "// a comment before parent" + System.lineSeparator() + + "{ if (file != null) {} }"); + assertTrue(st.getComment().isPresent()); + assertTrue(st.getOrphanComments().isEmpty()); + assertEquals(0, st.getAllContainedComments().size()); + } + + @Test + public void commentBeforeIfStatement() { + Statement st = StaticJavaParser.parseStatement( + "// a comment before parent" + System.lineSeparator() + + "if (file != null) {}"); + assertTrue(st.getComment().isPresent()); + assertTrue(st.getOrphanComments().isEmpty()); + assertEquals(0, st.getAllContainedComments().size()); + } + + @Test + public void commentBeforeAssignment() { + Statement st = StaticJavaParser.parseStatement( + "// a comment" + System.lineSeparator() + + "int x = 3;"); + + assertTrue(st.getComment().isPresent()); + assertTrue(st.getOrphanComments().isEmpty()); + assertEquals(0, st.getAllContainedComments().size()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/Issue3064Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/Issue3064Test.java new file mode 100644 index 0000000..3af87b6 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/Issue3064Test.java @@ -0,0 +1,62 @@ +/* + * Copyright (C) 2013-2024 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; + +import com.github.javaparser.ast.CompilationUnit; +import org.junit.jupiter.api.Test; + +import java.io.StringReader; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class Issue3064Test { + + @Test + public void test0() { + String str = "import java.util.function.Supplier;\n" + + "\n" + + "public class MyClass {\n" + + "\n" + + " public MyClass() {\n" + + " Supplier aStringSupplier = false ? () -> \"\" : true ? () -> \"\" : () -> \"path\";\n" + + " }\n" + + "}\n"; + + JavaParser parser = new JavaParser(); + ParseResult unitOpt = parser.parse(new StringReader(str)); + unitOpt.getProblems().stream().forEach(p -> System.err.println(p.toString())); + CompilationUnit unit = unitOpt.getResult().orElseThrow(() -> new IllegalStateException("Could not parse file")); + + assertEquals(str, unit.toString()); + } + + @Test + public void test1() { + String str = "public class MyClass {\n" + + " {\n" + + " Supplier aStringSupplier = false ? () -> \"F\" : true ? () -> \"T\" : () -> \"path\";\n" + + " }\n" + + "}"; + CompilationUnit unit = StaticJavaParser.parse(str); + assertEquals(str.replace("\n", ""), unit.toString().replace("\n", "")); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/Issue3577Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/Issue3577Test.java new file mode 100755 index 0000000..0f231c5 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/Issue3577Test.java @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2013-2024 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; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +import com.github.javaparser.ParserConfiguration.LanguageLevel; + +public class Issue3577Test { + + @Test + public void test() { + String str = "public class MyClass {\n" + + " public static void main(String args[]) {\n" + + " System.out.println(\"Hello\\sWorld\");\n" + + " }\n" + + "}"; + + ParserConfiguration config = new ParserConfiguration().setLanguageLevel(LanguageLevel.JAVA_15); + StaticJavaParser.setConfiguration(config); + + assertDoesNotThrow(() -> StaticJavaParser.parse(str)); +// unitOpt.getProblems().stream().forEach(p -> System.err.println(p.toString())); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/JavaParserAdapterTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/JavaParserAdapterTest.java new file mode 100644 index 0000000..2aabac0 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/JavaParserAdapterTest.java @@ -0,0 +1,287 @@ +/* + * Copyright (C) 2013-2024 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; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.ImportDeclaration; +import com.github.javaparser.ast.PackageDeclaration; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.modules.ModuleDeclaration; +import com.github.javaparser.ast.modules.ModuleDirective; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.ast.stmt.ExplicitConstructorInvocationStmt; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.ast.type.ClassOrInterfaceType; +import com.github.javaparser.ast.type.Type; +import com.github.javaparser.ast.type.TypeParameter; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import java.io.ByteArrayInputStream; +import java.io.CharArrayReader; +import java.io.InputStream; +import java.io.Reader; +import java.nio.charset.StandardCharsets; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; + + +class JavaParserAdapterTest { + + private final JavaParser javaParser = Mockito.spy(JavaParser.class); + + private final JavaParserAdapter adapter = new JavaParserAdapter(javaParser); + + @Test + void of_withValidParser() { + JavaParserAdapter actualAdapter = JavaParserAdapter.of(javaParser); + assertSame(javaParser, actualAdapter.getParser()); + assertSame(javaParser.getParserConfiguration(), adapter.getParserConfiguration()); + } + + @Test + void parse_withSourceCode() { + + CompilationUnit cu = adapter.parse("class A {}"); + + Optional classA = cu.findFirst(ClassOrInterfaceDeclaration.class); + assertTrue(classA.isPresent()); + assertEquals("A", classA.get().getNameAsString()); + + Mockito.verify(javaParser).parse("class A {}"); + } + + @Test + void parse_withInvalidSourceCode() { + assertThrows(ParseProblemException.class, () -> adapter.parse("class A")); + } + + @Test + void parse_withSourceCodeFromInputStream() { + + InputStream is = new ByteArrayInputStream("class A {}".getBytes(StandardCharsets.UTF_8)); + + CompilationUnit cu = adapter.parse(is); + + Optional classA = cu.findFirst(ClassOrInterfaceDeclaration.class); + assertTrue(classA.isPresent()); + assertEquals("A", classA.get().getNameAsString()); + + Mockito.verify(javaParser).parse(is); + } + + @Test + void parse_withSourceCodeFromReader() { + + Reader reader = new CharArrayReader("class A {}".toCharArray()); + + CompilationUnit cu = adapter.parse(reader); + + Optional classA = cu.findFirst(ClassOrInterfaceDeclaration.class); + assertTrue(classA.isPresent()); + assertEquals("A", classA.get().getNameAsString()); + + Mockito.verify(javaParser).parse(reader); + } + + @Test + void parseBlock_withValidSource() { + BlockStmt block = adapter.parseBlock("{ System.out.println(\"Hello world!\"); }"); + + assertEquals(1, block.getStatements().size()); + + Mockito.verify(javaParser).parseBlock("{ System.out.println(\"Hello world!\"); }"); + } + + @Test + void parseStatement_withValidSource() { + Statement statement = adapter.parseStatement("break;"); + + assertTrue(statement.isBreakStmt()); + + Mockito.verify(javaParser).parseStatement("break;"); + } + + @Test + void parseImport_withValidSource() { + ImportDeclaration importDecl = adapter.parseImport("import java.util.Optional;"); + + assertEquals("Optional", importDecl.getName().getIdentifier()); + + Mockito.verify(javaParser).parseImport("import java.util.Optional;"); + } + + @Test + void parseExpression_withValidSource() { + Expression expression = adapter.parseExpression("System.out.println(\"Hello world!\")"); + + assertTrue(expression.isMethodCallExpr()); + + Mockito.verify(javaParser).parseExpression("System.out.println(\"Hello world!\")"); + } + + @Test + void parseAnnotation_withValidSource() { + AnnotationExpr annotation = adapter.parseAnnotation("@Test"); + + assertEquals("Test", annotation.getNameAsString()); + + Mockito.verify(javaParser).parseAnnotation("@Test"); + } + + @Test + void parseAnnotationBodyDeclaration_withValidSource() { + BodyDeclaration annotationBody = adapter.parseAnnotationBodyDeclaration("@interface Test{}"); + + assertTrue(annotationBody.isAnnotationDeclaration()); + + Mockito.verify(javaParser).parseAnnotationBodyDeclaration("@interface Test{}"); + } + + @Test + void parseBodyDeclaration_withValidSource() { + BodyDeclaration interfaceBody = adapter.parseBodyDeclaration("interface CustomInterface {}"); + + assertTrue(interfaceBody.isClassOrInterfaceDeclaration()); + + Mockito.verify(javaParser).parseBodyDeclaration("interface CustomInterface {}"); + } + + @Test + void parseClassOrInterfaceType_withValidSource() { + ClassOrInterfaceType customType = adapter.parseClassOrInterfaceType("CustomInterface"); + + assertTrue(customType.isClassOrInterfaceType()); + + Mockito.verify(javaParser).parseClassOrInterfaceType("CustomInterface"); + } + + @Test + void parseType_withValidSource() { + Type customType = adapter.parseType("int"); + + assertTrue(customType.isPrimitiveType()); + + Mockito.verify(javaParser).parseType("int"); + } + + @Test + void parseVariableDeclarationExpr_withValidSource() { + VariableDeclarationExpr variable = adapter.parseVariableDeclarationExpr("final int x = 0"); + + assertTrue(variable.isFinal()); + + Mockito.verify(javaParser).parseVariableDeclarationExpr("final int x = 0"); + } + + @Test + void parseExplicitConstructorInvocationStmt_withValidSource() { + ExplicitConstructorInvocationStmt statement = adapter.parseExplicitConstructorInvocationStmt("super();"); + + assertTrue(statement.getArguments().isEmpty()); + + Mockito.verify(javaParser).parseExplicitConstructorInvocationStmt("super();"); + } + + @Test + void parseName_withValidSource() { + Name name = adapter.parseName("com.github.javaparser.JavaParser"); + + assertEquals("JavaParser", name.getIdentifier()); + + Mockito.verify(javaParser).parseName("com.github.javaparser.JavaParser"); + } + + @Test + void parseSimpleName_withValidSource() { + SimpleName name = adapter.parseSimpleName("JavaParser"); + + assertEquals("JavaParser", name.getIdentifier()); + + Mockito.verify(javaParser).parseSimpleName("JavaParser"); + } + + @Test + void parseParameter_withValidSource() { + Parameter parameter = adapter.parseParameter("String foo"); + + assertEquals("foo", parameter.getNameAsString()); + + Mockito.verify(javaParser).parseParameter("String foo"); + } + + @Test + void parsePackageDeclaration_withValidSource() { + PackageDeclaration packageDeclaration = adapter.parsePackageDeclaration("package com.github.javaparser;"); + + assertEquals("com.github.javaparser", packageDeclaration.getNameAsString()); + + Mockito.verify(javaParser).parsePackageDeclaration("package com.github.javaparser;"); + } + + @Test + void parseTypeDeclaration_withValidSource() { + TypeDeclaration typeDeclaration = adapter.parseTypeDeclaration("class A {}"); + + assertEquals("A", typeDeclaration.getNameAsString()); + + Mockito.verify(javaParser).parseTypeDeclaration("class A {}"); + } + + @Test + void parseModuleDeclaration_withValidSource() { + ModuleDeclaration moduleDeclaration = adapter.parseModuleDeclaration("module X {}"); + + assertEquals("X", moduleDeclaration.getNameAsString()); + + Mockito.verify(javaParser).parseModuleDeclaration("module X {}"); + } + + @Test + void parseModuleDirective_withValidSource() { + ModuleDirective moduleDirective = adapter.parseModuleDirective("opens X;"); + + assertTrue(moduleDirective.isModuleOpensDirective()); + + Mockito.verify(javaParser).parseModuleDirective("opens X;"); + } + + @Test + void parseTypeParameter_withValidSource() { + TypeParameter typeParameter = adapter.parseTypeParameter("T extends Object"); + + assertEquals("T", typeParameter.getNameAsString()); + + Mockito.verify(javaParser).parseTypeParameter("T extends Object"); + } + + @Test + void parseMethodDeclaration_withValidSource() { + MethodDeclaration methodDeclaration = adapter.parseMethodDeclaration("void test() {}"); + + assertEquals("test", methodDeclaration.getNameAsString()); + + Mockito.verify(javaParser).parseMethodDeclaration("void test() {}"); + } + +} \ No newline at end of file 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 new file mode 100644 index 0000000..f45c549 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/JavaParserTest.java @@ -0,0 +1,329 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +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; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.ast.stmt.ForStmt; +import com.github.javaparser.ast.stmt.ReturnStmt; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.ast.type.ClassOrInterfaceType; +import com.github.javaparser.ast.type.IntersectionType; +import com.github.javaparser.ast.type.Type; +import com.github.javaparser.printer.YamlPrinter; + +class JavaParserTest { + + @BeforeEach + void setToLatestJava() { + StaticJavaParser.getConfiguration().setLanguageLevel(BLEEDING_EDGE); + } + + @AfterEach + void resetJavaLevel() { + StaticJavaParser.getConfiguration().setLanguageLevel(CURRENT); + } + + @Test + void rangeOfAnnotationMemberDeclarationIsCorrect() { + String code = "@interface AD { String foo(); }"; + CompilationUnit cu = parse(code); + AnnotationMemberDeclaration memberDeclaration = cu.getAnnotationDeclarationByName("AD").get().getMember(0).asAnnotationMemberDeclaration(); + assertTrue(memberDeclaration.hasRange()); + assertEquals(new Range(new Position(1, 17), new Position(1, 29)), memberDeclaration.getRange().get()); + } + + @Test + void testSourcePositionsWithUnicodeEscapes() { + String code = "@interface AD \\u007B String foo(); \\u007D"; + CompilationUnit cu = parseWithUnicodeEscapes(code).getResult().get(); + AnnotationMemberDeclaration memberDeclaration = cu.getAnnotationDeclarationByName("AD").get().getMember(0).asAnnotationMemberDeclaration(); + assertTrue(memberDeclaration.hasRange()); + assertEquals(new Range(new Position(1, 22), new Position(1, 34)), memberDeclaration.getRange().get()); + } + + @Test + void testSourcePositionsWithBrokenUnicodeEscapes() { + // Source positions + // 111111111122222222 2 22333 3333 + // 123456789012345678901234567 8 90123 4567 + String code = "@interface AD { String X = \"\\uABC\"; }"; + ParseResult cu = parseWithUnicodeEscapes(code); + assertFalse(cu.getResult().isPresent()); + assertEquals("Lexical error at line 1, column 34. Encountered: \"\\\"\" (34), after : \"\\\"\\\\uABC\"", cu.getProblem(0).getMessage()); + } + + private static ParseResult parseWithUnicodeEscapes(String code) { + ParserConfiguration config = new ParserConfiguration(); + config.setPreprocessUnicodeEscapes(true); + return new JavaParser(config).parse(code); + } + + @Test + void rangeOfAnnotationMemberDeclarationWithArrayTypeIsCorrect() { + String code = "@interface AD { String[] foo(); }"; + CompilationUnit cu = parse(code); + AnnotationMemberDeclaration memberDeclaration = cu.getAnnotationDeclarationByName("AD").get().getMember(0).asAnnotationMemberDeclaration(); + assertTrue(memberDeclaration.hasRange()); + assertEquals(new Range(new Position(1, 17), new Position(1, 31)), memberDeclaration.getRange().get()); + } + + @Test + void rangeOfArrayCreationLevelWithExpressionIsCorrect() { + String code = "new int[123][456]"; + ArrayCreationExpr expression = parseExpression(code); + Optional range; + + range = expression.getLevels().get(0).getRange(); + assertTrue(range.isPresent()); + assertEquals(new Range(new Position(1, 8), new Position(1, 12)), range.get()); + + range = expression.getLevels().get(1).getRange(); + assertTrue(range.isPresent()); + assertEquals(new Range(new Position(1, 13), new Position(1, 17)), range.get()); + } + + @Test + void rangeOfArrayCreationLevelWithoutExpressionIsCorrect() { + String code = "new int[][]"; + ArrayCreationExpr expression = parseExpression(code); + Optional range; + + range = expression.getLevels().get(0).getRange(); + assertTrue(range.isPresent()); + assertEquals(new Range(new Position(1, 8), new Position(1, 9)), range.get()); + + range = expression.getLevels().get(1).getRange(); + assertTrue(range.isPresent()); + assertEquals(new Range(new Position(1, 10), new Position(1, 11)), range.get()); + } + + @Test + void parseErrorContainsLocation() { + ParseResult result = new JavaParser().parse(COMPILATION_UNIT, provider("class X { // blah")); + + 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\" \"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()); + } + + @Test + void parseIntersectionType() { + String code = "(Runnable & Serializable) (() -> {})"; + Expression expression = parseExpression(code); + Type type = expression.asCastExpr().getType(); + + assertTrue(type instanceof IntersectionType); + IntersectionType intersectionType = type.asIntersectionType(); + assertEquals(2, intersectionType.getElements().size()); + assertTrue(intersectionType.getElements().get(0) instanceof ClassOrInterfaceType); + assertEquals("Runnable", intersectionType.getElements().get(0).asClassOrInterfaceType().getNameAsString()); + assertTrue(intersectionType.getElements().get(1) instanceof ClassOrInterfaceType); + assertEquals("Serializable", intersectionType.getElements().get(1).asClassOrInterfaceType().getNameAsString()); + } + + @Test + void parseArrayInitialization() { + String code = "{1,2,3}"; + ArrayInitializerExpr expression = parseArrayInitializerExpr(code); + + assertEquals(3, expression.getValues().size()); + } + + @Test + void rangeOfIntersectionType() { + String code = "class A {" + SYSTEM_EOL + + " Object f() {" + SYSTEM_EOL + + " return (Comparator> & Serializable)(c1, c2) -> c1.getKey().compareTo(c2.getKey()); " + SYSTEM_EOL + + "}}"; + CompilationUnit cu = parse(code); + MethodDeclaration methodDeclaration = cu.getClassByName("A").get().getMember(0).asMethodDeclaration(); + ReturnStmt returnStmt = methodDeclaration.getBody().get().getStatement(0).asReturnStmt(); + CastExpr castExpr = returnStmt.getExpression().get().asCastExpr(); + Type type = castExpr.getType(); + assertEquals(range(3, 13, 3, 54), type.getRange().get()); + } + + @Test + void rangeOfCast() { + String code = "class A {" + SYSTEM_EOL + + " Object f() {" + SYSTEM_EOL + + " return (Comparator> & Serializable)(c1, c2) -> c1.getKey().compareTo(c2.getKey()); " + SYSTEM_EOL + + "}}"; + CompilationUnit cu = parse(code); + MethodDeclaration methodDeclaration = cu.getClassByName("A").get().getMember(0).asMethodDeclaration(); + ReturnStmt returnStmt = methodDeclaration.getBody().get().getStatement(0).asReturnStmt(); + CastExpr castExpr = returnStmt.getExpression().get().asCastExpr(); + assertEquals(range(3, 12, 3, 101), castExpr.getRange().get()); + } + + @Test + void rangeOfCastNonIntersection() { + String code = "class A {" + SYSTEM_EOL + + " Object f() {" + SYSTEM_EOL + + " return (Comparator> )(c1, c2) -> c1.getKey().compareTo(c2.getKey()); " + SYSTEM_EOL + + "}}"; + CompilationUnit cu = parse(code); + MethodDeclaration methodDeclaration = cu.getClassByName("A").get().getMember(0).asMethodDeclaration(); + ReturnStmt returnStmt = methodDeclaration.getBody().get().getStatement(0).asReturnStmt(); + CastExpr castExpr = returnStmt.getExpression().get().asCastExpr(); + assertEquals(range(3, 12, 3, 101), castExpr.getRange().get()); + } + + @Test + void rangeOfLambda() { + String code = "class A {" + SYSTEM_EOL + + " Object f() {" + SYSTEM_EOL + + " return (Comparator> & Serializable)(c1, c2) -> c1.getKey().compareTo(c2.getKey()); " + SYSTEM_EOL + + "}}"; + CompilationUnit cu = parse(code); + MethodDeclaration methodDeclaration = cu.getClassByName("A").get().getMember(0).asMethodDeclaration(); + ReturnStmt returnStmt = methodDeclaration.getBody().get().getStatement(0).asReturnStmt(); + CastExpr castExpr = returnStmt.getExpression().get().asCastExpr(); + LambdaExpr lambdaExpr = castExpr.getExpression().asLambdaExpr(); + assertEquals(range(3, 56, 3, 101), lambdaExpr.getRange().get()); + assertEquals(GeneratedJavaParserConstants.LPAREN, lambdaExpr.getTokenRange().get().getBegin().getKind()); + assertEquals(GeneratedJavaParserConstants.RPAREN, lambdaExpr.getTokenRange().get().getEnd().getKind()); + } + + @Test + void rangeOfLambdaBody() { + String code = "class A {" + SYSTEM_EOL + + " Object f() {" + SYSTEM_EOL + + " return (Comparator> & Serializable)(c1, c2) -> c1.getKey().compareTo(c2.getKey()); " + SYSTEM_EOL + + "}}"; + CompilationUnit cu = parse(code); + MethodDeclaration methodDeclaration = cu.getClassByName("A").get().getMember(0).asMethodDeclaration(); + ReturnStmt returnStmt = methodDeclaration.getBody().get().getStatement(0).asReturnStmt(); + CastExpr castExpr = returnStmt.getExpression().get().asCastExpr(); + LambdaExpr lambdaExpr = castExpr.getExpression().asLambdaExpr(); + Statement lambdaBody = lambdaExpr.getBody(); + assertEquals(range(3, 68, 3, 101), lambdaBody.getRange().get()); + } + + @Test + void testNotStoringTokens() { + JavaParser javaParser = new JavaParser(new ParserConfiguration().setStoreTokens(false)); + ParseResult result = javaParser.parse(ParseStart.COMPILATION_UNIT, provider("class X{}")); + assertFalse(result.getResult().get().getTokenRange().isPresent()); + } + + @Test + void trailingCodeIsAnError() { + assertThrows(ParseProblemException.class, () -> parseBlock("{} efijqoifjqefj")); + } + + @Test + void trailingWhitespaceIsIgnored() { + BlockStmt blockStmt = parseBlock("{} // hello"); + assertEquals("{}", blockStmt.getTokenRange().get().toString()); + } + + @Test + void parsingInitializedAndUnitializedVarsInForStmt() { + ForStmt forStmt = parseStatement("for(int a,b=0;;){}").asForStmt(); + assertEquals(1, forStmt.getInitialization().size()); + assertTrue(forStmt.getInitialization().get(0).isVariableDeclarationExpr()); + assertEquals(2, forStmt.getInitialization().get(0).asVariableDeclarationExpr().getVariables().size()); + assertEquals("a", forStmt.getInitialization().get(0).asVariableDeclarationExpr().getVariables().get(0).getNameAsString()); + assertEquals("b", forStmt.getInitialization().get(0).asVariableDeclarationExpr().getVariables().get(1).getNameAsString()); + assertFalse(forStmt.getInitialization().get(0).asVariableDeclarationExpr().getVariables().get(0).getInitializer().isPresent()); + assertTrue(forStmt.getInitialization().get(0).asVariableDeclarationExpr().getVariables().get(1).getInitializer().isPresent()); + } + + @Test + void parsingInitializedAndUnitializedVarsInForStmtComplexCase() { + // See issue 1281 + ForStmt forStmt = parseStatement("for(int i, j = array2.length - 1;;){}").asForStmt(); + assertEquals(1, forStmt.getInitialization().size()); + assertTrue(forStmt.getInitialization().get(0).isVariableDeclarationExpr()); + assertEquals(2, forStmt.getInitialization().get(0).asVariableDeclarationExpr().getVariables().size()); + assertEquals("i", forStmt.getInitialization().get(0).asVariableDeclarationExpr().getVariables().get(0).getNameAsString()); + assertEquals("j", forStmt.getInitialization().get(0).asVariableDeclarationExpr().getVariables().get(1).getNameAsString()); + assertFalse(forStmt.getInitialization().get(0).asVariableDeclarationExpr().getVariables().get(0).getInitializer().isPresent()); + assertTrue(forStmt.getInitialization().get(0).asVariableDeclarationExpr().getVariables().get(1).getInitializer().isPresent()); + } + + @Test + void creatingNewObjectCreationExprShouldDefaultToParsing() { + String className = String.class.getCanonicalName(); + ClassOrInterfaceType type = parseClassOrInterfaceType(className); + ObjectCreationExpr expected = parseExpression("new " + className + "()"); + ObjectCreationExpr actual = new ObjectCreationExpr(null, type, NodeList.nodeList()); + assertEquals(expected, actual); + } + + @Test + void parseModuleDeclaration() { + StaticJavaParser.parseModuleDeclaration("module X {}"); + } + + @Test + void parseModuleDirective() { + StaticJavaParser.parseModuleDirective("opens C;"); + } + + @Test + void parseTypeParameter() { + StaticJavaParser.parseTypeParameter("T extends Serializable & AttachableListener"); + } + + @Test + void parseTypeDeclaration() { + StaticJavaParser.parseTypeDeclaration("enum Z {A, B}"); + } + + @Test + void xxx(){ + YamlPrinter.print(StaticJavaParser.parse("class X{}")); + } + + @Test + void issue2879() { + StaticJavaParser.parse( + "public class Test {" + + " public void method(int @MyAnno ... param) {}" + + "}" + + "@Target(java.lang.annotation.ElementType.TYPE_USE) @interface MyAnno {}"); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/JavaTokenTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/JavaTokenTest.java new file mode 100644 index 0000000..7ad6233 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/JavaTokenTest.java @@ -0,0 +1,161 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + + +import com.github.javaparser.ast.expr.Expression; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Field; +import java.util.Iterator; + +import static com.github.javaparser.GeneratedJavaParserConstants.*; +import static com.github.javaparser.JavaToken.Category.*; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.Range.range; +import static org.junit.jupiter.api.Assertions.*; + +class JavaTokenTest { + + @Test + void testAFewTokens() { + ParseResult result = new JavaParser().parse(ParseStart.EXPRESSION, provider("1 +/*2*/1 ")); + Iterator iterator = result.getResult().get().getTokenRange().get().iterator(); + assertToken("1", range(1, 1, 1, 1), INTEGER_LITERAL, LITERAL, iterator.next()); + assertToken(" ", range(1, 2, 1, 2), SPACE, WHITESPACE_NO_EOL, iterator.next()); + assertToken("+", range(1, 3, 1, 3), PLUS, OPERATOR, iterator.next()); + assertToken("/*2*/", range(1, 4, 1, 8), MULTI_LINE_COMMENT, COMMENT, iterator.next()); + assertToken("1", range(1, 9, 1, 9), INTEGER_LITERAL, LITERAL, iterator.next()); + assertToken(" ", range(1, 10, 1, 10), SPACE, WHITESPACE_NO_EOL, iterator.next()); + assertToken("", range(1, 10, 1, 10), EOF, WHITESPACE_NO_EOL, iterator.next()); + assertFalse(iterator.hasNext()); + } + + private void assertToken(String image, Range range, int kind, JavaToken.Category category, JavaToken token) { + assertEquals(image, token.getText()); + assertEquals(range, token.getRange().get()); + assertEquals(kind, token.getKind()); + assertEquals(category, token.getCategory()); + token.getNextToken().ifPresent(nt -> assertEquals(token, nt.getPreviousToken().get())); + token.getPreviousToken().ifPresent(pt -> assertEquals(token, pt.getNextToken().get())); + assertTrue(token.getNextToken().isPresent() || token.getPreviousToken().isPresent()); + } + + @Test + void testAFewImagesForTokenKinds() { + assertEquals("=", new JavaToken(ASSIGN).getText()); + // TODO this shouldn't be a space. + assertEquals(" ", new JavaToken(EOF).getText()); + assertEquals("*/", new JavaToken(JAVADOC_COMMENT).getText()); + } + + @Test + void testKindEnum() { + JavaToken.Kind kind = JavaToken.Kind.valueOf(GeneratedJavaParserConstants.ASSERT); + + assertEquals(JavaToken.Kind.ASSERT, kind); + assertEquals(GeneratedJavaParserConstants.ASSERT, kind.getKind()); + } + + /** + * Two places where "generated" token types exist. + * - Firstly, {@link GeneratedJavaParserConstants} which is produced by JavaCC + * - Secondly, {@link JavaToken}, which is produced by JavaParser + *

+ * This test makes a best-effort attempt to ensure that the two are aligned. + */ + @Test + void test() throws NoSuchFieldException, IllegalAccessException { + + final int tokenCount = GeneratedJavaParserConstants.tokenImage.length; + assertEquals(tokenCount, JavaToken.Kind.values().length, "Error - mismatch between number of tokens."); + + // Iterate through the JP Tokens, and ensure that it matches the JavaCC tokens. + for (int i = 0; i < tokenCount; i++) { + + // Details about the Java Parser Token + JavaToken.Kind jpToken = JavaToken.Kind.valueOf(i); + String jpTokenName = jpToken.name(); + int jpTokenNumber = jpToken.getKind(); + + // Details about the JavaCC Token (using reflection) + Field declaredField = GeneratedJavaParserConstants.class.getDeclaredField(jpTokenName); + String javaCcTokenName = declaredField.getName(); + Object javaccTokenNumber = declaredField.get(null); // static fields, therefore null is okay + + + // Optional printing -- for debugging purposes. +// System.out.println(i + " - " + +// jpTokenName + " (" + jpTokenNumber + ") - " + +// javaCcTokenName + " (" + javaccTokenNumber + ")" +// ); + + assertEquals(jpTokenName, javaCcTokenName); + assertEquals( + javaccTokenNumber, jpTokenNumber, + "Error - Likely need to rerun JP Generators following a grammar change." + + "\nProblem with `" + jpTokenName + "`." + + "\nNote mismatch between:" + + "\n - token #" + javaccTokenNumber + " - GeneratedJavaParserConstants (generated using JavaCC)" + + "\n - token #" + jpTokenNumber + " - JavaToken (generated using JP Generators)." + ); + } + } + + @Test + void testDeleteToken() { + ParseResult result = new JavaParser().parse(ParseStart.EXPRESSION, provider("1+/*2*/1\n")); + TokenRange tokenRange = result.getResult().get().getTokenRange().get(); + + JavaToken tokenToBeDeleted = tokenRange.getBegin().getNextToken().get(); + tokenToBeDeleted.deleteToken(); + JavaToken nextTokenAfterDelete = tokenRange.getBegin().getNextToken().get(); + JavaToken previous = nextTokenAfterDelete.getPreviousToken().get(); + + assertNotEquals(tokenToBeDeleted, nextTokenAfterDelete); + assertEquals("/*2*/", nextTokenAfterDelete.getText()); + assertEquals("1", previous.getText()); + } + + @Test + void testFindLastToken() { + ParseResult result = new JavaParser().parse(ParseStart.EXPRESSION, provider("1 +/*2*/3 ")); + TokenRange tokenRange = result.getResult().get().getTokenRange().get(); + Iterator iterator = tokenRange.iterator(); + assertToken("", range(1, 10, 1, 10), EOF, WHITESPACE_NO_EOL, iterator.next().findLastToken()); + + // getEnd token in TokenRange is not the same as the last token from findLastToken() + // assertEquals(tokenRange.getEnd(), tokenRange.getBegin().findLastToken()); + } + + @Test + void testFindFirstToken() { + ParseResult result = new JavaParser().parse(ParseStart.EXPRESSION, provider("1 +/*2*/3+4")); + Iterator iterator = result.getResult().get().getTokenRange().get().iterator(); + iterator.next(); + iterator.next(); + iterator.next(); + assertEquals("/*2*/", iterator.next().getText()); + assertToken("1", range(1, 1, 1, 1), INTEGER_LITERAL, LITERAL, iterator.next().findFirstToken()); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/JavadocParserTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/JavadocParserTest.java new file mode 100644 index 0000000..1745005 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/JavadocParserTest.java @@ -0,0 +1,174 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.javadoc.Javadoc; +import com.github.javaparser.javadoc.JavadocBlockTag; +import com.github.javaparser.javadoc.description.JavadocDescription; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.utils.Utils.SYSTEM_EOL; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class JavadocParserTest { + + @Test + void parseSimplestContent() { + Assertions.assertEquals(new Javadoc(JavadocDescription.parseText("A simple line of text")), + JavadocParser.parse("A simple line of text")); + } + + @Test + void parseEmptySingleLine() { + Assertions.assertEquals(new Javadoc(JavadocDescription.parseText("")), + JavadocParser.parse(SYSTEM_EOL)); + } + + @Test + void parseSingleLineWithSpacing() { + assertEquals(new Javadoc(JavadocDescription.parseText("The line number of the first character of this Token.")), + JavadocParser.parse(" The line number of the first character of this Token. ")); + } + + @Test + void parseSingleLineWithNewLines() { + assertEquals(new Javadoc(JavadocDescription.parseText("The string image of the token.")), + JavadocParser.parse(SYSTEM_EOL + + " * The string image of the token." + SYSTEM_EOL + + " ")); + } + + @Test + void parseCommentWithNewLines() { + String text = SYSTEM_EOL + + " * The version identifier for this Serializable class." + SYSTEM_EOL + + " * Increment only if the serialized form of the" + SYSTEM_EOL + + " * class changes." + SYSTEM_EOL + + " "; + assertEquals(new Javadoc(JavadocDescription.parseText("The version identifier for this Serializable class." + SYSTEM_EOL + + "Increment only if the serialized form of the" + SYSTEM_EOL + + "class changes.")), + JavadocParser.parse(text)); + } + + @Test + void parseCommentWithIndentation() { + String text = "Returns a new Token object, by default." + SYSTEM_EOL + + " * However, if you want, you can create and return subclass objects based on the value of ofKind." + SYSTEM_EOL + + " *" + SYSTEM_EOL + + " * case MyParserConstants.ID : return new IDToken(ofKind, image);" + SYSTEM_EOL + + " *" + SYSTEM_EOL + + " * to the following switch statement. Then you can cast matchedToken"; + assertEquals(new Javadoc(JavadocDescription.parseText("Returns a new Token object, by default." + SYSTEM_EOL + + "However, if you want, you can create and return subclass objects based on the value of ofKind." + SYSTEM_EOL + + SYSTEM_EOL + + " case MyParserConstants.ID : return new IDToken(ofKind, image);" + SYSTEM_EOL + + SYSTEM_EOL + + "to the following switch statement. Then you can cast matchedToken")), + JavadocParser.parse(text)); + } + + @Test + void parseBlockTagsAndEmptyDescription() { + String text = SYSTEM_EOL + + " * @deprecated" + SYSTEM_EOL + + " * @see #getEndColumn" + SYSTEM_EOL + + " "; + assertEquals(new Javadoc(JavadocDescription.parseText("")) + .addBlockTag(new JavadocBlockTag(JavadocBlockTag.Type.DEPRECATED, "")) + .addBlockTag(new JavadocBlockTag(JavadocBlockTag.Type.SEE, "#getEndColumn")), JavadocParser.parse(text)); + } + + @Test + void parseBlockTagsAndProvideTagName() { + String expectedText = SYSTEM_EOL + + " * @unofficial" + SYSTEM_EOL + " " + + " "; + + Javadoc underTest = new Javadoc(JavadocDescription.parseText("")) + .addBlockTag(new JavadocBlockTag("unofficial", "")); + + + assertEquals(underTest, JavadocParser.parse(expectedText)); + assertEquals(1, underTest.getBlockTags().size()); + assertEquals("unofficial", underTest.getBlockTags().get(0).getTagName()); + } + + @Test + void parseParamBlockTags() { + String text = SYSTEM_EOL + + " * Add a field to this and automatically add the import of the type if needed" + SYSTEM_EOL + + " *" + SYSTEM_EOL + + " * @param typeClass the type of the field" + SYSTEM_EOL + + " * @param name the name of the field" + SYSTEM_EOL + + " * @param modifiers the modifiers like {@link Modifier#PUBLIC}" + SYSTEM_EOL + + " * @return the {@link FieldDeclaration} created" + SYSTEM_EOL + + " "; + Javadoc res = JavadocParser.parse(text); + assertEquals(new Javadoc(JavadocDescription.parseText("Add a field to this and automatically add the import of the type if needed")) + .addBlockTag(JavadocBlockTag.createParamBlockTag("typeClass", "the type of the field")) + .addBlockTag(JavadocBlockTag.createParamBlockTag("name", "the name of the field")) + .addBlockTag(JavadocBlockTag.createParamBlockTag("modifiers", "the modifiers like {@link Modifier#PUBLIC}")) + .addBlockTag(new JavadocBlockTag(JavadocBlockTag.Type.RETURN, "the {@link FieldDeclaration} created")), res); + } + + @Test + void parseMultilineParamBlockTags() { + String text = SYSTEM_EOL + + " * Add a field to this and automatically add the import of the type if needed" + SYSTEM_EOL + + " *" + SYSTEM_EOL + + " * @param typeClass the type of the field" + SYSTEM_EOL + + " * continued in a second line" + SYSTEM_EOL + + " * @param name the name of the field" + SYSTEM_EOL + + " * @param modifiers the modifiers like {@link Modifier#PUBLIC}" + SYSTEM_EOL + + " * @return the {@link FieldDeclaration} created" + SYSTEM_EOL + + " "; + Javadoc res = JavadocParser.parse(text); + assertEquals(new Javadoc(JavadocDescription.parseText("Add a field to this and automatically add the import of the type if needed")) + .addBlockTag(JavadocBlockTag.createParamBlockTag("typeClass", "the type of the field" + SYSTEM_EOL + " continued in a second line")) + .addBlockTag(JavadocBlockTag.createParamBlockTag("name", "the name of the field")) + .addBlockTag(JavadocBlockTag.createParamBlockTag("modifiers", "the modifiers like {@link Modifier#PUBLIC}")) + .addBlockTag(new JavadocBlockTag(JavadocBlockTag.Type.RETURN, "the {@link FieldDeclaration} created")), res); + } + + @Test + void startsWithAsteriskEmpty() { + assertEquals(-1, JavadocParser.startsWithAsterisk("")); + } + + @Test + void startsWithAsteriskNoAsterisk() { + assertEquals(-1, JavadocParser.startsWithAsterisk(" ciao")); + } + + @Test + void startsWithAsteriskAtTheBeginning() { + assertEquals(0, JavadocParser.startsWithAsterisk("* ciao")); + } + + @Test + void startsWithAsteriskAfterSpaces() { + assertEquals(3, JavadocParser.startsWithAsterisk(" * ciao")); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/LineSeparatorProcessorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/LineSeparatorProcessorTest.java new file mode 100644 index 0000000..14325a0 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/LineSeparatorProcessorTest.java @@ -0,0 +1,124 @@ +/* + * Copyright (C) 2013-2024 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; + +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.FieldDeclaration; +import com.github.javaparser.ast.body.VariableDeclarator; +import com.github.javaparser.ast.type.ClassOrInterfaceType; +import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest; +import com.github.javaparser.printer.lexicalpreservation.LexicalPreservingPrinter; +import com.github.javaparser.utils.LineSeparator; +import org.junit.jupiter.api.Test; + +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; + +public class LineSeparatorProcessorTest extends AbstractLexicalPreservingTest{ + + // TODO: Add more tests outside the "happy path" (e.g. mixed EOL, no EOL, etc.) + + /* + * This test case must prevent an UnsupportedOperation Removed throwed by LexicalPreservation when we try to replace an expression + */ + public void doTest(LineSeparator lineSeparator) { + String eol = lineSeparator.asRawString(); + + considerCode("" + + " public class Foo { //comment" + eol + + " private String a;" + eol + + " private String b;" + eol + + " private String c;" + eol + + " private String d;" + eol + + " }"); + + // Note: Expect the platform's EOL character when printing + String expected = "" + + " public class Foo { //comment" + eol + + " private String newField;" + eol + + " " + eol + + " private String a;" + eol + + " private String b;" + eol + + " private String c;" + eol + + " private String d;" + eol + + " }"; + + + // create a new field declaration + VariableDeclarator variable = new VariableDeclarator(new ClassOrInterfaceType("String"), "newField"); + FieldDeclaration fd = new FieldDeclaration(new NodeList(Modifier.privateModifier()), variable); + Optional cd = cu.findFirst(ClassOrInterfaceDeclaration.class); + + // add the new variable + cd.get().getMembers().addFirst(fd); + + // should be printed like this +// System.out.println("\n\nOriginal:\n" + original); +// System.out.println("\n\nExpected:\n" + expected); + + // but the result is + final String actual = LexicalPreservingPrinter.print(cu); +// System.out.println("\n\nActual:\n" + actual); + + + // The LineEndingProcessingProvider sets the line ending to the root node. + // Child nodes should then "inherit" then line ending style. + LineSeparator lineSeparator_cu = cu.getLineEndingStyle(); + LineSeparator lineSeparator_fd = fd.getLineEndingStyle(); + +// System.out.println("lineSeparator_cu.describe() = " + lineSeparator_cu.describe()); +// System.out.println("lineSeparator_fd.describe() = " + lineSeparator_fd.describe()); + + // Assert that it has been detected and injected correctly. + LineSeparator detectedLineSeparator = LineSeparator.detect(actual); + assertEquals(lineSeparator, detectedLineSeparator); + assertEquals(lineSeparator, lineSeparator_cu); + assertEquals(lineSeparator, lineSeparator_fd); + + // The line ending data is injected at the root node, thus should only exist there. + assertTrue(cu.containsData(Node.LINE_SEPARATOR_KEY), "Expected the processor provider to have set the data on the root node."); + assertFalse(fd.containsData(Node.LINE_SEPARATOR_KEY), "Expected the line ending value to have been inherited, not set directly"); + + } + + @Test + public void testWithCr() { + doTest(LineSeparator.CR); + } + + @Test + public void testWithCrLf() { + doTest(LineSeparator.CRLF); + } + + @Test + public void testWithLf() { + doTest(LineSeparator.LF); + } + + + // TODO: Test for textblocks + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ParseErrorRecoveryTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ParseErrorRecoveryTest.java new file mode 100644 index 0000000..c0f316c --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ParseErrorRecoveryTest.java @@ -0,0 +1,86 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.stmt.LabeledStmt; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.ast.stmt.UnparsableStmt; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.ast.Node.Parsedness.UNPARSABLE; +import static org.junit.jupiter.api.Assertions.*; + +class ParseErrorRecoveryTest { + private final JavaParser parser = new JavaParser(); + + @Test + void compilationUnitRecovery() { + CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, provider("XXX")).getResult().get(); + assertEquals(UNPARSABLE, cu.getParsed()); + } + + @Test + void bodystatementSemicolonRecovery() { + MethodDeclaration cu = parser.parse(ParseStart.CLASS_BODY, provider("int x(){X X X;}")).getResult().get().asMethodDeclaration(); + Statement xxx = cu.getBody().get().getStatements().get(0); + assertEquals(UNPARSABLE, xxx.getParsed()); + } + + @Test + void bodystatementClosingBraceRecovery() { + MethodDeclaration cu = parser.parse(ParseStart.CLASS_BODY, provider("int x(){X X X}")).getResult().get().asMethodDeclaration(); + Statement xxx = cu.getBody().get(); + assertEquals(1, xxx.getChildNodes().size()); + assertTrue(xxx.getChildNodes().get(0) instanceof UnparsableStmt); + } + + @Test + void labeledStatementSemicolonRecovery() { + CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, provider("class X{int x(){aaa:X X X;}}")).getResult().get(); + LabeledStmt xxx = cu.getClassByName("X").get().getMethods().get(0).getBody().get().getStatements().get(0).asLabeledStmt(); + assertEquals(UNPARSABLE, xxx.getStatement().getParsed()); + } + + @Test + void testIncompleteClassParse() { + CompilationUnit compilationUnit = parser.parse(getClass().getResourceAsStream("Sample.java")).getResult().get(); + assertFalse(compilationUnit.getTypes().isEmpty()); + assertFalse(compilationUnit.getTypes().get(0).getMembers().isEmpty()); + } + + @Test + void testBodyRecoverIf() { + CompilationUnit compilationUnit = parser.parse(ParseStart.COMPILATION_UNIT, provider("class A { int a() { if() }}")).getResult().get(); + assertFalse(compilationUnit.getTypes().isEmpty()); + assertEquals(1, compilationUnit.getTypes().get(0).getMembers().size()); + } + + @Test + void testBodyRecoverLevel() { + CompilationUnit compilationUnit = parser.parse(ParseStart.COMPILATION_UNIT, provider("class A { int a() { int b = if (true) {int c = 5;} }}")).getResult().get(); + assertFalse(compilationUnit.getTypes().isEmpty()); + assertEquals(1, compilationUnit.getTypes().get(0).getMembers().size()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ParserConfigurationTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ParserConfigurationTest.java new file mode 100644 index 0000000..247181f --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ParserConfigurationTest.java @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.stmt.Statement; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.ParseStart.STATEMENT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.RAW; +import static com.github.javaparser.Providers.provider; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ParserConfigurationTest { + @Test + void storeNoTokens() { + ParseResult result = new JavaParser(new ParserConfiguration().setStoreTokens(false)).parse(ParseStart.COMPILATION_UNIT, provider("class X{}")); + + assertFalse(result.getResult().get().getTokenRange().isPresent()); + assertTrue(result.getResult().get().findAll(Node.class).stream().noneMatch(node -> node.getTokenRange().isPresent())); + } + + @Test + void noProblemsHere() { + ParseResult result = + new JavaParser(new ParserConfiguration().setLanguageLevel(RAW)) + .parse(STATEMENT, provider("try{}")); + assertTrue(result.isSuccessful()); + } + + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/PositionMappingTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/PositionMappingTest.java new file mode 100644 index 0000000..1905dc0 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/PositionMappingTest.java @@ -0,0 +1,165 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.UnicodeEscapeProcessingProvider.PositionMapping; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import static com.github.javaparser.UnicodeEscapeProcessingProviderTest.process; +import static com.github.javaparser.UnicodeEscapeProcessingProviderTest.provider; +import static org.junit.jupiter.api.Assertions.*; + +/** + * Test case for {@link PositionMapping}. + * + * @author Bernhard Haumacher + */ +@SuppressWarnings("javadoc") +public class PositionMappingTest { + + @Test + public void testNoMapping() throws IOException { + List> input = lines( + line("Hello World !\n"), + line("Next Line\r"), + line("Third Line\r\n"), + line("Fourth Line.")); + String inputText = text(input); + UnicodeEscapeProcessingProvider provider = provider(inputText); + String outputText = process(provider); + assertEquals(inputText, outputText); + PositionMapping mapping = provider.getPositionMapping(); + assertTrue(mapping.isEmpty()); + assertEquals(4, provider.getInputCounter().getLine()); + assertEquals(4, provider.getOutputCounter().getLine()); + assertSame(PositionMapping.PositionUpdate.NONE, mapping.lookup(new Position(10000, 1))); + } + + @Test + public void testEncodedLineFeed() throws IOException { + List> input = lines( + line("B", "\\u000A", "C")); + List> output = lines( + line("B", "\n"), + line("C")); + + checkConvert(input, output); + } + + @Test + public void testComplexMapping() throws IOException { + List> input = lines( + // Character positions: + // 111 1 11111 1222 2 2222 2 + // 1 2 34567 89012 3 45678 9012 3 45678 9 + line("H", "\\u00E4", "llo W", "\\u00F6", "rld!", "\\u000A", "123 N", "\\u00E4", "xt Line", "\\u000D", "Third Line", "\r\n"), + line("Fo", "\\u00FC", "rth Line.")); + List> output = lines( + line("H", "ä", "llo W", "ö", "rld!", "\n"), + line("123 N", "ä", "xt Line", "\r"), + line("Third Line", "\r\n"), + line("Fo", "ü", "rth Line.")); + + checkConvert(input, output); + } + + private void checkConvert(List> input, + List> output) throws IOException { + UnicodeEscapeProcessingProvider provider = provider(text(input)); + String decoded = process(provider); + assertEquals(text(output), decoded); + + PositionMapping mapping = provider.getPositionMapping(); + + // Coarse grained test. + assertEquals(input.size(), provider.getInputCounter().getLine()); + assertEquals(output.size(), provider.getOutputCounter().getLine()); + + // Fine grained test. + int inPosLine = 1; + int inPosColumn = 1; + int outPosLine = 1; + int outPosColumn = 1; + Iterator> outLineIt = output.iterator(); + List outLine = outLineIt.next(); + Iterator outPartIt = outLine.iterator(); + String outPart = outPartIt.next(); + boolean outFinished = false; + for (List inLine : input) { + for (String inPart : inLine) { + assertFalse(outFinished); + + Position inPos = new Position(inPosLine, inPosColumn); + Position outPos = new Position(outPosLine, outPosColumn); + Position transfomedOutPos = mapping.transform(outPos); + + assertEquals(inPos, transfomedOutPos, + "Position mismatch at '" + outPart + "' " + outPos + " -> '" + inPart + "' " + inPos + "."); + + outPosColumn += outPart.length(); + inPosColumn += inPart.length(); + + if (!outPartIt.hasNext()) { + if (outLineIt.hasNext()) { + outPartIt = outLineIt.next().iterator(); + outPosLine ++; + outPosColumn = 1; + + outPart = outPartIt.next(); + } else { + outFinished = true; + } + } else { + outPart = outPartIt.next(); + } + } + + inPosColumn = 1; + inPosLine++; + } + } + + private static String text(List> input) { + StringBuilder result = new StringBuilder(); + for (List line : input) { + for (String part : line) { + result.append(part); + } + } + return result.toString(); + } + + @SafeVarargs + private static List line(String ...parts) { + return Arrays.asList(parts); + } + + @SafeVarargs + private static List> lines(List ...lines) { + return Arrays.asList(lines); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/PositionTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/PositionTest.java new file mode 100644 index 0000000..6664cd8 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/PositionTest.java @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2013-2024 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; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class PositionTest { + + @Test + public void testOrIfInvalid() { + Position p1 = new Position(1, 1); + Position p2 = new Position(2, 2); + + assertEquals(p1, p1.orIfInvalid(p2)); + + Position invalid = new Position(0, 0); + Position invalid2 = new Position(0, 1); + + assertEquals(p1, invalid.orIfInvalid(p1)); + assertEquals(invalid2, invalid2.orIfInvalid(invalid)); + } + + @Test + public void testPositionExceptionFormat() { + IllegalArgumentException thrown1 = Assertions.assertThrows(IllegalArgumentException.class, + () -> new Position(-10, 1)); + + assertEquals("Can't position at line -10", thrown1.getMessage()); + + IllegalArgumentException thrown2 = Assertions.assertThrows(IllegalArgumentException.class, + () -> new Position(1, -10)); + + assertEquals("Can't position at column -10", thrown2.getMessage()); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ProblemTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ProblemTest.java new file mode 100644 index 0000000..6416b21 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ProblemTest.java @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.utils.TestUtils.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ProblemTest { + @Test + void testSimpleGetters() { + Problem problem = new Problem("Parse error", TokenRange.INVALID, new Exception()); + + assertEquals(TokenRange.INVALID, problem.getLocation().get()); + assertEquals("Parse error", problem.getMessage()); + assertInstanceOf(Exception.class, problem.getCause().get()); + } + + @Test + void testVerboseMessage() { + Problem problem = new Problem("Parse error", TokenRange.INVALID, null); + + assertEquals("(line ?,col ?) Parse error", problem.getVerboseMessage()); + } + + @Test + void testVerboseMessageWithoutLocation() { + Problem problem = new Problem("Parse error", null, null); + + assertEquals("Parse error", problem.getVerboseMessage()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ProvidersTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ProvidersTest.java new file mode 100644 index 0000000..201abc2 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ProvidersTest.java @@ -0,0 +1,63 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.ast.CompilationUnit; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.nio.charset.Charset; + +import static org.junit.jupiter.api.Assertions.*; + +class ProvidersTest { + + @Test + void testResourceProvider() throws IOException { + Provider provider = Providers.resourceProvider("com/github/javaparser/issue_samples/Issue290.java.txt"); + assertNotNull(provider); + JavaParser parser = new JavaParser(); + ParseResult parse = parser.parse(ParseStart.COMPILATION_UNIT, provider); + assertTrue(parse.isSuccessful()); + } + + @Test + void testResourceProviderWithWrongEncoding() throws IOException { + Provider provider = Providers.resourceProvider("com/github/javaparser/TestFileIso88591.java"); + assertNotNull(provider); + JavaParser parser = new JavaParser(); + ParseResult parse = parser.parse(ParseStart.COMPILATION_UNIT, provider); + assertFalse(parse.isSuccessful()); + } + + @Test + void testResourceProviderWithEncoding() throws IOException { + Provider provider = Providers.resourceProvider( + "com/github/javaparser/TestFileIso88591.java", + Charset.forName("ISO-8859-1") + ); + assertNotNull(provider); + JavaParser parser = new JavaParser(); + ParseResult parse = parser.parse(ParseStart.COMPILATION_UNIT, provider); + assertTrue(parse.isSuccessful()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/RangeTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/RangeTest.java new file mode 100644 index 0000000..1a8acee --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/RangeTest.java @@ -0,0 +1,293 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class RangeTest { + + private final Position pos1 = new Position(10, 11); + private final Position pos2 = new Position(20, 21); + private final Range range_orderedPositions = Range.range(pos1, pos2); + private final Range range_reversedPositions = Range.range(pos2, pos1); + + private final Position posA1 = new Position(1, 1); + private final Position posB1 = new Position(2, 1); + private final Position posC1 = new Position(3, 1); + private final Position posD1 = new Position(4, 1); + private final Position posE1 = new Position(5, 1); + + private final Position posA5 = new Position(1, 5); + private final Position posB5 = new Position(2, 5); + private final Position posC5 = new Position(3, 5); + private final Position posD5 = new Position(4, 5); + private final Position posE5 = new Position(5, 5); + + private final Range arbitraryRange = Range.range(1, 1, 3, 10); + + // Potential expansion option for a larger variety of these categories of values to be provided to parameterised tests. + //@formatter:off + private Range[] rangePair_overlappingButNotContained = new Range[]{Range.range(posA1, posC1), Range.range(posB1, posE1)}; + private Range[] rangePair_unrelated = new Range[]{Range.range(posA1, posB1), Range.range(posD1, posE1)}; + private Range[] rangePair_equalBeginEnd = new Range[]{Range.range(posA1, posB1), Range.range(posA1, posB1)}; + private Range[] rangePair_strictlyContained = new Range[]{Range.range(posA1, posE1), Range.range(posB1, posD1)}; + private Range[] rangePair_touchingLineAndColumn = new Range[]{Range.range(posA1, posC1), Range.range(posC1, posE1)}; + private Range[] rangePair_touchingLineNotColumn = new Range[]{Range.range(posA1, posC1), Range.range(posC5, posD1)}; + //@formatter:on + + @Test + void constructorWithOrderedPositions() { + assertEquals(10, range_orderedPositions.begin.line); + assertEquals(11, range_orderedPositions.begin.column); + assertEquals(20, range_orderedPositions.end.line); + assertEquals(21, range_orderedPositions.end.column); + } + + @Test + void constructorWithReversedPositions() { + assertEquals(10, range_reversedPositions.begin.line); + assertEquals(11, range_reversedPositions.begin.column); + assertEquals(20, range_reversedPositions.end.line); + assertEquals(21, range_reversedPositions.end.column); + } + + @Test + void rangePair_equalBeginEnd_contains_true() { + assertTrue(rangePair_equalBeginEnd[0].contains(rangePair_equalBeginEnd[1])); + } + + @Test + void rangePair_equalBeginEnd_strictlyContains_false() { + assertFalse(rangePair_equalBeginEnd[0].strictlyContains(rangePair_equalBeginEnd[1])); + } + + @Test + void rangePair_overlappingButNotContained_contains_false() { + Range r1 = rangePair_overlappingButNotContained[0]; + Range r2 = rangePair_overlappingButNotContained[1]; + assertFalse(r1.contains(r2)); + assertFalse(r2.contains(r1)); + } + + @Test + void rangePair_overlappingButNotContained_strictlyContains_false() { + Range r1 = rangePair_overlappingButNotContained[0]; + Range r2 = rangePair_overlappingButNotContained[1]; + assertFalse(r1.strictlyContains(r2)); + assertFalse(r2.strictlyContains(r1)); + } + + @Test + void rangePair_unrelated_contains_false() { + Range r1 = rangePair_unrelated[0]; + Range r2 = rangePair_unrelated[1]; + assertFalse(r1.contains(r2)); + assertFalse(r2.contains(r1)); + } + + @Test + void rangePair_unrelated_strictlyContains_false() { + Range r1 = rangePair_unrelated[0]; + Range r2 = rangePair_unrelated[1]; + assertFalse(r1.strictlyContains(r2)); + assertFalse(r2.strictlyContains(r1)); + } + + @Test + void rangePair_strictlyContained_contains() { + Range r1 = rangePair_strictlyContained[0]; + Range r2 = rangePair_strictlyContained[1]; + assertTrue(r1.contains(r2)); + assertFalse(r2.contains(r1)); + } + + @Test + void rangePair_strictlyContained_strictlyContains() { + Range r1 = rangePair_strictlyContained[0]; + Range r2 = rangePair_strictlyContained[1]; + assertTrue(r1.strictlyContains(r2)); + assertFalse(r2.strictlyContains(r1)); + } + + @Test + void rangePair_touchingLineAndColumn_contains() { + Range r1 = rangePair_touchingLineAndColumn[0]; + Range r2 = rangePair_touchingLineAndColumn[1]; + assertFalse(r1.contains(r2)); + assertFalse(r2.contains(r1)); + } + + @Test + void rangePair_touchingLineAndColumn_strictlyContains() { + Range r1 = rangePair_touchingLineAndColumn[0]; + Range r2 = rangePair_touchingLineAndColumn[1]; + assertFalse(r1.strictlyContains(r2)); + assertFalse(r2.strictlyContains(r1)); + } + + @Test + void containsConsiderLines() { + Range r1 = Range.range(22, 9, 22, 29); + Range r2 = Range.range(26, 19, 26, 28); + assertFalse(r1.contains(r2)); + assertFalse(r2.contains(r1)); + } + + @Test + void rangePair_touchingLineAndColumn_overlapsAccountsForColumn_true() { + Range r1 = rangePair_touchingLineAndColumn[0]; + Range r2 = rangePair_touchingLineAndColumn[1]; + assertTrue(r1.overlapsWith(r2)); + assertTrue(r2.overlapsWith(r1)); + } + + @Test + void rangePair_touchingLineNotColumn_overlapsAccountsForColumn_false() { + Range r1 = rangePair_touchingLineNotColumn[0]; + Range r2 = rangePair_touchingLineNotColumn[1]; + assertFalse(r1.overlapsWith(r2)); + assertFalse(r2.overlapsWith(r1)); + } + + + @Test + void lineCountIsReturned() { + Range r1 = Range.range(1, 1, 5, 2); + assertEquals(5, r1.getLineCount()); + + Range r2 = Range.range(26, 5, 57, 6); + assertEquals(32, r2.getLineCount()); + } + + @Test + void arbitraryRange_containsItsBegin_true() { + Range r = arbitraryRange; + assertTrue(r.contains(r.begin)); + } + + @Test + void arbitraryRange_containsItsEnd_true() { + Range r = arbitraryRange; + assertTrue(r.contains(r.end)); + } + + @Test + void arbitraryRange_strictlyContainItsBegin_false() { + Range r = arbitraryRange; + assertFalse(r.strictlyContains(r.begin)); + } + + @Test + void arbitraryRange_strictlyContainItsEnd_false() { + Range r = arbitraryRange; + assertFalse(r.strictlyContains(r.end)); + } +@Test + void touchingLineColumnRangesOverlap() { + Range r1 = Range.range(1, 1, 3, 10); + Range r2 = Range.range(3, 10, 5, 10); + assertTrue(r1.overlapsWith(r2)); + assertTrue(r2.overlapsWith(r1)); + } + + @Test + void touchingLineNotColumnRangesDoNotOverlap() { + Range r1 = Range.range(1, 1, 3, 5); + Range r2 = Range.range(3, 10, 5, 10); + assertFalse(r1.overlapsWith(r2)); + assertFalse(r2.overlapsWith(r1)); + } + @Test + void rangePair_equalBeginEnd_overlap_true() { + Range r1 = rangePair_equalBeginEnd[0]; + Range r2 = rangePair_equalBeginEnd[1]; + assertTrue(r1.overlapsWith(r2)); + assertTrue(r2.overlapsWith(r1)); + } + + @Test + void rangePair_unrelated_overlap_false() { + Range r1 = rangePair_unrelated[0]; + Range r2 = rangePair_unrelated[1]; + assertFalse(r1.overlapsWith(r2)); + assertFalse(r2.overlapsWith(r1)); + } + + @Test + void rangePair_touchingLineAndColumn_overlap_false() { + Range r1 = rangePair_touchingLineAndColumn[0]; + Range r2 = rangePair_touchingLineAndColumn[1]; + assertTrue(r1.overlapsWith(r2)); + assertTrue(r2.overlapsWith(r1)); + } + + @Test + void rangePair_overlappingButNotContained_overlap_true() { + Range r1 = rangePair_overlappingButNotContained[0]; + Range r2 = rangePair_overlappingButNotContained[1]; + assertTrue(r1.overlapsWith(r2)); + assertTrue(r2.overlapsWith(r1)); + } + + @Test + void rangePair_strictlyContained_overlap_true() { + Range r1 = rangePair_strictlyContained[0]; + Range r2 = rangePair_strictlyContained[1]; + assertTrue(r1.overlapsWith(r2)); + assertTrue(r2.overlapsWith(r1)); + } + + @Test + void rangePair_is_before() { + Range r1 = Range.range(new Position(1,1), new Position(1,2)); + Range r2 = Range.range(new Position(1,3), new Position(1,4)); + assertTrue(r1.isBefore(r2)); + } + + @Test + void rangePair_is_not_before() { + Range r1 = Range.range(new Position(1,1), new Position(1,2)); + Range r2 = Range.range(new Position(1,3), new Position(1,4)); + Range r3 = Range.range(new Position(1,1), new Position(1,4)); + assertFalse(r2.isBefore(r1)); + assertFalse(r3.isBefore(r1)); + } + + @Test + void rangePair_is_after() { + Range r1 = Range.range(new Position(1,1), new Position(1,2)); + Range r2 = Range.range(new Position(1,3), new Position(1,4)); + assertTrue(r2.isAfter(r1)); + } + + @Test + void rangePair_is_not_after() { + Range r1 = Range.range(new Position(1,1), new Position(1,2)); + Range r2 = Range.range(new Position(1,3), new Position(1,4)); + Range r3 = Range.range(new Position(1,1), new Position(1,4)); + assertFalse(r1.isAfter(r2)); + assertFalse(r1.isAfter(r3)); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/TokenRangeTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/TokenRangeTest.java new file mode 100644 index 0000000..835839d --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/TokenRangeTest.java @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import org.junit.jupiter.api.Test; + +import java.util.Optional; + +import static com.github.javaparser.StaticJavaParser.parse; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class TokenRangeTest { + @Test + void toStringWorks() { + CompilationUnit cu = parse("class X {\n\tX(){\n// hello\n}\n}"); + assertEquals("X(){\n// hello\n}", cu.getClassByName("X").get().getDefaultConstructor().get().getTokenRange().get().toString()); + } + + @Test + void renumberRangesWorks() { + CompilationUnit cu = parse("class X {\n\tX(){\n// hello\n}\n}"); + + assertEquals("1,1-5/6,1-1/7,1-1/8,1-1/9,1-1/10,1-1/1,2-1/2,2-1/3,2-1/4,2-1/5,2-1/6,2-1/1,3-8/9,3-1/1,4-1/2,4-1/1,5-1/1,5-1/", makeRangesString(cu)); + + TokenRange tokenRange = cu.getTokenRange().get(); + tokenRange.getBegin().insertAfter(new JavaToken(1, "feif")); + tokenRange.getBegin().getNextToken().get().getNextToken().get().insert(new JavaToken(JavaToken.Kind.WINDOWS_EOL.getKind(), "\r\n")); + cu.recalculatePositions(); + + assertEquals("1,1-5/6,1-4/10,1-2/1,2-1/2,2-1/3,2-1/4,2-1/5,2-1/1,3-1/2,3-1/3,3-1/4,3-1/5,3-1/6,3-1/1,4-8/9,4-1/1,5-1/2,5-1/1,6-1/2,6-1/", makeRangesString(cu)); + } + + /** + * Make a compact String for comparing token range positions. + */ + private String makeRangesString(Node node) { + Optional token = node.getTokenRange().map(TokenRange::getBegin); + StringBuilder result = new StringBuilder(); + while (token.isPresent()) { + token = token.flatMap(t -> { + result.append(t.getRange().map(r -> + r.begin.column + "," + r.begin.line + "-" + + (r.end.column - r.begin.column + 1) + "/" + + ).orElse("?")); + return t.getNextToken(); + }); + } + return result.toString(); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/TokenTypesTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/TokenTypesTest.java new file mode 100644 index 0000000..bb25d74 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/TokenTypesTest.java @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.stmt.SwitchEntry; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.nio.file.Path; + +import static com.github.javaparser.StaticJavaParser.parse; +import static com.github.javaparser.utils.CodeGenerationUtils.mavenModuleRoot; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class TokenTypesTest { + + @Test + void everyTokenHasACategory() throws IOException { + final int tokenCount = GeneratedJavaParserConstants.tokenImage.length; + Path tokenTypesPath = mavenModuleRoot(JavaParserTest.class).resolve("../javaparser-core/src/main/java/com/github/javaparser/TokenTypes.java"); + CompilationUnit tokenTypesCu = parse(tokenTypesPath); + + // -1 to take off the default: case. + int switchEntries = tokenTypesCu.findAll(SwitchEntry.class).size() - 1; + + // The amount of "case XXX:" in TokenTypes.java should be equal to the amount of tokens JavaCC knows about: + assertEquals(tokenCount, switchEntries); + } + + @Test + void throwOnUnrecognisedTokenType() { + assertThrows(AssertionError.class, () -> { + TokenTypes.getCategory(-1); + }); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/UnicodeEscapeProcessingProviderTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/UnicodeEscapeProcessingProviderTest.java new file mode 100644 index 0000000..1b78054 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/UnicodeEscapeProcessingProviderTest.java @@ -0,0 +1,150 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Test case for {@link UnicodeEscapeProcessingProvider}. + */ +public class UnicodeEscapeProcessingProviderTest { + + @Test + void testUnicodeEscape() throws IOException { + assertEquals("13" + '\u12aA' + "98", new String(read("13\\u12aA98"))); + } + + @Test + void testEscapedUnicodeEscape() throws IOException { + assertEquals("13\\\\u12aA98", new String(read("13\\\\u12aA98"))); + } + + @Test + void testUnicodeEscapeWithMultipleUs() throws IOException { + assertEquals("13" + '\u12aA' + "98", new String(read("13\\uuuuuu12aA98"))); + } + + @Test + void testInputEndingInBackslash() throws IOException { + assertEquals("foobar\\", new String(read("foobar\\"))); + } + + @Test + void testInputEndingInBackslashU() throws IOException { + assertEquals("foobar\\u", new String(read("foobar\\u"))); + } + + @Test + void testInputEndingInBackslashUs() throws IOException { + assertEquals("foobar\\uuuuuu", new String(read("foobar\\uuuuuu"))); + } + + @Test + void testInputEndingInBackslashU1() throws IOException { + assertEquals("foobar\\uA", new String(read("foobar\\uA"))); + } + + @Test + void testInputEndingInBackslashU2() throws IOException { + assertEquals("foobar\\uAB", new String(read("foobar\\uAB"))); + } + + @Test + void testInputEndingInBackslashU3() throws IOException { + assertEquals("foobar\\uABC", new String(read("foobar\\uABC"))); + } + + @Test + void testInputEndingUnicodeEscape() throws IOException { + assertEquals("foobar\uABCD", new String(read("foobar\\uABCD"))); + } + + @Test + void testEmptyInput() throws IOException { + assertEquals("", new String(read(""))); + } + + @Test + void testBadUnicodeEscape0() throws IOException { + assertEquals("13\\ux", new String(read("13\\ux"))); + } + + @Test + void testBadUnicodeEscape1() throws IOException { + assertEquals("13\\u1x", new String(read("13\\u1x"))); + } + + @Test + void testBadUnicodeEscape2() throws IOException { + assertEquals("13\\u1Ax", new String(read("13\\u1Ax"))); + } + + @Test + void testBadUnicodeEscape3() throws IOException { + assertEquals("13\\u1ABx", new String(read("13\\u1ABx"))); + } + + @Test + void testBadUnicodeEscapeMultipleUs() throws IOException { + assertEquals("13\\uuuuuu1ABx", new String(read("13\\uuuuuu1ABx"))); + } + + @Test + void testPushBackWithFullBuffer() throws IOException { + assertEquals("12345678\\uuxxxxxxxxxxxxxxxxxxxxxxx", new String(read("12345678\\uuxxxxxxxxxxxxxxxxxxxxxxx"))); + } + + @Test + void testPushBackWithBufferShift() throws IOException { + assertEquals("12345678\\uuxx", new String(read("12345678\\uuxx"))); + } + + static String read(String source) throws IOException { + return process(provider(source)); + } + + static UnicodeEscapeProcessingProvider provider(String source) { + UnicodeEscapeProcessingProvider provider = new UnicodeEscapeProcessingProvider(10, + new StringProvider(source)); + return provider; + } + + static String process(UnicodeEscapeProcessingProvider provider) + throws IOException { + StringBuilder result = new StringBuilder(); + char[] buffer = new char[10]; + while (true) { + int direct = provider.read(buffer, 0, buffer.length); + if (direct < 0) { + break; + } + result.append(buffer, 0, direct); + } + + provider.close(); + + return result.toString(); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/AncestorDescendantTests.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/AncestorDescendantTests.java new file mode 100644 index 0000000..37123c2 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/AncestorDescendantTests.java @@ -0,0 +1,129 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.*; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.expr.VariableDeclarationExpr; +import org.junit.jupiter.api.Test; + +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.*; + +public class AncestorDescendantTests { + + @Test + void nodeIsNotAncestorOfItself() throws IOException { + JavaParser parser = new JavaParser(); + + Provider provider = Providers.resourceProvider("com/github/javaparser/range/A.java"); + assertNotNull(provider); + ParseResult parse = parser.parse(ParseStart.COMPILATION_UNIT, provider); + assertTrue(parse.isSuccessful()); + + VariableDeclarationExpr node = parse.getResult().get() + .getType(0) // class A + .getMember(0).asMethodDeclaration() // method foo() + .getBody().get().getStatement(0).asExpressionStmt() // int a = 42; + .getExpression().asVariableDeclarationExpr(); // a = 42 + + assertFalse(node.isAncestorOf(node)); + } + + @Test + void nodeIsNotDescendantOfItself() throws IOException { + JavaParser parser = new JavaParser(); + + Provider provider = Providers.resourceProvider("com/github/javaparser/range/A.java"); + assertNotNull(provider); + ParseResult parse = parser.parse(ParseStart.COMPILATION_UNIT, provider); + assertTrue(parse.isSuccessful()); + + VariableDeclarationExpr node = parse.getResult().get() + .getType(0) // class A + .getMember(0).asMethodDeclaration() // method foo() + .getBody().get().getStatement(0).asExpressionStmt() // int a = 42; + .getExpression().asVariableDeclarationExpr(); // a = 42 + + assertFalse(node.isDescendantOf(node)); + } + + @Test + void nodeInSameFileIsDescendantOfAncestor() throws IOException { + JavaParser parser = new JavaParser(); + + Provider provider = Providers.resourceProvider("com/github/javaparser/range/A.java"); + assertNotNull(provider); + ParseResult parse = parser.parse(ParseStart.COMPILATION_UNIT, provider); + assertTrue(parse.isSuccessful()); + + VariableDeclarationExpr superNode = parse.getResult().get() + .getType(0) // class A + .getMember(0).asMethodDeclaration() // method foo() + .getBody().get().getStatement(0).asExpressionStmt() // int a = 42; + .getExpression().asVariableDeclarationExpr(); // a = 42 + + Expression subNode = superNode.getVariable(0).getInitializer().get(); // 42 + + assertTrue(superNode.isAncestorOf(subNode)); + assertFalse(subNode.isAncestorOf(superNode)); + assertTrue(subNode.isDescendantOf(superNode)); + assertFalse(superNode.isDescendantOf(subNode)); + } + + @Test + void nodesInTwoDifferentFilesAreNotDescendantOrAncestorOfEachOther() throws IOException { + JavaParser parser = new JavaParser(); + + Provider providerA = Providers.resourceProvider("com/github/javaparser/range/A.java"); + assertNotNull(providerA); + ParseResult parseA = parser.parse(ParseStart.COMPILATION_UNIT, providerA); + assertTrue(parseA.isSuccessful()); + + Provider providerB = Providers.resourceProvider("com/github/javaparser/range/B.java"); + assertNotNull(providerB); + ParseResult parseB = parser.parse(ParseStart.COMPILATION_UNIT, providerB); + assertTrue(parseB.isSuccessful()); + + VariableDeclarationExpr superNodeA = parseA.getResult().get() + .getType(0) // class A + .getMember(0).asMethodDeclaration() // method foo() + .getBody().get().getStatement(0).asExpressionStmt() // int a = 42; + .getExpression().asVariableDeclarationExpr(); // a = 42 + + Expression subNodeA = superNodeA.getVariable(0).getInitializer().get(); // 42 + + VariableDeclarationExpr superNodeB = parseB.getResult().get() + .getType(0) // class B + .getMember(0).asMethodDeclaration() // method foo() + .getBody().get().getStatement(0).asExpressionStmt() // int b = 42; + .getExpression().asVariableDeclarationExpr(); // b = 42 + + Expression subNodeB = superNodeB.getVariable(0).getInitializer().get(); // 42 + + assertFalse(superNodeA.isAncestorOf(superNodeB)); + assertFalse(superNodeA.isDescendantOf(subNodeB)); + assertFalse(superNodeB.isAncestorOf(superNodeA)); + assertFalse(superNodeB.isDescendantOf(subNodeA)); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/CompilationUnitTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/CompilationUnitTest.java new file mode 100644 index 0000000..acd3778 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/CompilationUnitTest.java @@ -0,0 +1,109 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; + +import static com.github.javaparser.StaticJavaParser.parse; +import static com.github.javaparser.utils.CodeGenerationUtils.mavenModuleRoot; +import static org.junit.jupiter.api.Assertions.*; + +class CompilationUnitTest { + @Test + void issue578TheFirstCommentIsWithinTheCompilationUnit() { + CompilationUnit compilationUnit = parse("// This is my class, with my comment\n" + + "class A {\n" + + " static int a;\n" + + "}"); + + assertEquals(1, compilationUnit.getAllContainedComments().size()); + } + + @Test + void testGetSourceRoot() throws IOException { + Path sourceRoot = mavenModuleRoot(CompilationUnitTest.class).resolve(Paths.get("src", "test", "resources")).normalize(); + Path testFile = sourceRoot.resolve(Paths.get("com", "github", "javaparser", "storage", "Z.java")); + + CompilationUnit cu = parse(testFile); + Path sourceRoot1 = cu.getStorage().get().getSourceRoot(); + assertEquals(sourceRoot, sourceRoot1); + } + + @Test + void testGetSourceRootWithBadPackageDeclaration() { + assertThrows(RuntimeException.class, () -> { + Path sourceRoot = mavenModuleRoot(CompilationUnitTest.class).resolve(Paths.get("src", "test", "resources")).normalize(); + Path testFile = sourceRoot.resolve(Paths.get("com", "github", "javaparser", "storage", "A.java")); + CompilationUnit cu = parse(testFile); + cu.getStorage().get().getSourceRoot(); + }); + + } + + @Test + void testGetSourceRootInDefaultPackage() throws IOException { + Path sourceRoot = mavenModuleRoot(CompilationUnitTest.class).resolve(Paths.get("src", "test", "resources", "com", "github", "javaparser", "storage")).normalize(); + Path testFile = sourceRoot.resolve(Paths.get("B.java")); + + CompilationUnit cu = parse(testFile); + Path sourceRoot1 = cu.getStorage().get().getSourceRoot(); + assertEquals(sourceRoot, sourceRoot1); + } + + @Test + void testGetPrimaryTypeName() throws IOException { + Path sourceRoot = mavenModuleRoot(CompilationUnitTest.class).resolve(Paths.get("src", "test", "resources")).normalize(); + Path testFile = sourceRoot.resolve(Paths.get("com", "github", "javaparser", "storage", "PrimaryType.java")); + CompilationUnit cu = parse(testFile); + + assertEquals("PrimaryType", cu.getPrimaryTypeName().get()); + } + + @Test + void testNoPrimaryTypeName() { + CompilationUnit cu = parse("class PrimaryType{}"); + + assertFalse(cu.getPrimaryTypeName().isPresent()); + } + @Test + void testGetPrimaryType() throws IOException { + Path sourceRoot = mavenModuleRoot(CompilationUnitTest.class).resolve(Paths.get("src", "test", "resources")).normalize(); + Path testFile = sourceRoot.resolve(Paths.get("com", "github", "javaparser", "storage", "PrimaryType.java")); + CompilationUnit cu = parse(testFile); + + assertEquals("PrimaryType", cu.getPrimaryType().get().getNameAsString()); + } + + @Test + void testNoPrimaryType() throws IOException { + Path sourceRoot = mavenModuleRoot(CompilationUnitTest.class).resolve(Paths.get("src", "test", "resources")).normalize(); + Path testFile = sourceRoot.resolve(Paths.get("com", "github", "javaparser", "storage", "PrimaryType2.java")); + CompilationUnit cu = parse(testFile); + + assertFalse(cu.getPrimaryType().isPresent()); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/DataKeyTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/DataKeyTest.java new file mode 100644 index 0000000..06cb874 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/DataKeyTest.java @@ -0,0 +1,86 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.ast.expr.SimpleName; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class DataKeyTest { + private static final DataKey ABC = new DataKey() { + }; + private static final DataKey DEF = new DataKey() { + }; + private static final DataKey> LISTY = new DataKey>() { + }; + private static final DataKey> DING = new DataKey>() { + }; + + @Test + void addAFewKeysAndSeeIfTheyAreStoredCorrectly() { + Node node = new SimpleName(); + + node.setData(ABC, "Hurray!"); + node.setData(LISTY, Arrays.asList("a", "b")); + node.setData(ABC, "w00t"); + + assertThat(node.getData(ABC)).contains("w00t"); + assertThat(node.getData(LISTY)).containsExactly("a", "b"); + assertThat(node.containsData(ABC)).isTrue(); + assertThat(node.containsData(LISTY)).isTrue(); + assertThat(node.containsData(DING)).isFalse(); + } + + @Test + void removeWorks() { + Node node = new SimpleName(); + node.setData(ABC, "Hurray!"); + + node.removeData(ABC); + + assertThat(node.containsData(ABC)).isFalse(); + } + + @Test + void aNonExistentKeyThrowsAnException() { + Node node = new SimpleName(); + + assertThrows(IllegalStateException.class, () -> node.getData(DING)); + } + + @Test + void cloningCopiesData() { + Node node = new SimpleName(); + node.setData(ABC, "ABC!"); + node.setData(DEF, "DEF!"); + + Node clone = node.clone(); + assertEquals("ABC!", clone.getData(ABC)); + assertEquals("DEF!", clone.getData(DEF)); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/FindNodeTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/FindNodeTest.java new file mode 100644 index 0000000..260fe46 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/FindNodeTest.java @@ -0,0 +1,107 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.ast.expr.MethodCallExpr; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.ast.stmt.TryStmt; +import org.junit.jupiter.api.Test; + +import java.util.function.Predicate; + +import static com.github.javaparser.StaticJavaParser.parse; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Some tests for finding descendant and ancestor nodes. + */ +class FindNodeTest { + @Test + void testFindFirst() { + CompilationUnit cu = parse( + "class Foo {\n" + + " void foo() {\n" + + " try {\n" + + " } catch (Exception e) {\n" + + " } finally {\n" + + " try {\n" + + " } catch (Exception e) {\n" + + " foo();\n" + + " } finally {\n" + + " }\n" + + " }\n" + + "\n" + + " }\n" + + "}\n"); + + // find the method call expression foo() + MethodCallExpr actual = cu.findFirst(MethodCallExpr.class).orElse(null); + + MethodCallExpr expected = cu.getType(0).getMember(0) + .asMethodDeclaration().getBody().get().getStatement(0) + .asTryStmt().getFinallyBlock().get().getStatement(0) + .asTryStmt().getCatchClauses().get(0).getBody().getStatement(0) + .asExpressionStmt().getExpression() + .asMethodCallExpr(); + + assertEquals(expected, actual); + } + + @Test + void testFindAncestralFinallyBlock() { + CompilationUnit cu = parse( + "class Foo {\n" + + " void foo() {\n" + + " try {\n" + + " } catch (Exception e) {\n" + + " } finally {\n" + + " try {\n" + + " } catch (Exception e) {\n" + + " foo();\n" + + " } finally {\n" + + " }\n" + + " }\n" + + "\n" + + " }\n" + + "}\n"); + + // find the method call expression foo() + MethodCallExpr methodCallExpr = cu.findFirst(MethodCallExpr.class).orElse(null); + + // find the finally block that the method call expression foo() is in + Predicate predicate = (bs) -> { + if (bs.getParentNode().isPresent() && bs.getParentNode().get() instanceof TryStmt) { + TryStmt ancestralTryStmt = (TryStmt) bs.getParentNode().get(); + return bs == ancestralTryStmt.getFinallyBlock().orElse(null); + } + return false; + }; + BlockStmt actual = methodCallExpr.findAncestor(predicate, BlockStmt.class).orElse(null); + + BlockStmt expected = cu.getType(0).getMember(0) + .asMethodDeclaration().getBody().get().getStatement(0) + .asTryStmt().getFinallyBlock().get(); + + assertEquals(expected, actual); + } +} + diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/ListObservationTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/ListObservationTest.java new file mode 100644 index 0000000..3dcea75 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/ListObservationTest.java @@ -0,0 +1,250 @@ +/* + * Copyright (C) 2013-2024 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; + +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.FieldDeclaration; +import com.github.javaparser.ast.expr.SimpleName; +import com.github.javaparser.ast.observer.AstObserver; +import com.github.javaparser.ast.observer.ObservableProperty; +import com.github.javaparser.ast.type.PrimitiveType; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +import static com.github.javaparser.StaticJavaParser.parse; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +public class ListObservationTest { + + private FieldDeclaration createIntField(String name) { + return new FieldDeclaration(new NodeList<>(), PrimitiveType.intType(), name); + } + + private AstObserver createObserver(List changes) { + return new AstObserver() { + @Override + public void propertyChange(Node observedNode, ObservableProperty property, Object oldValue, Object newValue) { + changes.add(String.format("change of property %s for %s: from '%s' to '%s'", property, observedNode, oldValue, newValue)); + } + + @Override + public void parentChange(Node observedNode, Node previousParent, Node newParent) { + changes.add(String.format("setting parent for %s: was %s, now is %s", observedNode, previousParent, newParent)); + } + + @Override + public void listChange(NodeList observedNode, ListChangeType type, int index, Node nodeAddedOrRemoved) { + changes.add(String.format("'%s' %s in list at %d", nodeAddedOrRemoved, type, index)); + } + + @Override + public void listReplacement(NodeList observedNode, int index, Node oldNode, Node newNode) { + changes.add(String.format("'%s' %s in list at %d", oldNode, ListChangeType.REMOVAL, index)); + changes.add(String.format("'%s' %s in list at %d", newNode, ListChangeType.ADDITION, index)); + } + }; + } + @Test + void addAllWithoutIndex() { + List changes = new LinkedList<>(); + String code = "class A { void foo(int p) { }}"; + CompilationUnit cu = parse(code); + ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get(); + cd.getMembers().register(createObserver(changes)); + + cd.getMembers().addAll(Arrays.asList(createIntField("a"), createIntField("b"), createIntField("c"))); + assertEquals(Arrays.asList("'int a;' ADDITION in list at 1", + "'int b;' ADDITION in list at 2", + "'int c;' ADDITION in list at 3"), changes); + } + + @Test + void addAllWithIndex() { + List changes = new LinkedList<>(); + String code = "class A { void foo(int p) { }}"; + CompilationUnit cu = parse(code); + ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get(); + cd.getMembers().register(createObserver(changes)); + + cd.getMembers().addAll(0, Arrays.asList(createIntField("a"), createIntField("b"), createIntField("c"))); + assertEquals(Arrays.asList("'int a;' ADDITION in list at 0", + "'int b;' ADDITION in list at 1", + "'int c;' ADDITION in list at 2"), changes); + } + + @Test + void clear() { + List changes = new LinkedList<>(); + String code = "class A { int a; int b; int c; }"; + CompilationUnit cu = parse(code); + ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get(); + cd.getMembers().register(createObserver(changes)); + + cd.getMembers().clear(); + assertEquals(Arrays.asList("'int a;' REMOVAL in list at 0", + "'int b;' REMOVAL in list at 0", + "'int c;' REMOVAL in list at 0"), changes); + } + + @Test + void set() { + List changes = new LinkedList<>(); + String code = "class A { int a; int b; int c; }"; + CompilationUnit cu = parse(code); + ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get(); + cd.getMembers().register(createObserver(changes)); + + cd.getMembers().set(1, createIntField("d")); + assertEquals(Arrays.asList("'int b;' REMOVAL in list at 1", + "'int d;' ADDITION in list at 1"), changes); + } + + @Test + void removeNode() { + List changes = new LinkedList<>(); + String code = "class A { int a; int b; int c; int d; int e; }"; + CompilationUnit cu = parse(code); + ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get(); + cd.getMembers().register(createObserver(changes)); + + cd.getMembers().remove(cd.getFieldByName("c").get()); + assertThat(changes).containsExactlyInAnyOrder("'int c;' REMOVAL in list at 2"); + } + + @Test + void removeFirstNode() { + List changes = new LinkedList<>(); + String code = "class A { int a; int b; int c; int d; int e; }"; + CompilationUnit cu = parse(code); + ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get(); + cd.getMembers().register(createObserver(changes)); + + cd.getMembers().removeFirst(); + assertThat(changes).containsExactlyInAnyOrder("'int a;' REMOVAL in list at 0"); + assertEquals(cd.getMembers().size(), 4); + + for (int i = 3; i >= 0; i--) { + assertNotNull(cd.getMembers().removeFirst()); + assertEquals(cd.getMembers().size(), i); + } + + assertEquals(cd.getMembers().size(), 0); + } + + @Test + void removeLastNode() { + List changes = new LinkedList<>(); + String code = "class A { int a; int b; int c; int d; int e; }"; + CompilationUnit cu = parse(code); + ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get(); + cd.getMembers().register(createObserver(changes)); + + cd.getMembers().removeLast(); + assertThat(changes).containsExactlyInAnyOrder("'int e;' REMOVAL in list at 4"); + assertEquals(cd.getMembers().size(), 4); + + for (int i = 3; i >= 0; i--) { + assertNotNull(cd.getMembers().removeLast()); + assertEquals(cd.getMembers().size(), i); + } + + assertEquals(cd.getMembers().size(), 0); + } + + @Test + void removeObject() { + List changes = new LinkedList<>(); + String code = "class A { int a; int b; int c; int d; int e; }"; + CompilationUnit cu = parse(code); + ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get(); + cd.getMembers().register(createObserver(changes)); + + cd.getMembers().remove("hi"); + assertThat(changes).isEmpty(); + } + + @Test + void removeAll() { + List changes = new LinkedList<>(); + String code = "class A { int a; int b; int c; int d; int e; }"; + CompilationUnit cu = parse(code); + ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get(); + cd.getMembers().register(createObserver(changes)); + + cd.getMembers().removeAll(Arrays.asList(cd.getFieldByName("b").get(), "foo", cd.getFieldByName("d").get())); + assertThat(changes).containsExactlyInAnyOrder( + "'int b;' REMOVAL in list at 1", + "'int d;' REMOVAL in list at 2"); + } + + @Test + void retainAll() { + List changes = new LinkedList<>(); + String code = "class A { int a; int b; int c; int d; int e; }"; + CompilationUnit cu = parse(code); + ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get(); + cd.getMembers().register(createObserver(changes)); + + cd.getMembers().retainAll(Arrays.asList(cd.getFieldByName("b").get(), "foo", cd.getFieldByName("d").get())); + assertThat(changes).containsExactlyInAnyOrder( + "'int a;' REMOVAL in list at 0", + "'int c;' REMOVAL in list at 1", + "'int e;' REMOVAL in list at 2"); + } + + @Test + void replaceAll() { + List changes = new LinkedList<>(); + String code = "class A { int a; int b; int c; }"; + CompilationUnit cu = parse(code); + ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get(); + cd.getMembers().register(createObserver(changes)); + + cd.getMembers().replaceAll(bodyDeclaration -> { + FieldDeclaration clone = (FieldDeclaration) bodyDeclaration.clone(); + SimpleName id = clone.getVariable(0).getName(); + id.setIdentifier(id.getIdentifier().toUpperCase()); + return clone; + }); + assertThat(changes).containsExactlyInAnyOrder( + "'int a;' REMOVAL in list at 0", "'int A;' ADDITION in list at 0", + "'int b;' REMOVAL in list at 1", "'int B;' ADDITION in list at 1", + "'int c;' REMOVAL in list at 2", "'int C;' ADDITION in list at 2"); + } + + @Test + void removeIf() { + List changes = new LinkedList<>(); + String code = "class A { int a; int longName; int c; }"; + CompilationUnit cu = parse(code); + ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get(); + cd.getMembers().register(createObserver(changes)); + + cd.getMembers().removeIf(m -> ((FieldDeclaration) m).getVariable(0).getName().getIdentifier().length() > 3); + assertThat(changes).containsExactlyInAnyOrder("'int longName;' REMOVAL in list at 1"); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/NodeListTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/NodeListTest.java new file mode 100644 index 0000000..09868e6 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/NodeListTest.java @@ -0,0 +1,432 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.observer.AstObserver; +import com.github.javaparser.ast.observer.ObservableProperty; +import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest; +import com.github.javaparser.printer.lexicalpreservation.LexicalPreservingPrinter; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +import java.util.*; + +import static com.github.javaparser.ast.NodeList.nodeList; +import static org.junit.jupiter.api.Assertions.*; + +class NodeListTest extends AbstractLexicalPreservingTest { + + @Test + void replace() { + final NodeList list = nodeList(new Name("a"), new Name("b"), new Name("c")); + + final boolean replaced = list.replace(new Name("b"), new Name("z")); + + assertTrue(replaced); + assertEquals(3, list.size()); + assertEquals("a", list.get(0).asString()); + assertEquals("z", list.get(1).asString()); + assertEquals("c", list.get(2).asString()); + } + + @Test + void toStringTest() { + final NodeList list = nodeList(new Name("abc"), new Name("bcd"), new Name("cde")); + + assertEquals(3, list.size()); + assertEquals("[abc, bcd, cde]", list.toString()); + } + + @Test + void addFirst() { + final NodeList list = nodeList(new Name("abc"), new Name("bcd"), new Name("cde")); + + list.addFirst(new Name("xxx")); + + assertEquals(4, list.size()); + assertEquals("[xxx, abc, bcd, cde]", list.toString()); + } + + @Test + void addLast() { + final NodeList list = nodeList(new Name("abc"), new Name("bcd"), new Name("cde")); + + list.addLast(new Name("xxx")); + + assertEquals(4, list.size()); + assertEquals("[abc, bcd, cde, xxx]", list.toString()); + } + + @Test + void addBefore() { + Name n = new Name("bcd"); + final NodeList list = nodeList(new Name("abc"), n, new Name("cde")); + + list.addBefore(new Name("xxx"), n); + + assertEquals(4, list.size()); + assertEquals("[abc, xxx, bcd, cde]", list.toString()); + } + + @Test + void addAfter() { + Name n = new Name("bcd"); + final NodeList list = nodeList(new Name("abc"), n, new Name("cde")); + + list.addAfter(new Name("xxx"), n); + + assertEquals(4, list.size()); + assertEquals("[abc, bcd, xxx, cde]", list.toString()); + } + + @Test + void addBeforeFirst() { + Name abc = new Name("abc"); + final NodeList list = nodeList(abc, new Name("bcd"), new Name("cde")); + + list.addBefore(new Name("xxx"), abc); + + assertEquals(4, list.size()); + assertEquals("[xxx, abc, bcd, cde]", list.toString()); + } + + @Test + void addAfterLast() { + Name cde = new Name("cde"); + final NodeList list = nodeList(new Name("abc"), new Name("bcd"), cde); + + list.addAfter(new Name("xxx"), cde); + + assertEquals(4, list.size()); + assertEquals("[abc, bcd, cde, xxx]", list.toString()); + } + + + @Test + public void getFirstWhenEmpty() { + final NodeList list = nodeList(); + + Optional first = list.getFirst(); + + assertFalse(first.isPresent()); + assertEquals("Optional.empty", first.toString()); + } + + @Test + public void getFirstWhenNonEmpty() { + final NodeList list = nodeList(new Name("abc"), new Name("bcd"), new Name("cde")); + + Optional first = list.getFirst(); + + assertTrue(first.isPresent()); + assertEquals("Optional[abc]", first.toString()); + } + + @Test + public void getLastWhenEmpty() { + final NodeList list = nodeList(); + + Optional last = list.getLast(); + + assertFalse(last.isPresent()); + assertEquals("Optional.empty", last.toString()); + } + + @Test + public void getLastWhenNonEmpty() { + final NodeList list = nodeList(new Name("abc"), new Name("bcd"), new Name("cde")); + + Optional last = list.getLast(); + + assertTrue(last.isPresent()); + assertEquals("Optional[cde]", last.toString()); + } + + @Nested + class IteratorTest { + + @Nested + class ObserversTest { + NodeList list; + ListIterator iterator; + + List propertyChanges; + List parentChanges; + List listChanges; + List listReplacements; + AstObserver testObserver = new AstObserver() { + @Override + public void propertyChange(Node observedNode, ObservableProperty property, Object oldValue, Object newValue) { + propertyChanges.add(String.format("%s.%s changed from %s to %s", observedNode.getClass().getSimpleName(), property.name().toLowerCase(), oldValue, newValue)); + } + + @Override + public void parentChange(Node observedNode, Node previousParent, Node newParent) { + parentChanges.add(String.format("%s 's parent changed from %s to %s", observedNode.getClass().getSimpleName(), previousParent, newParent)); + } + + @Override + public void listChange(NodeList observedNode, ListChangeType type, int index, Node nodeAddedOrRemoved) { + listChanges.add(String.format("%s %s to/from %s at position %d", nodeAddedOrRemoved.getClass().getSimpleName(), type.name(), observedNode.getClass().getSimpleName(), index)); + } + + @Override + public void listReplacement(NodeList observedNode, int index, Node oldNode, Node newNode) { + listReplacements.add(String.format("%s replaced within %s at position %d", newNode.getClass().getSimpleName(), observedNode.getClass().getSimpleName(), index)); + } + + }; + + @BeforeEach + void pre() { + list = nodeList(); + list.register(testObserver); + iterator = list.listIterator(); + + propertyChanges = new ArrayList<>(); + parentChanges = new ArrayList<>(); + listChanges = new ArrayList<>(); + listReplacements = new ArrayList<>(); + } + + @Test + void whenAdd() { + assertEquals(0, propertyChanges.size()); + assertEquals(0, parentChanges.size()); + assertEquals(0, listChanges.size()); + assertEquals(0, listReplacements.size()); + + iterator.add(new Name("abc")); + + assertEquals(0, propertyChanges.size()); + assertEquals(0, parentChanges.size()); + assertEquals(1, listChanges.size()); + assertEquals(0, listReplacements.size()); + + assertEquals("Name ADDITION to/from NodeList at position 0", listChanges.get(0)); + } + + @Test + void whenRemove() { + iterator.add(new Name("abc")); + + assertEquals(0, propertyChanges.size()); + assertEquals(0, parentChanges.size()); + assertEquals(1, listChanges.size()); + assertEquals(0, listReplacements.size()); + + iterator.previous(); + iterator.remove(); + + assertEquals(0, propertyChanges.size()); + assertEquals(0, parentChanges.size()); + assertEquals(2, listChanges.size()); + assertEquals(0, listReplacements.size()); + + assertEquals("Name ADDITION to/from NodeList at position 0", listChanges.get(0)); + assertEquals("Name REMOVAL to/from NodeList at position 0", listChanges.get(1)); + } + + @Test + void whenSet() { + iterator.add(new Name("abc")); + + assertEquals(0, propertyChanges.size()); + assertEquals(0, parentChanges.size()); + assertEquals(1, listChanges.size()); + assertEquals(0, listReplacements.size()); + + iterator.previous(); + iterator.set(new Name("xyz")); + + assertEquals(0, propertyChanges.size()); + assertEquals(0, parentChanges.size()); + assertEquals(1, listChanges.size()); + assertEquals(1, listReplacements.size()); + + assertEquals("Name ADDITION to/from NodeList at position 0", listChanges.get(0)); + assertEquals("Name replaced within NodeList at position 0", listReplacements.get(0)); + } + + + @Test + void usageTest() { + final String REFERENCE_TO_BE_DELETED = "bad"; + considerCode("" + + "@MyAnnotation(myElements = {\"good\", \"bad\", \"ugly\"})\n" + + "public final class MyClass {\n" + + "}"); + String expected = "" + + "@MyAnnotation(myElements = {\"good\", \"ugly\"})\n" + + "public final class MyClass {\n" + + "}"; + + List annotations = cu.findAll(NormalAnnotationExpr.class); + + annotations.forEach(annotation -> { + // testcase, per https://github.com/javaparser/javaparser/issues/2936#issuecomment-731370505 + MemberValuePair mvp = annotation.getPairs().get(0); + Expression value = mvp.getValue(); + if ((value instanceof ArrayInitializerExpr)) { + NodeList myElements = ((ArrayInitializerExpr) value).getValues(); + + for (Iterator iterator = myElements.iterator(); iterator.hasNext(); ) { + Node elt = iterator.next(); + { + String nameAsString = ((StringLiteralExpr) elt).asString(); + if (REFERENCE_TO_BE_DELETED.equals(nameAsString)) + iterator.remove(); + } + } + } + }); + + assertEquals(expected, LexicalPreservingPrinter.print(cu)); + } + } + + @Nested + class AddRemoveListIteratorTest { + NodeList list; + ListIterator iterator; + + @BeforeEach + void pre() { + list = nodeList(); + iterator = list.listIterator(); + } + + @Test + void whenAdd() { + assertFalse(iterator.hasNext()); + assertFalse(iterator.hasPrevious()); + // Note that the element is added before the current cursor, thus is accessible via "previous" + iterator.add(new Name("abc")); + assertFalse(iterator.hasNext()); + assertTrue(iterator.hasPrevious()); + } + + } + + @Nested + class EmptyIteratorTest { + NodeList list; + ListIterator iterator; + + @BeforeEach + void pre() { + list = nodeList(); + iterator = list.listIterator(); + } + + @Test + void whenNext() { + assertThrows(NoSuchElementException.class, () -> { + iterator.next(); + }); + } + + @Test + void whenHasNext() { + assertFalse(iterator.hasNext()); + } + + @Test + void whenAdd() { + assertFalse(iterator.hasNext()); + assertFalse(iterator.hasPrevious()); + // Note that the element is added before the current cursor, thus is accessible via "previous" + iterator.add(new Name("abc")); + assertFalse(iterator.hasNext()); + assertTrue(iterator.hasPrevious()); + } + + @Test + void whenSet() { + assertFalse(iterator.hasNext()); + assertFalse(iterator.hasPrevious()); + assertThrows(IllegalArgumentException.class, () -> { + // Note that the cursor is initially at -1, thus not possible to set the value here + iterator.set(new Name("abc")); + }); + // Assert that next/previous are still empty + assertFalse(iterator.hasNext()); + assertFalse(iterator.hasPrevious()); + } + + } + + @Nested + class SingleItemIteratorTest { + NodeList list; + Iterator iterator; + + @BeforeEach + void pre() { + list = nodeList(new Name("abc")); + iterator = list.iterator(); + } + + @Test + void whenNext() { + Name next = iterator.next(); + assertNotNull(next); + } + + @Test + void whenHasNext() { + assertTrue(iterator.hasNext()); + } + + @Test + void whenHasNextRepeated() { + assertTrue(iterator.hasNext()); + assertTrue(iterator.hasNext()); + assertTrue(iterator.hasNext()); + assertTrue(iterator.hasNext()); + } + + @Test + void whenHasNextThenNext() { + assertTrue(iterator.hasNext()); + iterator.next(); + assertFalse(iterator.hasNext()); + assertThrows(NoSuchElementException.class, () -> { + iterator.next(); + }); + } + + @Test + void whenRemove() { + Name current = iterator.next(); + iterator.remove(); + assertFalse(iterator.hasNext()); + assertThrows(NoSuchElementException.class, () -> { + iterator.next(); + }); + } + + } + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/NodePositionTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/NodePositionTest.java new file mode 100644 index 0000000..ebf36af --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/NodePositionTest.java @@ -0,0 +1,95 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParseStart; +import com.github.javaparser.Providers; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.util.LinkedList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class NodePositionTest { + + private List getAllNodes(Node node) { + List nodes = new LinkedList<>(); + nodes.add(node); + node.getChildNodes().forEach(c -> nodes.addAll(getAllNodes(c))); + return nodes; + } + + @Test + void packageProtectedClassShouldHavePositionSet() throws IOException { + ensureAllNodesHaveValidBeginPosition("class A { }"); + } + + @Test + void packageProtectedInterfaceShouldHavePositionSet() throws IOException { + ensureAllNodesHaveValidBeginPosition("interface A { }"); + } + + @Test + void packageProtectedEnumShouldHavePositionSet() throws IOException { + ensureAllNodesHaveValidBeginPosition("enum A { }"); + } + + @Test + void packageProtectedAnnotationShouldHavePositionSet() throws IOException { + ensureAllNodesHaveValidBeginPosition("@interface A { }"); + } + + @Test + void packageProtectedFieldShouldHavePositionSet() throws IOException { + ensureAllNodesHaveValidBeginPosition("public class A { int i; }"); + } + + @Test + void packageProtectedMethodShouldHavePositionSet() throws IOException { + ensureAllNodesHaveValidBeginPosition("public class A { void foo() {} }"); + } + + @Test + void packageProtectedConstructorShouldHavePositionSet() throws IOException { + ensureAllNodesHaveValidBeginPosition("public class A { A() {} }"); + } + + private void ensureAllNodesHaveValidBeginPosition(final String code) { + ParseResult res = new JavaParser().parse(ParseStart.COMPILATION_UNIT, Providers.provider(code)); + assertTrue(res.getProblems().isEmpty()); + + CompilationUnit cu = res.getResult().get(); + getAllNodes(cu).forEach(n -> { + assertNotNull(n.getRange(), String.format("There should be no node without a range: %s (class: %s)", + n, n.getClass().getCanonicalName())); + if (n.getBegin().get().line == 0 && !n.toString().isEmpty()) { + throw new IllegalArgumentException("There should be no node at line 0: " + n + " (class: " + + n.getClass().getCanonicalName() + ")"); + } + }); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/NodeTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/NodeTest.java new file mode 100644 index 0000000..417c14b --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/NodeTest.java @@ -0,0 +1,155 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.FieldDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.body.VariableDeclarator; +import com.github.javaparser.ast.comments.BlockComment; +import com.github.javaparser.ast.comments.Comment; +import com.github.javaparser.ast.comments.JavadocComment; +import com.github.javaparser.ast.comments.LineComment; +import com.github.javaparser.ast.stmt.ExpressionStmt; +import com.github.javaparser.ast.type.PrimitiveType; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.StaticJavaParser.parse; +import static com.github.javaparser.utils.Utils.SYSTEM_EOL; +import static org.junit.jupiter.api.Assertions.*; + +class NodeTest { + @Test + void removeOrphanCommentPositiveCase() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(new NodeList<>(), false, "A"); + Comment c = new LineComment("A comment"); + decl.addOrphanComment(c); + assertEquals(1, decl.getOrphanComments().size()); + assertSame(decl, c.getParentNode().get()); + assertTrue(decl.removeOrphanComment(c)); + assertEquals(0, decl.getOrphanComments().size()); + assertFalse(c.getParentNode().isPresent()); + } + + @Test + void removeOrphanCommentNegativeCase() { + ClassOrInterfaceDeclaration aClass = new ClassOrInterfaceDeclaration(new NodeList<>(), false, "A"); + FieldDeclaration aField = new FieldDeclaration(new NodeList<>(), new VariableDeclarator(PrimitiveType.intType(), "f")); + aClass.getMembers().add(aField); + Comment c = new LineComment("A comment"); + aField.addOrphanComment(c); + // the comment is an orphan comment of the field, so trying to remove it on the class should not work + assertFalse(aClass.removeOrphanComment(c)); + assertEquals(1, aField.getOrphanComments().size()); + assertTrue(c.getParentNode().isPresent()); + } + + @Test + void hasJavaDocCommentPositiveCaseWithSetJavaDocComment() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(new NodeList<>(), false, "Foo"); + decl.setJavadocComment("A comment"); + assertTrue(decl.hasJavaDocComment()); + } + + @Test + void hasJavaDocCommentPositiveCaseWithSetComment() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(new NodeList<>(), false, "Foo"); + decl.setComment(new JavadocComment("A comment")); + assertTrue(decl.hasJavaDocComment()); + } + + @Test + void hasJavaDocCommentNegativeCaseNoComment() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(new NodeList<>(), false, "Foo"); + assertFalse(decl.hasJavaDocComment()); + } + + @Test + void hasJavaDocCommentNegativeCaseLineComment() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(new NodeList<>(), false, "Foo"); + decl.setComment(new LineComment("foo")); + assertFalse(decl.hasJavaDocComment()); + } + + @Test + void hasJavaDocCommentNegativeCaseBlockComment() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(new NodeList<>(), false, "Foo"); + decl.setComment(new BlockComment("foo")); + assertFalse(decl.hasJavaDocComment()); + } + + @Test + void findCompilationUnitOfCommentNode() { + CompilationUnit cu = parse("class X {\n" + + " void x() {\n" + + " // this is a comment\n" + + " foo();\n" + + " }\n" + + "}\n"); + + Comment comment = cu.getType(0).getMember(0) + .asMethodDeclaration().getBody().get() + .getStatement(0).getComment().get(); + + assertTrue(comment.findCompilationUnit().isPresent()); + } + + @Test + void findCompilationUnitOfOrphanCommentNode() { + CompilationUnit cu = parse("class X {\n" + + " void x() {\n" + + " // this is a comment\n" + + " }\n" + + "}\n"); + + Comment comment = cu.getType(0).getMember(0) + .asMethodDeclaration().getBody().get() + .getOrphanComments().get(0); + + assertTrue(comment.findCompilationUnit().isPresent()); + } + + @Test + void removeAllOnRequiredProperty() { + CompilationUnit cu = parse("class X{ void x(){}}"); + MethodDeclaration methodDeclaration = cu.getType(0).getMethods().get(0); + methodDeclaration.getName().removeForced(); + // Name is required, so to remove it the whole method is removed. + assertEquals(String.format("class X {%1$s}%1$s", SYSTEM_EOL), cu.toString()); + } + + @Test + void removingTheSecondOfAListOfIdenticalStatementsDoesNotMessUpTheParents() { + CompilationUnit unit = parse(String.format("public class Example {%1$s" + + " public static void example() {%1$s" + + " boolean swapped;%1$s" + + " swapped=false;%1$s" + + " swapped=false;%1$s" + + " }%1$s" + + "}%1$s", SYSTEM_EOL)); + // remove the second swapped=false + ExpressionStmt target = unit.findAll(ExpressionStmt.class).get(2); + target.remove(); + // This will throw an exception if the parents are bad. + unit.toString(); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/ObservationTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/ObservationTest.java new file mode 100644 index 0000000..c0bfd89 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/ObservationTest.java @@ -0,0 +1,232 @@ +/* + * Copyright (C) 2013-2024 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; + +import com.github.javaparser.ast.observer.AstObserver; +import com.github.javaparser.ast.observer.AstObserverAdapter; +import com.github.javaparser.ast.observer.ObservableProperty; +import com.github.javaparser.ast.type.PrimitiveType; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static com.github.javaparser.StaticJavaParser.parse; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class ObservationTest { + + @Test + void registerSubTree() { + String code = "class A { int f; void foo(int p) { return 'z'; }}"; + CompilationUnit cu = parse(code); + List changes = new ArrayList<>(); + AstObserver observer = new AstObserverAdapter() { + @Override + public void propertyChange(Node observedNode, ObservableProperty property, Object oldValue, Object newValue) { + changes.add(String.format("%s.%s changed from %s to %s", observedNode.getClass().getSimpleName(), property.name().toLowerCase(), oldValue, newValue)); + } + }; + cu.registerForSubtree(observer); + + assertThat(changes).isEmpty(); + + cu.getClassByName("A").get().setName("MyCoolClass"); + assertThat(changes).containsExactlyInAnyOrder("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass"); + + cu.getClassByName("MyCoolClass").get().getFieldByName("f").get().getVariable(0).setType(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN)); + assertThat(changes).containsExactlyInAnyOrder("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass", + "FieldDeclaration.maximum_common_type changed from int to boolean", + "VariableDeclarator.type changed from int to boolean"); + + cu.getClassByName("MyCoolClass").get().getMethodsByName("foo").get(0).getParameterByName("p").get().setName("myParam"); + assertThat(changes).containsExactlyInAnyOrder("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass", + "FieldDeclaration.maximum_common_type changed from int to boolean", + "VariableDeclarator.type changed from int to boolean", + "Parameter.name changed from p to myParam"); + } + + @Test + void registerWithJustNodeMode() { + String code = "class A { int f; void foo(int p) { return 'z'; }}"; + CompilationUnit cu = parse(code); + List changes = new ArrayList<>(); + AstObserver observer = new AstObserverAdapter() { + @Override + public void propertyChange(Node observedNode, ObservableProperty property, Object oldValue, Object newValue) { + changes.add(String.format("%s.%s changed from %s to %s", observedNode.getClass().getSimpleName(), property.name().toLowerCase(), oldValue, newValue)); + } + }; + cu.getClassByName("A").get().register(observer, Node.ObserverRegistrationMode.JUST_THIS_NODE); + + assertThat(changes).isEmpty(); + + cu.getClassByName("A").get().setName("MyCoolClass"); + assertThat(changes).containsExactlyInAnyOrder("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass"); + + cu.getClassByName("MyCoolClass").get().getFieldByName("f").get().getVariable(0).setType(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN)); + assertThat(changes).containsExactlyInAnyOrder("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass"); + + cu.getClassByName("MyCoolClass").get().getMethodsByName("foo").get(0).getParameterByName("p").get().setName("myParam"); + assertThat(changes).containsExactlyInAnyOrder("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass"); + + cu.getClassByName("MyCoolClass").get().addField("int", "bar").getVariables().get(0).setInitializer("0"); + assertThat(changes).containsExactlyInAnyOrder("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass"); + } + + @Test + void registerWithNodeAndExistingDescendantsMode() { + String code = "class A { int f; void foo(int p) { return 'z'; }}"; + CompilationUnit cu = parse(code); + List changes = new ArrayList<>(); + AstObserver observer = new AstObserverAdapter() { + @Override + public void propertyChange(Node observedNode, ObservableProperty property, Object oldValue, Object newValue) { + changes.add(String.format("%s.%s changed from %s to %s", observedNode.getClass().getSimpleName(), property.name().toLowerCase(), oldValue, newValue)); + } + }; + cu.getClassByName("A").get().register(observer, Node.ObserverRegistrationMode.THIS_NODE_AND_EXISTING_DESCENDANTS); + + assertThat(changes).isEmpty(); + + cu.getClassByName("A").get().setName("MyCoolClass"); + assertThat(changes).containsExactlyInAnyOrder("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass"); + + cu.getClassByName("MyCoolClass").get().getFieldByName("f").get().getVariable(0).setType(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN)); + assertThat(changes).containsExactlyInAnyOrder("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass", + "FieldDeclaration.maximum_common_type changed from int to boolean", + "VariableDeclarator.type changed from int to boolean"); + + cu.getClassByName("MyCoolClass").get().getMethodsByName("foo").get(0).getParameterByName("p").get().setName("myParam"); + assertThat(changes).containsExactlyInAnyOrder("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass", + "FieldDeclaration.maximum_common_type changed from int to boolean", + "VariableDeclarator.type changed from int to boolean", + "Parameter.name changed from p to myParam"); + + cu.getClassByName("MyCoolClass").get().addField("int", "bar").getVariables().get(0).setInitializer("0"); + assertThat(changes).containsExactlyInAnyOrder("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass", + "FieldDeclaration.maximum_common_type changed from int to boolean", + "VariableDeclarator.type changed from int to boolean", + "Parameter.name changed from p to myParam"); + } + + @Test + void registerWithSelfPropagatingMode() { + String code = "class A { int f; void foo(int p) { return 'z'; }}"; + CompilationUnit cu = parse(code); + List changes = new ArrayList<>(); + AstObserver observer = new AstObserverAdapter() { + @Override + public void propertyChange(Node observedNode, ObservableProperty property, Object oldValue, Object newValue) { + changes.add(String.format("%s.%s changed from %s to %s", observedNode.getClass().getSimpleName(), property.name().toLowerCase(), oldValue, newValue)); + } + }; + cu.getClassByName("A").get().register(observer, Node.ObserverRegistrationMode.SELF_PROPAGATING); + + assertThat(changes).isEmpty(); + + cu.getClassByName("A").get().setName("MyCoolClass"); + assertThat(changes).containsExactlyInAnyOrder("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass"); + + cu.getClassByName("MyCoolClass").get().getFieldByName("f").get().getVariable(0).setType(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN)); + assertThat(changes).containsExactlyInAnyOrder("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass", + "FieldDeclaration.maximum_common_type changed from int to boolean", + "VariableDeclarator.type changed from int to boolean"); + + cu.getClassByName("MyCoolClass").get().getMethodsByName("foo").get(0).getParameterByName("p").get().setName("myParam"); + assertThat(changes).containsExactlyInAnyOrder("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass", + "FieldDeclaration.maximum_common_type changed from int to boolean", + "VariableDeclarator.type changed from int to boolean", + "Parameter.name changed from p to myParam"); + + cu.getClassByName("MyCoolClass").get() + .addField("int", "bar") + .getVariables().get(0).setInitializer("0"); + assertThat(changes).containsExactlyInAnyOrder("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass", + "FieldDeclaration.maximum_common_type changed from int to boolean", + "VariableDeclarator.type changed from int to boolean", + "Parameter.name changed from p to myParam", + "VariableDeclarator.initializer changed from null to 0"); + } + + @Test + void deleteAParameterTriggerNotifications() { + String code = "class A { void foo(int p) { }}"; + CompilationUnit cu = parse(code); + List changes = new ArrayList<>(); + AstObserver observer = new AstObserverAdapter() { + + @Override + public void listChange(NodeList observedNode, ListChangeType type, int index, Node nodeAddedOrRemoved) { + changes.add("removing [" + nodeAddedOrRemoved + "] from index " + index); + } + }; + cu.register(observer, Node.ObserverRegistrationMode.SELF_PROPAGATING); + + cu.getClassByName("A").get().getMethodsByName("foo").get(0).getParameter(0).remove(); + assertThat(changes).containsExactlyInAnyOrder("removing [int p] from index 0"); + } + + @Test + void deleteClassNameDoesNotTriggerNotifications() { + String code = "class A { void foo(int p) { }}"; + CompilationUnit cu = parse(code); + List changes = new ArrayList<>(); + AstObserver observer = new AstObserverAdapter() { + + @Override + public void listChange(NodeList observedNode, ListChangeType type, int index, Node nodeAddedOrRemoved) { + changes.add("removing [" + nodeAddedOrRemoved + "] from index " + index); + } + }; + cu.register(observer, Node.ObserverRegistrationMode.SELF_PROPAGATING); + + // I cannot remove the name of a type + assertFalse(cu.getClassByName("A").get().getName().remove()); + assertThat(changes).isEmpty(); + } + + @Test + void deleteMethodBodyDoesTriggerNotifications() { + String code = "class A { void foo(int p) { }}"; + CompilationUnit cu = parse(code); + List changes = new ArrayList<>(); + AstObserver observer = new AstObserverAdapter() { + + @Override + public void propertyChange(Node observedNode, ObservableProperty property, Object oldValue, Object newValue) { + changes.add("setting [" + property + "] to " + newValue); + } + + @Override + public void listChange(NodeList observedNode, ListChangeType type, int index, Node nodeAddedOrRemoved) { + changes.add("removing [" + nodeAddedOrRemoved + "] from index " + index); + } + }; + cu.register(observer, Node.ObserverRegistrationMode.SELF_PROPAGATING); + + assertTrue(cu.getClassByName("A").get().getMethodsByName("foo").get(0).getBody().get().remove()); + assertThat(changes).containsExactlyInAnyOrder("setting [BODY] to null"); + } + +} 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 new file mode 100644 index 0000000..4b07d47 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/ParseResultTest.java @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import static com.github.javaparser.ParseStart.COMPILATION_UNIT; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.ast.Node.Parsedness.PARSED; +import static com.github.javaparser.ast.Node.Parsedness.UNPARSABLE; +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()); + + @Test + void whenParsingSucceedsThenWeGetResultsAndNoProblems() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X{}")); + + assertThat(result.getResult().isPresent()).isTrue(); + assertThat(result.getResult().get().getParsed()).isEqualTo(PARSED); + assertThat(result.getProblems()).isEmpty(); + + assertThat(result.toString()).isEqualTo("Parsing successful"); + } + + @Test + void whenParsingFailsThenWeGetProblemsAndABadResult() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class {")); + + assertThat(result.getResult().isPresent()).isTrue(); + assertThat(result.getResult().get().getParsed()).isEqualTo(UNPARSABLE); + assertThat(result.getProblems().size()).isEqualTo(1); + + Problem problem = result.getProblem(0); + assertThat(problem.getMessage()).isEqualTo("Parse error. Found \"{\", expected one of \"enum\" \"exports\" \"module\" \"open\" \"opens\" \"permits\" \"provides\" \"record\" \"requires\" \"sealed\" \"strictfp\" \"to\" \"transitive\" \"uses\" \"with\" \"yield\" "); + + assertThat(result.toString()).startsWith("Parsing failed:" + SYSTEM_EOL + "(line 1,col 1) Parse error."); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/ReplaceNodeTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/ReplaceNodeTest.java new file mode 100644 index 0000000..565d8ca --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/ReplaceNodeTest.java @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.StaticJavaParser.parse; +import static com.github.javaparser.StaticJavaParser.parsePackageDeclaration; +import static com.github.javaparser.utils.Utils.SYSTEM_EOL; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ReplaceNodeTest { + @Test + void testSimplePropertyWithGenericReplace() { + CompilationUnit cu = parse("package x; class Y {}"); + cu.replace(cu.getPackageDeclaration().get(), parsePackageDeclaration("package z;")); + assertEquals(String.format("package z;%1$s" + + "%1$s" + + "class Y {%1$s" + + "}%1$s", SYSTEM_EOL), cu.toString()); + } + + @Test + void testListProperty() { + CompilationUnit cu = parse("package x; class Y {}"); + cu.replace(cu.getClassByName("Y").get(), parse("class B{int y;}").getClassByName("B").get()); + assertEquals(String.format("package x;%1$s" + + "%1$s" + + "class B {%1$s" + + "%1$s" + + " int y;%1$s" + + "}%1$s", SYSTEM_EOL), cu.toString()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/WalkFindTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/WalkFindTest.java new file mode 100644 index 0000000..31854f2 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/WalkFindTest.java @@ -0,0 +1,135 @@ +/* + * Copyright (C) 2013-2024 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; + +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.FieldDeclaration; +import com.github.javaparser.ast.body.VariableDeclarator; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.expr.IntegerLiteralExpr; +import com.github.javaparser.ast.expr.SimpleName; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import static com.github.javaparser.StaticJavaParser.parse; +import static com.github.javaparser.StaticJavaParser.parseExpression; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +public class WalkFindTest { + @Test + void findCompilationUnit() { + CompilationUnit cu = parse("class X{int x;}"); + VariableDeclarator x = cu.getClassByName("X").get().getMember(0).asFieldDeclaration().getVariables().get(0); + assertEquals(cu, x.findCompilationUnit().get()); + } + + @Test + void findParent() { + CompilationUnit cu = parse("class X{int x;}"); + SimpleName x = cu.getClassByName("X").get().getMember(0).asFieldDeclaration().getVariables().get(0).getName(); + assertEquals("int x;", x.findAncestor(FieldDeclaration.class).get().toString()); + } + + @Test + void findParentFromTypes() { + CompilationUnit cu = parse("class X{Integer x;}"); + VariableDeclarator vd = cu.getClassByName("X").get().getMember(0).asFieldDeclaration().getVariables().get(0); + assertEquals(FieldDeclaration.class.getName(), + vd.findAncestor(new Class[] { CompilationUnit.class, ClassOrInterfaceDeclaration.class, FieldDeclaration.class }).get().getClass() + .getName()); + assertEquals(ClassOrInterfaceDeclaration.class.getName(), + vd.findAncestor(new Class[] { CompilationUnit.class, ClassOrInterfaceDeclaration.class }).get().getClass() + .getName()); + } + + @Test + void cantFindCompilationUnit() { + VariableDeclarator x = new VariableDeclarator(); + assertFalse(x.findCompilationUnit().isPresent()); + } + + @Test + void genericWalk() { + Expression e = parseExpression("1+1"); + StringBuilder b = new StringBuilder(); + e.walk(n -> b.append(n.toString())); + assertEquals("1 + 111", b.toString()); + } + + @Test + void classSpecificWalk() { + Expression e = parseExpression("1+1"); + StringBuilder b = new StringBuilder(); + e.walk(IntegerLiteralExpr.class, n -> b.append(n.toString())); + assertEquals("11", b.toString()); + } + + @Test + void conditionalFindAll() { + Expression e = parseExpression("1+2+3"); + List ints = e.findAll(IntegerLiteralExpr.class, n -> n.asInt() > 1); + assertEquals("[2, 3]", ints.toString()); + } + + @Test + void typeOnlyFindAll() { + Expression e = parseExpression("1+2+3"); + List ints = e.findAll(IntegerLiteralExpr.class); + assertEquals("[1, 2, 3]", ints.toString()); + } + + @Test + void typeOnlyFindAllMatchesSubclasses() { + Expression e = parseExpression("1+2+3"); + List ints = e.findAll(Node.class); + assertEquals("[1 + 2 + 3, 1 + 2, 1, 2, 3]", ints.toString()); + } + + @Test + void conditionalTypedFindFirst() { + Expression e = parseExpression("1+2+3"); + Optional ints = e.findFirst(IntegerLiteralExpr.class, n -> n.asInt() > 1); + assertEquals("Optional[2]", ints.toString()); + } + + @Test + void typeOnlyFindFirst() { + Expression e = parseExpression("1+2+3"); + Optional ints = e.findFirst(IntegerLiteralExpr.class); + assertEquals("Optional[1]", ints.toString()); + } + + @Test + void stream() { + Expression e = parseExpression("1+2+3"); + List ints = e.stream() + .filter(n -> n instanceof IntegerLiteralExpr) + .map(IntegerLiteralExpr.class::cast) + .filter(i -> i.asInt() > 1) + .collect(Collectors.toList()); + assertEquals("[2, 3]", ints.toString()); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/AnnotationDeclarationTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/AnnotationDeclarationTest.java new file mode 100644 index 0000000..3cfe932 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/AnnotationDeclarationTest.java @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.body; + +import com.github.javaparser.ast.stmt.Statement; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.utils.TestParser.parseStatement; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class AnnotationDeclarationTest { + @Test + void cantAddField() { + assertThrows(IllegalStateException.class, () -> new AnnotationDeclaration().addField(Object.class, "oo")); + } + + @Test + void issue2216() { + Statement statement = parseStatement("TT tt = new @TypeAnno @TA2 TT( \"S\" );"); + assertEquals("TT tt = new @TypeAnno @TA2 TT(\"S\");", statement.toString()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/AnnotationMemberDeclarationTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/AnnotationMemberDeclarationTest.java new file mode 100644 index 0000000..ee2d4a5 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/AnnotationMemberDeclarationTest.java @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.body; + +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.expr.IntegerLiteralExpr; +import com.github.javaparser.ast.expr.SimpleName; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class AnnotationMemberDeclarationTest { + + @Test + void whenSettingNameTheParentOfNameIsAssigned() { + AnnotationMemberDeclaration decl = new AnnotationMemberDeclaration(); + SimpleName name = new SimpleName("foo"); + decl.setName(name); + assertTrue(name.getParentNode().isPresent()); + assertSame(decl, name.getParentNode().get()); + } + + @Test + void removeDefaultValueWhenNoDefaultValueIsPresent() { + AnnotationMemberDeclaration decl = new AnnotationMemberDeclaration(); + SimpleName name = new SimpleName("foo"); + decl.setName(name); + + decl.removeDefaultValue(); + + assertFalse(decl.getDefaultValue().isPresent()); + } + + @Test + void removeDefaultValueWhenDefaultValueIsPresent() { + AnnotationMemberDeclaration decl = new AnnotationMemberDeclaration(); + SimpleName name = new SimpleName("foo"); + decl.setName(name); + Expression defaultValue = new IntegerLiteralExpr("2"); + decl.setDefaultValue(defaultValue); + + decl.removeDefaultValue(); + + assertFalse(defaultValue.getParentNode().isPresent()); + } +} 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 new file mode 100644 index 0000000..0b3105c --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/ClassOrInterfaceDeclarationTest.java @@ -0,0 +1,146 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.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; + +class ClassOrInterfaceDeclarationTest { + @Test + void staticNestedClass() { + CompilationUnit cu = parse("class X{static class Y{}}"); + ClassOrInterfaceDeclaration y = cu.getClassByName("X").get().getMembers().get(0).asClassOrInterfaceDeclaration(); + + assertFalse(y.isInnerClass()); + assertTrue(y.isNestedType()); + assertFalse(y.isLocalClassDeclaration()); + } + + @Test + void nestedInterface() { + CompilationUnit cu = parse("class X{interface Y{}}"); + ClassOrInterfaceDeclaration y = cu.getClassByName("X").get().getMembers().get(0).asClassOrInterfaceDeclaration(); + + assertFalse(y.isInnerClass()); + assertTrue(y.isNestedType()); + assertFalse(y.isLocalClassDeclaration()); + } + + @Test + void nonStaticNestedClass() { + CompilationUnit cu = parse("class X{class Y{}}"); + ClassOrInterfaceDeclaration y = cu.getClassByName("X").get().getMembers().get(0).asClassOrInterfaceDeclaration(); + + assertTrue(y.isInnerClass()); + assertTrue(y.isNestedType()); + assertFalse(y.isLocalClassDeclaration()); + } + + @Test + void topClass() { + CompilationUnit cu = parse("class X{}"); + ClassOrInterfaceDeclaration y = cu.getClassByName("X").get(); + + assertFalse(y.isInnerClass()); + assertFalse(y.isNestedType()); + assertFalse(y.isLocalClassDeclaration()); + } + + @Test + void localClass() { + MethodDeclaration method = parseBodyDeclaration("void x(){class X{};}").asMethodDeclaration(); + ClassOrInterfaceDeclaration x = method.findFirst(ClassOrInterfaceDeclaration.class).get(); + + assertFalse(x.isInnerClass()); + assertFalse(x.isNestedType()); + assertTrue(x.isLocalClassDeclaration()); + } + + @Test + void sealedClass() { + CompilationUnit cu = TestParser.parseCompilationUnit(ParserConfiguration.LanguageLevel.JAVA_17, "sealed class X permits Y, Z {}"); + ClassOrInterfaceDeclaration x = cu.getClassByName("X").get(); + + assertFalse(x.isInnerClass()); + assertFalse(x.isNestedType()); + assertFalse(x.isLocalClassDeclaration()); + assertTrue(x.hasModifier(Modifier.Keyword.SEALED)); + assertEquals(x.getPermittedTypes().size(), 2); + assertEquals(x.getPermittedTypes().get(0).getNameAsString(), "Y"); + assertEquals(x.getPermittedTypes().get(1).getNameAsString(), "Z"); + } + + @Test + void nonSealedClass() { + CompilationUnit cu = TestParser.parseCompilationUnit(ParserConfiguration.LanguageLevel.JAVA_17, "non-sealed class X{}"); + ClassOrInterfaceDeclaration x = cu.getClassByName("X").get(); + + assertFalse(x.isInnerClass()); + assertFalse(x.isNestedType()); + assertFalse(x.isLocalClassDeclaration()); + assertTrue(x.hasModifier(Modifier.Keyword.NON_SEALED)); + } + + @ParameterizedTest + @EnumSource(value = ParserConfiguration.LanguageLevel.class, names = {"JAVA_8","JAVA_9","JAVA_10","JAVA_11","JAVA_12","JAVA_13","JAVA_14", "JAVA_15", "JAVA_16"}) + void sealedFieldNamePermitted(ParserConfiguration.LanguageLevel languageLevel) { + assertDoesNotThrow(() -> { + TestParser.parseVariableDeclarationExpr(languageLevel, "boolean sealed"); + }); + } + + @ParameterizedTest + @EnumSource(value = ParserConfiguration.LanguageLevel.class, names = {"JAVA_17"}) + void sealedFieldNameNotPermitted(ParserConfiguration.LanguageLevel languageLevel) { + assertThrows(AssertionFailedError.class, () -> { + TestParser.parseVariableDeclarationExpr(languageLevel, "boolean sealed"); + }); + } + + @ParameterizedTest + @EnumSource(value = ParserConfiguration.LanguageLevel.class, names = {"JAVA_8","JAVA_9","JAVA_10","JAVA_11","JAVA_12","JAVA_13","JAVA_14", "JAVA_15", "JAVA_16"}) + void permitsFieldNamePermitted(ParserConfiguration.LanguageLevel languageLevel) { + assertDoesNotThrow(() -> { + TestParser.parseVariableDeclarationExpr(languageLevel, "boolean permits"); + }); + } + + @ParameterizedTest + @EnumSource(value = ParserConfiguration.LanguageLevel.class, names = {"JAVA_17"}) + void permitsFieldNameNotPermitted(ParserConfiguration.LanguageLevel languageLevel) { + assertThrows(AssertionFailedError.class, () -> { + TestParser.parseVariableDeclarationExpr(languageLevel, "boolean permits"); + }); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/ConstructorDeclarationTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/ConstructorDeclarationTest.java new file mode 100644 index 0000000..b0802c1 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/ConstructorDeclarationTest.java @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.body; + +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.utils.Utils.SYSTEM_EOL; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ConstructorDeclarationTest { + @Test + void acceptsSuper() { + ConstructorDeclaration cons = new ConstructorDeclaration("Cons"); + cons.createBody().addStatement("super();"); + + assertEquals(String.format("public Cons() {%1$s" + + " super();%1$s" + + "}", SYSTEM_EOL), cons.toString()); + } +} 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 new file mode 100644 index 0000000..e004d35 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/FieldDeclarationTest.java @@ -0,0 +1,131 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.body; + +import com.github.javaparser.StaticJavaParser; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.Modifier.Keyword; +import com.github.javaparser.ast.NodeList; +import org.junit.jupiter.api.Assertions; +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.*; + +class FieldDeclarationTest { + @Test + void wofjweoifj() { + CompilationUnit compilationUnit = parse("" + + "class A {\n" + + " int a, b;\n" + + "}"); + + BodyDeclaration declaration = compilationUnit.getType(0).getMembers().get(0); + FieldDeclaration fieldDeclaration = declaration.asFieldDeclaration(); + VariableDeclarator var1 = fieldDeclaration.getVariables().get(0); + VariableDeclarator var2 = fieldDeclaration.getVariables().get(1); + assertEquals(var1, var1.getType().getParentNode().get()); + assertEquals(var2, var2.getType().getParentNode().get()); + } + + @Test + void setModifiersPrimitiveType() { + FieldDeclaration field = parseBodyDeclaration("public static final int var = 1;").asFieldDeclaration(); + testChangingModifiers(field); + } + + @Test + void setModifiersNonPrimitiveType() { + FieldDeclaration field = parseBodyDeclaration("public static final String var = \"a\";").asFieldDeclaration(); + testChangingModifiers(field); + } + + private void testChangingModifiers(FieldDeclaration field) { + NodeList modifiers = field.getModifiers(); + assertTrue(modifiers.contains(Modifier.publicModifier())); + assertTrue(modifiers.contains(Modifier.staticModifier())); + assertTrue(modifiers.contains(Modifier.finalModifier())); + assertEquals(3, modifiers.size()); + + field.setModifiers(new NodeList()); + modifiers = field.getModifiers(); + assertEquals(0, modifiers.size()); + + field.setModifiers(Keyword.PRIVATE, Keyword.SYNCHRONIZED); + modifiers = field.getModifiers(); + assertTrue(modifiers.contains(Modifier.privateModifier())); + assertTrue(modifiers.contains(Modifier.synchronizedModifier())); + assertEquals(2, modifiers.size()); + } + + @Test + void interfaceFieldTest() { + CompilationUnit compilationUnit = parse("" + + "interface A {\n" + + " int a = 1;\n" + + " static int a_s = 1;\n" + + " final int a_f = 1;\n" + + " static final int a_s_f = 1;\n" + + " String b = \"b\";\n" + + " static String b_s = \"b\";\n" + + " final String b_f = \"b\";\n" + + " static final String b_s_f = \"b\";\n" + + "}\n"); + for (int i = 0; i < 8; ++i) { + BodyDeclaration declaration = compilationUnit.getType(0).getMembers().get(i); + FieldDeclaration fieldDeclaration = declaration.asFieldDeclaration(); + Assertions.assertTrue(fieldDeclaration.isStatic()); + Assertions.assertTrue(fieldDeclaration.isFinal()); + } + } + + /** + * 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/body/MethodDeclarationTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/MethodDeclarationTest.java new file mode 100644 index 0000000..0dc9118 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/MethodDeclarationTest.java @@ -0,0 +1,162 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.body; + +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.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +import com.github.javaparser.ast.CompilationUnit; + +class MethodDeclarationTest { + @Test + void annotationsAllowedAfterGenericsAndBeforeReturnType() { + parseBodyDeclaration("public @Abc String method() {return null;}"); + } + + @Test + void annotationsAllowedBeforeGenerics() { + parseBodyDeclaration("public @Abc String method() {return null;}"); + } + + @Test + void explicitReceiverParameters1() { + MethodDeclaration method = parseBodyDeclaration("void InnerInner(@mypackage.Anno Source.@mypackage.Anno Inner Source.Inner.this) { }").asMethodDeclaration(); + assertEquals("Source.Inner.this", method.getReceiverParameter().get().getNameAsString()); + } + + @Test + void explicitReceiverParameters2() { + MethodDeclaration method = parseBodyDeclaration("void x(A this) { }").asMethodDeclaration(); + assertEquals("this", method.getReceiverParameter().get().getNameAsString()); + } + + @Test + void explicitReceiverParameters3() { + MethodDeclaration method = parseBodyDeclaration("void x(A that) { }").asMethodDeclaration(); + assertFalse(method.getReceiverParameter().isPresent()); + } + + @Test + void signaturesEqual() { + MethodDeclaration method1 = parseBodyDeclaration("void x(String a) { }").asMethodDeclaration(); + MethodDeclaration method2 = parseBodyDeclaration("int x(String z);").asMethodDeclaration(); + assertEquals(method1.getSignature(), method2.getSignature()); + } + + @Test + void signaturesEqualWhenGenericsDiffer() { + MethodDeclaration method1 = parseBodyDeclaration("void x(List a) { }").asMethodDeclaration(); + MethodDeclaration method2 = parseBodyDeclaration("void x(List a) { }").asMethodDeclaration(); + assertEquals(method1.getSignature(), method2.getSignature()); + } + + @Test + void signaturesEqualWhenAnnotationsDiffer() { + MethodDeclaration method1 = parseBodyDeclaration("void x(@A @B List a) { }").asMethodDeclaration(); + MethodDeclaration method2 = parseBodyDeclaration("void x(@C List a) { }").asMethodDeclaration(); + assertEquals(method1.getSignature(), method2.getSignature()); + } + + @Test + void signaturesDifferentName() { + MethodDeclaration method1 = parseBodyDeclaration("void x(String a) { }").asMethodDeclaration(); + MethodDeclaration method2 = parseBodyDeclaration("int y(String z);").asMethodDeclaration(); + assertNotEquals(method1.getSignature(), method2.getSignature()); + } + + @Test + void signaturesDifferentTypes() { + MethodDeclaration method1 = parseBodyDeclaration("void x(String a) { }").asMethodDeclaration(); + MethodDeclaration method2 = parseBodyDeclaration("int x(int z);").asMethodDeclaration(); + assertNotEquals(method1.getSignature(), method2.getSignature()); + } + + @Test + void signaturesDifferentVarargs() { + MethodDeclaration method1 = parseBodyDeclaration("int x(int z);").asMethodDeclaration(); + MethodDeclaration method2 = parseBodyDeclaration("int x(int... z);").asMethodDeclaration(); + assertNotEquals(method1.getSignature(), method2.getSignature()); + } + + @Test + void signatureToString() { + MethodDeclaration method1 = parseBodyDeclaration("int x(int z, String q);").asMethodDeclaration(); + assertEquals("x(int, String)", method1.getSignature().toString()); + } + + @Test + void isVariableArityMethod() { + MethodDeclaration method1 = parseBodyDeclaration("int x(int... z);").asMethodDeclaration(); + assertTrue(method1.isVariableArityMethod()); + MethodDeclaration method2 = parseBodyDeclaration("int x(int i, int... z);").asMethodDeclaration(); + assertTrue(method2.isVariableArityMethod()); + } + + @Test + void isFixedArityMethod() { + MethodDeclaration method1 = parseBodyDeclaration("int x(int z);").asMethodDeclaration(); + assertTrue(method1.isFixedArityMethod()); + MethodDeclaration method2 = parseBodyDeclaration("int x();").asMethodDeclaration(); + assertTrue(method2.isFixedArityMethod()); + } + + /* + * A method in the body of an interface may be declared public or private + * (§6.6). If no access modifier is given, the method is implicitly public. + * https://docs.oracle.com/javase/specs/jls/se9/html/jls-9.html#jls-9.4 + */ + @Test + void isMethodInterfaceImplictlyPublic() { + CompilationUnit cu = parse("interface Foo { void m(); }"); + assertTrue(cu.findFirst(MethodDeclaration.class).get().isPublic()); + cu = parse("interface Foo { public void m(); }"); + assertTrue(cu.findFirst(MethodDeclaration.class).get().isPublic()); + cu = parse("interface Foo { abstract void m(); }"); + assertTrue(cu.findFirst(MethodDeclaration.class).get().isPublic()); + cu = parse("interface Foo { private void m(); }"); + assertFalse(cu.findFirst(MethodDeclaration.class).get().isPublic()); + } + + /* + * An interface method lacking a private, default, or static modifier is implicitly abstract. + * https://docs.oracle.com/javase/specs/jls/se9/html/jls-9.html#jls-9.4 + */ + @Test + void isMethodInterfaceImplictlyAbstract() { + CompilationUnit cu = parse("interface Foo { void m(); }"); + assertTrue(cu.findFirst(MethodDeclaration.class).get().isAbstract()); + cu = parse("interface Foo { abstract void m(); }"); + assertTrue(cu.findFirst(MethodDeclaration.class).get().isAbstract()); + cu = parse("interface Foo { private void m(); }"); + assertFalse(cu.findFirst(MethodDeclaration.class).get().isAbstract()); + cu = parse("interface Foo { static void m(); }"); + assertFalse(cu.findFirst(MethodDeclaration.class).get().isAbstract()); + cu = parse("interface Foo { default void m(){} }"); + assertFalse(cu.findFirst(MethodDeclaration.class).get().isAbstract()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/RecordDeclarationTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/RecordDeclarationTest.java new file mode 100644 index 0000000..2a954b0 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/RecordDeclarationTest.java @@ -0,0 +1,765 @@ +/* + * Copyright (C) 2013-2024 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.body; + +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.expr.ObjectCreationExpr; +import com.github.javaparser.utils.TestParser; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.opentest4j.AssertionFailedError; + +import java.util.List; + +import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; + +public class RecordDeclarationTest { + + @Nested + class LanguageLevels { + @ParameterizedTest + @EnumSource(value = ParserConfiguration.LanguageLevel.class, names = {"JAVA_13", "JAVA_13_PREVIEW", "JAVA_14", "JAVA_15"}) + void basicGrammarCompiles_languageLevelValidation_forbidden(ParserConfiguration.LanguageLevel languageLevel) { + String s = "record Point(int x, int y) { }"; + assertThrows(AssertionFailedError.class, () -> { + CompilationUnit cu = TestParser.parseCompilationUnit(languageLevel, s); + }); + } + + @ParameterizedTest + @EnumSource(value = ParserConfiguration.LanguageLevel.class, names = {"JAVA_14_PREVIEW", "JAVA_15_PREVIEW", "JAVA_16", "JAVA_16_PREVIEW"}) + void basicGrammarCompiles_languageLevelValidation_permitted(ParserConfiguration.LanguageLevel languageLevel) { + String s = "record Point(int x, int y) { }"; + CompilationUnit cu = TestParser.parseCompilationUnit(languageLevel, s); + } + + @ParameterizedTest + @EnumSource(value = ParserConfiguration.LanguageLevel.class, names = {"JAVA_14_PREVIEW", "JAVA_15_PREVIEW", "JAVA_16", "JAVA_16_PREVIEW"}) + void languageLevelValidation_recordAsTypeIdentifier_permitted(ParserConfiguration.LanguageLevel languageLevel) { + String s = "class record {}"; + assertThrows(AssertionFailedError.class, () -> { + CompilationUnit cu = TestParser.parseCompilationUnit(languageLevel, s); + }); + } + + @ParameterizedTest + @EnumSource(value = ParserConfiguration.LanguageLevel.class, names = {"JAVA_13", "JAVA_13_PREVIEW", "JAVA_14", "JAVA_15"}) + void languageLevelValidation_recordAsTypeIdentifier_forbidden(ParserConfiguration.LanguageLevel languageLevel) { + String s = "class record {}"; + CompilationUnit cu = TestParser.parseCompilationUnit(languageLevel, s); + } + } + + /** + * https://openjdk.java.net/jeps/395#Description + */ + @Test + void basicGrammarCompiles() { + String s = "record Point(int x, int y) { }"; + assertOneRecordDeclaration(TestParser.parseCompilationUnit(s)); + } + + /** + * https://openjdk.java.net/jeps/395#Description + */ + @Test + void basicGrammar() { + String s = "record Point(int x, int y) { }"; + CompilationUnit cu = TestParser.parseCompilationUnit(s); + assertOneRecordDeclaration(cu); + + RecordDeclaration recordDeclaration = cu.findAll(RecordDeclaration.class).get(0); + + assertTrue(recordDeclaration.isRecordDeclaration()); + assertTrue(recordDeclaration.getImplementedTypes().isEmpty()); + assertTrue(recordDeclaration.getTypeParameters().isEmpty()); + assertTrue(recordDeclaration.getFullyQualifiedName().isPresent()); + assertEquals("Point", recordDeclaration.getFullyQualifiedName().get()); + assertTrue(recordDeclaration.isRecordDeclaration()); + + NodeList parameters = recordDeclaration.getParameters(); + assertEquals(2, parameters.size()); + + Parameter parameter0 = parameters.get(0); + assertEquals("x", parameter0.getNameAsString()); + assertEquals("int", parameter0.getTypeAsString()); + Parameter parameter1 = parameters.get(1); + assertEquals("y", parameter1.getNameAsString()); + assertEquals("int", parameter1.getTypeAsString()); + + assertEquals(0, recordDeclaration.getMembers().size()); + } + + /** + * https://openjdk.java.net/jeps/395#Description + */ + @Test + void basicRecordPrints() { + String s = "record Point(int x, int y) { }"; + CompilationUnit cu = TestParser.parseCompilationUnit(s); + assertOneRecordDeclaration(cu); + + String expected = "" + + "record Point(int x, int y) {\n" + + "}\n" + + ""; + assertEqualsStringIgnoringEol(expected, cu.toString()); + } + + @Test + void genericRecordPrints() { + String s = "record Point(X x, Y y) { }"; + CompilationUnit cu = TestParser.parseCompilationUnit(s); + assertOneRecordDeclaration(cu); + + String expected = "" + + "record Point(X x, Y y) {\n" + + "}\n" + + ""; + assertEqualsStringIgnoringEol(expected, cu.toString()); + } + + /** + * https://openjdk.java.net/jeps/395#Restrictions-on-record + */ + @Test + void record_cannotExtend() { + String s = "record Point(int x, int y) extends OtherThing { }"; + assertCompilationFails(s); + } + + /** + * https://openjdk.java.net/jeps/395#Restrictions-on-records + */ + @Test + void record_cannotBeAbstract() { + String s = "abstract record Point(int x, int y) { }"; + assertCompilationFails(s); + } + + /** + * https://openjdk.java.net/jeps/395#Restrictions-on-records + */ + @Test + void record_mayImplementInterfaces() { + String s = "record Point(int x, int y) implements OtherInterface { }"; + CompilationUnit cu = TestParser.parseCompilationUnit(s); + + assertOneRecordDeclaration(cu); + } + + /** + * https://openjdk.java.net/jeps/395#Restrictions-on-records + */ + @Test + void record_mayBeStatic() { + String s = "static record Point(int x, int y) { }"; + CompilationUnit cu = TestParser.parseCompilationUnit(s); + + assertOneRecordDeclaration(cu); + } + + @Test + void recordWithVarArgs() { + String s = "record R(T1 c1, Tn... cn){ }"; + CompilationUnit cu = TestParser.parseCompilationUnit(s); + + List recordDeclarations = cu.findAll(RecordDeclaration.class); + assertEquals(1, recordDeclarations.size()); + + RecordDeclaration recordDeclaration = recordDeclarations.get(0); + NodeList parameters = recordDeclaration.getParameters(); + assertEquals(2, parameters.size()); + + Parameter parameter0 = parameters.get(0); + assertEquals("c1", parameter0.getNameAsString()); + assertEquals("T1", parameter0.getTypeAsString()); + assertFalse(parameter0.isVarArgs()); + + Parameter parameter1 = parameters.get(1); + assertEquals("cn", parameter1.getNameAsString()); + assertEquals("Tn", parameter1.getTypeAsString()); + assertTrue(parameter1.isVarArgs()); + } + + @Test + void recordWithAnnotationedParameters() { + String s = "record Card(@MyAnno Rank rank, @MyAnno Suit suit) { }"; + CompilationUnit cu = TestParser.parseCompilationUnit(s); + + List recordDeclarations = cu.findAll(RecordDeclaration.class); + assertEquals(1, recordDeclarations.size()); + + RecordDeclaration recordDeclaration = recordDeclarations.get(0); + NodeList parameters = recordDeclaration.getParameters(); + assertEquals(2, parameters.size()); + + Parameter parameter0 = parameters.get(0); + assertEquals("rank", parameter0.getNameAsString()); + assertEquals("Rank", parameter0.getTypeAsString()); + assertEquals(1, parameter0.getAnnotations().size()); + + Parameter parameter1 = parameters.get(1); + assertEquals("suit", parameter1.getNameAsString()); + assertEquals("Suit", parameter1.getTypeAsString()); + assertEquals(1, parameter1.getAnnotations().size()); + + assertEquals(0, recordDeclaration.getMembers().size()); + } + + @Test + void record_emptyMembers() { + String s = "record Point(int x, int y) { }"; + CompilationUnit cu = TestParser.parseCompilationUnit(s); + assertOneRecordDeclaration(cu); + + List recordDeclarations = cu.findAll(RecordDeclaration.class); + RecordDeclaration recordDeclaration = recordDeclarations.get(0); + + assertEquals(0, recordDeclaration.getMembers().size()); + } + + @Test + void record_permitStaticMethods() { + String s = "" + + "record ABC(int x, int y) {\n" + + "\n" + + " static public int abc() {\n" + + " return x;\n" + + " }\n" + + "\n" + + "}\n" + + ""; + CompilationUnit cu = TestParser.parseCompilationUnit(s); + assertOneRecordDeclaration(cu); + } + + @Test + void record_permitMethods() { + String s = "" + + "record ABC(int x, int y) {\n" + + "\n" + + " public int x() {\n" + + " return x;\n" + + " }\n" + + "\n" + + " public String xyz() {\n" + + " return \"10\";\n" + + " }\n" + + "\n" + + "}\n" + + ""; + CompilationUnit cu = TestParser.parseCompilationUnit(s); + assertOneRecordDeclaration(cu); + } + + @Test + void record_forbidNonStaticFields() { + String s = "record Point(int x, int y) { int z; }"; + assertCompilationFails(s); + } + + @Test + void record_permitStaticFields() { + String s = "record Point(int x, int y) { static int z; }"; + CompilationUnit cu = TestParser.parseCompilationUnit(s); + assertOneRecordDeclaration(cu); + } + + @Test + void record_permitPublicStaticFieldInRecord1() { + String s = "public final record RecordPublicField() {" + + " public static final Object EMPTY = new Object();" + + "}\n"; + CompilationUnit cu = TestParser.parseCompilationUnit(s); + assertOneRecordDeclaration(cu); + } + + @Test + void record_permitPublicStaticFieldInNestedRecord() { + String s = "public final record RecordTopLevel(Object member) {\n" + + " private static record RecordNested() {\n" + + " public static final RecordNested EMPTY = new RecordNested();\n" + + " }\n" + + "}\n"; + CompilationUnit cu = TestParser.parseCompilationUnit(s); + assertTwoRecordDeclarations(cu); + } + + @Test + void record_permitStaticFields2() { + String s = "" + + "record ABC(int x, int y) {\n" + + "\n" + + " static int z;\n" + + "\n" + + " static {\n" + + " int z = 10;\n" + + " }\n" + + "\n" + + " public int x() {\n" + + " return x;\n" + + " }\n" + + "\n" + + "}\n" + + ""; + CompilationUnit cu = TestParser.parseCompilationUnit(s); + assertOneRecordDeclaration(cu); + } + + /** + * https://openjdk.java.net/jeps/395#Restrictions-on-records + */ + @Test + void record_isImplicitlyFinal() { + String s = "record Point(int x, int y) { static int z; }"; + CompilationUnit cu = TestParser.parseCompilationUnit(s); + assertOneRecordDeclaration(cu); + + RecordDeclaration recordDeclaration = cu.findFirst(RecordDeclaration.class).get(); + assertFalse(recordDeclaration.hasModifier(Modifier.Keyword.FINAL)); + assertTrue(recordDeclaration.isFinal(), "Records are implicitly final."); + } + + /** + * https://openjdk.java.net/jeps/395#Restrictions-on-records + */ + @Test + void record_isImplicitlyFinalWithoutExplicit() { + String s = "record Point(int x, int y) { static int z; }"; + CompilationUnit cu = TestParser.parseCompilationUnit(s); + assertOneRecordDeclaration(cu); + + RecordDeclaration recordDeclaration = cu.findFirst(RecordDeclaration.class).get(); + assertFalse(recordDeclaration.hasModifier(Modifier.Keyword.FINAL)); + assertTrue(recordDeclaration.isFinal(), "Records are implicitly final."); + } + + /** + * https://openjdk.java.net/jeps/395#Restrictions-on-records + */ + @Test + void record_canHaveGenerics() { + String s = "record Point (T x, int y) { }"; + CompilationUnit cu = TestParser.parseCompilationUnit(s); + assertOneRecordDeclaration(cu); + + RecordDeclaration recordDeclaration = cu.findFirst(RecordDeclaration.class).get(); + assertFalse(recordDeclaration.getTypeParameters().isEmpty()); + assertEquals("T", recordDeclaration.getTypeParameters().get(0).getNameAsString()); + } + + + @Test + void record_mustNotAllowMismatchedComponentAccessorReturnType() { + String s = "record Point(int x, int y) {\n" + + " public String x() {\n" + + " return \"10\";\n" + + " }\n" + + "}"; + assertCompilationFails(s); + } + + @Test + void record_allowMethodsWithSameNameAsRecordComponentButNotAnAccessorMethod() { + String s = "record Point(int x, int y) {\n" + + " public String x(int a) {\n" + + " return \"10\";\n" + + " }\n" + + "}"; + + CompilationUnit cu = TestParser.parseCompilationUnit(s); + assertOneRecordDeclaration(cu); + } + + @Test + void record_allowMethodsWithSameNameAsRecordComponentButNotAnAccessorMethod2() { + String s = "record Point(int x, int y) {\n" + + " public int x(int a) {\n" + + " return 10;\n" + + " }\n" + + "}"; + + CompilationUnit cu = TestParser.parseCompilationUnit(s); + assertOneRecordDeclaration(cu); + } + + @Test + void record_allowComponentAccessorWithMatchingType() { + String s = "record Point(int x, int y) {\n" + + " public int x() {\n" + + " return 10;\n" + + " }\n" + + "}"; + + CompilationUnit cu = TestParser.parseCompilationUnit(s); + assertOneRecordDeclaration(cu); + } + + /** + * https://openjdk.java.net/jeps/395#Restrictions-on-records + */ + @Test + void record_allowNestedWithinClass() { + String s = "\n" + + "class X {\n" + + " record Point(int x, int y) {\n" + + " }\n" + + "}\n"; + + CompilationUnit cu = TestParser.parseCompilationUnit(s); + assertOneRecordDeclaration(cu); + } + + /** + * https://openjdk.java.net/jeps/395#Restrictions-on-records + */ + @Test + void record_componentsAreImplicitlyFinal() { + String s = "record Point(int x, int y) { }"; + + CompilationUnit cu = TestParser.parseCompilationUnit(s); + assertOneRecordDeclaration(cu); + + RecordDeclaration recordDeclaration = cu.findAll(RecordDeclaration.class).get(0); + + NodeList parameters = recordDeclaration.getParameters(); + assertTrue(parameters.get(0).isFinal()); + assertTrue(parameters.get(1).isFinal()); + } + + /** + * https://openjdk.java.net/jeps/395#Restrictions-on-records + */ + @Test + void record_allowClassWithinRecord() { + String s = "\n" + + "record Point(int x, int y) {\n" + + " class X {\n" + + " }\n" + + "}\n"; + + CompilationUnit cu = TestParser.parseCompilationUnit(s); + assertOneRecordDeclaration(cu); + + List recordDeclarations = cu.findAll(RecordDeclaration.class); + assertEquals(1, recordDeclarations.size()); + + RecordDeclaration recordDeclaration = recordDeclarations.get(0); + BodyDeclaration member = recordDeclaration.getMember(0); + + assertTrue(member.isClassOrInterfaceDeclaration()); + } + + /** + * https://openjdk.java.net/jeps/395#Restrictions-on-records + */ + @Test + void record_allowNestedWithinInterface() { + String s = "\n" + + "interface X {\n" + + " record Point(int x, int y) {\n" + + " }\n" + + "}\n"; + + CompilationUnit cu = TestParser.parseCompilationUnit(s); + assertOneRecordDeclaration(cu); + } + + /** + * https://openjdk.java.net/jeps/395#Restrictions-on-records + */ + @Test + void record_allowNestedWithinEnum() { + String s = "\n" + + "enum ABC {\n" + + " ABC;\n" + + " \n" + + " record Point(int x, int y) {\n" + + " }\n" + + "}\n"; + + CompilationUnit cu = TestParser.parseCompilationUnit(s); + assertOneRecordDeclaration(cu); + } + + /** + * https://openjdk.java.net/jeps/395#Restrictions-on-records + */ + @Test + void record_allowNestedMultiple() { + String s = "\n" + + "interface Y {\n" + + " class X {\n" + + " record Point(int x, int y) {\n" + + " }\n" + + " }\n" + + "}\n"; + + CompilationUnit cu = TestParser.parseCompilationUnit(s); + assertOneRecordDeclaration(cu); + } + + /** + * https://openjdk.java.net/jeps/395#Restrictions-on-records + */ + @Test + void record_allowNestedMultiple2() { + String s = "\n" + + "interface Y {\n" + + " class X {\n" + + " record Point(int x, int y) {\n" + + " }\n" + + " record PointB(int x, int y) {\n" + + " }\n" + + " }\n" + + "\n" + + " record PointC(int x, int y) {\n" + + " }\n" + + "}\n"; + + CompilationUnit cu = TestParser.parseCompilationUnit(s); + + List recordDeclarations = cu.findAll(RecordDeclaration.class); + assertEquals(3, recordDeclarations.size()); + } + + /** + * https://openjdk.java.net/jeps/395#Restrictions-on-records + */ + @Test + void record_topLevelRecordsAreNotStatic() { + String s = "record Point(int x, int y) { }\n"; + + CompilationUnit cu = TestParser.parseCompilationUnit(s); + assertOneRecordDeclaration(cu); + + RecordDeclaration recordDeclaration = cu.findAll(RecordDeclaration.class).get(0); + assertFalse(recordDeclaration.hasModifier(Modifier.Keyword.STATIC)); + assertFalse(recordDeclaration.isStatic(), "Top level Records are NOT implicitly static."); + } + + /** + * https://openjdk.java.net/jeps/395#Restrictions-on-records + */ + @Test + void record_nestedRecordsAreImplicitlyStatic() { + String s = "\n" + + "class X {\n" + + " record Point(int x, int y) {\n" + + " }\n" + + "}\n"; + + CompilationUnit cu = TestParser.parseCompilationUnit(s); + assertOneRecordDeclaration(cu); + + RecordDeclaration recordDeclaration = cu.findAll(RecordDeclaration.class).get(0); + assertFalse(recordDeclaration.hasModifier(Modifier.Keyword.STATIC)); + assertTrue(recordDeclaration.isStatic(), "Nested Records are implicitly static."); + + } + + + @Test + void record_canBeCreatedUsingKeywordNew() { + String s = "\n" + + "\n" + + "record Point(int x, int y) {\n" + + "}\n" + + "\n" + + "class X {\n" + + " public static void main(String[] args) {\n" + + " new Point(10, 3);\n" + + " }\n" + + "}\n\n"; + + CompilationUnit cu = TestParser.parseCompilationUnit(s); + assertOneRecordDeclaration(cu); + + ClassOrInterfaceDeclaration coid = cu.findAll(ClassOrInterfaceDeclaration.class).get(0); + List objectCreationExprs = coid.findAll(ObjectCreationExpr.class); + + assertEquals(1, objectCreationExprs.size()); + ObjectCreationExpr objectCreationExpr = objectCreationExprs.get(0); + assertEquals("Point", objectCreationExpr.getTypeAsString()); + } + + /** + * Note the Record Declaration Constructor does not include parameters. + * (parameters are, instead, included within the record declaration) + *

+ * https://bugs.openjdk.java.net/browse/JDK-8222777 + */ + @Test + void recordDeclarationFromTheJDK8222777() { + CompilationUnit cu = TestParser.parseCompilationUnit("" + + "public record Range(int lo, int hi) {\n" + + "\n" + + " public Range {\n" + + " if (lo > hi) /* referring here to the implicit constructor parameters */\n" + + " throw new IllegalArgumentException(String.format(\"(%d,%d)\", lo, hi));\n" + + " }\n" + + "}" + ); + + RecordDeclaration recordDeclaration = cu.findFirst(RecordDeclaration.class).get(); + assertThat(recordDeclaration.getNameAsString()).isEqualTo("Range"); + assertThat(recordDeclaration.getModifiers()).containsExactly(Modifier.publicModifier()); + // test parameters + // get constructor + // test parameters (none) + } + + @Test + void recordDeclaration_exampleFromJls_8_10_4_1_normalCanonicalConstructors() { + CompilationUnit cu = TestParser.parseCompilationUnit("" + + "import java.lang.annotation.Target;\n" + + "import java.lang.annotation.ElementType;\n" + + "\n" + + "@interface Foo {}\n" + + "@interface Bar {}\n" + + "\n" + + "record Person(@Foo String name) {\n" + + " Person(String name2) {\n" + + " }\n" + + "}" + ); + + RecordDeclaration recordDeclaration = cu.findFirst(RecordDeclaration.class).get(); + assertThat(recordDeclaration.getNameAsString()).isEqualTo("Person"); + assertThat(recordDeclaration.getModifiers()).isEmpty(); + + assertThat(recordDeclaration.getConstructors()).hasSize(1); + assertThat(recordDeclaration.getCompactConstructors()).hasSize(0); + + } + + @Test + void compactConstructor_exampleFromJls_8_10_4_2_compactConstructors() { + CompilationUnit cu = TestParser.parseCompilationUnit("" + + "record Rational(int num, int denom) {\n" + + " private static int gcd(int a, int b) {\n" + + " if (b == 0) return Math.abs(a);\n" + + " else return gcd(b, a % b);\n" + + " }\n" + + " \n" + + " Rational {\n" + + " int gcd = gcd(num, denom);\n" + + " num /= gcd;\n" + + " denom /= gcd;\n" + + " }\n" + + "}\n" + ); + + RecordDeclaration recordDeclaration = cu.findFirst(RecordDeclaration.class).get(); + assertThat(recordDeclaration.getNameAsString()).isEqualTo("Rational"); + assertThat(recordDeclaration.getModifiers()).isEmpty(); + + assertThat(recordDeclaration.getConstructors()).hasSize(0); + assertThat(recordDeclaration.getCompactConstructors()).hasSize(1); + + } + + @Test + void nonCompactConstructor_exampleFromJls_8_10_4_2_compactConstructors() { + CompilationUnit cu = TestParser.parseCompilationUnit("" + + "record Rational(int num, int denom) {\n" + + " private static int gcd(int a, int b) {\n" + + " if (b == 0) return Math.abs(a);\n" + + " else return gcd(b, a % b);\n" + + " }\n" + + " \n" + + " Rational(int num, int demon) {\n" + + " int gcd = gcd(num, denom);\n" + + " num /= gcd;\n" + + " denom /= gcd;\n" + + " this.num = num;\n" + + " this.denom = denom;\n" + + " }\n" + + "}\n" + ); + + RecordDeclaration recordDeclaration = cu.findFirst(RecordDeclaration.class).get(); + assertThat(recordDeclaration.getNameAsString()).isEqualTo("Rational"); + assertThat(recordDeclaration.getModifiers()).isEmpty(); + + assertThat(recordDeclaration.getConstructors()).hasSize(1); + assertThat(recordDeclaration.getCompactConstructors()).hasSize(0); + + } + + /** + * https://openjdk.java.net/jeps/395 + */ + @Test + void localRecords() { + CompilationUnit cu = TestParser.parseCompilationUnit("" + + "class Scratch {\n" + + " List findTopMerchants(List merchants, int month) {\n" + + " // Local record\n" + + " record MerchantSales(Merchant merchant, double sales) {}\n" + + "\n" + + " return merchants.stream()\n" + + " .map(merchant -> new MerchantSales(merchant, computeSales(merchant, month)))\n" + + " .sorted((m1, m2) -> Double.compare(m2.sales(), m1.sales()))\n" + + " .map(MerchantSales::merchant)\n" + + " .collect(toList());\n" + + " }\n" + + "}\n" + ); + + RecordDeclaration recordDeclaration = cu.findFirst(RecordDeclaration.class).get(); + assertThat(recordDeclaration.getNameAsString()).isEqualTo("MerchantSales"); + + } + + @Test + void instanceFieldIsNotAllowedInRecord() { + String s = "record X { int record; }"; + + assertThrows(AssertionFailedError.class, () -> { + CompilationUnit cu = TestParser.parseCompilationUnit(s); + }); + } + + private void assertCompilationFails(String s) { + assertThrows(AssertionFailedError.class, () -> { + CompilationUnit cu = TestParser.parseCompilationUnit(s); + }); + } + + private void assertOneRecordDeclaration(CompilationUnit cu) { + List recordDeclarations = cu.findAll(RecordDeclaration.class); + assertEquals(1, recordDeclarations.size()); + } + + private void assertTwoRecordDeclarations(CompilationUnit cu) { + List recordDeclarations = cu.findAll(RecordDeclaration.class); + assertEquals(2, recordDeclarations.size()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/TypeDeclarationTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/TypeDeclarationTest.java new file mode 100644 index 0000000..3356271 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/body/TypeDeclarationTest.java @@ -0,0 +1,84 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.body; + +import com.github.javaparser.ast.Node; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.utils.TestParser.parseBodyDeclaration; +import static com.github.javaparser.utils.TestParser.parseCompilationUnit; +import static java.util.stream.Collectors.joining; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class TypeDeclarationTest { + @Test + void qualifiedNameOfClassInDefaultPackage() { + assertFQN("X", parseCompilationUnit("class X{ }")); + } + + @Test + void qualifiedNameOfClassInAPackage() { + assertFQN("a.b.c.X", parseCompilationUnit("package a.b.c; class X{}")); + } + + @Test + void qualifiedNameOfInterfaceInAPackage() { + assertFQN("a.b.c.X", parseCompilationUnit("package a.b.c; interface X{}")); + } + + @Test + void qualifiedNameOfEnumInAPackage() { + assertFQN("a.b.c.X", parseCompilationUnit("package a.b.c; enum X{}")); + } + + @Test + void qualifiedNameOfAnnotationInAPackage() { + assertFQN("a.b.c.X", parseCompilationUnit("package a.b.c; @interface X{}")); + } + + @Test + void qualifiedNameOfNestedClassInAPackage() { + assertFQN("a.b.c.Outer,a.b.c.Outer.Nested", parseCompilationUnit("package a.b.c; class Outer{ class Nested {} }")); + } + + @Test + void qualifiedNameOfAnonymousClassCantBeQueried() { + assertFQN("X", parseCompilationUnit("class X{ int aaa() {new Object(){};} }")); + } + + @Test + void qualifiedNameOfLocalClassIsEmpty() { + assertFQN("X,?", parseCompilationUnit("class X{ int aaa() {class Local {}} }")); + } + + @Test + void qualifiedNameOfDetachedClassIsEmpty() { + assertFQN("?", parseBodyDeclaration("class X{}")); + } + + void assertFQN(String fqn, Node node) { + assertEquals(fqn, node.findAll(TypeDeclaration.class).stream() + .map(td -> (TypeDeclaration) td) + .map(td -> td.getFullyQualifiedName().orElse("?")) + .collect(joining(","))); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/comments/CommentTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/comments/CommentTest.java new file mode 100644 index 0000000..389236a --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/comments/CommentTest.java @@ -0,0 +1,204 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.comments; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.javadoc.Javadoc; +import com.github.javaparser.javadoc.description.JavadocDescription; +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.Indentation; +import com.github.javaparser.printer.configuration.Indentation.IndentType; +import com.github.javaparser.printer.configuration.PrinterConfiguration; +import org.junit.jupiter.api.Test; + +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.*; + +class CommentTest { + + private static final PrinterConfiguration PRETTY_PRINTER_CONFIG_TWO_INDENT = new DefaultPrinterConfiguration().addOption(new DefaultConfigurationOption(ConfigOption.INDENTATION, new Indentation(IndentType.SPACES, 2))); + + @Test + void removeOrphanComment() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(new NodeList<>(), false, "A"); + Comment c = new LineComment("A comment"); + decl.addOrphanComment(c); + assertEquals(1, decl.getOrphanComments().size()); + assertTrue(c.remove()); + assertEquals(0, decl.getOrphanComments().size()); + } + + @Test + void removeAssociatedComment() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(new NodeList<>(), false, "A"); + Comment c = new LineComment("A comment"); + decl.setComment(c); + assertTrue(decl.getComment().isPresent()); + assertTrue(c.remove()); + assertFalse(decl.getComment().isPresent()); + } + + @Test + void cannotRemoveCommentNotUsedAnywhere() { + Comment c = new LineComment("A comment"); + assertFalse(c.remove()); + } + + @Test + void unicodeEscapesArePreservedInComments() { + CompilationUnit cu = parse("// xxx\\u2122xxx"); + Comment comment = cu.getAllContainedComments().get(0); + assertEquals(" xxx\\u2122xxx", comment.getContent()); + } + + @Test + void testReplaceDuplicateJavaDocComment() { + // Arrange + CompilationUnit cu = parse("public class MyClass {" + SYSTEM_EOL + + SYSTEM_EOL + + " /**" + SYSTEM_EOL + + " * Comment A" + SYSTEM_EOL + + " */" + SYSTEM_EOL + + " public void oneMethod() {" + SYSTEM_EOL + + " }" + SYSTEM_EOL + + SYSTEM_EOL + + " /**" + SYSTEM_EOL + + " * Comment A" + SYSTEM_EOL + + " */" + SYSTEM_EOL + + " public void anotherMethod() {" + SYSTEM_EOL + + " }" + SYSTEM_EOL + + "}" + SYSTEM_EOL); + + MethodDeclaration methodDeclaration = cu.findFirst(MethodDeclaration.class).get(); + + // Act + Javadoc javadoc = new Javadoc(JavadocDescription.parseText("Change Javadoc")); + methodDeclaration.setJavadocComment("", javadoc); + + // Assert + assertEqualsStringIgnoringEol("public class MyClass {\n" + + "\n" + + " /**\n" + + " * Change Javadoc\n" + + " */\n" + + " public void oneMethod() {\n" + + " }\n" + + "\n" + + " /**\n" + + " * Comment A\n" + + " */\n" + + " public void anotherMethod() {\n" + + " }\n" + + "}\n", cu.toString(PRETTY_PRINTER_CONFIG_TWO_INDENT)); + } + + @Test + void testRemoveDuplicateComment() { + // Arrange + CompilationUnit cu = parse("public class MyClass {" + SYSTEM_EOL + + SYSTEM_EOL + + " /**" + SYSTEM_EOL + + " * Comment A" + SYSTEM_EOL + + " */" + SYSTEM_EOL + + " public void oneMethod() {" + SYSTEM_EOL + + " }" + SYSTEM_EOL + + SYSTEM_EOL + + " /**" + SYSTEM_EOL + + " * Comment A" + SYSTEM_EOL + + " */" + SYSTEM_EOL + + " public void anotherMethod() {" + SYSTEM_EOL + + " }" + SYSTEM_EOL + + "}" + + SYSTEM_EOL); + + MethodDeclaration methodDeclaration = cu.findFirst(MethodDeclaration.class).get(); + + // Act + methodDeclaration.removeComment(); + + // Assert + assertEqualsStringIgnoringEol("public class MyClass {\n" + + "\n" + + " public void oneMethod() {\n" + + " }\n" + + "\n" + + " /**\n" + + " * Comment A\n" + + " */\n" + + " public void anotherMethod() {\n" + + " }\n" + + "}\n", cu.toString(PRETTY_PRINTER_CONFIG_TWO_INDENT)); + } + + @Test + void testRemoveDuplicateJavaDocComment() { + // Arrange + CompilationUnit cu = parse("public class MyClass {" + SYSTEM_EOL + + SYSTEM_EOL + + " /**" + SYSTEM_EOL + + " * Comment A" + SYSTEM_EOL + + " */" + SYSTEM_EOL + + " public void oneMethod() {" + SYSTEM_EOL + + " }" + SYSTEM_EOL + + SYSTEM_EOL + + " /**" + SYSTEM_EOL + + " * Comment A" + SYSTEM_EOL + + " */" + SYSTEM_EOL + + " public void anotherMethod() {" + SYSTEM_EOL + + " }" + SYSTEM_EOL + + "}" + + SYSTEM_EOL); + + MethodDeclaration methodDeclaration = cu.findAll(MethodDeclaration.class).get(1); + + // Act + methodDeclaration.removeJavaDocComment(); + + // Assert + assertEqualsStringIgnoringEol("public class MyClass {\n" + + "\n" + + " /**\n" + + " * Comment A\n" + + " */\n" + + " public void oneMethod() {\n" + + " }\n" + + "\n" + + " public void anotherMethod() {\n" + + " }\n" + + "}\n", cu.toString(PRETTY_PRINTER_CONFIG_TWO_INDENT)); + } + + @Test() + void testVerifyOrphanCommentInsertedInEmptyBlock() { + BlockStmt block = new BlockStmt(); + block.addOrphanComment(new LineComment("TODO")); + assertTrue(block.toString().contains("TODO")); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/ArrayCreationExprTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/ArrayCreationExprTest.java new file mode 100644 index 0000000..f1ec609 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/ArrayCreationExprTest.java @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2013-2024 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.expr; + +import com.github.javaparser.ast.ArrayCreationLevel; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.type.PrimitiveType; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ArrayCreationExprTest { + + @Test + void correctlyCreatesExpressionWithDefaultConstructor() { + ArrayCreationExpr expr = new ArrayCreationExpr(); + + assertEquals("new empty[] {}", expr.toString()); + } + + @Test + void correctlyCreatesExpressionWithSimpleConstructor() { + ArrayCreationExpr expr = new ArrayCreationExpr(PrimitiveType.byteType()); + + assertEquals("new byte[] {}", expr.toString()); + } + + @Test + void correctlyCreatesExpressionWithFullConstructor() { + ArrayInitializerExpr initializer = new ArrayInitializerExpr(new NodeList<>( + new IntegerLiteralExpr("1"), + new IntegerLiteralExpr("2"), + new IntegerLiteralExpr("3") + )); + ArrayCreationExpr expr = new ArrayCreationExpr(PrimitiveType.intType(), new NodeList<>(new ArrayCreationLevel()), initializer); + + assertEquals("new int[] { 1, 2, 3 }", expr.toString()); + } +} \ No newline at end of file diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/AssignExprTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/AssignExprTest.java new file mode 100644 index 0000000..09968f0 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/AssignExprTest.java @@ -0,0 +1,33 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.expr; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class AssignExprTest { + @Test + void convertOperator() { + assertEquals(BinaryExpr.Operator.PLUS, AssignExpr.Operator.PLUS.toBinaryOperator().get()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/BinaryExprTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/BinaryExprTest.java new file mode 100644 index 0000000..88b2de2 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/BinaryExprTest.java @@ -0,0 +1,139 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.expr; + +import com.github.javaparser.StaticJavaParser; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class BinaryExprTest { + + @Test + void convertOperator() { + assertEquals(AssignExpr.Operator.PLUS, BinaryExpr.Operator.PLUS.toAssignOperator().get()); + } + + /** + * Evaluation takes place left to right, with && taking precedence over || + * + * true || false && false || false + * true || (1) || false + * ( 2 ) || false + * ( 3 ) + * + * true || false && false || false + * true || (false) || false + * ( true ) || false + * ( true ) + */ + @Nested + class LogicalOperatorPrecedence { + + @Test + public void logicalAndOr() { + Expression expression = StaticJavaParser.parseExpression("true || false && false || false"); + Expression bracketedExpression = applyBrackets(expression); + + String expected = "(true || (false && false)) || false"; + String actual = bracketedExpression.toString(); + + assertEquals(expected, actual); + } + + @Test + public void logicalOrEvaluationLeftToRight() { + Expression expression = StaticJavaParser.parseExpression("false || true || false || true || false || true"); + Expression bracketedExpression = applyBrackets(expression); + + String expected = "((((false || true) || false) || true) || false) || true"; + String actual = bracketedExpression.toString(); + + assertEquals(expected, actual); + } + + @Test + public void logicalAndEvaluationLeftToRight() { + Expression expression = StaticJavaParser.parseExpression("false && true && false && true && false && true"); + Expression bracketedExpression = applyBrackets(expression); + + String expected = "((((false && true) && false) && true) && false) && true"; + String actual = bracketedExpression.toString(); + + assertEquals(expected, actual); + } + + @Test + public void andTakesPrecedenceOverOr() { + Expression expression = StaticJavaParser.parseExpression("true || false && false"); + Expression bracketedExpression = applyBrackets(expression); + + String expected = "true || (false && false)"; + String actual = bracketedExpression.toString(); + + assertEquals(expected, actual); + } + + @Test + public void andTakesPrecedenceOverOrThenLeftToRight() { + Expression expression = StaticJavaParser.parseExpression("true || false && false || true"); + Expression bracketedExpression = applyBrackets(expression); + + String expected = "(true || (false && false)) || true"; + String actual = bracketedExpression.toString(); + + assertEquals(expected, actual); + } + + + @Test + public void example() { + Expression expression = StaticJavaParser.parseExpression("year % 4 == 0 && year % 100 != 0 || year % 400 == 0"); + Expression bracketedExpression = applyBrackets(expression); + + String expected = "((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)"; + String actual = bracketedExpression.toString(); + + assertEquals(expected, actual); + } + + + } + + + private Expression applyBrackets(Expression expression) { + expression.findAll(BinaryExpr.class) + .stream() + .filter(binaryExpr -> binaryExpr.getOperator() == BinaryExpr.Operator.AND || binaryExpr.getOperator() == BinaryExpr.Operator.OR) + .forEach(binaryExpr -> { + if(!binaryExpr.getLeft().isBooleanLiteralExpr()) { + binaryExpr.setLeft(new EnclosedExpr(binaryExpr.getLeft())); + } + if(!binaryExpr.getRight().isBooleanLiteralExpr()) { + binaryExpr.setRight(new EnclosedExpr(binaryExpr.getRight())); + } + }); + + return expression; + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/CharLiteralExprTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/CharLiteralExprTest.java new file mode 100644 index 0000000..529c18f --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/CharLiteralExprTest.java @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.expr; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseStart; +import com.github.javaparser.ParserConfiguration; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.StaticJavaParser.parseExpression; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class CharLiteralExprTest { + @Test + void parseSimpleChar() { + CharLiteralExpr c = parseExpression("'a'"); + assertEquals("a", c.getValue()); + } + + @Test + void parseSimpleEscape() { + CharLiteralExpr c = parseExpression("'\\t'"); + assertEquals("\\t", c.getValue()); + } + + @Test + void parseUnicode() { + CharLiteralExpr c = parseExpression("'Ω'"); + assertEquals("Ω", c.getValue()); + } + + @Test + void parseNumericEscape() { + CharLiteralExpr c = parseExpression("'\\177'"); + assertEquals("\\177", c.getValue()); + } + + @Test + void parseUnicodeEscape() { + CharLiteralExpr c = parseExpression("'\\u03a9'"); + assertEquals("\\u03a9", c.getValue()); + } + + @Test + void parseUnicodeEscapedEscape() { + JavaParser javaParser = new JavaParser(new ParserConfiguration() + .setPreprocessUnicodeEscapes(true)); + + CharLiteralExpr c = javaParser.parse(ParseStart.EXPRESSION, provider("'\\u005c''")).getResult().get().asCharLiteralExpr(); + assertEquals("\\'", c.getValue()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/DoubleLiteralExprTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/DoubleLiteralExprTest.java new file mode 100644 index 0000000..b2d8753 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/DoubleLiteralExprTest.java @@ -0,0 +1,64 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.expr; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.StaticJavaParser.parseExpression; + +class DoubleLiteralExprTest { + @Test + void test1() { + float x = 0x0.00_00_02p-126f; + DoubleLiteralExpr e = parseExpression("0x0.00_00_02p-126f"); + Assertions.assertEquals(x, e.asDouble()); + } + + @Test + void test2() { + double x = 0x0.000_000_000_000_1p-1_022; + DoubleLiteralExpr e = parseExpression("0x0.000_000_000_000_1p-1_022"); + Assertions.assertEquals(x, e.asDouble()); + } + + @Test + void test3() { + double a = 0x1.p+1; + DoubleLiteralExpr e = parseExpression("0x1.p+1"); + Assertions.assertEquals(a, e.asDouble()); + } + + @Test + void test4() { + double a = 0x.0p0; + DoubleLiteralExpr e = parseExpression("0x.0p0"); + Assertions.assertEquals(a, e.asDouble()); + } + + @Test + void test5() { + double x = 0x0_0.0_0p-1_0; + DoubleLiteralExpr e = parseExpression("0x0_0.0_0p-1_0"); + Assertions.assertEquals(x, e.asDouble()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/InstanceOfExprTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/InstanceOfExprTest.java new file mode 100644 index 0000000..78363ba --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/InstanceOfExprTest.java @@ -0,0 +1,181 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.expr; + +import com.github.javaparser.utils.TestParser; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.ParserConfiguration.LanguageLevel; +import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; +import static org.junit.jupiter.api.Assertions.*; + +/** + * See the following JEPs: "Pattern Matching for instanceof" + *

    + *
  • JDK14 - Preview - https://openjdk.java.net/jeps/305
  • + *
  • JDK15 - Second Preview - https://openjdk.java.net/jeps/375
  • + *
  • JDK16 - Release - https://openjdk.java.net/jeps/395
  • + *
+ * + *
+ * The instanceof grammar is extended accordingly: + * + *
+ *     RelationalExpression:
+ *          ...
+ *          RelationalExpression instanceof ReferenceType
+ *          RelationalExpression instanceof Pattern
+ *
+ *     Pattern:
+ *          ReferenceType Identifier
+ * 
+ *
+ */ +class InstanceOfExprTest { + + @Test + void annotationsOnTheType_patternExpression() { + InstanceOfExpr expr = TestParser.parseExpression(LanguageLevel.JAVA_14_PREVIEW, "obj instanceof @A @DA String s"); + + assertThat(expr.getType().getAnnotations()) + .containsExactly( + new MarkerAnnotationExpr("A"), + new MarkerAnnotationExpr("DA") + ); + } + + @Test + void annotationsOnTheType_finalPatternExpression() { + InstanceOfExpr expr = TestParser.parseExpression(LanguageLevel.JAVA_14_PREVIEW, "obj instanceof @A final @DA String s"); + + assertThat(expr.getType().getAnnotations()) + .containsExactly( + new MarkerAnnotationExpr("A"), + new MarkerAnnotationExpr("DA")); + } + + @Test + void annotationsOnTheType_finalPatternExpression_prettyPrinter() { + InstanceOfExpr expr = TestParser.parseExpression(LanguageLevel.JAVA_14_PREVIEW, "obj instanceof @A final @DA String s"); + + assertEquals("obj instanceof final @A @DA String s", expr.toString()); + } + + @Test + void annotationsOnTheType_referenceTypeExpression() { + InstanceOfExpr expr = TestParser.parseExpression(LanguageLevel.JAVA_14, "obj instanceof @A @DA String"); + + assertThat(expr.getType().getAnnotations()) + .containsExactly( + new MarkerAnnotationExpr("A"), + new MarkerAnnotationExpr("DA") + ); + } + + @Test + void instanceOf_patternExpression() { + String x = "obj instanceof String s"; + InstanceOfExpr expr = TestParser.parseExpression(LanguageLevel.JAVA_14_PREVIEW, x); + + assertEquals("obj", expr.getExpression().toString()); + assertEquals("String", expr.getType().asString()); + assertTrue(expr.getPattern().isPresent()); + + PatternExpr patternExpr = expr.getPattern().get(); + assertEquals("String", patternExpr.getType().asString()); + assertEquals("s", patternExpr.getName().asString()); + assertFalse(patternExpr.isFinal()); + + // + assertTrue(expr.getName().isPresent()); + assertEquals("s", expr.getName().get().asString()); + } + + @Test + void instanceOf_patternExpression_prettyPrinter() { + String x = "obj instanceof String s"; + InstanceOfExpr expr = TestParser.parseExpression(LanguageLevel.JAVA_14_PREVIEW, x); + + assertEquals("obj instanceof String s", expr.toString()); + } + + @Test + void instanceOf_referenceTypeExpression() { + String x = "obj instanceof String"; + InstanceOfExpr expr = TestParser.parseExpression(LanguageLevel.JAVA_14, x); + + assertEquals("obj", expr.getExpression().toString()); + assertEquals(String.class.getSimpleName(), expr.getType().asString()); + assertFalse(expr.getPattern().isPresent()); + + // + assertFalse(expr.getName().isPresent()); + } + + @Test + void instanceOf_finalPatternExpression() { + String x = "obj instanceof final String s"; + InstanceOfExpr expr = TestParser.parseExpression(LanguageLevel.JAVA_14_PREVIEW, x); + + assertEquals("obj", expr.getExpression().toString()); + assertEquals("String", expr.getType().asString()); + assertTrue(expr.getPattern().isPresent()); + + PatternExpr patternExpr = expr.getPattern().get(); + assertEquals("String", patternExpr.getType().asString()); + assertEquals("s", patternExpr.getName().asString()); + assertTrue(patternExpr.isFinal()); + + // + assertTrue(expr.getName().isPresent()); + assertEquals("s", expr.getName().get().asString()); + } + + @Test + void instanceOf_finalPatternExpression_prettyPrinter() { + String x = "obj instanceof final String s"; + InstanceOfExpr expr = TestParser.parseExpression(LanguageLevel.JAVA_14_PREVIEW, x); + + assertEquals("obj instanceof final String s", expr.toString()); + } + + + /* + * resolution / scoping tests? + * + *
+     * {@code
+     * if (!(obj instanceof String s)) {
+     *     .. s.contains(..) ..
+     * } else {
+     *     .. s.contains(..) ..
+     * }
+     * }
+     * 
+ * + * Allowed / in scope: {@code if (obj instanceof String s && s.length() > 5) {..}} + * Not in scope: {@code if (obj instanceof String s || s.length() > 5) {..}} + * + */ + + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/LambdaExprTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/LambdaExprTest.java new file mode 100644 index 0000000..f4b7efb --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/LambdaExprTest.java @@ -0,0 +1,97 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.expr; + +import com.github.javaparser.TokenRange; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.Parameter; +import com.github.javaparser.ast.type.UnknownType; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.StaticJavaParser.parseBlock; +import static com.github.javaparser.StaticJavaParser.parseExpression; +import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class LambdaExprTest { + @Test + void lambdaRange1() { + Expression expression = parseExpression("x -> y"); + assertRange("x", "y", expression); + } + + @Test + void lambdaRange2() { + Expression expression = parseExpression("(x) -> y"); + assertRange("(", "y", expression); + } + + private void assertRange(String startToken, String endToken, Node node) { + TokenRange tokenRange = node.getTokenRange().get(); + assertEquals(startToken, tokenRange.getBegin().asString()); + assertEquals(endToken, tokenRange.getEnd().asString()); + } + + @Test + void getExpressionBody() { + LambdaExpr lambdaExpr = parseExpression("x -> y").asLambdaExpr(); + assertEquals("Optional[y]", lambdaExpr.getExpressionBody().toString()); + } + + @Test + void getNoExpressionBody() { + LambdaExpr lambdaExpr = parseExpression("x -> {y;}").asLambdaExpr(); + assertEquals("Optional.empty", lambdaExpr.getExpressionBody().toString()); + } + + @Test + void oneParameterAndExpressionUtilityConstructor() { + LambdaExpr expr = new LambdaExpr(new Parameter(new UnknownType(), "a"), parseExpression("5")); + assertEquals("a -> 5", expr.toString()); + } + + @Test + void oneParameterAndStatementUtilityConstructor() { + LambdaExpr expr = new LambdaExpr(new Parameter(new UnknownType(), "a"), parseBlock("{return 5;}")); + assertEqualsStringIgnoringEol("a -> {\n return 5;\n}", expr.toString()); + } + + @Test + void multipleParametersAndExpressionUtilityConstructor() { + LambdaExpr expr = new LambdaExpr(new NodeList<>(new Parameter(new UnknownType(), "a"), new Parameter(new UnknownType(), "b")), parseExpression("5")); + assertEquals("(a, b) -> 5", expr.toString()); + } + + @Test + void multipleParametersAndStatementUtilityConstructor() { + LambdaExpr expr = new LambdaExpr(new NodeList<>(new Parameter(new UnknownType(), "a"), new Parameter(new UnknownType(), "b")), parseBlock("{return 5;}")); + assertEqualsStringIgnoringEol("(a, b) -> {\n return 5;\n}", expr.toString()); + } + + @Test + void zeroParametersAndStatementUtilityConstructor() { + LambdaExpr expr = new LambdaExpr(new NodeList<>(), parseBlock("{return 5;}")); + assertEqualsStringIgnoringEol("() -> {\n return 5;\n}", expr.toString()); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/LiteralStringValueExprTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/LiteralStringValueExprTest.java new file mode 100644 index 0000000..18c3954 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/LiteralStringValueExprTest.java @@ -0,0 +1,185 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.expr; + +import org.assertj.core.data.Percentage; +import org.junit.jupiter.api.Test; + +import java.math.BigInteger; + +import static com.github.javaparser.StaticJavaParser.parseExpression; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +@SuppressWarnings("OctalInteger") +class LiteralStringValueExprTest { + + @Test + void trivialLiteralsAreConverted() { + assertThat(new CharLiteralExpr('\t').getValue()).isEqualTo("\\t"); + assertThat(new CharLiteralExpr('\b').getValue()).isEqualTo("\\b"); + assertThat(new CharLiteralExpr('\f').getValue()).isEqualTo("\\f"); + assertThat(new CharLiteralExpr('\r').getValue()).isEqualTo("\\r"); + assertThat(new CharLiteralExpr('\n').getValue()).isEqualTo("\\n"); + assertThat(new CharLiteralExpr('\\').getValue()).isEqualTo("\\\\"); + assertThat(new CharLiteralExpr('\"').getValue()).isEqualTo("\\\""); + + assertThat(new IntegerLiteralExpr("0B0").asInt()).isEqualTo(0); + assertThat(new IntegerLiteralExpr("0b0").asInt()).isEqualTo(0); + assertThat(new IntegerLiteralExpr("0X0").asInt()).isEqualTo(0); + assertThat(new IntegerLiteralExpr("0x0").asInt()).isEqualTo(0); + assertThat(new IntegerLiteralExpr(0).asInt()).isEqualTo(0); + assertThat(new IntegerLiteralExpr(00).asInt()).isEqualTo(0); + assertThat(new IntegerLiteralExpr(0B0).asInt()).isEqualTo(0); + assertThat(new IntegerLiteralExpr(0b0).asInt()).isEqualTo(0); + assertThat(new IntegerLiteralExpr(0X0).asInt()).isEqualTo(0); + assertThat(new IntegerLiteralExpr(0x0).asInt()).isEqualTo(0); + + assertThat(new LongLiteralExpr("0B0L").asLong()).isEqualTo(0); + assertThat(new LongLiteralExpr("0b0L").asLong()).isEqualTo(0); + assertThat(new LongLiteralExpr("0X0L").asLong()).isEqualTo(0); + assertThat(new LongLiteralExpr("0x0L").asLong()).isEqualTo(0); + assertThat(new LongLiteralExpr(0L).asLong()).isEqualTo(0); + assertThat(new LongLiteralExpr(00L).asLong()).isEqualTo(0); + assertThat(new LongLiteralExpr(0B0L).asLong()).isEqualTo(0); + assertThat(new LongLiteralExpr(0b0L).asLong()).isEqualTo(0); + assertThat(new LongLiteralExpr(0X0L).asLong()).isEqualTo(0); + assertThat(new LongLiteralExpr(0x0L).asLong()).isEqualTo(0); + + assertThat(new DoubleLiteralExpr("0.0f").asDouble()).isEqualTo(0.0); + assertThat(new DoubleLiteralExpr("0.0F").asDouble()).isEqualTo(0.0); + assertThat(new DoubleLiteralExpr("0.0d").asDouble()).isEqualTo(0.0); + assertThat(new DoubleLiteralExpr("0.0D").asDouble()).isEqualTo(0.0); + assertThat(new DoubleLiteralExpr(0.0F).asDouble()).isEqualTo(0.0); + assertThat(new DoubleLiteralExpr(0.0f).asDouble()).isEqualTo(0.0); + assertThat(new DoubleLiteralExpr(0.0D).asDouble()).isEqualTo(0.0); + assertThat(new DoubleLiteralExpr(0.0d).asDouble()).isEqualTo(0.0); + } + + @Test + void lowerAndUpperBoundIntegersAreConverted() { + IntegerLiteralExpr dec = parseExpression("2147483647"); + IntegerLiteralExpr posOct = parseExpression("0177_7777_7777"); + IntegerLiteralExpr negOct = parseExpression("0377_7777_7777"); + IntegerLiteralExpr posHex = parseExpression("0x7fff_ffff"); + IntegerLiteralExpr negHex = parseExpression("0xffff_ffff"); + IntegerLiteralExpr posBin = parseExpression("0b0111_1111_1111_1111_1111_1111_1111_1111"); + IntegerLiteralExpr negBin = parseExpression("0b1000_0000_0000_0000_0000_0000_0000_0000"); + + assertThat(dec.asInt()).isEqualTo(2147483647); + assertThat(posOct.asInt()).isEqualTo(2147483647); // 0177_7777_7777 + assertThat(negOct.asInt()).isEqualTo(-1); // 0377_7777_7777 + assertThat(posHex.asInt()).isEqualTo(0x7fff_ffff); + assertThat(negHex.asInt()).isEqualTo(0xffff_ffff); + assertThat(posBin.asInt()).isEqualTo(0b0111_1111_1111_1111_1111_1111_1111_1111); + assertThat(negBin.asInt()).isEqualTo(0b1000_0000_0000_0000_0000_0000_0000_0000); + } + + @Test + void negativeLiteralValues() { + UnaryExpr unaryIntExpr = parseExpression("-2147483648"); // valid, Integer.MIN_VALUE + IntegerLiteralExpr literalIntExpr = (IntegerLiteralExpr) unaryIntExpr.getExpression(); + IntegerLiteralExpr notValidIntExpr = parseExpression("2147483648"); // not valid + + UnaryExpr unaryLongExpr = parseExpression("-9223372036854775808L"); // valid, Long.MIN_VALUE + LongLiteralExpr literalLongExpr = (LongLiteralExpr) unaryLongExpr.getExpression(); + LongLiteralExpr notValidLongExpr = parseExpression("9223372036854775808L"); // not valid + + assertThat(literalIntExpr.asNumber()).isEqualTo(2147483648L); + assertThat(literalLongExpr.asNumber()).isEqualTo(new BigInteger("9223372036854775808")); + + assertThatThrownBy(notValidIntExpr::asNumber).isInstanceOf(NumberFormatException.class); + assertThatThrownBy(notValidLongExpr::asNumber).isInstanceOf(NumberFormatException.class); + } + + @Test + void lowerAndUpperBoundLongsAreConverted() { + LongLiteralExpr dec = parseExpression("9223372036854775807L"); + LongLiteralExpr posOct = parseExpression("07_7777_7777_7777_7777_7777L"); + LongLiteralExpr negOct = parseExpression("010_0000_0000_0000_0000_0000L"); + LongLiteralExpr posHex = parseExpression("0x7fff_ffff_ffff_ffffL"); + LongLiteralExpr negHex = parseExpression("0xffff_ffff_ffff_ffffL"); + LongLiteralExpr posBin = parseExpression("0b0111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111L"); + LongLiteralExpr negBin = parseExpression("0b1000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000L"); + + assertThat(dec.asLong()).isEqualTo(9223372036854775807L); + assertThat(posOct.asLong()).isEqualTo(9223372036854775807L); // 07_7777_7777_7777_7777_7777L + assertThat(negOct.asLong()).isEqualTo(-9223372036854775808L); // 010_0000_0000_0000_0000_0000L + assertThat(posHex.asLong()).isEqualTo(0x7fff_ffff_ffff_ffffL); + assertThat(negHex.asLong()).isEqualTo(0xffff_ffff_ffff_ffffL); + assertThat(posBin.asLong()).isEqualTo(0b0111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111L); + assertThat(negBin.asLong()).isEqualTo(0b1000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000L); + } + + @Test + void charLiteralsAreConverted() { + CharLiteralExpr a = parseExpression("'a'"); + CharLiteralExpr percent = parseExpression("'%'"); + CharLiteralExpr tab = parseExpression("'\\t'"); + CharLiteralExpr newLine = parseExpression("'\\n'"); + CharLiteralExpr slash = parseExpression("'\\\\'"); + CharLiteralExpr quote = parseExpression("'\\''"); + CharLiteralExpr omega = parseExpression("'\\u03a9'"); + CharLiteralExpr unicode = parseExpression("'\\uFFFF'"); + CharLiteralExpr ascii = parseExpression("'\\177'"); + CharLiteralExpr trademark = parseExpression("'™'"); + + assertThat(a.asChar()).isEqualTo('a'); + assertThat(percent.asChar()).isEqualTo('%'); + assertThat(tab.asChar()).isEqualTo('\t'); + assertThat(newLine.asChar()).isEqualTo('\n'); + assertThat(slash.asChar()).isEqualTo('\\'); + assertThat(quote.asChar()).isEqualTo('\''); + assertThat(omega.asChar()).isEqualTo('\u03a9'); + assertThat(unicode.asChar()).isEqualTo('\uFFFF'); + assertThat(ascii.asChar()).isEqualTo('\177'); + assertThat(trademark.asChar()).isEqualTo('™'); + } + + @Test + void lowerAndUpperBoundDoublesAreConverted() { + DoubleLiteralExpr posFloat = parseExpression("3.4028235e38f"); + DoubleLiteralExpr negFloat = parseExpression("1.40e-45f"); + DoubleLiteralExpr posDouble = parseExpression("1.7976931348623157e308"); + DoubleLiteralExpr negDouble = parseExpression("4.9e-324"); + DoubleLiteralExpr posHexFloat = parseExpression("0x1.fffffffffffffp1023"); + DoubleLiteralExpr negHexFloat = parseExpression("0x0.0000000000001P-1022"); + + assertThat(posFloat.asDouble()).isCloseTo(3.4028235e38f, Percentage.withPercentage(1)); + assertThat(negFloat.asDouble()).isCloseTo(1.40e-45f, Percentage.withPercentage(1)); + assertThat(posDouble.asDouble()).isEqualTo(1.7976931348623157e308); + assertThat(negDouble.asDouble()).isEqualTo(4.9e-324); + assertThat(posHexFloat.asDouble()).isEqualTo(0x1.fffffffffffffp1023); + assertThat(negHexFloat.asDouble()).isEqualTo(0x0.0000000000001P-1022); + } + + @Test + void specialCharactersInStringsAreEscaped() { + assertThat(new StringLiteralExpr("\n").getValue()).isEqualTo("\\n"); + assertThat(new StringLiteralExpr("\r").getValue()).isEqualTo("\\r"); + assertThat(new StringLiteralExpr("").setEscapedValue("\n").getValue()).isEqualTo("\\n"); + assertThat(new StringLiteralExpr("").setEscapedValue("\r").getValue()).isEqualTo("\\r"); + assertThat(new StringLiteralExpr("").setEscapedValue("\n").asString()).isEqualTo("\n"); + assertThat(new StringLiteralExpr("").setEscapedValue("\r").asString()).isEqualTo("\r"); + assertThat(new StringLiteralExpr("Hello\nWorld\rHello\"World\'").asString()).isEqualTo("Hello\nWorld\rHello\"World\'"); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/MethodCallExprTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/MethodCallExprTest.java new file mode 100644 index 0000000..0052c64 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/MethodCallExprTest.java @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.expr; + +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.StaticJavaParser.parseExpression; +import static java.util.Optional.empty; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class MethodCallExprTest { + + @Test + void replaceLambdaIssue1290() { + MethodCallExpr methodCallExpr = parseExpression("callSomeFun(r -> r instanceof SomeType)").asMethodCallExpr(); + LambdaExpr lambdaExpr = methodCallExpr.getArgument(0).asLambdaExpr(); + MethodCallExpr lambdaWrapper = new MethodCallExpr("lambdaWrapper"); + lambdaExpr.replace(lambdaWrapper); + + assertEquals(2, methodCallExpr.getChildNodes().size()); + assertEquals(empty(), lambdaExpr.getParentNode()); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/MethodReferenceExprTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/MethodReferenceExprTest.java new file mode 100644 index 0000000..d5bceb8 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/MethodReferenceExprTest.java @@ -0,0 +1,135 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.expr; + +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.utils.TestUtils.assertExpressionValid; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class MethodReferenceExprTest { + + @Test + void methodReferenceExprHasAlwaysAScope() { + assertNotNull(new MethodReferenceExpr().getScope()); + } + + @Test + void reference1() { + assertExpressionValid("String::length"); + } + + @Test + void reference2() { + assertExpressionValid("System::currentTimeMillis // static method"); + } + + @Test + void reference3() { + assertExpressionValid("List::size // explicit type arguments for generic type"); + } + + @Test + void reference4() { + assertExpressionValid("List::size // inferred type arguments for generic type"); + } + + @Test + void reference5() { + assertExpressionValid("int[]::clone"); + } + + @Test + void reference6() { + assertExpressionValid("T::tvarMember"); + } + + @Test + void reference7() { + assertExpressionValid("System.out::println"); + } + + @Test + void reference8() { + assertExpressionValid("\"abc\"::length"); + } + + @Test + void reference9() { + assertExpressionValid("foo[x]::bar"); + } + + @Test + void reference10() { + assertExpressionValid("(test ? list.replaceAll(String::trim) : list) :: iterator"); + } + + @Test + void reference10Annotated1() { + assertExpressionValid("(test ? list.replaceAll(@A String::trim) : list) :: iterator"); + } + + @Test + void reference11() { + assertExpressionValid("String::valueOf // overload resolution needed"); + } + + @Test + void reference12() { + assertExpressionValid("Arrays::sort // type arguments inferred from context"); + } + + @Test + void reference13() { + assertExpressionValid("Arrays::sort // explicit type arguments"); + } + + @Test + void reference14() { + assertExpressionValid("ArrayList::new // constructor for parameterized type"); + } + + @Test + void reference15() { + assertExpressionValid("ArrayList::new // inferred type arguments"); + } + + @Test + void reference16() { + assertExpressionValid("Foo::new // explicit type arguments"); + } + + @Test + void reference17() { + assertExpressionValid("Bar::new // generic class, generic constructor"); + } + + @Test + void reference18() { + assertExpressionValid("Outer.Inner::new // inner class constructor"); + } + + @Test + void reference19() { + assertExpressionValid("int[]::new // array creation"); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/NameTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/NameTest.java new file mode 100644 index 0000000..a27ddd4 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/NameTest.java @@ -0,0 +1,101 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.expr; + +import com.github.javaparser.ParseProblemException; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.ImportDeclaration; +import com.github.javaparser.printer.ConcreteSyntaxModel; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.StaticJavaParser.*; +import static com.github.javaparser.utils.Utils.SYSTEM_EOL; +import static org.junit.jupiter.api.Assertions.*; + +class NameTest { + + @Test + void outerNameExprIsTheRightMostIdentifier() { + Name name = parseName("a.b.c"); + assertEquals("c", name.getIdentifier()); + } + + @Test + void parsingAndUnparsingWorks() { + Name name = parseName("a.b.c"); + assertEquals("a.b.c", name.asString()); + } + + @Test + void parsingEmptyNameThrowsException() { + assertThrows(ParseProblemException.class, () -> parseName("")); + } + + @Test + void importName() { + ImportDeclaration importDeclaration = parseImport("import java.util.List;"); + + assertEquals("import java.util.List;" + SYSTEM_EOL, importDeclaration.toString()); + assertEquals("import java.util.List;" , ConcreteSyntaxModel.genericPrettyPrint(importDeclaration)); + } + + @Test + void packageName() { + CompilationUnit cu = parse("package p1.p2;"); + + assertEquals("package p1.p2;" + SYSTEM_EOL + SYSTEM_EOL, cu.toString()); + assertEquals("package p1.p2;" + SYSTEM_EOL + SYSTEM_EOL, ConcreteSyntaxModel.genericPrettyPrint(cu)); + } + + @Test + void isInternalNegative() { + Name name = parseName("a.b.c"); + assertFalse(name.isInternal()); + } + + @Test + void isInternalPositive() { + Name name = parseName("a.b.c"); + assertTrue(name + .getQualifier().get().isInternal()); + assertTrue(name + .getQualifier().get() + .getQualifier().get().isInternal()); + } + + @Test + void isTopLevelNegative() { + Name name = parseName("a.b.c"); + assertFalse(name + .getQualifier().get().isTopLevel()); + assertFalse(name + .getQualifier().get() + .getQualifier().get().isTopLevel()); + } + + @Test + void isTopLevelPositive() { + Name name = parseName("a.b.c"); + assertTrue(name.isTopLevel()); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/ObjectCreationExprTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/ObjectCreationExprTest.java new file mode 100644 index 0000000..f94be49 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/ObjectCreationExprTest.java @@ -0,0 +1,35 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.expr; + +import com.github.javaparser.utils.TestParser; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ObjectCreationExprTest { + @Test + void aaa() { + Expression e = TestParser.parseExpression("new @Test N()"); + assertEquals("new @Test N()", e.toString()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/SimpleNameTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/SimpleNameTest.java new file mode 100644 index 0000000..159d9e8 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/SimpleNameTest.java @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.expr; + +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.StaticJavaParser.parseSimpleName; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class SimpleNameTest { + + @Test + void defaultConstructorSetsIdentifierToEmpty() { + assertEquals("empty", new SimpleName().getIdentifier()); + } + + @Test + void identifierMustNotBeEmpty() { + assertThrows(AssertionError.class, () -> new SimpleName("")); + } + + @Test + void identifierMustNotBeNull() { + assertThrows(AssertionError.class, () -> new SimpleName(null)); + } + + @Test + void unicodeEscapesArePreservedInIdentifiers() { + SimpleName name = parseSimpleName("xxx\\u2122xxx"); + assertEquals("xxx\\u2122xxx", name.asString()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/StringLiteralExprTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/StringLiteralExprTest.java new file mode 100644 index 0000000..d041659 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/StringLiteralExprTest.java @@ -0,0 +1,35 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.expr; + +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.StaticJavaParser.parseExpression; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class StringLiteralExprTest { + @Test + void unicodeEscapesArePreservedInStrings() { + StringLiteralExpr omega = parseExpression("\"xxx\\u03a9xxx\""); + assertEquals("xxx\\u03a9xxx", omega.getValue()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/SuperExprTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/SuperExprTest.java new file mode 100644 index 0000000..0b4e1f0 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/SuperExprTest.java @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.expr; + +import com.github.javaparser.ParseProblemException; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.StaticJavaParser.parseExpression; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class SuperExprTest { + @Test + void justSuper() { + assertThrows(ParseProblemException.class, () -> parseExpression("super")); + } + + @Test + void singleScopeSuper() { + Expression expr = parseExpression("A.super"); + + Name className = expr.asSuperExpr().getTypeName().get(); + + assertEquals("A", className.asString()); + } + + @Test + void multiScopeSuper() { + Expression expr = parseExpression("a.B.super"); + + Name className = expr.asSuperExpr().getTypeName().get(); + + assertEquals("a.B", className.asString()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/SwitchExprTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/SwitchExprTest.java new file mode 100644 index 0000000..0646252 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/SwitchExprTest.java @@ -0,0 +1,213 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.expr; + +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.ast.stmt.SwitchEntry; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.ast.stmt.SwitchEntry.Type.*; +import static com.github.javaparser.utils.TestParser.*; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class SwitchExprTest { + @Test + void jep325Example2() { + NodeList entry2labels = parseStatement("int numLetters = switch (day) {\n" + + " case MONDAY, FRIDAY, SUNDAY -> 6;\n" + + " case TUESDAY -> 7;\n" + + " case THURSDAY, SATURDAY -> 8;\n" + + " case WEDNESDAY -> 9;\n" + + "};").findAll(SwitchEntry.class).get(0).getLabels(); + + assertEquals(3, entry2labels.size()); + assertEquals("MONDAY", entry2labels.get(0).toString()); + assertEquals("FRIDAY", entry2labels.get(1).toString()); + assertEquals("SUNDAY", entry2labels.get(2).toString()); + } + + @Test + void funkyExpressions() { + parseStatement("int numLetters = switch (day) {\n" + + " case 1+1, 2+2 -> 6;\n" + + " case \"Henk\"-> 7;\n" + + " case ((3)+3)+3 -> 8;\n" + + "};"); + } + + @Test + void jep325Example3() { + parseBodyDeclaration("static void howMany(int k) {\n" + + " switch (k) {\n" + + " case 1 -> System.out.println(\"one\");\n" + + " case 2 -> System.out.println(\"two\");\n" + + " case 3 -> System.out.println(\"many\");\n" + + " }\n" + + "}"); + } + + + @Test + void aThrowStatement() { + SwitchExpr switchExpr = parseExpression("switch (k) {\n" + + " case 1 -> throw new Exception(\"one\");\n" + + " }").findFirst(SwitchExpr.class).get(); + + assertEquals(THROWS_STATEMENT, switchExpr.getEntry(0).getType()); + } + + @Test + void jep325Example4() { + SwitchExpr switchExpr = parseStatement("T result = switch (arg) {\n" + + " case L1 -> e1;\n" + + " case L2 -> e2;\n" + + " default -> e3;\n" + + "};").findFirst(SwitchExpr.class).get(); + + assertEquals(EXPRESSION, switchExpr.getEntry(0).getType()); + } + + @Test + void jep325Example5() { + SwitchExpr switchExpr = parseStatement("int j = switch (day) {\n" + + " case MONDAY -> 0;\n" + + " case TUESDAY -> 1;\n" + + " default -> {\n" + + " int k = day.toString().length();\n" + + " int result = f(k);\n" + + " yield result;\n" + + " }\n" + + "};").findFirst(SwitchExpr.class).get(); + + assertEquals(BLOCK, switchExpr.getEntry(2).getType()); + assertEquals(BlockStmt.class, switchExpr.getEntry(2).getStatements().get(0).getClass()); + } + + @Test + void jep325Example6() { + parseStatement("int result = switch (s) {\n" + + " case \"Foo\": \n" + + " yield 1;\n" + + " case \"Bar\":\n" + + " yield 2;\n" + + " default:\n" + + " System.out.println(\"Neither Foo nor Bar, hmmm...\");\n" + + " yield 0;\n" + + "};"); + } + + @Test + void yieldMethodCall() { + parseStatement("int randomNumber = switch (5) {\n" + + " default -> {\n" + + " yield a.randomNumberGenerator();\n" + + " }\n" + + " case 1 -> {\n" + + " yield method();\n" + + " }\n" + + " case 2 -> {\n" + + " yield method(args);\n" + + " }\n" + + " case 3 -> {\n" + + " yield this.method();\n" + + " }\n" + + " case 4 -> {\n" + + " yield Clazz.this.method(args);\n" + + " }\n" + + "};"); + } + + @Test + void yieldExpression1() { + parseStatement("int randomNumber = switch (5) {\n" + + " default -> {\n" + + " yield 1 * 1;\n" + + " }\n" + + " case 1 -> {\n" + + " yield (5 + 5);\n" + + " }\n" + + " case 2 -> {\n" + + " yield (5 + 5) * 3;\n" + + " }\n" + + "};"); + } + + @Test + void yieldExpression2() { + parseStatement("boolean b = switch (5) {\n" + + " case 3 -> {\n" + + " yield true || false;\n" + + " }\n" + + " default -> {\n" + + " yield !true;\n" + + " }\n" + + "};"); + } + + @Test + void yieldAssignment() { + parseStatement("int randomNumber = switch (5) {\n" + + " default -> {\n" + + " int x;\n" + + " yield (x = 5);\n" + + " }\n" + + " case 'a' -> {\n" + + " int x;\n" + + " yield x = 3;\n" + + " }\n" + + "};"); + } + + @Test + void yieldConditional() { + parseStatement("int randomNumber = switch (5) {\n" + + " default -> {\n" + + " yield x ? 1 : 2;\n" + + " }\n" + + " case 1 -> {\n" + + " yield (x ? 1 : 2);\n" + + " }\n" + + " case 2 -> {\n" + + " yield x < 0 ? 0 : x > y ? y : x;\n" + + " }\n" + + "};"); + } + + @Test + void yieldYield() { + parseStatement("yield = switch (yield) {\n" + + " default -> {\n" + + " yield yield;\n" + + " }\n" + + " case yield -> {\n" + + " yield Clazz.yield();\n" + + " }\n" + + " case enumValue2 -> {\n" + + " yield yield = yield;\n" + + " }\n" + + " case enumValue3 -> {\n" + + " yield yield == yield ? yield : yield;\n" + + " }\n" + + "};"); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/TextBlockLiteralExprTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/TextBlockLiteralExprTest.java new file mode 100644 index 0000000..12863ad --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/TextBlockLiteralExprTest.java @@ -0,0 +1,204 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.expr; + +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.utils.TestParser.parseStatement; +import static java.util.Arrays.asList; +import static java.util.stream.Collectors.toList; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class TextBlockLiteralExprTest { + @Test + void htmlExample() { + TextBlockLiteralExpr textBlock = parseStatement("String html = \"\"\"\n" + + " \n" + + " \n" + + "

Hello, world

\n" + + " \n" + + " \n" + + " \"\"\";").findFirst(TextBlockLiteralExpr.class).get(); + + assertEquals(" \n" + + " \n" + + "

Hello, world

\n" + + " \n" + + " \n" + + " ", textBlock.getValue()); + + assertEquals(asList( + "", + " ", + "

Hello, world

", + " ", + "", + "" + ), textBlock.stripIndentOfLines().collect(toList())); + + assertEquals("\n" + + " \n" + + "

Hello, world

\n" + + " \n" + + "\n", textBlock.stripIndent()); + + assertEquals("\n" + + " \n" + + "

Hello, world

\n" + + " \n" + + "\n", textBlock.translateEscapes()); + } + + @Test + void htmlExampleWithEndAllToTheLeft() { + TextBlockLiteralExpr textBlock = parseStatement("String html = \"\"\"\n" + + " \n" + + " \n" + + "

Hello, world

\n" + + " \n" + + " \n" + + "\"\"\";").findFirst(TextBlockLiteralExpr.class).get(); + + assertEquals( + " \n" + + " \n" + + "

Hello, world

\n" + + " \n" + + " \n", textBlock.translateEscapes()); + } + + @Test + void htmlExampleWithEndALittleToTheLeft() { + TextBlockLiteralExpr textBlock = parseStatement("String html = \"\"\"\n" + + " \n" + + " \n" + + "

Hello, world

\n" + + " \n" + + " \n" + + " \"\"\";").findFirst(TextBlockLiteralExpr.class).get(); + + assertEquals(" \n" + + " \n" + + "

Hello, world

\n" + + " \n" + + " \n", textBlock.translateEscapes()); + } + + @Test + void htmlExampleWithEndALittleToTheRight() { + TextBlockLiteralExpr textBlock = parseStatement("String html = \"\"\"\n" + + " \n" + + " \n" + + "

Hello, world

\n" + + " \n" + + " \n" + + " \"\"\";").findFirst(TextBlockLiteralExpr.class).get(); + + assertEquals("\n" + + " \n" + + "

Hello, world

\n" + + " \n" + + "\n", textBlock.translateEscapes()); + } + + @Test + void itIsLegalToUseDoubleQuoteFreelyInsideATextBlock() { + parseStatement("String story = \"\"\"\n" + + " \"When I use a word,\" Humpty Dumpty said,\n" + + " in rather a scornful tone, \"it means just what I\n" + + " choose it to mean - neither more nor less.\"\n" + + " \"The question is,\" said Alice, \"whether you\n" + + " can make words mean so many different things.\"\n" + + " \"The question is,\" said Humpty Dumpty,\n" + + " \"which is to be master - that's all.\"\n" + + " \"\"\";"); + } + + @Test + void sequencesOfThreeDoubleQuotesNeedAtLeastOneEscaped() { + TextBlockLiteralExpr textBlock = parseStatement("String code = \n" + + " \"\"\"\n" + + " String text = \\\"\"\"\n" + + " A text block inside a text block\n" + + " \\\"\"\";\n" + + " \"\"\";").findFirst(TextBlockLiteralExpr.class).get(); + + assertEquals("String text = \"\"\"\n" + + " A text block inside a text block\n" + + "\"\"\";\n", textBlock.translateEscapes()); + } + + @Test + void concatenatingTextBlocks() { + parseStatement("String code = \"public void print(Object o) {\" +\n" + + " \"\"\"\n" + + " System.out.println(Objects.toString(o));\n" + + " }\n" + + " \"\"\";"); + } + + @Test + void forceTrailingWhitespace() { + TextBlockLiteralExpr textBlock = parseStatement("String code = \"\"\"\n" + + "The quick brown fox\\040\\040\n" + + "jumps over the lazy dog\n" + + "\"\"\";").findFirst(TextBlockLiteralExpr.class).get(); + + assertEquals("The quick brown fox \n" + + "jumps over the lazy dog\n", textBlock.translateEscapes()); + } + + @Test + void escapeLineTerminator() { + TextBlockLiteralExpr textBlock = parseStatement("String text = \"\"\"\n" + + " Lorem ipsum dolor sit amet, consectetur adipiscing \\\n" + + " elit, sed do eiusmod tempor incididunt ut labore \\\n" + + " et dolore magna aliqua.\\\n" + + " \"\"\";").findFirst(TextBlockLiteralExpr.class).get(); + + assertEquals("Lorem ipsum dolor sit amet, consectetur adipiscing " + + "elit, sed do eiusmod tempor incididunt ut labore " + + "et dolore magna aliqua.", textBlock.translateEscapes()); + } + + @Test + void escapeSpace() { + TextBlockLiteralExpr textBlock = parseStatement("String colors = \"\"\"\n" + + " red \\s\n" + + " green\\s\n" + + " blue \\s\n" + + " \"\"\";").findFirst(TextBlockLiteralExpr.class).get(); + + assertEquals("red \n" + + "green \n" + + "blue \n", textBlock.translateEscapes()); + } + + @Test + void whiteSpaceLineShorterThanMiniumCommonPrefix() { + TextBlockLiteralExpr textBlock = parseStatement("String text = \"\"\" \n" + + " Hello\n" + + " World\"\"\";").findFirst(TextBlockLiteralExpr.class).get(); + assertEquals("\nHello\n" + + "World", textBlock.translateEscapes()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/ThisExprTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/ThisExprTest.java new file mode 100644 index 0000000..5d10628 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/expr/ThisExprTest.java @@ -0,0 +1,86 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.expr; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.StaticJavaParser.parseExpression; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ThisExprTest { + @Test + void justThis() { + Expression expr = parseExpression("this"); + + assertTrue(expr.isThisExpr()); + } + + @Test + void justThisName() { + JavaParser javaParser = new JavaParser(new ParserConfiguration() + .setStoreTokens(false)); + ParseResult parseResult = javaParser.parseExpression("this.c"); + FieldAccessExpr fieldAccess = parseResult.getResult().get().asFieldAccessExpr(); + assertEquals("c", fieldAccess.getName().asString()); + } + + @Test + void singleScopeThis() { + Expression expr = parseExpression("A.this"); + + Name className = expr.asThisExpr().getTypeName().get(); + + assertEquals("A", className.asString()); + } + + @Test + void singleScopeThisName() { + JavaParser javaParser = new JavaParser(new ParserConfiguration() + .setStoreTokens(false)); + ParseResult parseResult = javaParser.parseExpression("A.this.c"); + FieldAccessExpr fieldAccess = parseResult.getResult().get().asFieldAccessExpr(); + assertEquals("c", fieldAccess.getName().asString()); + } + + @Test + void multiScopeThis() { + Expression expr = parseExpression("a.B.this"); + + Name className = expr.asThisExpr().getTypeName().get(); + + assertEquals("a.B", className.asString()); + } + + @Test + void multiScopeThisName() { + JavaParser javaParser = new JavaParser(new ParserConfiguration() + .setStoreTokens(false)); + ParseResult parseResult = javaParser.parseExpression("a.B.this.c"); + FieldAccessExpr fieldAccess = parseResult.getResult().get().asFieldAccessExpr(); + assertEquals("c", fieldAccess.getName().asString()); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/imports/ImportDeclarationTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/imports/ImportDeclarationTest.java new file mode 100644 index 0000000..1ce9d0b --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/imports/ImportDeclarationTest.java @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.imports; + +import com.github.javaparser.ast.ImportDeclaration; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.StaticJavaParser.parseImport; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ImportDeclarationTest { + @Test + void singleTypeImportDeclaration() { + ImportDeclaration i = parseImport("import a.b.c.X;"); + assertEquals("a.b.c.X", i.getNameAsString()); + } + + @Test + void typeImportOnDemandDeclaration() { + ImportDeclaration i = parseImport("import a.b.c.D.*;"); + assertEquals("a.b.c.D", i.getName().toString()); + assertEquals("D", i.getName().getIdentifier()); + } + + @Test + void singleStaticImportDeclaration() { + ImportDeclaration i = parseImport("import static a.b.c.X.def;"); + assertEquals("a.b.c.X", i.getName().getQualifier().get().asString()); + assertEquals("def", i.getName().getIdentifier()); + } + + @Test + void staticImportOnDemandDeclaration() { + ImportDeclaration i = parseImport("import static a.b.c.X.*;"); + assertEquals("a.b.c.X", i.getNameAsString()); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithArgumentsTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithArgumentsTest.java new file mode 100644 index 0000000..777a13d --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithArgumentsTest.java @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.nodeTypes; + +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.expr.MethodCallExpr; +import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.ast.expr.Expression.EXCLUDE_ENCLOSED_EXPR; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class NodeWithArgumentsTest extends AbstractLexicalPreservingTest { + + @Test + void testGetArgumentPosition() { + considerCode("" + + "class Foo {\n" + + " Map map = new HashMap<>();\n" + + " public String bar(int i) {\n" + + " return map.put(((i)),((\"baz\")));\n" + + " } \n" + + "}"); + MethodCallExpr mce = cu.findFirst(MethodCallExpr.class).get(); + Expression arg0 = mce.getArgument(0); + Expression arg1 = mce.getArgument(1); + Expression innerExpr0 = arg0.asEnclosedExpr().getInner() + .asEnclosedExpr().getInner(); + Expression innerExpr1 = arg1.asEnclosedExpr().getInner() + .asEnclosedExpr().getInner(); + + assertEquals(0, mce.getArgumentPosition(arg0)); // with no conversion + assertEquals(0, mce.getArgumentPosition(innerExpr0, EXCLUDE_ENCLOSED_EXPR)); // with a conversion skipping EnclosedExprs + assertEquals(1, mce.getArgumentPosition(arg1)); // with no conversion + assertEquals(1, mce.getArgumentPosition(innerExpr1, EXCLUDE_ENCLOSED_EXPR)); // with a conversion skipping EnclosedExprs + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithBodyTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithBodyTest.java new file mode 100644 index 0000000..7d25e08 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithBodyTest.java @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.nodeTypes; + +import com.github.javaparser.ast.stmt.ForStmt; +import com.github.javaparser.utils.TestParser; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class NodeWithBodyTest { + @Test + void emptyStatementIsEmpty() { + ForStmt forStmt = TestParser.parseStatement("for(;;);").asForStmt(); + + assertTrue(forStmt.hasEmptyBody()); + } + + @Test + void emptyBlockIsEmpty() { + ForStmt forStmt = TestParser.parseStatement("for(;;){}").asForStmt(); + + assertTrue(forStmt.hasEmptyBody()); + } + + @Test + void simpleStatementIsNotEmpty() { + ForStmt forStmt = TestParser.parseStatement("for(;;)a=b;").asForStmt(); + + assertFalse(forStmt.hasEmptyBody()); + } + + @Test + void nonEmptyBlockIsNotEmpty() { + ForStmt forStmt = TestParser.parseStatement("for(;;){a=b;}").asForStmt(); + + assertFalse(forStmt.hasEmptyBody()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithJavadocTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithJavadocTest.java new file mode 100644 index 0000000..88eeff1 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithJavadocTest.java @@ -0,0 +1,70 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.nodeTypes; + +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.comments.JavadocComment; +import com.github.javaparser.ast.comments.LineComment; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class NodeWithJavadocTest { + + @Test + void removeJavaDocNegativeCaseNoComment() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(new NodeList<>(), + false, "Foo"); + assertFalse(decl.removeJavaDocComment()); + } + + @Test + void removeJavaDocNegativeCaseCommentNotJavaDoc() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(new NodeList<>(), + false, "Foo"); + decl.setComment(new LineComment("A comment")); + assertFalse(decl.removeJavaDocComment()); + assertTrue(decl.getComment().isPresent()); + } + + @Test + void removeJavaDocPositiveCase() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(new NodeList<>(), + false, "Foo"); + decl.setComment(new JavadocComment("A comment")); + assertTrue(decl.removeJavaDocComment()); + assertFalse(decl.getComment().isPresent()); + } + + @Test + void getJavadocOnMethodWithLineCommentShouldReturnEmptyOptional() { + MethodDeclaration method = new MethodDeclaration(); + method.setLineComment("Lorem Ipsum."); + + assertFalse(method.getJavadocComment().isPresent()); + assertFalse(method.getJavadoc().isPresent()); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithModifiersTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithModifiersTest.java new file mode 100644 index 0000000..43c14ce --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithModifiersTest.java @@ -0,0 +1,93 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.nodeTypes; + +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.observer.AstObserverAdapter; +import com.github.javaparser.ast.observer.ObservableProperty; +import org.junit.jupiter.api.Test; + +import java.util.LinkedList; +import java.util.List; + +import static com.github.javaparser.ast.Modifier.Keyword.*; +import static com.github.javaparser.ast.Modifier.createModifierList; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class NodeWithModifiersTest { + + @Test + void addModifierWorks() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(new NodeList<>(), + false, "Foo"); + decl.addModifier(PUBLIC); + assertEquals(createModifierList(PUBLIC), decl.getModifiers()); + } + + @Test + void addModifierTriggerNotification() { + List changes = new LinkedList<>(); + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(new NodeList<>(), + false, "Foo"); + decl.register(new AstObserverAdapter() { + @Override + public void propertyChange(Node observedNode, ObservableProperty property, Object oldValue, Object newValue) { + changes.add("property " + property.name() + " is changed to " + newValue); + } + }); + decl.addModifier(PUBLIC); + assertEquals(1, changes.size()); + assertEquals("property MODIFIERS is changed to [public ]", changes.get(0)); + } + + @Test + void removeExistingModifier() { + NodeWithModifiers node = anythingWithModifiers(PUBLIC); + node.removeModifier(PUBLIC); + assertEquals(0, node.getModifiers().size()); + } + + @Test + void ignoreNotExistingModifiersOnRemove() { + NodeWithModifiers node = anythingWithModifiers(PUBLIC); + node.removeModifier(PRIVATE); + + assertEquals(createModifierList(PUBLIC), node.getModifiers()); + } + + @Test + void keepModifiersThatShouldNotBeRemoved() { + NodeWithModifiers node = anythingWithModifiers(PUBLIC, STATIC, SYNCHRONIZED); + node.removeModifier(PUBLIC, PRIVATE, STATIC); + + assertEquals(createModifierList(SYNCHRONIZED), node.getModifiers()); + } + + private NodeWithModifiers anythingWithModifiers(Modifier.Keyword ... keywords) { + ClassOrInterfaceDeclaration foo = new ClassOrInterfaceDeclaration(new NodeList<>(), false, "Foo"); + foo.addModifier(keywords); + return foo; + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithOptionalScopeTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithOptionalScopeTest.java new file mode 100644 index 0000000..0511142 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithOptionalScopeTest.java @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.nodeTypes; + +import com.github.javaparser.ast.expr.MethodCallExpr; +import com.github.javaparser.ast.expr.NameExpr; +import com.github.javaparser.ast.expr.ObjectCreationExpr; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class NodeWithOptionalScopeTest { + + @Test + void commonExpressionWhichHaveInterfaceNodeWithOptionalScope() { + MethodCallExpr methodCallExpr = new MethodCallExpr(new NameExpr("A"), "call"); + ObjectCreationExpr objectCreationExpr = new ObjectCreationExpr(); + + assertTrue(methodCallExpr.hasScope()); + assertFalse(objectCreationExpr.hasScope()); + } + + @Test + void removeScope() { + MethodCallExpr methodCallExpr = new MethodCallExpr(new NameExpr("A"), "method"); + + methodCallExpr.removeScope(); + + assertFalse(methodCallExpr.hasScope()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithTraversableScopeTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithTraversableScopeTest.java new file mode 100644 index 0000000..6662d3b --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithTraversableScopeTest.java @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.nodeTypes; + +import com.github.javaparser.ast.expr.FieldAccessExpr; +import com.github.javaparser.ast.expr.MethodCallExpr; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.StaticJavaParser.parseExpression; +import static com.github.javaparser.utils.TestUtils.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertFalse; + +class NodeWithTraversableScopeTest { + @Test + void traverse1() { + NodeWithTraversableScope expression = parseExpression("getAddress().name.startsWith(\"abc\")"); + + assertInstanceOf(MethodCallExpr.class, expression); + expression = (NodeWithTraversableScope) expression.traverseScope().get(); + assertInstanceOf(FieldAccessExpr.class, expression); + expression = (NodeWithTraversableScope) expression.traverseScope().get(); + assertInstanceOf(MethodCallExpr.class, expression); + assertFalse(expression.traverseScope().isPresent()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithVariablesTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithVariablesTest.java new file mode 100644 index 0000000..9dd4713 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithVariablesTest.java @@ -0,0 +1,110 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.nodeTypes; + +import com.github.javaparser.StaticJavaParser; +import com.github.javaparser.ast.expr.VariableDeclarationExpr; +import com.github.javaparser.ast.type.PrimitiveType; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.StaticJavaParser.parseVariableDeclarationExpr; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class NodeWithVariablesTest { + + @Test + void getCommonTypeWorksForNormalVariables() { + VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a,b"); + assertEquals(PrimitiveType.intType(), declaration.getCommonType()); + } + + @Test + void getCommonTypeWorksForArrayTypes() { + parseVariableDeclarationExpr("int a[],b[]").getCommonType(); + } + + @Test + void getCommonTypeFailsOnArrayDifferences() { + assertThrows(AssertionError.class, () -> parseVariableDeclarationExpr("int a[],b[][]").getCommonType()); + } + + @Test + void getCommonTypeFailsOnDodgySetterUsage() { + assertThrows(AssertionError.class, () -> { + VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a,b"); + declaration.getVariable(1).setType(String.class); + declaration.getCommonType(); + }); + } + + @Test + void getCommonTypeFailsOnInvalidEmptyVariableList() { + assertThrows(AssertionError.class, () -> { + VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a"); + declaration.getVariables().clear(); + declaration.getCommonType(); + }); + } + + @Test + void getElementTypeWorksForNormalVariables() { + VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a,b"); + assertEquals(PrimitiveType.intType(), declaration.getElementType()); + } + + @Test + void getElementTypeWorksForArrayTypes() { + VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a[],b[]"); + assertEquals(PrimitiveType.intType(), declaration.getElementType()); + } + + @Test + void getElementTypeIsOkayWithArrayDifferences() { + parseVariableDeclarationExpr("int a[],b[][]").getElementType(); + } + + @Test + void getElementTypeFailsOnDodgySetterUsage() { + assertThrows(AssertionError.class, () -> { + VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a,b"); + declaration.getVariable(1).setType(String.class); + declaration.getElementType(); + }); + } + + @Test + void getElementTypeFailsOnInvalidEmptyVariableList() { + assertThrows(AssertionError.class, () -> { + VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a"); + declaration.getVariables().clear(); + declaration.getElementType(); + }); + } + + @Test + void setAllTypesWorks() { + VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int[] a[],b[][]"); + declaration.setAllTypes(StaticJavaParser.parseType("Dog")); + assertEquals("Dog a, b", declaration.toString()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/observer/PropagatingAstObserverTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/observer/PropagatingAstObserverTest.java new file mode 100644 index 0000000..a1bb86f --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/observer/PropagatingAstObserverTest.java @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.observer; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.body.FieldDeclaration; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static com.github.javaparser.StaticJavaParser.parse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class PropagatingAstObserverTest { + @Test + void verifyPropagation() { + String code = "class A { }"; + CompilationUnit cu = parse(code); + List changes = new ArrayList<>(); + AstObserver observer = new PropagatingAstObserver() { + @Override + public void concretePropertyChange(Node observedNode, ObservableProperty property, Object oldValue, Object newValue) { + changes.add(String.format("%s.%s changed from %s to %s", observedNode.getClass().getSimpleName(), property.name().toLowerCase(), oldValue, newValue)); + } + }; + cu.registerForSubtree(observer); + + assertEquals(Arrays.asList(), changes); + + FieldDeclaration fieldDeclaration = cu.getClassByName("A").get().addField("String", "foo"); + assertEquals(Arrays.asList(), changes); + assertTrue(fieldDeclaration.isRegistered(observer)); + + cu.getClassByName("A").get().getFieldByName("foo").get().getVariables().get(0).setName("Bar"); + assertEquals(Arrays.asList("VariableDeclarator.name changed from foo to Bar"), changes); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/stmt/BreakStmtTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/stmt/BreakStmtTest.java new file mode 100644 index 0000000..1cc4771 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/stmt/BreakStmtTest.java @@ -0,0 +1,127 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.stmt; + +import com.github.javaparser.ast.expr.SimpleName; +import org.junit.jupiter.api.Test; + +import java.util.Optional; + +import static com.github.javaparser.utils.TestParser.parseStatement; +import static org.junit.jupiter.api.Assertions.*; + +class BreakStmtTest { + + @Test + void simpleBreak() { + BreakStmt statement = parseStatement("break;").asBreakStmt(); + assertFalse(statement.getLabel().isPresent()); + } + + @Test + void breakWithLabel() { + BreakStmt statement = parseStatement("break hond;").asBreakStmt(); + assertEquals("hond", statement.getLabel().get().asString()); + } + + @Test + void constructor_simpleBreakWithoutLabel() { + BreakStmt statement = new BreakStmt(); + assertFalse(statement.getLabel().isPresent()); + assertEquals("break;", statement.toString()); + } + + @Test + void constructor_simpleBreakWithLabel() { + BreakStmt statement = new BreakStmt("customLabel"); + assertTrue(statement.getLabel().isPresent()); + } + + @Test + void constructor_simpleBreakWithSimpleNameLabel() { + SimpleName label = new SimpleName("customLabel"); + BreakStmt statement = new BreakStmt(label); + assertTrue(statement.getLabel().isPresent()); + assertEquals(label, statement.getLabel().get()); + } + + @Test + void removeLabel_shouldRemoveTheLabel() { + BreakStmt statement = new BreakStmt("customLabel"); + assertTrue(statement.getLabel().isPresent()); + + statement.removeLabel(); + assertFalse(statement.getLabel().isPresent()); + } + + @Test + void isBreakStmt_shouldBeTrue() { + assertTrue(new BreakStmt().isBreakStmt()); + } + + @Test + void asBreakStmt_shouldBeSame() { + BreakStmt breakStatement = new BreakStmt(); + assertSame(breakStatement, breakStatement.asBreakStmt()); + } + + @Test + void toBreakStmt_shouldBePresentAndBeTheSame() { + BreakStmt breakStatement = new BreakStmt(); + Optional optBreak = breakStatement.toBreakStmt(); + assertTrue(optBreak.isPresent()); + assertSame(breakStatement, optBreak.get()); + } + + @Test + void clone_shouldNotBeTheSameButShouldBeEquals() { + BreakStmt breakStatement = new BreakStmt(); + BreakStmt clonedStatement = breakStatement.clone(); + assertNotSame(breakStatement, clonedStatement); + assertEquals(breakStatement, clonedStatement); + } + + @Test + void remove_whenLabelIsPassedAsArgumentItShouldBeRemoved() { + BreakStmt breakStatement = new BreakStmt("Label"); + assertTrue(breakStatement.getLabel().isPresent()); + + SimpleName label = breakStatement.getLabel().get(); + assertTrue(breakStatement.remove(label)); + assertFalse(breakStatement.getLabel().isPresent()); + } + + @Test + void replace_testReplaceLabelWithNewOne() { + SimpleName originalLabel = new SimpleName("original"); + SimpleName replacementLabel = new SimpleName("replacement"); + + BreakStmt breakStatement = new BreakStmt(originalLabel); + assertTrue(breakStatement.getLabel().isPresent()); + assertSame(originalLabel, breakStatement.getLabel().get()); + + breakStatement.replace(originalLabel, replacementLabel); + assertTrue(breakStatement.getLabel().isPresent()); + assertSame(replacementLabel, breakStatement.getLabel().get()); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/stmt/ForEachStmtTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/stmt/ForEachStmtTest.java new file mode 100644 index 0000000..417aa94 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/stmt/ForEachStmtTest.java @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.stmt; + +import com.github.javaparser.ast.type.ClassOrInterfaceType; +import com.github.javaparser.ast.type.PrimitiveType; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.StaticJavaParser.parseStatement; +import static org.junit.jupiter.api.Assertions.*; + +class ForEachStmtTest { + @Test + void nonFinalPrimitive() { + ForEachStmt statement = parseStatement("for (int i : ints) {}").asForEachStmt(); + assertFalse(statement.hasFinalVariable()); + assertEquals(PrimitiveType.intType(), statement.getVariableDeclarator().getType()); + assertEquals("i", statement.getVariableDeclarator().getName().getIdentifier()); + } + + @Test + void finalNonPrimitive() { + ForEachStmt statement = parseStatement("for (final Object o : objs) {}").asForEachStmt(); + assertTrue(statement.hasFinalVariable()); + assertEquals(new ClassOrInterfaceType(null, "Object"), statement.getVariableDeclarator().getType()); + assertEquals("o", statement.getVariableDeclarator().getName().getIdentifier()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/stmt/IfElseStmtTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/stmt/IfElseStmtTest.java new file mode 100644 index 0000000..03773c4 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/stmt/IfElseStmtTest.java @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.stmt; + +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.StaticJavaParser.parseStatement; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class IfElseStmtTest { + + @Test + void issue1247withElseSingleStmt() { + IfStmt ifStmt = parseStatement("if (cond) doSomething(); else doSomethingElse();").asIfStmt(); + assertFalse(ifStmt.hasElseBlock()); + assertTrue(ifStmt.hasElseBranch()); + assertFalse(ifStmt.hasCascadingIfStmt()); + } + + @Test + void issue1247withElseBlockStmt() { + IfStmt ifStmt = parseStatement("if (cond) doSomething(); else { doSomethingElse(); }").asIfStmt(); + assertTrue(ifStmt.hasElseBlock()); + assertTrue(ifStmt.hasElseBranch()); + assertFalse(ifStmt.hasCascadingIfStmt()); + } + + @Test + void issue1247withElseSingleStmtWhichIsAnIf() { + IfStmt ifStmt = parseStatement("if (cond1) doSomething(); else if (cond2) doSomethingElse();").asIfStmt(); + assertFalse(ifStmt.hasElseBlock()); + assertTrue(ifStmt.hasElseBranch()); + assertTrue(ifStmt.hasCascadingIfStmt()); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/stmt/SwitchStmtTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/stmt/SwitchStmtTest.java new file mode 100644 index 0000000..dbb9095 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/stmt/SwitchStmtTest.java @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.stmt; + +import com.github.javaparser.ast.NodeList; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.StaticJavaParser.parseStatement; +import static com.github.javaparser.ast.stmt.SwitchEntry.Type.EXPRESSION; +import static com.github.javaparser.ast.stmt.SwitchEntry.Type.STATEMENT_GROUP; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class SwitchStmtTest { + @Test + void classicSwitch() { + SwitchStmt switchStmt = parseStatement("switch (day) {\n" + + " case TUESDAY: System.out.println(7); break;\n" + + " case FRIDAY: System.out.println(8); break;\n" + + " default: System.out.println(-1); \n" + + "}").asSwitchStmt(); + + assertEquals(STATEMENT_GROUP, switchStmt.getEntry(0).getType()); + assertEquals(STATEMENT_GROUP, switchStmt.getEntry(1).getType()); + assertEquals(STATEMENT_GROUP, switchStmt.getEntry(2).getType()); + assertEquals(new NodeList<>(), switchStmt.getEntry(2).getLabels()); + } + @Test + void jep325Example1() { + SwitchStmt switchStmt = parseStatement("switch (day) {\n" + +// " case MONDAY, FRIDAY, SUNDAY -> System.out.println(6);\n" + + " case TUESDAY -> System.out.println(7);\n" + +// " case THURSDAY, SATURDAY -> System.out.println(8);\n" + + " case WEDNESDAY -> System.out.println(9);\n" + + "}").asSwitchStmt(); + + assertEquals(EXPRESSION, switchStmt.getEntry(0).getType()); + } + + + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/stmt/TryStmtTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/stmt/TryStmtTest.java new file mode 100644 index 0000000..5568a0b --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/stmt/TryStmtTest.java @@ -0,0 +1,120 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.stmt; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParseStart; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.expr.FieldAccessExpr; +import com.github.javaparser.ast.expr.NameExpr; +import com.github.javaparser.ast.expr.VariableDeclarationExpr; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.ParserConfiguration.LanguageLevel.*; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.TestUtils.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class TryStmtTest { + @Test + void simpleTest() { + TryStmt tryStmt = parse9("try(Reader x = new FileReader()){}"); + assertInstanceOf(VariableDeclarationExpr.class, tryStmt.getResources().get(0)); + } + + @Test + void multipleTest() { + TryStmt tryStmt = parse9("try(Reader x = new FileReader(); Reader x = new FileReader()){}"); + assertInstanceOf(VariableDeclarationExpr.class, tryStmt.getResources().get(0)); + } + + @Test + void modifiersTest() { + TryStmt tryStmt = parse9("try(final @A Reader x = new FileReader()){}"); + assertInstanceOf(VariableDeclarationExpr.class, tryStmt.getResources().get(0)); + } + + @Test + void simpleVariable() { + TryStmt tryStmt = parse9("try(a){}"); + assertInstanceOf(NameExpr.class, tryStmt.getResources().get(0)); + } + + @Test + void twoSimpleVariables() { + TryStmt tryStmt = parse9("try(a;b){}"); + assertInstanceOf(NameExpr.class, tryStmt.getResources().get(0)); + assertInstanceOf(NameExpr.class, tryStmt.getResources().get(1)); + } + + @Test + void complexVariable() { + TryStmt tryStmt = parse9("try(a.b.c){}"); + assertInstanceOf(FieldAccessExpr.class, tryStmt.getResources().get(0)); + } + + @Test + void superAccess() { + TryStmt tryStmt = parse9("try(super.a){}"); + assertInstanceOf(FieldAccessExpr.class, tryStmt.getResources().get(0)); + } + + @Test + void outerClassAccess() { + TryStmt tryStmt = parse9("try(X.this.a){}"); + assertInstanceOf(FieldAccessExpr.class, tryStmt.getResources().get(0)); + } + + @Test + void varTestJava10() { + TryStmt tryStmt = parse10("try(var x = new FileReader()){}"); + assertInstanceOf(VariableDeclarationExpr.class, tryStmt.getResources().get(0)); + } + + @Test + void varTestJava11() { + TryStmt tryStmt = parse11("try(var x = new FileReader()){}"); + assertInstanceOf(VariableDeclarationExpr.class, tryStmt.getResources().get(0)); + } + + private T parse9(String code) { + JavaParser parser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_9)); + ParseResult result = parser.parse(ParseStart.STATEMENT, provider(code)); + assertTrue(result.isSuccessful(), result.toString()); + return (T) result.getResult().get(); + } + + private T parse10(String code) { + JavaParser parser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_10)); + ParseResult result = parser.parse(ParseStart.STATEMENT, provider(code)); + assertTrue(result.isSuccessful(), result.toString()); + return (T) result.getResult().get(); + } + + private T parse11(String code) { + JavaParser parser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_11)); + ParseResult result = parser.parse(ParseStart.STATEMENT, provider(code)); + assertTrue(result.isSuccessful(), result.toString()); + return (T) result.getResult().get(); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/stmt/YieldStmtTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/stmt/YieldStmtTest.java new file mode 100644 index 0000000..333074b --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/stmt/YieldStmtTest.java @@ -0,0 +1,118 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.stmt; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.expr.*; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_12; +import static com.github.javaparser.utils.TestParser.parseCompilationUnit; +import static com.github.javaparser.utils.TestParser.parseStatement; +import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class YieldStmtTest { + @Test + void yield() { + YieldStmt statement = parseStatement("yield 12*12;").asYieldStmt(); + assertEquals(BinaryExpr.class, statement.getExpression().getClass()); + } + + @Test + void yield2() { + YieldStmt statement; + statement = parseStatement("yield (2 + 2);").asYieldStmt(); + assertEquals(EnclosedExpr.class, statement.getExpression().getClass()); + statement = parseStatement("yield ((2 + 2) * 3);").asYieldStmt(); + assertEquals(EnclosedExpr.class, statement.getExpression().getClass()); + } + + @Test + void yieldMethodCall() { + YieldStmt statement; + statement = parseStatement("yield a();").asYieldStmt(); + assertEquals(MethodCallExpr.class, statement.getExpression().getClass()); + statement = parseStatement("yield a(5, arg);").asYieldStmt(); + assertEquals(MethodCallExpr.class, statement.getExpression().getClass()); + statement = parseStatement("yield a.b();").asYieldStmt(); + assertEquals(MethodCallExpr.class, statement.getExpression().getClass()); + statement = parseStatement("yield a.b(5, arg);").asYieldStmt(); + assertEquals(MethodCallExpr.class, statement.getExpression().getClass()); + statement = parseStatement("yield this.b();").asYieldStmt(); + assertEquals(MethodCallExpr.class, statement.getExpression().getClass()); + statement = parseStatement("yield this.b(5, arg);").asYieldStmt(); + assertEquals(MethodCallExpr.class, statement.getExpression().getClass()); + statement = parseStatement("yield Clazz.this.b();").asYieldStmt(); + assertEquals(MethodCallExpr.class, statement.getExpression().getClass()); + statement = parseStatement("yield Clazz.this.b(5, arg);").asYieldStmt(); + assertEquals(MethodCallExpr.class, statement.getExpression().getClass()); + } + + @Test + void yieldAssignment() { + YieldStmt statement = parseStatement("yield (x = 5);").asYieldStmt(); + assertEquals(EnclosedExpr.class, statement.getExpression().getClass()); + } + + @Test + void yieldConditional() { + YieldStmt statement = parseStatement("yield x ? 5 : 6;").asYieldStmt(); + assertEquals(ConditionalExpr.class, statement.getExpression().getClass()); + } + + @Test + void threadYieldShouldNotBreak() { + parseStatement("Thread.yield();").asExpressionStmt().getExpression().asMethodCallExpr(); + } + + @Test + void keywordShouldNotInterfereWithIdentifiers() { + CompilationUnit compilationUnit = parseCompilationUnit(JAVA_12, "class yield { yield yield(yield yield){yield();} }"); + assertEqualsStringIgnoringEol("class yield {\n" + + "\n" + + " yield yield(yield yield) {\n" + + " yield();\n" + + " }\n" + + "}\n", compilationUnit.toString()); + } + + @Test + void keywordShouldNotInterfereWithIdentifiers2() { + CompilationUnit compilationUnit = parseCompilationUnit("enum X { yield, }"); + assertEqualsStringIgnoringEol("enum X {\n" + + "\n" + + " yield\n" + + "}\n", compilationUnit.toString()); + } + + @Test + void keywordShouldNotInterfereWithIdentifiers3() { + YieldStmt statement; + statement = parseStatement("yield yield;").asYieldStmt(); + assertEquals(NameExpr.class, statement.getExpression().getClass()); + statement = parseStatement("yield Clazz.yield();").asYieldStmt(); + assertEquals(MethodCallExpr.class, statement.getExpression().getClass()); + statement = parseStatement("yield yield.yield();").asYieldStmt(); + assertEquals(MethodCallExpr.class, statement.getExpression().getClass()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/type/ArrayTypeTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/type/ArrayTypeTest.java new file mode 100644 index 0000000..8a4a386 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/type/ArrayTypeTest.java @@ -0,0 +1,200 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.type; + +import com.github.javaparser.StaticJavaParser; +import com.github.javaparser.ast.body.FieldDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.body.Parameter; +import com.github.javaparser.ast.expr.ArrayCreationExpr; +import com.github.javaparser.ast.expr.MarkerAnnotationExpr; +import com.github.javaparser.ast.expr.VariableDeclarationExpr; +import com.github.javaparser.ast.stmt.ExpressionStmt; +import com.github.javaparser.printer.ConcreteSyntaxModel; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.StaticJavaParser.*; +import static com.github.javaparser.utils.Utils.SYSTEM_EOL; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ArrayTypeTest { + @Test + void getFieldDeclarationWithArrays() { + FieldDeclaration fieldDeclaration = parseBodyDeclaration("@C int @A[] @B[] a @X[] @Y[];").asFieldDeclaration(); + + ArrayType arrayType1 = fieldDeclaration.getVariable(0).getType().asArrayType(); + ArrayType arrayType2 = arrayType1.getComponentType().asArrayType(); + ArrayType arrayType3 = arrayType2.getComponentType().asArrayType(); + ArrayType arrayType4 = arrayType3.getComponentType().asArrayType(); + PrimitiveType elementType = arrayType4.getComponentType().asPrimitiveType(); + + assertThat(arrayType1.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("X"))); + assertThat(arrayType2.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("Y"))); + assertThat(arrayType3.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("A"))); + assertThat(arrayType4.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("B"))); + + assertThat(elementType.getType()).isEqualTo(PrimitiveType.Primitive.INT); + assertThat(fieldDeclaration.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("C"))); + + assertThat(arrayType1.getParentNode().get().getParentNode().get()).isSameAs(fieldDeclaration); + } + + @Test + void getVariableDeclarationWithArrays() { + ExpressionStmt variableDeclarationStatement = parseStatement("@C int @A[] @B[] a @X[] @Y[];").asExpressionStmt(); + VariableDeclarationExpr variableDeclarationExpr = variableDeclarationStatement.getExpression().asVariableDeclarationExpr(); + + ArrayType arrayType1 = variableDeclarationExpr.getVariable(0).getType().asArrayType(); + ArrayType arrayType2 = arrayType1.getComponentType().asArrayType(); + ArrayType arrayType3 = arrayType2.getComponentType().asArrayType(); + ArrayType arrayType4 = arrayType3.getComponentType().asArrayType(); + PrimitiveType elementType = arrayType4.getComponentType().asPrimitiveType(); + + assertThat(arrayType1.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("X"))); + assertThat(arrayType2.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("Y"))); + assertThat(arrayType3.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("A"))); + assertThat(arrayType4.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("B"))); + + assertThat(elementType.getType()).isEqualTo(PrimitiveType.Primitive.INT); + assertThat(variableDeclarationExpr.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("C"))); + + assertThat(arrayType1.getParentNode().get().getParentNode().get()).isSameAs(variableDeclarationExpr); + } + + @Test + void getMethodDeclarationWithArrays() { + MethodDeclaration methodDeclaration = parseBodyDeclaration("@C int @A[] a() @B[] {}").asMethodDeclaration(); + + ArrayType arrayType1 = methodDeclaration.getType().asArrayType(); + ArrayType arrayType2 = arrayType1.getComponentType().asArrayType(); + Type elementType = arrayType2.getComponentType(); + assertThat(elementType).isInstanceOf(PrimitiveType.class); + + assertThat(arrayType1.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("B"))); + assertThat(arrayType2.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("A"))); + assertThat(methodDeclaration.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("C"))); + + assertThat(methodDeclaration.getType().getParentNode().get()).isSameAs(methodDeclaration); + } + + @Test + void getParameterWithArrays() { + MethodDeclaration methodDeclaration = parseBodyDeclaration("void a(@C int @A[] a @B[]) {}").asMethodDeclaration(); + + Parameter parameter = methodDeclaration.getParameter(0); + + ArrayType outerArrayType = parameter.getType().asArrayType(); + + ArrayType innerArrayType = outerArrayType.getComponentType().asArrayType(); + PrimitiveType elementType = innerArrayType.getComponentType().asPrimitiveType(); + + assertThat(elementType).isInstanceOf(PrimitiveType.class); + assertThat(outerArrayType.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("B"))); + assertThat(innerArrayType.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("A"))); + assertThat(parameter.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("C"))); + + assertThat(parameter.getType().getParentNode().get()).isSameAs(parameter); + } + + @Test + void setVariableDeclarationWithArrays() { + ExpressionStmt variableDeclarationStatement = parseStatement("@C int @A[] @B[] a @X[] @Y[];").asExpressionStmt(); + VariableDeclarationExpr variableDeclarationExpr = variableDeclarationStatement.getExpression().asVariableDeclarationExpr(); + + variableDeclarationExpr.getVariable(0).setType(new ArrayType(new ArrayType(PrimitiveType.intType()))); + assertEquals("@C" + SYSTEM_EOL + "int[][] a;", variableDeclarationStatement.toString()); + } + + @Test + void setFieldDeclarationWithArrays() { + FieldDeclaration fieldDeclaration = parseBodyDeclaration("int[][] a[][];").asFieldDeclaration(); + fieldDeclaration.getVariable(0).setType(new ArrayType(new ArrayType(parseClassOrInterfaceType("Blob")))); + + assertEquals("Blob[][] a;", fieldDeclaration.toString()); + } + + @Test + void setMethodDeclarationWithArrays() { + MethodDeclaration method = parseBodyDeclaration("int[][] a()[][] {}").asMethodDeclaration(); + method.setType(new ArrayType(new ArrayType(parseClassOrInterfaceType("Blob")))); + + assertEquals("Blob[][] a() {" + SYSTEM_EOL + "}", method.toString()); + } + + @Test + void fieldDeclarationWithArraysHasCorrectOrigins() { + FieldDeclaration fieldDeclaration = parseBodyDeclaration("int[] a[];").asFieldDeclaration(); + + Type outerType = fieldDeclaration.getVariables().get(0).getType(); + assertEquals(ArrayType.Origin.NAME, outerType.asArrayType().getOrigin()); + assertEquals(ArrayType.Origin.TYPE, outerType.asArrayType().getComponentType().asArrayType().getOrigin()); + } + + @Test + void methodDeclarationWithArraysHasCorrectOrigins() { + MethodDeclaration method = (MethodDeclaration) parseBodyDeclaration("int[] a()[] {}"); + + Type outerType = method.getType(); + assertEquals(ArrayType.Origin.NAME, outerType.asArrayType().getOrigin()); + assertEquals(ArrayType.Origin.TYPE, outerType.asArrayType().getComponentType().asArrayType().getOrigin()); + } + + @Test + void setParameterWithArrays() { + MethodDeclaration method = parseBodyDeclaration("void a(int[][] a[][]) {}").asMethodDeclaration(); + method.getParameter(0).setType(new ArrayType(new ArrayType(parseClassOrInterfaceType("Blob")))); + + assertEquals("void a(Blob[][] a) {" + SYSTEM_EOL + "}", method.toString()); + } + + @Test + void getArrayCreationType() { + ArrayCreationExpr expr = parseExpression("new int[]"); + ArrayType outerType = expr.createdType().asArrayType(); + Type innerType = outerType.getComponentType(); + assertThat(innerType).isEqualTo(expr.getElementType()); + } + + @Test + void ellipsisCanHaveAnnotationsToo() { + Parameter p = parseParameter("int[]@X...a[]"); + + assertThat(p.getVarArgsAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("X"))); + assertEquals("int[][]@X ... a", p.toString()); + assertEquals("int[][]@X... a", ConcreteSyntaxModel.genericPrettyPrint(p)); + } + + @Test + void arrayLevel() { + FieldDeclaration fd1 = parseBodyDeclaration("int[] a;").asFieldDeclaration(); + assertEquals(1, fd1.getVariable(0).getType().getArrayLevel()); + FieldDeclaration fd2 = parseBodyDeclaration("int[][] a;").asFieldDeclaration(); + assertEquals(2, fd2.getVariable(0).getType().getArrayLevel()); + } + + @Test + void range() { + Type type = parseType("Long[][]"); + assertEquals(8, type.getRange().get().end.column); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/type/ClassOrInterfaceTypeTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/type/ClassOrInterfaceTypeTest.java new file mode 100644 index 0000000..709b6e3 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/type/ClassOrInterfaceTypeTest.java @@ -0,0 +1,139 @@ +/* + * Copyright (C) 2013-2024 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.type; + +import com.github.javaparser.StaticJavaParser; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.expr.AnnotationExpr; +import com.github.javaparser.ast.expr.SimpleName; +import com.github.javaparser.ast.visitor.VoidVisitorAdapter; +import com.github.javaparser.metamodel.JavaParserMetaModel; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; + +class ClassOrInterfaceTypeTest { + + @Test + void testSetName() { + ClassOrInterfaceType classOrInterfaceType = new ClassOrInterfaceType(); + + assertNotEquals("A", classOrInterfaceType.getName().toString()); + classOrInterfaceType.setName("A"); + assertEquals("A", classOrInterfaceType.getName().toString()); + } + + @Test + void testNestedClass() { + ClassOrInterfaceType classA = new ClassOrInterfaceType(); + classA.setName("A"); + ClassOrInterfaceType classB = new ClassOrInterfaceType(classA, "B"); + + assertEquals("A.B", classB.getNameWithScope()); + } + + @Test + void testWithGeneric() { + ClassOrInterfaceType classA = new ClassOrInterfaceType(null, "A"); + ClassOrInterfaceType classB = new ClassOrInterfaceType(classA, new SimpleName("B"), new NodeList<>(classA)); + + assertTrue(classB.getTypeArguments().isPresent()); + assertEquals(1, classB.getTypeArguments().get().size()); + assertEquals(classA, classB.getTypeArguments().get().get(0)); + + assertEquals("A.B", classB.getNameWithScope()); + assertEquals("A.B", classB.asString()); + } + + @Test + void testWithAnnotations() { + AnnotationExpr annotationExpr = StaticJavaParser.parseAnnotation("@Override"); + ClassOrInterfaceType classA = new ClassOrInterfaceType( + null, new SimpleName("A"), null, new NodeList<>(annotationExpr)); + + assertEquals(1, classA.getAnnotations().size()); + assertEquals(annotationExpr, classA.getAnnotation(0)); + } + + @Test + void testResolveWithoutCompilationUnit() { + ClassOrInterfaceType classA = new ClassOrInterfaceType(null, "A"); + Assertions.assertThrows(IllegalStateException.class, classA::resolve); + } + + @Test + void testToDescriptorWithoutCompilationUnit() { + ClassOrInterfaceType classA = new ClassOrInterfaceType(null, "A"); + Assertions.assertThrows(IllegalStateException.class, classA::toDescriptor); + } + + @Test + void testToClassOrInterfaceType() { + ClassOrInterfaceType classA = new ClassOrInterfaceType(null, "A"); + + Optional newClass = classA.toClassOrInterfaceType(); + assertTrue(newClass.isPresent()); + assertSame(classA, newClass.get()); + } + + @Test + void testIfClassOrInterfaceTypeIsCalled() { + ClassOrInterfaceType classA = new ClassOrInterfaceType(null, "A"); + classA.ifClassOrInterfaceType(classOrInterfaceType -> assertSame(classA, classOrInterfaceType)); + } + + @Test + void testAsClassOrInterfaceTypeIsTheSame() { + ClassOrInterfaceType classA = new ClassOrInterfaceType(null, "A"); + + assertTrue(classA.isClassOrInterfaceType()); + assertEquals(classA, classA.asClassOrInterfaceType()); + } + + @Test + void testCloneClass() { + ClassOrInterfaceType classA = new ClassOrInterfaceType(null, "A"); + assertEquals(classA, classA.clone()); + } + + @Test + void testMetaModel() { + ClassOrInterfaceType classA = new ClassOrInterfaceType(null, "A"); + assertEquals(JavaParserMetaModel.classOrInterfaceTypeMetaModel, classA.getMetaModel()); + } + + @Test + void testAcceptVoidVisitor() { + ClassOrInterfaceType classA = new ClassOrInterfaceType(null, "A"); + classA.accept(new VoidVisitorAdapter() { + @Override + public void visit(ClassOrInterfaceType classOrInterfaceType, Object object) { + super.visit(classOrInterfaceType, object); + + assertEquals(classA, classOrInterfaceType); + } + }, null); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/type/TypeTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/type/TypeTest.java new file mode 100644 index 0000000..f52baa0 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/type/TypeTest.java @@ -0,0 +1,89 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.type; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseProblemException; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.expr.VariableDeclarationExpr; +import com.github.javaparser.ast.validator.language_level_validations.Java5Validator; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.ParseStart.VARIABLE_DECLARATION_EXPR; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.RAW; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.StaticJavaParser.parseType; +import static com.github.javaparser.StaticJavaParser.parseVariableDeclarationExpr; +import static org.junit.jupiter.api.Assertions.*; + +class TypeTest { + @Test + void asString() { + assertEquals("int", typeAsString("int x")); + assertEquals("List", typeAsString("List x")); + assertEquals("String", typeAsString("@A String x")); + assertEquals("List", typeAsString("List x")); + } + + @Test + void primitiveTypeArgumentDefaultValidator() { + assertThrows(ParseProblemException.class, () -> typeAsString("List x;")); + } + + @Test + void primitiveTypeArgumentLenientValidator() { + ParserConfiguration config = new ParserConfiguration() + .setLanguageLevel(RAW); + config.getProcessors().add(() -> new Java5Validator() {{ + remove(noPrimitiveGenericArguments); + }}.processor()); + + ParseResult result = new JavaParser(config).parse( + VARIABLE_DECLARATION_EXPR, provider("List x")); + assertTrue(result.isSuccessful()); + + VariableDeclarationExpr decl = result.getResult().get(); + assertEquals("List", decl.getVariable(0).getType().asString()); + } + + private String typeAsString(String s) { + return parseVariableDeclarationExpr(s).getVariable(0).getType().asString(); + } + + @Test + void arrayType() { + Type type = parseType("int[]"); + assertTrue(type.isArrayType()); + ArrayType arrayType = type.asArrayType(); + final ArrayType[] s = new ArrayType[1]; + type.ifArrayType(t -> s[0] = t); + assertNotNull(s[0]); + } + + @Test + void issue1251() { + final Type type = parseType("TypeUtilsTest.Tester"); + assertEquals("TypeUtilsTest.Tester", type.toString()); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java10ValidatorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java10ValidatorTest.java new file mode 100644 index 0000000..171d4f4 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java10ValidatorTest.java @@ -0,0 +1,135 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.body.BodyDeclaration; +import com.github.javaparser.ast.stmt.Statement; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.ParseStart.CLASS_BODY; +import static com.github.javaparser.ParseStart.STATEMENT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_10; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.TestUtils.assertNoProblems; +import static com.github.javaparser.utils.TestUtils.assertProblems; + +class Java10ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_10)); + + @Test + void varAllowedInLocalVariableDeclaration() { + ParseResult result = javaParser.parse(STATEMENT, provider("var a = 5;")); + assertNoProblems(result); + } + + @Test + void varAllowedInForEach() { + ParseResult result = javaParser.parse(STATEMENT, provider("for(var a : as){}")); + assertNoProblems(result); + } + + @Test + void varAllowedInOldFor() { + ParseResult result = javaParser.parse(STATEMENT, provider("for(var a = 5;a<9;a++){}")); + assertNoProblems(result); + } + + @Test + void varAllowedInTryWithResources() { + ParseResult result = javaParser.parse(STATEMENT, provider("try(var f = new FileReader(\"\")){ }catch (Exception e){ }")); + assertNoProblems(result); + } + + @Test + void varNotAllowedInCast() { + ParseResult result = javaParser.parse(STATEMENT, provider("int a = (var)20;")); + assertNoProblems(result); + } + + @Test + void varNotAllowedInField() { + ParseResult> result = javaParser.parse(CLASS_BODY, provider("var a = 20;")); + assertProblems(result, "(line 1,col 1) \"var\" is not allowed here."); + } + + @Test + void varNotAllowedInTypeArguments() { + ParseResult result = javaParser.parse(STATEMENT, provider("new X();")); + assertProblems(result, "(line 1,col 7) \"var\" is not allowed here."); + } + + @Test + void varNotAllowedInLambdaParameters() { + ParseResult result = javaParser.parse(STATEMENT, provider("x((var x) -> null);")); + assertProblems(result, "(line 1,col 4) \"var\" is not allowed here."); + } + + @Test + void emptyInitializerNotAllowed() { + ParseResult result = javaParser.parse(STATEMENT, provider("var a;")); + assertProblems(result, "(line 1,col 1) \"var\" needs an initializer."); + } + + @Test + void multipleVariablesNotAllowed() { + ParseResult result = javaParser.parse(STATEMENT, provider("var a=1, b=2;")); + assertProblems(result, "(line 1,col 1) \"var\" only takes a single variable."); + } + + @Test + void nullVariablesNotAllowed() { + ParseResult result = javaParser.parse(STATEMENT, provider("var a=null;")); + assertProblems(result, "(line 1,col 1) \"var\" cannot infer type from just null."); + } + + @Test + void extraBracketPairsNotAllowed() { + ParseResult result = javaParser.parse(STATEMENT, provider("var d[] = new int[4];")); + assertProblems(result, "(line 1,col 5) \"var\" cannot have extra array brackets."); + } + + @Test + void arrayDimensionBracketsNotAllowed() { + ParseResult result = javaParser.parse(STATEMENT, provider("var a={ 6 };")); + assertProblems(result, "(line 1,col 1) \"var\" cannot infer array types."); + } + + // This is pretty hard to impossible to implement correctly with just the AST. + @Disabled + @Test + void selfReferenceNotAllowed() { + ParseResult result = javaParser.parse(STATEMENT, provider("var a=a;")); + assertProblems(result, ""); + } + + // Can be implemented once https://github.com/javaparser/javaparser/issues/1434 is implemented. + @Disabled + @Test + void polyExpressionAsInitializerNotAllowed() { + ParseResult result = javaParser.parse(STATEMENT, provider("var a=new ArrayList<>();")); + assertProblems(result, ""); + } +} 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 new file mode 100644 index 0000000..ce96ae2 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java11ValidatorTest.java @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.stmt.Statement; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.ParseStart.STATEMENT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_11; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.TestUtils.assertNoProblems; +import static com.github.javaparser.utils.TestUtils.assertProblems; + +class Java11ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_11)); + + @Test + void varAllowedInLocalVariableDeclaration() { + ParseResult result = javaParser.parse(STATEMENT, provider("x((var x, var y) -> x+y);")); + assertNoProblems(result); + } + + @Test + void switchExpressionNotAllowed() { + ParseResult result = javaParser.parse(STATEMENT, provider("int a = switch(x){};")); + 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. 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/Java12ValidatorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java12ValidatorTest.java new file mode 100644 index 0000000..01ede06 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java12ValidatorTest.java @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.stmt.Statement; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.ParseStart.STATEMENT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_12_PREVIEW; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.TestUtils.assertNoProblems; + +class Java12ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_12_PREVIEW)); + + @Test + void expressionsInLabelsNotAllowed() { + ParseResult result = javaParser.parse(STATEMENT, provider("switch(x){case 3+4+5: ;}")); + assertNoProblems(result); + } + + @Test + void switchExpressionNotAllowed() { + ParseResult result = javaParser.parse(STATEMENT, provider("int a = switch(x){};")); + assertNoProblems(result); + } + + @Test + void multiLabelCaseAllowed() { + ParseResult result = javaParser.parse(STATEMENT, provider("switch(x){case 3,4,5: ;}")); + assertNoProblems(result); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java13ValidatorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java13ValidatorTest.java new file mode 100644 index 0000000..1982571 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java13ValidatorTest.java @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.stmt.Statement; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.ParseStart.STATEMENT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_13_PREVIEW; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.TestUtils.assertNoProblems; + +class Java13ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_13_PREVIEW)); + + @Test + void yieldAllowed() { + ParseResult result = javaParser.parse(STATEMENT, provider("switch(x){case 3: yield 6;}")); + assertNoProblems(result); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java14PreviewValidatorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java14PreviewValidatorTest.java new file mode 100644 index 0000000..7611017 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java14PreviewValidatorTest.java @@ -0,0 +1,99 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.utils.TestUtils; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.ParseStart.COMPILATION_UNIT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_14_PREVIEW; +import static com.github.javaparser.Providers.provider; + +class Java14PreviewValidatorTest { + + private final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_14_PREVIEW)); + + /** + * Records are available within Java 14 (preview), Java 15 (2nd preview), and Java 16 (release). + * The introduction of records means that they are no longer able to be used as identifiers. + */ + @Nested + class Record { + + @Nested + class RecordAsTypeIdentifierForbidden { + @Test + void recordUsedAsClassIdentifier() { + String s = "public class record {}"; + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider(s)); + TestUtils.assertProblems(result, "(line 1,col 14) 'record' is a restricted identifier and cannot be used for type declarations"); + } + + @Test + void recordUsedAsEnumIdentifier() { + String s = "public enum record {}"; + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider(s)); + TestUtils.assertProblems(result, "(line 1,col 13) 'record' is a restricted identifier and cannot be used for type declarations"); + } + + @Test + void recordUsedAsRecordIdentifier() { + String s = "public record record() {}"; + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider(s)); + TestUtils.assertProblems(result, "(line 1,col 15) 'record' is a restricted identifier and cannot be used for type declarations"); + } + } + + @Nested + class RecordUsedAsIdentifierAllowedAsFieldDeclarations { + @Test + void recordUsedAsFieldIdentifierInClass() { + String s = "class X { int record; }"; + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider(s)); + TestUtils.assertNoProblems(result); + } + + @Test + void recordUsedAsFieldIdentifierInInterface() { + String s = "interface X { int record; }"; + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider(s)); + TestUtils.assertNoProblems(result); + } + } + + @Nested + class RecordDeclarationPermitted { + @Test + void recordDeclaration() { + String s = "record X() { }"; + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider(s)); + TestUtils.assertNoProblems(result); + } + } + } + +} 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 new file mode 100644 index 0000000..7414129 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java14ValidatorTest.java @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.utils.TestUtils; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.ParseStart.COMPILATION_UNIT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_14; +import static com.github.javaparser.Providers.provider; + +class Java14ValidatorTest { + + private final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_14)); + + + // TODO: Confirm FORBIDDEN - pattern matching instanceof + + // TODO: Confirm PERMITTED - text blocks permitted + + /** + * Records are available within Java 14 (preview), Java 15 (2nd preview), and Java 16 (release). + * The introduction of records means that they are no longer able to be used as identifiers. + */ + @Nested + class Record { + + @Nested + class RecordAsIdentifierPermitted { + @Test + void recordUsedAsClassName() { + String s = "public class record {}"; + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider(s)); + TestUtils.assertNoProblems(result); + } + + @Test + void recordUsedAsFieldName() { + String s = "class X { int record; }"; + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider(s)); + TestUtils.assertNoProblems(result); + } + } + + @Nested + class RecordDeclarationForbidden { + @Test + 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. 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/Java15PreviewValidatorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java15PreviewValidatorTest.java new file mode 100644 index 0000000..4972299 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java15PreviewValidatorTest.java @@ -0,0 +1,99 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.utils.TestUtils; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.ParseStart.COMPILATION_UNIT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_15_PREVIEW; +import static com.github.javaparser.Providers.provider; + +class Java15PreviewValidatorTest { + + private final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_15_PREVIEW)); + + /** + * Records are available within Java 14 (preview), Java 15 (2nd preview), and Java 16 (release). + * The introduction of records means that they are no longer able to be used as identifiers. + */ + @Nested + class Record { + + @Nested + class RecordAsTypeIdentifierForbidden { + @Test + void recordUsedAsClassIdentifier() { + String s = "public class record {}"; + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider(s)); + TestUtils.assertProblems(result, "(line 1,col 14) 'record' is a restricted identifier and cannot be used for type declarations"); + } + + @Test + void recordUsedAsEnumIdentifier() { + String s = "public enum record {}"; + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider(s)); + TestUtils.assertProblems(result, "(line 1,col 13) 'record' is a restricted identifier and cannot be used for type declarations"); + } + + @Test + void recordUsedAsRecordIdentifier() { + String s = "public record record() {}"; + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider(s)); + TestUtils.assertProblems(result, "(line 1,col 15) 'record' is a restricted identifier and cannot be used for type declarations"); + } + } + + @Nested + class RecordUsedAsIdentifierAllowedAsFieldDeclarations { + @Test + void recordUsedAsFieldIdentifierInClass() { + String s = "class X { int record; }"; + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider(s)); + TestUtils.assertNoProblems(result); + } + + @Test + void recordUsedAsFieldIdentifierInInterface() { + String s = "interface X { int record; }"; + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider(s)); + TestUtils.assertNoProblems(result); + } + } + + @Nested + class RecordDeclarationPermitted { + @Test + void recordDeclaration() { + String s = "record X() { }"; + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider(s)); + TestUtils.assertNoProblems(result); + } + } + } + +} 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 new file mode 100644 index 0000000..d36cdc8 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java15ValidatorTest.java @@ -0,0 +1,77 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.utils.TestUtils; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.ParseStart.COMPILATION_UNIT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_15; +import static com.github.javaparser.Providers.provider; + +class Java15ValidatorTest { + + private final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_15)); + + // TODO: Confirm PERMITTED - text blocks + + /** + * Records are available within Java 14 (preview), Java 15 (2nd preview), and Java 16 (release). + * The introduction of records means that they are no longer able to be used as identifiers. + */ + @Nested + class Record { + + @Nested + class RecordAsIdentifierPermitted { + @Test + void recordUsedAsClassName() { + String s = "public class record {}"; + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider(s)); + TestUtils.assertNoProblems(result); + } + + @Test + void recordUsedAsFieldName() { + String s = "class X { int record; }"; + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider(s)); + TestUtils.assertNoProblems(result); + } + } + + @Nested + class RecordDeclarationForbidden { + @Test + 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. 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/Java16PreviewValidatorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java16PreviewValidatorTest.java new file mode 100644 index 0000000..f52e647 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java16PreviewValidatorTest.java @@ -0,0 +1,33 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParserConfiguration; + +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_16_PREVIEW; + +class Java16PreviewValidatorTest { + + private final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_16_PREVIEW)); + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java16ValidatorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java16ValidatorTest.java new file mode 100644 index 0000000..43749a4 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java16ValidatorTest.java @@ -0,0 +1,110 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.utils.TestUtils; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.ParseStart.COMPILATION_UNIT; +import static com.github.javaparser.ParseStart.STATEMENT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_16; +import static com.github.javaparser.Providers.provider; + +class Java16ValidatorTest { + + private final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_16)); + + @Nested + class Yield { + @Test + void yieldAllowed() { + ParseResult result = javaParser.parse(STATEMENT, provider("switch(x){case 3: yield 6;}")); + TestUtils.assertNoProblems(result); + } + + } + + /** + * Records are available within Java 14 (preview), Java 15 (2nd preview), and Java 16 (release). + * The introduction of records means that they are no longer able to be used as identifiers. + */ + @Nested + class Record { + + @Nested + class RecordAsTypeIdentifierForbidden { + @Test + void recordUsedAsClassIdentifier() { + String s = "public class record {}"; + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider(s)); + TestUtils.assertProblems(result, "(line 1,col 14) 'record' is a restricted identifier and cannot be used for type declarations"); + } + + @Test + void recordUsedAsEnumIdentifier() { + String s = "public enum record {}"; + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider(s)); + TestUtils.assertProblems(result, "(line 1,col 13) 'record' is a restricted identifier and cannot be used for type declarations"); + } + + @Test + void recordUsedAsRecordIdentifier() { + String s = "public record record() {}"; + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider(s)); + TestUtils.assertProblems(result, "(line 1,col 15) 'record' is a restricted identifier and cannot be used for type declarations"); + } + } + + @Nested + class RecordUsedAsIdentifierAllowedAsFieldDeclarations { + @Test + void recordUsedAsFieldIdentifierInClass() { + String s = "class X { int record; }"; + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider(s)); + TestUtils.assertNoProblems(result); + } + + @Test + void recordUsedAsFieldIdentifierInInterface() { + String s = "interface X { int record; }"; + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider(s)); + TestUtils.assertNoProblems(result); + } + } + + @Nested + class RecordDeclarationPermitted { + @Test + void recordDeclaration() { + String s = "record X() { }"; + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider(s)); + TestUtils.assertNoProblems(result); + } + } + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java17ValidatorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java17ValidatorTest.java new file mode 100644 index 0000000..e0626ff --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java17ValidatorTest.java @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.utils.TestUtils; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.ParseStart.COMPILATION_UNIT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_17; +import static com.github.javaparser.Providers.provider; + +class Java17ValidatorTest { + + private final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_17)); + + @Nested + class Sealed { + + @Test + void sealedAllowed() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("sealed class X permits Y, Z {}")); + TestUtils.assertNoProblems(result); + } + + @Test + void nonSealedAllowed() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("non-sealed class X {}")); + TestUtils.assertNoProblems(result); + } + + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java18ValidatorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java18ValidatorTest.java new file mode 100755 index 0000000..ef98914 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java18ValidatorTest.java @@ -0,0 +1,34 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParserConfiguration; + +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_18; + +class Java18ValidatorTest { + + private final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_18)); + + +} 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 new file mode 100644 index 0000000..db4d5f2 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java1_0ValidatorTest.java @@ -0,0 +1,122 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.stmt.Statement; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.ParseStart.*; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_1_0; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.TestUtils.assertNoProblems; +import static com.github.javaparser.utils.TestUtils.assertProblems; + +class Java1_0ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_1_0)); + + @Test + void tryWithoutResources() { + ParseResult result = javaParser.parse(STATEMENT, provider("try(X x=new Y()){}")); + assertProblems(result, + "(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 + void classExtendingMoreThanOne() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X extends Y, Z {}")); + assertProblems(result, "(line 1,col 20) A class cannot extend more than one other class."); + } + + @Test + void interfaceUsingImplements() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("interface X implements Y {}")); + assertProblems(result, "(line 1,col 24) An interface cannot implement other interfaces."); + } + + @Test + void interfaceWithInitializer() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("interface X {{}}")); + assertProblems(result, "(line 1,col 14) An interface cannot have initializers."); + } + + @Test + void defaultInClass() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X {default void a(){};}")); + assertProblems(result, "(line 1,col 10) 'default' is not allowed here."); + } + + @Test + void leftHandAssignmentCannotBeAConditional() { + ParseResult result = javaParser.parse(EXPRESSION, provider("(1==2)=3")); + assertProblems(result, "(line 1,col 1) Illegal left hand side of an assignment."); + } + + @Test + 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. 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 + void leftHandAssignmentCanBeInBraces() { + ParseResult result = javaParser.parse(EXPRESSION, provider("(i) += (i) += 1")); + assertNoProblems(result); + } + + @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. 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. 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. 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 labelBreakAllowed() { + ParseResult result = javaParser.parse(STATEMENT, provider("switch(x){case 3: break bla;}")); + assertNoProblems(result); + } + + @Test + void emptyBreakAllowed() { + ParseResult result = javaParser.parse(STATEMENT, provider("switch(x){case 3: break;}")); + assertNoProblems(result); + } +} 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 new file mode 100644 index 0000000..1756e09 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java1_1ValidatorTest.java @@ -0,0 +1,310 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.stmt.Statement; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.ParseStart.*; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_1_1; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.TestUtils.assertNoProblems; +import static com.github.javaparser.utils.TestUtils.assertProblems; + +class Java1_1ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_1_1)); + + public static final String allModifiers = "public protected private abstract static final transient volatile synchronized native strictfp transitive default "; + + @Test + void topClass() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider(allModifiers + "class X{}")); + assertProblems(result, + "(line 1,col 1) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 1) Can have only one of 'final', 'abstract'.", + "(line 1,col 1) 'transient' is not allowed here.", + "(line 1,col 1) 'default' is not allowed here.", + "(line 1,col 1) 'volatile' is not allowed here.", + "(line 1,col 1) 'strictfp' is not allowed here.", + "(line 1,col 1) 'private' is not allowed here.", + "(line 1,col 1) 'protected' is not allowed here.", + "(line 1,col 1) 'synchronized' is not allowed here.", + "(line 1,col 1) 'native' is not allowed here.", + "(line 1,col 1) 'transitive' is not allowed here.", + "(line 1,col 1) 'static' is not allowed here." + ); + } + + @Test + void nestedClass() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "class I{}}")); + assertProblems(result, + "(line 1,col 9) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 9) Can have only one of 'final', 'abstract'.", + "(line 1,col 9) 'transient' is not allowed here.", + "(line 1,col 9) 'default' is not allowed here.", + "(line 1,col 9) 'strictfp' is not allowed here.", + "(line 1,col 9) 'volatile' is not allowed here.", + "(line 1,col 9) 'synchronized' is not allowed here.", + "(line 1,col 9) 'native' is not allowed here.", + "(line 1,col 9) 'transitive' is not allowed here." + ); + } + + @Test + void localClass() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X{ void x() {" + allModifiers + "class I{}}}")); + assertProblems(result, + "(line 1,col 20) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 20) Can have only one of 'final', 'abstract'.", + "(line 1,col 20) 'transient' is not allowed here.", + "(line 1,col 20) 'volatile' is not allowed here.", + "(line 1,col 20) 'default' is not allowed here.", + "(line 1,col 20) 'synchronized' is not allowed here.", + "(line 1,col 20) 'native' is not allowed here.", + "(line 1,col 20) 'transitive' is not allowed here.", + "(line 1,col 20) 'strictfp' is not allowed here.", + "(line 1,col 20) 'static' is not allowed here.", + "(line 1,col 20) 'public' is not allowed here.", + "(line 1,col 20) 'private' is not allowed here.", + "(line 1,col 20) 'protected' is not allowed here." + ); + } + + @Test + void topInterface() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider(allModifiers + "interface X{}")); + assertProblems(result, + "(line 1,col 1) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 1) Can have only one of 'final', 'abstract'.", + "(line 1,col 1) 'transient' is not allowed here.", + "(line 1,col 1) 'volatile' is not allowed here.", + "(line 1,col 1) 'default' is not allowed here.", + "(line 1,col 1) 'strictfp' is not allowed here.", + "(line 1,col 1) 'synchronized' is not allowed here.", + "(line 1,col 1) 'native' is not allowed here.", + "(line 1,col 1) 'transitive' is not allowed here.", + "(line 1,col 1) 'static' is not allowed here.", + "(line 1,col 1) 'final' is not allowed here.", + "(line 1,col 1) 'private' is not allowed here.", + "(line 1,col 1) 'protected' is not allowed here." + ); + } + + @Test + void nestedInterface() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "interface I{}}")); + assertProblems(result, + "(line 1,col 9) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 9) Can have only one of 'final', 'abstract'.", + "(line 1,col 9) 'transient' is not allowed here.", + "(line 1,col 9) 'volatile' is not allowed here.", + "(line 1,col 9) 'default' is not allowed here.", + "(line 1,col 9) 'final' is not allowed here.", + "(line 1,col 9) 'strictfp' is not allowed here.", + "(line 1,col 9) 'synchronized' is not allowed here.", + "(line 1,col 9) 'native' is not allowed here.", + "(line 1,col 9) 'transitive' is not allowed here." + ); + } + + @Test + void constructor() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "X(){};}")); + assertProblems(result, + "(line 1,col 9) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 9) Can have only one of 'final', 'abstract'.", + "(line 1,col 9) 'transient' is not allowed here.", + "(line 1,col 9) 'volatile' is not allowed here.", + "(line 1,col 9) 'final' is not allowed here.", + "(line 1,col 9) 'strictfp' is not allowed here.", + "(line 1,col 9) 'synchronized' is not allowed here.", + "(line 1,col 9) 'default' is not allowed here.", + "(line 1,col 9) 'native' is not allowed here.", + "(line 1,col 9) 'strictfp' is not allowed here.", + "(line 1,col 9) 'abstract' is not allowed here.", + "(line 1,col 9) 'static' is not allowed here.", + "(line 1,col 9) 'transitive' is not allowed here." + ); + } + + @Test + void constructorParameter() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X{X(" + allModifiers + " int i){};}")); + assertProblems(result, + "(line 1,col 11) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 11) Can have only one of 'final', 'abstract'.", + "(line 1,col 11) 'transient' is not allowed here.", + "(line 1,col 11) 'volatile' is not allowed here.", + "(line 1,col 11) 'synchronized' is not allowed here.", + "(line 1,col 11) 'native' is not allowed here.", + "(line 1,col 11) 'strictfp' is not allowed here.", + "(line 1,col 11) 'default' is not allowed here.", + "(line 1,col 11) 'abstract' is not allowed here.", + "(line 1,col 11) 'static' is not allowed here.", + "(line 1,col 11) 'transitive' is not allowed here.", + "(line 1,col 11) 'private' is not allowed here.", + "(line 1,col 11) 'public' is not allowed here.", + "(line 1,col 11) 'protected' is not allowed here." + ); + } + + @Test + void classMethod() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "int x(){};}")); + assertProblems(result, + "(line 1,col 9) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 9) Can have only one of 'final', 'abstract'.", + "(line 1,col 9) Cannot be 'abstract' and also 'private', 'static', 'final', 'native', 'strictfp', 'synchronized'.", + "(line 1,col 9) 'transient' is not allowed here.", + "(line 1,col 9) 'default' is not allowed here.", + "(line 1,col 9) 'strictfp' is not allowed here.", + "(line 1,col 9) 'volatile' is not allowed here.", + "(line 1,col 9) 'transitive' is not allowed here." + ); + } + + @Test + void interfaceMethod() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("interface X{" + allModifiers + "int x(){};}")); + assertProblems(result, + "(line 1,col 13) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 13) Can have only one of 'final', 'abstract'.", + "(line 1,col 13) Cannot be 'abstract' and also 'private', 'static', 'final', 'native', 'strictfp', 'synchronized'.", + "(line 1,col 13) 'transient' is not allowed here.", + "(line 1,col 13) 'strictfp' is not allowed here.", + "(line 1,col 13) 'volatile' is not allowed here.", + "(line 1,col 13) 'default' is not allowed here.", + "(line 1,col 13) 'transitive' is not allowed here.", + "(line 1,col 13) 'private' is not allowed here.", + "(line 1,col 13) 'static' is not allowed here." + ); + } + + @Test + void methodParameter() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X{int x(" + allModifiers + " int i){};}")); + assertProblems(result, + "(line 1,col 15) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 15) Can have only one of 'final', 'abstract'.", + "(line 1,col 15) 'transient' is not allowed here.", + "(line 1,col 15) 'volatile' is not allowed here.", + "(line 1,col 15) 'synchronized' is not allowed here.", + "(line 1,col 15) 'native' is not allowed here.", + "(line 1,col 15) 'strictfp' is not allowed here.", + "(line 1,col 15) 'abstract' is not allowed here.", + "(line 1,col 15) 'default' is not allowed here.", + "(line 1,col 15) 'static' is not allowed here.", + "(line 1,col 15) 'transitive' is not allowed here.", + "(line 1,col 15) 'private' is not allowed here.", + "(line 1,col 15) 'public' is not allowed here.", + "(line 1,col 15) 'protected' is not allowed here." + ); + } + + @Test + void field() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "int i;}")); + assertProblems(result, + "(line 1,col 9) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 9) Can have only one of 'final', 'abstract'.", + "(line 1,col 9) 'synchronized' is not allowed here.", + "(line 1,col 9) 'native' is not allowed here.", + "(line 1,col 9) 'strictfp' is not allowed here.", + "(line 1,col 9) 'default' is not allowed here.", + "(line 1,col 9) 'abstract' is not allowed here.", + "(line 1,col 9) 'transitive' is not allowed here." + ); + } + + @Test + void localVariable() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X{int x(){" + allModifiers + "int i;}}")); + assertProblems(result, + "(line 1,col 17) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 17) Can have only one of 'final', 'abstract'.", + "(line 1,col 17) 'transient' is not allowed here.", + "(line 1,col 17) 'volatile' is not allowed here.", + "(line 1,col 17) 'synchronized' is not allowed here.", + "(line 1,col 17) 'native' is not allowed here.", + "(line 1,col 17) 'default' is not allowed here.", + "(line 1,col 17) 'strictfp' is not allowed here.", + "(line 1,col 17) 'abstract' is not allowed here.", + "(line 1,col 17) 'static' is not allowed here.", + "(line 1,col 17) 'transitive' is not allowed here.", + "(line 1,col 17) 'private' is not allowed here.", + "(line 1,col 17) 'public' is not allowed here.", + "(line 1,col 17) 'protected' is not allowed here." + ); + } + + + @Test + void catchParameter() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X{int x(){ try{}catch(" + allModifiers + " Integer x){}}}")); + assertProblems(result, + "(line 1,col 29) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 29) Can have only one of 'final', 'abstract'.", + "(line 1,col 29) 'transient' is not allowed here.", + "(line 1,col 29) 'volatile' is not allowed here.", + "(line 1,col 29) 'synchronized' is not allowed here.", + "(line 1,col 29) 'native' is not allowed here.", + "(line 1,col 29) 'default' is not allowed here.", + "(line 1,col 29) 'strictfp' is not allowed here.", + "(line 1,col 29) 'abstract' is not allowed here.", + "(line 1,col 29) 'static' is not allowed here.", + "(line 1,col 29) 'transitive' is not allowed here.", + "(line 1,col 29) 'private' is not allowed here.", + "(line 1,col 29) 'public' is not allowed here.", + "(line 1,col 29) 'protected' is not allowed here." + ); + } + + @Test + void innerClasses() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X{class Y{}}")); + assertNoProblems(result); + } + + @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. 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 + void reflection() { + ParseResult result = javaParser.parse(EXPRESSION, provider("Abc.class")); + assertNoProblems(result); + } + + @Test + void strictfpAllowedAsIdentifier() { + ParseResult result = javaParser.parse(STATEMENT, provider("int strictfp;")); + assertNoProblems(result); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java1_2ValidatorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java1_2ValidatorTest.java new file mode 100644 index 0000000..6ea6e91 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java1_2ValidatorTest.java @@ -0,0 +1,295 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.stmt.Statement; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.ParseStart.COMPILATION_UNIT; +import static com.github.javaparser.ParseStart.STATEMENT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_1_2; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.TestUtils.assertProblems; + +class Java1_2ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_1_2)); + + private final String allModifiers = "public protected private abstract static final transient volatile synchronized native strictfp transitive default "; + + @Test + void topClass() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider(allModifiers + "class X{}")); + assertProblems(result, + "(line 1,col 1) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 1) Can have only one of 'final', 'abstract'.", + "(line 1,col 1) Can have only one of 'native', 'strictfp'.", + "(line 1,col 1) 'transient' is not allowed here.", + "(line 1,col 1) 'default' is not allowed here.", + "(line 1,col 1) 'volatile' is not allowed here.", + "(line 1,col 1) 'private' is not allowed here.", + "(line 1,col 1) 'protected' is not allowed here.", + "(line 1,col 1) 'synchronized' is not allowed here.", + "(line 1,col 1) 'native' is not allowed here.", + "(line 1,col 1) 'transitive' is not allowed here.", + "(line 1,col 1) 'static' is not allowed here." + ); + } + + @Test + void nestedClass() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "class I{}}")); + assertProblems(result, + "(line 1,col 9) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 9) Can have only one of 'final', 'abstract'.", + "(line 1,col 9) Can have only one of 'native', 'strictfp'.", + "(line 1,col 9) 'transient' is not allowed here.", + "(line 1,col 9) 'default' is not allowed here.", + "(line 1,col 9) 'volatile' is not allowed here.", + "(line 1,col 9) 'synchronized' is not allowed here.", + "(line 1,col 9) 'native' is not allowed here.", + "(line 1,col 9) 'transitive' is not allowed here." + ); + } + + @Test + void localClass() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X{ void x() {" + allModifiers + "class I{}}}")); + assertProblems(result, + "(line 1,col 20) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 20) Can have only one of 'final', 'abstract'.", + "(line 1,col 20) Can have only one of 'native', 'strictfp'.", + "(line 1,col 20) 'transient' is not allowed here.", + "(line 1,col 20) 'volatile' is not allowed here.", + "(line 1,col 20) 'default' is not allowed here.", + "(line 1,col 20) 'synchronized' is not allowed here.", + "(line 1,col 20) 'native' is not allowed here.", + "(line 1,col 20) 'transitive' is not allowed here.", + "(line 1,col 20) 'static' is not allowed here.", + "(line 1,col 20) 'public' is not allowed here.", + "(line 1,col 20) 'private' is not allowed here.", + "(line 1,col 20) 'protected' is not allowed here." + ); + } + + @Test + void topInterface() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider(allModifiers + "interface X{}")); + assertProblems(result, + "(line 1,col 1) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 1) Can have only one of 'final', 'abstract'.", + "(line 1,col 1) Can have only one of 'native', 'strictfp'.", + "(line 1,col 1) 'transient' is not allowed here.", + "(line 1,col 1) 'volatile' is not allowed here.", + "(line 1,col 1) 'default' is not allowed here.", + "(line 1,col 1) 'synchronized' is not allowed here.", + "(line 1,col 1) 'native' is not allowed here.", + "(line 1,col 1) 'transitive' is not allowed here.", + "(line 1,col 1) 'static' is not allowed here.", + "(line 1,col 1) 'final' is not allowed here.", + "(line 1,col 1) 'private' is not allowed here.", + "(line 1,col 1) 'protected' is not allowed here." + ); + } + + @Test + void nestedInterface() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "interface I{}}")); + assertProblems(result, + "(line 1,col 9) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 9) Can have only one of 'final', 'abstract'.", + "(line 1,col 9) Can have only one of 'native', 'strictfp'.", + "(line 1,col 9) 'transient' is not allowed here.", + "(line 1,col 9) 'volatile' is not allowed here.", + "(line 1,col 9) 'default' is not allowed here.", + "(line 1,col 9) 'final' is not allowed here.", + "(line 1,col 9) 'synchronized' is not allowed here.", + "(line 1,col 9) 'native' is not allowed here.", + "(line 1,col 9) 'transitive' is not allowed here." + ); + } + + @Test + void constructor() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "X(){};}")); + assertProblems(result, + "(line 1,col 9) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 9) Can have only one of 'final', 'abstract'.", + "(line 1,col 9) Can have only one of 'native', 'strictfp'.", + "(line 1,col 9) 'transient' is not allowed here.", + "(line 1,col 9) 'volatile' is not allowed here.", + "(line 1,col 9) 'final' is not allowed here.", + "(line 1,col 9) 'synchronized' is not allowed here.", + "(line 1,col 9) 'default' is not allowed here.", + "(line 1,col 9) 'native' is not allowed here.", + "(line 1,col 9) 'strictfp' is not allowed here.", + "(line 1,col 9) 'abstract' is not allowed here.", + "(line 1,col 9) 'static' is not allowed here.", + "(line 1,col 9) 'transitive' is not allowed here." + ); + } + + @Test + void constructorParameter() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X{X(" + allModifiers + " int i){};}")); + assertProblems(result, + "(line 1,col 11) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 11) Can have only one of 'final', 'abstract'.", + "(line 1,col 11) Can have only one of 'native', 'strictfp'.", + "(line 1,col 11) 'transient' is not allowed here.", + "(line 1,col 11) 'volatile' is not allowed here.", + "(line 1,col 11) 'synchronized' is not allowed here.", + "(line 1,col 11) 'native' is not allowed here.", + "(line 1,col 11) 'strictfp' is not allowed here.", + "(line 1,col 11) 'default' is not allowed here.", + "(line 1,col 11) 'abstract' is not allowed here.", + "(line 1,col 11) 'static' is not allowed here.", + "(line 1,col 11) 'transitive' is not allowed here.", + "(line 1,col 11) 'private' is not allowed here.", + "(line 1,col 11) 'public' is not allowed here.", + "(line 1,col 11) 'protected' is not allowed here." + ); + } + + @Test + void classMethod() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "int x(){};}")); + assertProblems(result, + "(line 1,col 9) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 9) Can have only one of 'final', 'abstract'.", + "(line 1,col 9) Can have only one of 'native', 'strictfp'.", + "(line 1,col 9) Cannot be 'abstract' and also 'private', 'static', 'final', 'native', 'strictfp', 'synchronized'.", + "(line 1,col 9) 'transient' is not allowed here.", + "(line 1,col 9) 'default' is not allowed here.", + "(line 1,col 9) 'volatile' is not allowed here.", + "(line 1,col 9) 'transitive' is not allowed here." + ); + } + + @Test + void interfaceMethod() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("interface X{" + allModifiers + "int x(){};}")); + assertProblems(result, + "(line 1,col 13) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 13) Can have only one of 'final', 'abstract'.", + "(line 1,col 13) Can have only one of 'native', 'strictfp'.", + "(line 1,col 13) Cannot be 'abstract' and also 'private', 'static', 'final', 'native', 'strictfp', 'synchronized'.", + "(line 1,col 13) 'transient' is not allowed here.", + "(line 1,col 13) 'volatile' is not allowed here.", + "(line 1,col 13) 'default' is not allowed here.", + "(line 1,col 13) 'transitive' is not allowed here.", + "(line 1,col 13) 'private' is not allowed here.", + "(line 1,col 13) 'static' is not allowed here." + ); + } + + @Test + void methodParameter() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X{int x(" + allModifiers + " int i){};}")); + assertProblems(result, + "(line 1,col 15) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 15) Can have only one of 'final', 'abstract'.", + "(line 1,col 15) Can have only one of 'native', 'strictfp'.", + "(line 1,col 15) 'transient' is not allowed here.", + "(line 1,col 15) 'volatile' is not allowed here.", + "(line 1,col 15) 'synchronized' is not allowed here.", + "(line 1,col 15) 'native' is not allowed here.", + "(line 1,col 15) 'strictfp' is not allowed here.", + "(line 1,col 15) 'abstract' is not allowed here.", + "(line 1,col 15) 'default' is not allowed here.", + "(line 1,col 15) 'static' is not allowed here.", + "(line 1,col 15) 'transitive' is not allowed here.", + "(line 1,col 15) 'private' is not allowed here.", + "(line 1,col 15) 'public' is not allowed here.", + "(line 1,col 15) 'protected' is not allowed here." + ); + } + + @Test + void field() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "int i;}")); + assertProblems(result, + "(line 1,col 9) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 9) Can have only one of 'final', 'abstract'.", + "(line 1,col 9) Can have only one of 'native', 'strictfp'.", + "(line 1,col 9) 'synchronized' is not allowed here.", + "(line 1,col 9) 'native' is not allowed here.", + "(line 1,col 9) 'strictfp' is not allowed here.", + "(line 1,col 9) 'default' is not allowed here.", + "(line 1,col 9) 'abstract' is not allowed here.", + "(line 1,col 9) 'transitive' is not allowed here." + ); + } + + @Test + void localVariable() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X{int x(){" + allModifiers + "int i;}}")); + assertProblems(result, + "(line 1,col 17) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 17) Can have only one of 'final', 'abstract'.", + "(line 1,col 17) Can have only one of 'native', 'strictfp'.", + "(line 1,col 17) 'transient' is not allowed here.", + "(line 1,col 17) 'volatile' is not allowed here.", + "(line 1,col 17) 'synchronized' is not allowed here.", + "(line 1,col 17) 'native' is not allowed here.", + "(line 1,col 17) 'default' is not allowed here.", + "(line 1,col 17) 'strictfp' is not allowed here.", + "(line 1,col 17) 'abstract' is not allowed here.", + "(line 1,col 17) 'static' is not allowed here.", + "(line 1,col 17) 'transitive' is not allowed here.", + "(line 1,col 17) 'private' is not allowed here.", + "(line 1,col 17) 'public' is not allowed here.", + "(line 1,col 17) 'protected' is not allowed here." + ); + } + + @Test + void catchParameter() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X{int x(){ try{}catch(" + allModifiers + " Integer x){}}}")); + assertProblems(result, + "(line 1,col 29) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 29) Can have only one of 'final', 'abstract'.", + "(line 1,col 29) Can have only one of 'native', 'strictfp'.", + "(line 1,col 29) 'transient' is not allowed here.", + "(line 1,col 29) 'volatile' is not allowed here.", + "(line 1,col 29) 'synchronized' is not allowed here.", + "(line 1,col 29) 'native' is not allowed here.", + "(line 1,col 29) 'default' is not allowed here.", + "(line 1,col 29) 'strictfp' is not allowed here.", + "(line 1,col 29) 'abstract' is not allowed here.", + "(line 1,col 29) 'static' is not allowed here.", + "(line 1,col 29) 'transitive' is not allowed here.", + "(line 1,col 29) 'private' is not allowed here.", + "(line 1,col 29) 'public' is not allowed here.", + "(line 1,col 29) 'protected' is not allowed here." + ); + } + + @Test + void strictfpNotAllowedAsIdentifier() { + ParseResult result = javaParser.parse(STATEMENT, provider("int strictfp;")); + assertProblems(result, "(line 1,col 5) 'strictfp' cannot be used as an identifier as it is a keyword."); + } +} 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 new file mode 100644 index 0000000..67a6b56 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java1_3ValidatorTest.java @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.stmt.Statement; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.ParseStart.STATEMENT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_1_3; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.TestUtils.assertProblems; + +class Java1_3ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_1_3)); + + @Test + void noAssert() { + ParseResult result = javaParser.parse(STATEMENT, provider("assert a;")); + 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 new file mode 100644 index 0000000..b802133 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java1_4ValidatorTest.java @@ -0,0 +1,91 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.Parameter; +import com.github.javaparser.ast.stmt.Statement; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.ParseStart.*; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_1_4; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.TestUtils.assertNoProblems; +import static com.github.javaparser.utils.TestUtils.assertProblems; + +class Java1_4ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_1_4)); + + @Test + void yesAssert() { + ParseResult result = javaParser.parse(STATEMENT, provider("assert a;")); + assertNoProblems(result); + } + + @Test + void noGenerics() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X{List b;}")); + assertProblems(result, + "(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." + ); + } + + @Test + void noAnnotations() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("@Abc @Def() @Ghi(a=3) @interface X{}")); + assertProblems(result, + "(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. 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. 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 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 + void enumAllowedAsIdentifier() { + ParseResult result = javaParser.parse(STATEMENT, provider("int enum;")); + assertNoProblems(result); + } +} 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 new file mode 100644 index 0000000..6826264 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java5ValidatorTest.java @@ -0,0 +1,194 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.Parameter; +import com.github.javaparser.ast.stmt.Statement; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.ParseStart.*; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_5; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.ast.validator.Java1_1ValidatorTest.allModifiers; +import static com.github.javaparser.utils.TestUtils.assertNoProblems; +import static com.github.javaparser.utils.TestUtils.assertProblems; + +class Java5ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_5)); + + @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. 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 + void topAnnotationDeclaration() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider(allModifiers + "@interface X{}")); + assertProblems(result, + "(line 1,col 1) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 1) Can have only one of 'final', 'abstract'.", + "(line 1,col 1) Can have only one of 'native', 'strictfp'.", + "(line 1,col 1) 'transient' is not allowed here.", + "(line 1,col 1) 'volatile' is not allowed here.", + "(line 1,col 1) 'synchronized' is not allowed here.", + "(line 1,col 1) 'default' is not allowed here.", + "(line 1,col 1) 'native' is not allowed here.", + "(line 1,col 1) 'transitive' is not allowed here.", + "(line 1,col 1) 'static' is not allowed here.", + "(line 1,col 1) 'final' is not allowed here.", + "(line 1,col 1) 'private' is not allowed here.", + "(line 1,col 1) 'protected' is not allowed here." + ); + } + + @Test + void nestedAnnotationDeclaration() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "@interface I{}}")); + assertProblems(result, + "(line 1,col 9) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 9) Can have only one of 'final', 'abstract'.", + "(line 1,col 9) Can have only one of 'native', 'strictfp'.", + "(line 1,col 9) 'transient' is not allowed here.", + "(line 1,col 9) 'volatile' is not allowed here.", + "(line 1,col 9) 'default' is not allowed here.", + "(line 1,col 9) 'final' is not allowed here.", + "(line 1,col 9) 'synchronized' is not allowed here.", + "(line 1,col 9) 'native' is not allowed here.", + "(line 1,col 9) 'transitive' is not allowed here." + ); + } + + @Test + void annotationMember() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("@interface X{" + allModifiers + "int x();}")); + assertProblems(result, + "(line 1,col 14) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 14) Can have only one of 'final', 'abstract'.", + "(line 1,col 14) Can have only one of 'native', 'strictfp'.", + "(line 1,col 14) 'transient' is not allowed here.", + "(line 1,col 14) 'volatile' is not allowed here.", + "(line 1,col 14) 'final' is not allowed here.", + "(line 1,col 14) 'synchronized' is not allowed here.", + "(line 1,col 14) 'default' is not allowed here.", + "(line 1,col 14) 'native' is not allowed here.", + "(line 1,col 14) 'protected' is not allowed here.", + "(line 1,col 14) 'private' is not allowed here.", + "(line 1,col 14) 'strictfp' is not allowed here.", + "(line 1,col 14) 'static' is not allowed here.", + "(line 1,col 14) 'transitive' is not allowed here." + ); + } + + @Test + void topEnum() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider(allModifiers + "enum X{}")); + assertProblems(result, + "(line 1,col 1) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 1) Can have only one of 'final', 'abstract'.", + "(line 1,col 1) Can have only one of 'native', 'strictfp'.", + "(line 1,col 1) 'transient' is not allowed here.", + "(line 1,col 1) 'volatile' is not allowed here.", + "(line 1,col 1) 'synchronized' is not allowed here.", + "(line 1,col 1) 'default' is not allowed here.", + "(line 1,col 1) 'native' is not allowed here.", + "(line 1,col 1) 'transitive' is not allowed here.", + "(line 1,col 1) 'static' is not allowed here.", + "(line 1,col 1) 'abstract' is not allowed here.", + "(line 1,col 1) 'final' is not allowed here.", + "(line 1,col 1) 'private' is not allowed here.", + "(line 1,col 1) 'protected' is not allowed here." + ); + } + + @Test + void nestedEnum() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "enum I{}}")); + assertProblems(result, + "(line 1,col 9) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 9) Can have only one of 'final', 'abstract'.", + "(line 1,col 9) Can have only one of 'native', 'strictfp'.", + "(line 1,col 9) 'transient' is not allowed here.", + "(line 1,col 9) 'volatile' is not allowed here.", + "(line 1,col 9) 'default' is not allowed here.", + "(line 1,col 9) 'abstract' is not allowed here.", + "(line 1,col 9) 'final' is not allowed here.", + "(line 1,col 9) 'synchronized' is not allowed here.", + "(line 1,col 9) 'native' is not allowed here.", + "(line 1,col 9) 'transitive' is not allowed here." + ); + } + + @Test + void varargs() { + ParseResult result = javaParser.parse(PARAMETER, provider("String... x")); + assertNoProblems(result); + } + + @Test + void foreach() { + ParseResult result = javaParser.parse(STATEMENT, provider("for(X x: xs){}")); + assertNoProblems(result); + } + + @Test + void noMultipleVariablesInForEach() { + ParseResult result = javaParser.parse(STATEMENT, provider("for(int i, j : nums){}")); + assertProblems(result, + "(line 1,col 1) A foreach statement's variable declaration must have exactly one variable declarator. Given: 2."); + } + + @Test + void noModifiersInForEachBesideFinal() { + ParseResult result = javaParser.parse(STATEMENT, provider("for(static transient int i : nums){}")); + assertProblems(result, + "(line 1,col 5) 'static' is not allowed here.", "(line 1,col 5) 'transient' is not allowed here."); + } + + @Test + void staticImport() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("import static x;import static x.*;import x.X;import x.*;")); + assertNoProblems(result); + } + + @Test + void noPrimitiveTypeArguments() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X extends Y {}")); + assertProblems(result, "(line 1,col 17) Type arguments may not be primitive."); + } + + @Test + void enumAllowedAsIdentifier() { + ParseResult result = javaParser.parse(STATEMENT, provider("int enum;")); + assertProblems(result, "(line 1,col 5) 'enum' cannot be used as an identifier as it is a keyword."); + } + + @Test + void enumAllowedInSwitch() { + ParseResult result = javaParser.parse(STATEMENT, provider("switch(x){case GREEN: ;}")); + assertNoProblems(result); + } +} 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 new file mode 100644 index 0000000..7d26c15 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java6ValidatorTest.java @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.stmt.Statement; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.ParseStart.EXPRESSION; +import static com.github.javaparser.ParseStart.STATEMENT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_6; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.TestUtils.assertProblems; + +class Java6ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_6)); + + @Test + void nobinaryIntegerLiterals() { + ParseResult result = javaParser.parse(EXPRESSION, provider("0b01")); + assertProblems(result, "(line 1,col 1) Binary literal values are not supported."); + } + + @Test + void noUnderscoresInIntegerLiterals() { + ParseResult result = javaParser.parse(EXPRESSION, provider("1_000_000")); + assertProblems(result, "(line 1,col 1) Underscores in literal values are not supported."); + } + + @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. 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 new file mode 100644 index 0000000..0908275 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java7ValidatorTest.java @@ -0,0 +1,128 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.Problem; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.ast.type.ClassOrInterfaceType; +import com.github.javaparser.ast.type.UnionType; +import com.github.javaparser.ast.validator.language_level_validations.Java7Validator; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static com.github.javaparser.ParseStart.*; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_7; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.TestUtils.assertNoProblems; +import static com.github.javaparser.utils.TestUtils.assertProblems; + +class Java7ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_7)); + + @Test + void generics() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X{List b = new ArrayList<>();}")); + assertNoProblems(result); + } + + @Test + void defaultMethodWithoutBody() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("interface X {default void a();}")); + assertProblems(result, "(line 1,col 14) 'default' is not allowed here."); + } + + @Test + void tryWithoutAnything() { + ParseResult result = javaParser.parse(STATEMENT, provider("try{}")); + assertProblems(result, "(line 1,col 1) Try has no finally, no catch, and no resources."); + } + + @Test + void tryWithResourceVariableDeclaration() { + ParseResult result = javaParser.parse(STATEMENT, provider("try(Reader r = new Reader()){}")); + assertNoProblems(result); + } + + @Test + void tryWithResourceReference() { + ParseResult result = javaParser.parse(STATEMENT, provider("try(a.b.c){}")); + assertProblems(result, "(line 1,col 1) Try with resources only supports variable declarations."); + } + + @Test + void stringsInSwitch() { + ParseResult result = javaParser.parse(STATEMENT, provider("switch(x){case \"abc\": ;}")); + assertNoProblems(result); + } + + @Test + void binaryIntegerLiterals() { + ParseResult result = javaParser.parse(EXPRESSION, provider("0b01")); + assertNoProblems(result); + } + + @Test + void underscoresInIntegerLiterals() { + ParseResult result = javaParser.parse(EXPRESSION, provider("1_000_000")); + assertNoProblems(result); + } + + @Test + void multiCatch() { + ParseResult result = javaParser.parse(STATEMENT, provider("try{}catch(Abc|Def e){}")); + assertNoProblems(result); + } + + @Test + void multiCatchWithoutElements() { + UnionType unionType = new UnionType(); + + List problems = new ArrayList<>(); + new Java7Validator().accept(unionType, new ProblemReporter(problems::add)); + + assertProblems(problems, "UnionType.elements can not be empty."); + } + + @Test + void multiCatchWithOneElement() { + UnionType unionType = new UnionType(); + unionType.getElements().add(new ClassOrInterfaceType()); + + List problems = new ArrayList<>(); + new Java7Validator().accept(unionType, new ProblemReporter(problems::add)); + + assertProblems(problems, "Union type (multi catch) must have at least two elements."); + } + + @Test + void noLambdas() { + ParseResult result = javaParser.parse(STATEMENT, provider("a(() -> 1);")); + 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 new file mode 100644 index 0000000..cd89028 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java8ValidatorTest.java @@ -0,0 +1,103 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.stmt.Statement; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.ParseStart.COMPILATION_UNIT; +import static com.github.javaparser.ParseStart.STATEMENT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_8; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.ast.validator.Java1_1ValidatorTest.allModifiers; +import static com.github.javaparser.utils.TestUtils.assertNoProblems; +import static com.github.javaparser.utils.TestUtils.assertProblems; + +class Java8ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_8)); + + @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. 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 + void lambdaParameter() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("class X{int x(){ a((" + allModifiers + " Integer x) -> 10);}}")); + assertProblems(result, + "(line 1,col 21) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 21) Can have only one of 'final', 'abstract'.", + "(line 1,col 21) Can have only one of 'native', 'strictfp'.", + "(line 1,col 21) 'transient' is not allowed here.", + "(line 1,col 21) 'volatile' is not allowed here.", + "(line 1,col 21) 'synchronized' is not allowed here.", + "(line 1,col 21) 'strictfp' is not allowed here.", + "(line 1,col 21) 'default' is not allowed here.", + "(line 1,col 21) 'native' is not allowed here.", + "(line 1,col 21) 'strictfp' is not allowed here.", + "(line 1,col 21) 'abstract' is not allowed here.", + "(line 1,col 21) 'static' is not allowed here.", + "(line 1,col 21) 'transitive' is not allowed here.", + "(line 1,col 21) 'private' is not allowed here.", + "(line 1,col 21) 'public' is not allowed here.", + "(line 1,col 21) 'protected' is not allowed here." + ); + } + + @Test + void interfaceMethod() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("interface X{" + allModifiers + "int x(){};}")); + assertProblems(result, + "(line 1,col 13) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 13) Can have only one of 'final', 'abstract'.", + "(line 1,col 13) Can have only one of 'native', 'strictfp'.", + "(line 1,col 13) Cannot be 'abstract' and also 'private', 'static', 'final', 'native', 'strictfp', 'synchronized'.", + "(line 1,col 13) 'transient' is not allowed here.", + "(line 1,col 13) 'volatile' is not allowed here.", + "(line 1,col 13) 'transitive' is not allowed here.", + "(line 1,col 13) 'private' is not allowed here." + ); + } + + @Test + void defaultMethodWithoutBody() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("interface X {default void a();}")); + assertProblems(result, "(line 1,col 14) 'default' methods must have a body."); + } + + @Test + void lambdas() { + ParseResult result = javaParser.parse(STATEMENT, provider("a(() -> 1);")); + assertNoProblems(result); + } + + @Test + void noModules() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("open module x {}")); + 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/ast/validator/Java9ValidatorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java9ValidatorTest.java new file mode 100644 index 0000000..9df80cf --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/validator/Java9ValidatorTest.java @@ -0,0 +1,100 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.stmt.Statement; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.ParseStart.COMPILATION_UNIT; +import static com.github.javaparser.ParseStart.STATEMENT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_9; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.ast.validator.Java1_1ValidatorTest.allModifiers; +import static com.github.javaparser.utils.TestUtils.assertNoProblems; +import static com.github.javaparser.utils.TestUtils.assertProblems; + +class Java9ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_9)); + + @Test + void underscoreIdentifiers() { + ParseResult result = javaParser.parse(STATEMENT, provider("a.b._.c.d = act(_, _ -> _);")); + assertProblems(result, + "(line 1,col 5) '_' is a reserved keyword.", + "(line 1,col 17) '_' is a reserved keyword.", + "(line 1,col 20) '_' is a reserved keyword.", + "(line 1,col 25) '_' is a reserved keyword." + ); + } + + @Test + void moduleRequires() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("module x{requires " + allModifiers + " a;}")); + assertProblems(result, + "(line 1,col 10) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 10) Can have only one of 'final', 'abstract'.", + "(line 1,col 10) Can have only one of 'native', 'strictfp'.", + "(line 1,col 10) 'transient' is not allowed here.", + "(line 1,col 10) 'volatile' is not allowed here.", + "(line 1,col 10) 'final' is not allowed here.", + "(line 1,col 10) 'synchronized' is not allowed here.", + "(line 1,col 10) 'default' is not allowed here.", + "(line 1,col 10) 'native' is not allowed here.", + "(line 1,col 10) 'private' is not allowed here.", + "(line 1,col 10) 'protected' is not allowed here.", + "(line 1,col 10) 'strictfp' is not allowed here.", + "(line 1,col 10) 'abstract' is not allowed here.", + "(line 1,col 10) 'public' is not allowed here." + ); + } + + @Test + void interfaceMethod() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("interface X{" + allModifiers + "int x(){};}")); + assertProblems(result, + "(line 1,col 13) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 13) Can have only one of 'final', 'abstract'.", + "(line 1,col 13) Can have only one of 'native', 'strictfp'.", + "(line 1,col 13) Cannot be 'abstract' and also 'private', 'static', 'final', 'native', 'strictfp', 'synchronized'.", + "(line 1,col 13) 'transient' is not allowed here.", + "(line 1,col 13) 'volatile' is not allowed here.", + "(line 1,col 13) 'transitive' is not allowed here." + ); + } + + @Test + void modules() { + ParseResult result = javaParser.parse(COMPILATION_UNIT, provider("open module x {}")); + assertNoProblems(result); + } + + @Test + void tryWithResourceReference() { + ParseResult result = javaParser.parse(STATEMENT, provider("try(a.b.c){}")); + assertNoProblems(result); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/CloneVisitorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/CloneVisitorTest.java new file mode 100644 index 0000000..bc0cbd1 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/CloneVisitorTest.java @@ -0,0 +1,107 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.visitor; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.type.Type; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Iterator; + +import static com.github.javaparser.StaticJavaParser.parseType; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class CloneVisitorTest { + CompilationUnit cu; + + @BeforeEach + void setUp() { + cu = new CompilationUnit(); + } + + @AfterEach + void teardown() { + cu = null; + } + + @Test + void cloneJavaDocTest() { + NodeList> bodyDeclarationList = new NodeList<>(); + bodyDeclarationList.add(new AnnotationMemberDeclaration().setJavadocComment("javadoc")); + bodyDeclarationList.add(new ConstructorDeclaration().setJavadocComment("javadoc")); + bodyDeclarationList.add(new EnumConstantDeclaration().setJavadocComment("javadoc")); + bodyDeclarationList.add(new FieldDeclaration().setJavadocComment("javadoc")); + bodyDeclarationList.add(new InitializerDeclaration().setJavadocComment("javadoc")); + bodyDeclarationList.add(new MethodDeclaration().setJavadocComment("javadoc")); + + NodeList> typeDeclarationList = new NodeList<>(); + AnnotationDeclaration annotationDeclaration = new AnnotationDeclaration(); + annotationDeclaration.setName("nnotationDeclarationTest"); + typeDeclarationList.add(annotationDeclaration.setJavadocComment("javadoc")); + + ClassOrInterfaceDeclaration classOrInterfaceDeclaration2 = new ClassOrInterfaceDeclaration(); + classOrInterfaceDeclaration2.setName("emptyTypeDeclarationTest"); + typeDeclarationList.add(classOrInterfaceDeclaration2.setJavadocComment("javadoc")); + + EnumDeclaration enumDeclaration = new EnumDeclaration(); + enumDeclaration.setName("enumDeclarationTest"); + typeDeclarationList.add(enumDeclaration.setJavadocComment("javadoc")); + + ClassOrInterfaceDeclaration classOrInterfaceDeclaration = new ClassOrInterfaceDeclaration(); + classOrInterfaceDeclaration.setName("classOrInterfaceDeclarationTest"); + typeDeclarationList.add(classOrInterfaceDeclaration.setJavadocComment("javadoc")); + + ClassOrInterfaceDeclaration classOrInterfaceDeclaration1 = new ClassOrInterfaceDeclaration(); + classOrInterfaceDeclaration1.setName("emptyTypeDeclarationTest1"); + typeDeclarationList.add(classOrInterfaceDeclaration2.setMembers(bodyDeclarationList)); + + cu.setTypes(typeDeclarationList); + CompilationUnit cuClone = (CompilationUnit) new CloneVisitor().visit(cu, null); + + NodeList> typeDeclarationListClone = cuClone.getTypes(); + Iterator> typeItr = typeDeclarationListClone.iterator(); + TypeDeclaration typeDeclaration; + while (typeItr.hasNext()) { + typeDeclaration = typeItr.next(); + if (typeDeclaration.getMembers() == null) { + assertEquals("javadoc", typeDeclaration.getComment().get().getContent()); + } else { + Iterator> bodyItr = typeDeclaration.getMembers().iterator(); + while (bodyItr.hasNext()) { + BodyDeclaration bodyDeclaration = bodyItr.next(); + assertEquals("javadoc", bodyDeclaration.getComment().get().getContent()); + } + } + } + } + + @Test + void cloneAnnotationOnWildcardTypeArgument() { + Type type = parseType("List<@C ? extends Object>").clone(); + assertEquals("List<@C ? extends Object>", type.toString()); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/GenericListVisitorAdapterTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/GenericListVisitorAdapterTest.java new file mode 100644 index 0000000..6250f3e --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/GenericListVisitorAdapterTest.java @@ -0,0 +1,2553 @@ +/* + * Copyright (C) 2013-2024 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.visitor; + +import com.github.javaparser.ast.*; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.comments.BlockComment; +import com.github.javaparser.ast.comments.Comment; +import com.github.javaparser.ast.comments.JavadocComment; +import com.github.javaparser.ast.comments.LineComment; +import com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.modules.*; +import com.github.javaparser.ast.stmt.*; +import com.github.javaparser.ast.type.*; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; + +class GenericListVisitorAdapterTest { + + private final GenericListVisitorAdapter visitor = new GenericListVisitorAdapter() {}; + + @Test + void visit_GivenAnnotationDeclaration() { + // Given + Object argument = mock(Object.class); + AnnotationDeclaration node = mock(AnnotationDeclaration.class); + + // When + Mockito.when(node.getMembers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getModifiers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getMembers(); + order.verify(node).getModifiers(); + order.verify(node).getName(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenAnnotationMemberDeclaration() { + // Given + Object argument = mock(Object.class); + AnnotationMemberDeclaration node = mock(AnnotationMemberDeclaration.class); + + // When + Mockito.when(node.getDefaultValue()).thenReturn(Optional.of(mock(Expression.class))); + Mockito.when(node.getModifiers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getType()).thenReturn(mock(Type.class)); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getDefaultValue(); + order.verify(node).getModifiers(); + order.verify(node).getName(); + order.verify(node).getType(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenArrayAccessExpr() { + // Given + Object argument = mock(Object.class); + ArrayAccessExpr node = mock(ArrayAccessExpr.class); + + // When + Mockito.when(node.getIndex()).thenReturn(mock(Expression.class)); + Mockito.when(node.getName()).thenReturn(mock(Expression.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getIndex(); + order.verify(node).getName(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenArrayCreationExpr() { + // Given + Object argument = mock(Object.class); + ArrayCreationExpr node = mock(ArrayCreationExpr.class); + + // When + Mockito.when(node.getElementType()).thenReturn(mock(Type.class)); + Mockito.when(node.getInitializer()).thenReturn(Optional.of(mock(ArrayInitializerExpr.class))); + Mockito.when(node.getLevels()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getElementType(); + order.verify(node, times(2)).getInitializer(); + order.verify(node).getLevels(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenArrayCreationLevel() { + // Given + Object argument = mock(Object.class); + ArrayCreationLevel node = mock(ArrayCreationLevel.class); + + // When + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getDimension()).thenReturn(Optional.of(mock(ArrayInitializerExpr.class))); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getDimension(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenArrayInitializerExpr() { + // Given + Object argument = mock(Object.class); + ArrayInitializerExpr node = mock(ArrayInitializerExpr.class); + + // When + Mockito.when(node.getValues()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getValues(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenArrayType() { + // Given + Object argument = mock(Object.class); + ArrayType node = mock(ArrayType.class); + + // When + Mockito.when(node.getComponentType()).thenReturn(mock(Type.class)); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getComponentType(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenAssertStmt() { + // Given + Object argument = mock(Object.class); + AssertStmt node = mock(AssertStmt.class); + + // When + Mockito.when(node.getCheck()).thenReturn(mock(Expression.class)); + Mockito.when(node.getMessage()).thenReturn(Optional.of(mock(Expression.class))); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getCheck(); + order.verify(node, times(2)).getMessage(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenAssignExpr() { + // Given + Object argument = mock(Object.class); + AssignExpr node = mock(AssignExpr.class); + + // When + Mockito.when(node.getTarget()).thenReturn(mock(Expression.class)); + Mockito.when(node.getValue()).thenReturn(mock(Expression.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getTarget(); + order.verify(node).getValue(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenBinaryExpr() { + // Given + Object argument = mock(Object.class); + BinaryExpr node = mock(BinaryExpr.class); + + // When + Mockito.when(node.getLeft()).thenReturn(mock(Expression.class)); + Mockito.when(node.getRight()).thenReturn(mock(Expression.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getLeft(); + order.verify(node).getRight(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenBlockComment() { + // Given + Object argument = mock(Object.class); + BlockComment node = mock(BlockComment.class); + + // When + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenBlockStmt() { + // Given + Object argument = mock(Object.class); + BlockStmt node = mock(BlockStmt.class); + + // When + Mockito.when(node.getStatements()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getStatements(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenBooleanLiteralExpr() { + // Given + Object argument = mock(Object.class); + BooleanLiteralExpr node = mock(BooleanLiteralExpr.class); + + // When + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenBreakStmt() { + // Given + Object argument = mock(Object.class); + BreakStmt node = mock(BreakStmt.class); + + // When + Mockito.when(node.getLabel()).thenReturn(Optional.of(mock(SimpleName.class))); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getLabel(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenCastExpr() { + // Given + Object argument = mock(Object.class); + CastExpr node = mock(CastExpr.class); + + // When + Mockito.when(node.getExpression()).thenReturn(mock(Expression.class)); + Mockito.when(node.getType()).thenReturn(mock(Type.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getExpression(); + order.verify(node).getType(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenCatchClause() { + // Given + Object argument = mock(Object.class); + CatchClause node = mock(CatchClause.class); + + // When + Mockito.when(node.getBody()).thenReturn(mock(BlockStmt.class)); + Mockito.when(node.getParameter()).thenReturn(mock(Parameter.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getBody(); + order.verify(node).getParameter(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenCharLiteralExpr() { + // Given + Object argument = mock(Object.class); + CharLiteralExpr node = mock(CharLiteralExpr.class); + + // When + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenClassExpr() { + // Given + Object argument = mock(Object.class); + ClassExpr node = mock(ClassExpr.class); + + // When + Mockito.when(node.getType()).thenReturn(mock(Type.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getType(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenClassOrInterfaceDeclaration() { + // Given + Object argument = mock(Object.class); + ClassOrInterfaceDeclaration node = mock(ClassOrInterfaceDeclaration.class); + + // When + Mockito.when(node.getExtendedTypes()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getImplementedTypes()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getPermittedTypes()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getTypeParameters()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getMembers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getModifiers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getExtendedTypes(); + order.verify(node).getImplementedTypes(); + order.verify(node).getPermittedTypes(); + order.verify(node).getTypeParameters(); + order.verify(node).getMembers(); + order.verify(node).getModifiers(); + order.verify(node).getName(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenClassOrInterfaceType() { + // Given + Object argument = mock(Object.class); + ClassOrInterfaceType node = mock(ClassOrInterfaceType.class); + + // When + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getScope()).thenReturn(Optional.of(mock(ClassOrInterfaceType.class))); + Mockito.when(node.getTypeArguments()).thenReturn(Optional.of(mock(NodeList.class))); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getName(); + order.verify(node, times(2)).getScope(); + order.verify(node, times(2)).getTypeArguments(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenCompilationUnit() { + // Given + Object argument = mock(Object.class); + CompilationUnit node = mock(CompilationUnit.class); + + // When + Mockito.when(node.getImports()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getModule()).thenReturn(Optional.of(mock(ModuleDeclaration.class))); + Mockito.when(node.getPackageDeclaration()).thenReturn(Optional.of(mock(PackageDeclaration.class))); + Mockito.when(node.getTypes()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getImports(); + order.verify(node, times(2)).getModule(); + order.verify(node, times(2)).getPackageDeclaration(); + order.verify(node).getTypes(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenConditionalExpr() { + // Given + Object argument = mock(Object.class); + ConditionalExpr node = mock(ConditionalExpr.class); + + // When + Mockito.when(node.getCondition()).thenReturn(mock(Expression.class)); + Mockito.when(node.getElseExpr()).thenReturn(mock(Expression.class)); + Mockito.when(node.getThenExpr()).thenReturn(mock(Expression.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getCondition(); + order.verify(node).getElseExpr(); + order.verify(node).getThenExpr(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenConstructorDeclaration() { + // Given + Object argument = mock(Object.class); + ConstructorDeclaration node = mock(ConstructorDeclaration.class); + + // When + Mockito.when(node.getBody()).thenReturn(mock(BlockStmt.class)); + Mockito.when(node.getModifiers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getParameters()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getReceiverParameter()).thenReturn(Optional.of(mock(ReceiverParameter.class))); + Mockito.when(node.getThrownExceptions()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getTypeParameters()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getBody(); + order.verify(node).getModifiers(); + order.verify(node).getName(); + order.verify(node).getParameters(); + order.verify(node, times(2)).getReceiverParameter(); + order.verify(node).getThrownExceptions(); + order.verify(node).getTypeParameters(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenContinueStmt() { + // Given + Object argument = mock(Object.class); + ContinueStmt node = mock(ContinueStmt.class); + + // When + Mockito.when(node.getLabel()).thenReturn(Optional.of(mock(SimpleName.class))); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getLabel(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenDoStmt() { + // Given + Object argument = mock(Object.class); + DoStmt node = mock(DoStmt.class); + + // When + Mockito.when(node.getBody()).thenReturn(mock(Statement.class)); + Mockito.when(node.getCondition()).thenReturn(mock(Expression.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getBody(); + order.verify(node).getCondition(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenDoubleLiteralExpr() { + // Given + Object argument = mock(Object.class); + DoubleLiteralExpr node = mock(DoubleLiteralExpr.class); + + // When + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenEmptyStmt() { + // Given + Object argument = mock(Object.class); + EmptyStmt node = mock(EmptyStmt.class); + + // When + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenEnclosedExpr() { + // Given + Object argument = mock(Object.class); + EnclosedExpr node = mock(EnclosedExpr.class); + + // When + Mockito.when(node.getInner()).thenReturn(mock(Expression.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getInner(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenEnumConstantDeclaration() { + // Given + Object argument = mock(Object.class); + EnumConstantDeclaration node = mock(EnumConstantDeclaration.class); + + // When + Mockito.when(node.getArguments()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getClassBody()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getArguments(); + order.verify(node).getClassBody(); + order.verify(node).getName(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenEnumDeclaration() { + // Given + Object argument = mock(Object.class); + EnumDeclaration node = mock(EnumDeclaration.class); + + // When + Mockito.when(node.getEntries()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getImplementedTypes()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getMembers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getModifiers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getEntries(); + order.verify(node).getImplementedTypes(); + order.verify(node).getMembers(); + order.verify(node).getModifiers(); + order.verify(node).getName(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenExplicitConstructorInvocationStmt() { + // Given + Object argument = mock(Object.class); + ExplicitConstructorInvocationStmt node = mock(ExplicitConstructorInvocationStmt.class); + + // When + Mockito.when(node.getArguments()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getExpression()).thenReturn(Optional.of(mock(Expression.class))); + Mockito.when(node.getTypeArguments()).thenReturn(Optional.of(mock(NodeList.class))); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getArguments(); + order.verify(node, times(2)).getExpression(); + order.verify(node, times(2)).getTypeArguments(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenExpressionStmt() { + // Given + Object argument = mock(Object.class); + ExpressionStmt node = mock(ExpressionStmt.class); + + // When + Mockito.when(node.getExpression()).thenReturn(mock(Expression.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getExpression(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenFieldAccessExpr() { + // Given + Object argument = mock(Object.class); + FieldAccessExpr node = mock(FieldAccessExpr.class); + + // When + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getScope()).thenReturn(mock(Expression.class)); + Mockito.when(node.getTypeArguments()).thenReturn(Optional.of(mock(NodeList.class))); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getName(); + order.verify(node).getScope(); + order.verify(node, times(2)).getTypeArguments(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenFieldDeclaration() { + // Given + Object argument = mock(Object.class); + FieldDeclaration node = mock(FieldDeclaration.class); + + // When + Mockito.when(node.getModifiers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getVariables()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getModifiers(); + order.verify(node).getVariables(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenForStmt() { + // Given + Object argument = mock(Object.class); + ForStmt node = mock(ForStmt.class); + + // When + Mockito.when(node.getBody()).thenReturn(mock(Statement.class)); + Mockito.when(node.getCompare()).thenReturn(Optional.of(mock(Expression.class))); + Mockito.when(node.getInitialization()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getUpdate()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getBody(); + order.verify(node, times(2)).getCompare(); + order.verify(node).getInitialization(); + order.verify(node).getUpdate(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenForEachStmt() { + // Given + Object argument = mock(Object.class); + ForEachStmt node = mock(ForEachStmt.class); + + // When + Mockito.when(node.getBody()).thenReturn(mock(Statement.class)); + Mockito.when(node.getIterable()).thenReturn(mock(Expression.class)); + Mockito.when(node.getVariable()).thenReturn(mock(VariableDeclarationExpr.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getBody(); + order.verify(node).getIterable(); + order.verify(node).getVariable(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenIfStmt() { + // Given + Object argument = mock(Object.class); + IfStmt node = mock(IfStmt.class); + + // When + Mockito.when(node.getCondition()).thenReturn(mock(ConditionalExpr.class)); + Mockito.when(node.getElseStmt()).thenReturn(Optional.of(mock(Statement.class))); + Mockito.when(node.getThenStmt()).thenReturn(mock(Statement.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getCondition(); + order.verify(node, times(2)).getElseStmt(); + order.verify(node).getThenStmt(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenImportDeclaration() { + // Given + Object argument = mock(Object.class); + ImportDeclaration node = mock(ImportDeclaration.class); + + // When + Mockito.when(node.getName()).thenReturn(mock(Name.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getName(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenInitializerDeclaration() { + // Given + Object argument = mock(Object.class); + InitializerDeclaration node = mock(InitializerDeclaration.class); + + // When + Mockito.when(node.getBody()).thenReturn(mock(BlockStmt.class)); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getBody(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenInstanceOfExpr() { + // Given + Object argument = mock(Object.class); + InstanceOfExpr node = mock(InstanceOfExpr.class); + + // When + Mockito.when(node.getExpression()).thenReturn(mock(Expression.class)); + Mockito.when(node.getPattern()).thenReturn(Optional.of(mock(PatternExpr.class))); + Mockito.when(node.getType()).thenReturn(mock(ReferenceType.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getExpression(); + order.verify(node, times(2)).getPattern(); + order.verify(node).getType(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenIntegerLiteralExpr() { + // Given + Object argument = mock(Object.class); + IntegerLiteralExpr node = mock(IntegerLiteralExpr.class); + + // When + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenIntersectionType() { + // Given + Object argument = mock(Object.class); + IntersectionType node = mock(IntersectionType.class); + + // When + Mockito.when(node.getElements()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getElements(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenJavadocComment() { + // Given + Object argument = mock(Object.class); + JavadocComment node = mock(JavadocComment.class); + + // When + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenLabeledStmt() { + // Given + Object argument = mock(Object.class); + LabeledStmt node = mock(LabeledStmt.class); + + // When + Mockito.when(node.getLabel()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getStatement()).thenReturn(mock(Statement.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getLabel(); + order.verify(node).getStatement(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenLambdaExpr() { + // Given + Object argument = mock(Object.class); + LambdaExpr node = mock(LambdaExpr.class); + + // When + Mockito.when(node.getBody()).thenReturn(mock(Statement.class)); + Mockito.when(node.getParameters()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getBody(); + order.verify(node).getParameters(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenLineComment() { + // Given + Object argument = mock(Object.class); + LineComment node = mock(LineComment.class); + + // When + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenLocalClassDeclarationStmt() { + // Given + Object argument = mock(Object.class); + LocalClassDeclarationStmt node = mock(LocalClassDeclarationStmt.class); + + // When + Mockito.when(node.getClassDeclaration()).thenReturn(mock(ClassOrInterfaceDeclaration.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getClassDeclaration(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenLocalRecordDeclarationStmt() { + // Given + Object argument = mock(Object.class); + LocalRecordDeclarationStmt node = mock(LocalRecordDeclarationStmt.class); + + // When + Mockito.when(node.getRecordDeclaration()).thenReturn(mock(RecordDeclaration.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getRecordDeclaration(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenLongLiteralExpr() { + // Given + Object argument = mock(Object.class); + LongLiteralExpr node = mock(LongLiteralExpr.class); + + // When + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenMarkerAnnotationExpr() { + // Given + Object argument = mock(Object.class); + MarkerAnnotationExpr node = mock(MarkerAnnotationExpr.class); + + // When + Mockito.when(node.getName()).thenReturn(mock(Name.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getName(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenMemberValuePair() { + // Given + Object argument = mock(Object.class); + MemberValuePair node = mock(MemberValuePair.class); + + // When + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getValue()).thenReturn(mock(Expression.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getName(); + order.verify(node).getValue(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenMethodCallExpr() { + // Given + Object argument = mock(Object.class); + MethodCallExpr node = mock(MethodCallExpr.class); + + // When + Mockito.when(node.getArguments()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getScope()).thenReturn(Optional.of(mock(Expression.class))); + Mockito.when(node.getTypeArguments()).thenReturn(Optional.of(mock(NodeList.class))); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getArguments(); + order.verify(node).getName(); + order.verify(node, times(2)).getScope(); + order.verify(node, times(2)).getTypeArguments(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenMethodDeclaration() { + // Given + Object argument = mock(Object.class); + MethodDeclaration node = mock(MethodDeclaration.class); + + // When + Mockito.when(node.getBody()).thenReturn(Optional.of(mock(BlockStmt.class))); + Mockito.when(node.getType()).thenReturn(mock(Type.class)); + Mockito.when(node.getModifiers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getParameters()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getThrownExceptions()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getTypeParameters()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getBody(); + order.verify(node).getType(); + order.verify(node).getModifiers(); + order.verify(node).getName(); + order.verify(node).getParameters(); + order.verify(node).getThrownExceptions(); + order.verify(node).getTypeParameters(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenMethodReferenceExpr() { + // Given + Object argument = mock(Object.class); + MethodReferenceExpr node = mock(MethodReferenceExpr.class); + + // When + Mockito.when(node.getScope()).thenReturn(mock(Expression.class)); + Mockito.when(node.getTypeArguments()).thenReturn(Optional.of(mock(NodeList.class))); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getScope(); + order.verify(node, times(2)).getTypeArguments(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenNameExpr() { + // Given + Object argument = mock(Object.class); + NameExpr node = mock(NameExpr.class); + + // When + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getName(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenName() { + // Given + Object argument = mock(Object.class); + Name node = mock(Name.class); + + // When + Mockito.when(node.getQualifier()).thenReturn(Optional.of(mock(Name.class))); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getQualifier(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenNormalAnnotationExpr() { + // Given + Object argument = mock(Object.class); + NormalAnnotationExpr node = mock(NormalAnnotationExpr.class); + + // When + Mockito.when(node.getPairs()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(Name.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getPairs(); + order.verify(node).getName(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenNullLiteralExpr() { + // Given + Object argument = mock(Object.class); + NullLiteralExpr node = mock(NullLiteralExpr.class); + + // When + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenObjectCreationExpr() { + // Given + Object argument = mock(Object.class); + ObjectCreationExpr node = mock(ObjectCreationExpr.class); + + // When + Mockito.when(node.getAnonymousClassBody()).thenReturn(Optional.of(mock(NodeList.class))); + Mockito.when(node.getArguments()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getScope()).thenReturn(Optional.of(mock(Expression.class))); + Mockito.when(node.getType()).thenReturn(mock(ClassOrInterfaceType.class)); + Mockito.when(node.getTypeArguments()).thenReturn(Optional.of(mock(NodeList.class))); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getAnonymousClassBody(); + order.verify(node).getArguments(); + order.verify(node, times(2)).getScope(); + order.verify(node).getType(); + order.verify(node, times(2)).getTypeArguments(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenPackageDeclaration() { + // Given + Object argument = mock(Object.class); + PackageDeclaration node = mock(PackageDeclaration.class); + + // When + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(Name.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getAnnotations(); + order.verify(node).getName(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenParameter() { + // Given + Object argument = mock(Object.class); + Parameter node = mock(Parameter.class); + + // When + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getModifiers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getType()).thenReturn(mock(Type.class)); + Mockito.when(node.getVarArgsAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getAnnotations(); + order.verify(node).getModifiers(); + order.verify(node).getName(); + order.verify(node).getType(); + order.verify(node).getVarArgsAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenPrimitiveType() { + // Given + Object argument = mock(Object.class); + PrimitiveType node = mock(PrimitiveType.class); + + // When + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenReturnStmt() { + // Given + Object argument = mock(Object.class); + ReturnStmt node = mock(ReturnStmt.class); + + // When + Mockito.when(node.getExpression()).thenReturn(Optional.of(mock(Expression.class))); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getExpression(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenSimpleName() { + // Given + Object argument = mock(Object.class); + SimpleName node = mock(SimpleName.class); + + // When + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenSingleMemberAnnotationExpr() { + // Given + Object argument = mock(Object.class); + SingleMemberAnnotationExpr node = mock(SingleMemberAnnotationExpr.class); + + // When + Mockito.when(node.getMemberValue()).thenReturn(mock(Expression.class)); + Mockito.when(node.getName()).thenReturn(mock(Name.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getMemberValue(); + order.verify(node).getName(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenStringLiteralExpr() { + // Given + Object argument = mock(Object.class); + StringLiteralExpr node = mock(StringLiteralExpr.class); + + // When + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenSuperExpr() { + // Given + Object argument = mock(Object.class); + SuperExpr node = mock(SuperExpr.class); + + // When + Mockito.when(node.getTypeName()).thenReturn(Optional.of(mock(Name.class))); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getTypeName(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenSwitchEntry() { + // Given + Object argument = mock(Object.class); + SwitchEntry node = mock(SwitchEntry.class); + + // When + Mockito.when(node.getLabels()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getStatements()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getLabels(); + order.verify(node).getStatements(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenSwitchStmt() { + // Given + Object argument = mock(Object.class); + SwitchStmt node = mock(SwitchStmt.class); + + // When + Mockito.when(node.getEntries()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getSelector()).thenReturn(mock(Expression.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getEntries(); + order.verify(node).getSelector(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenSynchronizedStmt() { + // Given + Object argument = mock(Object.class); + SynchronizedStmt node = mock(SynchronizedStmt.class); + + // When + Mockito.when(node.getBody()).thenReturn(mock(BlockStmt.class)); + Mockito.when(node.getExpression()).thenReturn(mock(Expression.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getBody(); + order.verify(node).getExpression(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenThisExpr() { + // Given + Object argument = mock(Object.class); + ThisExpr node = mock(ThisExpr.class); + + // When + Mockito.when(node.getTypeName()).thenReturn(Optional.of(mock(Name.class))); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getTypeName(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenThrowStmt() { + // Given + Object argument = mock(Object.class); + ThrowStmt node = mock(ThrowStmt.class); + + // When + Mockito.when(node.getExpression()).thenReturn(mock(Expression.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getExpression(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenTryStmt() { + // Given + Object argument = mock(Object.class); + TryStmt node = mock(TryStmt.class); + + // When + Mockito.when(node.getCatchClauses()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getFinallyBlock()).thenReturn(Optional.of(mock(BlockStmt.class))); + Mockito.when(node.getResources()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getTryBlock()).thenReturn(mock(BlockStmt.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getCatchClauses(); + order.verify(node, times(2)).getFinallyBlock(); + order.verify(node).getResources(); + order.verify(node).getTryBlock(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenTypeExpr() { + // Given + Object argument = mock(Object.class); + TypeExpr node = mock(TypeExpr.class); + + // When + Mockito.when(node.getType()).thenReturn(mock(Type.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getType(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenTypeParameter() { + // Given + Object argument = mock(Object.class); + TypeParameter node = mock(TypeParameter.class); + + // When + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getTypeBound()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getName(); + order.verify(node).getTypeBound(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenUnaryExpr() { + // Given + Object argument = mock(Object.class); + UnaryExpr node = mock(UnaryExpr.class); + + // When + Mockito.when(node.getExpression()).thenReturn(mock(Expression.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getExpression(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenUnionType() { + // Given + Object argument = mock(Object.class); + UnionType node = mock(UnionType.class); + + // When + Mockito.when(node.getElements()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getElements(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenUnknownType() { + // Given + Object argument = mock(Object.class); + UnknownType node = mock(UnknownType.class); + + // When + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenVariableDeclarationExpr() { + // Given + Object argument = mock(Object.class); + VariableDeclarationExpr node = mock(VariableDeclarationExpr.class); + + // When + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getModifiers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getVariables()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getAnnotations(); + order.verify(node).getModifiers(); + order.verify(node).getVariables(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenVariableDeclarator() { + // Given + Object argument = mock(Object.class); + VariableDeclarator node = mock(VariableDeclarator.class); + + // When + Mockito.when(node.getInitializer()).thenReturn(Optional.of(mock(Expression.class))); + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getType()).thenReturn(mock(Type.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getInitializer(); + order.verify(node).getName(); + order.verify(node).getType(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenVoidType() { + // Given + Object argument = mock(Object.class); + VoidType node = mock(VoidType.class); + + // When + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenWhileStmt() { + // Given + Object argument = mock(Object.class); + WhileStmt node = mock(WhileStmt.class); + + // When + Mockito.when(node.getBody()).thenReturn(mock(Statement.class)); + Mockito.when(node.getCondition()).thenReturn(mock(Expression.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getBody(); + order.verify(node).getCondition(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenWildcardType() { + // Given + Object argument = mock(Object.class); + WildcardType node = mock(WildcardType.class); + + // When + Mockito.when(node.getExtendedType()).thenReturn(Optional.of(mock(ReferenceType.class))); + Mockito.when(node.getSuperType()).thenReturn(Optional.of(mock(ReferenceType.class))); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getExtendedType(); + order.verify(node, times(2)).getSuperType(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenModuleDeclaration() { + // Given + Object argument = mock(Object.class); + ModuleDeclaration node = mock(ModuleDeclaration.class); + + // When + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getDirectives()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(Name.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getAnnotations(); + order.verify(node).getDirectives(); + order.verify(node).getName(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenModuleExportsDirective() { + // Given + Object argument = mock(Object.class); + ModuleExportsDirective node = mock(ModuleExportsDirective.class); + + // When + Mockito.when(node.getModuleNames()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(Name.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getModuleNames(); + order.verify(node).getName(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenModuleOpensDirective() { + // Given + Object argument = mock(Object.class); + ModuleOpensDirective node = mock(ModuleOpensDirective.class); + + // When + Mockito.when(node.getModuleNames()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(Name.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getModuleNames(); + order.verify(node).getName(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenModuleProvidesDirective() { + // Given + Object argument = mock(Object.class); + ModuleProvidesDirective node = mock(ModuleProvidesDirective.class); + + // When + Mockito.when(node.getName()).thenReturn(mock(Name.class)); + Mockito.when(node.getWith()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getName(); + order.verify(node).getWith(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenModuleRequiresDirective() { + // Given + Object argument = mock(Object.class); + ModuleRequiresDirective node = mock(ModuleRequiresDirective.class); + + // When + Mockito.when(node.getModifiers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(Name.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getModifiers(); + order.verify(node).getName(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenModuleUsesDirective() { + // Given + Object argument = mock(Object.class); + ModuleUsesDirective node = mock(ModuleUsesDirective.class); + + // When + Mockito.when(node.getName()).thenReturn(mock(Name.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getName(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenUnparsableStmt() { + // Given + Object argument = mock(Object.class); + UnparsableStmt node = mock(UnparsableStmt.class); + + // When + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenReceiverParameter() { + // Given + Object argument = mock(Object.class); + ReceiverParameter node = mock(ReceiverParameter.class); + + // When + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(Name.class)); + Mockito.when(node.getType()).thenReturn(mock(Type.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getAnnotations(); + order.verify(node).getName(); + order.verify(node).getType(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenVarType() { + // Given + Object argument = mock(Object.class); + VarType node = mock(VarType.class); + + // When + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenModifier() { + // Given + Object argument = mock(Object.class); + Modifier node = mock(Modifier.class); + + // When + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenSwitchExpr() { + // Given + Object argument = mock(Object.class); + SwitchExpr node = mock(SwitchExpr.class); + + // When + Mockito.when(node.getEntries()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getSelector()).thenReturn(mock(Expression.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getEntries(); + order.verify(node).getSelector(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenYieldStmt() { + // Given + Object argument = mock(Object.class); + YieldStmt node = mock(YieldStmt.class); + + // When + Mockito.when(node.getExpression()).thenReturn(mock(Expression.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getExpression(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenTextBlockLiteralExpr() { + // Given + Object argument = mock(Object.class); + TextBlockLiteralExpr node = mock(TextBlockLiteralExpr.class); + + // When + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenPatternExpr() { + // Given + Object argument = mock(Object.class); + PatternExpr node = mock(PatternExpr.class); + + // When + Mockito.when(node.getModifiers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getType()).thenReturn(mock(ReferenceType.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getModifiers(); + order.verify(node).getName(); + order.verify(node).getType(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenRecordDeclaration() { + // Given + Object argument = mock(Object.class); + RecordDeclaration node = mock(RecordDeclaration.class); + + // When + Mockito.when(node.getImplementedTypes()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getParameters()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getReceiverParameter()).thenReturn(Optional.of(mock(ReceiverParameter.class))); + Mockito.when(node.getTypeParameters()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getMembers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getModifiers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getImplementedTypes(); + order.verify(node).getParameters(); + order.verify(node, times(2)).getReceiverParameter(); + order.verify(node).getTypeParameters(); + order.verify(node).getMembers(); + order.verify(node).getModifiers(); + order.verify(node).getName(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_CompactConstructorDeclaration () { + // Given + Object argument = mock(Object.class); + CompactConstructorDeclaration node = mock(CompactConstructorDeclaration .class); + + // When + Mockito.when(node.getBody()).thenReturn(mock(BlockStmt.class)); + Mockito.when(node.getModifiers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getThrownExceptions()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getTypeParameters()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + List result = visitor.visit(node, argument); + + // Assert + assertNotNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getBody(); + order.verify(node).getModifiers(); + order.verify(node).getName(); + order.verify(node).getThrownExceptions(); + order.verify(node).getTypeParameters(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + +} \ No newline at end of file diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/GenericVisitorAdapterTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/GenericVisitorAdapterTest.java new file mode 100644 index 0000000..a2fcff0 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/GenericVisitorAdapterTest.java @@ -0,0 +1,2552 @@ +/* + * Copyright (C) 2013-2024 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.visitor; + +import com.github.javaparser.ast.*; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.comments.BlockComment; +import com.github.javaparser.ast.comments.Comment; +import com.github.javaparser.ast.comments.JavadocComment; +import com.github.javaparser.ast.comments.LineComment; +import com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.modules.*; +import com.github.javaparser.ast.stmt.*; +import com.github.javaparser.ast.type.*; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; + +public class GenericVisitorAdapterTest { + + private final GenericVisitorAdapter visitor = new GenericVisitorAdapter() {}; + + @Test + void visit_GivenAnnotationDeclaration() { + // Given + Object argument = mock(Object.class); + AnnotationDeclaration node = mock(AnnotationDeclaration.class); + + // When + Mockito.when(node.getMembers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getModifiers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getMembers(); + order.verify(node).getModifiers(); + order.verify(node).getName(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenAnnotationMemberDeclaration() { + // Given + Object argument = mock(Object.class); + AnnotationMemberDeclaration node = mock(AnnotationMemberDeclaration.class); + + // When + Mockito.when(node.getDefaultValue()).thenReturn(Optional.of(mock(Expression.class))); + Mockito.when(node.getModifiers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getType()).thenReturn(mock(Type.class)); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getDefaultValue(); + order.verify(node).getModifiers(); + order.verify(node).getName(); + order.verify(node).getType(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenArrayAccessExpr() { + // Given + Object argument = mock(Object.class); + ArrayAccessExpr node = mock(ArrayAccessExpr.class); + + // When + Mockito.when(node.getIndex()).thenReturn(mock(Expression.class)); + Mockito.when(node.getName()).thenReturn(mock(Expression.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getIndex(); + order.verify(node).getName(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenArrayCreationExpr() { + // Given + Object argument = mock(Object.class); + ArrayCreationExpr node = mock(ArrayCreationExpr.class); + + // When + Mockito.when(node.getElementType()).thenReturn(mock(Type.class)); + Mockito.when(node.getInitializer()).thenReturn(Optional.of(mock(ArrayInitializerExpr.class))); + Mockito.when(node.getLevels()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getElementType(); + order.verify(node, times(2)).getInitializer(); + order.verify(node).getLevels(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenArrayCreationLevel() { + // Given + Object argument = mock(Object.class); + ArrayCreationLevel node = mock(ArrayCreationLevel.class); + + // When + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getDimension()).thenReturn(Optional.of(mock(ArrayInitializerExpr.class))); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getDimension(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenArrayInitializerExpr() { + // Given + Object argument = mock(Object.class); + ArrayInitializerExpr node = mock(ArrayInitializerExpr.class); + + // When + Mockito.when(node.getValues()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getValues(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenArrayType() { + // Given + Object argument = mock(Object.class); + ArrayType node = mock(ArrayType.class); + + // When + Mockito.when(node.getComponentType()).thenReturn(mock(Type.class)); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getComponentType(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenAssertStmt() { + // Given + Object argument = mock(Object.class); + AssertStmt node = mock(AssertStmt.class); + + // When + Mockito.when(node.getCheck()).thenReturn(mock(Expression.class)); + Mockito.when(node.getMessage()).thenReturn(Optional.of(mock(Expression.class))); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getCheck(); + order.verify(node, times(2)).getMessage(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenAssignExpr() { + // Given + Object argument = mock(Object.class); + AssignExpr node = mock(AssignExpr.class); + + // When + Mockito.when(node.getTarget()).thenReturn(mock(Expression.class)); + Mockito.when(node.getValue()).thenReturn(mock(Expression.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getTarget(); + order.verify(node).getValue(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenBinaryExpr() { + // Given + Object argument = mock(Object.class); + BinaryExpr node = mock(BinaryExpr.class); + + // When + Mockito.when(node.getLeft()).thenReturn(mock(Expression.class)); + Mockito.when(node.getRight()).thenReturn(mock(Expression.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getLeft(); + order.verify(node).getRight(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenBlockComment() { + // Given + Object argument = mock(Object.class); + BlockComment node = mock(BlockComment.class); + + // When + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenBlockStmt() { + // Given + Object argument = mock(Object.class); + BlockStmt node = mock(BlockStmt.class); + + // When + Mockito.when(node.getStatements()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getStatements(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenBooleanLiteralExpr() { + // Given + Object argument = mock(Object.class); + BooleanLiteralExpr node = mock(BooleanLiteralExpr.class); + + // When + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenBreakStmt() { + // Given + Object argument = mock(Object.class); + BreakStmt node = mock(BreakStmt.class); + + // When + Mockito.when(node.getLabel()).thenReturn(Optional.of(mock(SimpleName.class))); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getLabel(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenCastExpr() { + // Given + Object argument = mock(Object.class); + CastExpr node = mock(CastExpr.class); + + // When + Mockito.when(node.getExpression()).thenReturn(mock(Expression.class)); + Mockito.when(node.getType()).thenReturn(mock(Type.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getExpression(); + order.verify(node).getType(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenCatchClause() { + // Given + Object argument = mock(Object.class); + CatchClause node = mock(CatchClause.class); + + // When + Mockito.when(node.getBody()).thenReturn(mock(BlockStmt.class)); + Mockito.when(node.getParameter()).thenReturn(mock(Parameter.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getBody(); + order.verify(node).getParameter(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenCharLiteralExpr() { + // Given + Object argument = mock(Object.class); + CharLiteralExpr node = mock(CharLiteralExpr.class); + + // When + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenClassExpr() { + // Given + Object argument = mock(Object.class); + ClassExpr node = mock(ClassExpr.class); + + // When + Mockito.when(node.getType()).thenReturn(mock(Type.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getType(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenClassOrInterfaceDeclaration() { + // Given + Object argument = mock(Object.class); + ClassOrInterfaceDeclaration node = mock(ClassOrInterfaceDeclaration.class); + + // When + Mockito.when(node.getExtendedTypes()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getImplementedTypes()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getPermittedTypes()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getTypeParameters()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getMembers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getModifiers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getExtendedTypes(); + order.verify(node).getImplementedTypes(); + order.verify(node).getPermittedTypes(); + order.verify(node).getTypeParameters(); + order.verify(node).getMembers(); + order.verify(node).getModifiers(); + order.verify(node).getName(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenClassOrInterfaceType() { + // Given + Object argument = mock(Object.class); + ClassOrInterfaceType node = mock(ClassOrInterfaceType.class); + + // When + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getScope()).thenReturn(Optional.of(mock(ClassOrInterfaceType.class))); + Mockito.when(node.getTypeArguments()).thenReturn(Optional.of(mock(NodeList.class))); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getName(); + order.verify(node, times(2)).getScope(); + order.verify(node, times(2)).getTypeArguments(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenCompilationUnit() { + // Given + Object argument = mock(Object.class); + CompilationUnit node = mock(CompilationUnit.class); + + // When + Mockito.when(node.getImports()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getModule()).thenReturn(Optional.of(mock(ModuleDeclaration.class))); + Mockito.when(node.getPackageDeclaration()).thenReturn(Optional.of(mock(PackageDeclaration.class))); + Mockito.when(node.getTypes()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getImports(); + order.verify(node, times(2)).getModule(); + order.verify(node, times(2)).getPackageDeclaration(); + order.verify(node).getTypes(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenConditionalExpr() { + // Given + Object argument = mock(Object.class); + ConditionalExpr node = mock(ConditionalExpr.class); + + // When + Mockito.when(node.getCondition()).thenReturn(mock(Expression.class)); + Mockito.when(node.getElseExpr()).thenReturn(mock(Expression.class)); + Mockito.when(node.getThenExpr()).thenReturn(mock(Expression.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getCondition(); + order.verify(node).getElseExpr(); + order.verify(node).getThenExpr(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenConstructorDeclaration() { + // Given + Object argument = mock(Object.class); + ConstructorDeclaration node = mock(ConstructorDeclaration.class); + + // When + Mockito.when(node.getBody()).thenReturn(mock(BlockStmt.class)); + Mockito.when(node.getModifiers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getParameters()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getReceiverParameter()).thenReturn(Optional.of(mock(ReceiverParameter.class))); + Mockito.when(node.getThrownExceptions()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getTypeParameters()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getBody(); + order.verify(node).getModifiers(); + order.verify(node).getName(); + order.verify(node).getParameters(); + order.verify(node, times(2)).getReceiverParameter(); + order.verify(node).getThrownExceptions(); + order.verify(node).getTypeParameters(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenContinueStmt() { + // Given + Object argument = mock(Object.class); + ContinueStmt node = mock(ContinueStmt.class); + + // When + Mockito.when(node.getLabel()).thenReturn(Optional.of(mock(SimpleName.class))); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getLabel(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenDoStmt() { + // Given + Object argument = mock(Object.class); + DoStmt node = mock(DoStmt.class); + + // When + Mockito.when(node.getBody()).thenReturn(mock(Statement.class)); + Mockito.when(node.getCondition()).thenReturn(mock(Expression.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getBody(); + order.verify(node).getCondition(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenDoubleLiteralExpr() { + // Given + Object argument = mock(Object.class); + DoubleLiteralExpr node = mock(DoubleLiteralExpr.class); + + // When + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenEmptyStmt() { + // Given + Object argument = mock(Object.class); + EmptyStmt node = mock(EmptyStmt.class); + + // When + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenEnclosedExpr() { + // Given + Object argument = mock(Object.class); + EnclosedExpr node = mock(EnclosedExpr.class); + + // When + Mockito.when(node.getInner()).thenReturn(mock(Expression.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getInner(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenEnumConstantDeclaration() { + // Given + Object argument = mock(Object.class); + EnumConstantDeclaration node = mock(EnumConstantDeclaration.class); + + // When + Mockito.when(node.getArguments()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getClassBody()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getArguments(); + order.verify(node).getClassBody(); + order.verify(node).getName(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenEnumDeclaration() { + // Given + Object argument = mock(Object.class); + EnumDeclaration node = mock(EnumDeclaration.class); + + // When + Mockito.when(node.getEntries()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getImplementedTypes()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getMembers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getModifiers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getEntries(); + order.verify(node).getImplementedTypes(); + order.verify(node).getMembers(); + order.verify(node).getModifiers(); + order.verify(node).getName(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenExplicitConstructorInvocationStmt() { + // Given + Object argument = mock(Object.class); + ExplicitConstructorInvocationStmt node = mock(ExplicitConstructorInvocationStmt.class); + + // When + Mockito.when(node.getArguments()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getExpression()).thenReturn(Optional.of(mock(Expression.class))); + Mockito.when(node.getTypeArguments()).thenReturn(Optional.of(mock(NodeList.class))); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getArguments(); + order.verify(node, times(2)).getExpression(); + order.verify(node, times(2)).getTypeArguments(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenExpressionStmt() { + // Given + Object argument = mock(Object.class); + ExpressionStmt node = mock(ExpressionStmt.class); + + // When + Mockito.when(node.getExpression()).thenReturn(mock(Expression.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getExpression(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenFieldAccessExpr() { + // Given + Object argument = mock(Object.class); + FieldAccessExpr node = mock(FieldAccessExpr.class); + + // When + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getScope()).thenReturn(mock(Expression.class)); + Mockito.when(node.getTypeArguments()).thenReturn(Optional.of(mock(NodeList.class))); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getName(); + order.verify(node).getScope(); + order.verify(node, times(2)).getTypeArguments(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenFieldDeclaration() { + // Given + Object argument = mock(Object.class); + FieldDeclaration node = mock(FieldDeclaration.class); + + // When + Mockito.when(node.getModifiers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getVariables()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getModifiers(); + order.verify(node).getVariables(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenForStmt() { + // Given + Object argument = mock(Object.class); + ForStmt node = mock(ForStmt.class); + + // When + Mockito.when(node.getBody()).thenReturn(mock(Statement.class)); + Mockito.when(node.getCompare()).thenReturn(Optional.of(mock(Expression.class))); + Mockito.when(node.getInitialization()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getUpdate()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getBody(); + order.verify(node, times(2)).getCompare(); + order.verify(node).getInitialization(); + order.verify(node).getUpdate(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenForEachStmt() { + // Given + Object argument = mock(Object.class); + ForEachStmt node = mock(ForEachStmt.class); + + // When + Mockito.when(node.getBody()).thenReturn(mock(Statement.class)); + Mockito.when(node.getIterable()).thenReturn(mock(Expression.class)); + Mockito.when(node.getVariable()).thenReturn(mock(VariableDeclarationExpr.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getBody(); + order.verify(node).getIterable(); + order.verify(node).getVariable(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenIfStmt() { + // Given + Object argument = mock(Object.class); + IfStmt node = mock(IfStmt.class); + + // When + Mockito.when(node.getCondition()).thenReturn(mock(ConditionalExpr.class)); + Mockito.when(node.getElseStmt()).thenReturn(Optional.of(mock(Statement.class))); + Mockito.when(node.getThenStmt()).thenReturn(mock(Statement.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getCondition(); + order.verify(node, times(2)).getElseStmt(); + order.verify(node).getThenStmt(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenImportDeclaration() { + // Given + Object argument = mock(Object.class); + ImportDeclaration node = mock(ImportDeclaration.class); + + // When + Mockito.when(node.getName()).thenReturn(mock(Name.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getName(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenInitializerDeclaration() { + // Given + Object argument = mock(Object.class); + InitializerDeclaration node = mock(InitializerDeclaration.class); + + // When + Mockito.when(node.getBody()).thenReturn(mock(BlockStmt.class)); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getBody(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenInstanceOfExpr() { + // Given + Object argument = mock(Object.class); + InstanceOfExpr node = mock(InstanceOfExpr.class); + + // When + Mockito.when(node.getExpression()).thenReturn(mock(Expression.class)); + Mockito.when(node.getPattern()).thenReturn(Optional.of(mock(PatternExpr.class))); + Mockito.when(node.getType()).thenReturn(mock(ReferenceType.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getExpression(); + order.verify(node, times(2)).getPattern(); + order.verify(node).getType(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenIntegerLiteralExpr() { + // Given + Object argument = mock(Object.class); + IntegerLiteralExpr node = mock(IntegerLiteralExpr.class); + + // When + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenIntersectionType() { + // Given + Object argument = mock(Object.class); + IntersectionType node = mock(IntersectionType.class); + + // When + Mockito.when(node.getElements()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getElements(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenJavadocComment() { + // Given + Object argument = mock(Object.class); + JavadocComment node = mock(JavadocComment.class); + + // When + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenLabeledStmt() { + // Given + Object argument = mock(Object.class); + LabeledStmt node = mock(LabeledStmt.class); + + // When + Mockito.when(node.getLabel()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getStatement()).thenReturn(mock(Statement.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getLabel(); + order.verify(node).getStatement(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenLambdaExpr() { + // Given + Object argument = mock(Object.class); + LambdaExpr node = mock(LambdaExpr.class); + + // When + Mockito.when(node.getBody()).thenReturn(mock(Statement.class)); + Mockito.when(node.getParameters()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getBody(); + order.verify(node).getParameters(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenLineComment() { + // Given + Object argument = mock(Object.class); + LineComment node = mock(LineComment.class); + + // When + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenLocalClassDeclarationStmt() { + // Given + Object argument = mock(Object.class); + LocalClassDeclarationStmt node = mock(LocalClassDeclarationStmt.class); + + // When + Mockito.when(node.getClassDeclaration()).thenReturn(mock(ClassOrInterfaceDeclaration.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getClassDeclaration(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenLocalRecordDeclarationStmt() { + // Given + Object argument = mock(Object.class); + LocalRecordDeclarationStmt node = mock(LocalRecordDeclarationStmt.class); + + // When + Mockito.when(node.getRecordDeclaration()).thenReturn(mock(RecordDeclaration.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getRecordDeclaration(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenLongLiteralExpr() { + // Given + Object argument = mock(Object.class); + LongLiteralExpr node = mock(LongLiteralExpr.class); + + // When + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenMarkerAnnotationExpr() { + // Given + Object argument = mock(Object.class); + MarkerAnnotationExpr node = mock(MarkerAnnotationExpr.class); + + // When + Mockito.when(node.getName()).thenReturn(mock(Name.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getName(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenMemberValuePair() { + // Given + Object argument = mock(Object.class); + MemberValuePair node = mock(MemberValuePair.class); + + // When + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getValue()).thenReturn(mock(Expression.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getName(); + order.verify(node).getValue(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenMethodCallExpr() { + // Given + Object argument = mock(Object.class); + MethodCallExpr node = mock(MethodCallExpr.class); + + // When + Mockito.when(node.getArguments()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getScope()).thenReturn(Optional.of(mock(Expression.class))); + Mockito.when(node.getTypeArguments()).thenReturn(Optional.of(mock(NodeList.class))); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getArguments(); + order.verify(node).getName(); + order.verify(node, times(2)).getScope(); + order.verify(node, times(2)).getTypeArguments(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenMethodDeclaration() { + // Given + Object argument = mock(Object.class); + MethodDeclaration node = mock(MethodDeclaration.class); + + // When + Mockito.when(node.getBody()).thenReturn(Optional.of(mock(BlockStmt.class))); + Mockito.when(node.getType()).thenReturn(mock(Type.class)); + Mockito.when(node.getModifiers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getParameters()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getThrownExceptions()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getTypeParameters()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getBody(); + order.verify(node).getType(); + order.verify(node).getModifiers(); + order.verify(node).getName(); + order.verify(node).getParameters(); + order.verify(node).getThrownExceptions(); + order.verify(node).getTypeParameters(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenMethodReferenceExpr() { + // Given + Object argument = mock(Object.class); + MethodReferenceExpr node = mock(MethodReferenceExpr.class); + + // When + Mockito.when(node.getScope()).thenReturn(mock(Expression.class)); + Mockito.when(node.getTypeArguments()).thenReturn(Optional.of(mock(NodeList.class))); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getScope(); + order.verify(node, times(2)).getTypeArguments(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenNameExpr() { + // Given + Object argument = mock(Object.class); + NameExpr node = mock(NameExpr.class); + + // When + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getName(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenName() { + // Given + Object argument = mock(Object.class); + Name node = mock(Name.class); + + // When + Mockito.when(node.getQualifier()).thenReturn(Optional.of(mock(Name.class))); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getQualifier(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenNormalAnnotationExpr() { + // Given + Object argument = mock(Object.class); + NormalAnnotationExpr node = mock(NormalAnnotationExpr.class); + + // When + Mockito.when(node.getPairs()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(Name.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getPairs(); + order.verify(node).getName(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenNullLiteralExpr() { + // Given + Object argument = mock(Object.class); + NullLiteralExpr node = mock(NullLiteralExpr.class); + + // When + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenObjectCreationExpr() { + // Given + Object argument = mock(Object.class); + ObjectCreationExpr node = mock(ObjectCreationExpr.class); + + // When + Mockito.when(node.getAnonymousClassBody()).thenReturn(Optional.of(mock(NodeList.class))); + Mockito.when(node.getArguments()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getScope()).thenReturn(Optional.of(mock(Expression.class))); + Mockito.when(node.getType()).thenReturn(mock(ClassOrInterfaceType.class)); + Mockito.when(node.getTypeArguments()).thenReturn(Optional.of(mock(NodeList.class))); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getAnonymousClassBody(); + order.verify(node).getArguments(); + order.verify(node, times(2)).getScope(); + order.verify(node).getType(); + order.verify(node, times(2)).getTypeArguments(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenPackageDeclaration() { + // Given + Object argument = mock(Object.class); + PackageDeclaration node = mock(PackageDeclaration.class); + + // When + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(Name.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getAnnotations(); + order.verify(node).getName(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenParameter() { + // Given + Object argument = mock(Object.class); + Parameter node = mock(Parameter.class); + + // When + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getModifiers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getType()).thenReturn(mock(Type.class)); + Mockito.when(node.getVarArgsAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getAnnotations(); + order.verify(node).getModifiers(); + order.verify(node).getName(); + order.verify(node).getType(); + order.verify(node).getVarArgsAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenPrimitiveType() { + // Given + Object argument = mock(Object.class); + PrimitiveType node = mock(PrimitiveType.class); + + // When + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenReturnStmt() { + // Given + Object argument = mock(Object.class); + ReturnStmt node = mock(ReturnStmt.class); + + // When + Mockito.when(node.getExpression()).thenReturn(Optional.of(mock(Expression.class))); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getExpression(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenSimpleName() { + // Given + Object argument = mock(Object.class); + SimpleName node = mock(SimpleName.class); + + // When + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenSingleMemberAnnotationExpr() { + // Given + Object argument = mock(Object.class); + SingleMemberAnnotationExpr node = mock(SingleMemberAnnotationExpr.class); + + // When + Mockito.when(node.getMemberValue()).thenReturn(mock(Expression.class)); + Mockito.when(node.getName()).thenReturn(mock(Name.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getMemberValue(); + order.verify(node).getName(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenStringLiteralExpr() { + // Given + Object argument = mock(Object.class); + StringLiteralExpr node = mock(StringLiteralExpr.class); + + // When + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenSuperExpr() { + // Given + Object argument = mock(Object.class); + SuperExpr node = mock(SuperExpr.class); + + // When + Mockito.when(node.getTypeName()).thenReturn(Optional.of(mock(Name.class))); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getTypeName(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenSwitchEntry() { + // Given + Object argument = mock(Object.class); + SwitchEntry node = mock(SwitchEntry.class); + + // When + Mockito.when(node.getLabels()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getStatements()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getLabels(); + order.verify(node).getStatements(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenSwitchStmt() { + // Given + Object argument = mock(Object.class); + SwitchStmt node = mock(SwitchStmt.class); + + // When + Mockito.when(node.getEntries()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getSelector()).thenReturn(mock(Expression.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getEntries(); + order.verify(node).getSelector(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenSynchronizedStmt() { + // Given + Object argument = mock(Object.class); + SynchronizedStmt node = mock(SynchronizedStmt.class); + + // When + Mockito.when(node.getBody()).thenReturn(mock(BlockStmt.class)); + Mockito.when(node.getExpression()).thenReturn(mock(Expression.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getBody(); + order.verify(node).getExpression(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenThisExpr() { + // Given + Object argument = mock(Object.class); + ThisExpr node = mock(ThisExpr.class); + + // When + Mockito.when(node.getTypeName()).thenReturn(Optional.of(mock(Name.class))); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getTypeName(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenThrowStmt() { + // Given + Object argument = mock(Object.class); + ThrowStmt node = mock(ThrowStmt.class); + + // When + Mockito.when(node.getExpression()).thenReturn(mock(Expression.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getExpression(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenTryStmt() { + // Given + Object argument = mock(Object.class); + TryStmt node = mock(TryStmt.class); + + // When + Mockito.when(node.getCatchClauses()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getFinallyBlock()).thenReturn(Optional.of(mock(BlockStmt.class))); + Mockito.when(node.getResources()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getTryBlock()).thenReturn(mock(BlockStmt.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getCatchClauses(); + order.verify(node, times(2)).getFinallyBlock(); + order.verify(node).getResources(); + order.verify(node).getTryBlock(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenTypeExpr() { + // Given + Object argument = mock(Object.class); + TypeExpr node = mock(TypeExpr.class); + + // When + Mockito.when(node.getType()).thenReturn(mock(Type.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getType(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenTypeParameter() { + // Given + Object argument = mock(Object.class); + TypeParameter node = mock(TypeParameter.class); + + // When + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getTypeBound()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getName(); + order.verify(node).getTypeBound(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenUnaryExpr() { + // Given + Object argument = mock(Object.class); + UnaryExpr node = mock(UnaryExpr.class); + + // When + Mockito.when(node.getExpression()).thenReturn(mock(Expression.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getExpression(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenUnionType() { + // Given + Object argument = mock(Object.class); + UnionType node = mock(UnionType.class); + + // When + Mockito.when(node.getElements()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getElements(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenUnknownType() { + // Given + Object argument = mock(Object.class); + UnknownType node = mock(UnknownType.class); + + // When + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenVariableDeclarationExpr() { + // Given + Object argument = mock(Object.class); + VariableDeclarationExpr node = mock(VariableDeclarationExpr.class); + + // When + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getModifiers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getVariables()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getAnnotations(); + order.verify(node).getModifiers(); + order.verify(node).getVariables(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenVariableDeclarator() { + // Given + Object argument = mock(Object.class); + VariableDeclarator node = mock(VariableDeclarator.class); + + // When + Mockito.when(node.getInitializer()).thenReturn(Optional.of(mock(Expression.class))); + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getType()).thenReturn(mock(Type.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getInitializer(); + order.verify(node).getName(); + order.verify(node).getType(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenVoidType() { + // Given + Object argument = mock(Object.class); + VoidType node = mock(VoidType.class); + + // When + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenWhileStmt() { + // Given + Object argument = mock(Object.class); + WhileStmt node = mock(WhileStmt.class); + + // When + Mockito.when(node.getBody()).thenReturn(mock(Statement.class)); + Mockito.when(node.getCondition()).thenReturn(mock(Expression.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getBody(); + order.verify(node).getCondition(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenWildcardType() { + // Given + Object argument = mock(Object.class); + WildcardType node = mock(WildcardType.class); + + // When + Mockito.when(node.getExtendedType()).thenReturn(Optional.of(mock(ReferenceType.class))); + Mockito.when(node.getSuperType()).thenReturn(Optional.of(mock(ReferenceType.class))); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getExtendedType(); + order.verify(node, times(2)).getSuperType(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenModuleDeclaration() { + // Given + Object argument = mock(Object.class); + ModuleDeclaration node = mock(ModuleDeclaration.class); + + // When + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getDirectives()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(Name.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getAnnotations(); + order.verify(node).getDirectives(); + order.verify(node).getName(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenModuleExportsDirective() { + // Given + Object argument = mock(Object.class); + ModuleExportsDirective node = mock(ModuleExportsDirective.class); + + // When + Mockito.when(node.getModuleNames()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(Name.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getModuleNames(); + order.verify(node).getName(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenModuleOpensDirective() { + // Given + Object argument = mock(Object.class); + ModuleOpensDirective node = mock(ModuleOpensDirective.class); + + // When + Mockito.when(node.getModuleNames()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(Name.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getModuleNames(); + order.verify(node).getName(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenModuleProvidesDirective() { + // Given + Object argument = mock(Object.class); + ModuleProvidesDirective node = mock(ModuleProvidesDirective.class); + + // When + Mockito.when(node.getName()).thenReturn(mock(Name.class)); + Mockito.when(node.getWith()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getName(); + order.verify(node).getWith(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenModuleRequiresDirective() { + // Given + Object argument = mock(Object.class); + ModuleRequiresDirective node = mock(ModuleRequiresDirective.class); + + // When + Mockito.when(node.getModifiers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(Name.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getModifiers(); + order.verify(node).getName(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenModuleUsesDirective() { + // Given + Object argument = mock(Object.class); + ModuleUsesDirective node = mock(ModuleUsesDirective.class); + + // When + Mockito.when(node.getName()).thenReturn(mock(Name.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getName(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenUnparsableStmt() { + // Given + Object argument = mock(Object.class); + UnparsableStmt node = mock(UnparsableStmt.class); + + // When + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenReceiverParameter() { + // Given + Object argument = mock(Object.class); + ReceiverParameter node = mock(ReceiverParameter.class); + + // When + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(Name.class)); + Mockito.when(node.getType()).thenReturn(mock(Type.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getAnnotations(); + order.verify(node).getName(); + order.verify(node).getType(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenVarType() { + // Given + Object argument = mock(Object.class); + VarType node = mock(VarType.class); + + // When + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenModifier() { + // Given + Object argument = mock(Object.class); + Modifier node = mock(Modifier.class); + + // When + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenSwitchExpr() { + // Given + Object argument = mock(Object.class); + SwitchExpr node = mock(SwitchExpr.class); + + // When + Mockito.when(node.getEntries()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getSelector()).thenReturn(mock(Expression.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getEntries(); + order.verify(node).getSelector(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenYieldStmt() { + // Given + Object argument = mock(Object.class); + YieldStmt node = mock(YieldStmt.class); + + // When + Mockito.when(node.getExpression()).thenReturn(mock(Expression.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getExpression(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenTextBlockLiteralExpr() { + // Given + Object argument = mock(Object.class); + TextBlockLiteralExpr node = mock(TextBlockLiteralExpr.class); + + // When + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenPatternExpr() { + // Given + Object argument = mock(Object.class); + PatternExpr node = mock(PatternExpr.class); + + // When + Mockito.when(node.getModifiers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getType()).thenReturn(mock(ReferenceType.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getModifiers(); + order.verify(node).getName(); + order.verify(node).getType(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_GivenRecordDeclaration() { + // Given + Object argument = mock(Object.class); + RecordDeclaration node = mock(RecordDeclaration.class); + + // When + Mockito.when(node.getImplementedTypes()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getParameters()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getReceiverParameter()).thenReturn(Optional.of(mock(ReceiverParameter.class))); + Mockito.when(node.getTypeParameters()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getMembers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getModifiers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getImplementedTypes(); + order.verify(node).getParameters(); + order.verify(node, times(2)).getReceiverParameter(); + order.verify(node).getTypeParameters(); + order.verify(node).getMembers(); + order.verify(node).getModifiers(); + order.verify(node).getName(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + + @Test + void visit_CompactConstructorDeclaration () { + // Given + Object argument = mock(Object.class); + CompactConstructorDeclaration node = mock(CompactConstructorDeclaration .class); + + // When + Mockito.when(node.getBody()).thenReturn(mock(BlockStmt.class)); + Mockito.when(node.getModifiers()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getName()).thenReturn(mock(SimpleName.class)); + Mockito.when(node.getThrownExceptions()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getTypeParameters()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getAnnotations()).thenReturn(mock(NodeList.class)); + Mockito.when(node.getComment()).thenReturn(Optional.of(mock(Comment.class))); + + // Then + Object result = visitor.visit(node, argument); + + // Assert + assertNull(result); + + // Verify + InOrder order = Mockito.inOrder(node); + order.verify(node).getBody(); + order.verify(node).getModifiers(); + order.verify(node).getName(); + order.verify(node).getThrownExceptions(); + order.verify(node).getTypeParameters(); + order.verify(node).getAnnotations(); + order.verify(node, times(2)).getComment(); + order.verifyNoMoreInteractions(); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/GenericVisitorWithDefaultsTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/GenericVisitorWithDefaultsTest.java new file mode 100644 index 0000000..81cfb32 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/GenericVisitorWithDefaultsTest.java @@ -0,0 +1,707 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General 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 License for more details. + */ + +package com.github.javaparser.ast.visitor; + +import com.github.javaparser.ast.*; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.comments.BlockComment; +import com.github.javaparser.ast.comments.JavadocComment; +import com.github.javaparser.ast.comments.LineComment; +import com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.modules.*; +import com.github.javaparser.ast.stmt.*; +import com.github.javaparser.ast.type.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; + +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.mockito.Mockito.*; +import static org.mockito.MockitoAnnotations.openMocks; + +/** + * This class contains the tests to validate GenericVisitorWithDefaults. + * + * @author 4everTheOne + */ +class GenericVisitorWithDefaultsTest { + + @Captor + private ArgumentCaptor argumentCaptor; + + private Object argument; + private GenericVisitorWithDefaults visitor; + + @BeforeEach + void initialize() { + openMocks(this); + + argument = new Object(); + visitor = spy( + new GenericVisitorWithDefaults() { + @Override + public Node defaultAction(Node n, Object arg) { + super.defaultAction(n, arg); + return n; + } + } + ); + } + + @Test + void testThatVisitWithNodeListMethodAsParameter() { + NodeList nodeList = new NodeList<>(); + Node node = visitor.visit(nodeList, argument); + assertNull(node); + } + + @Test + void testThatVisitWithAnnotationDeclarationMethodAsParameterCallsDefaultAction() { + Node node = visitor.visit(mock(AnnotationDeclaration.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithAnnotationMemberDeclarationMethodAsParameterCallsDefaultAction() { + Node node = visitor.visit(mock(AnnotationMemberDeclaration.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithArrayAccessExprMethodAsParameterCallsDefaultAction() { + Node node = visitor.visit(mock(ArrayAccessExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithArrayCreationExprMethodAsParameterCallsDefaultAction() { + Node node = visitor.visit(mock(ArrayCreationExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithArrayInitializerExprMethodAsParameterCallsDefaultAction() { + Node node = visitor.visit(mock(ArrayInitializerExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithAssertStmtMethodAsParameterCallsDefaultAction() { + Node node = visitor.visit(mock(AssertStmt.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithBlockStmtAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(BlockStmt.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithBooleanLiteralExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(BooleanLiteralExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithBreakStmtAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(BreakStmt.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithCastExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(CastExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithCatchClauseAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(CatchClause.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithCharLiteralExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(CharLiteralExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithClassExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(ClassExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithClassOrInterfaceDeclarationAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(ClassOrInterfaceDeclaration.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithClassOrInterfaceTypeAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(ClassOrInterfaceType.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithCompilationUnitAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(CompilationUnit.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithConditionalExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(ConditionalExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithConstructorDeclarationAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(ConstructorDeclaration.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithContinueStmtAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(ContinueStmt.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithDoStmtAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(DoStmt.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithDoubleLiteralExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(DoubleLiteralExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithAnnotationDeclarationAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(AnnotationDeclaration.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithAnnotationMemberDeclarationAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(AnnotationMemberDeclaration.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithArrayAccessExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(ArrayAccessExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithArrayCreationExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(ArrayCreationExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithArrayCreationLevelAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(ArrayCreationLevel.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithArrayInitializerExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(ArrayInitializerExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithArrayTypeAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(ArrayType.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithAssertStmtAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(AssertStmt.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithAssignExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(AssignExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithBinaryExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(BinaryExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithBlockCommentAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(BlockComment.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithEmptyStmtAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(EmptyStmt.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithEnclosedExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(EnclosedExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithEnumConstantDeclarationAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(EnumConstantDeclaration.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithEnumDeclarationAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(EnumDeclaration.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithExplicitConstructorInvocationStmtAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(ExplicitConstructorInvocationStmt.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithExpressionStmtAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(ExpressionStmt.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithFieldAccessExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(FieldAccessExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithFieldDeclarationAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(FieldDeclaration.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithForEachStmtAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(ForEachStmt.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithForStmtAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(ForStmt.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithIfStmtAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(IfStmt.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithImportDeclarationAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(ImportDeclaration.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithInitializerDeclarationAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(InitializerDeclaration.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithInstanceOfExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(InstanceOfExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithIntegerLiteralExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(IntegerLiteralExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithIntersectionTypeAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(IntersectionType.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithJavadocCommentAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(JavadocComment.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithLabeledStmtAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(LabeledStmt.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithLambdaExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(LambdaExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithLineCommentAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(LineComment.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithLocalClassDeclarationStmtAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(LocalClassDeclarationStmt.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithLocalRecordDeclarationStmtAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(LocalRecordDeclarationStmt.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithLongLiteralExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(LongLiteralExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithMarkerAnnotationExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(MarkerAnnotationExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithMemberValuePairAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(MemberValuePair.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithMethodCallExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(MethodCallExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithMethodDeclarationAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(MethodDeclaration.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithMethodReferenceExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(MethodReferenceExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithModifierAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(Modifier.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithModuleDeclarationAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(ModuleDeclaration.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithModuleExportsDirectiveAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(ModuleExportsDirective.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithModuleOpensDirectiveAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(ModuleOpensDirective.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithModuleProvidesDirectiveAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(ModuleProvidesDirective.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithModuleRequiresDirectiveAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(ModuleRequiresDirective.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithModuleUsesDirectiveAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(ModuleUsesDirective.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithNameExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(NameExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithNameAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(Name.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithNormalAnnotationExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(NormalAnnotationExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithNullLiteralExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(NullLiteralExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithObjectCreationExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(ObjectCreationExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithPackageDeclarationAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(PackageDeclaration.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithParameterAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(Parameter.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithPatternExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(PatternExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithPrimitiveTypeAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(PrimitiveType.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithReceiverParameterAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(ReceiverParameter.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithReturnStmtAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(ReturnStmt.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithSimpleNameAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(SimpleName.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithSingleMemberAnnotationExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(SingleMemberAnnotationExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithStringLiteralExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(StringLiteralExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithSuperExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(SuperExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithSwitchEntryAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(SwitchEntry.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithSwitchExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(SwitchExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithSwitchStmtAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(SwitchStmt.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithSynchronizedStmtAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(SynchronizedStmt.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithTextBlockLiteralExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(TextBlockLiteralExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithThisExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(ThisExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithThrowStmtAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(ThrowStmt.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithTryStmtAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(TryStmt.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithTypeExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(TypeExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithTypeParameterAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(TypeParameter.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithUnaryExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(UnaryExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithUnionTypeAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(UnionType.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithUnknownTypeAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(UnknownType.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithUnparsableStmtAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(UnparsableStmt.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithVarTypeAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(VarType.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithVariableDeclarationExprAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(VariableDeclarationExpr.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithVariableDeclaratorCallDefaultAction() { + Node node = visitor.visit(mock(VariableDeclarator.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithVoidTypeAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(VoidType.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithWhileStmtAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(WhileStmt.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithWildcardTypeAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(WildcardType.class), argument); + assertNodeVisitDefaultAction(node); + } + + @Test + void testThatVisitWithYieldStmtAsParameterCallDefaultAction() { + Node node = visitor.visit(mock(YieldStmt.class), argument); + assertNodeVisitDefaultAction(node); + } + + /** + * Assert that at the default methods was called only once and with the same argument. + */ + void assertNodeVisitDefaultAction(Node node) { + // Check if the default method was only called once + verify(visitor, times(1)).defaultAction(same(node), argumentCaptor.capture()); + // Check if the original argument was passed to the default method + assertSame(argument, argumentCaptor.getValue()); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/HashCodeVisitorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/HashCodeVisitorTest.java new file mode 100644 index 0000000..8b5a969 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/HashCodeVisitorTest.java @@ -0,0 +1,968 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.visitor; + +import com.github.javaparser.ast.*; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.comments.BlockComment; +import com.github.javaparser.ast.comments.JavadocComment; +import com.github.javaparser.ast.comments.LineComment; +import com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.modules.*; +import com.github.javaparser.ast.stmt.*; +import com.github.javaparser.ast.type.*; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.StaticJavaParser.parse; +import static com.github.javaparser.ast.type.PrimitiveType.intType; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.mockito.Mockito.*; + +class HashCodeVisitorTest { + + @Test + void testEquals() { + CompilationUnit p1 = parse("class X { }"); + CompilationUnit p2 = parse("class X { }"); + assertEquals(p1.hashCode(), p2.hashCode()); + } + + @Test + void testNotEquals() { + CompilationUnit p1 = parse("class X { }"); + CompilationUnit p2 = parse("class Y { }"); + assertNotEquals(p1.hashCode(), p2.hashCode()); + } + + @Test + void testVisitAnnotationDeclaration() { + AnnotationDeclaration node = spy(new AnnotationDeclaration()); + HashCodeVisitor.hashCode(node); + + verify(node, times(1)).getMembers(); + verify(node, times(1)).getModifiers(); + verify(node, times(1)).getName(); + verify(node, times(1)).getAnnotations(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitAnnotationMemberDeclaration() { + AnnotationMemberDeclaration node = spy(new AnnotationMemberDeclaration()); + HashCodeVisitor.hashCode(node); + + verify(node, times(1)).getDefaultValue(); + verify(node, times(1)).getModifiers(); + verify(node, times(1)).getName(); + verify(node, times(1)).getType(); + verify(node, times(1)).getAnnotations(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitArrayAccessExpr() { + ArrayAccessExpr node = spy(new ArrayAccessExpr()); + HashCodeVisitor.hashCode(node); + + verify(node, times(1)).getIndex(); + verify(node, times(1)).getName(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitArrayCreationExpr() { + ArrayCreationExpr node = spy(new ArrayCreationExpr()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getElementType(); + verify(node, times(2)).getInitializer(); + verify(node, times(1)).getLevels(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitArrayCreationLevel() { + ArrayCreationLevel node = spy(new ArrayCreationLevel()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getAnnotations(); + verify(node, times(1)).getDimension(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitArrayInitializerExpr() { + ArrayInitializerExpr node = spy(new ArrayInitializerExpr()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getValues(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitArrayType() { + ArrayType node = spy(new ArrayType(intType())); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getComponentType(); + verify(node, times(1)).getOrigin(); + verify(node, times(1)).getAnnotations(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitAssertStmt() { + AssertStmt node = spy(new AssertStmt()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getCheck(); + verify(node, times(1)).getMessage(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitAssignExpr() { + AssignExpr node = spy(new AssignExpr()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getOperator(); + verify(node, times(1)).getTarget(); + verify(node, times(1)).getValue(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitBinaryExpr() { + BinaryExpr node = spy(new BinaryExpr()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getLeft(); + verify(node, times(1)).getOperator(); + verify(node, times(1)).getRight(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitBlockComment() { + BlockComment node = spy(new BlockComment()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getContent(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitBlockStmt() { + BlockStmt node = spy(new BlockStmt()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getStatements(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitBooleanLiteralExpr() { + BooleanLiteralExpr node = spy(new BooleanLiteralExpr()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).isValue(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitBreakStmt() { + BreakStmt node = spy(new BreakStmt()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getLabel(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitCastExpr() { + CastExpr node = spy(new CastExpr()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getExpression(); + verify(node, times(1)).getType(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitCatchClause() { + CatchClause node = spy(new CatchClause()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getBody(); + verify(node, times(1)).getParameter(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitCharLiteralExpr() { + CharLiteralExpr node = spy(new CharLiteralExpr()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getValue(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitClassExpr() { + ClassExpr node = spy(new ClassExpr()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getType(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitClassOrInterfaceDeclaration() { + ClassOrInterfaceDeclaration node = spy(new ClassOrInterfaceDeclaration()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getExtendedTypes(); + verify(node, times(1)).getImplementedTypes(); + verify(node, times(1)).isInterface(); + verify(node, times(1)).getTypeParameters(); + verify(node, times(1)).getMembers(); + verify(node, times(1)).getModifiers(); + verify(node, times(1)).getName(); + verify(node, times(1)).getAnnotations(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitClassOrInterfaceType() { + ClassOrInterfaceType node = spy(new ClassOrInterfaceType()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getName(); + verify(node, times(1)).getScope(); + verify(node, times(1)).getTypeArguments(); + verify(node, times(1)).getAnnotations(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitCompilationUnit() { + CompilationUnit node = spy(new CompilationUnit()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getImports(); + verify(node, times(1)).getModule(); + verify(node, times(1)).getPackageDeclaration(); + verify(node, times(1)).getTypes(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitConditionalExpr() { + ConditionalExpr node = spy(new ConditionalExpr()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getCondition(); + verify(node, times(1)).getElseExpr(); + verify(node, times(1)).getThenExpr(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitConstructorDeclaration() { + ConstructorDeclaration node = spy(new ConstructorDeclaration()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getBody(); + verify(node, times(1)).getModifiers(); + verify(node, times(1)).getName(); + verify(node, times(1)).getParameters(); + verify(node, times(1)).getReceiverParameter(); + verify(node, times(1)).getThrownExceptions(); + verify(node, times(1)).getTypeParameters(); + verify(node, times(1)).getAnnotations(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitContinueStmt() { + ContinueStmt node = spy(new ContinueStmt()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getLabel(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitDoStmt() { + DoStmt node = spy(new DoStmt()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getBody(); + verify(node, times(1)).getCondition(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitDoubleLiteralExpr() { + DoubleLiteralExpr node = spy(new DoubleLiteralExpr()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getValue(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitEmptyStmt() { + EmptyStmt node = spy(new EmptyStmt()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitEnclosedExpr() { + EnclosedExpr node = spy(new EnclosedExpr()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getInner(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitEnumConstantDeclaration() { + EnumConstantDeclaration node = spy(new EnumConstantDeclaration()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getArguments(); + verify(node, times(1)).getClassBody(); + verify(node, times(1)).getName(); + verify(node, times(1)).getAnnotations(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitEnumDeclaration() { + EnumDeclaration node = spy(new EnumDeclaration()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getEntries(); + verify(node, times(1)).getImplementedTypes(); + verify(node, times(1)).getMembers(); + verify(node, times(1)).getModifiers(); + verify(node, times(1)).getName(); + verify(node, times(1)).getAnnotations(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitExplicitConstructorInvocationStmt() { + ExplicitConstructorInvocationStmt node = spy(new ExplicitConstructorInvocationStmt()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getArguments(); + verify(node, times(1)).getExpression(); + verify(node, times(1)).isThis(); + verify(node, times(1)).getTypeArguments(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitExpressionStmt() { + ExpressionStmt node = spy(new ExpressionStmt()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getExpression(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitFieldAccessExpr() { + FieldAccessExpr node = spy(new FieldAccessExpr()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getName(); + verify(node, times(1)).getScope(); + verify(node, times(1)).getTypeArguments(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitFieldDeclaration() { + FieldDeclaration node = spy(new FieldDeclaration()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getModifiers(); + verify(node, times(1)).getVariables(); + verify(node, times(1)).getAnnotations(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitForEachStmt() { + ForEachStmt node = spy(new ForEachStmt()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getBody(); + verify(node, times(1)).getIterable(); + verify(node, times(1)).getVariable(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitForStmt() { + ForStmt node = spy(new ForStmt()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getBody(); + verify(node, times(2)).getCompare(); + verify(node, times(1)).getInitialization(); + verify(node, times(1)).getUpdate(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitIfStmt() { + IfStmt node = spy(new IfStmt()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getCondition(); + verify(node, times(1)).getElseStmt(); + verify(node, times(1)).getThenStmt(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitImportDeclaration() { + ImportDeclaration node = spy(new ImportDeclaration(new Name(), false, false)); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).isAsterisk(); + verify(node, times(1)).isStatic(); + verify(node, times(1)).getName(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitInitializerDeclaration() { + InitializerDeclaration node = spy(new InitializerDeclaration()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getBody(); + verify(node, times(1)).isStatic(); + verify(node, times(1)).getAnnotations(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitInstanceOfExpr() { + InstanceOfExpr node = spy(new InstanceOfExpr()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getExpression(); + verify(node, times(1)).getPattern(); + verify(node, times(1)).getType(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitIntegerLiteralExpr() { + IntegerLiteralExpr node = spy(new IntegerLiteralExpr()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getValue(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitIntersectionType() { + NodeList elements = new NodeList<>(); + elements.add(new ClassOrInterfaceType()); + IntersectionType node = spy(new IntersectionType(elements)); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getElements(); + verify(node, times(1)).getAnnotations(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitJavadocComment() { + JavadocComment node = spy(new JavadocComment()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getContent(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitLabeledStmt() { + LabeledStmt node = spy(new LabeledStmt()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getLabel(); + verify(node, times(1)).getStatement(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitLambdaExpr() { + LambdaExpr node = spy(new LambdaExpr()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getBody(); + verify(node, times(1)).isEnclosingParameters(); + verify(node, times(1)).getParameters(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitLineComment() { + LineComment node = spy(new LineComment()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getContent(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitLocalClassDeclarationStmt() { + LocalClassDeclarationStmt node = spy(new LocalClassDeclarationStmt()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getClassDeclaration(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitLocalRecordDeclarationStmt() { + LocalRecordDeclarationStmt node = spy(new LocalRecordDeclarationStmt()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getRecordDeclaration(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitLongLiteralExpr() { + LongLiteralExpr node = spy(new LongLiteralExpr()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getValue(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitMarkerAnnotationExpr() { + MarkerAnnotationExpr node = spy(new MarkerAnnotationExpr()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getName(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitMemberValuePair() { + MemberValuePair node = spy(new MemberValuePair()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getName(); + verify(node, times(1)).getValue(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitMethodCallExpr() { + MethodCallExpr node = spy(new MethodCallExpr()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getArguments(); + verify(node, times(1)).getName(); + verify(node, times(1)).getScope(); + verify(node, times(1)).getTypeArguments(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitMethodDeclaration() { + MethodDeclaration node = spy(new MethodDeclaration()); + HashCodeVisitor.hashCode(node); + verify(node, times(2)).getBody(); + verify(node, times(1)).getType(); + verify(node, times(1)).getModifiers(); + verify(node, times(1)).getName(); + verify(node, times(1)).getParameters(); + verify(node, times(1)).getReceiverParameter(); + verify(node, times(1)).getThrownExceptions(); + verify(node, times(1)).getTypeParameters(); + verify(node, times(1)).getAnnotations(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitMethodReferenceExpr() { + MethodReferenceExpr node = spy(new MethodReferenceExpr()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getIdentifier(); + verify(node, times(1)).getScope(); + verify(node, times(1)).getTypeArguments(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitModifier() { + Modifier node = spy(new Modifier()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getKeyword(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitModuleDeclaration() { + ModuleDeclaration node = spy(new ModuleDeclaration()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getAnnotations(); + verify(node, times(1)).getDirectives(); + verify(node, times(1)).isOpen(); + verify(node, times(1)).getName(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitModuleExportsDirective() { + ModuleExportsDirective node = spy(new ModuleExportsDirective()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getModuleNames(); + verify(node, times(1)).getName(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitModuleOpensDirective() { + ModuleOpensDirective node = spy(new ModuleOpensDirective()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getModuleNames(); + verify(node, times(1)).getName(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitModuleProvidesDirective() { + ModuleProvidesDirective node = spy(new ModuleProvidesDirective()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getName(); + verify(node, times(1)).getWith(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitModuleRequiresDirective() { + ModuleRequiresDirective node = spy(new ModuleRequiresDirective()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getModifiers(); + verify(node, times(1)).getName(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitModuleUsesDirective() { + ModuleUsesDirective node = spy(new ModuleUsesDirective()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getName(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitNameExpr() { + NameExpr node = spy(new NameExpr()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getName(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitName() { + Name node = spy(new Name()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getIdentifier(); + verify(node, times(1)).getQualifier(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitNormalAnnotationExpr() { + NormalAnnotationExpr node = spy(new NormalAnnotationExpr()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getPairs(); + verify(node, times(1)).getName(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitNullLiteralExpr() { + NullLiteralExpr node = spy(new NullLiteralExpr()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitObjectCreationExpr() { + ObjectCreationExpr node = spy(new ObjectCreationExpr()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getAnonymousClassBody(); + verify(node, times(1)).getArguments(); + verify(node, times(1)).getScope(); + verify(node, times(1)).getType(); + verify(node, times(2)).getTypeArguments(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitPackageDeclaration() { + PackageDeclaration node = spy(new PackageDeclaration()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getAnnotations(); + verify(node, times(1)).getName(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitParameter() { + Parameter node = spy(new Parameter()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getAnnotations(); + verify(node, times(1)).isVarArgs(); + verify(node, times(1)).getModifiers(); + verify(node, times(1)).getName(); + verify(node, times(1)).getType(); + verify(node, times(1)).getVarArgsAnnotations(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitPatternExpr() { + PatternExpr node = spy(new PatternExpr()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getModifiers(); + verify(node, times(1)).getName(); + verify(node, times(1)).getType(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitPrimitiveType() { + PrimitiveType node = spy(new PrimitiveType()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getType(); + verify(node, times(1)).getAnnotations(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitReceiverParameter() { + ReceiverParameter node = spy(new ReceiverParameter()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getAnnotations(); + verify(node, times(1)).getName(); + verify(node, times(1)).getType(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitReturnStmt() { + ReturnStmt node = spy(new ReturnStmt()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getExpression(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitSimpleName() { + SimpleName node = spy(new SimpleName()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getIdentifier(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitSingleMemberAnnotationExpr() { + SingleMemberAnnotationExpr node = spy(new SingleMemberAnnotationExpr()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getMemberValue(); + verify(node, times(1)).getName(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitStringLiteralExpr() { + StringLiteralExpr node = spy(new StringLiteralExpr()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getValue(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitSuperExpr() { + SuperExpr node = spy(new SuperExpr()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getTypeName(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitSwitchEntry() { + SwitchEntry node = spy(new SwitchEntry()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getLabels(); + verify(node, times(1)).getStatements(); + verify(node, times(1)).getType(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitSwitchExpr() { + SwitchExpr node = spy(new SwitchExpr()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getEntries(); + verify(node, times(1)).getSelector(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitSwitchStmt() { + SwitchStmt node = spy(new SwitchStmt()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getEntries(); + verify(node, times(1)).getSelector(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitSynchronizedStmt() { + SynchronizedStmt node = spy(new SynchronizedStmt()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getBody(); + verify(node, times(1)).getExpression(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitTextBlockLiteralExpr() { + TextBlockLiteralExpr node = spy(new TextBlockLiteralExpr()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getValue(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitThisExpr() { + ThisExpr node = spy(new ThisExpr()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getTypeName(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitThrowStmt() { + ThrowStmt node = spy(new ThrowStmt()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getExpression(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitTryStmt() { + TryStmt node = spy(new TryStmt()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getCatchClauses(); + verify(node, times(1)).getFinallyBlock(); + verify(node, times(1)).getResources(); + verify(node, times(1)).getTryBlock(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitTypeExpr() { + TypeExpr node = spy(new TypeExpr()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getType(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitTypeParameter() { + TypeParameter node = spy(new TypeParameter()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getName(); + verify(node, times(1)).getTypeBound(); + verify(node, times(1)).getAnnotations(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitUnaryExpr() { + UnaryExpr node = spy(new UnaryExpr()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getExpression(); + verify(node, times(1)).getOperator(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitUnionType() { + UnionType node = spy(new UnionType()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getElements(); + verify(node, times(1)).getAnnotations(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitUnknownType() { + UnknownType node = spy(new UnknownType()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getAnnotations(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitUnparsableStmt() { + UnparsableStmt node = spy(new UnparsableStmt()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitVarType() { + VarType node = spy(new VarType()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getAnnotations(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitVariableDeclarationExpr() { + VariableDeclarationExpr node = spy(new VariableDeclarationExpr()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getAnnotations(); + verify(node, times(1)).getModifiers(); + verify(node, times(1)).getVariables(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitVariableDeclarator() { + VariableDeclarator node = spy(new VariableDeclarator()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getInitializer(); + verify(node, times(1)).getName(); + verify(node, times(1)).getType(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitVoidType() { + VoidType node = spy(new VoidType()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getAnnotations(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitWhileStmt() { + WhileStmt node = spy(new WhileStmt()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getBody(); + verify(node, times(1)).getCondition(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitWildcardType() { + WildcardType node = spy(new WildcardType()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getExtendedType(); + verify(node, times(1)).getSuperType(); + verify(node, times(1)).getAnnotations(); + verify(node, times(1)).getComment(); + } + + @Test + void testVisitYieldStmt() { + YieldStmt node = spy(new YieldStmt()); + HashCodeVisitor.hashCode(node); + verify(node, times(1)).getExpression(); + verify(node, times(1)).getComment(); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/ModifierVisitorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/ModifierVisitorTest.java new file mode 100644 index 0000000..a8f1a0d --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/ModifierVisitorTest.java @@ -0,0 +1,144 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.visitor; + +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.BodyDeclaration; +import com.github.javaparser.ast.body.VariableDeclarator; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.expr.IntegerLiteralExpr; +import com.github.javaparser.ast.expr.StringLiteralExpr; +import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest; +import com.github.javaparser.printer.lexicalpreservation.LexicalPreservingPrinter; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.StaticJavaParser.parseBodyDeclaration; +import static com.github.javaparser.StaticJavaParser.parseExpression; +import static com.github.javaparser.utils.Utils.SYSTEM_EOL; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class ModifierVisitorTest extends AbstractLexicalPreservingTest { + @Test + void makeSureParentListsCanBeModified() { + NodeList list = new NodeList<>(); + list.add(new StringLiteralExpr("t")); + list.add(new StringLiteralExpr("a")); + list.add(new StringLiteralExpr("b")); + list.add(new StringLiteralExpr("c")); + + list.accept(new ModifierVisitor() { + @Override + public Visitable visit(final StringLiteralExpr n, final Void arg) { + String v = n.getValue(); + + list.addFirst(new StringLiteralExpr("extra " + v)); + list.remove(new StringLiteralExpr("t")); + + if (v.equals("a")) { + return new StringLiteralExpr("x"); + } + if (v.equals("b")) { + return null; + } + + return n; + } + }, null); + + assertEquals("extra c", list.get(0).getValue()); + assertEquals("extra b", list.get(1).getValue()); + assertEquals("extra a", list.get(2).getValue()); + assertEquals("extra t", list.get(3).getValue()); + assertEquals("x", list.get(4).getValue()); + assertEquals("c", list.get(5).getValue()); + assertEquals(6, list.size()); + } + + @Test + void binaryExprReturnsLeftExpressionWhenRightSideIsRemoved() { + Expression expression = parseExpression("1+2"); + Visitable result = expression.accept(new ModifierVisitor() { + public Visitable visit(IntegerLiteralExpr integerLiteralExpr, Void arg) { + if (integerLiteralExpr.getValue().equals("1")) { + return null; + } + return integerLiteralExpr; + } + }, null); + assertEquals("2", result.toString()); + } + + @Test + void binaryExprReturnsRightExpressionWhenLeftSideIsRemoved() { + final Expression expression = parseExpression("1+2"); + final Visitable result = expression.accept(new ModifierVisitor() { + public Visitable visit(IntegerLiteralExpr integerLiteralExpr, Void arg) { + if (integerLiteralExpr.getValue().equals("2")) { + return null; + } + return integerLiteralExpr; + } + }, null); + assertEquals("1", result.toString()); + } + + @Test + void fieldDeclarationCantSurviveWithoutVariables() { + final BodyDeclaration bodyDeclaration = parseBodyDeclaration("int x=1;"); + + final Visitable result = bodyDeclaration.accept(new ModifierVisitor() { + public Visitable visit(VariableDeclarator x, Void arg) { + return null; + } + }, null); + + assertNull(result); + } + + @Test + void variableDeclarationCantSurviveWithoutVariables() { + final BodyDeclaration bodyDeclaration = parseBodyDeclaration("void x() {int x=1;}"); + + final Visitable result = bodyDeclaration.accept(new ModifierVisitor() { + public Visitable visit(VariableDeclarator x, Void arg) { + return null; + } + }, null); + + assertEquals("void x() {" + SYSTEM_EOL + "}", result.toString()); + } + + @Test + void issue2124() { + ModifierVisitor modifier = new ModifierVisitor<>(); + considerCode("\n" + + "public class ModifierVisitorTest {\n" + + " private void causesException() {\n" + + " String[] listWithExtraCommaAndEqualElements = {\"a\", \"a\",};\n" + + " }\n" + + "}"); + cu.accept(modifier, null); + //there should be no exception + LexicalPreservingPrinter.print(cu); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/NoCommentEqualsVisitorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/NoCommentEqualsVisitorTest.java new file mode 100644 index 0000000..1f6c88b --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/NoCommentEqualsVisitorTest.java @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.visitor; + +import com.github.javaparser.ast.CompilationUnit; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.StaticJavaParser.parse; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class NoCommentEqualsVisitorTest { + + @Test + void testEquals() { + CompilationUnit p1 = parse("class X { }"); + CompilationUnit p2 = parse("class X { }"); + assertTrue(NoCommentEqualsVisitor.equals(p1, p2)); + } + + @Test + void testEqualsWithDifferentComments() { + CompilationUnit p1 = parse("/* a */ class X { /** b */} //c"); + CompilationUnit p2 = parse("/* b */ class X { } //c"); + assertTrue(NoCommentEqualsVisitor.equals(p1, p2)); + } + + @Test + void testNotEquals() { + CompilationUnit p1 = parse("class X { }"); + CompilationUnit p2 = parse("class Y { }"); + assertFalse(NoCommentEqualsVisitor.equals(p1, p2)); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/NoCommentHashCodeVisitorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/NoCommentHashCodeVisitorTest.java new file mode 100644 index 0000000..af58a7e --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/NoCommentHashCodeVisitorTest.java @@ -0,0 +1,1067 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.visitor; + +import com.github.javaparser.ast.*; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.comments.BlockComment; +import com.github.javaparser.ast.comments.JavadocComment; +import com.github.javaparser.ast.comments.LineComment; +import com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.modules.*; +import com.github.javaparser.ast.stmt.*; +import com.github.javaparser.ast.type.*; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.StaticJavaParser.parse; +import static com.github.javaparser.ast.type.PrimitiveType.intType; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.mockito.Mockito.*; + +class NoCommentHashCodeVisitorTest { + + @Test + void testEquals() { + CompilationUnit p1 = parse("class X { }"); + CompilationUnit p2 = parse("class X { }"); + assertEquals(p1.hashCode(), p2.hashCode()); + } + + @Test + void testEqualsWithDifferentComments() { + CompilationUnit p1 = parse("/* a */ class X { /** b */} //c"); + CompilationUnit p2 = parse("/* b */ class X { } //c"); + assertEquals(p1.hashCode(), p2.hashCode()); + assertEquals(3, p1.getAllComments().size()); + assertEquals(2, p2.getAllComments().size()); + } + + @Test + void testNotEquals() { + CompilationUnit p1 = parse("class X { }"); + CompilationUnit p2 = parse("class Y { }"); + assertNotEquals(p1.hashCode(), p2.hashCode()); + } + + @Test + void testJavadocCommentDoesNotHaveHashCode() { + JavadocComment node = spy(new JavadocComment()); + assertEquals(0, NoCommentHashCodeVisitor.hashCode(node)); + + verify(node).accept(isA(NoCommentHashCodeVisitor.class), isNull()); + } + + @Test + void testLineCommentDoesNotHaveHashCode() { + LineComment node = spy(new LineComment()); + assertEquals(0, NoCommentHashCodeVisitor.hashCode(node)); + + verify(node).accept(isA(NoCommentHashCodeVisitor.class), isNull()); + } + + @Test + void testBlockCommentDoesNotHaveHashCode() { + BlockComment node = spy(new BlockComment()); + assertEquals(0, NoCommentHashCodeVisitor.hashCode(node)); + + verify(node).accept(isA(NoCommentHashCodeVisitor.class), isNull()); + } + + @Test + void testVisitAnnotationDeclaration() { + AnnotationDeclaration node = spy(new AnnotationDeclaration()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getMembers(); + verify(node, times(1)).getModifiers(); + verify(node, times(1)).getName(); + verify(node, times(1)).getAnnotations(); + verify(node, never()).getComment(); + } + + @Test + void testVisitAnnotationMemberDeclaration() { + AnnotationMemberDeclaration node = spy(new AnnotationMemberDeclaration()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getDefaultValue(); + verify(node, times(1)).getModifiers(); + verify(node, times(1)).getName(); + verify(node, times(1)).getType(); + verify(node, times(1)).getAnnotations(); + verify(node, never()).getComment(); + } + + @Test + void testVisitArrayAccessExpr() { + ArrayAccessExpr node = spy(new ArrayAccessExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getIndex(); + verify(node, times(1)).getName(); + verify(node, never()).getComment(); + } + + @Test + void testVisitArrayCreationExpr() { + ArrayCreationExpr node = spy(new ArrayCreationExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getElementType(); + verify(node, times(2)).getInitializer(); + verify(node, times(1)).getLevels(); + verify(node, never()).getComment(); + } + + @Test + void testVisitArrayCreationLevel() { + ArrayCreationLevel node = spy(new ArrayCreationLevel()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getAnnotations(); + verify(node, times(1)).getDimension(); + verify(node, never()).getComment(); + } + + @Test + void testVisitArrayInitializerExpr() { + ArrayInitializerExpr node = spy(new ArrayInitializerExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getValues(); + verify(node, never()).getComment(); + } + + @Test + void testVisitArrayType() { + ArrayType node = spy(new ArrayType(intType())); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getComponentType(); + verify(node, times(1)).getOrigin(); + verify(node, times(1)).getAnnotations(); + verify(node, never()).getComment(); + } + + @Test + void testVisitAssertStmt() { + AssertStmt node = spy(new AssertStmt()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getCheck(); + verify(node, times(1)).getMessage(); + verify(node, never()).getComment(); + } + + @Test + void testVisitAssignExpr() { + AssignExpr node = spy(new AssignExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getOperator(); + verify(node, times(1)).getTarget(); + verify(node, times(1)).getValue(); + verify(node, never()).getComment(); + } + + @Test + void testVisitBinaryExpr() { + BinaryExpr node = spy(new BinaryExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getLeft(); + verify(node, times(1)).getOperator(); + verify(node, times(1)).getRight(); + verify(node, never()).getComment(); + } + + @Test + void testVisitBlockStmt() { + BlockStmt node = spy(new BlockStmt()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getStatements(); + verify(node, never()).getComment(); + } + + @Test + void testVisitBooleanLiteralExpr() { + BooleanLiteralExpr node = spy(new BooleanLiteralExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).isValue(); + verify(node, never()).getComment(); + } + + @Test + void testVisitBreakStmt() { + BreakStmt node = spy(new BreakStmt()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getLabel(); + verify(node, never()).getComment(); + } + + @Test + void testVisitCastExpr() { + CastExpr node = spy(new CastExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getExpression(); + verify(node, times(1)).getType(); + verify(node, never()).getComment(); + } + + @Test + void testVisitCatchClause() { + CatchClause node = spy(new CatchClause()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getBody(); + verify(node, times(1)).getParameter(); + verify(node, never()).getComment(); + } + + @Test + void testVisitCharLiteralExpr() { + CharLiteralExpr node = spy(new CharLiteralExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getValue(); + verify(node, never()).getComment(); + } + + @Test + void testVisitClassExpr() { + ClassExpr node = spy(new ClassExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getType(); + verify(node, never()).getComment(); + } + + @Test + void testVisitClassOrInterfaceDeclaration() { + ClassOrInterfaceDeclaration node = spy(new ClassOrInterfaceDeclaration()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getExtendedTypes(); + verify(node, times(1)).getImplementedTypes(); + verify(node, times(1)).isInterface(); + verify(node, times(1)).getTypeParameters(); + verify(node, times(1)).getMembers(); + verify(node, times(1)).getModifiers(); + verify(node, times(1)).getName(); + verify(node, times(1)).getAnnotations(); + verify(node, never()).getComment(); + } + + @Test + void testVisitClassOrInterfaceType() { + ClassOrInterfaceType node = spy(new ClassOrInterfaceType()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getName(); + verify(node, times(1)).getScope(); + verify(node, times(1)).getTypeArguments(); + verify(node, times(1)).getAnnotations(); + verify(node, never()).getComment(); + } + + @Test + void testVisitCompilationUnit() { + CompilationUnit node = spy(new CompilationUnit()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getImports(); + verify(node, times(1)).getModule(); + verify(node, times(1)).getPackageDeclaration(); + verify(node, times(1)).getTypes(); + verify(node, never()).getComment(); + } + + @Test + void testVisitConditionalExpr() { + ConditionalExpr node = spy(new ConditionalExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getCondition(); + verify(node, times(1)).getElseExpr(); + verify(node, times(1)).getThenExpr(); + verify(node, never()).getComment(); + } + + @Test + void testVisitConstructorDeclaration() { + ConstructorDeclaration node = spy(new ConstructorDeclaration()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getBody(); + verify(node, times(1)).getModifiers(); + verify(node, times(1)).getName(); + verify(node, times(1)).getParameters(); + verify(node, times(1)).getReceiverParameter(); + verify(node, times(1)).getThrownExceptions(); + verify(node, times(1)).getTypeParameters(); + verify(node, times(1)).getAnnotations(); + verify(node, never()).getComment(); + } + + @Test + void testVisitContinueStmt() { + ContinueStmt node = spy(new ContinueStmt()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getLabel(); + verify(node, never()).getComment(); + } + + @Test + void testVisitDoStmt() { + DoStmt node = spy(new DoStmt()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getBody(); + verify(node, times(1)).getCondition(); + verify(node, never()).getComment(); + } + + @Test + void testVisitDoubleLiteralExpr() { + DoubleLiteralExpr node = spy(new DoubleLiteralExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getValue(); + verify(node, never()).getComment(); + } + + @Test + void testVisitEmptyStmt() { + EmptyStmt node = spy(new EmptyStmt()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, never()).getComment(); + } + + @Test + void testVisitEnclosedExpr() { + EnclosedExpr node = spy(new EnclosedExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getInner(); + verify(node, never()).getComment(); + } + + @Test + void testVisitEnumConstantDeclaration() { + EnumConstantDeclaration node = spy(new EnumConstantDeclaration()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getArguments(); + verify(node, times(1)).getClassBody(); + verify(node, times(1)).getName(); + verify(node, times(1)).getAnnotations(); + verify(node, never()).getComment(); + } + + @Test + void testVisitEnumDeclaration() { + EnumDeclaration node = spy(new EnumDeclaration()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getEntries(); + verify(node, times(1)).getImplementedTypes(); + verify(node, times(1)).getMembers(); + verify(node, times(1)).getModifiers(); + verify(node, times(1)).getName(); + verify(node, times(1)).getAnnotations(); + verify(node, never()).getComment(); + } + + @Test + void testVisitExplicitConstructorInvocationStmt() { + ExplicitConstructorInvocationStmt node = spy(new ExplicitConstructorInvocationStmt()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getArguments(); + verify(node, times(1)).getExpression(); + verify(node, times(1)).isThis(); + verify(node, times(1)).getTypeArguments(); + verify(node, never()).getComment(); + } + + @Test + void testVisitExpressionStmt() { + ExpressionStmt node = spy(new ExpressionStmt()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getExpression(); + verify(node, never()).getComment(); + } + + @Test + void testVisitFieldAccessExpr() { + FieldAccessExpr node = spy(new FieldAccessExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getName(); + verify(node, times(1)).getScope(); + verify(node, times(1)).getTypeArguments(); + verify(node, never()).getComment(); + } + + @Test + void testVisitFieldDeclaration() { + FieldDeclaration node = spy(new FieldDeclaration()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getModifiers(); + verify(node, times(1)).getVariables(); + verify(node, times(1)).getAnnotations(); + verify(node, never()).getComment(); + } + + @Test + void testVisitForStmt() { + ForStmt node = spy(new ForStmt()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getBody(); + verify(node, times(2)).getCompare(); + verify(node, times(1)).getInitialization(); + verify(node, times(1)).getUpdate(); + verify(node, never()).getComment(); + } + + @Test + void testVisitForEachStmt() { + ForEachStmt node = spy(new ForEachStmt()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getBody(); + verify(node, times(1)).getIterable(); + verify(node, times(1)).getVariable(); + verify(node, never()).getComment(); + } + + @Test + void testVisitIfStmt() { + IfStmt node = spy(new IfStmt()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getCondition(); + verify(node, times(1)).getElseStmt(); + verify(node, times(1)).getThenStmt(); + verify(node, never()).getComment(); + } + + @Test + void testVisitImportDeclaration() { + ImportDeclaration node = spy(new ImportDeclaration(new Name(), false, false)); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).isAsterisk(); + verify(node, times(1)).isStatic(); + verify(node, times(1)).getName(); + verify(node, never()).getComment(); + } + + @Test + void testVisitInitializerDeclaration() { + InitializerDeclaration node = spy(new InitializerDeclaration()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getBody(); + verify(node, times(1)).isStatic(); + verify(node, times(1)).getAnnotations(); + verify(node, never()).getComment(); + } + + @Test + void testVisitInstanceOfExpr() { + InstanceOfExpr node = spy(new InstanceOfExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getExpression(); + verify(node, times(1)).getPattern(); + verify(node, times(1)).getType(); + verify(node, never()).getComment(); + } + + @Test + void testVisitIntegerLiteralExpr() { + IntegerLiteralExpr node = spy(new IntegerLiteralExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getValue(); + verify(node, never()).getComment(); + } + + @Test + void testVisitIntersectionType() { + NodeList elements = new NodeList<>(); + elements.add(new ClassOrInterfaceType()); + IntersectionType node = spy(new IntersectionType(elements)); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getElements(); + verify(node, times(1)).getAnnotations(); + verify(node, never()).getComment(); + } + + @Test + void testVisitLabeledStmt() { + LabeledStmt node = spy(new LabeledStmt()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getLabel(); + verify(node, times(1)).getStatement(); + verify(node, never()).getComment(); + } + + @Test + void testVisitLambdaExpr() { + LambdaExpr node = spy(new LambdaExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getBody(); + verify(node, times(1)).isEnclosingParameters(); + verify(node, times(1)).getParameters(); + verify(node, never()).getComment(); + } + + @Test + void testVisitLocalClassDeclarationStmt() { + LocalClassDeclarationStmt node = spy(new LocalClassDeclarationStmt()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getClassDeclaration(); + verify(node, never()).getComment(); + } + + @Test + void testVisitLocalRecordDeclarationStmt() { + LocalRecordDeclarationStmt node = spy(new LocalRecordDeclarationStmt()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getRecordDeclaration(); + verify(node, never()).getComment(); + } + + @Test + void testVisitLongLiteralExpr() { + LongLiteralExpr node = spy(new LongLiteralExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getValue(); + verify(node, never()).getComment(); + } + + @Test + void testVisitMarkerAnnotationExpr() { + MarkerAnnotationExpr node = spy(new MarkerAnnotationExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getName(); + verify(node, never()).getComment(); + } + + @Test + void testVisitMemberValuePair() { + MemberValuePair node = spy(new MemberValuePair()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getName(); + verify(node, times(1)).getValue(); + verify(node, never()).getComment(); + } + + @Test + void testVisitMethodCallExpr() { + MethodCallExpr node = spy(new MethodCallExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getArguments(); + verify(node, times(1)).getName(); + verify(node, times(1)).getScope(); + verify(node, times(1)).getTypeArguments(); + verify(node, never()).getComment(); + } + + @Test + void testVisitMethodDeclaration() { + MethodDeclaration node = spy(new MethodDeclaration()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(2)).getBody(); + verify(node, times(1)).getType(); + verify(node, times(1)).getModifiers(); + verify(node, times(1)).getName(); + verify(node, times(1)).getParameters(); + verify(node, times(1)).getReceiverParameter(); + verify(node, times(1)).getThrownExceptions(); + verify(node, times(1)).getTypeParameters(); + verify(node, times(1)).getAnnotations(); + verify(node, never()).getComment(); + } + + @Test + void testVisitMethodReferenceExpr() { + MethodReferenceExpr node = spy(new MethodReferenceExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getIdentifier(); + verify(node, times(1)).getScope(); + verify(node, times(1)).getTypeArguments(); + verify(node, never()).getComment(); + } + + @Test + void testVisitNameExpr() { + NameExpr node = spy(new NameExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getName(); + verify(node, never()).getComment(); + } + + @Test + void testVisitName() { + Name node = spy(new Name()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getIdentifier(); + verify(node, times(1)).getQualifier(); + verify(node, never()).getComment(); + } + + @Test + void testVisitNormalAnnotationExpr() { + NormalAnnotationExpr node = spy(new NormalAnnotationExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getPairs(); + verify(node, times(1)).getName(); + verify(node, never()).getComment(); + } + + @Test + void testVisitNullLiteralExpr() { + NullLiteralExpr node = spy(new NullLiteralExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, never()).getComment(); + } + + @Test + void testVisitObjectCreationExpr() { + ObjectCreationExpr node = spy(new ObjectCreationExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getAnonymousClassBody(); + verify(node, times(1)).getArguments(); + verify(node, times(1)).getScope(); + verify(node, times(1)).getType(); + verify(node, times(2)).getTypeArguments(); + verify(node, never()).getComment(); + } + + @Test + void testVisitPackageDeclaration() { + PackageDeclaration node = spy(new PackageDeclaration()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getAnnotations(); + verify(node, times(1)).getName(); + verify(node, never()).getComment(); + } + + @Test + void testVisitParameter() { + Parameter node = spy(new Parameter()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getAnnotations(); + verify(node, times(1)).isVarArgs(); + verify(node, times(1)).getModifiers(); + verify(node, times(1)).getName(); + verify(node, times(1)).getType(); + verify(node, times(1)).getVarArgsAnnotations(); + verify(node, never()).getComment(); + } + + @Test + void testVisitPrimitiveType() { + PrimitiveType node = spy(new PrimitiveType()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getType(); + verify(node, times(1)).getAnnotations(); + verify(node, never()).getComment(); + } + + @Test + void testVisitReturnStmt() { + ReturnStmt node = spy(new ReturnStmt()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getExpression(); + verify(node, never()).getComment(); + } + + @Test + void testVisitSimpleName() { + SimpleName node = spy(new SimpleName()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getIdentifier(); + verify(node, never()).getComment(); + } + + @Test + void testVisitSingleMemberAnnotationExpr() { + SingleMemberAnnotationExpr node = spy(new SingleMemberAnnotationExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getMemberValue(); + verify(node, times(1)).getName(); + verify(node, never()).getComment(); + } + + @Test + void testVisitStringLiteralExpr() { + StringLiteralExpr node = spy(new StringLiteralExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getValue(); + verify(node, never()).getComment(); + } + + @Test + void testVisitSuperExpr() { + SuperExpr node = spy(new SuperExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getTypeName(); + verify(node, never()).getComment(); + } + + @Test + void testVisitSwitchEntry() { + SwitchEntry node = spy(new SwitchEntry()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getLabels(); + verify(node, times(1)).getStatements(); + verify(node, times(1)).getType(); + verify(node, never()).getComment(); + } + + @Test + void testVisitSwitchStmt() { + SwitchStmt node = spy(new SwitchStmt()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getEntries(); + verify(node, times(1)).getSelector(); + verify(node, never()).getComment(); + } + + @Test + void testVisitSynchronizedStmt() { + SynchronizedStmt node = spy(new SynchronizedStmt()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getBody(); + verify(node, times(1)).getExpression(); + verify(node, never()).getComment(); + } + + @Test + void testVisitThisExpr() { + ThisExpr node = spy(new ThisExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getTypeName(); + verify(node, never()).getComment(); + } + + @Test + void testVisitThrowStmt() { + ThrowStmt node = spy(new ThrowStmt()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getExpression(); + verify(node, never()).getComment(); + } + + @Test + void testVisitTryStmt() { + TryStmt node = spy(new TryStmt()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getCatchClauses(); + verify(node, times(1)).getFinallyBlock(); + verify(node, times(1)).getResources(); + verify(node, times(1)).getTryBlock(); + verify(node, never()).getComment(); + } + + @Test + void testVisitTypeExpr() { + TypeExpr node = spy(new TypeExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getType(); + verify(node, never()).getComment(); + } + + @Test + void testVisitTypeParameter() { + TypeParameter node = spy(new TypeParameter()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getName(); + verify(node, times(1)).getTypeBound(); + verify(node, times(1)).getAnnotations(); + verify(node, never()).getComment(); + } + + @Test + void testVisitUnaryExpr() { + UnaryExpr node = spy(new UnaryExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getExpression(); + verify(node, times(1)).getOperator(); + verify(node, never()).getComment(); + } + + @Test + void testVisitUnionType() { + UnionType node = spy(new UnionType()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getElements(); + verify(node, times(1)).getAnnotations(); + verify(node, never()).getComment(); + } + + @Test + void testVisitUnknownType() { + UnknownType node = spy(new UnknownType()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getAnnotations(); + verify(node, never()).getComment(); + } + + @Test + void testVisitVariableDeclarationExpr() { + VariableDeclarationExpr node = spy(new VariableDeclarationExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getAnnotations(); + verify(node, times(1)).getModifiers(); + verify(node, times(1)).getVariables(); + verify(node, never()).getComment(); + } + + @Test + void testVisitVariableDeclarator() { + VariableDeclarator node = spy(new VariableDeclarator()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getInitializer(); + verify(node, times(1)).getName(); + verify(node, times(1)).getType(); + verify(node, never()).getComment(); + } + + @Test + void testVisitVoidType() { + VoidType node = spy(new VoidType()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getAnnotations(); + verify(node, never()).getComment(); + } + + @Test + void testVisitWhileStmt() { + WhileStmt node = spy(new WhileStmt()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getBody(); + verify(node, times(1)).getCondition(); + verify(node, never()).getComment(); + } + + @Test + void testVisitWildcardType() { + WildcardType node = spy(new WildcardType()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getExtendedType(); + verify(node, times(1)).getSuperType(); + verify(node, times(1)).getAnnotations(); + verify(node, never()).getComment(); + } + + @Test + void testVisitModuleDeclaration() { + ModuleDeclaration node = spy(new ModuleDeclaration()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getAnnotations(); + verify(node, times(1)).getDirectives(); + verify(node, times(1)).isOpen(); + verify(node, times(1)).getName(); + verify(node, never()).getComment(); + } + + @Test + void testVisitModuleRequiresDirective() { + ModuleRequiresDirective node = spy(new ModuleRequiresDirective()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getModifiers(); + verify(node, times(1)).getName(); + verify(node, never()).getComment(); + } + + @Test + void testVisitModuleExportsDirective() { + ModuleExportsDirective node = spy(new ModuleExportsDirective()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getModuleNames(); + verify(node, times(1)).getName(); + verify(node, never()).getComment(); + } + + @Test + void testVisitModuleProvidesDirective() { + ModuleProvidesDirective node = spy(new ModuleProvidesDirective()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getName(); + verify(node, times(1)).getWith(); + verify(node, never()).getComment(); + } + + @Test + void testVisitModuleUsesDirective() { + ModuleUsesDirective node = spy(new ModuleUsesDirective()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getName(); + verify(node, never()).getComment(); + } + + @Test + void testVisitModuleOpensDirective() { + ModuleOpensDirective node = spy(new ModuleOpensDirective()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getModuleNames(); + verify(node, times(1)).getName(); + verify(node, never()).getComment(); + } + + @Test + void testVisitUnparsableStmt() { + UnparsableStmt node = spy(new UnparsableStmt()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, never()).getComment(); + } + + @Test + void testVisitReceiverParameter() { + ReceiverParameter node = spy(new ReceiverParameter()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getAnnotations(); + verify(node, times(1)).getName(); + verify(node, times(1)).getType(); + verify(node, never()).getComment(); + } + + @Test + void testVisitVarType() { + VarType node = spy(new VarType()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getAnnotations(); + verify(node, never()).getComment(); + } + + @Test + void testVisitModifier() { + Modifier node = spy(new Modifier()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getKeyword(); + verify(node, never()).getComment(); + } + + @Test + void testVisitSwitchExpr() { + SwitchExpr node = spy(new SwitchExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getEntries(); + verify(node, times(1)).getSelector(); + verify(node, never()).getComment(); + } + + @Test + void testVisitYieldStmt() { + YieldStmt node = spy(new YieldStmt()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getExpression(); + verify(node, never()).getComment(); + } + + @Test + void testVisitTextBlockLiteralExpr() { + TextBlockLiteralExpr node = spy(new TextBlockLiteralExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getValue(); + verify(node, never()).getComment(); + } + + @Test + void testVisitPatternExpr() { + PatternExpr node = spy(new PatternExpr()); + NoCommentHashCodeVisitor.hashCode(node); + + verify(node, times(1)).getName(); + verify(node, times(1)).getType(); + verify(node, never()).getComment(); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/NodeFinderVisitorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/NodeFinderVisitorTest.java new file mode 100644 index 0000000..549d358 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/NodeFinderVisitorTest.java @@ -0,0 +1,100 @@ +/* + * Copyright (C) 2013-2024 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.visitor; + +import static com.github.javaparser.StaticJavaParser.parse; +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +import com.github.javaparser.Position; +import com.github.javaparser.Range; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.expr.VariableDeclarationExpr; +import com.github.javaparser.ast.type.Type; + +class NodeFinderVisitorTest { + + NodeFinderVisitor finder = new NodeFinderVisitor(NodeFinderVisitor.fConveringNode); + + @Test + void testNoCoveringNode() { + CompilationUnit cu = parse("class X { }"); + Position position = new Position(0,0); + Range range = new Range(position, position); + cu.accept(finder, range); + assertTrue(finder.getSelectedNode() == null); + } + + @Test + void testClassOrInterfaceDeclarationIsCovering() { + CompilationUnit cu = parse("class X { }"); + ClassOrInterfaceDeclaration cid = cu.findFirst(ClassOrInterfaceDeclaration.class).get(); + Range range = new Range(Position.HOME, Position.HOME); + cu.accept(finder, range); + assertEquals(cid , finder.getSelectedNode()); + } + + @Test + void testClassOrInterfaceDeclarationIsCovering2() { + CompilationUnit cu = parse("class X { }"); + ClassOrInterfaceDeclaration cid = cu.findFirst(ClassOrInterfaceDeclaration.class).get(); + cu.accept(finder, range(1, 11)); + assertEquals(cid , finder.getSelectedNode()); + } + + @Test + void testClassOrInterfaceDeclarationCovering() { + CompilationUnit cu = parse( + "class X {\n" + + " Boolean f;\n" + + "}"); + + ClassOrInterfaceDeclaration cid = cu.findFirst(ClassOrInterfaceDeclaration.class).get(); + cu.accept(finder, range(2, 11)); + assertEquals(cid , finder.getSelectedNode()); + } + + @Test + void testNoCoveringOrCoveredNode2() { + CompilationUnit cu = parse( + "class X {\n" + + " void f() {\n" + + " int i = 0;\n" + + " }\n" + + "}"); + MethodDeclaration md = cu.findFirst(MethodDeclaration.class).get(); + cu.accept(finder, range(3, 11)); + System.out.println(finder.getSelectedNode().toString()); + assertEquals(md.getBody().get() , finder.getSelectedNode()); + } + + private Range range(int line, int length) { + return range(line, 1, length); + } + + private Range range(int line, int begin, int length) { + return new Range(new Position(line, begin), new Position(line, length)); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/ObjectIdentityEqualsVisitorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/ObjectIdentityEqualsVisitorTest.java new file mode 100644 index 0000000..43eb4d8 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/ObjectIdentityEqualsVisitorTest.java @@ -0,0 +1,928 @@ +/* + * Copyright (C) 2013-2024 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.visitor; + +import com.github.javaparser.ast.*; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.comments.BlockComment; +import com.github.javaparser.ast.comments.JavadocComment; +import com.github.javaparser.ast.comments.LineComment; +import com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.modules.*; +import com.github.javaparser.ast.stmt.*; +import com.github.javaparser.ast.type.*; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +class ObjectIdentityEqualsVisitorTest { + + @Test + void equals_GivenCompilationUnit() { + Node nodeA = new CompilationUnit(); + Node nodeB = new CompilationUnit(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenPackageDeclaration() { + Node nodeA = new PackageDeclaration(); + Node nodeB = new PackageDeclaration(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenTypeParameter() { + Node nodeA = new TypeParameter(); + Node nodeB = new TypeParameter(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenLineComment() { + Node nodeA = new LineComment(); + Node nodeB = new LineComment(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenBlockComment() { + Node nodeA = new BlockComment(); + Node nodeB = new BlockComment(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenClassOrInterfaceDeclaration() { + Node nodeA = new ClassOrInterfaceDeclaration(); + Node nodeB = new ClassOrInterfaceDeclaration(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenEnumDeclaration() { + Node nodeA = new EnumDeclaration(); + Node nodeB = new EnumDeclaration(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenEnumConstantDeclaration() { + Node nodeA = new EnumConstantDeclaration(); + Node nodeB = new EnumConstantDeclaration(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenAnnotationDeclaration() { + Node nodeA = new AnnotationDeclaration(); + Node nodeB = new AnnotationDeclaration(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenAnnotationMemberDeclaration() { + Node nodeA = new AnnotationMemberDeclaration(); + Node nodeB = new AnnotationMemberDeclaration(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenFieldDeclaration() { + Node nodeA = new FieldDeclaration(); + Node nodeB = new FieldDeclaration(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenVariableDeclarator() { + Node nodeA = new VariableDeclarator(); + Node nodeB = new VariableDeclarator(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenConstructorDeclaration() { + Node nodeA = new ConstructorDeclaration(); + Node nodeB = new ConstructorDeclaration(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenMethodDeclaration() { + Node nodeA = new MethodDeclaration(); + Node nodeB = new MethodDeclaration(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenParameter() { + Node nodeA = new Parameter(); + Node nodeB = new Parameter(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenInitializerDeclaration() { + Node nodeA = new InitializerDeclaration(); + Node nodeB = new InitializerDeclaration(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenJavadocComment() { + Node nodeA = new JavadocComment(); + Node nodeB = new JavadocComment(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenClassOrInterfaceType() { + Node nodeA = new ClassOrInterfaceType(); + Node nodeB = new ClassOrInterfaceType(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenPrimitiveType() { + Node nodeA = new PrimitiveType(); + Node nodeB = new PrimitiveType(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenArrayType() { + Node nodeA = new ArrayType(new VoidType()); + Node nodeB = new ArrayType(new VoidType()); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenArrayCreationLevel() { + Node nodeA = new ArrayCreationLevel(); + Node nodeB = new ArrayCreationLevel(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenIntersectionType() { + Node nodeA = new IntersectionType(new NodeList<>()); + Node nodeB = new IntersectionType(new NodeList<>()); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenUnionType() { + Node nodeA = new UnionType(); + Node nodeB = new UnionType(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenVoidType() { + Node nodeA = new VoidType(); + Node nodeB = new VoidType(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenWildcardType() { + Node nodeA = new WildcardType(); + Node nodeB = new WildcardType(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenUnknownType() { + Node nodeA = new UnknownType(); + Node nodeB = new UnknownType(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenArrayAccessExpr() { + Node nodeA = new ArrayAccessExpr(); + Node nodeB = new ArrayAccessExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenArrayCreationExpr() { + Node nodeA = new ArrayCreationExpr(); + Node nodeB = new ArrayCreationExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenArrayInitializerExpr() { + Node nodeA = new ArrayInitializerExpr(); + Node nodeB = new ArrayInitializerExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenAssignExpr() { + Node nodeA = new AssignExpr(); + Node nodeB = new AssignExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenBinaryExpr() { + Node nodeA = new BinaryExpr(); + Node nodeB = new BinaryExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenCastExpr() { + Node nodeA = new CastExpr(); + Node nodeB = new CastExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenClassExpr() { + Node nodeA = new ClassExpr(); + Node nodeB = new ClassExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenConditionalExpr() { + Node nodeA = new ConditionalExpr(); + Node nodeB = new ConditionalExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenEnclosedExpr() { + Node nodeA = new EnclosedExpr(); + Node nodeB = new EnclosedExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenFieldAccessExpr() { + Node nodeA = new FieldAccessExpr(); + Node nodeB = new FieldAccessExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenInstanceOfExpr() { + Node nodeA = new InstanceOfExpr(); + Node nodeB = new InstanceOfExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenStringLiteralExpr() { + Node nodeA = new StringLiteralExpr(); + Node nodeB = new StringLiteralExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenIntegerLiteralExpr() { + Node nodeA = new IntegerLiteralExpr(); + Node nodeB = new IntegerLiteralExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenLongLiteralExpr() { + Node nodeA = new LongLiteralExpr(); + Node nodeB = new LongLiteralExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenCharLiteralExpr() { + Node nodeA = new CharLiteralExpr(); + Node nodeB = new CharLiteralExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenDoubleLiteralExpr() { + Node nodeA = new DoubleLiteralExpr(); + Node nodeB = new DoubleLiteralExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenBooleanLiteralExpr() { + Node nodeA = new BooleanLiteralExpr(); + Node nodeB = new BooleanLiteralExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenNullLiteralExpr() { + Node nodeA = new NullLiteralExpr(); + Node nodeB = new NullLiteralExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenMethodCallExpr() { + Node nodeA = new MethodCallExpr(); + Node nodeB = new MethodCallExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenNameExpr() { + Node nodeA = new NameExpr(); + Node nodeB = new NameExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenObjectCreationExpr() { + Node nodeA = new ObjectCreationExpr(); + Node nodeB = new ObjectCreationExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenName() { + Node nodeA = new Name(); + Node nodeB = new Name(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenSimpleName() { + Node nodeA = new SimpleName(); + Node nodeB = new SimpleName(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenThisExpr() { + Node nodeA = new ThisExpr(); + Node nodeB = new ThisExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenSuperExpr() { + Node nodeA = new SuperExpr(); + Node nodeB = new SuperExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenUnaryExpr() { + Node nodeA = new UnaryExpr(); + Node nodeB = new UnaryExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenVariableDeclarationExpr() { + Node nodeA = new VariableDeclarationExpr(); + Node nodeB = new VariableDeclarationExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenMarkerAnnotationExpr() { + Node nodeA = new MarkerAnnotationExpr(); + Node nodeB = new MarkerAnnotationExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenSingleMemberAnnotationExpr() { + Node nodeA = new SingleMemberAnnotationExpr(); + Node nodeB = new SingleMemberAnnotationExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenNormalAnnotationExpr() { + Node nodeA = new NormalAnnotationExpr(); + Node nodeB = new NormalAnnotationExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenMemberValuePair() { + Node nodeA = new MemberValuePair(); + Node nodeB = new MemberValuePair(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenExplicitConstructorInvocationStmt() { + Node nodeA = new ExplicitConstructorInvocationStmt(); + Node nodeB = new ExplicitConstructorInvocationStmt(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenLocalClassDeclarationStmt() { + Node nodeA = new LocalClassDeclarationStmt(); + Node nodeB = new LocalClassDeclarationStmt(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenLocalRecordDeclarationStmt() { + Node nodeA = new LocalRecordDeclarationStmt(); + Node nodeB = new LocalRecordDeclarationStmt(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenAssertStmt() { + Node nodeA = new AssertStmt(); + Node nodeB = new AssertStmt(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenBlockStmt() { + Node nodeA = new BlockStmt(); + Node nodeB = new BlockStmt(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenLabeledStmt() { + Node nodeA = new LabeledStmt(); + Node nodeB = new LabeledStmt(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenEmptyStmt() { + Node nodeA = new EmptyStmt(); + Node nodeB = new EmptyStmt(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenExpressionStmt() { + Node nodeA = new ExpressionStmt(); + Node nodeB = new ExpressionStmt(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenSwitchStmt() { + Node nodeA = new SwitchStmt(); + Node nodeB = new SwitchStmt(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenSwitchEntry() { + Node nodeA = new SwitchEntry(); + Node nodeB = new SwitchEntry(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenBreakStmt() { + Node nodeA = new BreakStmt(); + Node nodeB = new BreakStmt(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenReturnStmt() { + Node nodeA = new ReturnStmt(); + Node nodeB = new ReturnStmt(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenIfStmt() { + Node nodeA = new IfStmt(); + Node nodeB = new IfStmt(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenWhileStmt() { + Node nodeA = new WhileStmt(); + Node nodeB = new WhileStmt(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenContinueStmt() { + Node nodeA = new ContinueStmt(); + Node nodeB = new ContinueStmt(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenDoStmt() { + Node nodeA = new DoStmt(); + Node nodeB = new DoStmt(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenForEachStmt() { + Node nodeA = new ForEachStmt(); + Node nodeB = new ForEachStmt(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenForStmt() { + Node nodeA = new ForStmt(); + Node nodeB = new ForStmt(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenThrowStmt() { + Node nodeA = new ThrowStmt(); + Node nodeB = new ThrowStmt(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenSynchronizedStmt() { + Node nodeA = new SynchronizedStmt(); + Node nodeB = new SynchronizedStmt(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenTryStmt() { + Node nodeA = new TryStmt(); + Node nodeB = new TryStmt(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenCatchClause() { + Node nodeA = new CatchClause(); + Node nodeB = new CatchClause(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenLambdaExpr() { + Node nodeA = new LambdaExpr(); + Node nodeB = new LambdaExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenMethodReferenceExpr() { + Node nodeA = new MethodReferenceExpr(); + Node nodeB = new MethodReferenceExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenTypeExpr() { + Node nodeA = new TypeExpr(); + Node nodeB = new TypeExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenImportDeclaration() { + Node nodeA = new ImportDeclaration("a", false, false); + Node nodeB = new ImportDeclaration("b", false, false); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenModuleDeclaration() { + Node nodeA = new ModuleDeclaration(); + Node nodeB = new ModuleDeclaration(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenModuleRequiresDirective() { + Node nodeA = new ModuleRequiresDirective(); + Node nodeB = new ModuleRequiresDirective(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenModuleExportsDirective() { + Node nodeA = new ModuleExportsDirective(); + Node nodeB = new ModuleExportsDirective(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenModuleProvidesDirective() { + Node nodeA = new ModuleProvidesDirective(); + Node nodeB = new ModuleProvidesDirective(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenModuleUsesDirective() { + Node nodeA = new ModuleUsesDirective(); + Node nodeB = new ModuleUsesDirective(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenModuleOpensDirective() { + Node nodeA = new ModuleOpensDirective(); + Node nodeB = new ModuleOpensDirective(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenUnparsableStmt() { + Node nodeA = new UnparsableStmt(); + Node nodeB = new UnparsableStmt(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenReceiverParameter() { + Node nodeA = new ReceiverParameter(); + Node nodeB = new ReceiverParameter(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenVarType() { + Node nodeA = new VarType(); + Node nodeB = new VarType(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenModifier() { + Node nodeA = new Modifier(); + Node nodeB = new Modifier(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenSwitchExpr() { + Node nodeA = new SwitchExpr(); + Node nodeB = new SwitchExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenYieldStmt() { + Node nodeA = new YieldStmt(); + Node nodeB = new YieldStmt(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenTextBlockLiteralExpr() { + Node nodeA = new TextBlockLiteralExpr(); + Node nodeB = new TextBlockLiteralExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenPatternExpr() { + Node nodeA = new PatternExpr(); + Node nodeB = new PatternExpr(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenRecordDeclaration() { + Node nodeA = new RecordDeclaration(); + Node nodeB = new RecordDeclaration(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + + @Test + void equals_GivenCompactConstructorDeclaration() { + Node nodeA = new CompactConstructorDeclaration(); + Node nodeB = new CompactConstructorDeclaration(); + + Assertions.assertTrue(ObjectIdentityEqualsVisitor.equals(nodeA, nodeA)); + Assertions.assertFalse(ObjectIdentityEqualsVisitor.equals(nodeA, nodeB)); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/ObjectIdentityHashCodeVisitorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/ObjectIdentityHashCodeVisitorTest.java new file mode 100644 index 0000000..4b6e2d8 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/ObjectIdentityHashCodeVisitorTest.java @@ -0,0 +1,625 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.visitor; + +import com.github.javaparser.ast.*; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.comments.BlockComment; +import com.github.javaparser.ast.comments.JavadocComment; +import com.github.javaparser.ast.comments.LineComment; +import com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.modules.*; +import com.github.javaparser.ast.stmt.*; +import com.github.javaparser.ast.type.*; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.ast.type.PrimitiveType.intType; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.spy; + +class ObjectIdentityHashCodeVisitorTest { + + @Test + void testVisitAnnotationDeclaration() { + AnnotationDeclaration node = spy(new AnnotationDeclaration()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitAnnotationMemberDeclaration() { + AnnotationMemberDeclaration node = spy(new AnnotationMemberDeclaration()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitArrayAccessExpr() { + ArrayAccessExpr node = spy(new ArrayAccessExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitArrayCreationExpr() { + ArrayCreationExpr node = spy(new ArrayCreationExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitArrayCreationLevel() { + ArrayCreationLevel node = spy(new ArrayCreationLevel()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitArrayInitializerExpr() { + ArrayInitializerExpr node = spy(new ArrayInitializerExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitArrayType() { + ArrayType node = spy(new ArrayType(intType())); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitAssertStmt() { + AssertStmt node = spy(new AssertStmt()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitAssignExpr() { + AssignExpr node = spy(new AssignExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitBinaryExpr() { + BinaryExpr node = spy(new BinaryExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitBlockComment() { + BlockComment node = spy(new BlockComment()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitBlockStmt() { + BlockStmt node = spy(new BlockStmt()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitBooleanLiteralExpr() { + BooleanLiteralExpr node = spy(new BooleanLiteralExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitBreakStmt() { + BreakStmt node = spy(new BreakStmt()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitCastExpr() { + CastExpr node = spy(new CastExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitCatchClause() { + CatchClause node = spy(new CatchClause()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitCharLiteralExpr() { + CharLiteralExpr node = spy(new CharLiteralExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitClassExpr() { + ClassExpr node = spy(new ClassExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitClassOrInterfaceDeclaration() { + ClassOrInterfaceDeclaration node = spy(new ClassOrInterfaceDeclaration()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitClassOrInterfaceType() { + ClassOrInterfaceType node = spy(new ClassOrInterfaceType()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitCompilationUnit() { + CompilationUnit node = spy(new CompilationUnit()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitConditionalExpr() { + ConditionalExpr node = spy(new ConditionalExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitConstructorDeclaration() { + ConstructorDeclaration node = spy(new ConstructorDeclaration()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitContinueStmt() { + ContinueStmt node = spy(new ContinueStmt()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitDoStmt() { + DoStmt node = spy(new DoStmt()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitDoubleLiteralExpr() { + DoubleLiteralExpr node = spy(new DoubleLiteralExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitEmptyStmt() { + EmptyStmt node = spy(new EmptyStmt()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitEnclosedExpr() { + EnclosedExpr node = spy(new EnclosedExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitEnumConstantDeclaration() { + EnumConstantDeclaration node = spy(new EnumConstantDeclaration()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitEnumDeclaration() { + EnumDeclaration node = spy(new EnumDeclaration()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitExplicitConstructorInvocationStmt() { + ExplicitConstructorInvocationStmt node = spy(new ExplicitConstructorInvocationStmt()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitExpressionStmt() { + ExpressionStmt node = spy(new ExpressionStmt()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitFieldAccessExpr() { + FieldAccessExpr node = spy(new FieldAccessExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitFieldDeclaration() { + FieldDeclaration node = spy(new FieldDeclaration()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitForEachStmt() { + ForEachStmt node = spy(new ForEachStmt()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitForStmt() { + ForStmt node = spy(new ForStmt()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitIfStmt() { + IfStmt node = spy(new IfStmt()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitImportDeclaration() { + ImportDeclaration node = spy(new ImportDeclaration(new Name(), false, false)); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitInitializerDeclaration() { + InitializerDeclaration node = spy(new InitializerDeclaration()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitInstanceOfExpr() { + InstanceOfExpr node = spy(new InstanceOfExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitIntegerLiteralExpr() { + IntegerLiteralExpr node = spy(new IntegerLiteralExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitIntersectionType() { + NodeList elements = new NodeList<>(); + elements.add(new ClassOrInterfaceType()); + IntersectionType node = spy(new IntersectionType(elements)); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitJavadocComment() { + JavadocComment node = spy(new JavadocComment()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitLabeledStmt() { + LabeledStmt node = spy(new LabeledStmt()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitLambdaExpr() { + LambdaExpr node = spy(new LambdaExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitLineComment() { + LineComment node = spy(new LineComment()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitLocalClassDeclarationStmt() { + LocalClassDeclarationStmt node = spy(new LocalClassDeclarationStmt()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitLocalRecordDeclarationStmt() { + LocalRecordDeclarationStmt node = spy(new LocalRecordDeclarationStmt()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitLongLiteralExpr() { + LongLiteralExpr node = spy(new LongLiteralExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitMarkerAnnotationExpr() { + MarkerAnnotationExpr node = spy(new MarkerAnnotationExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitMemberValuePair() { + MemberValuePair node = spy(new MemberValuePair()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitMethodCallExpr() { + MethodCallExpr node = spy(new MethodCallExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitMethodDeclaration() { + MethodDeclaration node = spy(new MethodDeclaration()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitMethodReferenceExpr() { + MethodReferenceExpr node = spy(new MethodReferenceExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitModifier() { + Modifier node = spy(new Modifier()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitModuleDeclaration() { + ModuleDeclaration node = spy(new ModuleDeclaration()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitModuleExportsDirective() { + ModuleExportsDirective node = spy(new ModuleExportsDirective()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitModuleOpensDirective() { + ModuleOpensDirective node = spy(new ModuleOpensDirective()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitModuleProvidesDirective() { + ModuleProvidesDirective node = spy(new ModuleProvidesDirective()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitModuleRequiresDirective() { + ModuleRequiresDirective node = spy(new ModuleRequiresDirective()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitModuleUsesDirective() { + ModuleUsesDirective node = spy(new ModuleUsesDirective()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitNameExpr() { + NameExpr node = spy(new NameExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitName() { + Name node = spy(new Name()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitNormalAnnotationExpr() { + NormalAnnotationExpr node = spy(new NormalAnnotationExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitNullLiteralExpr() { + NullLiteralExpr node = spy(new NullLiteralExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitObjectCreationExpr() { + ObjectCreationExpr node = spy(new ObjectCreationExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitPackageDeclaration() { + PackageDeclaration node = spy(new PackageDeclaration()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitParameter() { + Parameter node = spy(new Parameter()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitPatternExpr() { + PatternExpr node = spy(new PatternExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitPrimitiveType() { + PrimitiveType node = spy(new PrimitiveType()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitReceiverParameter() { + ReceiverParameter node = spy(new ReceiverParameter()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitReturnStmt() { + ReturnStmt node = spy(new ReturnStmt()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitSimpleName() { + SimpleName node = spy(new SimpleName()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitSingleMemberAnnotationExpr() { + SingleMemberAnnotationExpr node = spy(new SingleMemberAnnotationExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitStringLiteralExpr() { + StringLiteralExpr node = spy(new StringLiteralExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitSuperExpr() { + SuperExpr node = spy(new SuperExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitSwitchEntry() { + SwitchEntry node = spy(new SwitchEntry()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitSwitchExpr() { + SwitchExpr node = spy(new SwitchExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitSwitchStmt() { + SwitchStmt node = spy(new SwitchStmt()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitSynchronizedStmt() { + SynchronizedStmt node = spy(new SynchronizedStmt()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitTextBlockLiteralExpr() { + TextBlockLiteralExpr node = spy(new TextBlockLiteralExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitThisExpr() { + ThisExpr node = spy(new ThisExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitThrowStmt() { + ThrowStmt node = spy(new ThrowStmt()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitTryStmt() { + TryStmt node = spy(new TryStmt()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitTypeExpr() { + TypeExpr node = spy(new TypeExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitTypeParameter() { + TypeParameter node = spy(new TypeParameter()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitUnaryExpr() { + UnaryExpr node = spy(new UnaryExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitUnionType() { + UnionType node = spy(new UnionType()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitUnknownType() { + UnknownType node = spy(new UnknownType()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitUnparsableStmt() { + UnparsableStmt node = spy(new UnparsableStmt()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitVarType() { + VarType node = spy(new VarType()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitVariableDeclarationExpr() { + VariableDeclarationExpr node = spy(new VariableDeclarationExpr()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitVariableDeclarator() { + VariableDeclarator node = spy(new VariableDeclarator()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitVoidType() { + VoidType node = spy(new VoidType()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitWhileStmt() { + WhileStmt node = spy(new WhileStmt()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitWildcardType() { + WildcardType node = spy(new WildcardType()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + + @Test + void testVisitYieldStmt() { + YieldStmt node = spy(new YieldStmt()); + assertEquals(node.hashCode(), ObjectIdentityHashCodeVisitor.hashCode(node)); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/TreeVisitorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/TreeVisitorTest.java new file mode 100644 index 0000000..eb0fec1 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/TreeVisitorTest.java @@ -0,0 +1,160 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.visitor; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.expr.ArrayInitializerExpr; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.expr.IntegerLiteralExpr; +import com.github.javaparser.ast.expr.SimpleName; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.StaticJavaParser.parse; +import static com.github.javaparser.StaticJavaParser.parseExpression; +import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +class TreeVisitorTest { + @Test + void isValidBreadthFirstTraversal() { + Expression expression = parseExpression("(2+3)+(4+5)"); + + StringBuilder result = new StringBuilder(); + + TreeVisitor visitor = new TreeVisitor() { + @Override + public void process(Node node) { + result.append("<").append(node).append("> "); + } + }; + + visitor.visitBreadthFirst(expression); + assertEquals("<(2 + 3) + (4 + 5)> <(2 + 3)> <(4 + 5)> <2 + 3> <4 + 5> <2> <3> <4> <5> ", result.toString()); + } + + @Test + void issue743ConcurrentModificationProblem() { + Expression expression = parseExpression("new int[]{1,2,3,4}"); + + StringBuilder result = new StringBuilder(); + TreeVisitor visitor = new TreeVisitor() { + @Override + public void process(Node node) { + if (node instanceof IntegerLiteralExpr) { + node.getParentNode().ifPresent( + parent -> ((ArrayInitializerExpr) parent).getValues().add(new IntegerLiteralExpr("1"))); + } + result.append("<").append(node).append("> "); + } + }; + visitor.visitPreOrder(expression); +// System.out.println(result); + } + + @Test + void isValidPreOrderTraversal() { + StringBuilder result = new StringBuilder(); + new TreeVisitor() { + @Override + public void process(Node node) { + result.append("<").append(node).append("> "); + } + }.visitPreOrder(parseExpression("(2+3)+(4+5)")); + assertEquals("<(2 + 3) + (4 + 5)> <(2 + 3)> <2 + 3> <2> <3> <(4 + 5)> <4 + 5> <4> <5> ", result.toString()); + } + + @Test + void isValidPostOrderTraversal() { + StringBuilder result = new StringBuilder(); + new TreeVisitor() { + @Override + public void process(Node node) { + result.append("<").append(node).append("> "); + } + }.visitPostOrder(parseExpression("(2+3)+(4+5)")); + assertEquals("<2> <3> <2 + 3> <(2 + 3)> <4> <5> <4 + 5> <(4 + 5)> <(2 + 3) + (4 + 5)> ", result.toString()); + } + + @Test + void preOrderConcurrentModificationIsOk() { + new TreeVisitor() { + @Override + public void process(Node node) { + if (node instanceof IntegerLiteralExpr) { + node.getParentNode().ifPresent( + parent -> ((ArrayInitializerExpr) parent).getValues().add(new IntegerLiteralExpr("1"))); + } + } + }.visitPreOrder(parseExpression("new int[]{1,2,3,4}")); + } + + @Test + void postOrderConcurrentModificationIsOk() { + new TreeVisitor() { + @Override + public void process(Node node) { + if (node instanceof IntegerLiteralExpr) { + node.getParentNode().ifPresent( + parent -> ((ArrayInitializerExpr) parent).getValues().add(new IntegerLiteralExpr("1"))); + } + } + }.visitPostOrder(parseExpression("new int[]{1,2,3,4}")); + } + + @Test + void parents() { + CompilationUnit cu = parse("class X{int x=1;}"); + SimpleName x = cu.getClassByName("X").get().getMember(0).asFieldDeclaration().getVariable(0).getName(); + + Node.ParentsVisitor visitor = new Node.ParentsVisitor(x); + assertEquals("x = 1", visitor.next().toString()); + assertEquals("int x = 1;", visitor.next().toString()); + assertEqualsStringIgnoringEol("class X {\n" + + "\n" + + " int x = 1;\n" + + "}", visitor.next().toString()); + assertEqualsStringIgnoringEol("class X {\n" + + "\n" + + " int x = 1;\n" + + "}\n", visitor.next().toString()); + assertFalse(visitor.hasNext()); + } + + @Test + void isValidDirectChildrenTraversal() { + Expression expression = parseExpression("(2+3)+(4+5)"); + + StringBuilder result = new StringBuilder(); + + TreeVisitor visitor = new TreeVisitor() { + @Override + public void process(Node node) { + result.append("<").append(node).append("> "); + } + }; + + visitor.visitDirectChildren(expression); + assertEquals("<(2 + 3)> <(4 + 5)> ", result.toString()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/VoidVisitorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/VoidVisitorTest.java new file mode 100644 index 0000000..8da3807 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/VoidVisitorTest.java @@ -0,0 +1,81 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.visitor; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.expr.ObjectCreationExpr; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +public class VoidVisitorTest { + @Test() + void compareFindAllSizeWithVoidVisitorAdapterSize() throws IOException { + CompilationUnit unit = createUnit(); + + List oce = unit.findAll(ObjectCreationExpr.class); + + AtomicInteger foundObjs = new AtomicInteger(0); + unit.accept(new VoidVisitorAdapter() { + @Override + public void visit(ObjectCreationExpr exp, Object arg) { + super.visit(exp, arg); + ((AtomicInteger)arg).incrementAndGet(); + } + }, foundObjs); + + Assertions.assertEquals(oce.size(), foundObjs.get()); + } + + private CompilationUnit createUnit() { + JavaParser javaParser = new JavaParser(); + + CompilationUnit unit = javaParser.parse("public class Test\n" + + "{\n" + + " public class InnerTest\n" + + " {\n" + + " public InnerTest() {}\n" + + " }\n" + + " \n" + + " public Test() {\n" + + " }\n" + + "\n" + + " public static void main( String[] args ) { \n" + + " new Test().new InnerTest();\n" + + " }\n" + + "}").getResult().get(); + return unit; + } + + @Test() + void testFindAllSize() throws IOException { + CompilationUnit unit = createUnit(); + + List oce = unit.findAll(ObjectCreationExpr.class); + + Assertions.assertEquals(2, oce.size()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/VoidVisitorWithDefaultsTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/VoidVisitorWithDefaultsTest.java new file mode 100644 index 0000000..473adda --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/ast/visitor/VoidVisitorWithDefaultsTest.java @@ -0,0 +1,705 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General 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 License for more details. + */ + +package com.github.javaparser.ast.visitor; + +import com.github.javaparser.ast.*; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.comments.BlockComment; +import com.github.javaparser.ast.comments.JavadocComment; +import com.github.javaparser.ast.comments.LineComment; +import com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.modules.*; +import com.github.javaparser.ast.stmt.*; +import com.github.javaparser.ast.type.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; + +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.mockito.Mockito.*; +import static org.mockito.MockitoAnnotations.openMocks; + +/** + * This class contains the tests to validate VoidVisitorWithDefaults. + * + * @author 4everTheOne + */ +class VoidVisitorWithDefaultsTest { + + @Captor + private ArgumentCaptor argumentCaptor; + + private Object argument; + private VoidVisitorWithDefaults visitor; + + @BeforeEach + void initialize() { + openMocks(this); + + argument = new Object(); + visitor = spy( + new VoidVisitorWithDefaults() {} + ); + } + + @Test + void testThatVisitWithNodeListMethodAsParameter() { + NodeList nodeList = new NodeList<>(); + visitor.visit(nodeList, argument); + + // Verify that the call was executed + verify(visitor, times(1)).visit(same(nodeList), argumentCaptor.capture()); + verify(visitor, times(1)).defaultAction(same(nodeList), same(argumentCaptor.getValue())); + assertSame(argument, argumentCaptor.getValue()); + verifyNoMoreInteractions(visitor); + } + + @Test + void testThatVisitWithAnnotationDeclarationMethodAsParameterCallsDefaultAction() { + visitor.visit(mock(AnnotationDeclaration.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithAnnotationMemberDeclarationMethodAsParameterCallsDefaultAction() { + visitor.visit(mock(AnnotationMemberDeclaration.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithArrayAccessExprMethodAsParameterCallsDefaultAction() { + visitor.visit(mock(ArrayAccessExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithArrayCreationExprMethodAsParameterCallsDefaultAction() { + visitor.visit(mock(ArrayCreationExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithArrayInitializerExprMethodAsParameterCallsDefaultAction() { + visitor.visit(mock(ArrayInitializerExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithAssertStmtMethodAsParameterCallsDefaultAction() { + visitor.visit(mock(AssertStmt.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithBlockStmtAsParameterCallDefaultAction() { + visitor.visit(mock(BlockStmt.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithBooleanLiteralExprAsParameterCallDefaultAction() { + visitor.visit(mock(BooleanLiteralExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithBreakStmtAsParameterCallDefaultAction() { + visitor.visit(mock(BreakStmt.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithCastExprAsParameterCallDefaultAction() { + visitor.visit(mock(CastExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithCatchClauseAsParameterCallDefaultAction() { + visitor.visit(mock(CatchClause.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithCharLiteralExprAsParameterCallDefaultAction() { + visitor.visit(mock(CharLiteralExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithClassExprAsParameterCallDefaultAction() { + visitor.visit(mock(ClassExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithClassOrInterfaceDeclarationAsParameterCallDefaultAction() { + visitor.visit(mock(ClassOrInterfaceDeclaration.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithClassOrInterfaceTypeAsParameterCallDefaultAction() { + visitor.visit(mock(ClassOrInterfaceType.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithCompilationUnitAsParameterCallDefaultAction() { + visitor.visit(mock(CompilationUnit.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithConditionalExprAsParameterCallDefaultAction() { + visitor.visit(mock(ConditionalExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithConstructorDeclarationAsParameterCallDefaultAction() { + visitor.visit(mock(ConstructorDeclaration.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithContinueStmtAsParameterCallDefaultAction() { + visitor.visit(mock(ContinueStmt.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithDoStmtAsParameterCallDefaultAction() { + visitor.visit(mock(DoStmt.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithDoubleLiteralExprAsParameterCallDefaultAction() { + visitor.visit(mock(DoubleLiteralExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithAnnotationDeclarationAsParameterCallDefaultAction() { + visitor.visit(mock(AnnotationDeclaration.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithAnnotationMemberDeclarationAsParameterCallDefaultAction() { + visitor.visit(mock(AnnotationMemberDeclaration.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithArrayAccessExprAsParameterCallDefaultAction() { + visitor.visit(mock(ArrayAccessExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithArrayCreationExprAsParameterCallDefaultAction() { + visitor.visit(mock(ArrayCreationExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithArrayCreationLevelAsParameterCallDefaultAction() { + visitor.visit(mock(ArrayCreationLevel.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithArrayInitializerExprAsParameterCallDefaultAction() { + visitor.visit(mock(ArrayInitializerExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithArrayTypeAsParameterCallDefaultAction() { + visitor.visit(mock(ArrayType.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithAssertStmtAsParameterCallDefaultAction() { + visitor.visit(mock(AssertStmt.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithAssignExprAsParameterCallDefaultAction() { + visitor.visit(mock(AssignExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithBinaryExprAsParameterCallDefaultAction() { + visitor.visit(mock(BinaryExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithBlockCommentAsParameterCallDefaultAction() { + visitor.visit(mock(BlockComment.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithEmptyStmtAsParameterCallDefaultAction() { + visitor.visit(mock(EmptyStmt.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithEnclosedExprAsParameterCallDefaultAction() { + visitor.visit(mock(EnclosedExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithEnumConstantDeclarationAsParameterCallDefaultAction() { + visitor.visit(mock(EnumConstantDeclaration.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithEnumDeclarationAsParameterCallDefaultAction() { + visitor.visit(mock(EnumDeclaration.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithExplicitConstructorInvocationStmtAsParameterCallDefaultAction() { + visitor.visit(mock(ExplicitConstructorInvocationStmt.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithExpressionStmtAsParameterCallDefaultAction() { + visitor.visit(mock(ExpressionStmt.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithFieldAccessExprAsParameterCallDefaultAction() { + visitor.visit(mock(FieldAccessExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithFieldDeclarationAsParameterCallDefaultAction() { + visitor.visit(mock(FieldDeclaration.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithForEachStmtAsParameterCallDefaultAction() { + visitor.visit(mock(ForEachStmt.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithForStmtAsParameterCallDefaultAction() { + visitor.visit(mock(ForStmt.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithIfStmtAsParameterCallDefaultAction() { + visitor.visit(mock(IfStmt.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithImportDeclarationAsParameterCallDefaultAction() { + visitor.visit(mock(ImportDeclaration.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithInitializerDeclarationAsParameterCallDefaultAction() { + visitor.visit(mock(InitializerDeclaration.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithInstanceOfExprAsParameterCallDefaultAction() { + visitor.visit(mock(InstanceOfExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithIntegerLiteralExprAsParameterCallDefaultAction() { + visitor.visit(mock(IntegerLiteralExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithIntersectionTypeAsParameterCallDefaultAction() { + visitor.visit(mock(IntersectionType.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithJavadocCommentAsParameterCallDefaultAction() { + visitor.visit(mock(JavadocComment.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithLabeledStmtAsParameterCallDefaultAction() { + visitor.visit(mock(LabeledStmt.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithLambdaExprAsParameterCallDefaultAction() { + visitor.visit(mock(LambdaExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithLineCommentAsParameterCallDefaultAction() { + visitor.visit(mock(LineComment.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithLocalClassDeclarationStmtAsParameterCallDefaultAction() { + visitor.visit(mock(LocalClassDeclarationStmt.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithLocalRecordDeclarationStmtAsParameterCallDefaultAction() { + visitor.visit(mock(LocalRecordDeclarationStmt.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithLongLiteralExprAsParameterCallDefaultAction() { + visitor.visit(mock(LongLiteralExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithMarkerAnnotationExprAsParameterCallDefaultAction() { + visitor.visit(mock(MarkerAnnotationExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithMemberValuePairAsParameterCallDefaultAction() { + visitor.visit(mock(MemberValuePair.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithMethodCallExprAsParameterCallDefaultAction() { + visitor.visit(mock(MethodCallExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithMethodDeclarationAsParameterCallDefaultAction() { + visitor.visit(mock(MethodDeclaration.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithMethodReferenceExprAsParameterCallDefaultAction() { + visitor.visit(mock(MethodReferenceExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithModifierAsParameterCallDefaultAction() { + visitor.visit(mock(Modifier.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithModuleDeclarationAsParameterCallDefaultAction() { + visitor.visit(mock(ModuleDeclaration.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithModuleExportsDirectiveAsParameterCallDefaultAction() { + visitor.visit(mock(ModuleExportsDirective.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithModuleOpensDirectiveAsParameterCallDefaultAction() { + visitor.visit(mock(ModuleOpensDirective.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithModuleProvidesDirectiveAsParameterCallDefaultAction() { + visitor.visit(mock(ModuleProvidesDirective.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithModuleRequiresDirectiveAsParameterCallDefaultAction() { + visitor.visit(mock(ModuleRequiresDirective.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithModuleUsesDirectiveAsParameterCallDefaultAction() { + visitor.visit(mock(ModuleUsesDirective.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithNameExprAsParameterCallDefaultAction() { + visitor.visit(mock(NameExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithNameAsParameterCallDefaultAction() { + visitor.visit(mock(Name.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithNormalAnnotationExprAsParameterCallDefaultAction() { + visitor.visit(mock(NormalAnnotationExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithNullLiteralExprAsParameterCallDefaultAction() { + visitor.visit(mock(NullLiteralExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithObjectCreationExprAsParameterCallDefaultAction() { + visitor.visit(mock(ObjectCreationExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithPackageDeclarationAsParameterCallDefaultAction() { + visitor.visit(mock(PackageDeclaration.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithParameterAsParameterCallDefaultAction() { + visitor.visit(mock(Parameter.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithPatternExprAsParameterCallDefaultAction() { + visitor.visit(mock(PatternExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithPrimitiveTypeAsParameterCallDefaultAction() { + visitor.visit(mock(PrimitiveType.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithReceiverParameterAsParameterCallDefaultAction() { + visitor.visit(mock(ReceiverParameter.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithReturnStmtAsParameterCallDefaultAction() { + visitor.visit(mock(ReturnStmt.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithSimpleNameAsParameterCallDefaultAction() { + visitor.visit(mock(SimpleName.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithSingleMemberAnnotationExprAsParameterCallDefaultAction() { + visitor.visit(mock(SingleMemberAnnotationExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithStringLiteralExprAsParameterCallDefaultAction() { + visitor.visit(mock(StringLiteralExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithSuperExprAsParameterCallDefaultAction() { + visitor.visit(mock(SuperExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithSwitchEntryAsParameterCallDefaultAction() { + visitor.visit(mock(SwitchEntry.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithSwitchExprAsParameterCallDefaultAction() { + visitor.visit(mock(SwitchExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithSwitchStmtAsParameterCallDefaultAction() { + visitor.visit(mock(SwitchStmt.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithSynchronizedStmtAsParameterCallDefaultAction() { + visitor.visit(mock(SynchronizedStmt.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithTextBlockLiteralExprAsParameterCallDefaultAction() { + visitor.visit(mock(TextBlockLiteralExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithThisExprAsParameterCallDefaultAction() { + visitor.visit(mock(ThisExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithThrowStmtAsParameterCallDefaultAction() { + visitor.visit(mock(ThrowStmt.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithTryStmtAsParameterCallDefaultAction() { + visitor.visit(mock(TryStmt.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithTypeExprAsParameterCallDefaultAction() { + visitor.visit(mock(TypeExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithTypeParameterAsParameterCallDefaultAction() { + visitor.visit(mock(TypeParameter.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithUnaryExprAsParameterCallDefaultAction() { + visitor.visit(mock(UnaryExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithUnionTypeAsParameterCallDefaultAction() { + visitor.visit(mock(UnionType.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithUnknownTypeAsParameterCallDefaultAction() { + visitor.visit(mock(UnknownType.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithUnparsableStmtAsParameterCallDefaultAction() { + visitor.visit(mock(UnparsableStmt.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithVarTypeAsParameterCallDefaultAction() { + visitor.visit(mock(VarType.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithVariableDeclarationExprAsParameterCallDefaultAction() { + visitor.visit(mock(VariableDeclarationExpr.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithVariableDeclaratorCallDefaultAction() { + visitor.visit(mock(VariableDeclarator.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithVoidTypeAsParameterCallDefaultAction() { + visitor.visit(mock(VoidType.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithWhileStmtAsParameterCallDefaultAction() { + visitor.visit(mock(WhileStmt.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithWildcardTypeAsParameterCallDefaultAction() { + visitor.visit(mock(WildcardType.class), argument); + assertNodeVisitDefaultAction(); + } + + @Test + void testThatVisitWithYieldStmtAsParameterCallDefaultAction() { + visitor.visit(mock(YieldStmt.class), argument); + assertNodeVisitDefaultAction(); + } + + /** + * Assert that at the default methods was called only once and with the same argument. + */ + void assertNodeVisitDefaultAction() { + // Check if the default method was only called once + verify(visitor, times(1)).defaultAction(isA(Node.class), argumentCaptor.capture()); + // Check if the original argument was passed to the default method + assertSame(argument, argumentCaptor.getValue()); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/builders/ClassOrInterfaceDeclarationBuildersTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/builders/ClassOrInterfaceDeclarationBuildersTest.java new file mode 100644 index 0000000..84147c3 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/builders/ClassOrInterfaceDeclarationBuildersTest.java @@ -0,0 +1,70 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.builders; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.function.Function; + +import static com.github.javaparser.utils.Utils.SYSTEM_EOL; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ClassOrInterfaceDeclarationBuildersTest { + CompilationUnit cu; + + @BeforeEach + void setup() { + cu = new CompilationUnit(); + } + + @AfterEach + void teardown() { + cu = null; + } + + @Test + void testAddExtends() { + ClassOrInterfaceDeclaration testClass = cu.addClass("test"); + testClass.addExtendedType(List.class); + assertEquals(1, cu.getImports().size()); + assertEquals("import " + List.class.getName() + ";" + SYSTEM_EOL, + cu.getImport(0).toString()); + assertEquals(1, testClass.getExtendedTypes().size()); + assertEquals(List.class.getSimpleName(), testClass.getExtendedTypes(0).getNameAsString()); + } + + @Test + void testAddImplements() { + ClassOrInterfaceDeclaration testClass = cu.addClass("test"); + testClass.addImplementedType(Function.class); + assertEquals(1, cu.getImports().size()); + assertEquals("import " + Function.class.getName() + ";" + SYSTEM_EOL, + cu.getImport(0).toString()); + assertEquals(1, testClass.getImplementedTypes().size()); + assertEquals(Function.class.getSimpleName(), testClass.getImplementedTypes(0).getNameAsString()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/builders/CompilationUnitBuildersTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/builders/CompilationUnitBuildersTest.java new file mode 100644 index 0000000..c92e392 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/builders/CompilationUnitBuildersTest.java @@ -0,0 +1,292 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.builders; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.PackageDeclaration; +import com.github.javaparser.ast.body.AnnotationDeclaration; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.EnumDeclaration; +import com.github.javaparser.ast.body.RecordDeclaration; +import com.github.javaparser.ast.expr.Name; +import org.junit.jupiter.api.Test; + +import java.lang.annotation.ElementType; +import java.util.Comparator; +import java.util.List; +import java.util.Map; + +import static com.github.javaparser.StaticJavaParser.parseImport; +import static com.github.javaparser.ast.Modifier.Keyword.PRIVATE; +import static com.github.javaparser.ast.Modifier.Keyword.PUBLIC; +import static com.github.javaparser.utils.Utils.SYSTEM_EOL; +import static org.junit.jupiter.api.Assertions.*; + +class CompilationUnitBuildersTest { + private final CompilationUnit cu = new CompilationUnit(); + + @Test + void testAddImport() { + // duplicate imports + cu.addImport(Map.class); + cu.addImport(Map.class); + cu.addImport(Map.class.getCanonicalName()); + cu.addImport(List.class); + assertEquals(2, cu.getImports().size()); + + cu.addImport(com.github.javaparser.StaticJavaParser.class.getCanonicalName() + ".parseImport", true, false); + assertEquals(3, cu.getImports().size()); + + assertEquals("import " + Map.class.getCanonicalName() + ";" + SYSTEM_EOL, cu.getImport(0).toString()); + assertEquals("import " + List.class.getCanonicalName() + ";" + SYSTEM_EOL, cu.getImport(1).toString()); + assertEquals("import static " + com.github.javaparser.StaticJavaParser.class.getCanonicalName() + ".parseImport;" + SYSTEM_EOL, + cu.getImport(2).toString()); + } + + public class $tartsWith$ { + } + + @Test + public void test$ImportStarts() { + cu.addImport($tartsWith$.class); + cu.addImport("my.$tartsWith$"); + assertEquals(2, cu.getImports().size()); + assertEquals("import " + $tartsWith$.class.getCanonicalName() + ";" + SYSTEM_EOL, cu.getImport(0).toString()); + assertEquals("import my.$tartsWith$;" + SYSTEM_EOL, cu.getImport(1).toString()); + } + + public class F$F { + } + + @Test + public void test$Import() { + cu.addImport(F$F.class); + cu.addImport("my.F$F"); + // doesnt fail, but imports class "F.F" + assertEquals(2, cu.getImports().size()); + assertEquals("import " + F$F.class.getCanonicalName() + ";" + SYSTEM_EOL, cu.getImport(0).toString()); + assertEquals("import my.F$F;" + SYSTEM_EOL, cu.getImport(1).toString()); + } + + @Test + void ignoreJavaLangImports() { + cu.addImport("java.lang.Long"); + cu.addImport("java.lang.*"); + cu.addImport(String.class); + assertEquals(0, cu.getImports().size()); + } + + @Test + void ignoreImportsWithinSamePackage() { + cu.setPackageDeclaration(new PackageDeclaration(new Name(new Name("one"), "two"))); + cu.addImport("one.two.IgnoreImportWithinSamePackage"); + assertEquals(0, cu.getImports().size()); + cu.addImport("one.two.three.DoNotIgnoreImportWithinSubPackage"); + assertEquals(1, cu.getImports().size()); + assertEquals("import one.two.three.DoNotIgnoreImportWithinSubPackage;" + SYSTEM_EOL, cu.getImport(0).toString()); + } + + @Test + void throwIllegalArgumentExceptionOnImportingAnonymousClass() { + assertThrows(IllegalArgumentException.class, () -> cu.addImport(new Comparator() { + + @Override + public int compare(Long o1, Long o2) { + return o1.compareTo(o2); + } + }.getClass())); + } + + @Test + void throwIllegalArgumentExceptionOnImportingLocalClass() { + class LocalClass implements Comparator { + + @Override + public int compare(Long o1, Long o2) { + return o1.compareTo(o2); + } + } + Class localClass = LocalClass.class; + assertThrows(IllegalArgumentException.class, () -> cu.addImport(localClass)); + } + + @Test + void ignoreImportsOfDefaultPackageClasses() { + cu.addImport("MyImport"); + assertEquals(0, cu.getImports().size()); + } + + @Test + void duplicateByAsterisk() { + // check asterisk imports + cu.addImport("my", false, true); + cu.addImport("my.Import"); + cu.addImport("my.AnotherImport"); + cu.addImport("my.other.Import"); + assertEquals(2, cu.getImports().size()); + assertEquals("import my.*;" + SYSTEM_EOL, cu.getImport(0).toString()); + assertEquals("import my.other.Import;" + SYSTEM_EOL, cu.getImport(1).toString()); + cu.addImport("my.other.*"); + assertEquals(2, cu.getImports().size()); + assertEquals("import my.*;" + SYSTEM_EOL, cu.getImport(0).toString()); + assertEquals("import my.other.*;" + SYSTEM_EOL, cu.getImport(1).toString()); + } + + @Test + void typesInTheJavaLangPackageDoNotNeedExplicitImports() { + cu.addImport(String.class); + assertEquals(0, cu.getImports().size()); + } + + @Test + void typesInSubPackagesOfTheJavaLangPackageRequireExplicitImports() { + cu.addImport(ElementType.class); + assertEquals(1, cu.getImports().size()); + assertEquals("import java.lang.annotation.ElementType;" + SYSTEM_EOL, cu.getImport(0).toString()); + } + + @Test + void doNotAddDuplicateImportsByClass() { + cu.addImport(Map.class); + cu.addImport(Map.class); + assertEquals(1, cu.getImports().size()); + } + + @Test + void doNotAddDuplicateImportsByString() { + cu.addImport(Map.class); + cu.addImport("java.util.Map"); + assertEquals(1, cu.getImports().size()); + } + + @Test + void doNotAddDuplicateImportsByStringAndFlags() { + cu.addImport(Map.class); + cu.addImport("java.util.Map", false, false); + assertEquals(1, cu.getImports().size()); + } + + @Test + void doNotAddDuplicateImportsByImportDeclaration() { + cu.addImport(Map.class); + cu.addImport(parseImport("import java.util.Map;")); + assertEquals(1, cu.getImports().size()); + } + + @Test + void testAddImportArrayTypes() { + cu.addImport(CompilationUnit[][][].class); + cu.addImport(int[][][].class); + cu.addImport(Integer[][][].class); + cu.addImport(List[][][].class); + assertEquals(2, cu.getImports().size()); + assertEquals("com.github.javaparser.ast.CompilationUnit", cu.getImport(0).getNameAsString()); + assertEquals("java.util.List", cu.getImport(1).getNameAsString()); + } + + class testInnerClass { + + } + + @Test + void testAddImportAnonymousClass() { + cu.addImport(testInnerClass.class); + assertEquals("import " + testInnerClass.class.getCanonicalName().replace("$", ".") + ";" + SYSTEM_EOL, + cu.getImport(0).toString()); + } + + @Test + void testAddClass() { + ClassOrInterfaceDeclaration myClassDeclaration = cu.addClass("testClass", PRIVATE); + assertEquals(1, cu.getTypes().size()); + assertEquals("testClass", cu.getType(0).getNameAsString()); + assertEquals(ClassOrInterfaceDeclaration.class, cu.getType(0).getClass()); + assertTrue(myClassDeclaration.isPrivate()); + assertFalse(myClassDeclaration.isInterface()); + } + + @Test + void testAddInterface() { + ClassOrInterfaceDeclaration myInterfaceDeclaration = cu.addInterface("testInterface"); + assertEquals(1, cu.getTypes().size()); + assertEquals("testInterface", cu.getType(0).getNameAsString()); + assertTrue(myInterfaceDeclaration.isPublic()); + assertEquals(ClassOrInterfaceDeclaration.class, cu.getType(0).getClass()); + assertTrue(myInterfaceDeclaration.isInterface()); + } + + @Test + void testAddEnum() { + EnumDeclaration myEnumDeclaration = cu.addEnum("test"); + assertEquals(1, cu.getTypes().size()); + assertEquals("test", cu.getType(0).getNameAsString()); + assertTrue(myEnumDeclaration.isPublic()); + assertEquals(EnumDeclaration.class, cu.getType(0).getClass()); + } + + @Test + void testAddAnnotationDeclaration() { + AnnotationDeclaration myAnnotationDeclaration = cu.addAnnotationDeclaration("test"); + assertEquals(1, cu.getTypes().size()); + assertEquals("test", cu.getType(0).getNameAsString()); + assertTrue(myAnnotationDeclaration.isPublic()); + assertEquals(AnnotationDeclaration.class, cu.getType(0).getClass()); + } + + @Test + void testAddTypeWithRecordDeclaration() { + RecordDeclaration myRecordDeclaration = new RecordDeclaration(Modifier.createModifierList(PUBLIC), "test"); + cu.addType(myRecordDeclaration); + assertEquals(1, cu.getTypes().size()); + assertEquals("test", cu.getType(0).getNameAsString()); + assertTrue(myRecordDeclaration.isPublic()); + assertTrue(myRecordDeclaration.isFinal()); + assertEquals(RecordDeclaration.class, cu.getType(0).getClass()); + } + + @Test + void testGetClassByName() { + assertEquals(cu.addClass("test"), cu.getClassByName("test").get()); + } + + @Test + void testGetInterfaceByName() { + assertEquals(cu.addInterface("test"), cu.getInterfaceByName("test").get()); + } + + @Test + void testGetEnumByName() { + assertEquals(cu.addEnum("test"), cu.getEnumByName("test").get()); + } + + @Test + void testGetAnnotationDeclarationByName() { + assertEquals(cu.addAnnotationDeclaration("test"), cu.getAnnotationDeclarationByName("test").get()); + } + + @Test + void testGetRecordByName() { + assertEquals(cu.addType(new RecordDeclaration(Modifier.createModifierList(), "test")).getType(0), + cu.getRecordByName("test").get()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/builders/EnumDeclarationBuildersTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/builders/EnumDeclarationBuildersTest.java new file mode 100644 index 0000000..508dc15 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/builders/EnumDeclarationBuildersTest.java @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.builders; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.EnumDeclaration; +import org.junit.jupiter.api.Test; + +import java.util.function.Function; + +import static com.github.javaparser.utils.Utils.SYSTEM_EOL; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class EnumDeclarationBuildersTest { + private final CompilationUnit cu = new CompilationUnit(); + + @Test + void testAddImplements() { + EnumDeclaration testEnum = cu.addEnum("test"); + testEnum.addImplementedType(Function.class); + assertEquals(1, cu.getImports().size()); + assertEquals("import " + Function.class.getName() + ";" + SYSTEM_EOL, + cu.getImport(0).toString()); + assertEquals(1, testEnum.getImplementedTypes().size()); + assertEquals(Function.class.getSimpleName(), testEnum.getImplementedTypes(0).getNameAsString()); + } + + @Test + void testAddEnumConstant() { + EnumDeclaration testEnum = cu.addEnum("test"); + testEnum.addEnumConstant("MY_ENUM_CONSTANT"); + assertEquals(1, testEnum.getEntries().size()); + assertEquals("MY_ENUM_CONSTANT", testEnum.getEntry(0).getNameAsString()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/builders/FieldDeclarationBuildersTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/builders/FieldDeclarationBuildersTest.java new file mode 100644 index 0000000..0e90596 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/builders/FieldDeclarationBuildersTest.java @@ -0,0 +1,123 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.builders; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.stmt.ExpressionStmt; +import com.github.javaparser.ast.stmt.ReturnStmt; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static com.github.javaparser.ast.type.PrimitiveType.intType; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class FieldDeclarationBuildersTest { + private final CompilationUnit cu = new CompilationUnit(); + private ClassOrInterfaceDeclaration testClass = cu.addClass("testClass"); + private EnumDeclaration testEnum = cu.addEnum("testEnum"); + + @Test + void testOrphanFieldGetter() { + assertThrows(IllegalStateException.class, () -> new FieldDeclaration().createGetter()); + } + + @Test + void testOrphanFieldSetter() { + assertThrows(IllegalStateException.class, () -> new FieldDeclaration().createSetter()); + } + + @Test + void testCreateGetterInAClass() { + testClass.addPrivateField(int.class, "myField").createGetter(); + assertEquals(2, testClass.getMembers().size()); + assertEquals(MethodDeclaration.class, testClass.getMember(1).getClass()); + List methodsWithName = testClass.getMethodsByName("getMyField"); + assertEquals(1, methodsWithName.size()); + MethodDeclaration getter = methodsWithName.get(0); + assertEquals("getMyField", getter.getNameAsString()); + assertEquals("int", getter.getType().toString()); + assertEquals(ReturnStmt.class, getter.getBody().get().getStatement(0).getClass()); + } + + @Test + void testCreateSetterInAClass() { + testClass.addPrivateField(int.class, "myField").createSetter(); + assertEquals(2, testClass.getMembers().size()); + assertEquals(MethodDeclaration.class, testClass.getMember(1).getClass()); + List methodsWithName = testClass.getMethodsByName("setMyField"); + assertEquals(1, methodsWithName.size()); + MethodDeclaration setter = methodsWithName.get(0); + assertEquals("setMyField", setter.getNameAsString()); + assertEquals("int", setter.getParameter(0).getType().toString()); + assertEquals(ExpressionStmt.class, setter.getBody().get().getStatement(0).getClass()); + assertEquals("this.myField = myField;", setter.getBody().get().getStatement(0).toString()); + } + + @Test + void testCreateGetterInEnum() { + testEnum.addPrivateField(int.class, "myField").createGetter(); + assertEquals(2, testEnum.getMembers().size()); + assertEquals(MethodDeclaration.class, testEnum.getMember(1).getClass()); + List methodsWithName = testEnum.getMethodsByName("getMyField"); + assertEquals(1, methodsWithName.size()); + MethodDeclaration getter = methodsWithName.get(0); + assertEquals("getMyField", getter.getNameAsString()); + assertEquals("int", getter.getType().toString()); + assertEquals(ReturnStmt.class, getter.getBody().get().getStatement(0).getClass()); + } + + @Test + void testCreateSetterInEnum() { + testEnum.addPrivateField(int.class, "myField").createSetter(); + assertEquals(2, testEnum.getMembers().size()); + assertEquals(MethodDeclaration.class, testEnum.getMember(1).getClass()); + List methodsWithName = testEnum.getMethodsByName("setMyField"); + assertEquals(1, methodsWithName.size()); + MethodDeclaration setter = methodsWithName.get(0); + assertEquals("setMyField", setter.getNameAsString()); + assertEquals("int", setter.getParameter(0).getType().toString()); + assertEquals(ExpressionStmt.class, setter.getBody().get().getStatement(0).getClass()); + assertEquals("this.myField = myField;", setter.getBody().get().getStatement(0).toString()); + } + + @Test + void testCreateGetterWithANonValidField() { + assertThrows(IllegalStateException.class, () -> { + FieldDeclaration myPrivateField = testClass.addPrivateField(int.class, "myField"); + myPrivateField.getVariables().add(new VariableDeclarator(intType(), "secondField")); + myPrivateField.createGetter(); + }); + } + + @Test + void testCreateSetterWithANonValidField() { + assertThrows(IllegalStateException.class, () -> { + FieldDeclaration myPrivateField = testClass.addPrivateField(int.class, "myField"); + myPrivateField.getVariables().add(new VariableDeclarator(intType(), "secondField")); + myPrivateField.createSetter(); + }); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/builders/NodeWithAnnotationsBuildersTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/builders/NodeWithAnnotationsBuildersTest.java new file mode 100644 index 0000000..c525b3b --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/builders/NodeWithAnnotationsBuildersTest.java @@ -0,0 +1,88 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.builders; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.expr.NameExpr; +import com.github.javaparser.ast.expr.NormalAnnotationExpr; +import com.github.javaparser.ast.expr.SimpleName; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class NodeWithAnnotationsBuildersTest { + private CompilationUnit cu = new CompilationUnit(); + private ClassOrInterfaceDeclaration testClass = cu.addClass("testClass"); + + @interface hey { + + } + + @Test + void testAddAnnotation() { + NormalAnnotationExpr annotation = testClass.addAndGetAnnotation(hey.class); + assertEquals("import com.github.javaparser.builders.NodeWithAnnotationsBuildersTest.hey;", cu.getImport(0).toString().trim()); + assertEquals(1, testClass.getAnnotations().size()); + assertEquals(annotation, testClass.getAnnotation(0)); + assertEquals(NormalAnnotationExpr.class, testClass.getAnnotation(0).getClass()); + } + + @Test + void testAddMarkerAnnotation() { + testClass.addMarkerAnnotation("test"); + assertEquals(1, testClass.getAnnotations().size()); + } + + @Test + void testAddSingleMemberAnnotation() { + testClass.addSingleMemberAnnotation("test", "value"); + assertEquals(1, testClass.getAnnotations().size()); + assertEquals("value", testClass.getAnnotation(0).asSingleMemberAnnotationExpr().getMemberValue().toString()); + } + + @Test + void testAddSingleMemberAnnotation2() { + testClass.addSingleMemberAnnotation(hey.class, new NameExpr(new SimpleName("value"))); + assertEquals(1, testClass.getAnnotations().size()); + assertEquals("value", testClass.getAnnotation(0).asSingleMemberAnnotationExpr().getMemberValue().toString()); + } + + @Test + void testIsAnnotationPresent() { + testClass.addMarkerAnnotation(hey.class); + assertTrue(testClass.isAnnotationPresent(hey.class)); + } + + @Test + void testGetAnnotationByName() { + NormalAnnotationExpr annotation = testClass.addAndGetAnnotation(hey.class); + assertEquals(annotation, testClass.getAnnotationByName("hey").get()); + } + + @Test + void testGetAnnotationByClass() { + NormalAnnotationExpr annotation = testClass.addAndGetAnnotation(hey.class); + assertEquals(annotation, testClass.getAnnotationByClass(hey.class).get()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/builders/NodeWithMembersBuildersTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/builders/NodeWithMembersBuildersTest.java new file mode 100644 index 0000000..b81f354 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/builders/NodeWithMembersBuildersTest.java @@ -0,0 +1,280 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.builders; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.type.ClassOrInterfaceType; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Optional; + +import static com.github.javaparser.StaticJavaParser.*; +import static com.github.javaparser.ast.Modifier.Keyword.*; +import static org.junit.jupiter.api.Assertions.*; + +class NodeWithMembersBuildersTest { + private final CompilationUnit cu = new CompilationUnit(); + private final ClassOrInterfaceDeclaration classDeclaration = cu.addClass("test"); + + @Test + void testAddField() { + FieldDeclaration addField = classDeclaration.addField(int.class, "fieldName", PRIVATE); + assertEquals(1, classDeclaration.getMembers().size()); + assertEquals(addField, classDeclaration.getMember(0)); + assertEquals("fieldName", addField.getVariable(0).getNameAsString()); + } + + @Test + void testAddMethod() { + MethodDeclaration addMethod = classDeclaration.addMethod("foo", PUBLIC); + assertEquals(1, classDeclaration.getMembers().size()); + assertEquals(addMethod, classDeclaration.getMember(0)); + assertEquals("foo", addMethod.getNameAsString()); + } + + @Test + void testAddCtor() { + ConstructorDeclaration addCtor = classDeclaration.addConstructor(PUBLIC); + assertEquals(1, classDeclaration.getMembers().size()); + assertEquals(addCtor, classDeclaration.getMember(0)); + assertEquals(classDeclaration.getName(), addCtor.getName()); + } + + @Test + void testAddInitializers() { + classDeclaration.addInitializer(); + assertEquals(1, classDeclaration.getMembers().size()); + assertEquals(InitializerDeclaration.class, classDeclaration.getMember(0).getClass()); + + classDeclaration.addStaticInitializer(); + assertEquals(2, classDeclaration.getMembers().size()); + assertEquals(InitializerDeclaration.class, classDeclaration.getMember(0).getClass()); + } + + @Test + void testGetMethodsWithName() { + MethodDeclaration addMethod = classDeclaration.addMethod("foo", PUBLIC); + MethodDeclaration addMethod2 = classDeclaration.addMethod("foo", PUBLIC).addParameter(int.class, "overload"); + List methodsByName = classDeclaration.getMethodsByName("foo"); + assertEquals(2, methodsByName.size()); + assertTrue(methodsByName.contains(addMethod)); + assertTrue(methodsByName.contains(addMethod2)); + } + + @Test + void testGetMethods() { + MethodDeclaration addMethod = classDeclaration.addMethod("foo", PUBLIC); + MethodDeclaration addMethod2 = classDeclaration.addMethod("foo", PUBLIC).addParameter(int.class, "overload"); + + List methods = classDeclaration.getMethods(); + + assertEquals(2, methods.size()); + assertTrue(methods.contains(addMethod)); + assertTrue(methods.contains(addMethod2)); + } + + @Test + void testGetMethodsWithParameterTypes() { + MethodDeclaration mFoo = classDeclaration.addMethod("foo", PUBLIC); // foo() + MethodDeclaration mFooInt = classDeclaration.addMethod("foo", PUBLIC).addParameter(int.class, "i"); // foo(int) + ClassOrInterfaceType type = parseClassOrInterfaceType("List"); + type.setTypeArguments(parseClassOrInterfaceType("String")); + MethodDeclaration mFooIntList = classDeclaration.addMethod("foo", PUBLIC).addParameter(int.class, "i").addParameter(type, "l"); // foo(int, List) + MethodDeclaration mFooListInt = classDeclaration.addMethod("foo", PUBLIC).addParameter(type, "l").addParameter(int.class, "i"); // foo(List, int) + MethodDeclaration mFoo2Int = classDeclaration.addMethod("foo2", PUBLIC).addParameter(int.class, "i"); // foo2(int) + MethodDeclaration mFoo2IntInt = classDeclaration.addMethod("foo2", PUBLIC).addParameter(int.class, "i").addParameter(int.class, "j"); // foo2(int, int) + + List methodsWithNoParams = classDeclaration.getMethodsByParameterTypes(new Class[0]); // should return foo() + assertEquals(1, methodsWithNoParams.size()); + assertTrue(methodsWithNoParams.contains(mFoo)); + + List methodsWithIntParam = classDeclaration.getMethodsByParameterTypes(int.class); // should return foo(int) and foo2(int) + assertEquals(2, methodsWithIntParam.size()); + assertTrue(methodsWithIntParam.contains(mFooInt)); + assertTrue(methodsWithIntParam.contains(mFoo2Int)); + + List methodsWithListParam = classDeclaration.getMethodsByParameterTypes("List"); + assertEquals(0, methodsWithListParam.size()); + + List methodsWithIntAndListParams = classDeclaration.getMethodsByParameterTypes("int", "List"); + assertEquals(1, methodsWithIntAndListParams.size()); + assertTrue(methodsWithIntAndListParams.contains(mFooIntList)); + + List methodsWithListAndIntParams = classDeclaration.getMethodsByParameterTypes(List.class, int.class); + assertEquals(1, methodsWithListAndIntParams.size()); + assertTrue(methodsWithListAndIntParams.contains(mFooListInt)); + + List methodsWithIntAndIntParams = classDeclaration.getMethodsByParameterTypes(int.class, int.class); + assertEquals(1, methodsWithListAndIntParams.size()); + assertTrue(methodsWithIntAndIntParams.contains(mFoo2IntInt)); + } + + @Test + void testGetConstructors() { + ConstructorDeclaration addConstructor = classDeclaration.addConstructor(PUBLIC); + ConstructorDeclaration addConstructor2 = classDeclaration.addConstructor(PUBLIC).addParameter(int.class, "overload"); + + List constructors = classDeclaration.getConstructors(); + + assertEquals(2, constructors.size()); + assertTrue(constructors.contains(addConstructor)); + assertTrue(constructors.contains(addConstructor2)); + } + + @Test + void testGetConstructorsWithParameterTypes() { + ConstructorDeclaration c = classDeclaration.addConstructor(PUBLIC); // Foo() + ConstructorDeclaration cInt = classDeclaration.addConstructor(PUBLIC).addParameter(int.class, "i"); // Foo(int) + ClassOrInterfaceType type = parseClassOrInterfaceType("List"); + type.setTypeArguments(parseClassOrInterfaceType("String")); + ConstructorDeclaration cIntList = classDeclaration.addConstructor(PUBLIC).addParameter(int.class, "i").addParameter(type, "l"); // Foo(int, List) + ConstructorDeclaration cListInt = classDeclaration.addConstructor(PUBLIC).addParameter(type, "l").addParameter(int.class, "i"); // Foo(List, int) + ConstructorDeclaration cIntInt = classDeclaration.addConstructor(PUBLIC).addParameter(int.class, "i").addParameter(int.class, "j"); // Foo(int, int) + + Optional constructorWithNoParams = classDeclaration.getDefaultConstructor(); + assertTrue(constructorWithNoParams.isPresent()); + assertSame(c, constructorWithNoParams.get()); + + Optional constructorWithIntParam = classDeclaration.getConstructorByParameterTypes(int.class); + assertTrue(constructorWithIntParam.isPresent()); + assertSame(cInt, constructorWithIntParam.get()); + + Optional constructorWithListParam = classDeclaration.getConstructorByParameterTypes("List"); + assertFalse(constructorWithListParam.isPresent()); + + Optional constructorWithIntAndListParams = classDeclaration.getConstructorByParameterTypes("int", "List"); + assertTrue(constructorWithIntAndListParams.isPresent()); + assertSame(cIntList, constructorWithIntAndListParams.get()); + + Optional constructorWithListAndIntParams = classDeclaration.getConstructorByParameterTypes(List.class, int.class); + assertTrue(constructorWithListAndIntParams.isPresent()); + assertSame(cListInt, constructorWithListAndIntParams.get()); + + Optional constructorWithIntAndIntParams = classDeclaration.getConstructorByParameterTypes(int.class, int.class); + assertTrue(constructorWithIntAndIntParams.isPresent()); + assertSame(cIntInt, constructorWithIntAndIntParams.get()); + } + + @Test + void testGetFieldWithName() { + FieldDeclaration addField = classDeclaration.addField(int.class, "fieldName", PRIVATE); + classDeclaration.addField(float.class, "secondField", PRIVATE); + FieldDeclaration fieldByName = classDeclaration.getFieldByName("fieldName").get(); + assertEquals(addField, fieldByName); + } + + @Test + void testGetFields() { + FieldDeclaration firstField = classDeclaration.addField(int.class, "fieldName", PRIVATE); + FieldDeclaration secondField = classDeclaration.addField(float.class, "secondField", PRIVATE); + + List fields = classDeclaration.getFields(); + + assertTrue(fields.contains(firstField)); + assertTrue(fields.contains(secondField)); + } + + @Test + void testAddPrivateFieldWithType(){ + CompilationUnit compilationUnit = new CompilationUnit(); + ClassOrInterfaceDeclaration classOrInterfaceDeclaration = compilationUnit.addClass("Person"); + classOrInterfaceDeclaration.addPrivateField(parseType("java.lang.String"), "name"); + + assertNotNull(classOrInterfaceDeclaration.getFields()); + assertEquals(1, classOrInterfaceDeclaration.getFields().size()); + + FieldDeclaration fieldDeclaration = classOrInterfaceDeclaration.getFields().get(0); + assertEquals(PRIVATE, fieldDeclaration.getModifiers().iterator().next().getKeyword()); + assertEquals("java.lang.String",fieldDeclaration.getVariables().get(0).getType().toString()); + assertEquals("name",fieldDeclaration.getVariables().get(0).getName().toString()); + } + + @Test + void testAddPublicFieldWithType(){ + CompilationUnit compilationUnit = new CompilationUnit(); + ClassOrInterfaceDeclaration classOrInterfaceDeclaration = compilationUnit.addClass("Person"); + classOrInterfaceDeclaration.addPublicField(parseType("java.lang.String"), "name"); + + assertNotNull(classOrInterfaceDeclaration.getFields()); + assertEquals(1, classOrInterfaceDeclaration.getFields().size()); + + FieldDeclaration fieldDeclaration = classOrInterfaceDeclaration.getFields().get(0); + assertEquals(PUBLIC, fieldDeclaration.getModifiers().iterator().next().getKeyword()); + assertEquals("java.lang.String",fieldDeclaration.getVariables().get(0).getType().toString()); + assertEquals("name",fieldDeclaration.getVariables().get(0).getName().toString()); + } + + @Test + void testAddProtectedFieldWithType(){ + CompilationUnit compilationUnit = new CompilationUnit(); + ClassOrInterfaceDeclaration classOrInterfaceDeclaration = compilationUnit.addClass("Person"); + classOrInterfaceDeclaration.addProtectedField(parseType("java.lang.String"), "name"); + + assertNotNull(classOrInterfaceDeclaration.getFields()); + assertEquals(1, classOrInterfaceDeclaration.getFields().size()); + + FieldDeclaration fieldDeclaration = classOrInterfaceDeclaration.getFields().get(0); + assertEquals(PROTECTED, fieldDeclaration.getModifiers().iterator().next().getKeyword()); + assertEquals("java.lang.String",fieldDeclaration.getVariables().get(0).getType().toString()); + assertEquals("name",fieldDeclaration.getVariables().get(0).getName().toString()); + } + + @Test + void testClassWithInitializersWithString(){ + CompilationUnit compilationUnit = new CompilationUnit(); + ClassOrInterfaceDeclaration classOrInterfaceDeclaration = compilationUnit.addClass("Person"); + classOrInterfaceDeclaration.addFieldWithInitializer( + "java.lang.String", + "name", + parseExpression("John"), + PUBLIC); + assertNotNull(classOrInterfaceDeclaration.getFields()); + assertEquals(1, classOrInterfaceDeclaration.getFields().size()); + + FieldDeclaration fieldDeclaration = classOrInterfaceDeclaration.getFields().get(0); + assertEquals(PUBLIC, fieldDeclaration.getModifiers().iterator().next().getKeyword()); + assertEquals("java.lang.String",fieldDeclaration.getVariables().get(0).getType().toString()); + assertEquals("name",fieldDeclaration.getVariables().get(0).getName().toString()); + assertEquals("John",fieldDeclaration.getVariables().get(0).getInitializer().get().toString()); + } + + @Test + void testClassWithInitializersWithClass(){ + CompilationUnit compilationUnit = new CompilationUnit(); + ClassOrInterfaceDeclaration classOrInterfaceDeclaration = compilationUnit.addClass("Person"); + classOrInterfaceDeclaration.addFieldWithInitializer( + List.class, + "skills", + parseExpression("new ArrayList()"), + PUBLIC); + assertNotNull(classOrInterfaceDeclaration.getFields()); + assertEquals(1, classOrInterfaceDeclaration.getFields().size()); + + FieldDeclaration fieldDeclaration = classOrInterfaceDeclaration.getFields().get(0); + assertEquals(PUBLIC, fieldDeclaration.getModifiers().iterator().next().getKeyword()); + assertEquals("List",fieldDeclaration.getVariables().get(0).getType().toString()); + assertEquals("skills",fieldDeclaration.getVariables().get(0).getName().toString()); + assertEquals("new ArrayList()",fieldDeclaration.getVariables().get(0).getInitializer().get().toString()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/builders/NodeWithParametersBuildersTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/builders/NodeWithParametersBuildersTest.java new file mode 100644 index 0000000..1d144df --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/builders/NodeWithParametersBuildersTest.java @@ -0,0 +1,66 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.builders; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.body.Parameter; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static com.github.javaparser.ast.Modifier.Keyword.PUBLIC; +import static com.github.javaparser.utils.Utils.SYSTEM_EOL; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class NodeWithParametersBuildersTest { + private final CompilationUnit cu = new CompilationUnit(); + + @Test + void testAddParameter() { + MethodDeclaration addMethod = cu.addClass("test").addMethod("foo", PUBLIC); + addMethod.addParameter(int.class, "yay"); + Parameter myNewParam = addMethod.addAndGetParameter(List.class, "myList"); + assertEquals(1, cu.getImports().size()); + assertEquals("import " + List.class.getName() + ";" + SYSTEM_EOL, cu.getImport(0).toString()); + assertEquals(2, addMethod.getParameters().size()); + assertEquals("yay", addMethod.getParameter(0).getNameAsString()); + assertEquals("List", addMethod.getParameter(1).getType().toString()); + assertEquals(myNewParam, addMethod.getParameter(1)); + } + + @Test + void testGetParamByName() { + MethodDeclaration addMethod = cu.addClass("test").addMethod("foo", PUBLIC); + Parameter addAndGetParameter = addMethod.addAndGetParameter(int.class, "yay"); + assertEquals(addAndGetParameter, addMethod.getParameterByName("yay").get()); + } + + @Test + void testGetParamByType() { + MethodDeclaration addMethod = cu.addClass("test").addMethod("foo", PUBLIC); + Parameter addAndGetParameter = addMethod.addAndGetParameter(int.class, "yay"); + assertEquals(addAndGetParameter, addMethod.getParameterByType("int").get()); + assertEquals(addAndGetParameter, addMethod.getParameterByType(int.class).get()); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/builders/NodeWithThrownExceptionsBuildersTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/builders/NodeWithThrownExceptionsBuildersTest.java new file mode 100644 index 0000000..ea4059f --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/builders/NodeWithThrownExceptionsBuildersTest.java @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.builders; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.MethodDeclaration; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.StaticJavaParser.parseClassOrInterfaceType; +import static com.github.javaparser.ast.Modifier.Keyword.PUBLIC; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class NodeWithThrownExceptionsBuildersTest { + private final CompilationUnit cu = new CompilationUnit(); + + @Test + void testThrows() { + MethodDeclaration addMethod = cu.addClass("test").addMethod("foo", PUBLIC); + addMethod.addThrownException(IllegalStateException.class); + assertEquals(1, addMethod.getThrownExceptions().size()); + assertTrue(addMethod.isThrown(IllegalStateException.class)); + addMethod.addThrownException(parseClassOrInterfaceType("Test")); + assertEquals(2, addMethod.getThrownExceptions().size()); + assertEquals("Test", addMethod.getThrownException(1).toString()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/issues/Issue2627Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/issues/Issue2627Test.java new file mode 100644 index 0000000..ec02e41 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/issues/Issue2627Test.java @@ -0,0 +1,165 @@ +/* + * Copyright (C) 2013-2024 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.issues; + +import com.github.javaparser.Range; +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 org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.IOException; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class Issue2627Test { + + private static final String RESOURCE_PATH_STRING_CR = "com/github/javaparser/issue_samples/issue_2627/Ops_cr.java"; + private static final String RESOURCE_PATH_STRING_LF = "com/github/javaparser/issue_samples/issue_2627/Ops_lf.java"; + private static final String RESOURCE_PATH_STRING_CRLF = "com/github/javaparser/issue_samples/issue_2627/Ops_crlf.java"; + private static final String RESOURCE_PATH_STRING_MINIMAL = "com/github/javaparser/issue_samples/issue_2627/Ops_minimal.java"; + private static final String RESOURCE_PATH_STRING_ORIGINAL = "com/github/javaparser/issue_samples/issue_2627/Ops.java"; + private static final String RESOURCE_PATH_GROOVY_ORIGINAL = "com/github/javaparser/issue_samples/issue_2627/DefaultStrategy.java"; + + private static Stream arguments_minimal() { + return Stream.of( + Arguments.of("methodA", 258, 260), + Arguments.of("methodB", 163, 164), + Arguments.of("methodC", 3, 4) + ); + } + + private static Stream arguments_original() { + return Stream.of( + Arguments.of("batchToSpace", 796, 799), + Arguments.of("batchToSpaceNd", 911, 914), + Arguments.of("placeholder", 3686, 3689) + ); + } + + private static Stream arguments_groovy_original() { + return Stream.of( + Arguments.of("buildMethod", 180, 193) + ); + } + + private void assertMethodInExpectedLines(CompilationUnit cu, String name, int expectedStartLine, int expectedEndLine) { + MethodDeclaration node = getFirstMethodDeclarationByName(cu, name); + assertNodeInExpectedLines(node, expectedStartLine, expectedEndLine); + } + + private void assertNodeInExpectedLines(Node node, int expectedStartLine, int expectedEndLine) { + Range range = node.getRange().get(); + + assertEquals(expectedStartLine, range.begin.line); + assertEquals(expectedEndLine, range.end.line); + } + + private MethodDeclaration getFirstMethodDeclarationByName(CompilationUnit cu, String name) { + return cu.findAll(MethodDeclaration.class).stream() + .filter(n -> name.equals(n.getNameAsString())) + .findFirst() + .get(); + } + +// @Test +// public void cuLength_minimal() throws IOException { +// CompilationUnit cu = StaticJavaParser.parseResource(RESOURCE_PATH_STRING_MINIMAL); +// +// final Range cuRange = cu.getRange().get(); +// +// int lineCount = cuRange.end.line - cuRange.begin.line; +// +// } + +// @Test +// public void commentPositions_minimal() throws IOException { +// CompilationUnit cu = StaticJavaParser.parseResource(RESOURCE_PATH_STRING_MINIMAL); +// +// List allComments = cu.getAllComments(); +// for (int i = 0; i < allComments.size(); i++) { +// Comment comment = allComments.get(i); +// Optional optionalRange = comment.getRange(); +// if (optionalRange.isPresent()) { +// Range range = optionalRange.get(); +// final TokenRange tokens = comment.getTokenRange().get(); +// int tokenIndex = 0; +// for (JavaToken token : tokens) { +// System.out.println("token " + tokenIndex + " = " + token); +// tokenIndex++; +// } +// System.out.println(tokens); +// } +// } +// +// +//// assertNodeInExpectedLines(cu, 1, 288); +// } + + @ParameterizedTest + @MethodSource("arguments_minimal") + public void method_minimal(String name, int expectedStart, int expectedEnd) throws IOException { + CompilationUnit cu = StaticJavaParser.parseResource(RESOURCE_PATH_STRING_MINIMAL); + assertMethodInExpectedLines(cu, name, expectedStart, expectedEnd); + } + + + @ParameterizedTest + @MethodSource("arguments_original") + public void method_original(String name, int expectedStart, int expectedEnd) throws IOException { + CompilationUnit cu = StaticJavaParser.parseResource(RESOURCE_PATH_STRING_ORIGINAL); + assertMethodInExpectedLines(cu, name, expectedStart, expectedEnd); + } + + @ParameterizedTest + @MethodSource("arguments_original") + public void method_original_cr(String name, int expectedStart, int expectedEnd) throws IOException { + CompilationUnit cu = StaticJavaParser.parseResource(RESOURCE_PATH_STRING_CR); + assertMethodInExpectedLines(cu, name, expectedStart, expectedEnd); + } + + @ParameterizedTest + @MethodSource("arguments_original") + public void method_original_crlf(String name, int expectedStart, int expectedEnd) throws IOException { + CompilationUnit cu = StaticJavaParser.parseResource(RESOURCE_PATH_STRING_CRLF); + assertMethodInExpectedLines(cu, name, expectedStart, expectedEnd); + } + + @ParameterizedTest + @MethodSource("arguments_original") + public void method_original_lf(String name, int expectedStart, int expectedEnd) throws IOException { + CompilationUnit cu = StaticJavaParser.parseResource(RESOURCE_PATH_STRING_LF); + assertMethodInExpectedLines(cu, name, expectedStart, expectedEnd); + } + + + @ParameterizedTest + @MethodSource("arguments_groovy_original") + public void method_groovy_original(String name, int expectedStart, int expectedEnd) throws IOException { + CompilationUnit cu = StaticJavaParser.parseResource(RESOURCE_PATH_GROOVY_ORIGINAL); + assertMethodInExpectedLines(cu, name, expectedStart, expectedEnd); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/issues/Issue3113Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/issues/Issue3113Test.java new file mode 100644 index 0000000..878a62f --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/issues/Issue3113Test.java @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2013-2024 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.issues; + +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.StaticJavaParser; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.stmt.SwitchStmt; +import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest; +import com.github.javaparser.printer.lexicalpreservation.LexicalPreservingPrinter; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class Issue3113Test extends AbstractLexicalPreservingTest { + @Test + public void issue3113() { + StaticJavaParser.getConfiguration().setLanguageLevel(ParserConfiguration.LanguageLevel.JAVA_12); + + String originalSourceCode = "public class HelloWorld {\n" + + " public static void main(String[] args) {\n" + + " final int value = 2;\n" + + " String numericString;\n" + + " switch (value)\n" + + " {\n" + + " case 1 -> numericString = \"one\";\n" + + " default -> numericString = \"N/A\";\n" + + " }\n" + + " System.out.println(\"value:\" + value + \" as string: \" + numericString);\n" + + " }\n" + + "}\n"; + + CompilationUnit cu = StaticJavaParser.parse(originalSourceCode); + LexicalPreservingPrinter.setup(cu); + SwitchStmt expr = cu.findFirst(SwitchStmt.class).get(); + String modifiedSourceCode = LexicalPreservingPrinter.print(expr); + assertEquals("switch (value)\n" + + " {\n" + + " case 1 -> numericString = \"one\";\n" + + " default -> numericString = \"N/A\";\n" + + " }", modifiedSourceCode); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/issues/Issue3255Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/issues/Issue3255Test.java new file mode 100644 index 0000000..8473fcb --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/issues/Issue3255Test.java @@ -0,0 +1,85 @@ +/* + * Copyright (C) 2013-2024 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.issues; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.utils.LineSeparator; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.utils.TestParser.parseStatement; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class Issue3255Test { + + private static final String EOL = LineSeparator.SYSTEM.asRawString(); + + @Test + public void test() { + JavaParser javaParser = new JavaParser(); + ParseResult parseResult = javaParser.parse("class Test {" + EOL + + " private void bad() {" + EOL + + " String record = \"\";" + EOL + + " record.getBytes();" + EOL + + " }" + EOL + + "}"); + + assertEquals(0, parseResult.getProblems().size()); + + CompilationUnit compilationUnit = parseResult.getResult().get(); + } + + @Test + public void test2() { + JavaParser javaParser = new JavaParser(); + ParseResult parseResult = javaParser.parse("class Test {" + EOL + + " private void bad() {" + EOL + + " String record2 = \"\";" + EOL + + " record2.getBytes();" + EOL + + " }" + EOL + + "}"); + + assertEquals(0, parseResult.getProblems().size()); + + CompilationUnit compilationUnit = parseResult.getResult().get(); + } + + @Test + void recordIsAValidVariableNameWhenParsingAStatement() { + parseStatement("Object record;"); + } + + @Test + public void recordIsAValidVariableNameWhenUsedInAClass() { + JavaParser javaParser = new JavaParser(); + ParseResult parseResult = javaParser.parse("class Test {" + EOL + + " private void goodInJava16() {" + EOL + + " Object record;" + EOL + + " }" + EOL + + "}"); + + assertEquals(0, parseResult.getProblems().size()); + + CompilationUnit compilationUnit = parseResult.getResult().get(); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/javadoc/JavadocExtractorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/javadoc/JavadocExtractorTest.java new file mode 100644 index 0000000..16244cc --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/javadoc/JavadocExtractorTest.java @@ -0,0 +1,66 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.javadoc; + +import com.github.javaparser.ParseProblemException; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.comments.JavadocComment; +import com.github.javaparser.ast.visitor.VoidVisitorAdapter; +import org.junit.jupiter.api.Test; + +import java.io.File; +import java.io.FileNotFoundException; + +import static com.github.javaparser.StaticJavaParser.parse; + +class JavadocExtractorTest { + + @Test + void canParseAllJavadocsInJavaParser() throws FileNotFoundException { + processDir(new File("..")); + } + + private void processFile(File file) throws FileNotFoundException { + try { + CompilationUnit cu = parse(file); + new VoidVisitorAdapter() { + @Override + public void visit(JavadocComment n, Object arg) { + super.visit(n, arg); + n.parse(); + } + }.visit(cu, null); + } catch (ParseProblemException e) { + System.err.println("ERROR PROCESSING "+ file); + } + } + + private void processDir(File dir) throws FileNotFoundException { + for (File child : dir.listFiles()) { + if (child.isFile() && child.getName().endsWith(".java")) { + processFile(child); + } else if (child.isDirectory()) { + processDir(child); + } + } + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/javadoc/JavadocTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/javadoc/JavadocTest.java new file mode 100644 index 0000000..f9d7631 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/javadoc/JavadocTest.java @@ -0,0 +1,172 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.javadoc; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.comments.JavadocComment; +import com.github.javaparser.javadoc.description.JavadocDescription; +import com.github.javaparser.javadoc.description.JavadocDescriptionElement; +import com.github.javaparser.javadoc.description.JavadocInlineTag; +import com.github.javaparser.javadoc.description.JavadocSnippet; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static com.github.javaparser.StaticJavaParser.parse; +import static com.github.javaparser.StaticJavaParser.parseJavadoc; +import static com.github.javaparser.javadoc.description.JavadocInlineTag.Type.*; +import static com.github.javaparser.utils.Utils.SYSTEM_EOL; +import static java.util.stream.Collectors.toList; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class JavadocTest { + + @Test + void toTextForEmptyJavadoc() { + Javadoc javadoc = new Javadoc(new JavadocDescription()); + assertEquals("", javadoc.toText()); + } + + @Test + void toTextForJavadocWithTwoLinesOfJustDescription() { + Javadoc javadoc = new Javadoc(JavadocDescription.parseText("first line" + SYSTEM_EOL + "second line")); + assertEquals("first line" + SYSTEM_EOL + "second line" + SYSTEM_EOL, javadoc.toText()); + } + + @Test + void toTextForJavadocWithTwoLinesOfJustDescriptionAndOneBlockTag() { + Javadoc javadoc = new Javadoc(JavadocDescription.parseText("first line" + SYSTEM_EOL + "second line")); + javadoc.addBlockTag("foo", "something useful"); + assertEquals("first line" + SYSTEM_EOL + "second line" + SYSTEM_EOL + SYSTEM_EOL + "@foo something useful" + SYSTEM_EOL, javadoc.toText()); + } + + @Test + void toCommentForEmptyJavadoc() { + Javadoc javadoc = new Javadoc(new JavadocDescription()); + assertEquals(new JavadocComment("" + SYSTEM_EOL + "\t\t "), javadoc.toComment("\t\t")); + } + + @Test + void toCommentorJavadocWithTwoLinesOfJustDescription() { + Javadoc javadoc = new Javadoc(JavadocDescription.parseText("first line" + SYSTEM_EOL + "second line")); + assertEquals(new JavadocComment("" + SYSTEM_EOL + "\t\t * first line" + SYSTEM_EOL + "\t\t * second line" + SYSTEM_EOL + "\t\t "), javadoc.toComment("\t\t")); + } + + @Test + void toCommentForJavadocWithTwoLinesOfJustDescriptionAndOneBlockTag() { + Javadoc javadoc = new Javadoc(JavadocDescription.parseText("first line" + SYSTEM_EOL + "second line")); + javadoc.addBlockTag("foo", "something useful"); + assertEquals(new JavadocComment("" + SYSTEM_EOL + "\t\t * first line" + SYSTEM_EOL + "\t\t * second line" + SYSTEM_EOL + "\t\t * " + SYSTEM_EOL + "\t\t * @foo something useful" + SYSTEM_EOL + "\t\t "), javadoc.toComment("\t\t")); + } + + @Test + void descriptionAndBlockTagsAreRetrievable() { + Javadoc javadoc = parseJavadoc("first line" + SYSTEM_EOL + "second line" + SYSTEM_EOL + SYSTEM_EOL + "@param node a node" + SYSTEM_EOL + "@return result the result"); + assertEquals("first line" + SYSTEM_EOL + "second line", javadoc.getDescription().toText()); + assertEquals(2, javadoc.getBlockTags().size()); + } + + @Test + void inlineTagsAreParsable() { + String docText = + "Returns the {@link TOFilename}s of all files that existed during the requested" + SYSTEM_EOL + + "{@link TOVersion}. Set {@systemProperty JAVA_HOME} correctly." + SYSTEM_EOL + + "" + SYSTEM_EOL + + "@param versionID the id of the {@link TOVersion}." + SYSTEM_EOL + + "@return the filenames" + SYSTEM_EOL + + "@throws InvalidIDException if the {@link IPersistence} doesn't recognize the given versionID." + SYSTEM_EOL; + Javadoc javadoc = parseJavadoc(docText); + + List inlineTags = javadoc.getDescription().getElements().stream() + .filter(element -> element instanceof JavadocInlineTag) + .map(element -> (JavadocInlineTag) element) + .collect(toList()); + + assertEquals("link", inlineTags.get(0).getName()); + assertEquals(" TOFilename", inlineTags.get(0).getContent()); + assertEquals(LINK, inlineTags.get(0).getType()); + assertEquals("link", inlineTags.get(1).getName()); + assertEquals(" TOVersion", inlineTags.get(1).getContent()); + assertEquals(LINK, inlineTags.get(1).getType()); + assertEquals("systemProperty", inlineTags.get(2).getName()); + assertEquals(" JAVA_HOME", inlineTags.get(2).getContent()); + assertEquals(SYSTEM_PROPERTY, inlineTags.get(2).getType()); + + String javadocText = javadoc.toText(); + assertTrue(javadocText.contains("{@link TOVersion}")); + } + + @Test + void emptyLinesBetweenBlockTagsGetsFiltered() { + String comment = " * The type of the Object to be mapped." + SYSTEM_EOL + + " * This interface maps the given Objects to existing ones in the database and" + SYSTEM_EOL + + " * saves them." + SYSTEM_EOL + + " * " + SYSTEM_EOL + + " * @author censored" + SYSTEM_EOL + + " * " + SYSTEM_EOL + + " * @param " + SYSTEM_EOL; + Javadoc javadoc = parseJavadoc(comment); + assertEquals(2, javadoc.getBlockTags().size()); + } + + @Test + void blockTagModificationWorks() { + Javadoc javadoc = new Javadoc(new JavadocDescription()); + + assertEquals(0, javadoc.getBlockTags().size()); + JavadocBlockTag blockTag = new JavadocBlockTag(JavadocBlockTag.Type.RETURN, "a value"); + javadoc.addBlockTag(blockTag); + + assertEquals(1, javadoc.getBlockTags().size()); + assertEquals(blockTag, javadoc.getBlockTags().get(0)); + + assertEquals(blockTag, javadoc.getBlockTags().remove(0)); + assertEquals(0, javadoc.getBlockTags().size()); + } + + @Test + void descriptionModificationWorks() { + JavadocDescription description = new JavadocDescription(); + + assertEquals(0, description.getElements().size()); + + JavadocDescriptionElement inlineTag = new JavadocInlineTag("inheritDoc", INHERIT_DOC, ""); + assertTrue(description.addElement(inlineTag)); + + assertEquals(1, description.getElements().size()); + assertEquals(inlineTag, description.getElements().get(0)); + + assertEquals(inlineTag, description.getElements().remove(0)); + assertEquals(0, description.getElements().size()); + } + + @Test + void issue1533() { + CompilationUnit compilationUnit = parse("/** hallo {@link Foo} welt */ public interface Foo extends Comparable { }"); + List elements = compilationUnit.getType(0).getJavadoc().get().getDescription().getElements(); + assertEquals(3, elements.size()); + assertEquals(new JavadocSnippet("hallo "), elements.get(0)); + assertEquals(new JavadocInlineTag("link", LINK, " Foo"), elements.get(1)); + assertEquals(new JavadocSnippet(" welt"), elements.get(2)); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/javadoc/description/JavadocInlineTagTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/javadoc/description/JavadocInlineTagTest.java new file mode 100644 index 0000000..2673a6f --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/javadoc/description/JavadocInlineTagTest.java @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.javadoc.description; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class JavadocInlineTagTest { + + @Test + void javadocInlineTagShouldPersistCustomTagNames() { + String tag = JavadocInlineTag.fromText("{@foo something}").toText(); + + assertEquals(tag, "{@foo something}"); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/manual/BulkParseTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/manual/BulkParseTest.java new file mode 100644 index 0000000..1be1fc9 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/manual/BulkParseTest.java @@ -0,0 +1,164 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.manual; + +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.Problem; +import com.github.javaparser.utils.Log; +import com.github.javaparser.utils.SourceRoot; +import com.github.javaparser.utils.SourceZip; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.BufferedWriter; +import java.io.IOException; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import static com.github.javaparser.ParserConfiguration.LanguageLevel.*; +import static com.github.javaparser.utils.CodeGenerationUtils.f; +import static com.github.javaparser.utils.CodeGenerationUtils.mavenModuleRoot; +import static com.github.javaparser.utils.SourceRoot.Callback.Result.DONT_SAVE; +import static com.github.javaparser.utils.TestUtils.download; +import static com.github.javaparser.utils.TestUtils.temporaryDirectory; +import static java.util.Comparator.comparing; + +class BulkParseTest { + /** + * Running this will download a version of the OpenJDK, unzip it, and parse it. If it throws a stack overflow + * exception, increase the JVM's stack size. + */ + public static void main(String[] args) throws IOException { + Log.setAdapter(new Log.StandardOutStandardErrorAdapter()); + // This contains all kinds of test cases so it will lead to a lot of errors: + new BulkParseTest().parseOpenJdkLangToolsRepository(); + // This contains the JDK source code, so it should have zero errors: + new BulkParseTest().parseJdkSrcZip(); + } + + private void parseOpenJdkLangToolsRepository() throws IOException { + Path workdir = mavenModuleRoot(BulkParseTest.class).resolve(Paths.get(temporaryDirectory(), "javaparser_bulkparsetest")); + workdir.toFile().mkdirs(); + Path openJdkZipPath = workdir.resolve("langtools.zip"); + if (Files.notExists(openJdkZipPath)) { + Log.info("Downloading JDK langtools"); + /* Found by choosing a tag here: http://hg.openjdk.java.net/jdk9/jdk9/langtools/tags + then copying the "zip" link to the line below: */ + download(new URL("http://hg.openjdk.java.net/jdk10/jdk10/langtools/archive/19293ea3999f.zip"), openJdkZipPath); + } + bulkTest(new SourceZip(openJdkZipPath), "openjdk_src_repo_test_results.txt", new ParserConfiguration().setLanguageLevel(JAVA_10)); + } + + private void parseJdkSrcZip() throws IOException { + // This is where Ubuntu stores the contents of package openjdk-8-src + Path path = Paths.get("/usr/lib/jvm/openjdk-9/src.zip"); + bulkTest(new SourceZip(path), "openjdk_src_zip_test_results.txt", new ParserConfiguration().setLanguageLevel(JAVA_9)); + } + + @BeforeEach + void startLogging() { + Log.setAdapter(new Log.StandardOutStandardErrorAdapter()); + } + + @AfterEach + void stopLogging() { + Log.setAdapter(new Log.SilentAdapter()); + } + + @Test + void parseOwnSourceCode() throws IOException { + String[] roots = new String[]{ + "javaparser-core/src/main/java", + "javaparser-core-testing/src/test/java", + "javaparser-core-generators/src/main/java", + "javaparser-core-metamodel-generator/src/main/java", + "javaparser-symbol-solver-core/src/main/java", + "javaparser-symbol-solver-testing/src/test/java" + }; + for (String root : roots) { + bulkTest( + new SourceRoot(mavenModuleRoot(BulkParseTest.class).resolve("..").resolve(root)), + "javaparser_test_results_" + root.replace("-", "_").replace("/", "_") + ".txt", + new ParserConfiguration().setLanguageLevel(BLEEDING_EDGE) + ); + } + } + + public void bulkTest(SourceRoot sourceRoot, String testResultsFileName, ParserConfiguration configuration) throws IOException { + sourceRoot.setParserConfiguration(configuration); + TreeMap> results = new TreeMap<>(comparing(o -> o.toString().toLowerCase())); + sourceRoot.parseParallelized((localPath, absolutePath, result) -> { + if (!localPath.toString().contains("target")) { + if (!result.isSuccessful()) { + results.put(localPath, result.getProblems()); + } + } + return DONT_SAVE; + }); + writeResults(results, testResultsFileName); + } + + public void bulkTest(SourceZip sourceRoot, String testResultsFileName, ParserConfiguration configuration) throws IOException { + sourceRoot.setParserConfiguration(configuration); + TreeMap> results = new TreeMap<>(comparing(o -> o.toString().toLowerCase())); + sourceRoot.parse((path, result) -> { + if (!path.toString().contains("target")) { + if (!result.isSuccessful()) { + results.put(path, result.getProblems()); + } + } + }); + writeResults(results, testResultsFileName); + } + + private void writeResults(TreeMap> results, String testResultsFileName) throws IOException { + Log.info("Writing results..."); + + Path testResults = mavenModuleRoot(BulkParseTest.class).resolve(Paths.get("..", "javaparser-core-testing", "src", "test", "resources", "com", "github", "javaparser", "bulk_test_results")).normalize(); + testResults.toFile().mkdirs(); + testResults = testResults.resolve(testResultsFileName); + + int problemTotal = 0; + try (BufferedWriter writer = Files.newBufferedWriter(testResults)) { + for (Map.Entry> file : results.entrySet()) { + writer.write(file.getKey().toString().replace("\\", "/")); + writer.newLine(); + for (Problem problem : file.getValue()) { + writer.write(problem.getVerboseMessage()); + writer.newLine(); + problemTotal++; + } + writer.newLine(); + } + writer.write(f("%s problems in %s files", problemTotal, results.size())); + } + + Path finalTestResults = testResults; + Log.info("Results are in %s", () -> finalTestResults); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/metamodel/BaseNodeMetaModelTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/metamodel/BaseNodeMetaModelTest.java new file mode 100644 index 0000000..a263709 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/metamodel/BaseNodeMetaModelTest.java @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.metamodel; + +import com.github.javaparser.ast.expr.StringLiteralExpr; +import org.junit.jupiter.api.Test; + +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class TestMetaModel extends BaseNodeMetaModel { + + public TestMetaModel() { + super(Optional.empty(), StringLiteralExpr.class, "stri", "com.japa", true, true); + } +} + +class BaseNodeMetaModelTest { + @Test + void testGetters() { + TestMetaModel test = new TestMetaModel(); + + assertEquals("testMetaModel", test.getMetaModelFieldName()); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/metamodel/PropertyMetaModelTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/metamodel/PropertyMetaModelTest.java new file mode 100644 index 0000000..aa0ba1a --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/metamodel/PropertyMetaModelTest.java @@ -0,0 +1,66 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.metamodel; + +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.body.BodyDeclaration; +import org.junit.jupiter.api.Test; + +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class PropertyMetaModelTest { + @Test + void whenPropertyIsVerySimpleThenTypeInfoIsCorrect() { + PropertyMetaModel bert = new PropertyMetaModel(null, "bert", int.class, Optional.empty(), false, false, false, false); + assertEquals("int", bert.getTypeName()); + assertEquals("int", bert.getTypeNameGenerified()); + assertEquals("int", bert.getTypeNameForGetter()); + assertEquals("int", bert.getTypeNameForSetter()); + } + + @Test + void whenPropertyIsVeryComplexThenTypeInfoIsCorrect() { + PropertyMetaModel bert = new PropertyMetaModel(null, "bert", BodyDeclaration.class, Optional.empty(), true, false, true, true); + assertEquals("BodyDeclaration", bert.getTypeName()); + assertEquals("BodyDeclaration", bert.getTypeNameGenerified()); + assertEquals("Optional>>", bert.getTypeNameForGetter()); + assertEquals("NodeList>", bert.getTypeNameForSetter()); + } + + @Test + void whenPropertyIsANodeListThenTypeInfoIsCorrect() { + PropertyMetaModel bert = new PropertyMetaModel(null, "bert", Modifier.class, Optional.empty(), false, false, true, false); + assertEquals("Modifier", bert.getTypeName()); + assertEquals("Modifier", bert.getTypeNameGenerified()); + assertEquals("NodeList", bert.getTypeNameForGetter()); + assertEquals("NodeList", bert.getTypeNameForSetter()); + } + + @Test + void metaModelFieldName() { + PropertyMetaModel bert = new PropertyMetaModel(null, "bert", Modifier.class, Optional.empty(), false, false, false, false); + assertEquals("bertPropertyMetaModel", bert.getMetaModelFieldName()); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/modules/ModuleDeclarationTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/modules/ModuleDeclarationTest.java new file mode 100644 index 0000000..2032626 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/modules/ModuleDeclarationTest.java @@ -0,0 +1,259 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.modules; + +import com.github.javaparser.*; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.expr.IntegerLiteralExpr; +import com.github.javaparser.ast.expr.MarkerAnnotationExpr; +import com.github.javaparser.ast.expr.Name; +import com.github.javaparser.ast.expr.SingleMemberAnnotationExpr; +import com.github.javaparser.ast.modules.*; +import com.github.javaparser.printer.ConcreteSyntaxModel; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.GeneratedJavaParserConstants.IDENTIFIER; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_9; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.StaticJavaParser.parseName; +import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol; +import static com.github.javaparser.utils.Utils.SYSTEM_EOL; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; + +class ModuleDeclarationTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_9)); + + private CompilationUnit parse(String code) { + ParseResult result = javaParser.parse(ParseStart.COMPILATION_UNIT, provider(code)); + if(!result.isSuccessful()){ + System.err.println(result); + } + return result.getResult().get(); + } + + @Test + void moduleInfoKeywordsAreSeenAsIdentifiers() { + CompilationUnit cu = parse("class module { }"); + JavaToken moduleToken = cu.getClassByName("module").get().getName().getTokenRange().get().getBegin(); + assertEquals(IDENTIFIER, moduleToken.getKind()); + } + + @Test + void issue988RequireTransitiveShouldRequireAModuleCalledTransitive() { + CompilationUnit cu = parse("module X { requires transitive; }"); + ModuleRequiresDirective requiresTransitive = (ModuleRequiresDirective) cu.getModule().get().getDirectives().get(0); + assertEquals("transitive", requiresTransitive.getNameAsString()); + assertEquals(IDENTIFIER, requiresTransitive.getName().getTokenRange().get().getBegin().getKind()); + } + + @Test + void jlsExample1() { + CompilationUnit cu = parse( + "@Foo(1) @Foo(2) @Bar " + + "module M.N {" + + " requires A.B;" + + " requires transitive C.D;" + + " requires static E.F;" + + " requires transitive static G.H;" + + "" + + " exports P.Q;" + + " exports R.S to T1.U1, T2.U2;" + + "" + + " opens P.Q;" + + " opens R.S to T1.U1, T2.U2;" + + "" + + " uses V.W;" + + " provides X.Y with Z1.Z2, Z3.Z4;" + + "}"); + + ModuleDeclaration module = cu.getModule().get(); + assertEquals("M.N", module.getNameAsString()); + assertFalse(module.isOpen()); + assertThat(module.getAnnotations()).containsExactly( + new SingleMemberAnnotationExpr(new Name("Foo"), new IntegerLiteralExpr("1")), + new SingleMemberAnnotationExpr(new Name("Foo"), new IntegerLiteralExpr("2")), + new MarkerAnnotationExpr(new Name("Bar"))); + + ModuleRequiresDirective moduleRequiresStmt = module.getDirectives().get(0).asModuleRequiresStmt(); + assertThat(moduleRequiresStmt.getNameAsString()).isEqualTo("A.B"); + assertThat(moduleRequiresStmt.getModifiers()).isEmpty(); + + ModuleExportsDirective moduleExportsStmt = module.getDirectives().get(5).asModuleExportsStmt(); + assertThat(moduleExportsStmt.getNameAsString()).isEqualTo("R.S"); + assertThat(moduleExportsStmt.getModuleNames()).containsExactly(parseName("T1.U1"), parseName("T2.U2")); + + ModuleOpensDirective moduleOpensStmt = module.getDirectives().get(7).asModuleOpensStmt(); + assertThat(moduleOpensStmt.getNameAsString()).isEqualTo("R.S"); + assertThat(moduleOpensStmt.getModuleNames()).containsExactly(parseName("T1.U1"), parseName("T2.U2")); + + ModuleUsesDirective moduleUsesStmt = module.getDirectives().get(8).asModuleUsesStmt(); + assertThat(moduleUsesStmt.getNameAsString()).isEqualTo("V.W"); + + ModuleProvidesDirective moduleProvidesStmt = module.getDirectives().get(9).asModuleProvidesStmt(); + assertThat(moduleProvidesStmt.getNameAsString()).isEqualTo("X.Y"); + assertThat(moduleProvidesStmt.getWith()).containsExactly( + parseName("Z1.Z2"), + parseName("Z3.Z4")); + + } + + @Test + void jlsExample2HasAnOpenModule() { + CompilationUnit cu = parse("open module M.N {}"); + + ModuleDeclaration module = cu.getModule().get(); + assertEquals("M.N", module.getNameAsString()); + assertTrue(module.isOpen()); + } + + @Test + void testPrettyPrinting() { + CompilationUnit cu = parse( + "@Foo(1) @Foo(2) @Bar " + + "module M.N {" + + " requires A.B;" + + " requires transitive C.D;" + + " requires static E.F;" + + " requires static transitive G.H;" + + "" + + " exports P.Q;" + + " exports R.S to T1.U1, T2.U2;" + + "" + + " opens P.Q;" + + " opens R.S to T1.U1, T2.U2;" + + "" + + " uses V.W;" + + " provides X.Y with Z1.Z2, Z3.Z4;" + + "}"); + + assertEquals( + "@Foo(1)" + SYSTEM_EOL + + "@Foo(2)" + SYSTEM_EOL + + "@Bar" + SYSTEM_EOL + + "module M.N {" + SYSTEM_EOL + + " requires A.B;" + SYSTEM_EOL + + " requires transitive C.D;" + SYSTEM_EOL + + " requires static E.F;" + SYSTEM_EOL + + " requires static transitive G.H;" + SYSTEM_EOL + + " exports P.Q;" + SYSTEM_EOL + + " exports R.S to T1.U1, T2.U2;" + SYSTEM_EOL + + " opens P.Q;" + SYSTEM_EOL + + " opens R.S to T1.U1, T2.U2;" + SYSTEM_EOL + + " uses V.W;" + SYSTEM_EOL + + " provides X.Y with Z1.Z2, Z3.Z4;" + SYSTEM_EOL + + "}" + SYSTEM_EOL, cu.toString()); + + } + + @Test + void testCsmPrinting() { + CompilationUnit cu = parse( + "@Foo(1) @Foo(2) @Bar " + + "open module M.N {" + + " requires A.B;" + + " requires transitive C.D;" + + " requires static E.F;" + + " requires transitive static G.H;" + + "" + + " exports P.Q;" + + " exports R.S to T1.U1, T2.U2;" + + "" + + " opens P.Q;" + + " opens R.S to T1.U1, T2.U2;" + + "" + + " uses V.W;" + + " provides X.Y with Z1.Z2, Z3.Z4;" + + "}"); + + assertEquals( + "@Foo(1)" + SYSTEM_EOL + + "@Foo(2)" + SYSTEM_EOL + + "@Bar" + SYSTEM_EOL + + "open module M.N {" + SYSTEM_EOL + + " requires A.B;" + SYSTEM_EOL + + " requires transitive C.D;" + SYSTEM_EOL + + " requires static E.F;" + SYSTEM_EOL + + " requires transitive static G.H;" + SYSTEM_EOL + + " exports P.Q;" + SYSTEM_EOL + + " exports R.S to T1.U1, T2.U2;" + SYSTEM_EOL + + " opens P.Q;" + SYSTEM_EOL + + " opens R.S to T1.U1, T2.U2;" + SYSTEM_EOL + + " uses V.W;" + SYSTEM_EOL + + " provides X.Y with Z1.Z2, Z3.Z4;" + SYSTEM_EOL + + "}" + SYSTEM_EOL, ConcreteSyntaxModel.genericPrettyPrint(cu)); + + } + + @Test + void fluentInterface() { + ModuleDeclaration moduleDeclaration = new CompilationUnit() + .setModule("com.laamella.base") + .addSingleMemberAnnotation(SuppressWarnings.class, "\"module\"") + .addDirective("requires transitive java.desktop;") + .addDirective("exports com.laamella.base.entity.channel;") + .addDirective("exports com.laamella.base.entity.channel.internal to com.laamella.core;") + .addDirective("uses com.laamella.base.util.internal.FactoryDelegate;"); + + moduleDeclaration.getDirectives() + .addLast(new ModuleExportsDirective() + .setName("foo.bar") + .addModuleName("other.foo") + .addModuleName("other.bar") + ); + + moduleDeclaration + .addDirective(new ModuleExportsDirective() + .setName("foo.bar.x") + .addModuleName("other.foo") + .addModuleName("other.bar") + ); + + assertEqualsStringIgnoringEol("@SuppressWarnings(\"module\")\n" + + "module com.laamella.base {\n" + + " requires transitive java.desktop;\n" + + " exports com.laamella.base.entity.channel;\n" + + " exports com.laamella.base.entity.channel.internal to com.laamella.core;\n" + + " uses com.laamella.base.util.internal.FactoryDelegate;\n" + + " exports foo.bar to other.foo, other.bar;\n" + + " exports foo.bar.x to other.foo, other.bar;\n" + + "}\n", moduleDeclaration.toString()); + } + + @Test + void testModifierRequire() { + ModuleDeclaration moduleDeclaration = new CompilationUnit() + .setModule("com.laamella.base") + .addDirective("requires transitive java.desktop;"); + ModuleRequiresDirective moduleRequiresStmt = moduleDeclaration.getDirectives().get(0).asModuleRequiresStmt(); + assertTrue(moduleRequiresStmt.isTransitive()); + } + + @Test + void testModifierStatic() { + ModuleDeclaration moduleDeclaration = new CompilationUnit() + .setModule("com.laamella.base") + .addDirective("requires static java.desktop;"); + ModuleRequiresDirective moduleRequiresStmt = moduleDeclaration.getDirectives().get(0).asModuleRequiresStmt(); + assertTrue(moduleRequiresStmt.isStatic()); + } +} 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 new file mode 100644 index 0000000..e29e22a --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/ConcreteSyntaxModelAcceptanceTest.java @@ -0,0 +1,66 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.utils.CodeGenerationUtils; +import com.github.javaparser.utils.TestUtils; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.nio.file.Path; + +import static com.github.javaparser.StaticJavaParser.parse; + +class ConcreteSyntaxModelAcceptanceTest { + private final Path rootDir = CodeGenerationUtils.mavenModuleRoot(ConcreteSyntaxModelAcceptanceTest.class).resolve("src/test/test_sourcecode"); + + private String prettyPrint(Node node) { + return ConcreteSyntaxModel.genericPrettyPrint(node); + } + + private String prettyPrintedExpectation(String name) throws IOException { + return TestUtils.readResource("com/github/javaparser/printer/" + name + "_prettyprinted"); + } + + @Test + void printingExamplePrettyPrintVisitor() throws IOException { + CompilationUnit cu = parse(rootDir.resolve("com/github/javaparser/printer/PrettyPrintVisitor.java")); + TestUtils.assertEqualsStringIgnoringEol(prettyPrintedExpectation("PrettyPrintVisitor"), prettyPrint(cu)); + } + + @Test + void printingExampleJavaConcepts() throws IOException { + 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/ConcreteSyntaxModelTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/ConcreteSyntaxModelTest.java new file mode 100644 index 0000000..df91566 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/ConcreteSyntaxModelTest.java @@ -0,0 +1,97 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.expr.ClassExpr; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.StaticJavaParser.*; +import static com.github.javaparser.utils.Utils.SYSTEM_EOL; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ConcreteSyntaxModelTest { + + private String print(Node node) { + return ConcreteSyntaxModel.genericPrettyPrint(node); + } + + @Test + void printSimpleClassExpr() { + ClassExpr expr = parseExpression("Foo.class"); + assertEquals("Foo.class", print(expr)); + } + + @Test + void printArrayClassExpr() { + ClassExpr expr = parseExpression("Foo[].class"); + assertEquals("Foo[].class", print(expr)); + } + + @Test + void printGenericClassExpr() { + ClassExpr expr = parseExpression("Foo.class"); + assertEquals("Foo.class", print(expr)); + } + + @Test + void printSimplestClass() { + Node node = parse("class A {}"); + assertEquals("class A {" + SYSTEM_EOL + + "}" + SYSTEM_EOL, print(node)); + } + + @Test + void printAClassWithField() { + Node node = parse("class A { int a; }"); + assertEquals("class A {" + SYSTEM_EOL + + SYSTEM_EOL + + " int a;" + SYSTEM_EOL + + "}" + SYSTEM_EOL, print(node)); + } + + @Test + void printParameters() { + Node node = parseBodyDeclaration("int x(int y, int z) {}"); + assertEquals("int x(int y, int z) {" + SYSTEM_EOL + "}", print(node)); + } + + @Test + void printReceiverParameter() { + Node node = parseBodyDeclaration("int x(X A.B.this, int y, int z) {}"); + assertEquals("int x(X A.B.this, int y, int z) {" + SYSTEM_EOL + "}", print(node)); + } + + @Test + void printAnEmptyInterface() { + Node node = parse("interface A {}"); + assertEquals("interface A {" + SYSTEM_EOL + + "}" + SYSTEM_EOL, print(node)); + } + + @Test + void printAnEmptyInterfaceWithModifier() { + Node node = parse("public interface A {}"); + assertEquals("public interface A {" + SYSTEM_EOL + + "}" + SYSTEM_EOL, print(node)); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/DefaultPrettyPrinterTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/DefaultPrettyPrinterTest.java new file mode 100644 index 0000000..8125f73 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/DefaultPrettyPrinterTest.java @@ -0,0 +1,665 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.*; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.FieldDeclaration; +import com.github.javaparser.ast.body.TypeDeclaration; +import com.github.javaparser.ast.expr.VariableDeclarationExpr; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.ast.type.PrimitiveType; +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.Indentation; +import com.github.javaparser.printer.configuration.Indentation.IndentType; +import com.github.javaparser.printer.configuration.PrinterConfiguration; +import com.github.javaparser.printer.configuration.imports.EclipseImportOrderingStrategy; +import com.github.javaparser.printer.configuration.imports.IntelliJImportOrderingStrategy; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.ParseStart.COMPILATION_UNIT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_9; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.StaticJavaParser.*; +import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class DefaultPrettyPrinterTest { + + private final JavaParser javaParser = new JavaParser(); + + private final JavaParserAdapter parserAdapter = JavaParserAdapter.of(javaParser); + + private final PrinterConfiguration printerConfiguration = new DefaultPrinterConfiguration(); + + private Printer getDefaultPrinter() { + PrinterConfiguration configuration = new DefaultPrinterConfiguration(); + return new DefaultPrettyPrinter(configuration); + } + + private Printer getDefaultPrinter(PrinterConfiguration configuration) { + return new DefaultPrettyPrinter(configuration); + } + + private String prettyPrintField(String code) { + CompilationUnit cu = parse(code); + return getDefaultPrinter().print(cu.findFirst(FieldDeclaration.class).get()); + } + + private String prettyPrintVar(String code) { + CompilationUnit cu = parse(code); + return getDefaultPrinter().print(cu.findAll(VariableDeclarationExpr.class).get(0)); + } + + @Test + void printingArrayFields() { + String code; + code = "class A { int a, b[]; }"; + assertEquals("int a, b[];", prettyPrintField(code)); + + code = "class A { int[] a[], b[]; }"; + assertEquals("int[][] a, b;", prettyPrintField(code)); + + code = "class A { int[] a[][], b; }"; + assertEquals("int[] a[][], b;", prettyPrintField(code)); + + code = "class A { int[] a, b; }"; + assertEquals("int[] a, b;", prettyPrintField(code)); + + code = "class A { int a[], b[]; }"; + assertEquals("int[] a, b;", prettyPrintField(code)); + } + + @Test + void printingArrayVariables() { + String code; + code = "class A { void foo(){ int a, b[]; }}"; + assertEquals("int a, b[]", prettyPrintVar(code)); + + code = "class A { void foo(){ int[] a[], b[]; }}"; + assertEquals("int[][] a, b", prettyPrintVar(code)); + + code = "class A { void foo(){ int[] a[][], b; }}"; + assertEquals("int[] a[][], b", prettyPrintVar(code)); + + code = "class A { void foo(){ int[] a, b; }}"; + assertEquals("int[] a, b", prettyPrintVar(code)); + + code = "class A { void foo(){ int a[], b[]; }}"; + assertEquals("int[] a, b", prettyPrintVar(code)); + } + + @Disabled + private String prettyPrintConfigurable(String code) { + CompilationUnit cu = parse(code); + return getDefaultPrinter().print(cu.findFirst(ClassOrInterfaceDeclaration.class).get().getName()); + } + + @Test + void printUseTestVisitor() { + String code; + code = "class A { void foo(){ int a, b[]; }}"; + assertEquals("A", prettyPrintConfigurable(code)); + } + + @Test + void prettyColumnAlignParameters_enabled() { + PrinterConfiguration configuration = new DefaultPrinterConfiguration() + .addOption(new DefaultConfigurationOption(ConfigOption.COLUMN_ALIGN_FIRST_METHOD_CHAIN)) + .addOption(new DefaultConfigurationOption(ConfigOption.COLUMN_ALIGN_PARAMETERS)); + + final String EOL = configuration.get(new DefaultConfigurationOption(ConfigOption.END_OF_LINE_CHARACTER)).get().asString(); + + String code = "class Example { void foo(Object arg0,Object arg1){ myMethod(1, 2, 3, 5, Object.class); } }"; + String expected = "class Example {" + EOL + + "" + EOL + + " void foo(Object arg0, Object arg1) {" + EOL + + " myMethod(1," + EOL + + " 2," + EOL + + " 3," + EOL + + " 5," + EOL + + " Object.class);" + EOL + + " }" + EOL + + "}" + EOL + + ""; + + assertEquals(expected, getDefaultPrinter(configuration).print(parse(code))); + } + + @Test + void prettyColumnAlignParameters_disabled() { + + PrinterConfiguration configuration = new DefaultPrinterConfiguration(); + final String EOL = configuration.get(new DefaultConfigurationOption(ConfigOption.END_OF_LINE_CHARACTER)).get().asString(); + + String code = "class Example { void foo(Object arg0,Object arg1){ myMethod(1, 2, 3, 5, Object.class); } }"; + String expected = "class Example {" + EOL + + "" + EOL + + " void foo(Object arg0, Object arg1) {" + EOL + + " myMethod(1, 2, 3, 5, Object.class);" + EOL + + " }" + EOL + + "}" + EOL + + ""; + + assertEquals(expected, getDefaultPrinter(configuration).print(parse(code))); + } + + @Test + void prettyAlignMethodCallChains_enabled() { + + PrinterConfiguration configuration = new DefaultPrinterConfiguration() + .addOption(new DefaultConfigurationOption(ConfigOption.COLUMN_ALIGN_FIRST_METHOD_CHAIN)); + + final String EOL = configuration.get(new DefaultConfigurationOption(ConfigOption.END_OF_LINE_CHARACTER)).get().asString(); + + String code = "class Example { void foo() { IntStream.range(0, 10).filter(x -> x % 2 == 0).map(x -> x * IntStream.of(1,3,5,1).sum()).forEach(System.out::println); } }"; + String expected = "class Example {" + EOL + + "" + EOL + + " void foo() {" + EOL + + " IntStream.range(0, 10)" + EOL + + " .filter(x -> x % 2 == 0)" + EOL + + " .map(x -> x * IntStream.of(1, 3, 5, 1)" + EOL + + " .sum())" + EOL + + " .forEach(System.out::println);" + EOL + + " }" + EOL + + "}" + EOL + + ""; + + String printed = getDefaultPrinter(configuration).print(parse(code)); + + assertEquals(expected, printed); + } + + @Test + void prettyAlignMethodCallChains_disabled() { + + PrinterConfiguration configuration = new DefaultPrinterConfiguration(); + final String EOL = configuration.get(new DefaultConfigurationOption(ConfigOption.END_OF_LINE_CHARACTER)).get().asString(); + + String code = "class Example { void foo() { IntStream.range(0, 10).filter(x -> x % 2 == 0).map(x -> x * IntStream.of(1,3,5,1).sum()).forEach(System.out::println); } }"; + String expected = "class Example {" + EOL + + "" + EOL + + " void foo() {" + EOL + + " IntStream.range(0, 10).filter(x -> x % 2 == 0).map(x -> x * IntStream.of(1, 3, 5, 1).sum()).forEach(System.out::println);" + EOL + + " }" + EOL + + "}" + EOL + + ""; + + assertEquals(expected, getDefaultPrinter(configuration).print(parse(code))); + } + + @Test + void enumConstantsHorizontally() { + CompilationUnit cu = parse("enum X{A, B, C, D, E}"); + assertEqualsStringIgnoringEol("enum X {\n\n A, B, C, D, E\n}\n", new DefaultPrettyPrinter().print(cu)); + } + + @Test + void enumConstantsVertically() { + CompilationUnit cu = parse("enum X{A, B, C, D, E, F}"); + assertEqualsStringIgnoringEol("enum X {\n\n A,\n B,\n C,\n D,\n E,\n F\n}\n", new DefaultPrettyPrinter().print(cu)); + } + + @Test + void printingInconsistentVariables() { + FieldDeclaration fieldDeclaration = parseBodyDeclaration("int a, b;").asFieldDeclaration(); + + assertEquals("int a, b;", fieldDeclaration.toString()); + + fieldDeclaration.getVariable(0).setType(PrimitiveType.doubleType()); + + assertEquals("??? a, b;", fieldDeclaration.toString()); + + fieldDeclaration.getVariable(1).setType(PrimitiveType.doubleType()); + + assertEquals("double a, b;", fieldDeclaration.toString()); + } + + @Test + void prettyAlignMethodCallChainsIndentsArgumentsWithBlocksCorrectly() { + + CompilationUnit cu = parse("class Foo { void bar() { a.b.c.d.e; a.b.c().d().e(); a.b.c().d.e(); foo().bar().baz(boo().baa().bee()).bam(); foo().bar().baz(boo().baa().bee()).bam; foo().bar(Long.foo().b.bar(), bam).baz(); foo().bar().baz(foo, () -> { boo().baa().bee(); }).baz(() -> { boo().baa().bee(); }).bam(() -> { boo().baa().bee(); }); } }"); + + Indentation indentation = new Indentation(IndentType.TABS_WITH_SPACE_ALIGN, 1); + PrinterConfiguration configuration = new DefaultPrinterConfiguration() + .addOption(new DefaultConfigurationOption(ConfigOption.COLUMN_ALIGN_FIRST_METHOD_CHAIN)) + .addOption(new DefaultConfigurationOption(ConfigOption.COLUMN_ALIGN_PARAMETERS)) + .addOption(new DefaultConfigurationOption(ConfigOption.INDENTATION, indentation)); + String printed = getDefaultPrinter(configuration).print(cu); + + assertEqualsStringIgnoringEol("class Foo {\n" + + "\n" + + "\tvoid bar() {\n" + + "\t\ta.b.c.d.e;\n" + + "\t\ta.b.c()\n" + + "\t\t .d()\n" + + "\t\t .e();\n" + + "\t\ta.b.c().d\n" + + "\t\t .e();\n" + + "\t\tfoo().bar()\n" + + "\t\t .baz(boo().baa().bee())\n" + + "\t\t .bam();\n" + + "\t\tfoo().bar()\n" + + "\t\t .baz(boo().baa().bee()).bam;\n" + + "\t\tfoo().bar(Long.foo().b.bar(),\n" + + "\t\t bam)\n" + + "\t\t .baz();\n" + + "\t\tfoo().bar()\n" + + "\t\t .baz(foo,\n" + + "\t\t () -> {\n" + + "\t\t \tboo().baa()\n" + + "\t\t \t .bee();\n" + + "\t\t })\n" + + "\t\t .baz(() -> {\n" + + "\t\t \tboo().baa()\n" + + "\t\t \t .bee();\n" + + "\t\t })\n" + + "\t\t .bam(() -> {\n" + + "\t\t \tboo().baa()\n" + + "\t\t \t .bee();\n" + + "\t\t });\n" + + "\t}\n" + + "}\n", printed); + } + + @Test + void noChainsIndentsInIf() { + Statement cu = parseStatement("if (x.y().z()) { boo().baa().bee(); }"); + + PrinterConfiguration configuration = new DefaultPrinterConfiguration().addOption(new DefaultConfigurationOption(ConfigOption.COLUMN_ALIGN_FIRST_METHOD_CHAIN)); + String printed = getDefaultPrinter(configuration).print(cu); + + assertEqualsStringIgnoringEol("if (x.y().z()) {\n" + + " boo().baa()\n" + + " .bee();\n" + + "}", printed); + } + + @Test + void noChainsIndentsInFor() { + Statement cu = parseStatement("for(int x=1; x.y().z(); x.z().z()) { boo().baa().bee(); }"); + + PrinterConfiguration configuration = new DefaultPrinterConfiguration().addOption(new DefaultConfigurationOption(ConfigOption.COLUMN_ALIGN_FIRST_METHOD_CHAIN)); + String printed = getDefaultPrinter(configuration).print(cu); + + assertEqualsStringIgnoringEol("for (int x = 1; x.y().z(); x.z().z()) {\n" + + " boo().baa()\n" + + " .bee();\n" + + "}", printed); + } + + @Test + void noChainsIndentsInWhile() { + Statement cu = parseStatement("while(x.y().z()) { boo().baa().bee(); }"); + + PrinterConfiguration configuration = new DefaultPrinterConfiguration() + .addOption(new DefaultConfigurationOption(ConfigOption.COLUMN_ALIGN_FIRST_METHOD_CHAIN)); + String printed = getDefaultPrinter(configuration).print(cu); + + assertEqualsStringIgnoringEol("while (x.y().z()) {\n" + + " boo().baa()\n" + + " .bee();\n" + + "}", printed); + } + + @Test + void indentWithTabsAsFarAsPossible() { + + CompilationUnit cu = parse("class Foo { void bar() { foo().bar().baz(() -> { boo().baa().bee(a, b, c); }).bam(); } }"); + + Indentation indentation = new Indentation(IndentType.TABS, 1); + PrinterConfiguration configuration = new DefaultPrinterConfiguration() + .addOption(new DefaultConfigurationOption(ConfigOption.COLUMN_ALIGN_FIRST_METHOD_CHAIN)) + .addOption(new DefaultConfigurationOption(ConfigOption.COLUMN_ALIGN_PARAMETERS)) + .addOption(new DefaultConfigurationOption(ConfigOption.INDENTATION, indentation)); + + String printed = getDefaultPrinter(configuration).print(cu); + + assertEqualsStringIgnoringEol("class Foo {\n" + + "\n" + + "\tvoid bar() {\n" + + "\t\tfoo().bar()\n" + + "\t\t\t .baz(() -> {\n" + + "\t\t\t\t boo().baa()\n" + + "\t\t\t\t\t .bee(a,\n" + + "\t\t\t\t\t\t b,\n" + + "\t\t\t\t\t\t c);\n" + + "\t\t\t })\n" + + "\t\t\t .bam();\n" + + "\t}\n" + + "}\n", printed); + } + + @Test + void indentWithTabsAlignWithSpaces() { + + CompilationUnit cu = parse("class Foo { void bar() { foo().bar().baz(() -> { boo().baa().bee(a, b, c); }).baz(() -> { return boo().baa(); }).bam(); } }"); + + Indentation indentation = new Indentation(IndentType.TABS_WITH_SPACE_ALIGN, 1); + PrinterConfiguration configuration = new DefaultPrinterConfiguration() + .addOption(new DefaultConfigurationOption(ConfigOption.COLUMN_ALIGN_FIRST_METHOD_CHAIN)) + .addOption(new DefaultConfigurationOption(ConfigOption.COLUMN_ALIGN_PARAMETERS)) + .addOption(new DefaultConfigurationOption(ConfigOption.INDENTATION, indentation)); + + String printed = getDefaultPrinter(configuration).print(cu); + + assertEqualsStringIgnoringEol("class Foo {\n" + + "\n" + + "\tvoid bar() {\n" + + "\t\tfoo().bar()\n" + + "\t\t .baz(() -> {\n" + + "\t\t \tboo().baa()\n" + + "\t\t \t .bee(a,\n" + + "\t\t \t b,\n" + + "\t\t \t c);\n" + + "\t\t })\n" + + "\t\t .baz(() -> {\n" + + "\t\t \treturn boo().baa();\n" + + "\t\t })\n" + + "\t\t .bam();\n" + + "\t}\n" + + "}\n", printed); + } + + @Test + void printAnnotationsAtPrettyPlaces() { + + JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_9)); + ParseResult parseResult = javaParser.parse(COMPILATION_UNIT, provider("@Documented\n" + + "@Repeatable\n" + + "package com.github.javaparser;\n" + + "\n" + + "import java.lang.annotation.Documented;\n" + + "import java.lang.annotation.Repeatable;\n" + + "\n" + + "@Documented\n" + + "@Repeatable\n" + + "@interface Annotation {\n" + + "\n" + + " @Documented\n" + + " @Repeatable\n" + + " String value();\n" + + "}\n" + + "\n" + + "@Documented\n" + + "@Repeatable\n" + + "class Class<@Documented @Repeatable T> {\n" + + "\n" + + " @Documented\n" + + " @Repeatable\n" + + " byte b;\n" + + "\n" + + " @Documented\n" + + " @Repeatable\n" + + " Class(@Documented @Repeatable int i) {\n" + + " @Documented\n" + + " @Repeatable\n" + + " short s;\n" + + " }\n" + + "\n" + + " @Documented\n" + + " @Repeatable\n" + + " void method(@Documented @Repeatable Class this) {\n" + + " for (@Deprecated int i : arr4[0]) {\n" + + " x--;\n" + + " }\n" + + " }\n" + + "\n" + + " void method(@Documented @Repeatable Class this, int i) {\n" + + " }\n" + + "}\n" + + "\n" + + "@Documented\n" + + "@Repeatable\n" + + "enum Foo {\n" + + "\n" + + " @Documented\n" + + " @Repeatable\n" + + " BAR\n" + + "}\n" + + "@Documented\n" + + "@Repeatable\n" + + "module foo.bar {\n" + + "}\n")); + if (!parseResult.isSuccessful()) { + throw new ParseProblemException(parseResult.getProblems()); + } + CompilationUnit cu = parseResult.getResult().orElseThrow(AssertionError::new); + String printed = getDefaultPrinter().print(cu); + + assertEqualsStringIgnoringEol("@Documented\n" + + "@Repeatable\n" + + "package com.github.javaparser;\n" + + "\n" + + "import java.lang.annotation.Documented;\n" + + "import java.lang.annotation.Repeatable;\n" + + "\n" + + "@Documented\n" + + "@Repeatable\n" + + "@interface Annotation {\n" + + "\n" + + " @Documented\n" + + " @Repeatable\n" + + " String value();\n" + + "}\n" + + "\n" + + "@Documented\n" + + "@Repeatable\n" + + "class Class<@Documented @Repeatable T> {\n" + + "\n" + + " @Documented\n" + + " @Repeatable\n" + + " byte b;\n" + + "\n" + + " @Documented\n" + + " @Repeatable\n" + + " Class(@Documented @Repeatable int i) {\n" + + " @Documented\n" + + " @Repeatable\n" + + " short s;\n" + + " }\n" + + "\n" + + " @Documented\n" + + " @Repeatable\n" + + " void method(@Documented @Repeatable Class this) {\n" + + " for (@Deprecated int i : arr4[0]) {\n" + + " x--;\n" + + " }\n" + + " }\n" + + "\n" + + " void method(@Documented @Repeatable Class this, int i) {\n" + + " }\n" + + "}\n" + + "\n" + + "@Documented\n" + + "@Repeatable\n" + + "enum Foo {\n" + + "\n" + + " @Documented\n" + + " @Repeatable\n" + + " BAR\n" + + "}\n" + + "@Documented\n" + + "@Repeatable\n" + + "module foo.bar {\n" + + "}\n", printed); + } + + @Test + public void testIssue2578() { + String code = + "class C{\n" + + " //orphan\n" + + " /*orphan*/\n" + + "}"; + CompilationUnit cu = StaticJavaParser.parse(code); + TypeDeclaration td = cu.findFirst(TypeDeclaration.class).get(); + assertEquals(2, td.getAllContainedComments().size()); + td.setPublic(true); // --- simple AST change ----- + assertEquals(2, td.getAllContainedComments().size()); // the orphaned comments exist + } + + @Test + public void testIssue2535() { + + String code = + "public class A {\n" + + " public static A m() {\n" + + " System.out.println(\"\");\n" + + " // TODO\n" + + " /* TODO */\n" + + " /** TODO */\n" + + " }\n" + + "}"; + + StaticJavaParser.setConfiguration(new ParserConfiguration()); + + CompilationUnit cu = StaticJavaParser.parse(code); + + // default indent is 4 spaces + assertTrue(cu.toString().contains(" // TODO")); + assertTrue(cu.toString().contains(" /* TODO */")); + + } + + @Test + public void testIndentationWithDefaultSize() { + Indentation indentation = new Indentation(IndentType.SPACES); + assertTrue(indentation.getSize()==4); + assertEquals(" ", indentation.getIndent()); + // on-the-fly modification + indentation.setSize(2); + assertTrue(indentation.getSize()==2); + assertEquals(" ", indentation.getIndent()); + } + + @Test + public void testIndentationWithCustomSize() { + Indentation indentation = new Indentation(IndentType.TABS,2); + assertTrue(indentation.getSize()==2); + assertEquals("\t\t", indentation.getIndent()); + } + + @Test + public void testIndentationWithOnTheFlyModifcation() { + Indentation indentation = new Indentation(IndentType.SPACES); + // on-the-fly modification + indentation.setSize(2); + assertTrue(indentation.getSize()==2); + assertEquals(" ", indentation.getIndent()); + indentation.setType(IndentType.TABS); + assertTrue(indentation.getType() == IndentType.TABS); + assertEquals("\t\t", indentation.getIndent()); + } + + @Test + public void testIssue3317() { + + String code = "public class Test {\n" + + " protected void someMethod() {\n" + + " // Before\n" + + " System.out\n"+ + " // Middle Comment\n" + + " .println(\"\");\n" + + " // After\n" + + " }\n" + + "}"; + + String expected = "public class Test {\n" + + "\n" + + " protected void someMethod() {\n" + + " // Before\n" + + " System.out.// Middle Comment\n" + + " println(\"\");\n" + + " // After\n" + + " }\n" + + "}\n"; + + StaticJavaParser.setConfiguration(new ParserConfiguration()); + + CompilationUnit cu = StaticJavaParser.parse(code); + + assertEqualsStringIgnoringEol(expected, cu.toString()); + + } + + @Test + void testPrinterWithIntelliJImportOrdering() { + + String expectedCode = "package com.github.javaparser.printer;\n" + + "\n" + + "import com.github.javaparser.ast.Node;\n" + + "\n" + + "import java.util.Optional;\n" + + "import java.util.List;\n" + + "\n" + + "public interface TestClass {\n" + + "\n" + + " Node getRoot();\n" + + "\n" + + " List getChildern();\n" + + "}\n"; + + IntelliJImportOrderingStrategy strategy = new IntelliJImportOrderingStrategy(); + printerConfiguration.addOption(new DefaultConfigurationOption(ConfigOption.SORT_IMPORTS_STRATEGY, strategy)); + + CompilationUnit cu = parserAdapter.parse(expectedCode); + Printer printer = getDefaultPrinter(printerConfiguration); + String actualCode = printer.print(cu); + + assertEqualsStringIgnoringEol(expectedCode, actualCode); + } + + @Test + void testPrinterWithEclipseImportOrdering() { + + String expectedCode = "package com.github.javaparser.printer;\n" + + "\n" + + "import java.util.Optional;\n" + + "import java.util.List;\n" + + "\n" + + "import com.github.javaparser.ast.Node;\n" + + "\n" + + "public interface TestClass {\n" + + "\n" + + " Node getRoot();\n" + + "\n" + + " List getChildern();\n" + + "}\n"; + + EclipseImportOrderingStrategy strategy = new EclipseImportOrderingStrategy(); + printerConfiguration.addOption(new DefaultConfigurationOption(ConfigOption.SORT_IMPORTS_STRATEGY, strategy)); + + CompilationUnit cu = parserAdapter.parse(expectedCode); + Printer printer = getDefaultPrinter(printerConfiguration); + String actualCode = printer.print(cu); + + assertEqualsStringIgnoringEol(expectedCode, actualCode); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/DotPrinterTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/DotPrinterTest.java new file mode 100644 index 0000000..8365c2b --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/DotPrinterTest.java @@ -0,0 +1,105 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.expr.Expression; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.StaticJavaParser.parse; +import static com.github.javaparser.StaticJavaParser.parseExpression; +import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class DotPrinterTest { + @Test + void testWithType() { + String expectedOutput = "digraph {" + System.lineSeparator(); + expectedOutput += "n0 [label=\"root (MethodCallExpr)\"];" + System.lineSeparator(); + expectedOutput += "n1 [label=\"name (SimpleName)\"];" + System.lineSeparator(); + expectedOutput += "n0 -> n1;" + System.lineSeparator(); + expectedOutput += "n2 [label=\"identifier='x'\"];" + System.lineSeparator(); + expectedOutput += "n1 -> n2;" + System.lineSeparator(); + expectedOutput += "n3 [label=\"arguments\"];" + System.lineSeparator(); + expectedOutput += "n0 -> n3;" + System.lineSeparator(); + expectedOutput += "n4 [label=\"argument (IntegerLiteralExpr)\"];" + System.lineSeparator(); + expectedOutput += "n3 -> n4;" + System.lineSeparator(); + expectedOutput += "n5 [label=\"value='1'\"];" + System.lineSeparator(); + expectedOutput += "n4 -> n5;" + System.lineSeparator(); + expectedOutput += "n6 [label=\"argument (IntegerLiteralExpr)\"];" + System.lineSeparator(); + expectedOutput += "n3 -> n6;" + System.lineSeparator(); + expectedOutput += "n7 [label=\"value='1'\"];" + System.lineSeparator(); + expectedOutput += "n6 -> n7;" + System.lineSeparator(); + expectedOutput += "}"; + + DotPrinter dotPrinter = new DotPrinter(true); + Expression expression = parseExpression("x(1,1)"); + String output = dotPrinter.output(expression); + assertEquals(expectedOutput, output); + } + + @Test + void testWithoutType() { + String expectedOutput = "digraph {" + System.lineSeparator(); + expectedOutput += "n0 [label=\"root\"];" + System.lineSeparator(); + expectedOutput += "n1 [label=\"operator='PLUS'\"];" + System.lineSeparator(); + expectedOutput += "n0 -> n1;" + System.lineSeparator(); + expectedOutput += "n2 [label=\"left\"];" + System.lineSeparator(); + expectedOutput += "n0 -> n2;" + System.lineSeparator(); + expectedOutput += "n3 [label=\"value='1'\"];" + System.lineSeparator(); + expectedOutput += "n2 -> n3;" + System.lineSeparator(); + expectedOutput += "n4 [label=\"right\"];" + System.lineSeparator(); + expectedOutput += "n0 -> n4;" + System.lineSeparator(); + expectedOutput += "n5 [label=\"value='1'\"];" + System.lineSeparator(); + expectedOutput += "n4 -> n5;" + System.lineSeparator(); + expectedOutput += "}"; + + DotPrinter dotPrinter = new DotPrinter(false); + Expression expression = parseExpression("1+1"); + String output = dotPrinter.output(expression); + assertEquals(expectedOutput, output); + } + + @Test + void testIssue1871() { + DotPrinter printer = new DotPrinter(false); + CompilationUnit cu = parse("//q\"q\nclass X{}"); + String output = printer.output(cu); + assertEqualsStringIgnoringEol("digraph {\n" + + "n0 [label=\"root\"];\n" + + "n1 [label=\"types\"];\n" + + "n0 -> n1;\n" + + "n2 [label=\"type\"];\n" + + "n1 -> n2;\n" + + "n3 [label=\"isInterface='false'\"];\n" + + "n2 -> n3;\n" + + "n4 [label=\"name\"];\n" + + "n2 -> n4;\n" + + "n5 [label=\"identifier='X'\"];\n" + + "n4 -> n5;\n" + + "n6 [label=\"comment\"];\n" + + "n2 -> n6;\n" + + "n7 [label=\"content='q\\\"q'\"];\n" + + "n6 -> n7;\n" + + "}", output); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/JsonPrinterTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/JsonPrinterTest.java new file mode 100644 index 0000000..81a86c6 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/JsonPrinterTest.java @@ -0,0 +1,20 @@ +/* + * Copyright (C) 2013-2024 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. + */ + 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 new file mode 100644 index 0000000..b47641e --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/PrettyPrintVisitorTest.java @@ -0,0 +1,539 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +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; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.comments.LineComment; +import com.github.javaparser.ast.expr.CastExpr; +import com.github.javaparser.ast.expr.ClassExpr; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.expr.VariableDeclarationExpr; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.ast.type.Type; +import com.github.javaparser.printer.configuration.ConfigurationOption; +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; +import com.github.javaparser.utils.TestParser; + +class PrettyPrintVisitorTest extends TestParser { + + private Optional getOption(PrinterConfiguration config, ConfigOption cOption) { + return config.get(new DefaultConfigurationOption(cOption)); + } + + @Test + void getMaximumCommonTypeWithoutAnnotations() { + VariableDeclarationExpr vde1 = parseVariableDeclarationExpr("int a[], b[]"); + assertEquals("int[]", vde1.getMaximumCommonType().get().toString()); + + VariableDeclarationExpr vde2 = parseVariableDeclarationExpr("int[][] a[], b[]"); + assertEquals("int[][][]", vde2.getMaximumCommonType().get().toString()); + + VariableDeclarationExpr vde3 = parseVariableDeclarationExpr("int[][] a, b[]"); + assertEquals("int[][]", vde3.getMaximumCommonType().get().toString()); + } + + @Test + void getMaximumCommonTypeWithAnnotations() { + VariableDeclarationExpr vde1 = parseVariableDeclarationExpr("int a @Foo [], b[]"); + assertEquals("int", vde1.getMaximumCommonType().get().toString()); + + VariableDeclarationExpr vde2 = parseVariableDeclarationExpr("int[]@Foo [] a[], b[]"); + assertEquals("int[][] @Foo []", vde2.getMaximumCommonType().get().toString()); + } + + private String print(Node node) { + return new DefaultPrettyPrinter().print(node); + } + + private String print(Node node, PrinterConfiguration conf) { + return new DefaultPrettyPrinter(conf).print(node); + } + + + @Test + void printSimpleClassExpr() { + ClassExpr expr = parseExpression("Foo.class"); + assertEquals("Foo.class", print(expr)); + } + + + /** + * Here is a simple test according to R0 (removing spaces) + */ + @Test + void printOperatorsR0(){ + PrinterConfiguration conf1 = new DefaultPrinterConfiguration().removeOption(new DefaultConfigurationOption(ConfigOption.SPACE_AROUND_OPERATORS)); + Statement statement1 = parseStatement("a = 1 + 1;"); + assertEquals("a=1+1;", print(statement1, conf1)); + } + + /** + * Here we test different operators according to requirement R1 (handling different operators) + */ + @Test + void printOperatorsR1(){ + + Statement statement1 = parseStatement("a = 1 + 1;"); + assertEquals("a = 1 + 1;", print(statement1)); + + Statement statement2 = parseStatement("a = 1 - 1;"); + assertEquals("a = 1 - 1;", print(statement2)); + + Statement statement3 = parseStatement("a = 1 * 1;"); + assertEquals("a = 1 * 1;", print(statement3)); + + Statement statement4 = parseStatement("a = 1 % 1;"); + assertEquals("a = 1 % 1;", print(statement4)); + + Statement statement5 = parseStatement("a=1/1;"); + assertEquals("a = 1 / 1;", print(statement5)); + + Statement statement6 = parseStatement("if (1 > 2 && 1 < 3 || 1 < 3){}"); + assertEquals("if (1 > 2 && 1 < 3 || 1 < 3) {" + SYSTEM_EOL + + "}", print(statement6)); + + } + + /** + * Here is a simple test according to R2 (that it should be optional/modifiable) + */ + @Test + void printOperatorsR2(){ + PrinterConfiguration conf1 = new DefaultPrinterConfiguration().removeOption(new DefaultConfigurationOption(ConfigOption.SPACE_AROUND_OPERATORS)); + Statement statement1 = parseStatement("a = 1 + 1;"); + assertEquals("a=1+1;", print(statement1, conf1)); + + PrinterConfiguration conf2 = new DefaultPrinterConfiguration().removeOption(new DefaultConfigurationOption(ConfigOption.SPACE_AROUND_OPERATORS)); + Statement statement2 = parseStatement("a=1+1;"); + assertEquals("a=1+1;", print(statement2, conf2)); + + PrinterConfiguration conf3 = new DefaultPrinterConfiguration().addOption(new DefaultConfigurationOption(ConfigOption.SPACE_AROUND_OPERATORS)); + Statement statement3 = parseStatement("a = 1 + 1;"); + assertEquals("a = 1 + 1;", print(statement3, conf3)); + + PrinterConfiguration conf4 = new DefaultPrinterConfiguration().addOption(new DefaultConfigurationOption(ConfigOption.SPACE_AROUND_OPERATORS)); + Statement statement4 = parseStatement("a=1+1;"); + assertEquals("a = 1 + 1;", print(statement4, conf4)); + + } + + @Test + void printOperatorA(){ + PrinterConfiguration conf = new DefaultPrinterConfiguration().removeOption(new DefaultConfigurationOption(ConfigOption.SPACE_AROUND_OPERATORS)); + Statement statement6 = parseStatement("if(1>2&&1<3||1<3){}"); + assertEquals("if (1>2&&1<3||1<3) {" + SYSTEM_EOL + + "}", print(statement6, conf)); + } + + @Test + void printOperator2(){ + Expression expression = parseExpression("1+1"); + PrinterConfiguration spaces = new DefaultPrinterConfiguration().removeOption(new DefaultConfigurationOption(ConfigOption.SPACE_AROUND_OPERATORS)); + assertEquals("1+1", print(expression, spaces)); + } + + @Test + void printArrayClassExpr() { + ClassExpr expr = parseExpression("Foo[].class"); + assertEquals("Foo[].class", print(expr)); + } + + @Test + void printGenericClassExpr() { + ClassExpr expr = parseExpression("Foo.class"); + assertEquals("Foo.class", print(expr)); + } + + @Test + void printSimplestClass() { + Node node = parse("class A {}"); + assertEquals("class A {" + SYSTEM_EOL + + "}" + SYSTEM_EOL, print(node)); + } + + @Test + void printAClassWithField() { + Node node = parse("class A { int a; }"); + assertEquals("class A {" + SYSTEM_EOL + + SYSTEM_EOL + + " int a;" + SYSTEM_EOL + + "}" + SYSTEM_EOL, print(node)); + } + + @Test + void printAReceiverParameter() { + Node node = parseBodyDeclaration("int x(@O X A.B.this, int y) { }"); + assertEquals("int x(@O X A.B.this, int y) {" + SYSTEM_EOL + "}", print(node)); + } + + @Test + void printLambdaIntersectionTypeAssignment() { + String code = "class A {" + SYSTEM_EOL + + " void f() {" + SYSTEM_EOL + + " Runnable r = (Runnable & Serializable) (() -> {});" + SYSTEM_EOL + + " r = (Runnable & Serializable)() -> {};" + SYSTEM_EOL + + " r = (Runnable & I)() -> {};" + SYSTEM_EOL + + " }}"; + CompilationUnit cu = parse(code); + MethodDeclaration methodDeclaration = (MethodDeclaration) cu.getType(0).getMember(0); + + assertEquals("Runnable r = (Runnable & Serializable) (() -> {" + SYSTEM_EOL + "});", print(methodDeclaration.getBody().get().getStatements().get(0))); + } + + @Test + void printIntersectionType() { + String code = "(Runnable & Serializable) (() -> {})"; + Expression expression = parseExpression(code); + Type type = ((CastExpr) expression).getType(); + + assertEquals("Runnable & Serializable", print(type)); + } + + @Test + void printLambdaIntersectionTypeReturn() { + String code = "class A {" + SYSTEM_EOL + + " Object f() {" + SYSTEM_EOL + + " return (Comparator> & Serializable)(c1, c2) -> c1.getKey().compareTo(c2.getKey()); " + SYSTEM_EOL + + "}}"; + CompilationUnit cu = parse(code); + MethodDeclaration methodDeclaration = (MethodDeclaration) cu.getType(0).getMember(0); + + assertEquals("return (Comparator> & Serializable) (c1, c2) -> c1.getKey().compareTo(c2.getKey());", print(methodDeclaration.getBody().get().getStatements().get(0))); + } + + @Test + void printClassWithoutJavaDocButWithComment() { + String code = String.format("/** javadoc */ public class A { %s// stuff%s}", SYSTEM_EOL, SYSTEM_EOL); + CompilationUnit cu = parse(code); + PrinterConfiguration ignoreJavaDoc = new DefaultPrinterConfiguration().removeOption(new DefaultConfigurationOption(ConfigOption.PRINT_JAVADOC)); + String content = cu.toString(ignoreJavaDoc); + assertEquals(String.format("public class A {%s // stuff%s}%s", SYSTEM_EOL, SYSTEM_EOL, SYSTEM_EOL), content); + } + + @Test + void printImportsDefaultOrder() { + String code = "import x.y.z;import a.b.c;import static b.c.d;class c {}"; + CompilationUnit cu = parse(code); + String content = cu.toString(); + assertEqualsStringIgnoringEol("import x.y.z;\n" + + "import a.b.c;\n" + + "import static b.c.d;\n" + + "\n" + + "class c {\n" + + "}\n", content); + } + + @Test + void printImportsOrdered() { + String code = "import x.y.z;import a.b.c;import static b.c.d;class c {}"; + CompilationUnit cu = parse(code); + PrinterConfiguration orderImports = new DefaultPrinterConfiguration().addOption(new DefaultConfigurationOption(ConfigOption.ORDER_IMPORTS)); + String content = cu.toString(orderImports); + assertEqualsStringIgnoringEol("import static b.c.d;\n" + + "import a.b.c;\n" + + "import x.y.z;\n" + + "\n" + + "class c {\n" + + "}\n", content); + } + + @Test + void multilineJavadocGetsFormatted() { + CompilationUnit cu = new CompilationUnit(); + cu.addClass("X").addMethod("abc").setJavadocComment("line1\n line2 *\n * line3"); + + assertEqualsStringIgnoringEol("public class X {\n" + + "\n" + + " /**\n" + + " * line1\n" + + " * line2 *\n" + + " * line3\n" + + " */\n" + + " void abc() {\n" + + " }\n" + + "}\n", cu.toString()); + } + + @Test + void emptyJavadocGetsFormatted() { + CompilationUnit cu = new CompilationUnit(); + cu.addClass("X").addMethod("abc").setJavadocComment(""); + + assertEqualsStringIgnoringEol("public class X {\n" + + "\n" + + " /**\n" + + " */\n" + + " void abc() {\n" + + " }\n" + + "}\n", cu.toString()); + } + + @Test + void multilineJavadocWithLotsOfEmptyLinesGetsFormattedNeatly() { + CompilationUnit cu = new CompilationUnit(); + cu.addClass("X").addMethod("abc").setJavadocComment("\n\n\n ab\n\n\n cd\n\n\n"); + + assertEqualsStringIgnoringEol("public class X {\n" + + "\n" + + " /**\n" + + " * ab\n" + + " *\n" + + " * cd\n" + + " */\n" + + " void abc() {\n" + + " }\n" + + "}\n", cu.toString()); + } + + @Test + void singlelineJavadocGetsFormatted() { + CompilationUnit cu = new CompilationUnit(); + cu.addClass("X").addMethod("abc").setJavadocComment("line1"); + + assertEqualsStringIgnoringEol("public class X {\n" + + "\n" + + " /**\n" + + " * line1\n" + + " */\n" + + " void abc() {\n" + + " }\n" + + "}\n", cu.toString()); + } + + @Test + void javadocAlwaysGetsASpaceBetweenTheAsteriskAndTheRestOfTheLine() { + CompilationUnit cu = new CompilationUnit(); + cu.addClass("X").addMethod("abc").setJavadocComment("line1\nline2"); + + assertEqualsStringIgnoringEol("public class X {\n" + + "\n" + + " /**\n" + + " * line1\n" + + " * line2\n" + + " */\n" + + " void abc() {\n" + + " }\n" + + "}\n", cu.toString()); + } + + @Test + void javadocAlwaysGetsAnAdditionalSpaceOrNeverGetsIt() { + CompilationUnit cu = new CompilationUnit(); + cu.addClass("X").addMethod("abc").setJavadocComment("line1\n" + + "line2\n" + + " 3"); + + assertEqualsStringIgnoringEol("public class X {\n" + + "\n" + + " /**\n" + + " * line1\n" + + " * line2\n" + + " * 3\n" + + " */\n" + + " void abc() {\n" + + " }\n" + + "}\n", cu.toString()); + } + + @Test + void singlelineCommentGetsFormatted() { + CompilationUnit cu = new CompilationUnit(); + cu.addClass("X").addMethod("abc").setComment(new LineComment(" line1 \n ")); + + assertEqualsStringIgnoringEol("public class X {\n" + + "\n" + + " // line1\n" + + " void abc() {\n" + + " }\n" + + "}\n", cu.toString()); + } + + @Test + void blockcommentGetsNoFormatting() { + CompilationUnit cu = parse("class A {\n" + + " public void helloWorld(String greeting, String name) {\n" + + " //sdfsdfsdf\n" + + " //sdfds\n" + + " /*\n" + + " dgfdgfdgfdgfdgfd\n" + + " */\n" + + " }\n" + + "}\n"); + + assertEqualsStringIgnoringEol("class A {\n" + + "\n" + + " public void helloWorld(String greeting, String name) {\n" + + " //sdfsdfsdf\n" + + " //sdfds\n" + + " /*\n" + + " dgfdgfdgfdgfdgfd\n" + + " */\n" + + " }\n" + + "}\n", cu.toString()); + } + + private String expected = "public class SomeClass {\n" + + "\n" + + " /**\n" + + " * tester line\n" + + " * multi line comment\n" + + " * multi line comment\n" + + " * multi line comment\n" + + " * multi line comment\n" + + " */\n" + + " public void add(int x, int y) {\n" + + " }\n" + + "}\n"; + + @Test + void javadocIssue1907_allLeadingSpaces() { + String input_allLeadingSpaces = "public class SomeClass{" + + "/**\n" + + " * tester line\n" + + " * multi line comment\n" + + " * multi line comment\n" + + " * multi line comment\n" + + " multi line comment\n" + + " */\n" + + "public void add(int x, int y){}}"; + + CompilationUnit cu_allLeadingSpaces = parse(input_allLeadingSpaces); + assertEqualsStringIgnoringEol(expected, cu_allLeadingSpaces.toString()); + } + + @Test + void javadocIssue1907_singleMissingLeadingSpace() { + String input_singleMissingLeadingSpace = "public class SomeClass{" + + "/**\n" + + "* tester line\n" + + " * multi line comment\n" + + " * multi line comment\n" + + " * multi line comment\n" + + " multi line comment\n" + + " */\n" + + "public void add(int x, int y){}}"; + + CompilationUnit cu_singleMissingLeadingSpace = parse(input_singleMissingLeadingSpace); + assertEqualsStringIgnoringEol(expected, cu_singleMissingLeadingSpace.toString()); + } + + @Test + void javadocIssue1907_leadingTab() { + String input_leadingTab = "public class SomeClass{" + + "/**\n" + + "\t * tester line\n" + + " * multi line comment\n" + + " * multi line comment\n" + + " * multi line comment\n" + + " multi line comment\n" + + " */\n" + + "public void add(int x, int y){}}"; + + CompilationUnit cu_leadingTab = parseCompilationUnit(input_leadingTab); + assertEqualsStringIgnoringEol(expected, cu_leadingTab.toString()); + } + + @Test + void printYield() { + Statement statement = parseStatement("yield 5*5;"); + assertEqualsStringIgnoringEol("yield 5 * 5;", statement.toString()); + } + + @Test + void printTextBlock() { + CompilationUnit cu = parseCompilationUnit( + ParserConfiguration.LanguageLevel.JAVA_13_PREVIEW, + "class X{String html = \"\"\"\n" + + " \n" + + " \n" + + "

Hello, world

\n" + + " \n" + + " \n" + + " \"\"\";}" + ); + + assertEqualsStringIgnoringEol("String html = \"\"\"\n" + + " \n" + + " \n" + + "

Hello, world

\n" + + " \n" + + " \n" + + " \"\"\";", cu.getClassByName("X").get().getFieldByName("html").get().toString()); + } + + @Test + void printTextBlock2() { + CompilationUnit cu = parseCompilationUnit( + ParserConfiguration.LanguageLevel.JAVA_13_PREVIEW, + "class X{String html = \"\"\"\n" + + " \n" + + " \"\"\";}" + ); + + assertEqualsStringIgnoringEol("String html = \"\"\"\n" + + " \n" + + " \"\"\";", cu.getClassByName("X").get().getFieldByName("html").get().toString()); + } + + + @Test + void innerClassWithConstructorReceiverParameterTest() { + String innerClassWithConstructorReceiverParam = + "public class A {\n\n" + + " class InnerA {\n\n" + + " InnerA(A A.this) {\n" + + " }\n" + + " }\n" + + "}\n"; + 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/PrettyPrinterTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/PrettyPrinterTest.java new file mode 100644 index 0000000..9c32204 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/PrettyPrinterTest.java @@ -0,0 +1,577 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.*; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.FieldDeclaration; +import com.github.javaparser.ast.body.TypeDeclaration; +import com.github.javaparser.ast.expr.VariableDeclarationExpr; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.ast.type.PrimitiveType; +import com.github.javaparser.ast.visitor.VoidVisitor; +import com.github.javaparser.printer.configuration.*; +import com.github.javaparser.printer.configuration.DefaultPrinterConfiguration.ConfigOption; +import com.github.javaparser.printer.configuration.Indentation.IndentType; +import org.junit.jupiter.api.Test; + +import java.util.Optional; +import java.util.function.Function; + +import static com.github.javaparser.ParseStart.COMPILATION_UNIT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_9; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.StaticJavaParser.*; +import static com.github.javaparser.printer.configuration.Indentation.IndentType.TABS; +import static com.github.javaparser.printer.configuration.Indentation.IndentType.TABS_WITH_SPACE_ALIGN; +import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol; +import static org.junit.jupiter.api.Assertions.*; + +class PrettyPrinterTest { + + private String prettyPrintField(String code) { + CompilationUnit cu = parse(code); + return new DefaultPrettyPrinter().print(cu.findFirst(FieldDeclaration.class).get()); + } + + private String prettyPrintVar(String code) { + CompilationUnit cu = parse(code); + return new DefaultPrettyPrinter().print(cu.findAll(VariableDeclarationExpr.class).get(0)); + } + + private Optional getOption(PrinterConfiguration config, ConfigOption cOption) { + return config.get(new DefaultConfigurationOption(cOption)); + } + + @Test + void printingArrayFields() { + String code; + code = "class A { int a, b[]; }"; + assertEquals("int a, b[];", prettyPrintField(code)); + + code = "class A { int[] a[], b[]; }"; + assertEquals("int[][] a, b;", prettyPrintField(code)); + + code = "class A { int[] a[][], b; }"; + assertEquals("int[] a[][], b;", prettyPrintField(code)); + + code = "class A { int[] a, b; }"; + assertEquals("int[] a, b;", prettyPrintField(code)); + + code = "class A { int a[], b[]; }"; + assertEquals("int[] a, b;", prettyPrintField(code)); + } + + @Test + void printingArrayVariables() { + String code; + code = "class A { void foo(){ int a, b[]; }}"; + assertEquals("int a, b[]", prettyPrintVar(code)); + + code = "class A { void foo(){ int[] a[], b[]; }}"; + assertEquals("int[][] a, b", prettyPrintVar(code)); + + code = "class A { void foo(){ int[] a[][], b; }}"; + assertEquals("int[] a[][], b", prettyPrintVar(code)); + + code = "class A { void foo(){ int[] a, b; }}"; + assertEquals("int[] a, b", prettyPrintVar(code)); + + code = "class A { void foo(){ int a[], b[]; }}"; + assertEquals("int[] a, b", prettyPrintVar(code)); + } + + private String prettyPrintConfigurable(String code) { + CompilationUnit cu = parse(code); + PrinterConfiguration configuration = new DefaultPrinterConfiguration(); + Function> visitorFactory = (config) -> new TestVisitor(config, new SourcePrinter(config)); + Printer printer = new DefaultPrettyPrinter(visitorFactory, configuration); + return printer.print(cu.findFirst(ClassOrInterfaceDeclaration.class).get()); + } + + @Test + void printUseTestVisitor() { + String code; + code = "class A { void foo(){ int a, b[]; }}"; + assertEquals("test", prettyPrintConfigurable(code)); + } + + @Test + void prettyColumnAlignParameters_enabled() { + PrinterConfiguration config = new DefaultPrinterConfiguration().addOption(new DefaultConfigurationOption(ConfigOption.COLUMN_ALIGN_PARAMETERS)); + final String EOL = getOption(config, ConfigOption.END_OF_LINE_CHARACTER).get().asValue(); + + String code = "class Example { void foo(Object arg0,Object arg1){ myMethod(1, 2, 3, 5, Object.class); } }"; + String expected = "class Example {" + EOL + + "" + EOL + + " void foo(Object arg0, Object arg1) {" + EOL + + " myMethod(1," + EOL + + " 2," + EOL + + " 3," + EOL + + " 5," + EOL + + " Object.class);" + EOL + + " }" + EOL + + "}" + EOL + + ""; + + assertEquals(expected, new DefaultPrettyPrinter(config).print(parse(code))); + } + + @Test + void prettyColumnAlignParameters_disabled() { + + PrinterConfiguration config = new DefaultPrinterConfiguration(); + final String EOL = getOption(config, ConfigOption.END_OF_LINE_CHARACTER).get().asValue(); + + String code = "class Example { void foo(Object arg0,Object arg1){ myMethod(1, 2, 3, 5, Object.class); } }"; + String expected = "class Example {" + EOL + + "" + EOL + + " void foo(Object arg0, Object arg1) {" + EOL + + " myMethod(1, 2, 3, 5, Object.class);" + EOL + + " }" + EOL + + "}" + EOL + + ""; + + assertEquals(expected, new DefaultPrettyPrinter(config).print(parse(code))); + } + + @Test + void prettyAlignMethodCallChains_enabled() { + + PrinterConfiguration config = new DefaultPrinterConfiguration().addOption(new DefaultConfigurationOption(ConfigOption.COLUMN_ALIGN_FIRST_METHOD_CHAIN)); + final String EOL = getOption(config, ConfigOption.END_OF_LINE_CHARACTER).get().asValue(); + + String code = "class Example { void foo() { IntStream.range(0, 10).filter(x -> x % 2 == 0).map(x -> x * IntStream.of(1,3,5,1).sum()).forEach(System.out::println); } }"; + String expected = "class Example {" + EOL + + "" + EOL + + " void foo() {" + EOL + + " IntStream.range(0, 10)" + EOL + + " .filter(x -> x % 2 == 0)" + EOL + + " .map(x -> x * IntStream.of(1, 3, 5, 1)" + EOL + + " .sum())" + EOL + + " .forEach(System.out::println);" + EOL + + " }" + EOL + + "}" + EOL + + ""; + + assertEquals(expected, new DefaultPrettyPrinter(config).print(parse(code))); + } + + @Test + void prettyAlignMethodCallChains_disabled() { + + PrinterConfiguration config = new DefaultPrinterConfiguration(); + final String EOL = getOption(config, ConfigOption.END_OF_LINE_CHARACTER).get().asValue(); + + String code = "class Example { void foo() { IntStream.range(0, 10).filter(x -> x % 2 == 0).map(x -> x * IntStream.of(1,3,5,1).sum()).forEach(System.out::println); } }"; + String expected = "class Example {" + EOL + + "" + EOL + + " void foo() {" + EOL + + " IntStream.range(0, 10).filter(x -> x % 2 == 0).map(x -> x * IntStream.of(1, 3, 5, 1).sum()).forEach(System.out::println);" + EOL + + " }" + EOL + + "}" + EOL + + ""; + + String printed = new DefaultPrettyPrinter(config).print(parse(code)); + + assertEquals(expected, printed); + } + + @Test + void enumConstantsHorizontally() { + CompilationUnit cu = parse("enum X{A, B, C, D, E}"); + assertEqualsStringIgnoringEol("enum X {\n\n A, B, C, D, E\n}\n", new DefaultPrettyPrinter().print(cu)); + } + + @Test + void enumConstantsVertically() { + CompilationUnit cu = parse("enum X{A, B, C, D, E, F}"); + assertEqualsStringIgnoringEol("enum X {\n\n A,\n B,\n C,\n D,\n E,\n F\n}\n", new DefaultPrettyPrinter().print(cu)); + } + + @Test + void printingInconsistentVariables() { + FieldDeclaration fieldDeclaration = parseBodyDeclaration("int a, b;").asFieldDeclaration(); + + assertEquals("int a, b;", fieldDeclaration.toString()); + + fieldDeclaration.getVariable(0).setType(PrimitiveType.doubleType()); + + assertEquals("??? a, b;", fieldDeclaration.toString()); + + fieldDeclaration.getVariable(1).setType(PrimitiveType.doubleType()); + + assertEquals("double a, b;", fieldDeclaration.toString()); + } + + @Test + void prettyAlignMethodCallChainsIndentsArgumentsWithBlocksCorrectly() { + + CompilationUnit cu = parse("class Foo { void bar() { a.b.c.d.e; a.b.c().d().e(); a.b.c().d.e(); foo().bar().baz(boo().baa().bee()).bam(); foo().bar().baz(boo().baa().bee()).bam; foo().bar(Long.foo().b.bar(), bam).baz(); foo().bar().baz(foo, () -> { boo().baa().bee(); }).baz(() -> { boo().baa().bee(); }).bam(() -> { boo().baa().bee(); }); } }"); + Indentation indentation = new Indentation(TABS_WITH_SPACE_ALIGN, 1); + + PrinterConfiguration config = new DefaultPrinterConfiguration() + .addOption(new DefaultConfigurationOption(ConfigOption.COLUMN_ALIGN_FIRST_METHOD_CHAIN)) + .addOption(new DefaultConfigurationOption(ConfigOption.COLUMN_ALIGN_PARAMETERS)) + .addOption(new DefaultConfigurationOption(ConfigOption.INDENTATION, indentation)); + + String printed = new DefaultPrettyPrinter(config).print(cu); + + assertEqualsStringIgnoringEol("class Foo {\n" + + "\n" + + "\tvoid bar() {\n" + + "\t\ta.b.c.d.e;\n" + + "\t\ta.b.c()\n" + + "\t\t .d()\n" + + "\t\t .e();\n" + + "\t\ta.b.c().d\n" + + "\t\t .e();\n" + + "\t\tfoo().bar()\n" + + "\t\t .baz(boo().baa().bee())\n" + + "\t\t .bam();\n" + + "\t\tfoo().bar()\n" + + "\t\t .baz(boo().baa().bee()).bam;\n" + + "\t\tfoo().bar(Long.foo().b.bar(),\n" + + "\t\t bam)\n" + + "\t\t .baz();\n" + + "\t\tfoo().bar()\n" + + "\t\t .baz(foo,\n" + + "\t\t () -> {\n" + + "\t\t \tboo().baa()\n" + + "\t\t \t .bee();\n" + + "\t\t })\n" + + "\t\t .baz(() -> {\n" + + "\t\t \tboo().baa()\n" + + "\t\t \t .bee();\n" + + "\t\t })\n" + + "\t\t .bam(() -> {\n" + + "\t\t \tboo().baa()\n" + + "\t\t \t .bee();\n" + + "\t\t });\n" + + "\t}\n" + + "}\n", printed); + } + + @Test + void noChainsIndentsInIf() { + Statement cu = parseStatement("if (x.y().z()) { boo().baa().bee(); }"); + + String printed = new DefaultPrettyPrinter(new DefaultPrinterConfiguration() + .addOption(new DefaultConfigurationOption(ConfigOption.COLUMN_ALIGN_FIRST_METHOD_CHAIN))) + .print(cu); + + assertEqualsStringIgnoringEol("if (x.y().z()) {\n" + + " boo().baa()\n" + + " .bee();\n" + + "}", printed); + } + + @Test + void noChainsIndentsInFor() { + Statement cu = parseStatement("for(int x=1; x.y().z(); x.z().z()) { boo().baa().bee(); }"); + + String printed = new DefaultPrettyPrinter(new DefaultPrinterConfiguration() + .addOption(new DefaultConfigurationOption(ConfigOption.COLUMN_ALIGN_FIRST_METHOD_CHAIN))) + .print(cu); + + assertEqualsStringIgnoringEol("for (int x = 1; x.y().z(); x.z().z()) {\n" + + " boo().baa()\n" + + " .bee();\n" + + "}", printed); + } + + @Test + void noChainsIndentsInWhile() { + Statement cu = parseStatement("while(x.y().z()) { boo().baa().bee(); }"); + + String printed = new DefaultPrettyPrinter(new DefaultPrinterConfiguration() + .addOption(new DefaultConfigurationOption(ConfigOption.COLUMN_ALIGN_FIRST_METHOD_CHAIN))) + .print(cu); + + assertEqualsStringIgnoringEol("while (x.y().z()) {\n" + + " boo().baa()\n" + + " .bee();\n" + + "}", printed); + } + + @Test + void indentWithTabsAsFarAsPossible() { + + CompilationUnit cu = parse("class Foo { void bar() { foo().bar().baz(() -> { boo().baa().bee(a, b, c); }).bam(); } }"); + Indentation indentation = new Indentation(TABS, 1); + String printed = new DefaultPrettyPrinter(new DefaultPrinterConfiguration() + .addOption(new DefaultConfigurationOption(ConfigOption.COLUMN_ALIGN_FIRST_METHOD_CHAIN)) + .addOption(new DefaultConfigurationOption(ConfigOption.COLUMN_ALIGN_PARAMETERS)) + .addOption(new DefaultConfigurationOption(ConfigOption.INDENTATION, indentation))) + .print(cu); + + assertEqualsStringIgnoringEol("class Foo {\n" + + "\n" + + "\tvoid bar() {\n" + + "\t\tfoo().bar()\n" + + "\t\t\t .baz(() -> {\n" + + "\t\t\t\t boo().baa()\n" + + "\t\t\t\t\t .bee(a,\n" + + "\t\t\t\t\t\t b,\n" + + "\t\t\t\t\t\t c);\n" + + "\t\t\t })\n" + + "\t\t\t .bam();\n" + + "\t}\n" + + "}\n", printed); + } + + @Test + void initializeWithSpecificConfiguration() { + CompilationUnit cu = parse("class Foo { // this is a comment \n" + + "}"); + PrinterConfiguration config = new DefaultPrinterConfiguration() + .removeOption(new DefaultConfigurationOption(ConfigOption.PRINT_COMMENTS)); + + Printer printer = new DefaultPrettyPrinter(config); + assertFalse(printer.getConfiguration().get(new DefaultConfigurationOption(ConfigOption.PRINT_COMMENTS)).isPresent()); + String printed = printer.print(cu); + assertEqualsStringIgnoringEol("class Foo {\n" + + "}\n", printed); + } + + + @Test + void indentWithTabsAlignWithSpaces() { + + CompilationUnit cu = parse("class Foo { void bar() { foo().bar().baz(() -> { boo().baa().bee(a, b, c); }).baz(() -> { return boo().baa(); }).bam(); } }"); + Indentation indentation = new Indentation(TABS_WITH_SPACE_ALIGN, 1); + String printed = new DefaultPrettyPrinter(new DefaultPrinterConfiguration() + .addOption(new DefaultConfigurationOption(ConfigOption.COLUMN_ALIGN_FIRST_METHOD_CHAIN)) + .addOption(new DefaultConfigurationOption(ConfigOption.COLUMN_ALIGN_PARAMETERS)) + .addOption(new DefaultConfigurationOption(ConfigOption.INDENTATION, indentation))) + .print(cu); + + assertEqualsStringIgnoringEol("class Foo {\n" + + "\n" + + "\tvoid bar() {\n" + + "\t\tfoo().bar()\n" + + "\t\t .baz(() -> {\n" + + "\t\t \tboo().baa()\n" + + "\t\t \t .bee(a,\n" + + "\t\t \t b,\n" + + "\t\t \t c);\n" + + "\t\t })\n" + + "\t\t .baz(() -> {\n" + + "\t\t \treturn boo().baa();\n" + + "\t\t })\n" + + "\t\t .bam();\n" + + "\t}\n" + + "}\n", printed); + } + + @Test + void printAnnotationsAtPrettyPlaces() { + + JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_9)); + ParseResult parseResult = javaParser.parse(COMPILATION_UNIT, provider("@Documented\n" + + "@Repeatable\n" + + "package com.github.javaparser;\n" + + "\n" + + "import java.lang.annotation.Documented;\n" + + "import java.lang.annotation.Repeatable;\n" + + "\n" + + "@Documented\n" + + "@Repeatable\n" + + "@interface Annotation {\n" + + "\n" + + " @Documented\n" + + " @Repeatable\n" + + " String value();\n" + + "}\n" + + "\n" + + "@Documented\n" + + "@Repeatable\n" + + "class Class<@Documented @Repeatable T> {\n" + + "\n" + + " @Documented\n" + + " @Repeatable\n" + + " byte b;\n" + + "\n" + + " @Documented\n" + + " @Repeatable\n" + + " Class(@Documented @Repeatable int i) {\n" + + " @Documented\n" + + " @Repeatable\n" + + " short s;\n" + + " }\n" + + "\n" + + " @Documented\n" + + " @Repeatable\n" + + " void method(@Documented @Repeatable Class this) {\n" + + " for (@Deprecated int i : arr4[0]) {\n" + + " x--;\n" + + " }\n" + + " }\n" + + "\n" + + " void method(@Documented @Repeatable Class this, int i) {\n" + + " }\n" + + "}\n" + + "\n" + + "@Documented\n" + + "@Repeatable\n" + + "enum Foo {\n" + + "\n" + + " @Documented\n" + + " @Repeatable\n" + + " BAR\n" + + "}\n" + + "@Documented\n" + + "@Repeatable\n" + + "module foo.bar {\n" + + "}\n")); + if (!parseResult.isSuccessful()) { + throw new ParseProblemException(parseResult.getProblems()); + } + CompilationUnit cu = parseResult.getResult().orElseThrow(AssertionError::new); + String printed = new DefaultPrettyPrinter().print(cu); + + assertEqualsStringIgnoringEol("@Documented\n" + + "@Repeatable\n" + + "package com.github.javaparser;\n" + + "\n" + + "import java.lang.annotation.Documented;\n" + + "import java.lang.annotation.Repeatable;\n" + + "\n" + + "@Documented\n" + + "@Repeatable\n" + + "@interface Annotation {\n" + + "\n" + + " @Documented\n" + + " @Repeatable\n" + + " String value();\n" + + "}\n" + + "\n" + + "@Documented\n" + + "@Repeatable\n" + + "class Class<@Documented @Repeatable T> {\n" + + "\n" + + " @Documented\n" + + " @Repeatable\n" + + " byte b;\n" + + "\n" + + " @Documented\n" + + " @Repeatable\n" + + " Class(@Documented @Repeatable int i) {\n" + + " @Documented\n" + + " @Repeatable\n" + + " short s;\n" + + " }\n" + + "\n" + + " @Documented\n" + + " @Repeatable\n" + + " void method(@Documented @Repeatable Class this) {\n" + + " for (@Deprecated int i : arr4[0]) {\n" + + " x--;\n" + + " }\n" + + " }\n" + + "\n" + + " void method(@Documented @Repeatable Class this, int i) {\n" + + " }\n" + + "}\n" + + "\n" + + "@Documented\n" + + "@Repeatable\n" + + "enum Foo {\n" + + "\n" + + " @Documented\n" + + " @Repeatable\n" + + " BAR\n" + + "}\n" + + "@Documented\n" + + "@Repeatable\n" + + "module foo.bar {\n" + + "}\n", printed); + } + + @Test + public void testIssue2578() { + String code = + "class C{\n" + + " //orphan\n" + + " /*orphan*/\n" + + "}"; + CompilationUnit cu = StaticJavaParser.parse(code); + TypeDeclaration td = cu.findFirst(TypeDeclaration.class).get(); + assertEquals(2, td.getAllContainedComments().size()); + td.setPublic(true); // --- simple AST change ----- + assertEquals(2, td.getAllContainedComments().size()); // the orphaned comments exist + } + + @Test + public void testIssue2535() { + + String code = + "public class A {\n" + + " public static A m() {\n" + + " System.out.println(\"\");\n" + + " // TODO\n" + + " /* TODO */\n" + + " /** TODO */\n" + + " }\n" + + "}"; + + StaticJavaParser.setConfiguration(new ParserConfiguration()); + + CompilationUnit cu = StaticJavaParser.parse(code); + + // default indent is 4 spaces + assertTrue(cu.toString().contains(" // TODO")); + assertTrue(cu.toString().contains(" /* TODO */")); + + } + + @Test + public void testIndentationWithDefaultSize() { + Indentation indentation = new Indentation(IndentType.SPACES); + assertTrue(indentation.getSize()==4); + assertEquals(" ", indentation.getIndent()); + // on-the-fly modification + indentation.setSize(2); + assertTrue(indentation.getSize()==2); + assertEquals(" ", indentation.getIndent()); + } + + @Test + public void testIndentationWithCustomSize() { + Indentation indentation = new Indentation(IndentType.TABS,2); + assertTrue(indentation.getSize()==2); + assertEquals("\t\t", indentation.getIndent()); + } + + @Test + public void testIndentationWithOnTheFlyModifcation() { + Indentation indentation = new Indentation(IndentType.SPACES); + // on-the-fly modification + indentation.setSize(2); + assertTrue(indentation.getSize()==2); + assertEquals(" ", indentation.getIndent()); + indentation.setType(IndentType.TABS); + assertTrue(indentation.getType() == IndentType.TABS); + assertEquals("\t\t", indentation.getIndent()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/PrinterConfigurationTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/PrinterConfigurationTest.java new file mode 100644 index 0000000..340c616 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/PrinterConfigurationTest.java @@ -0,0 +1,96 @@ +/* + * Copyright (C) 2013-2024 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; + +import com.github.javaparser.printer.configuration.ConfigurationOption; +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; +import com.github.javaparser.utils.Utils; +import org.junit.jupiter.api.Test; + +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; + +class PrinterConfigurationTest { + + private Optional getOption(PrinterConfiguration config, ConfigOption cOption) { + return config.get(new DefaultConfigurationOption(cOption)); + } + + @Test + void testDefaultConfigurationAndValue() { + PrinterConfiguration config = new DefaultPrinterConfiguration(); + assertTrue(getOption(config, ConfigOption.PRINT_COMMENTS).isPresent()); + assertTrue(getOption(config, ConfigOption.PRINT_JAVADOC).isPresent()); + assertTrue(getOption(config, ConfigOption.SPACE_AROUND_OPERATORS).isPresent()); + assertTrue(getOption(config, ConfigOption.INDENT_CASE_IN_SWITCH).isPresent()); + assertTrue(getOption(config, ConfigOption.MAX_ENUM_CONSTANTS_TO_ALIGN_HORIZONTALLY).isPresent()); + assertTrue(getOption(config, ConfigOption.END_OF_LINE_CHARACTER).isPresent()); + // values + assertEquals(getOption(config, ConfigOption.MAX_ENUM_CONSTANTS_TO_ALIGN_HORIZONTALLY).get().asValue(), + Integer.valueOf(5)); + assertEquals(getOption(config, ConfigOption.MAX_ENUM_CONSTANTS_TO_ALIGN_HORIZONTALLY).get().asValue(), + Integer.valueOf(5)); + assertTrue(getOption(config, ConfigOption.MAX_ENUM_CONSTANTS_TO_ALIGN_HORIZONTALLY).get().asValue() == + Integer.valueOf(5)); + assertEquals(getOption(config, ConfigOption.END_OF_LINE_CHARACTER).get().asString(), Utils.SYSTEM_EOL); + } + + @Test + void testConfigurationError() { + PrinterConfiguration config = new DefaultPrinterConfiguration(); + // verify configuration error case + assertThrows(IllegalArgumentException.class, () -> { + getOption(config, ConfigOption.PRINT_COMMENTS).get().asValue(); + }); + + // verify currentValue assignment: example we cannot assign a string to a boolean + assertThrows(IllegalArgumentException.class, () -> { + config.addOption(new DefaultConfigurationOption(ConfigOption.PRINT_COMMENTS, "1")); + }); + } + + @Test + void testUpdatedConfigurationOption() { + PrinterConfiguration config = new DefaultPrinterConfiguration(); + // change the default currentValue of the MAX_ENUM_CONSTANTS_TO_ALIGN_HORIZONTALLY option + getOption(config, ConfigOption.MAX_ENUM_CONSTANTS_TO_ALIGN_HORIZONTALLY).get().value(2); + // verify the currentValue is updated + assertEquals(getOption(config, ConfigOption.MAX_ENUM_CONSTANTS_TO_ALIGN_HORIZONTALLY).get().asValue(), Integer.valueOf(2)); + } + + @Test + void testRemoveOption() { + PrinterConfiguration config = new DefaultPrinterConfiguration(); + assertTrue(getOption(config, ConfigOption.PRINT_COMMENTS).isPresent()); + assertTrue(getOption(config, ConfigOption.END_OF_LINE_CHARACTER).isPresent()); + // remove option PRINT_COMMENTS + config.removeOption(new DefaultConfigurationOption(ConfigOption.PRINT_COMMENTS)); + assertFalse(getOption(config, ConfigOption.PRINT_COMMENTS).isPresent()); + // remove option with currentValue + config.removeOption(new DefaultConfigurationOption(ConfigOption.END_OF_LINE_CHARACTER, "\n")); + assertFalse(getOption(config, ConfigOption.END_OF_LINE_CHARACTER).isPresent()); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/TestVisitor.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/TestVisitor.java new file mode 100644 index 0000000..08891c4 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/TestVisitor.java @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.printer.configuration.PrinterConfiguration; + +public class TestVisitor extends DefaultPrettyPrinterVisitor { + + public TestVisitor(PrinterConfiguration configuration, SourcePrinter printer) { + super(configuration, printer); + } + + @Override + public void visit(final ClassOrInterfaceDeclaration n, final Void arg) { + printer.print("test"); + } +} 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 new file mode 100644 index 0000000..2a981b6 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java @@ -0,0 +1,314 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.ast.expr.Expression; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.StaticJavaParser.parseExpression; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.nio.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() throws SAXException, IOException { + Expression expression = parseExpression("1+1"); + XmlPrinter xmlOutput = new XmlPrinter(true); + + String output = xmlOutput.output(expression); + + assertXMLEquals("", output); + } + + @Test + void testWithoutType() throws SAXException, IOException { + Expression expression = parseExpression("1+1"); + + XmlPrinter xmlOutput = new XmlPrinter(false); + + String output = xmlOutput.output(expression); + + assertXMLEquals("", output); + } + + @Test + void testList() throws SAXException, IOException { + Expression expression = parseExpression("a(1,2)"); + + XmlPrinter xmlOutput = new XmlPrinter(true); + + String output = xmlOutput.output(expression); + + 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/YamlPrinterTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/YamlPrinterTest.java new file mode 100644 index 0000000..419f53b --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/YamlPrinterTest.java @@ -0,0 +1,83 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.expr.Expression; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.StaticJavaParser.parse; +import static com.github.javaparser.StaticJavaParser.parseExpression; +import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol; +import static com.github.javaparser.utils.TestUtils.readTextResource; + +class YamlPrinterTest { + + private String read(String filename) { + return readTextResource(YamlPrinterTest.class, filename); + } + + @Test + void testWithType() { + YamlPrinter yamlPrinter = new YamlPrinter(true); + Expression expression = parseExpression("x(1,1)"); + String output = yamlPrinter.output(expression); + assertEqualsStringIgnoringEol(read("yamlWithType.yaml"), output); + } + + @Test + void testWithoutType() { + YamlPrinter yamlPrinter = new YamlPrinter(false); + Expression expression = parseExpression("1+1"); + String output = yamlPrinter.output(expression); + assertEqualsStringIgnoringEol(read("yamlWithoutType.yaml"), output); + } + + @Test + void testWithColonFollowedBySpaceInValue() { + YamlPrinter yamlPrinter = new YamlPrinter(true); + Expression expression = parseExpression("\"a\\\\: b\""); + String output = yamlPrinter.output(expression); + assertEqualsStringIgnoringEol(read("yamlWithColonFollowedBySpaceInValue.yaml"), output); + } + + @Test + void testWithColonFollowedByLineSeparatorInValue() { + YamlPrinter yamlPrinter = new YamlPrinter(true); + Expression expression = parseExpression("\"a\\\\:\\\\nb\""); + String output = yamlPrinter.output(expression); + assertEqualsStringIgnoringEol(read("yamlWithColonFollowedByLineSeparatorInValue.yaml"), output); + } + + @Test + void testParsingJavadocWithQuoteAndNewline() { + String code = "/**\n" + + " * \" this comment contains a quote and newlines\n" + + " */\n" + + "public class Dog {}"; + + YamlPrinter yamlPrinter = new YamlPrinter(true); + CompilationUnit computationUnit = parse(code); + String output = yamlPrinter.output(computationUnit); + assertEqualsStringIgnoringEol(read("yamlParsingJavadocWithQuoteAndNewline.yaml"), output); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/configuration/imports/DefaultImportOrderingStrategyTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/configuration/imports/DefaultImportOrderingStrategyTest.java new file mode 100644 index 0000000..c471074 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/configuration/imports/DefaultImportOrderingStrategyTest.java @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2013-2024 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.configuration.imports; + +import com.github.javaparser.ast.ImportDeclaration; +import com.github.javaparser.ast.NodeList; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class DefaultImportOrderingStrategyTest { + + private final DefaultImportOrderingStrategy strategy = new DefaultImportOrderingStrategy(); + + @Test + void sortImports_givenNoImports_ThenNoImports_ShouldBeReturned() { + List> actual = strategy.sortImports(new NodeList<>()); + assertEquals(1, actual.size()); + assertEquals(0, actual.get(0).size()); + } + + @Test + void sortImports_givenImports_ThenImportsShouldBeInCorrectLocation() { + + NodeList imports = new NodeList<>(); + imports.add(new ImportDeclaration("org.junit.jupiter.api.Assertions.assertEquals", true, false)); + imports.add(new ImportDeclaration("java.util.List", false, false)); + imports.add(new ImportDeclaration("com.example.Test", false, false)); + + List> actual = strategy.sortImports(imports); + assertEquals(1, actual.size()); + + NodeList actualImports = actual.get(0); + + assertEquals(3, actualImports.size()); + assertEquals("org.junit.jupiter.api.Assertions.assertEquals", actualImports.get(0).getNameAsString()); + assertEquals("java.util.List", actualImports.get(1).getNameAsString()); + assertEquals("com.example.Test", actualImports.get(2).getNameAsString()); + } + + @Test + void sortImports_givenUnsortedImportsAndSortingIsTrue_ThenImportsShouldBeSorted() { + NodeList imports = new NodeList<>(); + imports.add(new ImportDeclaration("com.example.B", false, false)); + imports.add(new ImportDeclaration("com.example.A", false, false)); + + strategy.setSortImportsAlphabetically(true); + + List> actual = strategy.sortImports(imports); + assertEquals(1, actual.size()); + + NodeList actualImports = actual.get(0); + + assertEquals(2, actualImports.size()); + assertEquals("com.example.A", actualImports.get(0).getNameAsString()); + assertEquals("com.example.B", actualImports.get(1).getNameAsString()); + } + +} \ No newline at end of file diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/configuration/imports/EclipseImportOrderingStrategyTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/configuration/imports/EclipseImportOrderingStrategyTest.java new file mode 100644 index 0000000..323b43a --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/configuration/imports/EclipseImportOrderingStrategyTest.java @@ -0,0 +1,101 @@ +/* + * Copyright (C) 2013-2024 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.configuration.imports; + +import com.github.javaparser.ast.ImportDeclaration; +import com.github.javaparser.ast.NodeList; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class EclipseImportOrderingStrategyTest { + + private final EclipseImportOrderingStrategy strategy = new EclipseImportOrderingStrategy(); + + @Test + void sortImports_givenNoImports_ThenNoImports_ShouldBeReturned() { + List> actual = strategy.sortImports(new NodeList<>()); + assertEquals(6, actual.size()); + assertEquals(0, actual.get(0).size()); + assertEquals(0, actual.get(1).size()); + assertEquals(0, actual.get(2).size()); + assertEquals(0, actual.get(3).size()); + assertEquals(0, actual.get(4).size()); + assertEquals(0, actual.get(5).size()); + } + + @Test + void sortImports_givenImports_ThenImportsShouldBeInCorrectLocation() { + + NodeList imports = new NodeList<>(); + imports.add(new ImportDeclaration("org.junit.jupiter.api.Assertions.assertEquals", true, false)); + imports.add(new ImportDeclaration("org.junit.jupiter.api.Assertions", false, false)); + imports.add(new ImportDeclaration("java.util.List", false, false)); + imports.add(new ImportDeclaration("javax.swing", false, true)); + imports.add(new ImportDeclaration("com.example.Test", false, false)); + imports.add(new ImportDeclaration("pt.example.OtherTest", false, false)); + + List> actual = strategy.sortImports(imports); + assertEquals(6, actual.size()); + + assertEquals(1, actual.get(0).size()); + assertEquals("org.junit.jupiter.api.Assertions.assertEquals", actual.get(0).get(0).getNameAsString()); + + assertEquals(1, actual.get(1).size()); + assertEquals("java.util.List", actual.get(1).get(0).getNameAsString()); + + assertEquals(1, actual.get(2).size()); + assertEquals("javax.swing", actual.get(2).get(0).getNameAsString()); + + assertEquals(1, actual.get(3).size()); + assertEquals("org.junit.jupiter.api.Assertions", actual.get(3).get(0).getNameAsString()); + + assertEquals(1, actual.get(4).size()); + assertEquals("com.example.Test", actual.get(4).get(0).getNameAsString()); + + assertEquals(1, actual.get(5).size()); + assertEquals("pt.example.OtherTest", actual.get(5).get(0).getNameAsString()); + } + + @Test + void sortImports_givenUnsortedImportsAndSortingIsTrue_ThenImportsShouldBeSorted() { + NodeList imports = new NodeList<>(); + imports.add(new ImportDeclaration("com.example.B", false, false)); + imports.add(new ImportDeclaration("com.example.A", false, false)); + + strategy.setSortImportsAlphabetically(true); + + List> actual = strategy.sortImports(imports); + assertEquals(6, actual.size()); + + assertEquals(0, actual.get(0).size()); + assertEquals(0, actual.get(1).size()); + assertEquals(0, actual.get(2).size()); + assertEquals(0, actual.get(3).size()); + assertEquals(2, actual.get(4).size()); + assertEquals("com.example.A", actual.get(4).get(0).getNameAsString()); + assertEquals("com.example.B", actual.get(4).get(1).getNameAsString()); + assertEquals(0, actual.get(5).size()); + } + +} \ No newline at end of file diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/configuration/imports/IntelliJImportOrderingStrategyTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/configuration/imports/IntelliJImportOrderingStrategyTest.java new file mode 100644 index 0000000..82314e9 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/configuration/imports/IntelliJImportOrderingStrategyTest.java @@ -0,0 +1,83 @@ +/* + * Copyright (C) 2013-2024 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.configuration.imports; + +import com.github.javaparser.ast.ImportDeclaration; +import com.github.javaparser.ast.NodeList; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class IntelliJImportOrderingStrategyTest { + + private final IntelliJImportOrderingStrategy strategy = new IntelliJImportOrderingStrategy(); + + @Test + void sortImports_givenNoImports_ThenNoImports_ShouldBeReturned() { + List> actual = strategy.sortImports(new NodeList<>()); + assertEquals(3, actual.size()); + assertEquals(0, actual.get(0).size()); + assertEquals(0, actual.get(1).size()); + assertEquals(0, actual.get(2).size()); + } + + @Test + void sortImports_givenImports_ThenImportsShouldBeInCorrectLocation() { + + NodeList imports = new NodeList<>(); + imports.add(new ImportDeclaration("org.junit.jupiter.api.Assertions.assertEquals", true, false)); + imports.add(new ImportDeclaration("java.util.List", false, false)); + imports.add(new ImportDeclaration("com.example.Test", false, false)); + + List> actual = strategy.sortImports(imports); + assertEquals(3, actual.size()); + + assertEquals(1, actual.get(0).size()); + assertEquals("com.example.Test", actual.get(0).get(0).getNameAsString()); + + assertEquals(1, actual.get(1).size()); + assertEquals("java.util.List", actual.get(1).get(0).getNameAsString()); + + assertEquals(1, actual.get(2).size()); + assertEquals("org.junit.jupiter.api.Assertions.assertEquals", actual.get(2).get(0).getNameAsString()); + } + + @Test + void sortImports_givenUnsortedImportsAndSortingIsTrue_ThenImportsShouldBeSorted() { + NodeList imports = new NodeList<>(); + imports.add(new ImportDeclaration("com.example.B", false, false)); + imports.add(new ImportDeclaration("com.example.A", false, false)); + + strategy.setSortImportsAlphabetically(true); + + List> actual = strategy.sortImports(imports); + assertEquals(3, actual.size()); + + assertEquals(2, actual.get(0).size()); + assertEquals("com.example.A", actual.get(0).get(0).getNameAsString()); + assertEquals("com.example.B", actual.get(0).get(1).getNameAsString()); + assertEquals(0, actual.get(1).size()); + assertEquals(0, actual.get(2).size()); + } + +} \ No newline at end of file diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/AbstractLexicalPreservingTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/AbstractLexicalPreservingTest.java new file mode 100644 index 0000000..a7feecb --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/AbstractLexicalPreservingTest.java @@ -0,0 +1,102 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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 com.github.javaparser.ParserConfiguration; +import com.github.javaparser.StaticJavaParser; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.stmt.Statement; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; + +import java.io.IOException; + +import static com.github.javaparser.utils.TestUtils.assertEqualsString; +import static com.github.javaparser.utils.TestUtils.readResource; + +public abstract class AbstractLexicalPreservingTest { + + protected CompilationUnit cu; + protected Expression expression; + protected Statement statement; + + @AfterAll + public static void tearDown() { + } + + @AfterEach + public void reset() { + StaticJavaParser.setConfiguration(new ParserConfiguration()); + } + + protected void considerCode(String code) { + cu = LexicalPreservingPrinter.setup(StaticJavaParser.parse(code)); + } + + protected void considerExpression(String code) { + expression = LexicalPreservingPrinter.setup(StaticJavaParser.parseExpression(code)); + } + + protected void considerStatement(String code) { + statement = LexicalPreservingPrinter.setup(StaticJavaParser.parseStatement(code)); + } + + protected void considerVariableDeclaration(String code) { + expression = LexicalPreservingPrinter.setup(StaticJavaParser.parseVariableDeclarationExpr(code)); + } + + protected String considerExample(String resourceName) throws IOException { + String code = readExample(resourceName); + considerCode(code); + return code; + } + + protected String readExample(String resourceName) throws IOException { + return readResource("com/github/javaparser/lexical_preservation_samples/" + resourceName + ".java.txt"); + } + + protected void assertTransformed(String exampleName, Node node) throws IOException { + String expectedCode = readExample(exampleName + "_expected"); + String actualCode = LexicalPreservingPrinter.print(node); + + // Note that we explicitly care about line endings when handling lexical preservation. + assertEqualsString(expectedCode, actualCode); + } + + protected void assertUnchanged(String exampleName) throws IOException { + String expectedCode = considerExample(exampleName + "_original"); + String actualCode = LexicalPreservingPrinter.print(cu != null ? cu : expression); + + // Note that we explicitly care about line endings when handling lexical preservation. + assertEqualsString(expectedCode, actualCode); + } + + protected void assertTransformedToString(String expectedPartialCode, Node node) { + String actualCode = LexicalPreservingPrinter.print(node); + + // Note that we explicitly care about line endings when handling lexical preservation. + assertEqualsString(expectedPartialCode, actualCode); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/AnnotationSpaceTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/AnnotationSpaceTest.java new file mode 100644 index 0000000..c68dd93 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/AnnotationSpaceTest.java @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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 com.github.javaparser.ast.expr.MarkerAnnotationExpr; +import com.github.javaparser.ast.type.ClassOrInterfaceType; +import org.junit.jupiter.api.Test; + +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class AnnotationSpaceTest extends AbstractLexicalPreservingTest { + /** Tests that inserted annotations on types are followed by a space. */ + @Test + public void test() { + considerCode("public class Foo {\n" + + " void myMethod(String param);\n" + + "}"); + // Insert the annotation onto the String parameter type. + Optional type = cu.findFirst(ClassOrInterfaceType.class); + type.get().addAnnotation(new MarkerAnnotationExpr("Nullable")); + String result = LexicalPreservingPrinter.print(cu); + // Verify that there's a space between the annotation and the String type. + assertTrue(result.contains("@Nullable String")); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/DifferenceElementCalculatorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/DifferenceElementCalculatorTest.java new file mode 100644 index 0000000..7d18fbf --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/DifferenceElementCalculatorTest.java @@ -0,0 +1,452 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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 com.github.javaparser.GeneratedJavaParserConstants; +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.PackageDeclaration; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.comments.JavadocComment; +import com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.observer.ObservableProperty; +import com.github.javaparser.ast.stmt.ExpressionStmt; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.ast.type.ArrayType; +import com.github.javaparser.ast.type.PrimitiveType; +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.CsmToken; +import com.github.javaparser.printer.concretesyntaxmodel.CsmUnindent; +import com.github.javaparser.printer.lexicalpreservation.LexicalDifferenceCalculator.CsmChild; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static com.github.javaparser.TokenTypes.eolTokenKind; +import static com.github.javaparser.TokenTypes.spaceTokenKind; +import static com.github.javaparser.ast.Modifier.Keyword.PUBLIC; +import static com.github.javaparser.ast.Modifier.createModifierList; +import static com.github.javaparser.printer.lexicalpreservation.DifferenceElement.*; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class DifferenceElementCalculatorTest extends AbstractLexicalPreservingTest { + + @Test + void calculateDifferenceEmpty() { + LexicalDifferenceCalculator.CalculatedSyntaxModel a = new LexicalDifferenceCalculator.CalculatedSyntaxModel(Collections.emptyList()); + LexicalDifferenceCalculator.CalculatedSyntaxModel b = new LexicalDifferenceCalculator.CalculatedSyntaxModel(Collections.emptyList()); + List differenceElements = DifferenceElementCalculator.calculate(a, b); + assertEquals(0, differenceElements.size()); + } + + @Test + void calculateDifferenceAIsEmpty() { + Node n1 = new FieldDeclaration(); + Node n2 = new MethodDeclaration(); + + LexicalDifferenceCalculator.CalculatedSyntaxModel a = new LexicalDifferenceCalculator.CalculatedSyntaxModel(Collections.emptyList()); + LexicalDifferenceCalculator.CalculatedSyntaxModel b = new LexicalDifferenceCalculator.CalculatedSyntaxModel(Arrays.asList( + new CsmToken(GeneratedJavaParserConstants.LPAREN), + new CsmChild(n1), + new CsmToken(GeneratedJavaParserConstants.RPAREN), + new CsmChild(n2))); + List differenceElements = DifferenceElementCalculator.calculate(a, b); + assertEquals(4, differenceElements.size()); + assertEquals(added(new CsmToken(GeneratedJavaParserConstants.LPAREN)), differenceElements.get(0)); + assertEquals(added(new CsmChild(n1)), differenceElements.get(1)); + assertEquals(added(new CsmToken(GeneratedJavaParserConstants.RPAREN)), differenceElements.get(2)); + assertEquals(added(new CsmChild(n2)), differenceElements.get(3)); + } + + @Test + void calculateDifferenceBIsEmpty() { + Node n1 = new FieldDeclaration(); + Node n2 = new MethodDeclaration(); + + LexicalDifferenceCalculator.CalculatedSyntaxModel a = new LexicalDifferenceCalculator.CalculatedSyntaxModel(Arrays.asList( + new CsmToken(GeneratedJavaParserConstants.LPAREN), + new CsmChild(n1), + new CsmToken(GeneratedJavaParserConstants.RPAREN), + new CsmChild(n2))); + LexicalDifferenceCalculator.CalculatedSyntaxModel b = new LexicalDifferenceCalculator.CalculatedSyntaxModel(Collections.emptyList()); + List differenceElements = DifferenceElementCalculator.calculate(a, b); + assertEquals(4, differenceElements.size()); + assertEquals(removed(new CsmToken(GeneratedJavaParserConstants.LPAREN)), differenceElements.get(0)); + assertEquals(removed(new CsmChild(n1)), differenceElements.get(1)); + assertEquals(removed(new CsmToken(GeneratedJavaParserConstants.RPAREN)), differenceElements.get(2)); + assertEquals(removed(new CsmChild(n2)), differenceElements.get(3)); + } + + @Test + void compilationUnitExampleWithPackageSetDiff() { + considerCode("class A {}"); + CsmElement element = ConcreteSyntaxModel.forClass(cu.getClass()); + PackageDeclaration packageDeclaration = new PackageDeclaration(new Name(new Name("foo"), "bar")); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmOriginal = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(element, cu); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmChanged = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterPropertyChange(element, cu, ObservableProperty.PACKAGE_DECLARATION, null, packageDeclaration); + List differenceElements = DifferenceElementCalculator.calculate(csmOriginal, csmChanged); + assertEquals(3, differenceElements.size()); + assertEquals(added(new CsmChild(packageDeclaration)), differenceElements.get(0)); + assertEquals(kept(new CsmChild(cu.getType(0))), differenceElements.get(1)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(2)); + } + + @Test + void annotationDeclarationExampleWithModifierAdded() throws IOException { + considerExample("AnnotationDeclaration_Example1_original"); + AnnotationDeclaration annotationDeclaration = (AnnotationDeclaration)cu.getType(0); + CsmElement element = ConcreteSyntaxModel.forClass(annotationDeclaration.getClass()); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmOriginal = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(element, annotationDeclaration); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmChanged = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterPropertyChange(element, annotationDeclaration, ObservableProperty.MODIFIERS, new NodeList<>(), createModifierList(PUBLIC)); + List differenceElements = DifferenceElementCalculator.calculate(csmOriginal, csmChanged); + DifferenceElementCalculator.removeIndentationElements(differenceElements); + int i = 0; + assertEquals(added(new CsmChild(Modifier.publicModifier())), differenceElements.get(i++)); + assertEquals(added(new CsmToken(spaceTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.AT)), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.INTERFACE)), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(spaceTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getName())), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(spaceTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.LBRACE)), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(0))), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(1))), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(2))), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(3))), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(4))), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(5))), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.RBRACE)), differenceElements.get(i++)); + assertEquals(i, differenceElements.size()); + } + + @Test + void annotationDeclarationExampleWithNameChanged() throws IOException { + considerExample("AnnotationDeclaration_Example1_original"); + AnnotationDeclaration annotationDeclaration = (AnnotationDeclaration)cu.getType(0); + CsmElement element = ConcreteSyntaxModel.forClass(annotationDeclaration.getClass()); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmOriginal = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(element, annotationDeclaration); + SimpleName newName = new SimpleName("NewName"); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmChanged = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterPropertyChange(element, annotationDeclaration, ObservableProperty.NAME, + annotationDeclaration.getName(), newName); + List differenceElements = DifferenceElementCalculator.calculate(csmOriginal, csmChanged); + DifferenceElementCalculator.removeIndentationElements(differenceElements); + int i = 0; + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.AT)), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.INTERFACE)), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(spaceTokenKind())), differenceElements.get(i++)); + assertEquals(removed(new CsmChild(annotationDeclaration.getName())), differenceElements.get(i++)); + assertEquals(added(new CsmChild(newName)), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(spaceTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.LBRACE)), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(0))), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(1))), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(2))), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(3))), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(4))), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(5))), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.RBRACE)), differenceElements.get(i++)); + assertEquals(i, differenceElements.size()); + } + + @Test + void annotationDeclarationExampleWithJavadocAdded() throws IOException { + considerExample("AnnotationDeclaration_Example3_original"); + AnnotationDeclaration annotationDeclaration = (AnnotationDeclaration)cu.getType(0); + CsmElement element = ConcreteSyntaxModel.forClass(annotationDeclaration.getClass()); + JavadocComment comment = new JavadocComment("Cool this annotation!"); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmOriginal = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(element, annotationDeclaration); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmChanged = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterPropertyChange(element, annotationDeclaration, ObservableProperty.COMMENT, null, comment); + List differenceElements = DifferenceElementCalculator.calculate(csmOriginal, csmChanged); + DifferenceElementCalculator.removeIndentationElements(differenceElements); + int i = 0; + assertEquals(kept(new CsmChild(Modifier.publicModifier())), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(spaceTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.AT)), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.INTERFACE)), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(spaceTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getName())), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(spaceTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.LBRACE)), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(0))), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(1))), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(2))), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(3))), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(4))), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(5))), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.RBRACE)), differenceElements.get(i++)); + assertEquals(i, differenceElements.size()); + } + + @Test + void annotationDeclarationExampleWithJavadocRemoved() throws IOException { + considerExample("AnnotationDeclaration_Example9_original"); + AnnotationDeclaration annotationDeclaration = (AnnotationDeclaration)cu.getType(0); + CsmElement element = ConcreteSyntaxModel.forClass(annotationDeclaration.getClass()); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmOriginal = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(element, annotationDeclaration); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmChanged = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterPropertyChange(element, annotationDeclaration, ObservableProperty.COMMENT, annotationDeclaration.getComment().get(), null); + List differenceElements = DifferenceElementCalculator.calculate(csmOriginal, csmChanged); + DifferenceElementCalculator.removeIndentationElements(differenceElements); + int i = 0; + assertEquals(kept(new CsmChild(Modifier.publicModifier())), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(spaceTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.AT)), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.INTERFACE)), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(spaceTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getName())), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(spaceTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.LBRACE)), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(0))), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(1))), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(2))), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(3))), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(4))), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(5))), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.RBRACE)), differenceElements.get(i++)); + assertEquals(i, differenceElements.size()); + } + + @Test + void annotationDeclarationExampleWithModifierRemoved() throws IOException { + considerExample("AnnotationDeclaration_Example3_original"); + AnnotationDeclaration annotationDeclaration = (AnnotationDeclaration)cu.getType(0); + CsmElement element = ConcreteSyntaxModel.forClass(annotationDeclaration.getClass()); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmOriginal = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(element, annotationDeclaration); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmChanged = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterPropertyChange(element, annotationDeclaration, ObservableProperty.MODIFIERS, createModifierList(PUBLIC), new NodeList<>()); + List differenceElements = DifferenceElementCalculator.calculate(csmOriginal, csmChanged); + DifferenceElementCalculator.removeIndentationElements(differenceElements); + int i = 0; + assertEquals(removed(new CsmChild(Modifier.publicModifier())), differenceElements.get(i++)); + assertEquals(removed(new CsmToken(spaceTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.AT)), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.INTERFACE)), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(spaceTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getName())), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(spaceTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.LBRACE)), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(0))), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(1))), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(2))), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(3))), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(4))), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(5))), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.RBRACE)), differenceElements.get(i++)); + assertEquals(i, differenceElements.size()); + } + + @Test + void removeDefaultValueInAnnotationMemberDeclaration() { + AnnotationMemberDeclaration md = considerAmd("int foo() default 10;"); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmOriginal = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(md); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmChanged = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterPropertyChange(md, ObservableProperty.DEFAULT_VALUE, md.getDefaultValue(), null); + List differenceElements = DifferenceElementCalculator.calculate(csmOriginal, csmChanged); + int i = 0; + assertEquals(kept(new CsmChild(md.getType())), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(spaceTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(md.getName())), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.LPAREN)), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.RPAREN)), differenceElements.get(i++)); + assertEquals(removed(new CsmToken(spaceTokenKind())), differenceElements.get(i++)); + assertEquals(removed(new CsmToken(GeneratedJavaParserConstants._DEFAULT)), differenceElements.get(i++)); + assertEquals(removed(new CsmToken(spaceTokenKind())), differenceElements.get(i++)); + assertEquals(removed(new CsmChild(md.getDefaultValue().get())), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.SEMICOLON)), differenceElements.get(i++)); + assertEquals(i, differenceElements.size()); + } + + @Test + void addedDefaultValueInAnnotationMemberDeclaration() { + AnnotationMemberDeclaration md = considerAmd("int foo();"); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmOriginal = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(md); + Expression defaultValue = new IntegerLiteralExpr(("10")); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmChanged = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterPropertyChange(md, ObservableProperty.DEFAULT_VALUE, null, defaultValue); + List differenceElements = DifferenceElementCalculator.calculate(csmOriginal, csmChanged); + int i = 0; + assertEquals(kept(new CsmChild(md.getType())), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(spaceTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(md.getName())), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.LPAREN)), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.RPAREN)), differenceElements.get(i++)); + assertEquals(added(new CsmToken(spaceTokenKind())), differenceElements.get(i++)); + assertEquals(added(new CsmToken(GeneratedJavaParserConstants._DEFAULT)), differenceElements.get(i++)); + assertEquals(added(new CsmToken(spaceTokenKind())), differenceElements.get(i++)); + assertEquals(added(new CsmChild(defaultValue)), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.SEMICOLON)), differenceElements.get(i++)); + assertEquals(i, differenceElements.size()); + } + + @Test + void addedModifierToConstructorDeclaration() { + ConstructorDeclaration cd = considerCd("A(){}"); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmOriginal = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(cd); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmChanged = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterPropertyChange(cd, ObservableProperty.MODIFIERS, + new NodeList<>(), createModifierList(PUBLIC)); + List differenceElements = DifferenceElementCalculator.calculate(csmOriginal, csmChanged); + int i = 0; + assertEquals(added(new CsmChild(Modifier.publicModifier())), differenceElements.get(i++)); + assertEquals(added(new CsmToken(spaceTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(cd.getName())), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.LPAREN)), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.RPAREN)), differenceElements.get(i++)); + assertEquals(kept(new CsmToken(spaceTokenKind())), differenceElements.get(i++)); + assertEquals(kept(new CsmChild(cd.getBody())), differenceElements.get(i++)); + assertEquals(i, differenceElements.size()); + } + + @Test + void replacingNameForEnumConstantDeclaration() { + EnumConstantDeclaration ecd = considerEcd("A"); + SimpleName newName = new SimpleName("B"); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmOriginal = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(ecd); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmChanged = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterPropertyChange(ecd, ObservableProperty.NAME, + ecd.getName(), newName); + List differenceElements = DifferenceElementCalculator.calculate(csmOriginal, csmChanged); + int i = 0; + assertEquals(DifferenceElement.removed(new CsmChild(ecd.getName())), differenceElements.get(i++)); + assertEquals(DifferenceElement.added(new CsmChild(newName)), differenceElements.get(i++)); + assertEquals(i, differenceElements.size()); + } + + @Test + void addingStatementToEmptyMethodBody() { + String code = "class A { void foo(char p1, int p2) {} }"; + considerCode(code); + + Statement s = new ExpressionStmt(new BinaryExpr( + new IntegerLiteralExpr("10"), new IntegerLiteralExpr("2"), BinaryExpr.Operator.PLUS + )); + MethodDeclaration m = cu.getClassByName("A").get().getMethodsByName("foo").get(0); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmOriginal = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(m.getBody().get()); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmChanged = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterListAddition(m.getBody().get(), ObservableProperty.STATEMENTS, 0, s); + List differenceElements = DifferenceElementCalculator.calculate(csmOriginal, csmChanged); + int i = 0; + assertEquals(DifferenceElement.kept(new CsmToken(GeneratedJavaParserConstants.LBRACE)), differenceElements.get(i++)); + assertEquals(DifferenceElement.kept(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(DifferenceElement.added(new CsmIndent()), differenceElements.get(i++)); + assertEquals(DifferenceElement.added(new CsmChild(s)), differenceElements.get(i++)); + assertEquals(DifferenceElement.added(new CsmToken(eolTokenKind())), differenceElements.get(i++)); + assertEquals(DifferenceElement.added(new CsmUnindent()), differenceElements.get(i++)); + assertEquals(DifferenceElement.kept(new CsmToken(GeneratedJavaParserConstants.RBRACE)), differenceElements.get(i++)); + assertEquals(i, differenceElements.size()); + } + + @Test + void methodDeclarationRemovingParameter() { + MethodDeclaration md = considerMd("public void foo(float f){}"); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmOriginal = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(md); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmChanged = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterListRemoval(md, ObservableProperty.PARAMETERS, 0); + List differenceElements = DifferenceElementCalculator.calculate(csmOriginal, csmChanged); + int i = 0; + assertEquals(DifferenceElement.kept(new CsmChild(Modifier.publicModifier())), differenceElements.get(i++)); + assertEquals(DifferenceElement.kept(new CsmToken(spaceTokenKind())), differenceElements.get(i++)); + assertEquals(DifferenceElement.kept(new CsmChild(md.getType())), differenceElements.get(i++)); + assertEquals(DifferenceElement.kept(new CsmToken(spaceTokenKind())), differenceElements.get(i++)); + assertEquals(DifferenceElement.kept(new CsmChild(md.getName())), differenceElements.get(i++)); + assertEquals(DifferenceElement.kept(new CsmToken(GeneratedJavaParserConstants.LPAREN)), differenceElements.get(i++)); + assertEquals(DifferenceElement.removed(new CsmChild(md.getParameter(0))), differenceElements.get(i++)); + assertEquals(DifferenceElement.kept(new CsmToken(GeneratedJavaParserConstants.RPAREN)), differenceElements.get(i++)); + assertEquals(DifferenceElement.kept(new CsmToken(spaceTokenKind())), differenceElements.get(i++)); + assertEquals(DifferenceElement.kept(new CsmChild(md.getBody().get())), differenceElements.get(i++)); + assertEquals(i, differenceElements.size()); + } + + @Test + void methodDeclarationAddingParameter() { + MethodDeclaration md = considerMd("public void foo(){}"); + Parameter newParameter = new Parameter(new ArrayType(PrimitiveType.intType()), new SimpleName("foo")); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmOriginal = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(md); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmChanged = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterListAddition(md, ObservableProperty.PARAMETERS, 0, newParameter); + List differenceElements = DifferenceElementCalculator.calculate(csmOriginal, csmChanged); + int i = 0; + assertEquals(DifferenceElement.kept(new CsmChild(Modifier.publicModifier())), differenceElements.get(i++)); + assertEquals(DifferenceElement.kept(new CsmToken(spaceTokenKind())), differenceElements.get(i++)); + assertEquals(DifferenceElement.kept(new CsmChild(md.getType())), differenceElements.get(i++)); + assertEquals(DifferenceElement.kept(new CsmToken(spaceTokenKind())), differenceElements.get(i++)); + assertEquals(DifferenceElement.kept(new CsmChild(md.getName())), differenceElements.get(i++)); + assertEquals(DifferenceElement.kept(new CsmToken(GeneratedJavaParserConstants.LPAREN)), differenceElements.get(i++)); + assertEquals(DifferenceElement.added(new CsmChild(newParameter)), differenceElements.get(i++)); + assertEquals(DifferenceElement.kept(new CsmToken(GeneratedJavaParserConstants.RPAREN)), differenceElements.get(i++)); + assertEquals(DifferenceElement.kept(new CsmToken(spaceTokenKind())), differenceElements.get(i++)); + assertEquals(DifferenceElement.kept(new CsmChild(md.getBody().get())), differenceElements.get(i++)); + assertEquals(i, differenceElements.size()); + } + + private AnnotationMemberDeclaration considerAmd(String code) { + considerCode("@interface AD { " + code + " }"); + return (AnnotationMemberDeclaration)cu.getAnnotationDeclarationByName("AD").get().getMember(0); + } + + private ConstructorDeclaration considerCd(String code) { + considerCode("class A { " + code + " }"); + return (ConstructorDeclaration) cu.getType(0).getMembers().get(0); + } + + private EnumConstantDeclaration considerEcd(String code) { + considerCode("enum A { " + code + " }"); + return ((EnumDeclaration)cu.getType(0)).getEntries().get(0); + } + + private MethodDeclaration considerMd(String code) { + considerCode("class A { " + code + " }"); + return (MethodDeclaration) cu.getType(0).getMembers().get(0); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue1467Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue1467Test.java new file mode 100644 index 0000000..b5ff07f --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue1467Test.java @@ -0,0 +1,69 @@ +package com.github.javaparser.printer.lexicalpreservation; + +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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. + */ + +import com.github.javaparser.ast.Modifier.Keyword; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.expr.ObjectCreationExpr; +import com.github.javaparser.ast.expr.StringLiteralExpr; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.ast.stmt.ThrowStmt; +import com.github.javaparser.utils.TestUtils; +import org.junit.jupiter.api.Test; + +public class Issue1467Test extends AbstractLexicalPreservingTest { + + @Test + public void test() { + considerCode( + "public class Bar {\n" + + " public void foo() {\n" + + " System.out.print(\"Hello\");\n" + + " }\n" + + "}"); + String expected = + "public void f() {\n" + + " throw new UnsupportedOperationException(\"Not supported yet.\");\n" + + " }" ; + // add method declaration + MethodDeclaration decl = cu.getChildNodesByType(ClassOrInterfaceDeclaration.class).get(0).addMethod("f", Keyword.PUBLIC); + // create body + BlockStmt body = new BlockStmt(); + NodeList statements = new NodeList<>(); + ObjectCreationExpr exception = new ObjectCreationExpr(); + exception.setType("UnsupportedOperationException"); + NodeList arguments = new NodeList<>(); + arguments.add(new StringLiteralExpr("Not supported yet.")); + exception.setArguments(arguments); + statements.add(new ThrowStmt(exception)); + body.setStatements(statements); + // set body to the method declaration + decl.setBody(body); + // print the result from LexicalPreservingPrinter + String actual = LexicalPreservingPrinter.print(decl); + TestUtils.assertEqualsStringIgnoringEol(expected, actual); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue1634Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue1634Test.java new file mode 100644 index 0000000..8152225 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue1634Test.java @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2013-2024 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 com.github.javaparser.ast.ImportDeclaration; +import com.github.javaparser.ast.NodeList; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class Issue1634Test extends AbstractLexicalPreservingTest { + + @Test + public void testWithLexicalPreservationEnabled() { + + considerCode("package com.wangym.test;\nclass A{ }"); + + String expected = + "package com.wangym.test;\n" + + "import lombok.Data;\n" + + "\n" + + "class A{ }"; + + NodeList imports = cu.getImports(); + String str = "lombok.Data"; + imports.add(new ImportDeclaration(str, false, false)); + + assertEquals(expected, LexicalPreservingPrinter.print(cu)); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue1766Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue1766Test.java new file mode 100644 index 0000000..137a197 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue1766Test.java @@ -0,0 +1,84 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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 com.github.javaparser.utils.TestUtils; +import org.junit.jupiter.api.Test; + +public class Issue1766Test extends AbstractLexicalPreservingTest { + + @Test + public void testWithLexicalPreservationEnabled() { + + considerCode( + "public class SimpleTestClass {\n" + + " public SimpleTestClass() {\n" + + " // nothing\n" + + " }\n" + + " @Override\n" + + " void bubber() {\n" + + " // nothing\n" + + " }\n" + + "}"); + + String expected = + "public class SimpleTestClass {\n" + + " public SimpleTestClass() {\n" + + " // nothing\n" + + " }\n" + + " @Override\n" + + " void bubber() {\n" + + " // nothing\n" + + " }\n" + + "}"; + + TestUtils.assertEqualsStringIgnoringEol(expected, LexicalPreservingPrinter.print(cu)); + } + + @Test + public void testWithLexicalPreservingPrinterSetup() { + + considerCode( + "public class SimpleTestClass {\n" + + " public SimpleTestClass() {\n" + + " // nothing\n" + + " }\n" + + " @Override\n" + + " void bubber() {\n" + + " // nothing\n" + + " }\n" + + "}"); + + String expected = + "public class SimpleTestClass {\n" + + " public SimpleTestClass() {\n" + + " // nothing\n" + + " }\n" + + " @Override\n" + + " void bubber() {\n" + + " // nothing\n" + + " }\n" + + "}"; + + TestUtils.assertEqualsStringIgnoringEol(expected, LexicalPreservingPrinter.print(cu)); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue1793Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue1793Test.java new file mode 100644 index 0000000..617fc92 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue1793Test.java @@ -0,0 +1,53 @@ + +/* + * Copyright (C) 2015-2016 Federico Tomassetti + * Copyright (C) 2017-2024 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 com.github.javaparser.ParserConfiguration; +import com.github.javaparser.StaticJavaParser; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class Issue1793Test extends AbstractLexicalPreservingTest { + + @AfterEach + public void reset() { + StaticJavaParser.setConfiguration(new ParserConfiguration()); + } + + @Test + void importIsAddedOnTheSameLine() { + considerCode( + "public class Test {\n" + + " public void foo(Bar x, Bar y) {\n" + + " x.barf(); // expected to be wrapped\n" + + " x.bark(); // expected to be wrapped\n" + + " y.barf(); // expected to be wrapped\n" + + " y.bark(); // expected to be wrapped\n" + + " }\n" + + "}"); + assertEquals(LexicalPreservingPrinter.print(cu), LexicalPreservingPrinter.print(cu.clone())); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2137Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2137Test.java new file mode 100755 index 0000000..06d1311 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2137Test.java @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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 com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.type.VoidType; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol; + +public class Issue2137Test extends AbstractLexicalPreservingTest { + + @Test + void test2137() { + considerCode( + "public class Foo {\n" + + " void mymethod1() {}\n" + + " void mymethod2() {}\n" + + "}"); + String expected = + "public class Foo {\n" + + " void mymethod1() {}\n" + + " void mymethod3() {\n"+ + " }\n" + + " \n" + + " void mymethod2() {}\n" + + "}"; + ClassOrInterfaceDeclaration cid = cu.getClassByName("Foo").get(); + MethodDeclaration methodDeclaration = new MethodDeclaration(); + methodDeclaration.setName("mymethod3"); + methodDeclaration.setType(new VoidType()); + cid.getMembers().add(1, methodDeclaration); + + assertEqualsStringIgnoringEol(expected, LexicalPreservingPrinter.print(cu)); + } + + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2290Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2290Test.java new file mode 100644 index 0000000..839e1da --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2290Test.java @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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 com.github.javaparser.ast.stmt.ExpressionStmt; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class Issue2290Test extends AbstractLexicalPreservingTest { + + @Test + public void test() { + + considerCode( + "public class Clone1 {\n" + + " public static void main(String[] args) {\n" + + " System.out.println(\"I'm a clone10\");\n" + + " System.out.println(\"I'm not a clone!\");\n" + + " System.out.println(\"I'm a clone10\");\n" + + " }\n" + + "}"); + List exprs = cu.findAll(ExpressionStmt.class); + ExpressionStmt es = exprs.get(exprs.size()-1); + es.getParentNode().get().remove(es); + exprs = cu.findAll(ExpressionStmt.class); + // verify that one statement is removed + assertTrue(exprs.size()==2); + // verify that the first statement is not removed + assertEquals("System.out.println(\"I'm a clone10\");",exprs.get(0).toString()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2374Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2374Test.java new file mode 100644 index 0000000..f3fb425 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2374Test.java @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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 com.github.javaparser.StaticJavaParser; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.stmt.Statement; +import org.junit.jupiter.api.Test; + +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol; + +public class Issue2374Test extends AbstractLexicalPreservingTest { + + @Test + public void test() { + String lineComment = "Example comment"; + considerCode( + "public class Bar {\n" + + " public void foo() {\n" + + " System.out.print(\"Hello\");\n" + + " }\n" + + "}" + ); + String expected = + "public class Bar {\n" + + " public void foo() {\n" + + " System.out.print(\"Hello\");\n" + + " //Example comment\n" + + " System.out.println(\"World!\");\n" + + " }\n" + + "}"; + // contruct a statement with a comment + Statement stmt = StaticJavaParser.parseStatement("System.out.println(\"World!\");"); + stmt.setLineComment(lineComment); + // add the statement to the ast + Optional md = cu.findFirst(MethodDeclaration.class); + md.get().getBody().get().addStatement(stmt); + // print the result from LexicalPreservingPrinter + String result = LexicalPreservingPrinter.print(cu); + // verify that the LexicalPreservingPrinter don't forget the comment + assertEqualsStringIgnoringEol(expected, result); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2393Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2393Test.java new file mode 100644 index 0000000..c879a3f --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2393Test.java @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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 com.github.javaparser.StaticJavaParser; +import com.github.javaparser.ast.stmt.IfStmt; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class Issue2393Test extends AbstractLexicalPreservingTest { + + @Test + public void test() { + considerCode("public class Test { public void foo() { int i = 0;\nif(i == 5) { System.out.println(i); } } }"); + IfStmt ifStmt = cu.findFirst(IfStmt.class).orElseThrow(() -> new IllegalStateException("Expected if")); + ifStmt.setCondition(StaticJavaParser.parseExpression("i > 0")); + assertEquals("i > 0", ifStmt.getCondition().toString()); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2517Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2517Test.java new file mode 100755 index 0000000..369050d --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2517Test.java @@ -0,0 +1,62 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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 com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.expr.ObjectCreationExpr; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol; + +public class Issue2517Test extends AbstractLexicalPreservingTest { + + @Test + public void test() { + + considerCode("public class A {\n" + + " public A(String a , String b) {\n" + + " }\n" + + " public static A m() {\n" + + " return new A(\"a\",\"b\");\n" + + " }\n" + + "}"); + + String expected = + "public class A {\n" + + " public A(String a , String b) {\n" + + " }\n" + + " public static A m() {\n" + + " return new A(\"b\", \"a\");\n" + + " }\n" + + "}"; + + ObjectCreationExpr cd = cu.findFirst(ObjectCreationExpr.class).get(); + NodeList args = cd.getArguments(); + Expression a1 = args.get(0); + Expression a2 = args.get(1); + NodeList newArgs = new NodeList<>(a2, a1); + cd.setArguments(newArgs); + + assertEqualsStringIgnoringEol(expected, LexicalPreservingPrinter.print(cu)); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2592Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2592Test.java new file mode 100644 index 0000000..0b593ef --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2592Test.java @@ -0,0 +1,71 @@ +/* + * Copyright (C) 2013-2024 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 com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.body.Parameter; +import com.github.javaparser.ast.expr.SimpleName; +import org.junit.jupiter.api.Test; + +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertTrue; + + +public class Issue2592Test extends AbstractLexicalPreservingTest { + + @Test + public void testLPP() { + + considerCode("public class A {" + + " public void m(final int a_original, int b) {" + + " }" + + "} "); + Optional md = cu.findFirst(MethodDeclaration.class); + //all parameters have parent nodes here + assertTrue(md.get().getParameters().stream().allMatch(p -> p.getParentNode().isPresent())); + + //all parameters have parent nodes here + assertTrue(md.get().getParameters().stream().allMatch(p -> p.getParentNode().isPresent())); + + + //add a third parameter + md.get().addParameter("String", "c_brand_new"); + + //seems like we can add a parameter fine (and all of the parents still assigned) + assertTrue(md.get().getParameters().stream().allMatch(p -> p.getParentNode().isPresent())); + + +// md.get().getParameters().forEach(p -> System.out.println(p + " parent " + p.getParentNode().isPresent())); + Parameter p1 = md.get().getParameter(0); + Parameter p2 = new Parameter(p1.getModifiers(), p1.getType(), new SimpleName("a_renamed")); + + //here we replace a parameter + boolean isReplaced = md.get().replace(p1, p2); + assertTrue(isReplaced); //the replacement seemed to work + + + //...however when we replaced the parent nodes (for the replaced node AND the added node (after the replaced node) now null +// md.get().getParameters().forEach(p -> System.out.println(p + " parent " + p.getParentNode().isPresent())); + assertTrue(md.get().getParameters().stream().allMatch(p -> p.getParentNode().isPresent())); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2610Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2610Test.java new file mode 100644 index 0000000..2f703ae --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2610Test.java @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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 com.github.javaparser.StaticJavaParser; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.expr.MethodCallExpr; +import org.junit.jupiter.api.Test; + +import java.util.Optional; + +public class Issue2610Test extends AbstractLexicalPreservingTest { + + /* + * This test case must prevent an UnsupportedOperation Removed throwed by LexicalPreservation when we try to replace an expression + */ + @Test + public void test() { + + considerCode( + "public class Bar {\n" + + " public void foo() {\n" + + " // comment\n" + + " System.out.print(\"error\");\n" + + " }\n" + + "}" + ); + // contruct a statement with a comment + Expression expr = StaticJavaParser.parseExpression("System.out.println(\"warning\")"); + // Replace the method expression + Optional mce = cu.findFirst(MethodCallExpr.class); + mce.get().getParentNode().get().replace(mce.get(), expr); + // TODO assert something + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2620Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2620Test.java new file mode 100644 index 0000000..c8c49eb --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2620Test.java @@ -0,0 +1,120 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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 com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.FieldDeclaration; +import com.github.javaparser.ast.body.VariableDeclarator; +import com.github.javaparser.ast.type.ClassOrInterfaceType; +import com.github.javaparser.utils.LineSeparator; +import org.junit.jupiter.api.Test; + +import java.util.Optional; + +import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +public class Issue2620Test extends AbstractLexicalPreservingTest { + + @Test + public void testWithCr() { + doTest(LineSeparator.CR); + } + + @Test + public void testWithLf() { + doTest(LineSeparator.LF); + } + + @Test + public void testWithCrLf() { + doTest(LineSeparator.CRLF); + } + + + /* + * This test case must prevent an UnsupportedOperation Removed throwed by LexicalPreservation when we try to replace an expression + */ + public void doTest(LineSeparator eol) { + + considerCode("" + + " public class Foo { //comment" + eol + + " private String a;" + eol + + " private String b;" + eol + + " private String c;" + eol + + " private String d;" + eol + + " }"); + + // Note: Expect the platform's EOL character when printing + // FIXME: Indentation is bad here. + String expected = "" + + " public class Foo { //comment" + eol + + " private String newField;" + eol + + " " + eol + + " private String a;" + eol + + " private String b;" + eol + + " private String c;" + eol + + " private String d;" + eol + + " }"; + + + // create a new field declaration + VariableDeclarator variable = new VariableDeclarator(new ClassOrInterfaceType("String"), "newField"); + FieldDeclaration fd = new FieldDeclaration(new NodeList(Modifier.privateModifier()), variable); + Optional cd = cu.findFirst(ClassOrInterfaceDeclaration.class); + + // add the new variable + cd.get().getMembers().addFirst(fd); + + // should be printed like this +// System.out.println("\n\nOriginal:\n" + original); +// System.out.println("\n\nExpected:\n" + expected); + + // but the result is + final String actual = LexicalPreservingPrinter.print(cu); +// System.out.println("\n\nActual:\n" + actual); + + LineSeparator detectedLineSeparator = LineSeparator.detect(actual); + + assertFalse(detectedLineSeparator.equals(LineSeparator.MIXED)); + assertEquals(eol.asEscapedString(), detectedLineSeparator.asEscapedString()); + + assertEquals(normaliseNewlines(expected), normaliseNewlines(actual)); + + // Commented out until #2661 is fixed (re: EOL characters of injected code) + assertEqualsStringIgnoringEol(escapeNewlines(expected), escapeNewlines(actual)); + assertEquals(expected, actual, "Failed due to EOL differences."); + } + + private String escapeNewlines(String input) { + return input + .replaceAll("\\r", "\\\\r") + .replaceAll("\\n", "\\\\n"); + } + + private String normaliseNewlines(String input) { + return input.replaceAll("\\r\\n|\\r|\\n", "\\\\n"); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2806Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2806Test.java new file mode 100644 index 0000000..7cf47f9 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue2806Test.java @@ -0,0 +1,54 @@ + +/* + * Copyright (C) 2015-2016 Federico Tomassetti + * Copyright (C) 2017-2024 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 com.github.javaparser.JavaParser; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.ImportDeclaration; +import org.junit.jupiter.api.Test; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +class Issue2806Test extends AbstractLexicalPreservingTest{ + + private JavaParser javaParser; + + @Test + void importIsAddedOnTheSameLine() { + considerCode("import java.lang.IllegalArgumentException;\n" + + "\n" + + "public class A {\n" + + "}"); + String junit5 = "import java.lang.IllegalArgumentException;\n" + + "import java.nio.file.Paths;\n" + + "\n" + + "public class A {\n" + + "}"; + ImportDeclaration importDeclaration = new ImportDeclaration("java.nio.file.Paths", false, false); + CompilationUnit compilationUnit = cu.addImport(importDeclaration); + String out = LexicalPreservingPrinter.print(compilationUnit); + assertThat(out, equalTo(junit5)); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3296Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3296Test.java new file mode 100644 index 0000000..ffe3a9c --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3296Test.java @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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 com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.VariableDeclarator; +import org.junit.jupiter.api.Test; + +import java.util.Optional; + +import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class Issue3296Test extends AbstractLexicalPreservingTest { + + @Test + public void test() { + considerCode("public class Test { String[][] allTest; }"); + String expected = "public class Test { @Nullable\n" + + "String[][] allTest; }"; + Optional clazzOptional = cu.getClassByName("Test"); + assertTrue(clazzOptional.isPresent()); + ClassOrInterfaceDeclaration clazz = clazzOptional.get(); + clazz.getMembers().forEach( + bodyDeclaration -> + bodyDeclaration.ifFieldDeclaration( + fieldDeclaration -> { + NodeList vars = + fieldDeclaration.asFieldDeclaration().getVariables(); + for (VariableDeclarator v : vars) { + if (v.getName().toString().equals("allTest")) { + fieldDeclaration.addMarkerAnnotation("Nullable"); + break; + } + } + })); + assertEqualsStringIgnoringEol(expected, LexicalPreservingPrinter.print(cu)); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3358Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3358Test.java new file mode 100644 index 0000000..166a5d7 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3358Test.java @@ -0,0 +1,74 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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 com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.Modifier.Keyword; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class Issue3358Test extends AbstractLexicalPreservingTest { + + @Test + void testArrayTypeWithBracketAfterTypeWithoutWhitespace() { + String def = "int[] i"; + considerVariableDeclaration(def); + expression.asVariableDeclarationExpr().getModifiers().addFirst(Modifier.privateModifier()); + assertTrue(LexicalPreservingPrinter.getOrCreateNodeText(expression).getElements().stream() + .anyMatch(elem -> elem.expand().equals(Keyword.PRIVATE.asString()))); + assertTrue(LexicalPreservingPrinter.print(expression).equals("private int[] i")); + } + + @Test + void testArrayTypeWithWhitespaceBeforeTypeAndBracket() { + String def = "int [] i"; + considerVariableDeclaration(def); + expression.asVariableDeclarationExpr().getModifiers().addFirst(Modifier.privateModifier()); + assertTrue(LexicalPreservingPrinter.getOrCreateNodeText(expression).getElements().stream() + .anyMatch(elem -> elem.expand().equals(Keyword.PRIVATE.asString()))); + assertTrue(LexicalPreservingPrinter.print(expression).equals("private int [] i")); + } + + @Test + void testArrayTypeWithWhitespaceBeforeEachToken() { + String def = "int [ ] i"; + considerVariableDeclaration(def); + expression.asVariableDeclarationExpr().getModifiers().addFirst(Modifier.privateModifier()); + assertTrue(LexicalPreservingPrinter.getOrCreateNodeText(expression).getElements().stream() + .anyMatch(elem -> elem.expand().equals(Keyword.PRIVATE.asString()))); + assertTrue(LexicalPreservingPrinter.print(expression).equals("private int [ ] i")); + } + + @Test + void testArrayTypeWithMultipleWhitespaces() { + String def = "int [ ] i"; + considerVariableDeclaration(def); + expression.asVariableDeclarationExpr().getModifiers().addFirst(Modifier.privateModifier()); + assertTrue(LexicalPreservingPrinter.getOrCreateNodeText(expression).getElements().stream() + .anyMatch(elem -> elem.expand().equals(Keyword.PRIVATE.asString()))); + assertTrue(LexicalPreservingPrinter.print(expression).equals("private int [ ] i")); + } + +// TODO This syntax {@code int i[]} does not work! + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3387Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3387Test.java new file mode 100644 index 0000000..33c3568 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3387Test.java @@ -0,0 +1,66 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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 com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.javadoc.Javadoc; +import com.github.javaparser.javadoc.description.JavadocDescription; +import org.junit.jupiter.api.Test; + +import java.util.StringJoiner; + +import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol; + +public class Issue3387Test extends AbstractLexicalPreservingTest { + + @Test + public void test3387() { + considerCode(new StringJoiner("\n") + .add("class A {") + .add("") + .add("\tpublic void setTheNumber(int number) {") + .add("\t\tnumber = number;") + .add("\t}") + .add("") + .add("}").toString()); + + String expected = "class A {\n" + + "\n" + + "\t/**\n" + + "\t * Change Javadoc\n" + + "\t */\n" + + "\tpublic void setTheNumber(int number) {\n" + + "\t\tnumber = number;\n" + + "\t}\n" + + "\n" + + "}"; + + MethodDeclaration md = cu.findFirst(MethodDeclaration.class).get(); + // create new javadoc comment + Javadoc javadoc = new Javadoc(JavadocDescription.parseText("Change Javadoc")); + md.setJavadocComment("\t", javadoc); + System.out.println(LexicalPreservingPrinter.print(cu)); + assertEqualsStringIgnoringEol(expected, LexicalPreservingPrinter.print(cu)); + } + + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3440Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3440Test.java new file mode 100644 index 0000000..53407d0 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3440Test.java @@ -0,0 +1,40 @@ +package com.github.javaparser.printer.lexicalpreservation; + +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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. + */ + +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.stmt.SwitchEntry; +import com.github.javaparser.utils.TestUtils; +import org.junit.jupiter.api.Test; + +public class Issue3440Test extends AbstractLexicalPreservingTest { + + @Test + void test3440() { + considerCode("public class Foo { public void bar() { switch(1) {case 1: break; } } }"); + String expected = "public class Foo { public void bar() { switch(1) {case 1: } } }"; + SwitchEntry entry = cu.findFirst(SwitchEntry.class).get(); + entry.setStatements(new NodeList<>()); + TestUtils.assertEqualsStringIgnoringEol(expected, LexicalPreservingPrinter.print(cu)); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3441Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3441Test.java new file mode 100755 index 0000000..5d30557 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3441Test.java @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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 com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.ast.stmt.Statement; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol; + +public class Issue3441Test extends AbstractLexicalPreservingTest { + + @Test + void test() { + considerCode( + "public class Foo {\n" + + " void bar() {\n" + + " stmt1(); // comment 1\n" + + " stmt2(); // comment 2\n" + + " }\n" + + "}"); + String expected = + "public class Foo {\n" + + " void bar() {\n" + + " stmt2(); // comment 2\n" + + " }\n" + + "}"; + + BlockStmt block = cu.findFirst(BlockStmt.class).get(); + Statement stmt = block.getStatements().get(0); + + block.remove(stmt); + + assertEqualsStringIgnoringEol(expected, LexicalPreservingPrinter.print(cu)); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3721Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3721Test.java new file mode 100644 index 0000000..25fbd88 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3721Test.java @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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 com.github.javaparser.ast.body.VariableDeclarator; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol; + +public class Issue3721Test extends AbstractLexicalPreservingTest { + + @Test + void issue3721() { + considerCode( + "public class Bug {\n" + + " public static void main(String[] args) {\n" + + " Object msg;\n" + + " }\n" + + "}\n"); + + String expected = + "public class Bug {\n" + + "\n" + + " public static void main(String[] args) {\n" + + " boolean msg;\n" + + " }\n" + + "}\n"; + + + VariableDeclarator var = cu.findFirst(VariableDeclarator.class).get(); + var.setType("boolean"); + assertEqualsStringIgnoringEol(expected, cu.toString()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3746Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3746Test.java new file mode 100755 index 0000000..c5d5747 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3746Test.java @@ -0,0 +1,63 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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 com.github.javaparser.ast.expr.MethodCallExpr; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.ast.stmt.ExpressionStmt; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class Issue3746Test extends AbstractLexicalPreservingTest { + + @Test + void test() { + considerCode( + "public class MyClass {\n" + + " String s0;\n" + + " // Comment\n" + + " String s1;\n" + + "}"); + + considerCode("class A {\n" + + " void foo() {\n" + + " int first = 1;\n" + + " int second = 2;\n" + + " }\n" + + "}" + ); + + String expected = + "class A {\n" + + " void foo() {\n" + + " foo();\n" + + " int second = 2;\n" + + " }\n" + + "}"; + BlockStmt block = cu.findAll(BlockStmt.class).get(0); + ExpressionStmt newStmt = new ExpressionStmt(new MethodCallExpr("foo")); + block.addStatement(1,newStmt); + block.getStatement(0).remove(); + assertEquals(expected, LexicalPreservingPrinter.print(cu)); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3750Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3750Test.java new file mode 100755 index 0000000..b25d3b9 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3750Test.java @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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 com.github.javaparser.ast.body.FieldDeclaration; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class Issue3750Test extends AbstractLexicalPreservingTest { + + @Test + void test() { + considerCode( + "public class MyClass {\n" + + " String s0;\n" + + " // Comment\n" + + " String s1;\n" + + "}"); + + List fields = cu.findAll(FieldDeclaration.class); + FieldDeclaration field = fields.get(0); + + String expected = + "public class MyClass {\n" + + " // Comment\n" + + " String s1;\n" + + "}"; + + field.remove(); + + assertEquals(expected, LexicalPreservingPrinter.print(cu)); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3761Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3761Test.java new file mode 100755 index 0000000..bdac2b6 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3761Test.java @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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 com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.body.FieldDeclaration; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.stream.Collectors; + +import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol; + +public class Issue3761Test extends AbstractLexicalPreservingTest { + + @Test + public void test() { + considerCode( + "class C { \n" + + " static String S = \"s\";\n" + + "}"); + + FieldDeclaration field = cu.findAll(FieldDeclaration.class).get(0); + + List kws = field.getModifiers().stream().map(Modifier::getKeyword).collect(Collectors.toList()); + kws.add(0, Modifier.Keyword.PROTECTED); + field.setModifiers(kws.toArray(new Modifier.Keyword[] {})); + + String expected = + "class C { \r\n" + + " protected static String S = \"s\";\r\n" + + "}"; + + assertEqualsStringIgnoringEol(expected, LexicalPreservingPrinter.print(cu)); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3773Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3773Test.java new file mode 100755 index 0000000..642c018 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3773Test.java @@ -0,0 +1,148 @@ + +/* + * Copyright (C) 2015-2016 Federico Tomassetti + * Copyright (C) 2017-2024 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 com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.expr.BinaryExpr.Operator; +import com.github.javaparser.ast.stmt.ExpressionStmt; +import com.github.javaparser.ast.stmt.IfStmt; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.ast.visitor.ModifierVisitor; +import com.github.javaparser.ast.visitor.Visitable; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol; + +class Issue3773Test extends AbstractLexicalPreservingTest { + + @Test + void test3773() { + considerCode( + "class A {\r\n" + + " public String output = \"Contents of \";\r\n" + + " \r\n" + + " public String debug(String output) {\r\n" + + "\r\n" + + " Log.d(\"Debug\", output1); \r\n" + + " Log.d(\"Debug\", output2); \r\n" + + " Log.d(\"Debug\", output3); \r\n" + + " Log.d(\"Debug\", output4); \r\n" + + " \r\n" + + " output = \"1\";\r\n" + + " Log.d(\"Debug\", output1);\r\n" + + " \r\n" + + " output = \"2\";\r\n" + + " Log.d(\"Debug\", output2);\r\n" + + " \r\n" + + " output = \"3\";\r\n" + + " Log.d(\"Debug\", output3);\r\n" + + " \r\n" + + " Log.d(\"Debug\", \"\"); \r\n" + + " Log.d(\"Debug\", \"\"); \r\n" + + " Log.d(\"Debug\", \"3\"); \r\n" + + " Log.d(\"Debug\", \"4\"); \r\n" + + " \r\n" + + " return \"\";\r\n" + + " }\r\n" + + "}"); + String expected = + "class A {\r\n" + + " public String output = \"Contents of \";\r\n" + + " \r\n" + + " public String debug(String output) {\r\n" + + "\r\n" + + " if (Log.Level >= 3)\r\n" + + " Log.d(\"Debug\", output1); \r\n" + + " if (Log.Level >= 3)\r\n" + + " Log.d(\"Debug\", output2); \r\n" + + " if (Log.Level >= 3)\r\n" + + " Log.d(\"Debug\", output3); \r\n" + + " if (Log.Level >= 3)\r\n" + + " Log.d(\"Debug\", output4); \r\n" + + " \r\n" + + " output = \"1\";\r\n" + + " if (Log.Level >= 3)\r\n" + + " Log.d(\"Debug\", output1);\r\n" + + " \r\n" + + " output = \"2\";\r\n" + + " if (Log.Level >= 3)\r\n" + + " Log.d(\"Debug\", output2);\r\n" + + " \r\n" + + " output = \"3\";\r\n" + + " if (Log.Level >= 3)\r\n" + + " Log.d(\"Debug\", output3);\r\n" + + " \r\n" + + " if (Log.Level >= 3)\r\n" + + " Log.d(\"Debug\", \"\"); \r\n" + + " if (Log.Level >= 3)\r\n" + + " Log.d(\"Debug\", \"\"); \r\n" + + " if (Log.Level >= 3)\r\n" + + " Log.d(\"Debug\", \"3\"); \r\n" + + " if (Log.Level >= 3)\r\n" + + " Log.d(\"Debug\", \"4\"); \r\n" + + " \r\n" + + " return \"\";\r\n" + + " }\r\n" + + "}"; + + // here the logic + FunctionVisitor funVisitor = new FunctionVisitor(); + funVisitor.visit(cu, null); + + + assertEqualsStringIgnoringEol(expected, LexicalPreservingPrinter.print(cu)); + } + + public class FunctionVisitor extends ModifierVisitor { + + @Override + public Visitable visit(ExpressionStmt node, Object arg) { + List mces = node.getChildNodesByType(MethodCallExpr.class); + if (mces.isEmpty()) + return node; + MethodCallExpr mce = mces.get(0); + if (mce.getScope().isPresent() && mce.getName() != null) { + String nodeScope = mce.getScope().get().toString(); + String nodeName = mce.getName().toString(); + if (nodeScope.equals("Log")) { + if (nodeName.equals("d")) { + IfStmt ifStmt = makeIfStmt(node); + return ifStmt; + } + } + } + return node; + } + } + + private IfStmt makeIfStmt(Statement thenStmt) { + Expression left = new FieldAccessExpr(new NameExpr("Log"), "Level"); + Expression right = new IntegerLiteralExpr("3"); + BinaryExpr condition = new BinaryExpr(left, right, Operator.GREATER_EQUALS); + IfStmt ifStmt = new IfStmt(condition, thenStmt, null); + return ifStmt; + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3796Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3796Test.java new file mode 100755 index 0000000..9bb376b --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3796Test.java @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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 static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.List; + +import org.junit.jupiter.api.Test; + +import com.github.javaparser.ast.body.FieldDeclaration; + +public class Issue3796Test extends AbstractLexicalPreservingTest { + + @Test + void test() { + considerCode( + "public class MyClass {\n" + + " /** Comment */ \n" + + " @Rule String s0; \n" + + "}"); + String expected = + "public class MyClass {\n" + + "\n" + + "}"; + + List fields = cu.findAll(FieldDeclaration.class); + FieldDeclaration field = fields.get(0); + + field.remove(); + + assertEqualsStringIgnoringEol(expected, LexicalPreservingPrinter.print(cu)); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3818Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3818Test.java new file mode 100755 index 0000000..9e75d07 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3818Test.java @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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 com.github.javaparser.StaticJavaParser; +import com.github.javaparser.ast.body.BodyDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.body.Parameter; +import com.github.javaparser.ast.expr.SimpleName; + +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol; + +public class Issue3818Test extends AbstractLexicalPreservingTest { + + @Test + void test() { + String src = "public class Foo {\n" + + "\n" + + " public Long[][] m(int[] a){}\n" + + "}"; + + String expected = "public class Foo {\n" + + "\n" + + " public Long[][] m(int[] b){}\n" + + "}"; + + BodyDeclaration cu = StaticJavaParser.parseBodyDeclaration(src); + MethodDeclaration md = cu.findAll(MethodDeclaration.class).get(0); + LexicalPreservingPrinter.setup(md); + Parameter p = md.getParameter(0); + Parameter paramExpr = new Parameter(p.getModifiers(), p.getAnnotations(), p.getType(), + p.isVarArgs(), p.getVarArgsAnnotations(), new SimpleName("b")); + md.replace(p, paramExpr); + assertEqualsStringIgnoringEol(expected, LexicalPreservingPrinter.print(cu)); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3924Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3924Test.java new file mode 100755 index 0000000..3d98cba --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3924Test.java @@ -0,0 +1,76 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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; + +public class Issue3924Test extends AbstractLexicalPreservingTest { + + @Test + void test() { + considerCode( + "/*\n" + " * Licensed under the Apache License, Version 2.0 (the \"License\");\n" + + " * you may not use this file except in compliance with the License.\n" + + " * You may obtain a copy of the License at\n" + + " */\n" + + "\n" + + "@XmlSchema(\n" + + " xmlns = {\n" + + " @XmlNs(prefix = \"order\", namespaceURI = \"http://www.camel.apache.org/jaxb/example/order/1\"),\n" + + " @XmlNs(prefix = \"address\", namespaceURI = \"http://www.camel.apache.org/jaxb/example/address/1\")\n" + + " }\n" + + ")\n" + + "package net.revelc.code.imp;\n" + + "\n" + + "import net.revelc.code.imp.Something;\n" + + "\n" + + "@Component\n" + + "public class UnusedImports {\n" + + "}\n" + + ""); + + LexicalPreservingPrinter.setup(cu); + cu.getImport(0).remove(); + String actual = LexicalPreservingPrinter.print(cu); + String expected = + "/*\r\n" + + " * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n" + + " * you may not use this file except in compliance with the License.\r\n" + + " * You may obtain a copy of the License at\r\n" + + " */\r\n" + + "\r\n" + + "@XmlSchema(\r\n" + + " xmlns = {\r\n" + + " @XmlNs(prefix = \"order\", namespaceURI = \"http://www.camel.apache.org/jaxb/example/order/1\"),\r\n" + + " @XmlNs(prefix = \"address\", namespaceURI = \"http://www.camel.apache.org/jaxb/example/address/1\")\r\n" + + " }\r\n" + + ")\r\n" + + "package net.revelc.code.imp;\r\n" + + "\r\n" + + "@Component\r\n" + + "public class UnusedImports {\r\n" + + "}\n"; + assertEqualsStringIgnoringEol(expected, actual); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3936Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3936Test.java new file mode 100755 index 0000000..a100c2b --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3936Test.java @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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 com.github.javaparser.ast.body.VariableDeclarator; +import com.github.javaparser.ast.expr.TextBlockLiteralExpr; +import org.junit.jupiter.api.Test; + +public class Issue3936Test extends AbstractLexicalPreservingTest { + static final String given = "package some.project;\n" + + "\n" + + "import java.util.Optional;\n" + + "\n" + + "public class SomeClass {\n" + + "\n" + + " String html = \"\" + \"\\n\"\n" + + " + \"\\t\\n\"\n" + + " + \"\\t\\t\\n\"\n" + + " + \"\\t\\n\"\n" + + " + \"\\t\\n\"\n" + + " + \"\\t\\t

Hello, world

\\n\"\n" + + " + \"\\t\\n\"\n" + + " + \"\\n\";\n" + + "}"; + + @Test + void test() { + considerCode(given); + + String newText = "\tfirstRow\n\tsecondRow\n\tthirdRow"; + + LexicalPreservingPrinter.setup(cu); + + VariableDeclarator expr = cu.findFirst(VariableDeclarator.class).get(); + expr.setInitializer(new TextBlockLiteralExpr(newText)); + + String actual = LexicalPreservingPrinter.print(cu); + String expected ="package some.project;\n" + + "\n" + + "import java.util.Optional;\n" + + "\n" + + "public class SomeClass {\n" + + "\n" + + " String html = \"\"\"\n" + + "\tfirstRow\n" + + "\tsecondRow\n" + + "\tthirdRow\"\"\";\n" + + "}"; + assertEqualsStringIgnoringEol(expected, actual); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3937Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3937Test.java new file mode 100644 index 0000000..8632111 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3937Test.java @@ -0,0 +1,70 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.expr.LambdaExpr; +import com.github.javaparser.ast.expr.MethodCallExpr; +import com.github.javaparser.ast.expr.NameExpr; +import com.github.javaparser.ast.stmt.ExpressionStmt; + +public class Issue3937Test extends AbstractLexicalPreservingTest { + static final String given = "package custom.project;\n" + "\n" + + "import java.util.stream.Stream;\n" + + "\n" + + "class TestFileSystemCodeProvider {\n" + + " void testInMemoryFileSystem() {\n" + + "\n" + + " Stream.of(\"\").listFilesForContent(file -> {\n" + + " System.out.println(s);\n" + + " });\n" + + " }\n" + + "}\n" + + ""; + + @Test + void test() { + considerCode(given); + + LexicalPreservingPrinter.setup(cu); + + LambdaExpr lambdaExpr = cu.findFirst(LambdaExpr.class).get(); + lambdaExpr.setBody(new ExpressionStmt(new MethodCallExpr(new NameExpr("SomeClass"), "someMethod"))); + + String actual = LexicalPreservingPrinter.print(cu); + String expected = "package custom.project;\n" + + "\n" + + "import java.util.stream.Stream;\n" + + "\n" + + "class TestFileSystemCodeProvider {\n" + + " void testInMemoryFileSystem() {\n" + + "\n" + + " Stream.of(\"\").listFilesForContent(file -> SomeClass.someMethod());\n" + + " }\n" + + "}\n" + + ""; + assertEqualsStringIgnoringEol(expected, actual); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3949Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3949Test.java new file mode 100644 index 0000000..21c3055 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue3949Test.java @@ -0,0 +1,68 @@ +/* + * Copyright (C) 2013-2024 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.expr.LambdaExpr; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.ast.stmt.BreakStmt; +import com.github.javaparser.ast.stmt.ExpressionStmt; + +class Issue3949Test extends AbstractLexicalPreservingTest { + + @Test + public void test() { + considerCode( + "class A {\n" + + "\n" + + " void foo() {\n" + + " Consumer lambda = a -> System.out.println(a);\n" + + " }\n" + + "}"); + + ExpressionStmt estmt = cu.findAll(ExpressionStmt.class).get(1).clone(); + LambdaExpr lexpr = cu.findAll(LambdaExpr.class).get(0); + LexicalPreservingPrinter.setup(cu); + + BlockStmt block = new BlockStmt(); + BreakStmt bstmt = new BreakStmt(); + block.addStatement(new ExpressionStmt(estmt.getExpression())); + block.addStatement(bstmt); + lexpr.setBody(block); + + String expected = + "class A {\n" + + "\n" + + " void foo() {\n" + + " Consumer lambda = a -> {\n" + + " System.out.println(a);\n" + + " break;\n" + + " };\n" + + " }\n" + + "}"; + + assertEqualsStringIgnoringEol(expected, LexicalPreservingPrinter.print(cu)); + } + +} 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 0000000..fc55d0b --- /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-2024 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 0000000..939b8c0 --- /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-2024 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/Issue4245Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue4245Test.java new file mode 100644 index 0000000..717666a --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/Issue4245Test.java @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2013-2024 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.ParserConfiguration; +import com.github.javaparser.StaticJavaParser; +import com.github.javaparser.ParserConfiguration.LanguageLevel; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.expr.LambdaExpr; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.ast.stmt.BreakStmt; +import com.github.javaparser.ast.stmt.ExpressionStmt; + +class Issue4245Test extends AbstractLexicalPreservingTest { + + @Test + public void test() { + + ParserConfiguration parserConfiguration = new ParserConfiguration(); + parserConfiguration.setLanguageLevel(LanguageLevel.JAVA_17); + StaticJavaParser.setConfiguration(parserConfiguration); + considerCode( + "public sealed interface IUpdatePortCommand permits UpdateScheduleCommand, UpdateStateCommand {}"); + + ClassOrInterfaceDeclaration classOrInterface = cu.findFirst(ClassOrInterfaceDeclaration.class).get(); + classOrInterface.setModifiers(); + + String expected = + "interface IUpdatePortCommand permits UpdateScheduleCommand, UpdateStateCommand {}"; + + assertEqualsStringIgnoringEol(expected, LexicalPreservingPrinter.print(cu)); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/LexicalDifferenceCalculatorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/LexicalDifferenceCalculatorTest.java new file mode 100644 index 0000000..9ef843e --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/LexicalDifferenceCalculatorTest.java @@ -0,0 +1,327 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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 com.github.javaparser.GeneratedJavaParserConstants; +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.PackageDeclaration; +import com.github.javaparser.ast.body.AnnotationDeclaration; +import com.github.javaparser.ast.body.EnumConstantDeclaration; +import com.github.javaparser.ast.body.EnumDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.comments.JavadocComment; +import com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.observer.ObservableProperty; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.ast.stmt.ExpressionStmt; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.printer.ConcreteSyntaxModel; +import com.github.javaparser.printer.concretesyntaxmodel.CsmElement; +import com.github.javaparser.printer.concretesyntaxmodel.CsmToken; +import com.github.javaparser.printer.lexicalpreservation.LexicalDifferenceCalculator.CsmChild; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.util.List; + +import static com.github.javaparser.TokenTypes.eolTokenKind; +import static com.github.javaparser.TokenTypes.spaceTokenKind; +import static com.github.javaparser.ast.Modifier.Keyword.PUBLIC; +import static com.github.javaparser.ast.Modifier.createModifierList; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class LexicalDifferenceCalculatorTest extends AbstractLexicalPreservingTest { + + @Test + void compilationUnitExampleOriginal() { + considerCode("class A {}"); + CsmElement element = ConcreteSyntaxModel.forClass(cu.getClass()); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmOriginal = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(element, cu); + assertEquals(2, csmOriginal.elements.size()); + assertEquals(new CsmChild(cu.getType(0)), csmOriginal.elements.get(0)); + assertEquals(new CsmToken(eolTokenKind()), csmOriginal.elements.get(1)); + } + + @Test + void compilationUnitExampleWithPackageSet() { + considerCode("class A {}"); + CsmElement element = ConcreteSyntaxModel.forClass(cu.getClass()); + PackageDeclaration packageDeclaration = new PackageDeclaration(new Name(new Name("foo"), "bar")); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmChanged = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterPropertyChange(element, cu, ObservableProperty.PACKAGE_DECLARATION, null, packageDeclaration); + assertEquals(3, csmChanged.elements.size()); + assertEquals(new CsmChild(packageDeclaration), csmChanged.elements.get(0)); + assertEquals(new CsmChild(cu.getType(0)), csmChanged.elements.get(1)); + assertEquals(new CsmToken(eolTokenKind()), csmChanged.elements.get(2)); + } + + @Test + void annotationDeclarationModifiersExampleOriginal() throws IOException { + considerExample("AnnotationDeclaration_Example1_original"); + AnnotationDeclaration annotationDeclaration = (AnnotationDeclaration)cu.getType(0); + CsmElement element = ConcreteSyntaxModel.forClass(annotationDeclaration.getClass()); + LexicalDifferenceCalculator.CalculatedSyntaxModel csm = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(element, annotationDeclaration); + csm.removeIndentationElements(); + int i = 0; + assertEquals(new CsmToken(GeneratedJavaParserConstants.AT), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.INTERFACE), csm.elements.get(i++)); + assertEquals(new CsmToken(spaceTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getName()), csm.elements.get(i++)); + assertEquals(new CsmToken(spaceTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.LBRACE), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getMember(0)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getMember(1)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getMember(2)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getMember(3)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getMember(4)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getMember(5)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.RBRACE), csm.elements.get(i++)); + assertEquals(i, csm.elements.size()); + } + + @Test + void annotationDeclarationModifiersExampleModified() throws IOException { + considerExample("AnnotationDeclaration_Example1_original"); + AnnotationDeclaration annotationDeclaration = (AnnotationDeclaration)cu.getType(0); + CsmElement element = ConcreteSyntaxModel.forClass(annotationDeclaration.getClass()); + LexicalDifferenceCalculator.CalculatedSyntaxModel csm = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterPropertyChange(element, annotationDeclaration, ObservableProperty.MODIFIERS, new NodeList<>(), createModifierList(PUBLIC)); + csm.removeIndentationElements(); + int i = 0; + assertEquals(new CsmChild(Modifier.publicModifier()), csm.elements.get(i++)); + assertEquals(new CsmToken(spaceTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.AT), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.INTERFACE), csm.elements.get(i++)); + assertEquals(new CsmToken(spaceTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getName()), csm.elements.get(i++)); + assertEquals(new CsmToken(spaceTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.LBRACE), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getMember(0)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getMember(1)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getMember(2)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getMember(3)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getMember(4)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getMember(5)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.RBRACE), csm.elements.get(i++)); + assertEquals(i, csm.elements.size()); + } + + @Test + void annotationDeclarationNameExampleModified() throws IOException { + considerExample("AnnotationDeclaration_Example1_original"); + AnnotationDeclaration annotationDeclaration = (AnnotationDeclaration)cu.getType(0); + CsmElement element = ConcreteSyntaxModel.forClass(annotationDeclaration.getClass()); + SimpleName newName = new SimpleName("NewName"); + LexicalDifferenceCalculator.CalculatedSyntaxModel csm = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterPropertyChange(element, annotationDeclaration, ObservableProperty.NAME, + annotationDeclaration.getName(), newName); + csm.removeIndentationElements(); + int i = 0; + assertEquals(new CsmToken(GeneratedJavaParserConstants.AT), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.INTERFACE), csm.elements.get(i++)); + assertEquals(new CsmToken(spaceTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(newName), csm.elements.get(i++)); + assertEquals(new CsmToken(spaceTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.LBRACE), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getMember(0)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getMember(1)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getMember(2)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getMember(3)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getMember(4)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getMember(5)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.RBRACE), csm.elements.get(i++)); + assertEquals(i, csm.elements.size()); + } + + @Test + void annotationDeclarationJavadocExampleOriginal() throws IOException { + considerExample("AnnotationDeclaration_Example3_original"); + AnnotationDeclaration annotationDeclaration = (AnnotationDeclaration)cu.getType(0); + CsmElement element = ConcreteSyntaxModel.forClass(annotationDeclaration.getClass()); + LexicalDifferenceCalculator.CalculatedSyntaxModel csm = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(element, annotationDeclaration); + csm.removeIndentationElements(); + int i = 0; + assertEquals(new CsmChild(Modifier.publicModifier()), csm.elements.get(i++)); + assertEquals(new CsmToken(spaceTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.AT), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.INTERFACE), csm.elements.get(i++)); + assertEquals(new CsmToken(spaceTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getName()), csm.elements.get(i++)); + assertEquals(new CsmToken(spaceTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.LBRACE), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getMember(0)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getMember(1)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getMember(2)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getMember(3)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getMember(4)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getMember(5)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.RBRACE), csm.elements.get(i++)); + assertEquals(i, csm.elements.size()); + } + + @Test + void annotationDeclarationJavadocExampleAddingJavadoc() throws IOException { + considerExample("AnnotationDeclaration_Example3_original"); + AnnotationDeclaration annotationDeclaration = (AnnotationDeclaration)cu.getType(0); + CsmElement element = ConcreteSyntaxModel.forClass(annotationDeclaration.getClass()); + JavadocComment comment = new JavadocComment("Cool this annotation!"); + LexicalDifferenceCalculator.CalculatedSyntaxModel csm = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterPropertyChange(element, annotationDeclaration, ObservableProperty.COMMENT, null, comment); + csm.removeIndentationElements(); + int i = 0; + assertEquals(new CsmChild(Modifier.publicModifier()), csm.elements.get(i++)); + assertEquals(new CsmToken(spaceTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.AT), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.INTERFACE), csm.elements.get(i++)); + assertEquals(new CsmToken(spaceTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getName()), csm.elements.get(i++)); + assertEquals(new CsmToken(spaceTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.LBRACE), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getMember(0)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getMember(1)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getMember(2)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getMember(3)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getMember(4)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmChild(annotationDeclaration.getMember(5)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.RBRACE), csm.elements.get(i++)); + assertEquals(i, csm.elements.size()); + } + + @Test + void simpleEnumConstantDeclaration() { + EnumConstantDeclaration ecd = considerEcd("A"); + LexicalDifferenceCalculator.CalculatedSyntaxModel csm = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(ecd); + + int i = 0; + assertEquals(new CsmChild(ecd.getName()), csm.elements.get(i++)); + assertEquals(i, csm.elements.size()); + } + + @Test + void csmModelAfterAddingStatementToEmptyBlock() throws IOException { + LexicalDifferenceCalculator ldc = new LexicalDifferenceCalculator(); + considerExample("ASimpleClassWithMoreFormatting_step3"); + + MethodDeclaration setter = cu.getClassByName("MyRenamedClass").get() + .getMethodsByName("setAField").get(0); + Statement assignStatement = new ExpressionStmt( + new AssignExpr( + new FieldAccessExpr(new ThisExpr(),"aField"), + new NameExpr("aField"), + AssignExpr.Operator.ASSIGN + )); + LexicalDifferenceCalculator.CalculatedSyntaxModel calculatedSyntaxModel = + ldc.calculatedSyntaxModelAfterListAddition( + ConcreteSyntaxModel.forClass(BlockStmt.class), + ObservableProperty.STATEMENTS, + setter.getBody().get().getStatements(), + 0, + assignStatement); + int index = 0; + assertEquals(CsmElement.token(GeneratedJavaParserConstants.LBRACE), calculatedSyntaxModel.elements.get(index++)); + assertEquals(CsmElement.newline(), calculatedSyntaxModel.elements.get(index++)); + assertEquals(CsmElement.indent(), calculatedSyntaxModel.elements.get(index++)); + assertTrue(isChild(calculatedSyntaxModel.elements.get(index++), ExpressionStmt.class)); + assertEquals(CsmElement.newline(), calculatedSyntaxModel.elements.get(index++)); + assertEquals(CsmElement.unindent(), calculatedSyntaxModel.elements.get(index++)); + assertEquals(CsmElement.token(GeneratedJavaParserConstants.RBRACE), calculatedSyntaxModel.elements.get(index++)); + assertEquals(index, calculatedSyntaxModel.elements.size()); + } + + @Test + void differenceAfterddingStatementToEmptyBlock() throws IOException { + LexicalDifferenceCalculator ldc = new LexicalDifferenceCalculator(); + considerExample("ASimpleClassWithMoreFormatting_step3"); + + MethodDeclaration setter = cu.getClassByName("MyRenamedClass").get() + .getMethodsByName("setAField").get(0); + Statement assignStatement = new ExpressionStmt( + new AssignExpr( + new FieldAccessExpr(new ThisExpr(),"aField"), + new NameExpr("aField"), + AssignExpr.Operator.ASSIGN + )); + List differenceElements = ldc.calculateListAdditionDifference( + ObservableProperty.STATEMENTS, + setter.getBody().get().getStatements(), + 0, + assignStatement); + int index = 0; + assertEquals(DifferenceElement.kept(CsmElement.token(GeneratedJavaParserConstants.LBRACE)), differenceElements.get(index++)); + assertEquals(DifferenceElement.kept(CsmElement.newline()), differenceElements.get(index++)); + assertEquals(DifferenceElement.added(CsmElement.indent()), differenceElements.get(index++)); + assertTrue(isAddedChild(differenceElements.get(index++), ExpressionStmt.class)); + CsmElement cmsElement = differenceElements.get(index++).getElement(); + // all end of line tokens are not equal so it's safer to check if it's a token and then a end of line token + assertTrue(CsmToken.class.isAssignableFrom(cmsElement.getClass()) && ((CsmToken)cmsElement).isNewLine()); + assertEquals(DifferenceElement.added(CsmElement.unindent()), differenceElements.get(index++)); + assertEquals(DifferenceElement.kept(CsmElement.token(GeneratedJavaParserConstants.RBRACE)), differenceElements.get(index++)); + assertEquals(index, differenceElements.size()); + } + + private boolean isAddedChild(DifferenceElement element, Class childClass) { + return element.isAdded() && isChild(element.getElement(), childClass); + } + + private boolean isChild(CsmElement element, Class childClass) { + return element instanceof CsmChild && childClass.isInstance(((CsmChild)element).getChild()); + } + + protected EnumConstantDeclaration considerEcd(String code) { + considerCode("enum A { " + code + " }"); + return ((EnumDeclaration)cu.getType(0)).getEntries().get(0); + } +} 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 new file mode 100644 index 0000000..f8dd5e3 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinterTest.java @@ -0,0 +1,1858 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.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.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import org.junit.jupiter.api.Test; + +import com.github.javaparser.GeneratedJavaParserConstants; +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.StaticJavaParser; +import com.github.javaparser.ast.*; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.comments.LineComment; +import com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.stmt.*; +import com.github.javaparser.ast.type.Type; +import com.github.javaparser.ast.type.UnionType; +import com.github.javaparser.ast.type.VoidType; +import com.github.javaparser.ast.visitor.ModifierVisitor; +import com.github.javaparser.ast.visitor.Visitable; +import com.github.javaparser.utils.TestUtils; + +class LexicalPreservingPrinterTest extends AbstractLexicalPreservingTest { + private NodeText getTextForNode(Node node) { + return node.getData(NODE_TEXT_DATA); + } + + // + // Tests on TextNode definition + // + + @Test + void checkNodeTextCreatedForSimplestClass() { + considerCode("class A {}"); + + // CU + assertEquals(1, getTextForNode(cu).numberOfElements()); + assertTrue(getTextForNode(cu).getTextElement(0) instanceof ChildTextElement); + assertEquals(cu.getClassByName("A").get(), + ((ChildTextElement) getTextForNode(cu).getTextElement(0)).getChild()); + + // Class + ClassOrInterfaceDeclaration classA = cu.getClassByName("A").get(); + assertEquals(7, getTextForNode(classA).numberOfElements()); + assertEquals("class", getTextForNode(classA).getTextElement(0).expand()); + assertEquals(" ", getTextForNode(classA).getTextElement(1).expand()); + assertEquals("A", getTextForNode(classA).getTextElement(2).expand()); + assertEquals(" ", getTextForNode(classA).getTextElement(3).expand()); + assertEquals("{", getTextForNode(classA).getTextElement(4).expand()); + assertEquals("}", getTextForNode(classA).getTextElement(5).expand()); + assertEquals("", getTextForNode(classA).getTextElement(6).expand()); + assertTrue(getTextForNode(classA).getTextElement(6) instanceof TokenTextElement); + assertEquals(GeneratedJavaParserConstants.EOF, + ((TokenTextElement) getTextForNode(classA).getTextElement(6)).getTokenKind()); + } + + @Test + void checkNodeTextCreatedForField() { + String code = "class A {int i;}"; + considerCode(code); + + ClassOrInterfaceDeclaration classA = cu.getClassByName("A").get(); + FieldDeclaration fd = classA.getFieldByName("i").get(); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(fd); + assertEquals(Arrays.asList("int", " ", "i", ";"), + nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); + } + + @Test + void checkNodeTextCreatedForVariableDeclarator() { + String code = "class A {int i;}"; + considerCode(code); + + ClassOrInterfaceDeclaration classA = cu.getClassByName("A").get(); + FieldDeclaration fd = classA.getFieldByName("i").get(); + VariableDeclarator vd = fd.getVariables().get(0); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(vd); + assertEquals(Arrays.asList("i"), + nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); + } + + @Test + void checkNodeTextCreatedForMethod() { + String code = "class A {void foo(int p1, float p2) { }}"; + considerCode(code); + + ClassOrInterfaceDeclaration classA = cu.getClassByName("A").get(); + MethodDeclaration md = classA.getMethodsByName("foo").get(0); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(md); + assertEquals(Arrays.asList("void", " ", "foo", "(", "int p1", ",", " ", "float p2", ")", " ", "{ }"), + nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); + } + + @Test + void checkNodeTextCreatedForMethodParameter() { + String code = "class A {void foo(int p1, float p2) { }}"; + considerCode(code); + + ClassOrInterfaceDeclaration classA = cu.getClassByName("A").get(); + MethodDeclaration md = classA.getMethodsByName("foo").get(0); + Parameter p1 = md.getParameterByName("p1").get(); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(p1); + assertEquals(Arrays.asList("int", " ", "p1"), + nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); + } + + @Test + void checkNodeTextCreatedForPrimitiveType() { + String code = "class A {void foo(int p1, float p2) { }}"; + considerCode(code); + + ClassOrInterfaceDeclaration classA = cu.getClassByName("A").get(); + MethodDeclaration md = classA.getMethodsByName("foo").get(0); + Parameter p1 = md.getParameterByName("p1").get(); + Type t = p1.getType(); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(t); + assertEquals(Arrays.asList("int"), + nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); + } + + @Test + void checkNodeTextCreatedForSimpleImport() { + String code = "import a.b.c.D;"; + considerCode(code); + + ImportDeclaration imp = (ImportDeclaration) cu.getChildNodes().get(0); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(imp); + assertEquals(Arrays.asList("import", " ", "a.b.c.D", ";", ""), + nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); + } + + @Test + void addedImportShouldBePrependedWithEOL() { + considerCode("import a.A;" + SYSTEM_EOL + "class X{}"); + + cu.addImport("a.B"); + + assertEqualsStringIgnoringEol("import a.A;\nimport a.B;\nclass X{}", LexicalPreservingPrinter.print(cu)); + } + + @Test + void checkNodeTextCreatedGenericType() { + String code = "class A {ParseResult result;}"; + considerCode(code); + + FieldDeclaration field = cu.getClassByName("A").get().getFieldByName("result").get(); + Node t = field.getCommonType(); + Node t2 = field.getVariable(0).getType(); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(field); + assertEquals(Arrays.asList("ParseResult", "<", "T", ">", " ", "result", ";"), + nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); + } + + @Test + void checkNodeTextCreatedAnnotationDeclaration() { + String code = "public @interface ClassPreamble { String author(); }"; + considerCode(code); + + AnnotationDeclaration ad = cu.getAnnotationDeclarationByName("ClassPreamble").get(); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(ad); + assertEquals( + Arrays.asList("public", " ", "@", "interface", " ", "ClassPreamble", " ", "{", " ", "String author();", + " ", "}", ""), + nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); + } + + @Test + void checkNodeTextCreatedAnnotationMemberDeclaration() { + String code = "public @interface ClassPreamble { String author(); }"; + considerCode(code); + + AnnotationDeclaration ad = cu.getAnnotationDeclarationByName("ClassPreamble").get(); + AnnotationMemberDeclaration md = (AnnotationMemberDeclaration) ad.getMember(0); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(md); + assertEquals(Arrays.asList("String", " ", "author", "(", ")", ";"), + nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); + } + + @Test + void checkNodeTextCreatedAnnotationMemberDeclarationWithArrayType() { + String code = "public @interface ClassPreamble { String[] author(); }"; + considerCode(code); + + AnnotationDeclaration ad = cu.getAnnotationDeclarationByName("ClassPreamble").get(); + AnnotationMemberDeclaration md = (AnnotationMemberDeclaration) ad.getMember(0); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(md); + assertEquals(Arrays.asList("String[]", " ", "author", "(", ")", ";"), + nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); + } + + @Test + void checkNodeTextCreatedAnnotationMemberDeclarationArrayType() { + String code = "public @interface ClassPreamble { String[] author(); }"; + considerCode(code); + + AnnotationDeclaration ad = cu.getAnnotationDeclarationByName("ClassPreamble").get(); + AnnotationMemberDeclaration md = ad.getMember(0).asAnnotationMemberDeclaration(); + Type type = md.getType(); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(type); + assertEquals(Arrays.asList("String", "[", "]"), + nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); + } + + @Test + void checkNodeTextCreatedAnnotationMemberDeclarationWithComment() throws IOException { + considerExample("AnnotationDeclaration_Example3_original"); + + AnnotationMemberDeclaration md = cu.getAnnotationDeclarationByName("ClassPreamble").get().getMember(5) + .asAnnotationMemberDeclaration(); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(md); + assertEquals(Arrays.asList("String[]", " ", "reviewers", "(", ")", ";"), + nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); + } + + @Test + void checkNodeTextCreatedArrayCreationLevelWithoutExpression() { + considerExpression("new int[]"); + + ArrayCreationExpr arrayCreationExpr = expression.asArrayCreationExpr(); + ArrayCreationLevel arrayCreationLevel = arrayCreationExpr.getLevels().get(0); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(arrayCreationLevel); + assertEquals(Arrays.asList("[", "]"), + nodeText.getElements().stream().map(TextElement::expand).filter(e -> !e.isEmpty()) + .collect(Collectors.toList())); + } + + @Test + void checkNodeTextCreatedArrayCreationLevelWith() { + considerExpression("new int[123]"); + + ArrayCreationExpr arrayCreationExpr = expression.asArrayCreationExpr(); + ArrayCreationLevel arrayCreationLevel = arrayCreationExpr.getLevels().get(0); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(arrayCreationLevel); + assertEquals(Arrays.asList("[", "123", "]"), + nodeText.getElements().stream().map(TextElement::expand).filter(e -> !e.isEmpty()) + .collect(Collectors.toList())); + } + + // + // Tests on findIndentation + // + + @Test + void findIndentationForAnnotationMemberDeclarationWithoutComment() throws IOException { + considerExample("AnnotationDeclaration_Example3_original"); + Node node = cu.getAnnotationDeclarationByName("ClassPreamble").get().getMember(4); + List indentation = LexicalPreservingPrinter.findIndentation(node); + assertEquals(Arrays.asList(" ", " ", " "), + indentation.stream().map(TextElement::expand).collect(Collectors.toList())); + } + + @Test + void findIndentationForAnnotationMemberDeclarationWithComment() throws IOException { + considerExample("AnnotationDeclaration_Example3_original"); + Node node = cu.getAnnotationDeclarationByName("ClassPreamble").get().getMember(5); + List indentation = LexicalPreservingPrinter.findIndentation(node); + assertEquals(Arrays.asList(" ", " ", " "), + indentation.stream().map(TextElement::expand).collect(Collectors.toList())); + } + + // + // Tests on printing + // + + @Test + void printASuperSimpleCUWithoutChanges() { + String code = "class A {}"; + considerCode(code); + + assertEquals(code, LexicalPreservingPrinter.print(cu)); + } + + @Test + void printASuperSimpleClassWithAFieldAdded() { + String code = "class A {}"; + considerCode(code); + + ClassOrInterfaceDeclaration classA = cu.getClassByName("A").get(); + classA.addField("int", "myField"); + assertEquals("class A {" + SYSTEM_EOL + " int myField;" + SYSTEM_EOL + "}", LexicalPreservingPrinter.print(classA)); + } + + @Test + void printASuperSimpleClassWithoutChanges() { + String code = "class A {}"; + considerCode(code); + + assertEquals(code, LexicalPreservingPrinter.print(cu.getClassByName("A").get())); + } + + @Test + void printASimpleCUWithoutChanges() { + String code = "class /*a comment*/ A {\t\t" + SYSTEM_EOL + " int f;" + SYSTEM_EOL + SYSTEM_EOL + SYSTEM_EOL + + " void foo(int p ) { return 'z' \t; }}"; + considerCode(code); + + assertEquals(code, LexicalPreservingPrinter.print(cu)); + assertEquals(code, LexicalPreservingPrinter.print(cu.getClassByName("A").get())); + assertEquals("void foo(int p ) { return 'z' \t; }", + LexicalPreservingPrinter.print(cu.getClassByName("A").get().getMethodsByName("foo").get(0))); + } + + @Test + void printASimpleClassRemovingAField() { + String code = "class /*a comment*/ A {\t\t" + SYSTEM_EOL + + " int f;" + SYSTEM_EOL + SYSTEM_EOL + SYSTEM_EOL + + " void foo(int p ) { return 'z' \t; }}"; + considerCode(code); + + ClassOrInterfaceDeclaration c = cu.getClassByName("A").get(); + c.getMembers().remove(0); + // This rendering is probably caused by the concret syntax model + assertEquals("class /*a comment*/ A {\t\t" + SYSTEM_EOL + + SYSTEM_EOL + + " void foo(int p ) { return 'z' \t; }}", LexicalPreservingPrinter.print(c)); + } + + @Test + void printASimpleClassRemovingAMethod() { + String code = "class /*a comment*/ A {\t\t" + SYSTEM_EOL + + " int f;" + SYSTEM_EOL + SYSTEM_EOL + SYSTEM_EOL + + " void foo(int p ) { return 'z' \t; }" + SYSTEM_EOL + + " int g;}"; + considerCode(code); + + ClassOrInterfaceDeclaration c = cu.getClassByName("A").get(); + c.getMembers().remove(1); + assertEquals("class /*a comment*/ A {\t\t" + SYSTEM_EOL + + " int f;" + SYSTEM_EOL + SYSTEM_EOL + SYSTEM_EOL + + " int g;}", LexicalPreservingPrinter.print(c)); + } + + @Test + void printASimpleMethodAddingAParameterToAMethodWithZeroParameters() { + String code = "class A { void foo() {} }"; + considerCode(code); + + MethodDeclaration m = cu.getClassByName("A").get().getMethodsByName("foo").get(0); + m.addParameter("float", "p1"); + assertEquals("void foo(float p1) {}", LexicalPreservingPrinter.print(m)); + } + + @Test + void printASimpleMethodAddingAParameterToAMethodWithOneParameter() { + String code = "class A { void foo(char p1) {} }"; + considerCode(code); + + MethodDeclaration m = cu.getClassByName("A").get().getMethodsByName("foo").get(0); + m.addParameter("float", "p2"); + assertEquals("void foo(char p1, float p2) {}", LexicalPreservingPrinter.print(m)); + } + + @Test + void printASimpleMethodRemovingAParameterToAMethodWithOneParameter() { + String code = "class A { void foo(float p1) {} }"; + considerCode(code); + + MethodDeclaration m = cu.getClassByName("A").get().getMethodsByName("foo").get(0); + m.getParameters().remove(0); + assertEquals("void foo() {}", LexicalPreservingPrinter.print(m)); + } + + @Test + void printASimpleMethodRemovingParameterOneFromMethodWithTwoParameters() { + String code = "class A { void foo(char p1, int p2) {} }"; + considerCode(code); + + MethodDeclaration m = cu.getClassByName("A").get().getMethodsByName("foo").get(0); + m.getParameters().remove(0); + assertEquals("void foo(int p2) {}", LexicalPreservingPrinter.print(m)); + } + + @Test + void printASimpleMethodRemovingParameterTwoFromMethodWithTwoParameters() { + String code = "class A { void foo(char p1, int p2) {} }"; + considerCode(code); + + MethodDeclaration m = cu.getClassByName("A").get().getMethodsByName("foo").get(0); + m.getParameters().remove(1); + assertEquals("void foo(char p1) {}", LexicalPreservingPrinter.print(m)); + } + + @Test + void printASimpleMethodAddingAStatement() { + String code = "class A { void foo(char p1, int p2) {} }"; + considerCode(code); + + Statement s = new ExpressionStmt(new BinaryExpr( + new IntegerLiteralExpr("10"), new IntegerLiteralExpr("2"), BinaryExpr.Operator.PLUS)); + NodeList stmts = cu.getClassByName("A").get().getMethodsByName("foo").get(0).getBody().get() + .getStatements(); + stmts.add(s); + MethodDeclaration m = cu.getClassByName("A").get().getMethodsByName("foo").get(0); + assertEquals("void foo(char p1, int p2) {" + SYSTEM_EOL + + " 10 + 2;" + SYSTEM_EOL + + "}", LexicalPreservingPrinter.print(m)); + } + + @Test + void printASimpleMethodRemovingAStatementCRLF() { + printASimpleMethodRemovingAStatement("\r\n"); + } + + @Test + void printASimpleMethodRemovingAStatementLF() { + printASimpleMethodRemovingAStatement("\n"); + } + + @Test + void printASimpleMethodRemovingAStatementCR() { + printASimpleMethodRemovingAStatement("\r"); + } + + private void printASimpleMethodRemovingAStatement(String eol) { + considerCode("class A {" + eol + + "\t" + "foo(int a, int b) {" + eol + + "\t\t" + "int result = a * b;" + eol + + "\t\t" + "return a * b;" + eol + + "\t" + "}" + eol + + "}"); + + ExpressionStmt stmt = cu.findAll(ExpressionStmt.class).get(0); + stmt.remove(); + + assertEquals("class A {" + eol + + "\t" + "foo(int a, int b) {" + eol + + "\t\t" + "return a * b;" + eol + + "\t" + "}" + eol + + "}", LexicalPreservingPrinter.print(cu)); + } + + @Test + void printASimpleImport() { + String code = "import a.b.c.D;"; + considerCode(code); + + ImportDeclaration imp = (ImportDeclaration) cu.getChildNodes().get(0); + assertEquals("import a.b.c.D;", LexicalPreservingPrinter.print(imp)); + } + + @Test + void printAnotherImport() { + String code = "import com.github.javaparser.ast.CompilationUnit;"; + considerCode(code); + + ImportDeclaration imp = (ImportDeclaration) cu.getChildNodes().get(0); + assertEquals("import com.github.javaparser.ast.CompilationUnit;", LexicalPreservingPrinter.print(imp)); + } + + @Test + void printAStaticImport() { + String code = "import static com.github.javaparser.ParseStart.*;"; + considerCode(code); + + ImportDeclaration imp = (ImportDeclaration) cu.getChildNodes().get(0); + assertEquals("import static com.github.javaparser.ParseStart.*;", LexicalPreservingPrinter.print(imp)); + } + + @Test + void checkAnnidatedTypeParametersPrinting() { + String code = "class A { private final Stack> its = new Stack>(); }"; + considerCode(code); + assertEquals("class A { private final Stack> its = new Stack>(); }", + LexicalPreservingPrinter.print(cu)); + } + + @Test + void printASingleCatch() { + String code = "class A {{try { doit(); } catch (Exception e) {}}}"; + considerCode(code); + + assertEquals("class A {{try { doit(); } catch (Exception e) {}}}", LexicalPreservingPrinter.print(cu)); + } + + @Test + void printAMultiCatch() { + String code = "class A {{try { doit(); } catch (Exception | AssertionError e) {}}}"; + considerCode(code); + + assertEquals("class A {{try { doit(); } catch (Exception | AssertionError e) {}}}", + LexicalPreservingPrinter.print(cu)); + } + + @Test + void printASingleCatchType() { + String code = "class A {{try { doit(); } catch (Exception e) {}}}"; + considerCode(code); + InitializerDeclaration initializerDeclaration = (InitializerDeclaration) cu.getType(0).getMembers().get(0); + TryStmt tryStmt = (TryStmt) initializerDeclaration.getBody().getStatements().get(0); + CatchClause catchClause = tryStmt.getCatchClauses().get(0); + Type catchType = catchClause.getParameter().getType(); + + assertEquals("Exception", LexicalPreservingPrinter.print(catchType)); + } + + @Test + void printUnionType() { + String code = "class A {{try { doit(); } catch (Exception | AssertionError e) {}}}"; + considerCode(code); + InitializerDeclaration initializerDeclaration = (InitializerDeclaration) cu.getType(0).getMembers().get(0); + TryStmt tryStmt = (TryStmt) initializerDeclaration.getBody().getStatements().get(0); + CatchClause catchClause = tryStmt.getCatchClauses().get(0); + UnionType unionType = (UnionType) catchClause.getParameter().getType(); + + assertEquals("Exception | AssertionError", LexicalPreservingPrinter.print(unionType)); + } + + @Test + void printParameterHavingUnionType() { + String code = "class A {{try { doit(); } catch (Exception | AssertionError e) {}}}"; + considerCode(code); + InitializerDeclaration initializerDeclaration = (InitializerDeclaration) cu.getType(0).getMembers().get(0); + TryStmt tryStmt = (TryStmt) initializerDeclaration.getBody().getStatements().get(0); + CatchClause catchClause = tryStmt.getCatchClauses().get(0); + Parameter parameter = catchClause.getParameter(); + + assertEquals("Exception | AssertionError e", LexicalPreservingPrinter.print(parameter)); + } + + @Test + void printLambaWithUntypedParams() { + String code = "class A {Function f = a -> a;}"; + considerCode(code); + + assertEquals("class A {Function f = a -> a;}", LexicalPreservingPrinter.print(cu)); + } + + @Test + void printAModuleInfoSpecificKeywordUsedAsIdentifier1() { + considerCode("class module { }"); + + cu.getClassByName("module").get().setName("xyz"); + + assertEquals("class xyz { }", LexicalPreservingPrinter.print(cu)); + } + + @Test + void printAModuleInfoSpecificKeywordUsedAsIdentifier2() { + considerCode("class xyz { }"); + + cu.getClassByName("xyz").get().setName("module"); + + assertEquals("class module { }", LexicalPreservingPrinter.print(cu)); + } + + // Issue 823: setPackageDeclaration on CU starting with a comment + @Test + void reactToSetPackageDeclarationOnCuStartingWithComment() { + considerCode("// Hey, this is a comment\n" + + "\n" + + "\n" + + "// Another one\n" + + "\n" + + "class A {}"); + cu.setPackageDeclaration("org.javaparser.lexicalpreservation.examples"); + } + + @Test + void printLambdaIntersectionTypeAssignment() { + String code = "class A {" + SYSTEM_EOL + + " void f() {" + SYSTEM_EOL + + " Runnable r = (Runnable & Serializable) (() -> {});" + SYSTEM_EOL + + " r = (Runnable & Serializable)() -> {};" + SYSTEM_EOL + + " r = (Runnable & I)() -> {};" + SYSTEM_EOL + + " }}"; + considerCode(code); + + assertEquals(code, LexicalPreservingPrinter.print(cu)); + } + + @Test + void printLambdaIntersectionTypeReturn() { + String code = "class A {" + SYSTEM_EOL + + " Object f() {" + SYSTEM_EOL + + " return (Comparator> & Serializable)(c1, c2) -> c1.getKey().compareTo(c2.getKey()); " + + SYSTEM_EOL + + "}}"; + considerCode(code); + + assertEquals(code, LexicalPreservingPrinter.print(cu)); + } + + // See issue #855 + @Test + void handleOverrideAnnotation() { + considerCode("public class TestPage extends Page {" + SYSTEM_EOL + + SYSTEM_EOL + + " protected void test() {}" + SYSTEM_EOL + + SYSTEM_EOL + + " @Override" + SYSTEM_EOL + + " protected void initializePage() {}" + SYSTEM_EOL + + "}"); + + cu.getTypes() + .forEach(type -> type.getMembers() + .forEach(member -> { + if (member instanceof MethodDeclaration) { + MethodDeclaration methodDeclaration = (MethodDeclaration) member; + if (!methodDeclaration.getAnnotationByName("Override").isPresent()) { + methodDeclaration.addAnnotation("Override"); + } + } + })); + assertEquals("public class TestPage extends Page {" + SYSTEM_EOL + + SYSTEM_EOL + + " @Override" + SYSTEM_EOL + + " protected void test() {}" + SYSTEM_EOL + + SYSTEM_EOL + + " @Override" + SYSTEM_EOL + + " protected void initializePage() {}" + SYSTEM_EOL + + "}", LexicalPreservingPrinter.print(cu)); + } + + @Test + void preserveSpaceAsIsForASimpleClassWithMoreFormatting() throws IOException { + considerExample("ASimpleClassWithMoreFormatting"); + assertEquals(readExample("ASimpleClassWithMoreFormatting"), LexicalPreservingPrinter.print(cu)); + } + + @Test + void renameASimpleClassWithMoreFormatting() throws IOException { + considerExample("ASimpleClassWithMoreFormatting"); + + cu.getClassByName("ASimpleClass").get() + .setName("MyRenamedClass"); + assertEquals(readExample("ASimpleClassWithMoreFormatting_step1"), LexicalPreservingPrinter.print(cu)); + } + + @Test + void theLexicalPreservationStringForAnAddedMethodShouldBeIndented() throws IOException { + considerExample("ASimpleClassWithMoreFormatting"); + + cu.getClassByName("ASimpleClass").get() + .setName("MyRenamedClass"); + MethodDeclaration setter = cu + .getClassByName("MyRenamedClass").get() + .addMethod("setAField", PUBLIC); + assertEquals("public void setAField() {" + SYSTEM_EOL + + " }", LexicalPreservingPrinter.print(setter)); + } + + @Test + void addMethodToASimpleClassWithMoreFormatting() throws IOException { + considerExample("ASimpleClassWithMoreFormatting"); + + cu.getClassByName("ASimpleClass").get() + .setName("MyRenamedClass"); + MethodDeclaration setter = cu + .getClassByName("MyRenamedClass").get() + .addMethod("setAField", PUBLIC); + TestUtils.assertEqualsStringIgnoringEol(readExample("ASimpleClassWithMoreFormatting_step2"), LexicalPreservingPrinter.print(cu)); + } + + @Test + void addingParameterToAnAddedMethodInASimpleClassWithMoreFormatting() throws IOException { + considerExample("ASimpleClassWithMoreFormatting"); + + cu.getClassByName("ASimpleClass").get() + .setName("MyRenamedClass"); + MethodDeclaration setter = cu + .getClassByName("MyRenamedClass").get() + .addMethod("setAField", PUBLIC); + setter.addParameter("boolean", "aField"); + TestUtils.assertEqualsStringIgnoringEol(readExample("ASimpleClassWithMoreFormatting_step3"), LexicalPreservingPrinter.print(cu)); + } + + @Test + void findIndentationOfEmptyMethod() throws IOException { + considerExample("ASimpleClassWithMoreFormatting_step3"); + + MethodDeclaration setter = cu.getClassByName("MyRenamedClass").get() + .getMethodsByName("setAField").get(0); + assertEquals(4, LexicalPreservingPrinter.findIndentation(setter).size()); + assertEquals(4, LexicalPreservingPrinter.findIndentation(setter.getBody().get()).size()); + } + + @Test + void findIndentationOfMethodWithStatements() throws IOException { + considerExample("ASimpleClassWithMoreFormatting_step4"); + + MethodDeclaration setter = cu.getClassByName("MyRenamedClass").get() + .getMethodsByName("setAField").get(0); + assertEquals(4, LexicalPreservingPrinter.findIndentation(setter).size()); + assertEquals(4, LexicalPreservingPrinter.findIndentation(setter.getBody().get()).size()); + assertEquals(8, LexicalPreservingPrinter.findIndentation(setter.getBody().get().getStatement(0)).size()); + } + + @Test + void addingStatementToAnAddedMethodInASimpleClassWithMoreFormatting() throws IOException { + considerExample("ASimpleClassWithMoreFormatting"); + + cu.getClassByName("ASimpleClass").get() + .setName("MyRenamedClass"); + MethodDeclaration setter = cu + .getClassByName("MyRenamedClass").get() + .addMethod("setAField", PUBLIC); + setter.addParameter("boolean", "aField"); + setter.getBody().get().getStatements().add(new ExpressionStmt( + new AssignExpr( + new FieldAccessExpr(new ThisExpr(), "aField"), + new NameExpr("aField"), + AssignExpr.Operator.ASSIGN))); + TestUtils.assertEqualsStringIgnoringEol(readExample("ASimpleClassWithMoreFormatting_step4"), LexicalPreservingPrinter.print(cu)); + } + + @Test + void addingStatementToAnAddedMethodInASimpleClassWithMoreFormattingFromStep3() throws IOException { + considerExample("ASimpleClassWithMoreFormatting_step3"); + + MethodDeclaration setter = cu.getClassByName("MyRenamedClass").get() + .getMethodsByName("setAField").get(0); + setter.getBody().get().getStatements().add(new ExpressionStmt( + new AssignExpr( + new FieldAccessExpr(new ThisExpr(), "aField"), + new NameExpr("aField"), + AssignExpr.Operator.ASSIGN))); + assertEquals(readExample("ASimpleClassWithMoreFormatting_step4"), LexicalPreservingPrinter.print(cu)); + } + + @Test + void nodeTextForMethod() throws IOException { + considerExample("ASimpleClassWithMoreFormatting_step4"); + + MethodDeclaration setter = cu.getClassByName("MyRenamedClass").get() + .getMethodsByName("setAField").get(0); + NodeText nodeText; + + nodeText = getTextForNode(setter); + int index = 0; + assertTrue(nodeText.getElements().get(index++).isChildOfClass(Modifier.class)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isChildOfClass(VoidType.class)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isChildOfClass(SimpleName.class)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.LPAREN)); + assertTrue(nodeText.getElements().get(index++).isChildOfClass(Parameter.class)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.RPAREN)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isChildOfClass(BlockStmt.class)); + assertEquals(index, nodeText.getElements().size()); + + nodeText = getTextForNode(setter.getBody().get()); + index = 0; + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.LBRACE)); + assertTrue(nodeText.getElements().get(index++).isNewline()); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isChildOfClass(ExpressionStmt.class)); + assertTrue(nodeText.getElements().get(index++).isNewline()); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.RBRACE)); + assertEquals(index, nodeText.getElements().size()); + + nodeText = getTextForNode(setter.getBody().get().getStatement(0)); + index = 0; + assertTrue(nodeText.getElements().get(index++).isChildOfClass(AssignExpr.class)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SEMICOLON)); + assertEquals(index, nodeText.getElements().size()); + } + + @Test + void nodeTextForModifiedMethod() throws IOException { + considerExample("ASimpleClassWithMoreFormatting_step3"); + + MethodDeclaration setter = cu.getClassByName("MyRenamedClass").get() + .getMethodsByName("setAField").get(0); + setter.getBody().get().getStatements().add(new ExpressionStmt( + new AssignExpr( + new FieldAccessExpr(new ThisExpr(), "aField"), + new NameExpr("aField"), + AssignExpr.Operator.ASSIGN))); + NodeText nodeText; + + nodeText = getTextForNode(setter); + int index = 0; + assertTrue(nodeText.getElements().get(index++).isChildOfClass(Modifier.class)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isChildOfClass(VoidType.class)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isChildOfClass(SimpleName.class)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.LPAREN)); + assertTrue(nodeText.getElements().get(index++).isChildOfClass(Parameter.class)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.RPAREN)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isChildOfClass(BlockStmt.class)); + assertEquals(index, nodeText.getElements().size()); + + nodeText = getTextForNode(setter.getBody().get()); + index = 0; + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.LBRACE)); + assertTrue(nodeText.getElements().get(index++).isNewline()); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isChildOfClass(ExpressionStmt.class)); + assertTrue(nodeText.getElements().get(index++).isNewline()); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.RBRACE)); + assertEquals(index, nodeText.getElements().size()); + + nodeText = LexicalPreservingPrinter.getOrCreateNodeText(setter.getBody().get().getStatement(0)); + index = 0; + assertTrue(nodeText.getElements().get(index++).isChildOfClass(AssignExpr.class)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SEMICOLON)); + assertEquals(index, nodeText.getElements().size()); + } + + // See issue #926 + @Test + void addASecondStatementToExistingMethod() throws IOException { + considerExample("MethodWithOneStatement"); + + MethodDeclaration methodDeclaration = cu.getType(0).getMethodsByName("someMethod").get(0); + methodDeclaration.getBody().get().getStatements().add(new ExpressionStmt( + new VariableDeclarationExpr( + new VariableDeclarator( + parseClassOrInterfaceType("String"), + "test2", + new StringLiteralExpr(""))))); + TestUtils.assertEqualsStringIgnoringEol("public void someMethod() {" + SYSTEM_EOL + + " String test = \"\";" + SYSTEM_EOL + + " String test2 = \"\";" + SYSTEM_EOL + // HACK: The right closing brace should not have indentation + // because the original method did not introduce indentation, + // however due to necessity this test was left with indentation, + // in a later version it should be revised. + + " }", LexicalPreservingPrinter.print(methodDeclaration)); + } + + // See issue #866 + @Test + void moveOverrideAnnotations() { + considerCode("public class TestPage extends Page {" + SYSTEM_EOL + + SYSTEM_EOL + + " protected void test() {}" + SYSTEM_EOL + + SYSTEM_EOL + + " protected @Override void initializePage() {}" + SYSTEM_EOL + + "}"); + + cu.getTypes() + .forEach(type -> type.getMembers() + .forEach(member -> member.ifMethodDeclaration(methodDeclaration -> { + if (methodDeclaration.getAnnotationByName("Override").isPresent()) { + + while (methodDeclaration.getAnnotations().isNonEmpty()) { + AnnotationExpr annotationExpr = methodDeclaration.getAnnotations().get(0); + annotationExpr.remove(); + } + + methodDeclaration.addMarkerAnnotation("Override"); + } + }))); + assertEquals("public class TestPage extends Page {" + SYSTEM_EOL + + SYSTEM_EOL + + " protected void test() {}" + SYSTEM_EOL + + SYSTEM_EOL + + " @Override" + SYSTEM_EOL + + " protected void initializePage() {}" + SYSTEM_EOL + + "}", LexicalPreservingPrinter.print(cu)); + } + + // See issue #866 + @Test + void moveOrAddOverrideAnnotations() { + considerCode("public class TestPage extends Page {" + SYSTEM_EOL + + SYSTEM_EOL + + " protected void test() {}" + SYSTEM_EOL + + SYSTEM_EOL + + " protected @Override void initializePage() {}" + SYSTEM_EOL + + "}"); + + cu.getTypes() + .forEach(type -> type.getMembers() + .forEach(member -> { + if (member instanceof MethodDeclaration) { + MethodDeclaration methodDeclaration = (MethodDeclaration) member; + if (methodDeclaration.getAnnotationByName("Override").isPresent()) { + + while (methodDeclaration.getAnnotations().isNonEmpty()) { + AnnotationExpr annotationExpr = methodDeclaration.getAnnotations().get(0); + annotationExpr.remove(); + } + } + methodDeclaration.addMarkerAnnotation("Override"); + } + })); + assertEquals("public class TestPage extends Page {" + SYSTEM_EOL + + SYSTEM_EOL + + " @Override" + SYSTEM_EOL + + " protected void test() {}" + SYSTEM_EOL + + SYSTEM_EOL + + " @Override" + SYSTEM_EOL + + " protected void initializePage() {}" + SYSTEM_EOL + + "}", LexicalPreservingPrinter.print(cu)); + } + + // See issue #865 + @Test + void handleAddingMarkerAnnotation() { + considerCode("public class TestPage extends Page {" + SYSTEM_EOL + + SYSTEM_EOL + + " protected void test() {}" + SYSTEM_EOL + + SYSTEM_EOL + + " @Override" + SYSTEM_EOL + + " protected void initializePage() {}" + SYSTEM_EOL + + "}"); + + cu.getTypes() + .forEach(type -> type.getMembers() + .forEach(member -> { + if (member instanceof MethodDeclaration) { + MethodDeclaration methodDeclaration = (MethodDeclaration) member; + if (!methodDeclaration.getAnnotationByName("Override").isPresent()) { + methodDeclaration.addMarkerAnnotation("Override"); + } + } + })); + assertEquals("public class TestPage extends Page {" + SYSTEM_EOL + + SYSTEM_EOL + + " @Override" + SYSTEM_EOL + + " protected void test() {}" + SYSTEM_EOL + + SYSTEM_EOL + + " @Override" + SYSTEM_EOL + + " protected void initializePage() {}" + SYSTEM_EOL + + "}", LexicalPreservingPrinter.print(cu)); + } + + // See issue #865 + @Test + void handleOverrideMarkerAnnotation() { + considerCode("public class TestPage extends Page {" + SYSTEM_EOL + + SYSTEM_EOL + + " protected void test() {}" + SYSTEM_EOL + + SYSTEM_EOL + + " protected void initializePage() {}" + SYSTEM_EOL + + "}"); + + cu.getTypes() + .forEach(type -> type.getMembers() + .forEach(member -> member.ifMethodDeclaration( + methodDeclaration -> methodDeclaration.addMarkerAnnotation("Override")))); + assertEquals("public class TestPage extends Page {" + SYSTEM_EOL + + SYSTEM_EOL + + " @Override" + SYSTEM_EOL + + " protected void test() {}" + SYSTEM_EOL + + SYSTEM_EOL + + " @Override" + SYSTEM_EOL + + " protected void initializePage() {}" + SYSTEM_EOL + + "}", LexicalPreservingPrinter.print(cu)); + } + + // See issue #865 + @Test + void handleOverrideAnnotationAlternative() { + considerCode("public class TestPage extends Page {" + SYSTEM_EOL + + SYSTEM_EOL + + " protected void test() {}" + SYSTEM_EOL + + SYSTEM_EOL + + " protected void initializePage() {}" + SYSTEM_EOL + + "}"); + + cu.getTypes() + .forEach(type -> type.getMembers() + .forEach(member -> member.ifMethodDeclaration( + methodDeclaration -> methodDeclaration.addAnnotation("Override")))); + assertEquals("public class TestPage extends Page {" + SYSTEM_EOL + + SYSTEM_EOL + + " @Override" + SYSTEM_EOL + + " protected void test() {}" + SYSTEM_EOL + + SYSTEM_EOL + + " @Override" + SYSTEM_EOL + + " protected void initializePage() {}" + SYSTEM_EOL + + "}", LexicalPreservingPrinter.print(cu)); + } + + @Test + void invokeModifierVisitor() { + considerCode("class A {" + SYSTEM_EOL + + " Object f() {" + SYSTEM_EOL + + " return (Comparator> & Serializable)(c1, c2) -> c1.getKey().compareTo(c2.getKey()); " + + SYSTEM_EOL + + "}}"); + cu.accept(new ModifierVisitor<>(), null); + } + + @Test + void handleDeprecatedAnnotationFinalClass() { + considerCode("public final class A {}"); + + cu.getTypes().forEach(type -> type.addAndGetAnnotation(Deprecated.class)); + + assertEquals("@Deprecated" + SYSTEM_EOL + + "public final class A {}", LexicalPreservingPrinter.print(cu)); + + } + + @Test + void handleDeprecatedAnnotationAbstractClass() { + considerCode("public abstract class A {}"); + + cu.getTypes().forEach(type -> type.addAndGetAnnotation(Deprecated.class)); + + assertEquals("@Deprecated" + SYSTEM_EOL + + "public abstract class A {}", LexicalPreservingPrinter.print(cu)); + } + + @Test + void issue1244() { + considerCode("public class Foo {" + SYSTEM_EOL + SYSTEM_EOL + + "// Some comment" + SYSTEM_EOL + SYSTEM_EOL // does work with only one \n + + "public void writeExternal() {}" + SYSTEM_EOL + "}"); + + cu.findAll(ClassOrInterfaceDeclaration.class).forEach(c -> { + List methods = c.getMethodsByName("writeExternal"); + for (MethodDeclaration method : methods) { + c.remove(method); + } + }); + assertEqualsStringIgnoringEol("public class Foo {\n" + + "// Some comment\n\n" + + "}", LexicalPreservingPrinter.print(cu)); + } + + static class AddFooCallModifierVisitor extends ModifierVisitor { + @Override + public Visitable visit(MethodCallExpr n, Void arg) { + // Add a call to foo() on every found method call + return new MethodCallExpr(n, "foo"); + } + } + + // See issue 1277 + @Test + void testInvokeModifierVisitor() { + considerCode("class A {" + SYSTEM_EOL + + " public String message = \"hello\";" + SYSTEM_EOL + + " void bar() {" + SYSTEM_EOL + + " System.out.println(\"hello\");" + SYSTEM_EOL + + " }" + SYSTEM_EOL + + "}"); + + cu.accept(new AddFooCallModifierVisitor(), null); + } + + static class CallModifierVisitor extends ModifierVisitor { + @Override + public Visitable visit(MethodCallExpr n, Void arg) { + // Add a call to foo() on every found method call + return new MethodCallExpr(n.clone(), "foo"); + } + } + + @Test + void invokeModifierVisitorIssue1297() { + considerCode("class A {" + SYSTEM_EOL + + " public void bar() {" + SYSTEM_EOL + + " System.out.println(\"hello\");" + SYSTEM_EOL + + " System.out.println(\"hello\");" + SYSTEM_EOL + + " // comment" + SYSTEM_EOL + + " }" + SYSTEM_EOL + + "}"); + + cu.accept(new CallModifierVisitor(), null); + } + + @Test + void addedBlockCommentsPrinted() { + considerCode("public class Foo { }"); + + cu.getClassByName("Foo").get() + .addMethod("mymethod") + .setBlockComment("block"); + assertEqualsStringIgnoringEol("public class Foo {" + SYSTEM_EOL + + " /*block*/" + SYSTEM_EOL + + " void mymethod() {" + SYSTEM_EOL + + " }" + SYSTEM_EOL + + "}", LexicalPreservingPrinter.print(cu)); + } + + @Test + void addedLineCommentsPrinted() { + considerCode("public class Foo { }"); + + cu.getClassByName("Foo").get() + .addMethod("mymethod") + .setLineComment("line"); + assertEqualsStringIgnoringEol("public class Foo {" + SYSTEM_EOL + + " //line" + SYSTEM_EOL + + " void mymethod() {" + SYSTEM_EOL + + " }" + SYSTEM_EOL + + "}", LexicalPreservingPrinter.print(cu)); + } + + @Test + void removedLineCommentsPrinted() { + considerCode("public class Foo {" + SYSTEM_EOL + + "//line" + SYSTEM_EOL + + "void mymethod() {" + SYSTEM_EOL + + "}" + SYSTEM_EOL + + "}"); + cu.getAllContainedComments().get(0).remove(); + + assertEqualsStringIgnoringEol("public class Foo {" + SYSTEM_EOL + + "void mymethod() {" + SYSTEM_EOL + + "}" + SYSTEM_EOL + + "}", LexicalPreservingPrinter.print(cu)); + } + + // Checks if comments get removed properly with Unix style line endings + @Test + void removedLineCommentsPrintedUnix() { + considerCode("public class Foo {" + "\n" + + "//line" + "\n" + + "void mymethod() {" + "\n" + + "}" + "\n" + + "}"); + cu.getAllContainedComments().get(0).remove(); + + assertEquals("public class Foo {" + "\n" + + "void mymethod() {" + "\n" + + "}" + "\n" + + "}", LexicalPreservingPrinter.print(cu)); + } + + @Test + void removedBlockCommentsPrinted() { + considerCode("public class Foo {" + SYSTEM_EOL + + "/*" + SYSTEM_EOL + + "Block comment coming through" + SYSTEM_EOL + + "*/" + SYSTEM_EOL + + "void mymethod() {" + SYSTEM_EOL + + "}" + SYSTEM_EOL + + "}"); + cu.getAllContainedComments().get(0).remove(); + + assertEqualsStringIgnoringEol("public class Foo {" + SYSTEM_EOL + + "void mymethod() {" + SYSTEM_EOL + + "}" + SYSTEM_EOL + + "}", LexicalPreservingPrinter.print(cu)); + } + + @Test + void testFixIndentOfMovedNode() { + try { + considerExample("FixIndentOfMovedNode"); + + cu.getClassByName("ThisIsASampleClass").get() + .getMethodsByName("longerMethod") + .get(0) + .setBlockComment("Lorem ipsum dolor sit amet, consetetur sadipscing elitr."); + + cu.getClassByName("Foo").get() + .getFieldByName("myFoo") + .get() + .setLineComment("sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat"); + + String expectedCode = readExample("FixIndentOfMovedNodeExpected"); + assertEquals(expectedCode, LexicalPreservingPrinter.print(cu)); + } catch (IOException ex) { + fail("Could not read test code", ex); + } + } + + @Test + void issue1321() { + considerCode("class X { X() {} private void testme() {} }"); + + ClassOrInterfaceDeclaration type = cu.getClassByName("X").get(); + type.getConstructors().get(0).setBody(new BlockStmt().addStatement("testme();")); + + assertEqualsStringIgnoringEol("class X { X() {\n testme();\n} private void testme() {} }", + LexicalPreservingPrinter.print(cu)); + } + + @Test + void issue2001() { + considerCode("class X {void blubb(){X.p(\"blaubb04\");}}"); + + cu.findAll(MethodCallExpr.class).forEach(Node::removeForced); + + assertEqualsStringIgnoringEol("class X {void blubb(){}}", LexicalPreservingPrinter.print(cu)); + } + + @Test + void testIndentOfCodeBlocks() throws IOException { + considerExample("IndentOfInsertedCodeBlocks"); + + IfStmt ifStmt = new IfStmt(); + ifStmt.setCondition(StaticJavaParser.parseExpression("name.equals(\"foo\")")); + BlockStmt blockStmt = new BlockStmt(); + blockStmt.addStatement(StaticJavaParser.parseStatement("int i = 0;")); + blockStmt.addStatement(StaticJavaParser.parseStatement("System.out.println(i);")); + blockStmt.addStatement( + new IfStmt().setCondition(StaticJavaParser.parseExpression("i < 0")) + .setThenStmt(new BlockStmt().addStatement(StaticJavaParser.parseStatement("i = 0;")))); + blockStmt.addStatement(StaticJavaParser.parseStatement("new Object(){};")); + ifStmt.setThenStmt(blockStmt); + ifStmt.setElseStmt(new BlockStmt()); + + cu.findFirst(BlockStmt.class).get().addStatement(ifStmt); + String expected = considerExample("IndentOfInsertedCodeBlocksExpected"); + TestUtils.assertEqualsStringIgnoringEol(expected, LexicalPreservingPrinter.print(cu)); + } + + @Test + void commentAddedAtTopLevel() { + considerCode("package x;class X{}"); + + cu.setComment(new LineComment("Bla")); + assertEqualsStringIgnoringEol("//Bla\npackage x;class X{}", LexicalPreservingPrinter.print(cu)); + + cu.setComment(new LineComment("BlaBla")); + assertEqualsStringIgnoringEol("//BlaBla\npackage x;class X{}", LexicalPreservingPrinter.print(cu)); + + cu.removeComment(); + assertEqualsStringIgnoringEol("package x;class X{}", LexicalPreservingPrinter.print(cu)); + } + + @Test + public void testReplaceStringLiteral() { + considerExpression("\"asd\""); + final String expected = "\"REPLACEMENT\""; + + assertTrue(expression.isStringLiteralExpr()); + StringLiteralExpr sle = (StringLiteralExpr) expression; + sle.setValue("REPLACEMENT"); + + final String actual = LexicalPreservingPrinter.print(expression); + assertEquals(expected, actual); + } + + @Test + public void testReplaceStringLiteralWithinStatement() { + considerStatement("String str = \"aaa\";"); + String expected = "String str = \"REPLACEMENT\";"; + + statement.findAll(StringLiteralExpr.class).forEach(stringLiteralExpr -> { + stringLiteralExpr.setValue("REPLACEMENT"); + }); + + assertEquals(expected, LexicalPreservingPrinter.print(statement)); + assertEquals(expected, statement.toString()); + } + + @Test + public void testReplaceClassName() { + considerCode("class A {}"); + + assertEquals(1, cu.findAll(ClassOrInterfaceDeclaration.class).size()); + cu.findAll(ClassOrInterfaceDeclaration.class).forEach(coid -> coid.setName("B")); + + final String expected = "class B {}"; + + final String actual = LexicalPreservingPrinter.print(cu); + assertEquals(expected, actual); + } + + @Test + public void testReplaceIntLiteral() { + considerExpression("5"); + final String expected = "10"; + + assertTrue(expression.isIntegerLiteralExpr()); + ((IntegerLiteralExpr) expression).setValue("10"); + + final String actual = LexicalPreservingPrinter.print(expression); + assertEquals(expected, actual); + } + + @Test + public void testReplaceLongLiteral() { + considerStatement("long x = 5L;"); + String expected = "long x = 10L;"; + + statement.findAll(LongLiteralExpr.class).forEach(longLiteralExpr -> { + longLiteralExpr.setValue("10L"); + }); + + final String actual = LexicalPreservingPrinter.print(statement); + assertEquals(expected, actual); + } + + @Test + public void testReplaceBooleanLiteral() { + considerStatement("boolean x = true;"); + String expected = "boolean x = false;"; + + statement.findAll(BooleanLiteralExpr.class).forEach(booleanLiteralExpr -> { + booleanLiteralExpr.setValue(false); + }); + + final String actual = LexicalPreservingPrinter.print(statement); + assertEquals(expected, actual); + } + + @Test + public void testReplaceDoubleLiteral() { + considerStatement("double x = 5.0D;"); + String expected = "double x = 10.0D;"; + + statement.findAll(DoubleLiteralExpr.class).forEach(doubleLiteralExpr -> { + doubleLiteralExpr.setValue("10.0D"); + }); + + final String actual = LexicalPreservingPrinter.print(statement); + assertEquals(expected, actual); + } + + @Test + public void testReplaceCharLiteral() { + considerStatement("char x = 'a';"); + String expected = "char x = 'b';"; + + statement.findAll(CharLiteralExpr.class).forEach(charLiteralExpr -> { + charLiteralExpr.setValue("b"); + }); + + final String actual = LexicalPreservingPrinter.print(statement); + assertEquals(expected, actual); + } + + @Test + public void testReplaceCharLiteralUnicode() { + considerStatement("char x = 'a';"); + String expected = "char x = '\\u0000';"; + + statement.findAll(CharLiteralExpr.class).forEach(charLiteralExpr -> { + charLiteralExpr.setValue("\\u0000"); + }); + + final String actual = LexicalPreservingPrinter.print(statement); + assertEquals(expected, actual); + } + + @Test + public void testReplaceTextBlockLiteral() { + final JavaParser javaParser = new JavaParser( + new ParserConfiguration() + .setLexicalPreservationEnabled(true) + .setLanguageLevel(ParserConfiguration.LanguageLevel.JAVA_14) + ); + + String code = "String x = \"\"\"a\"\"\";"; + String expected = "String x = \"\"\"\n" + + " REPLACEMENT\n" + + " \"\"\";"; + + final Statement b = javaParser.parseStatement(code).getResult().orElseThrow(AssertionError::new); + b.findAll(TextBlockLiteralExpr.class).forEach(textblockLiteralExpr -> { + textblockLiteralExpr.setValue("\n REPLACEMENT\n "); + }); + + final String actual = LexicalPreservingPrinter.print(b); + assertEquals(expected, actual); + } + + @Test + void testTextBlockSupport() { + String code = + "String html = \"\"\"\n" + + " \n" + + " \n" + + "

Hello, world

\n" + + " \n" + + " \n" + + "\"\"\";"; + String expected = + "String html = \"\"\"\r\n" + + " \r\n" + + " \r\n" + + "

Hello, world

\r\n" + + " \r\n" + + " \r\n" + + "\"\"\";"; + final JavaParser javaParser = new JavaParser( + new ParserConfiguration() + .setLexicalPreservationEnabled(true) + .setLanguageLevel(ParserConfiguration.LanguageLevel.JAVA_15) + ); + Statement stmt = javaParser.parseStatement(code).getResult().orElseThrow(AssertionError::new); + LexicalPreservingPrinter.setup(stmt); + assertEqualsStringIgnoringEol(expected, LexicalPreservingPrinter.print(stmt)); + } + + @Test + void testArrayPreservation_WithSingleLanguageStyle() { + + // Given + considerCode("class Test {\n" + + " int[] foo;\n" + + "}"); + + // When + FieldDeclaration fooField = cu.findFirst(FieldDeclaration.class).orElseThrow(AssertionError::new); + fooField.addMarkerAnnotation("Nullable"); + + // Assert + String expectedCode = "class Test {\n" + + " @Nullable\n" + + " int[] foo;\n" + + "}"; + assertTransformedToString(expectedCode, cu); + } + + @Test + void testArrayPreservation_WithMultipleLanguageStyle() { + + // Given + considerCode("class Test {\n" + + " int[][] foo;\n" + + "}"); + + // When + FieldDeclaration fooField = cu.findFirst(FieldDeclaration.class).orElseThrow(AssertionError::new); + fooField.addMarkerAnnotation("Nullable"); + + // Assert + String expectedCode = "class Test {\n" + + " @Nullable\n" + + " int[][] foo;\n" + + "}"; + assertTransformedToString(expectedCode, cu); + } + + @Test + void testArrayPreservation_WithSingleCLanguageStyle() { + + // Given + considerCode("class Test {\n" + + " int foo[];\n" + + "}"); + + // When + FieldDeclaration fooField = cu.findFirst(FieldDeclaration.class).orElseThrow(AssertionError::new); + fooField.addMarkerAnnotation("Nullable"); + + // Assert + String expectedCode = "class Test {\n" + + " @Nullable\n" + + " int foo[];\n" + + "}"; + assertTransformedToString(expectedCode, cu); + } + + /** + * 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 + void testArrayPreservation_WithMultipleCLanguageStyle() { + + // Given + considerCode("class Test {\n" + + " int foo[][];\n" + + "}"); + + // When + FieldDeclaration fooField = cu.findFirst(FieldDeclaration.class).orElseThrow(AssertionError::new); + fooField.addMarkerAnnotation("Nullable"); + + // Assert + String expectedCode = "class Test {\n" + + " @Nullable\n" + + " int foo[][];\n" + + "}"; + assertTransformedToString(expectedCode, cu); + } + + @Test + void testArrayPreservation_WithSingleBracketWithoutSpace() { + + // Given + considerCode("class Test {\n" + + " int[]foo;\n" + + "}"); + + // When + FieldDeclaration fooField = cu.findFirst(FieldDeclaration.class).orElseThrow(AssertionError::new); + fooField.addMarkerAnnotation("Nullable"); + + // Assert + String expectedCode = "class Test {\n" + + " @Nullable\n" + + " int[]foo;\n" + + "}"; + assertTransformedToString(expectedCode, cu); + } + + @Test + void testArrayPreservation_WithMultipleBracketWithoutSpace() { + + // Given + considerCode("class Test {\n" + + " int[][]foo;\n" + + "}"); + + // When + FieldDeclaration fooField = cu.findFirst(FieldDeclaration.class).orElseThrow(AssertionError::new); + fooField.addMarkerAnnotation("Nullable"); + + // Assert + String expectedCode = "class Test {\n" + + " @Nullable\n" + + " int[][]foo;\n" + + "}"; + assertTransformedToString(expectedCode, cu); + } + + @Test + void testClassOrInterfacePreservationWithFullyQualifiedName_SingleType() { + // Given + considerCode("class Test {\n" + + " java.lang.Object foo;\n" + + "}"); + + // When + FieldDeclaration fooField = cu.findFirst(FieldDeclaration.class).orElseThrow(AssertionError::new); + // modification of the AST + fooField.addMarkerAnnotation("Nullable"); + + // Assert + String expectedCode = "class Test {\n" + + " @Nullable\n" + + " java.lang.Object foo;\n" + + "}"; + assertTransformedToString(expectedCode, cu); + + } + + @Test + void testClassOrInterfacePreservationWithFullyQualifiedName_ArrayType() { + // Given + considerCode("class Test {\n" + + " java.lang.Object[] foo;\n" + + "}"); + + // When + FieldDeclaration fooField = cu.findFirst(FieldDeclaration.class).orElseThrow(AssertionError::new); + // modification of the AST + fooField.addMarkerAnnotation("Nullable"); + + // Assert + String expectedCode = "class Test {\n" + + " @Nullable\n" + + " java.lang.Object[] foo;\n" + + "}"; + assertTransformedToString(expectedCode, cu); + + } + + @Test + void testClassOrInterfacePreservationWithFullyQualifiedName_MultipleVariablesDeclarationWithSameType() { + // Given + considerCode("class Test {\n" + + " java.lang.Object[] foo, bar;\n" + + "}"); + + // When + FieldDeclaration fooField = cu.findFirst(FieldDeclaration.class).orElseThrow(AssertionError::new); + // modification of the AST + fooField.addMarkerAnnotation("Nullable"); + + // Assert + String expectedCode = "class Test {\n" + + " @Nullable\n" + + " java.lang.Object[] foo, bar;\n" + + "}"; + assertTransformedToString(expectedCode, cu); + + } + + @Test + void testClassOrInterfacePreservationWithFullyQualifiedName_MultipleVariablesDeclarationwithDifferentType() { + // Given + considerCode("class Test {\n" + + " java.lang.Object foo[], bar;\n" + + "}"); + + // When + FieldDeclaration fooField = cu.findFirst(FieldDeclaration.class).orElseThrow(AssertionError::new); + // modification of the AST + fooField.addMarkerAnnotation("Nullable"); + + // Assert + String expectedCode = "class Test {\n" + + " @Nullable\n" + + " java.lang.Object foo[], bar;\n" + + "}"; + assertTransformedToString(expectedCode, cu); + + } + + // issue 3588 Modifier is removed when removing an annotation. + @Test + void testRemovingInlinedAnnotation() { + // Given + considerCode("public class Foo{\n" + + " protected @Nullable Object bar;\n" + + "}"); + + // When + FieldDeclaration fd = cu.findFirst(FieldDeclaration.class).get(); + // modification of the AST + AnnotationExpr ae = fd.getAnnotations().get(0); + ae.remove(); + + // Assert + String expectedCode = "public class Foo{\n" + + " protected Object bar;\n" + + "}"; + assertTransformedToString(expectedCode, cu); + + } + + // issue 3588 Modifier is removed when removing an annotation. + @Test + void testRemovingInlinedAnnotation_alternate_case() { + // Given + considerCode("public class Foo{\n" + + " @Nullable protected Object bar;\n" + + "}"); + + // When + FieldDeclaration fd = cu.findFirst(FieldDeclaration.class).get(); + // modification of the AST + AnnotationExpr ae = fd.getAnnotations().get(0); + ae.remove(); + + // Assert + String expectedCode = "public class Foo{\n" + + " protected Object bar;\n" + + "}"; + assertTransformedToString(expectedCode, cu); + + } + + // issue 3216 LexicalPreservingPrinter add Wrong indentation when removing comments + @Test + void removedIndentationLineCommentsPrinted() { + considerCode("public class Foo {\n" + + " //line \n" + + " void mymethod() {\n" + + " }\n" + + "}"); + String expected = + "public class Foo {\n" + + " void mymethod() {\n" + + " }\n" + + "}"; + cu.getAllContainedComments().get(0).remove(); + assertEqualsStringIgnoringEol(expected, LexicalPreservingPrinter.print(cu)); + } + + // issue 4311 IllegalStateException when removing all comments with LexicalPreservingPrinter + @Test + void removedLineCommentsWithSameContent() { + considerCode("public class Foo {\n" + + " //line 1 \n" + + " //line 1 \n" + + " void mymethod() {\n" + + " }\n" + + "}"); + String expected = + "public class Foo {\n" + + " void mymethod() {\n" + + " }\n" + + "}"; + cu.getAllContainedComments().stream().forEach(c -> c.remove()); + assertEqualsStringIgnoringEol(expected, LexicalPreservingPrinter.print(cu)); + } + + // issue 3216 LexicalPreservingPrinter add Wrong indentation when removing comments + @Test + void removedIndentationBlockCommentsPrinted() { + considerCode("public class Foo {\n" + + " /*\n" + + " *Block comment coming through\n" + + " */\n" + + " void mymethod() {\n" + + " }\n" + + "}"); + String expected = + "public class Foo {\n" + + " void mymethod() {\n" + + " }\n" + + "}"; + cu.getAllContainedComments().get(0).remove(); + + assertEqualsStringIgnoringEol(expected, LexicalPreservingPrinter.print(cu)); + } + + // issue 3216 LexicalPreservingPrinter add Wrong indentation when removing comments + @Test + void removedIndentationJavaDocCommentsPrinted() { + considerCode("public class Foo {\n" + + " /**\n" + + " *JavaDoc comment coming through\n" + + " */\n" + + " void mymethod() {\n" + + " }\n" + + "}"); + String expected = + "public class Foo {\n" + + " void mymethod() {\n" + + " }\n" + + "}"; + cu.getAllContainedComments().get(0).remove(); + + 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() { + String code = "class A {void foo(int p1, float p2) { }}"; + CompilationUnit cu = StaticJavaParser.parse(code); + MethodDeclaration md = cu.findFirst(MethodDeclaration.class).get(); + LexicalPreservingPrinter.setup(md); + + assertTrue(LexicalPreservingPrinter.isAvailableOn(md)); + assertFalse(LexicalPreservingPrinter.isAvailableOn(cu)); + } + +} diff --git a/javaparser-core-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 100644 index 0000000..de0c574 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/PeekingIteratorTest.java @@ -0,0 +1,146 @@ +/* + * Copyright (C) 2013-2024 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 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/printer/lexicalpreservation/PrettyPrinterIssue2340Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/PrettyPrinterIssue2340Test.java new file mode 100644 index 0000000..b7bbc80 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/PrettyPrinterIssue2340Test.java @@ -0,0 +1,77 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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 com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.Modifier.Keyword; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +class PrettyPrinterIssue2340Test extends AbstractLexicalPreservingTest { + + @Test + void printingVariableDeclarationWithAddedModifier() { + String def2 = "List i"; + considerVariableDeclaration(def2); + expression.asVariableDeclarationExpr().getModifiers().addFirst(Modifier.privateModifier()); + assertTrue(LexicalPreservingPrinter.getOrCreateNodeText(expression).getElements().stream() + .anyMatch(elem -> elem.expand().equals(Keyword.PRIVATE.asString()))); + } + + @Test + void printingGenericVariableDeclarationWithAddedModifier() { + String def2 = "List i"; + considerVariableDeclaration(def2); + expression.asVariableDeclarationExpr().getModifiers().addFirst(Modifier.privateModifier()); + assertTrue(LexicalPreservingPrinter.getOrCreateNodeText(expression).getElements().stream() + .anyMatch(elem -> elem.expand().equals(Keyword.PRIVATE.asString()))); + } + + @Test + void printingGenericVariableDeclarationWithAddedModifierWithAnotherSyntaxe() { + String def2 = "List i"; + considerVariableDeclaration(def2); + expression.asVariableDeclarationExpr().getModifiers().addFirst(Modifier.privateModifier()); + assertTrue(LexicalPreservingPrinter.getOrCreateNodeText(expression).getElements().stream() + .anyMatch(elem -> elem.expand().equals(Keyword.PRIVATE.asString()))); + } + + @Test + void printingGeneric2VariableDeclarationWithAddedModifier() { + String def2 = "List> i"; + considerVariableDeclaration(def2); + expression.asVariableDeclarationExpr().getModifiers().addFirst(Modifier.privateModifier()); + assertTrue(LexicalPreservingPrinter.getOrCreateNodeText(expression).getElements().stream() + .anyMatch(elem -> elem.expand().equals(Keyword.PRIVATE.asString()))); + } + + @Test + void printingGeneric2VariableDeclarationWithAddedModifierWithAnotherSyntaxe() { + String def2 = "List < List < String > > i"; + considerVariableDeclaration(def2); + expression.asVariableDeclarationExpr().getModifiers().addFirst(Modifier.privateModifier()); + assertTrue(LexicalPreservingPrinter.getOrCreateNodeText(expression).getElements().stream() + .anyMatch(elem -> elem.expand().equals(Keyword.PRIVATE.asString()))); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/PrettyPrinterIssue2351Test.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/PrettyPrinterIssue2351Test.java new file mode 100644 index 0000000..35a9876 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/PrettyPrinterIssue2351Test.java @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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 com.github.javaparser.ast.body.EnumDeclaration; +import org.junit.jupiter.api.Test; + +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +// manage java.lang.UnsupportedOperationException: Csm token token(}) NodeText TOKEN ";" <102> (line 1,col 39)-(line 1,col 39) +class PrettyPrinterIssue2351Test extends AbstractLexicalPreservingTest { + + @Test + void printingEnum2() { + String def2 = + "public enum RandomEnum {" + + " TYPE_1;" + + "}"; + considerCode(def2); + Optional decl = cu.findFirst(EnumDeclaration.class); + if (decl.isPresent()) decl.get().addEnumConstant("SOMETHING"); + assertTrue(decl.get().getEntries().size() == 2); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/TransformationsTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/TransformationsTest.java new file mode 100644 index 0000000..a73e51c --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/TransformationsTest.java @@ -0,0 +1,343 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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 com.github.javaparser.StaticJavaParser; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.FieldDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.body.VariableDeclarator; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.expr.NameExpr; +import com.github.javaparser.ast.expr.NullLiteralExpr; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.ast.stmt.ReturnStmt; +import com.github.javaparser.ast.type.ArrayType; +import com.github.javaparser.ast.type.PrimitiveType; +import org.junit.jupiter.api.Test; + +import java.io.IOException; + +import static com.github.javaparser.ast.Modifier.Keyword.STATIC; +import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol; +import static com.github.javaparser.utils.Utils.SYSTEM_EOL; + +/** + * These tests are more "high level" than the ones in LexicalPreservingPrinterTest. + * The idea is to perform some transformations on the code, print it back and see if the generated code + * is the expected one. We do not care about the internal state of LexicalPreservingPrinter, just the visible result. + */ +class TransformationsTest extends AbstractLexicalPreservingTest { + + @Test + void unchangedSimpleClasses() throws IOException { + assertUnchanged("Example1"); + assertUnchanged("Example2"); + } + + @Test + void unchangedComplexFile() throws IOException { + assertUnchanged("Example4"); + } + + @Test + void example1() throws IOException { + considerExample("Example1_original"); + cu.getClassByName("A").get().getFieldByName("a").get().setModifiers(STATIC); + assertTransformed("Example1", cu); + } + + @Test + void example2() throws IOException { + considerExample("Example2_original"); + cu.getClassByName("A").get().getFieldByName("a").get().getVariable(0).setInitializer("10"); + assertTransformed("Example2", cu); + } + + @Test + void example3() throws IOException { + considerExample("Example3_original"); + cu.getClassByName("A").get().getFieldByName("a").get().getVariable(0).setInitializer((Expression) null); + assertTransformed("Example3", cu); + } + + @Test + void example5() throws IOException { + considerExample("Example5_original"); + cu.getClassByName("A").get().getFieldByName("a").get().getVariable(0).setInitializer(new NullLiteralExpr()); + assertTransformed("Example5", cu); + } + + @Test + void example6() throws IOException { + considerExample("Example6_original"); + cu.getClassByName("A").get().getFieldByName("a").get().getVariable(0).setName("someOtherName"); + assertTransformed("Example6", cu); + } + + @Test + void example7() throws IOException { + considerExample("Example7_original"); + cu.getClassByName("A").get().getFieldByName("a").get().getVariable(0).setType(new ArrayType(PrimitiveType.intType())); + assertTransformed("Example7", cu); + } + + @Test + void example8() throws IOException { + considerExample("Example8_original"); + FieldDeclaration fd = cu.getClassByName("A").get().getMember(0).asFieldDeclaration(); + fd.addVariable(new VariableDeclarator(PrimitiveType.intType(), "b")); + assertTransformed("Example8", cu); + } + + @Test + void example9() throws IOException { + considerExample("Example9_original"); + FieldDeclaration fd = cu.getClassByName("A").get().getMember(0).asFieldDeclaration(); + fd.addVariable(new VariableDeclarator(new ArrayType(PrimitiveType.intType()), "b")); + assertTransformed("Example9", cu); + } + + @Test + void example10() throws IOException { + considerExample("Example10_original"); + cu.getClassByName("A").get().getMembers().remove(0); + assertTransformed("Example10", cu); + } + + @Test + void exampleParam1() throws IOException { + considerExample("Example_param1_original"); + MethodDeclaration md = cu.getClassByName("A").get().getMember(0).asMethodDeclaration(); + md.addParameter("int", "p1"); + assertTransformed("Example_param1", cu); + } + + @Test + void exampleParam2() throws IOException { + considerExample("Example_param1_original"); + MethodDeclaration md = cu.getClassByName("A").get().getMember(0).asMethodDeclaration(); + md.addParameter(new ArrayType(PrimitiveType.intType()), "p1"); + md.addParameter("char", "p2"); + assertTransformed("Example_param2", cu); + } + + @Test + void exampleParam3() throws IOException { + considerExample("Example_param3_original"); + MethodDeclaration md = cu.getClassByName("A").get().getMember(0).asMethodDeclaration(); + md.getParameters().remove(0); + assertTransformed("Example_param3", cu); + } + + @Test + void exampleParam4() throws IOException { + considerExample("Example_param3_original"); + MethodDeclaration md = cu.getClassByName("A").get().getMember(0).asMethodDeclaration(); + md.getParameters().remove(1); + assertTransformed("Example_param4", cu); + } + + @Test + void exampleParam5() throws IOException { + considerExample("Example_param3_original"); + MethodDeclaration md = cu.getClassByName("A").get().getMember(0).asMethodDeclaration(); + md.setType(PrimitiveType.intType()); + assertTransformed("Example_param5b", cu); + md.getBody().get().getStatements().add(new ReturnStmt(new NameExpr("p1"))); + String expected = readExample("Example_param5" + "_expected"); + String s = LexicalPreservingPrinter.print(cu); + assertEqualsStringIgnoringEol(expected, s); + } + + @Test + void issue2099AddingStatementAfterTraillingComment1() { + considerStatement( + " if(value != null) {" + SYSTEM_EOL + + " value.value();" + SYSTEM_EOL + + " }"); + + BlockStmt blockStmt = LexicalPreservingPrinter.setup(StaticJavaParser.parseBlock("{" + SYSTEM_EOL + + " value1();" + SYSTEM_EOL + + " value2(); // Test" + SYSTEM_EOL + + "}")); + + blockStmt.addStatement(statement); + String s = LexicalPreservingPrinter.print(blockStmt); + String expected = "{\n" + + " value1();\n" + + " value2(); // Test\n" + + " if(value != null) {\n" + + " value.value();\n" + + " }\n" + + "}"; + assertEqualsStringIgnoringEol(expected, s); + } + + @Test + void issue2099AddingStatementAfterTraillingComment2() { + considerStatement( + " if(value != null) {" + SYSTEM_EOL + + " value.value();" + SYSTEM_EOL + + " }"); + + BlockStmt blockStmt = LexicalPreservingPrinter.setup(StaticJavaParser.parseBlock("{" + SYSTEM_EOL + + " value1();" + SYSTEM_EOL + + " value2(); /* test */" + SYSTEM_EOL + + "}")); + + blockStmt.addStatement(statement); + String s = LexicalPreservingPrinter.print(blockStmt); + String expected = "{\n" + + " value1();\n" + + " value2(); /* test */\n" + + " if(value != null) {\n" + + " value.value();\n" + + " }\n" + + "}"; + assertEqualsStringIgnoringEol(expected, s); + } + + + @Test + void addingStatement1() { + considerStatement( + " if(value != null) {" + SYSTEM_EOL + + " value.value();" + SYSTEM_EOL + + " }"); + + CompilationUnit compilationUnit = LexicalPreservingPrinter.setup(StaticJavaParser.parse("public class Test {" + SYSTEM_EOL + + " public void method() {" + SYSTEM_EOL + + " value1();" + SYSTEM_EOL + + " value2(); // Test" + SYSTEM_EOL + + " }" + SYSTEM_EOL + + "}")); + ClassOrInterfaceDeclaration classOrInterfaceDeclaration = (ClassOrInterfaceDeclaration)compilationUnit.getChildNodes().get(0); + MethodDeclaration methodDeclaration = (MethodDeclaration)classOrInterfaceDeclaration.getChildNodes().get(2); + methodDeclaration.getBody().get().addStatement(statement); + + String s = LexicalPreservingPrinter.print(compilationUnit); + String expected = "public class Test {\n" + + " public void method() {\n" + + " value1();\n" + + " value2(); // Test\n" + + " if(value != null) {\n" + + " value.value();\n" + + " }\n" + + " }\n" + + "}"; + assertEqualsStringIgnoringEol(expected, s); + } + + @Test + void addingStatement2() { + considerStatement( + " if(value != null) {" + SYSTEM_EOL + + " value.value();" + SYSTEM_EOL + + " }"); + + CompilationUnit compilationUnit = LexicalPreservingPrinter.setup(StaticJavaParser.parse("public class Test {" + SYSTEM_EOL + + " public void method() {" + SYSTEM_EOL + + " value1();" + SYSTEM_EOL + + " value2();" + SYSTEM_EOL + + " }" + SYSTEM_EOL + + "}")); + ClassOrInterfaceDeclaration classOrInterfaceDeclaration = (ClassOrInterfaceDeclaration)compilationUnit.getChildNodes().get(0); + MethodDeclaration methodDeclaration = (MethodDeclaration)classOrInterfaceDeclaration.getChildNodes().get(2); + methodDeclaration.getBody().get().addStatement(statement); + + String s = LexicalPreservingPrinter.print(compilationUnit); + String expected = "public class Test {\n" + + " public void method() {\n" + + " value1();\n" + + " value2();\n" + + " if(value != null) {\n" + + " value.value();\n" + + " }\n" + + " }\n" + + "}"; + assertEqualsStringIgnoringEol(expected, s); + } + + @Test + void addingStatement3() { + considerStatement( + " if(value != null) {" + SYSTEM_EOL + + " value.value();" + SYSTEM_EOL + + " }"); + + CompilationUnit compilationUnit = LexicalPreservingPrinter.setup(StaticJavaParser.parse("public class Test {" + SYSTEM_EOL + + " public void method() {" + SYSTEM_EOL + + " value1();" + SYSTEM_EOL + + " value2();" + SYSTEM_EOL + SYSTEM_EOL + + " }" + SYSTEM_EOL + + "}")); + ClassOrInterfaceDeclaration classOrInterfaceDeclaration = (ClassOrInterfaceDeclaration)compilationUnit.getChildNodes().get(0); + MethodDeclaration methodDeclaration = (MethodDeclaration)classOrInterfaceDeclaration.getChildNodes().get(2); + methodDeclaration.getBody().get().addStatement(statement); + + String s = LexicalPreservingPrinter.print(compilationUnit); + String expected = "public class Test {\n" + + " public void method() {\n" + + " value1();\n" + + " value2();\n" + + " if(value != null) {\n" + + " value.value();\n" + + " }\n\n" + + " }\n" + + "}"; + assertEqualsStringIgnoringEol(expected, s); + } + + @Test + void removingInSingleMemberList() { + considerCode( + "class A {\n" + + " int a;\n" + + "}"); + cu.getClassByName("A").get().getMembers().remove(0); + String expected = + "class A {\n" + + "}"; + String s = LexicalPreservingPrinter.print(cu); + assertEqualsStringIgnoringEol(expected, s); + } + + @Test + void removingInMultiMembersList() { + considerCode( + "class A {\n" + + " int a;\n" + + " int b;\n" + + "}"); + cu.getClassByName("A").get().getMembers().removeLast(); + String expected = + "class A {\n" + + " int a;\n" + + "}"; + String s = LexicalPreservingPrinter.print(cu); + assertEqualsStringIgnoringEol(expected, s); + } + + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/changes/NoChangeTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/changes/NoChangeTest.java new file mode 100644 index 0000000..56e3e44 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/changes/NoChangeTest.java @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2013-2024 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.changes; + +import com.github.javaparser.ast.observer.ObservableProperty; +import com.github.javaparser.ast.type.ClassOrInterfaceType; +import org.junit.jupiter.api.*; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class NoChangeTest { + + @BeforeAll + static void setUpBeforeClass() throws Exception { + } + + @AfterAll + static void tearDownAfterClass() throws Exception { + } + + @BeforeEach + void setUp() throws Exception { + } + + @AfterEach + void tearDown() throws Exception { + } + + @Test + void getValue_WithMethodFound() { + Object o = new NoChange().getValue(ObservableProperty.ANNOTATIONS, new ClassOrInterfaceType()); + assertNotNull(o); + } + + @Test + void getValue_WithNoMethodFound() { + assertThrows(RuntimeException.class, () -> { + new NoChange().getValue(ObservableProperty.IMPORTS, new ClassOrInterfaceType()); + }, "RuntimeException was expected"); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/ArrayCreationLevelTransformationsTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/ArrayCreationLevelTransformationsTest.java new file mode 100644 index 0000000..e2f700c --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/ArrayCreationLevelTransformationsTest.java @@ -0,0 +1,91 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.transformations.ast; + +import com.github.javaparser.ast.ArrayCreationLevel; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.expr.ArrayCreationExpr; +import com.github.javaparser.ast.expr.IntegerLiteralExpr; +import com.github.javaparser.ast.expr.Name; +import com.github.javaparser.ast.expr.NormalAnnotationExpr; +import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest; +import com.github.javaparser.utils.Utils; +import org.junit.jupiter.api.Test; + +/** + * Transforming ArrayCreationLevel and verifying the LexicalPreservation works as expected. + */ +class ArrayCreationLevelTransformationsTest extends AbstractLexicalPreservingTest { + + protected ArrayCreationLevel consider(String code) { + considerExpression("new int" + code); + ArrayCreationExpr arrayCreationExpr = expression.asArrayCreationExpr(); + return arrayCreationExpr.getLevels().get(0); + } + + // Dimension + + @Test + void addingDimension() { + ArrayCreationLevel it = consider("[]"); + it.setDimension(new IntegerLiteralExpr("10")); + assertTransformedToString("[10]", it); + } + + @Test + void removingDimension() { + ArrayCreationLevel it = consider("[10]"); + it.removeDimension(); + assertTransformedToString("[]", it); + } + + @Test + void replacingDimension() { + ArrayCreationLevel it = consider("[10]"); + it.setDimension(new IntegerLiteralExpr("12")); + assertTransformedToString("[12]", it); + } + + // Annotations + + @Test + void addingAnnotation() { + ArrayCreationLevel it = consider("[]"); + it.addAnnotation("myAnno"); + assertTransformedToString("@myAnno"+ Utils.SYSTEM_EOL +"[]", it); + } + + @Test + void removingAnnotation() { + ArrayCreationLevel it = consider("@myAnno []"); + it.getAnnotations().remove(0); + assertTransformedToString("[]", it); + } + + @Test + void replacingAnnotation() { + ArrayCreationLevel it = consider("@myAnno []"); + it.getAnnotations().set(0, new NormalAnnotationExpr(new Name("myOtherAnno"), new NodeList<>())); + assertTransformedToString("@myOtherAnno []", it); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/CompilationUnitTransformationsTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/CompilationUnitTransformationsTest.java new file mode 100644 index 0000000..f4dfa96 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/CompilationUnitTransformationsTest.java @@ -0,0 +1,64 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.transformations.ast; + +import com.github.javaparser.ast.PackageDeclaration; +import com.github.javaparser.ast.expr.Name; +import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.utils.Utils.SYSTEM_EOL; + +/** + * Transforming CompilationUnit and verifying the LexicalPreservation works as expected. + */ +class CompilationUnitTransformationsTest extends AbstractLexicalPreservingTest { + + // packageDeclaration + + @Test + void addingPackageDeclaration() { + considerCode("class A {}"); + cu.setPackageDeclaration(new PackageDeclaration(new Name(new Name("foo"), "bar"))); + assertTransformedToString("package foo.bar;"+ SYSTEM_EOL + SYSTEM_EOL + "class A {}", cu); + } + + @Test + void removingPackageDeclaration() { + considerCode("package foo.bar; class A {}"); + cu.removePackageDeclaration(); + assertTransformedToString("class A {}", cu); + } + + @Test + void replacingPackageDeclaration() { + considerCode("package foo.bar; class A {}"); + cu.setPackageDeclaration(new PackageDeclaration(new Name(new Name("foo2"), "baz"))); + assertTransformedToString("package foo2.baz;" + + SYSTEM_EOL + SYSTEM_EOL + + " class A {}", cu); + } + + // imports + + // types +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/AnnotationDeclarationTransformationsTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/AnnotationDeclarationTransformationsTest.java new file mode 100644 index 0000000..85e4d7d --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/AnnotationDeclarationTransformationsTest.java @@ -0,0 +1,128 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.transformations.ast.body; + +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.AnnotationMemberDeclaration; +import com.github.javaparser.ast.type.PrimitiveType; +import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest; +import org.junit.jupiter.api.Test; + +import java.io.IOException; + +import static com.github.javaparser.ast.Modifier.Keyword.PROTECTED; +import static com.github.javaparser.ast.Modifier.Keyword.PUBLIC; +import static com.github.javaparser.ast.Modifier.createModifierList; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Transforming AnnotationDeclaration and verifying the LexicalPreservation works as expected. + */ +class AnnotationDeclarationTransformationsTest extends AbstractLexicalPreservingTest { + + @Test + void unchangedExamples() throws IOException { + assertUnchanged("AnnotationDeclaration_Example1"); + assertUnchanged("AnnotationDeclaration_Example3"); + assertUnchanged("AnnotationDeclaration_Example9"); + } + + // name + + @Test + void changingName() throws IOException { + considerExample("AnnotationDeclaration_Example1_original"); + cu.getAnnotationDeclarationByName("ClassPreamble").get().setName("NewName"); + assertTransformed("AnnotationDeclaration_Example1", cu); + } + + // modifiers + + @Test + void addingModifiers() throws IOException { + considerExample("AnnotationDeclaration_Example1_original"); + cu.getAnnotationDeclarationByName("ClassPreamble").get().setModifiers(createModifierList(PUBLIC)); + assertTransformed("AnnotationDeclaration_Example2", cu); + } + + @Test + void removingModifiers() throws IOException { + considerExample("AnnotationDeclaration_Example3_original"); + cu.getAnnotationDeclarationByName("ClassPreamble").get().setModifiers(new NodeList<>()); + assertTransformed("AnnotationDeclaration_Example3", cu); + } + + @Test + void replacingModifiers() throws IOException { + considerExample("AnnotationDeclaration_Example3_original"); + cu.getAnnotationDeclarationByName("ClassPreamble").get().setModifiers(createModifierList(PROTECTED)); + assertTransformed("AnnotationDeclaration_Example4", cu); + } + + // members + + @Test + void addingMember() throws IOException { + considerExample("AnnotationDeclaration_Example3_original"); + cu.getAnnotationDeclarationByName("ClassPreamble").get().addMember(new AnnotationMemberDeclaration(new NodeList<>(), PrimitiveType.intType(), "foo", null)); + assertTransformed("AnnotationDeclaration_Example5", cu); + } + + @Test + void removingMember() throws IOException { + considerExample("AnnotationDeclaration_Example3_original"); + cu.getAnnotationDeclarationByName("ClassPreamble").get().getMember(2).remove(); + assertTransformed("AnnotationDeclaration_Example6", cu); + } + + @Test + void replacingMember() throws IOException { + considerExample("AnnotationDeclaration_Example3_original"); + cu.getAnnotationDeclarationByName("ClassPreamble").get().setMember(2, new AnnotationMemberDeclaration(new NodeList<>(), PrimitiveType.intType(), "foo", null)); + assertTransformed("AnnotationDeclaration_Example7", cu); + } + + // javadoc + + @Test + void addingJavadoc() throws IOException { + considerExample("AnnotationDeclaration_Example3_original"); + cu.getAnnotationDeclarationByName("ClassPreamble").get().setJavadocComment("Cool this annotation!"); + assertTransformed("AnnotationDeclaration_Example8", cu); + } + + @Test + void removingJavadoc() throws IOException { + considerExample("AnnotationDeclaration_Example9_original"); + boolean removed = cu.getAnnotationDeclarationByName("ClassPreamble").get().getJavadocComment().get().remove(); + assertTrue(removed); + assertTransformed("AnnotationDeclaration_Example9", cu); + } + + @Test + void replacingJavadoc() throws IOException { + considerExample("AnnotationDeclaration_Example9_original"); + cu.getAnnotationDeclarationByName("ClassPreamble").get().setJavadocComment("Super extra cool this annotation!!!"); + assertTransformed("AnnotationDeclaration_Example10", cu); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/AnnotationMemberDeclarationTransformationsTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/AnnotationMemberDeclarationTransformationsTest.java new file mode 100644 index 0000000..5073dae --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/AnnotationMemberDeclarationTransformationsTest.java @@ -0,0 +1,174 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.transformations.ast.body; + +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.AnnotationMemberDeclaration; +import com.github.javaparser.ast.expr.IntegerLiteralExpr; +import com.github.javaparser.ast.expr.Name; +import com.github.javaparser.ast.expr.NormalAnnotationExpr; +import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.ast.Modifier.Keyword.PROTECTED; +import static com.github.javaparser.ast.Modifier.Keyword.PUBLIC; +import static com.github.javaparser.ast.Modifier.createModifierList; +import static com.github.javaparser.utils.Utils.SYSTEM_EOL; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Transforming AnnotationMemberDeclaration and verifying the LexicalPreservation works as expected. + */ +class AnnotationMemberDeclarationTransformationsTest extends AbstractLexicalPreservingTest { + + protected AnnotationMemberDeclaration consider(String code) { + considerCode("@interface AD { " + code + " }"); + return cu.getAnnotationDeclarationByName("AD").get().getMember(0).asAnnotationMemberDeclaration(); + } + + // Name + + @Test + void changingName() { + AnnotationMemberDeclaration md = consider("int foo();"); + md.setName("bar"); + assertTransformedToString("int bar();", md); + } + + // Type + + @Test + void changingType() { + AnnotationMemberDeclaration md = consider("int foo();"); + md.setType("String"); + assertTransformedToString("String foo();", md); + } + + // Modifiers + + @Test + void addingModifiers() { + AnnotationMemberDeclaration md = consider("int foo();"); + md.setModifiers(createModifierList(PUBLIC)); + assertTransformedToString("public int foo();", md); + } + + @Test + void removingModifiers() { + AnnotationMemberDeclaration md = consider("public int foo();"); + md.setModifiers(new NodeList<>()); + assertTransformedToString("int foo();", md); + } + + @Test + void replacingModifiers() { + AnnotationMemberDeclaration md = consider("public int foo();"); + md.setModifiers(createModifierList(PROTECTED)); + assertTransformedToString("protected int foo();", md); + } + + // Default value + + @Test + void addingDefaultValue() { + AnnotationMemberDeclaration md = consider("int foo();"); + md.setDefaultValue(new IntegerLiteralExpr("10")); + assertTransformedToString("int foo() default 10;", md); + } + + @Test + void removingDefaultValue() { + AnnotationMemberDeclaration md = consider("int foo() default 10;"); + assertTrue(md.getDefaultValue().get().remove()); + assertTransformedToString("int foo();", md); + } + + @Test + void replacingDefaultValue() { + AnnotationMemberDeclaration md = consider("int foo() default 10;"); + md.setDefaultValue(new IntegerLiteralExpr("11")); + assertTransformedToString("int foo() default 11;", md); + } + + // Annotations + + @Test + void addingAnnotation() { + AnnotationMemberDeclaration it = consider("int foo();"); + it.addAnnotation("myAnno"); + assertTransformedToString("@myAnno" + SYSTEM_EOL + "int foo();", it); + } + + @Test + void addingTwoAnnotations() { + AnnotationMemberDeclaration it = consider("int foo();"); + it.addAnnotation("myAnno"); + it.addAnnotation("myAnno2"); + assertTransformedToString("@myAnno" + SYSTEM_EOL + "@myAnno2" + SYSTEM_EOL + "int foo();", it); + } + + @Test + void removingAnnotationOnSomeLine() { + AnnotationMemberDeclaration it = consider("@myAnno int foo();"); + it.getAnnotations().remove(0); + assertTransformedToString("int foo();", it); + } + + @Test + void removingAnnotationOnPrevLine() { + AnnotationMemberDeclaration it = consider("@myAnno" + SYSTEM_EOL + "int foo();"); + it.getAnnotations().remove(0); + assertTransformedToString("int foo();", it); + } + + @Test + void replacingAnnotation() { + AnnotationMemberDeclaration it = consider("@myAnno int foo();"); + it.getAnnotations().set(0, new NormalAnnotationExpr(new Name("myOtherAnno"), new NodeList<>())); + assertTransformedToString("@myOtherAnno int foo();", it); + } + + // Javadoc + + @Test + void addingJavadoc() { + AnnotationMemberDeclaration it = consider("int foo();"); + it.setJavadocComment("Cool this annotation!"); + assertTransformedToString("@interface AD { /**Cool this annotation!*/" + SYSTEM_EOL + + "int foo(); }", it.getParentNode().get()); + } + + @Test + void removingJavadoc() { + AnnotationMemberDeclaration it = consider("/**Cool this annotation!*/ int foo();"); + assertTrue(it.getJavadocComment().get().remove()); + assertTransformedToString("@interface AD { int foo(); }", it.getParentNode().get()); + } + + @Test + void replacingJavadoc() { + AnnotationMemberDeclaration it = consider("/**Cool this annotation!*/ int foo();"); + it.setJavadocComment("Super extra cool this annotation!!!"); + assertTransformedToString("@interface AD { /**Super extra cool this annotation!!!*/ int foo(); }", it.getParentNode().get()); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/ClassOrInterfaceDeclarationTransformationsTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/ClassOrInterfaceDeclarationTransformationsTest.java new file mode 100644 index 0000000..d8b9ecf --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/ClassOrInterfaceDeclarationTransformationsTest.java @@ -0,0 +1,210 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.transformations.ast.body; + +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.FieldDeclaration; +import com.github.javaparser.ast.body.VariableDeclarator; +import com.github.javaparser.ast.type.PrimitiveType; +import com.github.javaparser.ast.type.TypeParameter; +import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.StaticJavaParser.parseClassOrInterfaceType; +import static com.github.javaparser.ast.Modifier.Keyword.PROTECTED; +import static com.github.javaparser.ast.Modifier.Keyword.PUBLIC; +import static com.github.javaparser.ast.Modifier.createModifierList; +import static com.github.javaparser.utils.Utils.SYSTEM_EOL; + +/** + * Transforming ClassOrInterfaceDeclaration and verifying the LexicalPreservation works as expected. + */ +class ClassOrInterfaceDeclarationTransformationsTest extends AbstractLexicalPreservingTest { + + protected ClassOrInterfaceDeclaration consider(String code) { + considerCode(code); + return cu.getType(0).asClassOrInterfaceDeclaration(); + } + + // Name + + @Test + void settingName() { + ClassOrInterfaceDeclaration cid = consider("class A {}"); + cid.setName("B"); + assertTransformedToString("class B {}", cid); + } + + // isInterface + + @Test + void classToInterface() { + ClassOrInterfaceDeclaration cid = consider("class A {}"); + cid.setInterface(true); + assertTransformedToString("interface A {}", cid); + } + + @Test + void interfaceToClass() { + ClassOrInterfaceDeclaration cid = consider("interface A {}"); + cid.setInterface(false); + assertTransformedToString("class A {}", cid); + } + + // typeParameters + + @Test + void addingTypeParameterWhenThereAreNone() { + ClassOrInterfaceDeclaration cid = consider("class A {}"); + cid.addTypeParameter("T"); + assertTransformedToString("class A {}", cid); + } + + @Test + void addingTypeParameterAsFirstWhenThereAreSome() { + ClassOrInterfaceDeclaration cid = consider("class A {}"); + cid.getTypeParameters().addFirst(new TypeParameter("T", new NodeList<>())); + assertTransformedToString("class A {}", cid); + } + + @Test + void addingTypeParameterAsLastWhenThereAreSome() { + ClassOrInterfaceDeclaration cid = consider("class A {}"); + cid.addTypeParameter("T"); + assertTransformedToString("class A {}", cid); + } + + // extendedTypes + + @Test + void addingExtendedTypes() { + ClassOrInterfaceDeclaration cid = consider("class A {}"); + cid.addExtendedType("Foo"); + assertTransformedToString("class A extends Foo {}", cid); + } + + @Test + void removingExtendedTypes() { + ClassOrInterfaceDeclaration cid = consider("public class A extends Foo {}"); + cid.getExtendedTypes().remove(0); + assertTransformedToString("public class A {}", cid); + } + + @Test + void replacingExtendedTypes() { + ClassOrInterfaceDeclaration cid = consider("public class A extends Foo {}"); + cid.getExtendedTypes().set(0, parseClassOrInterfaceType("Bar")); + assertTransformedToString("public class A extends Bar {}", cid); + } + + // implementedTypes + + @Test + void addingImplementedTypes() { + ClassOrInterfaceDeclaration cid = consider("class A {}"); + cid.addImplementedType("Foo"); + assertTransformedToString("class A implements Foo {}", cid); + } + + @Test + void removingImplementedTypes() { + ClassOrInterfaceDeclaration cid = consider("public class A implements Foo {}"); + cid.getImplementedTypes().remove(0); + assertTransformedToString("public class A {}", cid); + } + + @Test + void replacingImplementedTypes() { + ClassOrInterfaceDeclaration cid = consider("public class A implements Foo {}"); + cid.getImplementedTypes().set(0, parseClassOrInterfaceType("Bar")); + assertTransformedToString("public class A implements Bar {}", cid); + } + + // Modifiers + + @Test + void addingModifiers() { + ClassOrInterfaceDeclaration cid = consider("class A {}"); + cid.setModifiers(createModifierList(PUBLIC)); + assertTransformedToString("public class A {}", cid); + } + + @Test + void removingModifiers() { + ClassOrInterfaceDeclaration cid = consider("public class A {}"); + cid.setModifiers(new NodeList<>()); + assertTransformedToString("class A {}", cid); + } + + @Test + void replacingModifiers() { + ClassOrInterfaceDeclaration cid = consider("public class A {}"); + cid.setModifiers(createModifierList(PROTECTED)); + assertTransformedToString("protected class A {}", cid); + } + + // members + + @Test + void addingField() { + ClassOrInterfaceDeclaration cid = consider("class A {}"); + cid.addField("int", "foo"); + assertTransformedToString("class A {" + SYSTEM_EOL + " int foo;" + SYSTEM_EOL + "}", cid); + } + + @Test + void removingField() { + ClassOrInterfaceDeclaration cid = consider("public class A { int foo; }"); + cid.getMembers().remove(0); + assertTransformedToString("public class A { }", cid); + } + + @Test + void replacingFieldWithAnotherField() { + ClassOrInterfaceDeclaration cid = consider("public class A {float f;}"); + cid.getMembers().set(0, new FieldDeclaration(new NodeList<>(), new VariableDeclarator(PrimitiveType.intType(), "bar"))); + assertTransformedToString("public class A {int bar;}", cid); + } + + // Annotations + @Test + void removingAnnotations() { + ClassOrInterfaceDeclaration cid = consider( + "@Value" + SYSTEM_EOL + + "public class A {}"); + cid.getAnnotationByName("Value").get().remove(); + assertTransformedToString("public class A {}", cid); + } + + @Test + void removingAnnotationsWithSpaces() { + ClassOrInterfaceDeclaration cid = consider( + " @Value " + SYSTEM_EOL + + "public class A {}"); + cid.getAnnotationByName("Value").get().remove(); + assertTransformedToString("public class A {}", cid); + } + + // Javadoc + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/ConstructorDeclarationTransformationsTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/ConstructorDeclarationTransformationsTest.java new file mode 100644 index 0000000..4d05731 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/ConstructorDeclarationTransformationsTest.java @@ -0,0 +1,123 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.transformations.ast.body; + +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.ConstructorDeclaration; +import com.github.javaparser.ast.body.Parameter; +import com.github.javaparser.ast.expr.SimpleName; +import com.github.javaparser.ast.type.ArrayType; +import com.github.javaparser.ast.type.PrimitiveType; +import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.ast.Modifier.Keyword.PROTECTED; +import static com.github.javaparser.ast.Modifier.Keyword.PUBLIC; +import static com.github.javaparser.ast.Modifier.createModifierList; + +/** + * Transforming ConstructorDeclaration and verifying the LexicalPreservation works as expected. + */ +class ConstructorDeclarationTransformationsTest extends AbstractLexicalPreservingTest { + + protected ConstructorDeclaration consider(String code) { + considerCode("class A { " + code + " }"); + return cu.getType(0).getMembers().get(0).asConstructorDeclaration(); + } + + // Name + + @Test + void settingName() { + ConstructorDeclaration cd = consider("A(){}"); + cd.setName("B"); + assertTransformedToString("B(){}", cd); + } + + // JavaDoc + + // Modifiers + + @Test + void addingModifiers() { + ConstructorDeclaration cd = consider("A(){}"); + cd.setModifiers(createModifierList(PUBLIC)); + assertTransformedToString("public A(){}", cd); + } + + @Test + void removingModifiers() { + ConstructorDeclaration cd = consider("public A(){}"); + cd.setModifiers(new NodeList<>()); + assertTransformedToString("A(){}", cd); + } + + @Test + void replacingModifiers() { + ConstructorDeclaration cd = consider("public A(){}"); + cd.setModifiers(createModifierList(PROTECTED)); + assertTransformedToString("protected A(){}", cd); + } + + // Parameters + + @Test + void addingParameters() { + ConstructorDeclaration cd = consider("A(){}"); + cd.addParameter(PrimitiveType.doubleType(), "d"); + assertTransformedToString("A(double d){}", cd); + } + + @Test + void removingOnlyParameter() { + ConstructorDeclaration cd = consider("public A(double d){}"); + cd.getParameters().remove(0); + assertTransformedToString("public A(){}", cd); + } + + @Test + void removingFirstParameterOfMany() { + ConstructorDeclaration cd = consider("public A(double d, float f){}"); + cd.getParameters().remove(0); + assertTransformedToString("public A(float f){}", cd); + } + + @Test + void removingLastParameterOfMany() { + ConstructorDeclaration cd = consider("public A(double d, float f){}"); + cd.getParameters().remove(1); + assertTransformedToString("public A(double d){}", cd); + } + + @Test + void replacingOnlyParameter() { + ConstructorDeclaration cd = consider("public A(float f){}"); + cd.getParameters().set(0, new Parameter(new ArrayType(PrimitiveType.intType()), new SimpleName("foo"))); + assertTransformedToString("public A(int[] foo){}", cd); + } + + // ThrownExceptions + + // Body + + // Annotations +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/EnumConstantDeclarationTransformationsTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/EnumConstantDeclarationTransformationsTest.java new file mode 100644 index 0000000..bfadec8 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/EnumConstantDeclarationTransformationsTest.java @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.transformations.ast.body; + +import com.github.javaparser.ast.body.EnumConstantDeclaration; +import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest; +import org.junit.jupiter.api.Test; + +/** + * Transforming EnumConstantDeclaration and verifying the LexicalPreservation works as expected. + */ +class EnumConstantDeclarationTransformationsTest extends AbstractLexicalPreservingTest { + + protected EnumConstantDeclaration consider(String code) { + considerCode("enum A { " + code + " }"); + return cu.getType(0).asEnumDeclaration().getEntries().get(0); + } + + // Name + + @Test + void settingName() { + EnumConstantDeclaration ecd = consider("A"); + ecd.setName("B"); + assertTransformedToString("B", ecd); + } + + // Annotations + + // Javadoc + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/EnumDeclarationTransformationsTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/EnumDeclarationTransformationsTest.java new file mode 100644 index 0000000..a2fd31a --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/EnumDeclarationTransformationsTest.java @@ -0,0 +1,97 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.transformations.ast.body; + +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.EnumConstantDeclaration; +import com.github.javaparser.ast.body.EnumDeclaration; +import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.ast.Modifier.Keyword.PROTECTED; +import static com.github.javaparser.ast.Modifier.Keyword.PUBLIC; +import static com.github.javaparser.ast.Modifier.createModifierList; +import static com.github.javaparser.utils.Utils.SYSTEM_EOL; + +/** + * Transforming EnumDeclaration and verifying the LexicalPreservation works as expected. + */ +class EnumDeclarationTransformationsTest extends AbstractLexicalPreservingTest { + + protected EnumDeclaration consider(String code) { + considerCode(code); + return cu.getType(0).asEnumDeclaration(); + } + + // Name + + @Test + void settingName() { + EnumDeclaration cid = consider("enum A { E1, E2 }"); + cid.setName("B"); + assertTransformedToString("enum B { E1, E2 }", cid); + } + + // implementedTypes + + // Modifiers + + @Test + void addingModifiers() { + EnumDeclaration ed = consider("enum A { E1, E2 }"); + ed.setModifiers(createModifierList(PUBLIC)); + assertTransformedToString("public enum A { E1, E2 }", ed); + } + + @Test + void removingModifiers() { + EnumDeclaration ed = consider("public enum A { E1, E2 }"); + ed.setModifiers(new NodeList<>()); + assertTransformedToString("enum A { E1, E2 }", ed); + } + + @Test + void replacingModifiers() { + EnumDeclaration ed = consider("public enum A { E1, E2 }"); + ed.setModifiers(createModifierList(PROTECTED)); + assertTransformedToString("protected enum A { E1, E2 }", ed); + } + + @Test + void addingConstants() { + EnumDeclaration ed = consider("enum A {" + SYSTEM_EOL + + " E1" + SYSTEM_EOL + + "}"); + ed.getEntries().addLast(new EnumConstantDeclaration("E2")); + assertTransformedToString("enum A {" + SYSTEM_EOL + + " E1," + SYSTEM_EOL + + " E2" + SYSTEM_EOL + + "}", ed); + } + + // members + + // Annotations + + // Javadoc + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/FieldDeclarationTransformationsTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/FieldDeclarationTransformationsTest.java new file mode 100644 index 0000000..0be9c35 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/FieldDeclarationTransformationsTest.java @@ -0,0 +1,111 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.transformations.ast.body; + +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.FieldDeclaration; +import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.ast.Modifier.Keyword.PROTECTED; +import static com.github.javaparser.ast.Modifier.Keyword.PUBLIC; +import static com.github.javaparser.ast.Modifier.createModifierList; +import static com.github.javaparser.utils.Utils.SYSTEM_EOL; + +/** + * Transforming FieldDeclaration and verifying the LexicalPreservation works as expected. + */ +class FieldDeclarationTransformationsTest extends AbstractLexicalPreservingTest { + + protected FieldDeclaration consider(String code) { + considerCode("class A { " + code + " }"); + return cu.getType(0).getMembers().get(0).asFieldDeclaration(); + } + + // JavaDoc + + // Modifiers + + @Test + void addingModifiers() { + FieldDeclaration it = consider("int A;"); + it.setModifiers(createModifierList(PUBLIC)); + assertTransformedToString("public int A;", it); + } + + @Test + void removingModifiers() { + FieldDeclaration it = consider("public int A;"); + it.setModifiers(new NodeList<>()); + assertTransformedToString("int A;", it); + } + + @Test + void removingModifiersFromNonPrimitiveType() { + FieldDeclaration it = consider("public String A;"); + it.setModifiers(new NodeList<>()); + assertTransformedToString("String A;", it); + } + + @Test + void replacingModifiers() { + FieldDeclaration it = consider("int A;"); + it.setModifiers(createModifierList(PROTECTED)); + assertTransformedToString("protected int A;", it); + } + + @Test + void changingTypes() { + FieldDeclaration it = consider("int a, b;"); + assertTransformedToString("int a, b;", it); + it.getVariable(0).setType("Xyz"); + assertTransformedToString(" a, b;", it); + it.getVariable(1).setType("Xyz"); + assertTransformedToString("Xyz a, b;", it); + } + + @Test + public void changingNonePrimitiveTypes() { + FieldDeclaration it = consider("String a;"); + it.getVariable(0).setType("Xyz"); + assertTransformedToString("Xyz a;", it); + } + + // Annotations + @Test + void removingAnnotations() { + FieldDeclaration it = consider( SYSTEM_EOL + + "@Annotation" + SYSTEM_EOL + + "public int A;"); + it.getAnnotationByName("Annotation").get().remove(); + assertTransformedToString("public int A;", it); + } + + @Test + void removingAnnotationsWithSpaces() { + FieldDeclaration it = consider( SYSTEM_EOL + + " @Annotation " + SYSTEM_EOL + + "public int A;"); + it.getAnnotationByName("Annotation").get().remove(); + assertTransformedToString("public int A;", it); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/InitializerDeclarationTransformationsTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/InitializerDeclarationTransformationsTest.java new file mode 100644 index 0000000..5d2d5cf --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/InitializerDeclarationTransformationsTest.java @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.transformations.ast.body; + +import com.github.javaparser.ast.body.InitializerDeclaration; +import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest; +import org.junit.jupiter.api.Test; + +/** + * Transforming InitializerDeclaration and verifying the LexicalPreservation works as expected. + */ +class InitializerDeclarationTransformationsTest extends AbstractLexicalPreservingTest { + + protected InitializerDeclaration consider(String code) { + considerCode("class A { " + code + " }"); + return cu.getType(0).getMembers().get(0).asInitializerDeclaration(); + } + + // JavaDoc + + // Body + + // IsStatic + + @Test + void instanceToStatic() { + InitializerDeclaration it = consider("{ /*some comment*/ }"); + it.setStatic(true); + assertTransformedToString("static { /*some comment*/ }", it); + } + + @Test + void staticToInstance() { + InitializerDeclaration it = consider("static { /*some comment*/ }"); + it.setStatic(false); + assertTransformedToString("{ /*some comment*/ }", it); + } + + // Annotations +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/MethodDeclarationTransformationsTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/MethodDeclarationTransformationsTest.java new file mode 100644 index 0000000..421df2c --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/MethodDeclarationTransformationsTest.java @@ -0,0 +1,526 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.transformations.ast.body; + +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.body.Parameter; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.expr.MarkerAnnotationExpr; +import com.github.javaparser.ast.expr.SimpleName; +import com.github.javaparser.ast.expr.StringLiteralExpr; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.ast.type.ArrayType; +import com.github.javaparser.ast.type.PrimitiveType; +import com.github.javaparser.javadoc.Javadoc; +import com.github.javaparser.javadoc.description.JavadocDescription; +import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest; +import com.github.javaparser.printer.lexicalpreservation.LexicalPreservingPrinter; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.StaticJavaParser.parseExpression; +import static com.github.javaparser.StaticJavaParser.parseStatement; +import static com.github.javaparser.ast.Modifier.Keyword.PROTECTED; +import static com.github.javaparser.ast.Modifier.Keyword.PUBLIC; +import static com.github.javaparser.ast.Modifier.createModifierList; +import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol; +import static com.github.javaparser.utils.Utils.SYSTEM_EOL; + +/** + * Transforming MethodDeclaration and verifying the LexicalPreservation works as expected. + */ +class MethodDeclarationTransformationsTest extends AbstractLexicalPreservingTest { + + protected MethodDeclaration consider(String code) { + considerCode("class A { " + code + " }"); + return cu.getType(0).getMembers().get(0).asMethodDeclaration(); + } + + // Name + + @Test + void settingName() { + MethodDeclaration it = consider("void A(){}"); + it.setName("B"); + assertTransformedToString("void B(){}", it); + } + + // JavaDoc + + @Disabled + @Test + void removingDuplicateJavaDocComment() { + // Arrange + considerCode("public class MyClass {" + SYSTEM_EOL + + SYSTEM_EOL + + " /**" + SYSTEM_EOL + + " * Comment A" + SYSTEM_EOL + + " */" + SYSTEM_EOL + + " public void oneMethod() {" + SYSTEM_EOL + + " }" + SYSTEM_EOL + + SYSTEM_EOL + + " /**" + SYSTEM_EOL + + " * Comment A" + SYSTEM_EOL + + " */" + SYSTEM_EOL + + " public void anotherMethod() {" + SYSTEM_EOL + + " }" + SYSTEM_EOL + + "}" + + SYSTEM_EOL); + + MethodDeclaration methodDeclaration = cu.findAll(MethodDeclaration.class).get(1); + + // Act + methodDeclaration.removeComment(); + + // Assert + String result = LexicalPreservingPrinter.print(cu.findCompilationUnit().get()); + assertEqualsStringIgnoringEol("public class MyClass {\n" + + "\n" + + " /**\n" + + " * Comment A\n" + + " */\n" + + " public void oneMethod() {\n" + + " }\n" + + "\n" + + " public void anotherMethod() {\n" + + " }\n" + + "}\n", result); + } + + @Disabled + @Test + void replacingDuplicateJavaDocComment() { + // Arrange + considerCode("public class MyClass {" + SYSTEM_EOL + + SYSTEM_EOL + + " /**" + SYSTEM_EOL + + " * Comment A" + SYSTEM_EOL + + " */" + SYSTEM_EOL + + " public void oneMethod() {" + SYSTEM_EOL + + " }" + SYSTEM_EOL + + SYSTEM_EOL + + " /**" + SYSTEM_EOL + + " * Comment A" + SYSTEM_EOL + + " */" + SYSTEM_EOL + + " public void anotherMethod() {" + SYSTEM_EOL + + " }" + SYSTEM_EOL + + "}" + + SYSTEM_EOL); + + MethodDeclaration methodDeclaration = cu.findAll(MethodDeclaration.class).get(1); + + // Act + Javadoc javadoc = new Javadoc(JavadocDescription.parseText("Change Javadoc")); + methodDeclaration.setJavadocComment("", javadoc); + + // Assert + String result = LexicalPreservingPrinter.print(cu.findCompilationUnit().get()); + assertEqualsStringIgnoringEol("public class MyClass {\n" + + "\n" + + " /**\n" + + " * Comment A\n" + + " */\n" + + " public void oneMethod() {\n" + + " }\n" + + "\n" + + " /**\n" + + " * Change Javadoc\n" + + " */\n" + + " public void anotherMethod() {\n" + + " }\n" + + "}\n", result); + } + + // Comments + + @Disabled + @Test + void removingDuplicateComment() { + // Arrange + considerCode("public class MyClass {" + SYSTEM_EOL + + SYSTEM_EOL + + " /*" + SYSTEM_EOL + + " * Comment A" + SYSTEM_EOL + + " */" + SYSTEM_EOL + + " public void oneMethod() {" + SYSTEM_EOL + + " }" + SYSTEM_EOL + + SYSTEM_EOL + + " /*" + SYSTEM_EOL + + " * Comment A" + SYSTEM_EOL + + " */" + SYSTEM_EOL + + " public void anotherMethod() {" + SYSTEM_EOL + + " }" + SYSTEM_EOL + + "}" + + SYSTEM_EOL); + + MethodDeclaration methodDeclaration = cu.findAll(MethodDeclaration.class).get(1); + + // Act + methodDeclaration.removeComment(); + + // Assert + String result = LexicalPreservingPrinter.print(cu.findCompilationUnit().get()); + assertEqualsStringIgnoringEol("public class MyClass {\n" + + "\n" + + " /*\n" + + " * Comment A\n" + + " */\n" + + " public void oneMethod() {\n" + + " }\n" + + "\n" + + " public void anotherMethod() {\n" + + " }\n" + + "}\n", result); + } + + // Modifiers + + @Test + void addingModifiers() { + MethodDeclaration it = consider("void A(){}"); + it.setModifiers(createModifierList(PUBLIC)); + assertTransformedToString("public void A(){}", it); + } + + @Test + void removingModifiers() { + MethodDeclaration it = consider("public void A(){}"); + it.setModifiers(new NodeList<>()); + assertTransformedToString("void A(){}", it); + } + + @Test + void removingModifiersWithExistingAnnotationsShort() { + MethodDeclaration it = consider("@Override public void A(){}"); + it.setModifiers(new NodeList<>()); + assertTransformedToString("@Override void A(){}", it); + } + + @Test + void removingPublicModifierFromPublicStaticMethod() { + MethodDeclaration it = consider("public static void a(){}"); + it.removeModifier(Modifier.Keyword.PUBLIC); + assertTransformedToString("static void a(){}", it); + } + + @Test + void removingModifiersWithExistingAnnotations() { + considerCode( + "class X {" + SYSTEM_EOL + + " @Test" + SYSTEM_EOL + + " public void testCase() {" + SYSTEM_EOL + + " }" + SYSTEM_EOL + + "}" + SYSTEM_EOL + ); + + cu.getType(0).getMethods().get(0).setModifiers(new NodeList<>()); + + String result = LexicalPreservingPrinter.print(cu); + assertEqualsStringIgnoringEol("class X {\n" + + " @Test\n" + + " void testCase() {\n" + + " }\n" + + "}\n", result); + } + + @Test + void removingModifiersWithExistingAnnotations_withVariableNumberOfSeparator() { + considerCode( + "class X {" + SYSTEM_EOL + + " @Test" + SYSTEM_EOL + + " public void testCase() {" + SYSTEM_EOL + + " }" + SYSTEM_EOL + + "}" + SYSTEM_EOL + ); + + cu.getType(0).getMethods().get(0).setModifiers(new NodeList<>()); + + String result = LexicalPreservingPrinter.print(cu.findCompilationUnit().get()); + assertEqualsStringIgnoringEol( + "class X {\n" + + " @Test\n" + + " void testCase() {\n" + + " }\n" + + "}\n", result); + } + + @Test + void replacingModifiers() { + MethodDeclaration it = consider("public void A(){}"); + it.setModifiers(createModifierList(PROTECTED)); + assertTransformedToString("protected void A(){}", it); + } + + @Test + void replacingModifiersWithExistingAnnotationsShort() { + MethodDeclaration it = consider("@Override public void A(){}"); + it.setModifiers(createModifierList(PROTECTED)); + assertTransformedToString("@Override protected void A(){}", it); + } + + @Test + void replacingModifiersWithExistingAnnotations() { + considerCode( + "class X {" + SYSTEM_EOL + + " @Test" + SYSTEM_EOL + + " public void testCase() {" + SYSTEM_EOL + + " }" + SYSTEM_EOL + + "}" + SYSTEM_EOL + ); + + cu.getType(0).getMethods().get(0).setModifiers(createModifierList(PROTECTED)); + + String result = LexicalPreservingPrinter.print(cu.findCompilationUnit().get()); + assertEqualsStringIgnoringEol("class X {\n" + + " @Test\n" + + " protected void testCase() {\n" + + " }\n" + + "}\n", result); + } + + // Parameters + + @Test + void addingParameters() { + MethodDeclaration it = consider("void foo(){}"); + it.addParameter(PrimitiveType.doubleType(), "d"); + assertTransformedToString("void foo(double d){}", it); + } + + @Test + void removingOnlyParameter() { + MethodDeclaration it = consider("public void foo(double d){}"); + it.getParameters().remove(0); + assertTransformedToString("public void foo(){}", it); + } + + @Test + void removingFirstParameterOfMany() { + MethodDeclaration it = consider("public void foo(double d, float f){}"); + it.getParameters().remove(0); + assertTransformedToString("public void foo(float f){}", it); + } + + @Test + void removingLastParameterOfMany() { + MethodDeclaration it = consider("public void foo(double d, float f){}"); + it.getParameters().remove(1); + assertTransformedToString("public void foo(double d){}", it); + } + + @Test + void replacingOnlyParameter() { + MethodDeclaration it = consider("public void foo(float f){}"); + it.getParameters().set(0, new Parameter(new ArrayType(PrimitiveType.intType()), new SimpleName("foo"))); + assertTransformedToString("public void foo(int[] foo){}", it); + } + + // ThrownExceptions + + // Body + + // Annotations + @Test + void addingToExistingAnnotations() { + considerCode( + "class X {" + SYSTEM_EOL + + " @Test" + SYSTEM_EOL + + " public void testCase() {" + SYSTEM_EOL + + " }" + SYSTEM_EOL + + "}" + SYSTEM_EOL + ); + + cu.getType(0).getMethods().get(0).addSingleMemberAnnotation( + "org.junit.Ignore", + new StringLiteralExpr("flaky test")); + + String result = LexicalPreservingPrinter.print(cu.findCompilationUnit().get()); + assertEqualsStringIgnoringEol("class X {\n" + + " @Test\n" + + " @org.junit.Ignore(\"flaky test\")\n" + + " public void testCase() {\n" + + " }\n" + + "}\n", result); + } + + @Test + void addingAnnotationsNoModifiers() { + considerCode( + "class X {" + SYSTEM_EOL + + " void testCase() {" + SYSTEM_EOL + + " }" + SYSTEM_EOL + + "}" + SYSTEM_EOL + ); + + cu.getType(0).getMethods().get(0).addMarkerAnnotation("Test"); + cu.getType(0).getMethods().get(0).addMarkerAnnotation("Override"); + + String result = LexicalPreservingPrinter.print(cu.findCompilationUnit().get()); + assertEqualsStringIgnoringEol("class X {\n" + + " @Test\n" + + " @Override\n" + + " void testCase() {\n" + + " }\n" + + "}\n", result); + } + + @Test + void replacingAnnotations() { + considerCode( + "class X {" + SYSTEM_EOL + + " @Override" + SYSTEM_EOL + + " public void testCase() {" + SYSTEM_EOL + + " }" + SYSTEM_EOL + + "}" + SYSTEM_EOL + ); + + cu.getType(0).getMethods().get(0).setAnnotations(new NodeList<>(new MarkerAnnotationExpr("Test"))); + + String result = LexicalPreservingPrinter.print(cu.findCompilationUnit().get()); + assertEqualsStringIgnoringEol( + "class X {\n" + + " @Test\n" + + " public void testCase() {\n" + + " }\n" + + "}\n", result); + } + + @Test + void addingAnnotationsShort() { + MethodDeclaration it = consider("void testMethod(){}"); + it.addMarkerAnnotation("Override"); + assertTransformedToString( + "@Override" + SYSTEM_EOL + + "void testMethod(){}", it); + } + + // This test case was disabled because we cannot resolve this case for now + // because indentation before the removed annotation is not part + // of difference elements (see removingAnnotationsWithSpaces too) + @Disabled + @Test + void removingAnnotations() { + considerCode( + "class X {" + SYSTEM_EOL + + " @Override" + SYSTEM_EOL + + " public void testCase() {" + SYSTEM_EOL + + " }" + SYSTEM_EOL + + "}" + SYSTEM_EOL + ); + + cu.getType(0).getMethods().get(0).getAnnotationByName("Override").get().remove(); + + String result = LexicalPreservingPrinter.print(cu); + assertEqualsStringIgnoringEol( + "class X {\n" + + " public void testCase() {\n" + + " }\n" + + "}\n", result); + } + + @Disabled + @Test + void removingAnnotationsWithSpaces() { + considerCode( + "class X {" + SYSTEM_EOL + + " @Override " + SYSTEM_EOL + + " public void testCase() {" + SYSTEM_EOL + + " }" + SYSTEM_EOL + + "}" + SYSTEM_EOL + ); + + cu.getType(0).getMethods().get(0).getAnnotationByName("Override").get().remove(); + + String result = LexicalPreservingPrinter.print(cu); + assertEqualsStringIgnoringEol( + "class X {\n" + + " public void testCase() {\n" + + " }\n" + + "}\n", result); + } + + @Test + public void addingModifiersWithExistingAnnotationsShort() { + MethodDeclaration it = consider("@Override void A(){}"); + it.setModifiers(NodeList.nodeList(Modifier.publicModifier(), Modifier.finalModifier())); + assertTransformedToString("@Override public final void A(){}", it); + } + + @Test + public void addingModifiersWithExistingAnnotations() { + considerCode( + "class X {" + SYSTEM_EOL + + " @Test" + SYSTEM_EOL + + " void testCase() {" + SYSTEM_EOL + + " }" + SYSTEM_EOL + + "}" + SYSTEM_EOL + ); + + cu.getType(0).getMethods().get(0).addModifier(Modifier.finalModifier().getKeyword(), Modifier.publicModifier().getKeyword()); + + String result = LexicalPreservingPrinter.print(cu.findCompilationUnit().get()); + assertEqualsStringIgnoringEol("class X {\n" + + " @Test\n" + + " final public void testCase() {\n" + + " }\n" + + "}\n", result); + } + + @Test + public void parseAndPrintAnonymousClassExpression() { + Expression expression = parseExpression("new Object() {" + SYSTEM_EOL + + "}"); + String expected = "new Object() {" + SYSTEM_EOL + + "}"; + assertTransformedToString(expected, expression); + } + + @Test + public void parseAndPrintAnonymousClassStatement() { + Statement statement = parseStatement("Object anonymous = new Object() {" + SYSTEM_EOL + + "};"); + String expected = "Object anonymous = new Object() {" + SYSTEM_EOL + + "};"; + assertTransformedToString(expected, statement); + } + + @Test + public void replaceBodyShouldNotBreakAnonymousClasses() { + MethodDeclaration it = consider("public void method() { }"); + it.getBody().ifPresent(body -> { + Statement statement = parseStatement("Object anonymous = new Object() {" + SYSTEM_EOL + + "};"); + NodeList statements = new NodeList<>(); + statements.add(statement); + body.setStatements(statements); + }); + + String expected = "public void method() {" + SYSTEM_EOL + + " Object anonymous = new Object() {" + SYSTEM_EOL + + " };" + SYSTEM_EOL + + "}"; + assertTransformedToString(expected, it); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/OperatorTransformationsTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/OperatorTransformationsTest.java new file mode 100644 index 0000000..46bafc7 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/OperatorTransformationsTest.java @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.transformations.ast.body; + +import com.github.javaparser.ast.expr.IntegerLiteralExpr; +import com.github.javaparser.ast.expr.NameExpr; +import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest; +import org.junit.jupiter.api.Test; + +/** + * Transforming BinaryExpr and verifying the LexicalPreservation works as expected. + */ +class OperatorTransformationsTest extends AbstractLexicalPreservingTest { + + @Test + void binaryExpressionOperator() { + considerExpression("a && b"); + expression.asBinaryExpr().setRight(new NameExpr("c")); + assertTransformedToString("a && c", expression); + } + + @Test + void unaryExpressionOperator() { + considerExpression("!a"); + expression.asUnaryExpr().setExpression(new NameExpr("b")); + assertTransformedToString("!b", expression); + } + + @Test + void assignExpressionOperator() { + considerExpression("a <<= 1"); + expression.asAssignExpr().setValue(new IntegerLiteralExpr(2)); + assertTransformedToString("a <<= 2", expression); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/StatementTransformationsTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/StatementTransformationsTest.java new file mode 100644 index 0000000..859b87c --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/StatementTransformationsTest.java @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.transformations.ast.body; + +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.expr.NameExpr; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest; +import com.github.javaparser.printer.lexicalpreservation.LexicalPreservingPrinter; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.StaticJavaParser.parseStatement; + +/** + * Transforming Statement and verifying the LexicalPreservation works as expected. + */ +class StatementTransformationsTest extends AbstractLexicalPreservingTest { + + Statement consider(String code) { + Statement statement = parseStatement(code); + LexicalPreservingPrinter.setup(statement); + return statement; + } + + @Test + void ifStmtTransformation() { + Statement stmt = consider("if (a) {} else {}"); + stmt.asIfStmt().setCondition(new NameExpr("b")); + assertTransformedToString("if (b) {} else {}", stmt); + } + + @Test + void switchEntryCsmHasTrailingUnindent() { + Statement stmt = consider("switch (a) { case 1: a; a; }"); + NodeList statements = stmt.asSwitchStmt().getEntry(0).getStatements(); + statements.set(1, statements.get(1).clone()); // clone() to force replacement + assertTransformedToString("switch (a) { case 1: a; a; }", stmt); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/quality/PreconditionsTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/quality/PreconditionsTest.java new file mode 100644 index 0000000..1a6094b --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/quality/PreconditionsTest.java @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.quality; + +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.quality.Preconditions.checkArgument; +import static com.github.javaparser.quality.Preconditions.checkNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class PreconditionsTest { + + @Test + void checkArgument_withTrueExpression() { + checkArgument(true); + } + + @Test + void checkArgument_withFalseExpression() { + assertThrows(IllegalArgumentException.class, () -> checkArgument(false)); + } + + @Test + void checkNotNull_withNonNull() { + checkNotNull(new Object()); + } + + @Test + void checkNotNull_withNull() { + assertThrows(IllegalArgumentException.class, () -> checkNotNull(null)); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/remove/NodeRemovalTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/remove/NodeRemovalTest.java new file mode 100644 index 0000000..4d80274 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/remove/NodeRemovalTest.java @@ -0,0 +1,124 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.remove; + +import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; + +import org.junit.jupiter.api.Test; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.FieldDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest; +import com.github.javaparser.printer.lexicalpreservation.LexicalPreservingPrinter; + +class NodeRemovalTest extends AbstractLexicalPreservingTest{ + + private final CompilationUnit compilationUnit = new CompilationUnit(); + + @Test + void testRemoveClassFromCompilationUnit() { + ClassOrInterfaceDeclaration testClass = compilationUnit.addClass("test"); + assertEquals(1, compilationUnit.getTypes().size()); + boolean remove = testClass.remove(); + assertTrue(remove); + assertEquals(0, compilationUnit.getTypes().size()); + } + + @Test + void testRemoveFieldFromClass() { + ClassOrInterfaceDeclaration testClass = compilationUnit.addClass("test"); + + FieldDeclaration addField = testClass.addField(String.class, "test"); + assertEquals(1, testClass.getMembers().size()); + boolean remove = addField.remove(); + assertTrue(remove); + assertEquals(0, testClass.getMembers().size()); + } + + @Test + void testRemoveStatementFromMethodBody() { + ClassOrInterfaceDeclaration testClass = compilationUnit.addClass("testC"); + + MethodDeclaration addMethod = testClass.addMethod("testM"); + BlockStmt methodBody = addMethod.createBody(); + Statement addStatement = methodBody.addAndGetStatement("test"); + assertEquals(1, methodBody.getStatements().size()); + boolean remove = addStatement.remove(); + assertTrue(remove); + assertEquals(0, methodBody.getStatements().size()); + } + + @Test + void testRemoveStatementFromMethodBodyWithLexicalPreservingPrinter() { + considerStatement( + "{\r\n" + + " log.error(\"context\", e);\r\n" + + " log.error(\"context\", e);\r\n" + + " throw new ApplicationException(e);\r\n" + + "}\r\n"); + BlockStmt bstmt = statement.asBlockStmt(); + List children = bstmt.getChildNodes(); + remove(children.get(0)); + assertTrue(children.size() == 2); + remove(children.get(0)); + assertTrue(children.size() == 1); + assertTrue(children.stream().allMatch(n -> n.getParentNode() != null)); + } + + @Test + // issue 1638 + public void removingAnnotationsFormattedWithAdditionalSpaces() { + considerCode( + "class X {\n" + + " @Override\n" + + " public void testCase() {\n" + + " }\n" + + "}" + ); + + cu.getType(0).getMethods().get(0).getAnnotationByName("Override").get().remove(); + + String result = LexicalPreservingPrinter.print(cu.findCompilationUnit().get()); + assertEqualsStringIgnoringEol( + "class X {\n" + + " public void testCase() {\n" + + " }\n" + + "}", result); + } + + // remove the node and parent's node until response is true + boolean remove(Node node) { + boolean result = node.remove(); + if (!result && node.getParentNode().isPresent()) + result = remove(node.getParentNode().get()); + return result; + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/utils/CodeGenerationUtilsTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/utils/CodeGenerationUtilsTest.java new file mode 100644 index 0000000..2bf652a --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/utils/CodeGenerationUtilsTest.java @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.utils; + +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.utils.CodeGenerationUtils.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class CodeGenerationUtilsTest { + @Test + void setters() { + assertEquals("setValue", setterName("value")); + assertEquals("setBlue", setterName("isBlue")); + } + + @Test + void getters() { + assertEquals("getValue", getterName(Object.class, "value")); + assertEquals("isBlue", getterName(boolean.class, "isBlue")); + assertEquals("isBlue", getterName(boolean.class, "blue")); + assertEquals("getBlue", getterName(Boolean.class, "blue")); + assertEquals("getIsBlue", getterName(Boolean.class, "isBlue")); + } + + @Test + void testGetterToPropertyName() { + assertEquals("value", getterToPropertyName("getValue")); + assertEquals("blue", getterToPropertyName("isBlue")); + assertEquals("value", getterToPropertyName("hasValue")); + + IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, + () -> getterToPropertyName("value")); + assertEquals("Unexpected getterName 'value'", thrown.getMessage()); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/utils/ExtractingVisitors.java b/javaparser-core-testing/src/test/java/com/github/javaparser/utils/ExtractingVisitors.java new file mode 100644 index 0000000..9551986 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/utils/ExtractingVisitors.java @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.utils; + +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.expr.CharLiteralExpr; +import com.github.javaparser.ast.visitor.GenericVisitor; +import com.github.javaparser.ast.visitor.GenericVisitorAdapter; + +import java.util.ArrayList; +import java.util.List; + +public final class ExtractingVisitors { + + private static List extract(Node node, GenericVisitor> extractCharLiteralExprs) { + List list = new ArrayList<>(); + node.accept(extractCharLiteralExprs, list); + return list; + } + + public static List extractCharLiteralExprs(Node node) { + return extract(node, new GenericVisitorAdapter>() { + @Override + public Void visit(CharLiteralExpr n, List accumulator) { + accumulator.add(n); + return super.visit(n, accumulator); + } + }); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/utils/LineSeparatorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/utils/LineSeparatorTest.java new file mode 100644 index 0000000..7059dd7 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/utils/LineSeparatorTest.java @@ -0,0 +1,117 @@ +/* + * Copyright (C) 2013-2024 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.utils; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +/** + * @author Roger Howell + */ +class LineSeparatorTest { + + @Test + void escaped() { + assertEquals("\\r", LineSeparator.CR.asEscapedString()); + assertEquals("\\n", LineSeparator.LF.asEscapedString()); + assertEquals("\\r\\n", LineSeparator.CRLF.asEscapedString()); + } + + @Test + void lookup() { + assertEquals(LineSeparator.CR, LineSeparator.lookup("\r").get()); + assertEquals(LineSeparator.LF, LineSeparator.lookup("\n").get()); + assertEquals(LineSeparator.CRLF, LineSeparator.lookup("\r\n").get()); + + assertFalse(LineSeparator.lookup("").isPresent()); + assertFalse(LineSeparator.lookup(" ").isPresent()); + assertFalse(LineSeparator.lookup("\\r").isPresent()); + assertFalse(LineSeparator.lookup("\\n").isPresent()); + assertFalse(LineSeparator.lookup(" \\r").isPresent()); + assertFalse(LineSeparator.lookup(" \\n").isPresent()); + assertFalse(LineSeparator.lookup("\\r ").isPresent()); + assertFalse(LineSeparator.lookup("\\n ").isPresent()); + assertFalse(LineSeparator.lookup("test 123 123").isPresent()); + assertFalse(LineSeparator.lookup("\r \n").isPresent()); + assertFalse(LineSeparator.lookup("\\r \\n").isPresent()); + } + + @Test + void lookupEscaped() { + assertEquals(LineSeparator.CR, LineSeparator.lookupEscaped("\\r").get()); + assertEquals(LineSeparator.LF, LineSeparator.lookupEscaped("\\n").get()); + assertEquals(LineSeparator.CRLF, LineSeparator.lookupEscaped("\\r\\n").get()); + + assertFalse(LineSeparator.lookupEscaped("").isPresent()); + assertFalse(LineSeparator.lookupEscaped(" ").isPresent()); + assertFalse(LineSeparator.lookupEscaped("\r").isPresent()); + assertFalse(LineSeparator.lookupEscaped("\n").isPresent()); + assertFalse(LineSeparator.lookupEscaped(" \r").isPresent()); + assertFalse(LineSeparator.lookupEscaped(" \n").isPresent()); + assertFalse(LineSeparator.lookupEscaped("\r ").isPresent()); + assertFalse(LineSeparator.lookupEscaped("\n ").isPresent()); + assertFalse(LineSeparator.lookupEscaped("test 123 123").isPresent()); + assertFalse(LineSeparator.lookupEscaped("\r \n").isPresent()); + assertFalse(LineSeparator.lookupEscaped("\\r \\n").isPresent()); + } + + @Test + void detect() { + assertEquals(LineSeparator.CR, LineSeparator.detect("\r")); + assertEquals(LineSeparator.LF, LineSeparator.detect("\n")); + assertEquals(LineSeparator.CRLF, LineSeparator.detect("\r\n")); + + assertEquals(LineSeparator.NONE, LineSeparator.detect("")); + assertEquals(LineSeparator.NONE, LineSeparator.detect("test 123 123")); + + assertEquals(LineSeparator.MIXED, LineSeparator.detect("\r \n")); + } + + @Test + void testToString() { + assertEquals("\r", LineSeparator.CR.asRawString()); + assertEquals("\n", LineSeparator.LF.asRawString()); + assertEquals("\r\n", LineSeparator.CRLF.asRawString()); + + // Note that this represents an "arbitrary" line ending -- this test is to highlight any time that it changes. + assertEquals("\n", LineSeparator.ARBITRARY.asRawString()); + } + + @Test + void values() { + assertEquals(8, LineSeparator.values().length); + } + + @Test + void valueOf() { + assertEquals(LineSeparator.CR, LineSeparator.valueOf("CR")); + assertEquals(LineSeparator.LF, LineSeparator.valueOf("LF")); + assertEquals(LineSeparator.CRLF, LineSeparator.valueOf("CRLF")); + assertEquals(LineSeparator.NONE, LineSeparator.valueOf("NONE")); + assertEquals(LineSeparator.MIXED, LineSeparator.valueOf("MIXED")); + assertEquals(LineSeparator.SYSTEM, LineSeparator.valueOf("SYSTEM")); + assertEquals(LineSeparator.UNKNOWN, LineSeparator.valueOf("UNKNOWN")); + assertEquals(LineSeparator.ARBITRARY, LineSeparator.valueOf("ARBITRARY")); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/utils/LogTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/utils/LogTest.java new file mode 100644 index 0000000..0d94183 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/utils/LogTest.java @@ -0,0 +1,89 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.utils; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.function.Supplier; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class LogTest { + private static class TestAdapter implements Log.Adapter { + String output = ""; + + @Override + public void info(Supplier messageSupplier) { + output += "I" + messageSupplier.get(); + } + + @Override + public void trace(Supplier messageSupplier) { + output += "T" + messageSupplier.get(); + } + + @Override + public void error(Supplier throwableSupplier, Supplier messageSupplier) { + Throwable throwable = throwableSupplier.get(); + String s = messageSupplier.get(); + output += "E" + s + "M" + (throwable == null ? "null" : throwable.getMessage()); + } + } + + private TestAdapter testAdapter = new TestAdapter(); + + @BeforeEach + void setAdapter() { + Log.setAdapter(testAdapter); + } + + @AfterEach + void resetAdapter() { + Log.setAdapter(new Log.SilentAdapter()); + } + + @Test + void testTrace() { + Log.trace("abc"); + Log.trace("a%sc%s", () -> "b", () -> "d"); + assertEquals("TabcTabcd", testAdapter.output); + } + + @Test + void testInfo() { + Log.info("abc"); + Log.info("a%sc", () -> "b"); + assertEquals("IabcIabc", testAdapter.output); + } + + @Test + void testError() { + Log.error("abc"); + Log.error("a%sc", () -> "b"); + Log.error(new Throwable("!!!"), "abc"); + Log.error(new Throwable("!!!"), "a%sc%s", () -> "b", () -> "d"); + Log.error(new Throwable("!!!")); + assertEquals("EabcMnullEabcMnullEabcM!!!EabcdM!!!EnullM!!!", testAdapter.output); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/utils/PairTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/utils/PairTest.java new file mode 100644 index 0000000..ee9a253 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/utils/PairTest.java @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.utils; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class PairTest { + @Test + void testToString() { + Pair pair = new Pair<>("abc", "def"); + + assertEquals("", pair.toString()); + } + + @Test + void testToStringNulls() { + Pair pair = new Pair<>(null, null); + + assertEquals("", pair.toString()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/utils/ParserCollectionStrategyTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/utils/ParserCollectionStrategyTest.java new file mode 100644 index 0000000..1d88d34 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/utils/ParserCollectionStrategyTest.java @@ -0,0 +1,198 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.utils; + +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.CompilationUnit; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; + +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_9; +import static com.github.javaparser.utils.CodeGenerationUtils.mavenModuleRoot; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ParserCollectionStrategyTest { + + private final ParserCollectionStrategy parserCollectionStrategy = new ParserCollectionStrategy( + new ParserConfiguration().setLanguageLevel(JAVA_9)); + + @Test + void getSourceRoots() { + final Path root = mavenModuleRoot(ParserCollectionStrategyTest.class).resolve("").getParent(); + final ProjectRoot projectRoot = parserCollectionStrategy.collect(root); + + assertThat(projectRoot.getSourceRoots()).isNotEmpty(); + assertThat(projectRoot.getSourceRoot(root.resolve("javaparser-core/src/main/java"))).isNotEmpty(); + assertThat(projectRoot.getSourceRoot(root.resolve("javaparser-core-generators/src/main/java"))).isNotEmpty(); + assertThat(projectRoot.getSourceRoot(root.resolve("javaparser-core-metamodel-generator/src/main/java"))).isNotEmpty(); + assertThat(projectRoot.getSourceRoot(root.resolve("javaparser-symbol-solver-core/src/main/java"))).isNotEmpty(); + } + + + @Test + void rootAreFound_singleJavaFileInPackage() { + final Path root = mavenModuleRoot(SourceRootTest.class).resolve("src/test/resources/com/github/javaparser/utils/projectroot/issue2615/without_module_info"); + final ProjectRoot projectRoot = parserCollectionStrategy.collect(root); + + List sourceRoots = projectRoot.getSourceRoots(); + sourceRoots.forEach(System.out::println); + + assertThat(sourceRoots).map(SourceRoot::getRoot).extracting(Path::getFileName).map(Path::getFileName).map(Path::toString) + .containsExactly("without_module_info"); + } + + @Test + void rootsAreFound_withModuleInfoAndJavaFileInPackage() { + final Path root = mavenModuleRoot(SourceRootTest.class).resolve("src/test/resources/com/github/javaparser/utils/projectroot/issue2615/with_module_info"); + final ProjectRoot projectRoot = parserCollectionStrategy.collect(root); + + List sourceRoots = projectRoot.getSourceRoots(); + sourceRoots.forEach(System.out::println); + + assertThat(sourceRoots).map(SourceRoot::getRoot).extracting(Path::getFileName).map(Path::getFileName).map(Path::toString) + .containsExactly("with_module_info"); + } + + @Test + void rootsAreFound_withModuleInfoInRootAndJavaFileInPackage() { + final Path root = mavenModuleRoot(SourceRootTest.class).resolve("src/test/resources/com/github/javaparser/utils/projectroot/issue2615/with_module_info_in_root"); + final ProjectRoot projectRoot = parserCollectionStrategy.collect(root); + + List sourceRoots = projectRoot.getSourceRoots(); + sourceRoots.forEach(System.out::println); + + assertThat(sourceRoots).map(SourceRoot::getRoot).extracting(Path::getFileName).map(Path::getFileName).map(Path::toString) + .containsExactly("with_module_info_in_root"); + } + + @Test + void rootsAreFound_parentOfMultipleSourceRootsWithAndWithoutModuleInfo() { + final Path root = mavenModuleRoot(SourceRootTest.class).resolve("src/test/resources/com/github/javaparser/utils/projectroot/issue2615"); + final ProjectRoot projectRoot = parserCollectionStrategy.collect(root); + + List sourceRoots = projectRoot.getSourceRoots(); + +// for (SourceRoot sourceRoot : sourceRoots) { +// sourceRoot.getRoot().normalize().endsWith("with_module_info"); +// System.out.println(sourceRoot); +// } + + assertEquals(3, sourceRoots.size()); + } + + + @Test + void manualInspectionOfSystemOut_callbackOnSourceRootParse_parentOfMultipleSourceRootsWithAndWithoutModuleInfo() { + final Path root = mavenModuleRoot(SourceRootTest.class).resolve("src/test/resources/com/github/javaparser/utils/projectroot/issue2615"); + final ProjectRoot projectRoot = parserCollectionStrategy.collect(root); + + Callback cb = new Callback(); + + final List sourceRoots = projectRoot.getSourceRoots(); + assertThat(sourceRoots).map(SourceRoot::getRoot).extracting(Path::getFileName).map(Path::getFileName).map(Path::toString) + .containsExactlyInAnyOrder("with_module_info_in_root", "without_module_info", "with_module_info"); + + sourceRoots.forEach(sourceRoot -> { + try { + sourceRoot.parse("", cb); + } catch (IOException e) { + System.err.println("IOException: " + e); + } + }); + } + + @Test + void manualInspectionOfSystemOut_callbackOnSourceRootParse_singleJavaFileInPackage() { + final Path root = mavenModuleRoot(SourceRootTest.class).resolve("src/test/resources/com/github/javaparser/utils/projectroot/issue2615/without_module_info"); + final ProjectRoot projectRoot = parserCollectionStrategy.collect(root); + + Callback cb = new Callback(); + + final List sourceRoots = projectRoot.getSourceRoots(); + assertThat(sourceRoots).map(SourceRoot::getRoot).extracting(Path::getFileName).map(Path::getFileName).map(Path::toString) + .containsExactlyInAnyOrder("without_module_info"); + + sourceRoots.forEach(sourceRoot -> { + try { + sourceRoot.parse("", cb); + } catch (IOException e) { + System.err.println("IOException: " + e); + } + }); + } + + @Test + void manualInspectionOfSystemOut_callbackOnSourceRootParse_withModuleInfoAndJavaFileInPackage() { + final Path root = mavenModuleRoot(SourceRootTest.class).resolve("src/test/resources/com/github/javaparser/utils/projectroot/issue2615/with_module_info"); + final ProjectRoot projectRoot = parserCollectionStrategy.collect(root); + + Callback cb = new Callback(); + + final List sourceRoots = projectRoot.getSourceRoots(); + assertThat(sourceRoots).map(SourceRoot::getRoot).extracting(Path::getFileName).map(Path::getFileName).map(Path::toString) + .containsExactlyInAnyOrder("with_module_info"); + + sourceRoots.forEach(sourceRoot -> { + try { + sourceRoot.parse("", cb); + } catch (IOException e) { + System.err.println("IOException: " + e); + } + }); + } + + @Test + void manualInspectionOfSystemOut_callbackOnSourceRootParse_withModuleInfoInRootAndJavaFileInPackage() { + final Path root = mavenModuleRoot(SourceRootTest.class).resolve("src/test/resources/com/github/javaparser/utils/projectroot/issue2615/with_module_info_in_root"); + final ProjectRoot projectRoot = parserCollectionStrategy.collect(root); + + Callback cb = new Callback(); + + final List sourceRoots = projectRoot.getSourceRoots(); + assertThat(sourceRoots).map(SourceRoot::getRoot).extracting(Path::getFileName).map(Path::getFileName).map(Path::toString) + .containsExactlyInAnyOrder("with_module_info_in_root"); + + sourceRoots.forEach(sourceRoot -> { + try { + sourceRoot.parse("", cb); + } catch (IOException e) { + System.err.println("IOException: " + e); + } + }); + } + + + private static class Callback implements SourceRoot.Callback { + + @Override + public Result process(Path localPath, Path absolutePath, ParseResult result) { + System.out.printf("Found %s%n", absolutePath); + return Result.SAVE; + } + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/utils/PositionUtilsTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/utils/PositionUtilsTest.java new file mode 100644 index 0000000..505ccab --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/utils/PositionUtilsTest.java @@ -0,0 +1,282 @@ +/* + * Copyright (C) 2013-2024 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.utils; + +import com.github.javaparser.StaticJavaParser; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.FieldDeclaration; +import com.github.javaparser.ast.comments.Comment; +import com.github.javaparser.ast.expr.AnnotationExpr; +import com.github.javaparser.ast.expr.SimpleName; +import com.github.javaparser.ast.type.Type; +import org.junit.jupiter.api.Test; + +import static com.github.javaparser.utils.PositionUtils.nodeContains; +import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol; +import static org.junit.jupiter.api.Assertions.*; + +public class PositionUtilsTest { + @Test + public void nodeContains_NoAnnotationsAnywhere_IgnoringAnnotations() { + CompilationUnit cu = StaticJavaParser.parse("class X { int a; }"); + FieldDeclaration field = cu.findFirst(FieldDeclaration.class).get(); + + boolean contains = nodeContains(cu, field, true); + assertTrue(contains); + } + + @Test + public void nodeDoesNotContain_NoAnnotationsAnywhere_IgnoringAnnotations() { + CompilationUnit cu = StaticJavaParser.parse("class X { int a; }"); + FieldDeclaration field = cu.findFirst(FieldDeclaration.class).get(); + + Type fieldType = field.getVariable(0).getType(); + SimpleName fieldName = field.getVariable(0).getName(); + + boolean contains = nodeContains(fieldType, fieldName, true); + assertFalse(contains); + } + + @Test + public void nodeContains_NoAnnotationsAnywhere_IncludeAnnotations() { + CompilationUnit cu = StaticJavaParser.parse("class X { int a; }"); + FieldDeclaration field = cu.findFirst(FieldDeclaration.class).get(); + + boolean contains = nodeContains(cu, field, false); + assertTrue(contains); + } + + @Test + public void nodeDoesNotContain_NoAnnotationsAnywhere_IncludeAnnotations() { + CompilationUnit cu = StaticJavaParser.parse("class X { int a; }"); + FieldDeclaration field = cu.findFirst(FieldDeclaration.class).get(); + + Type fieldType = field.getVariable(0).getType(); + SimpleName fieldName = field.getVariable(0).getName(); + + boolean contains = nodeContains(fieldType, fieldName, false); + assertFalse(contains, "Type and Name are separate branches of the AST, thus should not contain each other."); + } + + @Test + public void nodeContainsAnnotations_IgnoringAnnotations() { + CompilationUnit cu = StaticJavaParser.parse("@A class X {} class Y {}"); + ClassOrInterfaceDeclaration x = cu.getClassByName("X").get(); + ClassOrInterfaceDeclaration y = cu.getClassByName("Y").get(); + + boolean contains = nodeContains(x, y, true); + assertFalse(contains); + } + + @Test + public void nodeContainsAnnotations_WithCommentNodeInTheMiddle_IgnoringAnnotations() { + String code = "" + + "@A\n" + + "/*o*/\n" + + "@B\n" + + "class X {\n" + + "}\n" + + ""; + + CompilationUnit cu = StaticJavaParser.parse(code); + assertEqualsStringIgnoringEol(code, cu.toString(), "Issue with the parsing of the code, not this test."); + + ClassOrInterfaceDeclaration x = cu.getClassByName("X").get(); + AnnotationExpr annotationB = x.getAnnotationByName("B").get(); + + // Comment gets added to the MarkerAnnotationExpr for @B -- correct + Comment o = annotationB.getComment().get(); + assertEquals(annotationB, o.getCommentedNode().get(), "Comment has been added to an unexpected node."); + + boolean contains = nodeContains(x, o, true); + assertFalse(contains); + } + + + @Test + public void nodeContainsAnnotations_WithAnnotationNodeInTheMiddle() { + String code = "" + + "@A\n" + + "@B\n" + + "@C\n" + + "class X {\n" + + "}\n" + + ""; + CompilationUnit cu = StaticJavaParser.parse(code); + assertEqualsStringIgnoringEol(code, cu.toString(), "Issue with the parsing of the code, not this test."); + + final ClassOrInterfaceDeclaration x = cu.getClassByName("X").get(); + final AnnotationExpr annotationA = x.getAnnotationByName("A").get(); + final AnnotationExpr annotationB = x.getAnnotationByName("B").get(); + final AnnotationExpr annotationC = x.getAnnotationByName("C").get(); + + // If including annotations (i.e. NOT ignoring them), all nodes should be included + assertTrue(nodeContains(x, annotationA, false), formatRangeCompareResult(x, annotationA, "X", "A")); + assertTrue(nodeContains(x, annotationB, false), formatRangeCompareResult(x, annotationB, "X", "B")); + assertTrue(nodeContains(x, annotationC, false), formatRangeCompareResult(x, annotationC, "X", "C")); + assertTrue(nodeContains(x, x, false), formatRangeCompareResult(x, x, "X", "X")); + + // If ignoring annotations, only the node itself should be included + assertFalse(nodeContains(x, annotationA, true), formatRangeCompareResult(x, annotationA, "X", "A")); + assertFalse(nodeContains(x, annotationB, true), formatRangeCompareResult(x, annotationB, "X", "B")); + assertFalse(nodeContains(x, annotationC, true), formatRangeCompareResult(x, annotationC, "X", "C")); + assertFalse(nodeContains(x, x, true), formatRangeCompareResult(x, x, "X", "X")); + + } + + private String formatRangeCompareResult(Node x, Node annotationA, String containerId, String otherId) { + return String.format("container range in detected as NOT containing other range: " + + "\n - container (%s): %s" + + "\n - other (%s): %s", + containerId, + x.getRange().get().toString(), + otherId, + annotationA.getRange().get().toString() + ); + } + + @Test + public void nodeContainsAnnotations_WithCommentAtTheEndOfAnnotations_IgnoringAnnotations() { + CompilationUnit cu = StaticJavaParser.parse("@A @B /*o*/ public class X {}"); + ClassOrInterfaceDeclaration x = cu.getClassByName("X").get(); + + // TODO: Should the comment be attached to the SimpleName (as opposed to the ClassOrInterfaceDeclaration?) + SimpleName simpleName = x.getName(); + Comment o = simpleName.getComment().get(); + + //// 0 1 2 2 + //// 123456789012345678901234567890 + //// @A @B /*o*/ public class X {} + //// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // range of x, WITH annotations -- thus contained == TRUE + //// @A @B /*o*/ public class X {} + //// ^^^^^^^^^^^^^^^^^ // range of x, ignoring annotations -- thus contained == FALSE + //// @A @B /*o*/ public class X {} + //// ^^^^^ // range of o + + // TODO: Determine if comments outside the text range of a node are "contained" within a node (part of the subtree, but are printed before). + assertTrue(nodeContains(x, o, false), formatRangeCompareResult(x, o, "X", "o")); + assertFalse(nodeContains(x, o, true), formatRangeCompareResult(x, o, "X", "o")); + + + // FIXME: Both tests currently fail due to the comment being attached to the SimpleName, as opposed to the ClassOrInterfaceDeclaration +// assertEquals(x.getClass(), o.getCommentedNode().get().getClass(), "Comment attached to an unexpected node -- expected to be the ClassOrInterfaceDeclaration"); +// assertEquals(x, o.getCommentedNode().get(), "Comment attached to an unexpected node -- expected to be the ClassOrInterfaceDeclaration"); + + } + + @Test + public void nodeContainsAnnotations_WithCommentAfterTheEnd_IgnoringAnnotations() { + CompilationUnit cu = StaticJavaParser.parse("@A @B public /*o*/ class X {}"); + ClassOrInterfaceDeclaration x = cu.getClassByName("X").get(); + + // TODO: Should the comment be attached to the SimpleName (as opposed to the ClassOrInterfaceDeclaration?) + SimpleName simpleName = x.getName(); + Comment o = simpleName.getComment().get(); + + //// 0 1 2 2 + //// 123456789012345678901234567890 + //// @A @B public /*o*/ class X {} + //// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // range of x, WITH annotations -- thus contained == TRUE + //// @A @B public /*o*/ class X {} + //// ^^^^^^^^^^^^^^^^^^^^^^^ // range of x, ignoring annotations -- thus contained == TRUE + //// @A @B public /*o*/ class X {} + //// ^^^^^ // range of o + + // TODO: Determine if comments outside the text range of a node are "contained" within a node (part of the subtree, but are printed before). + assertTrue(nodeContains(x, o, false), formatRangeCompareResult(x, o, "X", "o")); + assertTrue(nodeContains(x, o, true), formatRangeCompareResult(x, o, "X", "o")); + + // FIXME: Both tests currently fail due to the comment being attached to the SimpleName, as opposed to the ClassOrInterfaceDeclaration +// assertEquals(x.getClass(), o.getCommentedNode().get().getClass(), "Comment attached to an unexpected node -- expected to be the ClassOrInterfaceDeclaration"); +// assertEquals(x, o.getCommentedNode().get(), "Comment attached to an unexpected node -- expected to be the ClassOrInterfaceDeclaration"); + + } + + @Test + public void nodeContainsAnnotations_WithCommentAfterTheEnd_IgnoringAnnotations2() { + CompilationUnit cu = StaticJavaParser.parse("@A @B public class /*o*/ X {}"); + ClassOrInterfaceDeclaration x = cu.getClassByName("X").get(); + + // TODO: Should the comment be attached to the SimpleName (as opposed to the ClassOrInterfaceDeclaration?) + SimpleName simpleName = x.getName(); + Comment o = simpleName.getComment().get(); + + + //// 12345678912345678912345678901 + //// @A @B public class /*o*/ X {} + //// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // range of x, WITH annotations -- thus contained == TRUE + //// @A @B public class /*o*/ X {} + //// ^^^^^^^^^^^^^^^^^^^^^^^ // range of x, ignoring annotations -- thus contained == TRUE + //// @A @B public class /*o*/ X {} + //// ^^^^^ // range of o + + // TODO: Determine if comments outside the text range of a node are "contained" within a node (part of the subtree, but are printed before). + assertTrue(nodeContains(x, o, false), formatRangeCompareResult(x, o, "X", "o")); + assertTrue(nodeContains(x, o, true), formatRangeCompareResult(x, o, "X", "o")); + + assertTrue(o.getCommentedNode().isPresent()); + + // FIXME: Both tests currently fail due to the comment being attached to the SimpleName, as opposed to the ClassOrInterfaceDeclaration +// assertEquals(x.getClass(), o.getCommentedNode().get().getClass(), "Comment attached to an unexpected node -- expected to be the ClassOrInterfaceDeclaration"); +// assertEquals(x, o.getCommentedNode().get(), "Comment attached to an unexpected node -- expected to be the ClassOrInterfaceDeclaration"); + + } + + @Test + public void nodeContainsAnnotations_WithCommentAfterTheEnd_IgnoringAnnotations3() { + CompilationUnit cu = StaticJavaParser.parse("@A @B public class X /*o*/ {}"); + ClassOrInterfaceDeclaration x = cu.getClassByName("X").get(); + +// // TODO: At what point is the declaration supposed to end and the code block begin? Should the block comment move "inside" the code block? +// // cu = +// @A +// @B +// public class X { +// /*o*/ +// } + + // TODO: Should the comment be attached to the SimpleName (as opposed to being attached to null but not orphaned?) + Comment o = cu.getComments().get(0); + + + //// 12345678912345678912345678901 + //// @A @B public class X /*o*/ {} + //// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // range of x, WITH annotations -- thus contained == TRUE + //// @A @B public class X /*o*/ {} + //// ^^^^^^^^^^^^^^^^^^^^^^^ // range of x, ignoring annotations -- thus contained == TRUE + //// @A @B public class X /*o*/ {} + //// ^^^^^ // range of o + + // TODO: Determine if comments outside the text range of a node are "contained" within a node (part of the subtree, but are printed before). + assertTrue(nodeContains(x, o, false), formatRangeCompareResult(x, o, "X", "o")); + assertTrue(nodeContains(x, o, true), formatRangeCompareResult(x, o, "X", "o")); + + // FIXME: Comment is unattached (returns null), but is not considered to be orphaned...? +// assertTrue(o.getCommentedNode().isPresent()); + + // FIXME: Both tests currently fail due to the comment being unattached, as opposed to the ClassOrInterfaceDeclaration +// assertEquals(x.getClass(), o.getCommentedNode().get().getClass(), "Comment attached to an unexpected node -- expected to be the ClassOrInterfaceDeclaration"); +// assertEquals(x, o.getCommentedNode().get(), "Comment attached to an unexpected node -- expected to be the ClassOrInterfaceDeclaration"); + + } +} 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 new file mode 100644 index 0000000..445c5f1 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/utils/SourceRootTest.java @@ -0,0 +1,112 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.utils; + +import static org.junit.jupiter.api.Assertions.*; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; + +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 + void parseTestDirectory() throws IOException { + List> parseResults = sourceRoot.tryToParse(); + List units = sourceRoot.getCompilationUnits(); + + assertEquals(7, units.size()); + assertTrue(units.stream().allMatch(unit -> !unit.getTypes().isEmpty() || unit.getModule().isPresent())); + assertTrue(parseResults.stream().noneMatch(cu -> cu.getResult().get().getStorage().get().getPath().toString().contains("source.root"))); + } + + @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)); + } + + @Test + void fileAsRootIsNotAllowed() { + assertThrows(IllegalArgumentException.class, () -> { + Path path = CodeGenerationUtils.classLoaderRoot(SourceRootTest.class).resolve("com/github/javaparser/utils/Bla.java"); + new SourceRoot(path); + }); +} + + @Test + void dotsInRootDirectoryAreAllowed() throws IOException { + Path path = CodeGenerationUtils.mavenModuleRoot(SourceRootTest.class).resolve("src/test/resources/com/github/javaparser/utils/source.root"); + new SourceRoot(path).tryToParse(); + } + + @Test + void dotsInPackageAreNotAllowed() { + assertThrows(ParseProblemException.class, () -> { + Path path = CodeGenerationUtils.mavenModuleRoot(SourceRootTest.class).resolve("src/test/resources/com/github/javaparser/utils"); + new SourceRoot(path).parse("source.root", "Y.java"); + }); +} + + @Test + void isSensibleDirectoryToEnter() throws IOException { + try (MockedStatic mockedFiles = Mockito.mockStatic(Files.class)) { + mockedFiles.when(() -> Files.isHidden(Mockito.any())).thenReturn(false); + mockedFiles.when(() -> Files.isDirectory(Mockito.any())).thenReturn(true); + SourceRoot root = new SourceRoot(Paths.get("tests/01")); + assertTrue(root.isSensibleDirectoryToEnter(root.getRoot())); + } + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/utils/SourceZipTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/utils/SourceZipTest.java new file mode 100644 index 0000000..e43b33f --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/utils/SourceZipTest.java @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.utils; + +import com.github.javaparser.ParseResult; +import com.github.javaparser.ast.CompilationUnit; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +class SourceZipTest { + + private final Path testDir = CodeGenerationUtils.mavenModuleRoot(SourceZipTest.class) + .resolve(Paths.get("..", "javaparser-core-testing", "src", "test", "resources", "com", "github", "javaparser", + "source_zip")) + .normalize(); + + @Test + void parseTestDirectory() throws IOException { + SourceZip sourceZip = new SourceZip(testDir.resolve("test.zip")); + List>> results = sourceZip.parse(); + assertEquals(3, results.size()); + List units = new ArrayList<>(); + for (Pair> pr : results) { + units.add(pr.b.getResult().get()); + } + assertTrue(units.stream().noneMatch(unit -> unit.getTypes().isEmpty())); + } + + @Test + void parseTestDirectoryWithCallback() throws IOException { + SourceZip sourceZip = new SourceZip(testDir.resolve("test.zip")); + List>> results = new ArrayList<>(); + + sourceZip.parse((path, result) -> results.add(new Pair<>(path, result))); + + assertEquals(3, results.size()); + List units = new ArrayList<>(); + for (Pair> pr : results) { + units.add(pr.b.getResult().get()); + } + assertTrue(units.stream().noneMatch(unit -> unit.getTypes().isEmpty())); + } + + @Test + void dirAsZipIsNotAllowed() { + assertThrows(IOException.class, () -> new SourceZip(testDir.resolve("test")).parse()); + } + + @Test + void fileAsZipIsNotAllowed() { + assertThrows(IOException.class, () -> new SourceZip(testDir.resolve("test.txt")).parse()); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/utils/TestParser.java b/javaparser-core-testing/src/test/java/com/github/javaparser/utils/TestParser.java new file mode 100644 index 0000000..f5e346c --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/utils/TestParser.java @@ -0,0 +1,94 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.utils; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.BodyDeclaration; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.expr.VariableDeclarationExpr; +import com.github.javaparser.ast.stmt.Statement; + +import java.util.HashMap; +import java.util.Map; + +import static com.github.javaparser.ParserConfiguration.LanguageLevel; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.BLEEDING_EDGE; +import static org.junit.jupiter.api.Assertions.fail; + +public class TestParser { + + private static final Map parserCache = new HashMap<>(); + + private static JavaParser parser(LanguageLevel languageLevel) { + return parserCache.computeIfAbsent(languageLevel, ll -> new JavaParser(new ParserConfiguration().setLanguageLevel(ll))); + } + + private static T unpack(ParseResult result) { + if (!result.isSuccessful()) { + fail(result.getProblems().toString()); + } + return result.getResult().get(); + } + + public static CompilationUnit parseCompilationUnit(String stmt) { + return unpack(parser(BLEEDING_EDGE).parse(stmt)); + } + + public static Statement parseStatement(String stmt) { + return unpack(parser(BLEEDING_EDGE).parseStatement(stmt)); + } + + public static T parseExpression(String expr) { + return unpack(parser(BLEEDING_EDGE).parseExpression(expr)); + } + + public static > T parseBodyDeclaration(String bd) { + return (T) unpack(parser(BLEEDING_EDGE).parseBodyDeclaration(bd)); + } + + public static VariableDeclarationExpr parseVariableDeclarationExpr(String bd) { + return unpack(parser(BLEEDING_EDGE).parseVariableDeclarationExpr(bd)); + } + + public static CompilationUnit parseCompilationUnit(LanguageLevel languageLevel, String stmt) { + return unpack(parser(languageLevel).parse(stmt)); + } + + public static Statement parseStatement(LanguageLevel languageLevel, String stmt) { + return unpack(parser(languageLevel).parseStatement(stmt)); + } + + public static T parseExpression(LanguageLevel languageLevel, String expr) { + return unpack(parser(languageLevel).parseExpression(expr)); + } + + public static > T parseBodyDeclaration(LanguageLevel languageLevel, String bd) { + return (T) unpack(parser(languageLevel).parseBodyDeclaration(bd)); + } + + public static VariableDeclarationExpr parseVariableDeclarationExpr(LanguageLevel languageLevel, String bd) { + return unpack(parser(languageLevel).parseVariableDeclarationExpr(bd)); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/utils/TestUtils.java b/javaparser-core-testing/src/test/java/com/github/javaparser/utils/TestUtils.java new file mode 100644 index 0000000..e5bbd3d --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/utils/TestUtils.java @@ -0,0 +1,395 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.utils; + +import com.github.javaparser.*; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.expr.Expression; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; + +import java.io.*; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_9; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.CodeGenerationUtils.f; +import static com.github.javaparser.utils.Utils.normalizeEolInTextBlock; +import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.Arrays.asList; +import static java.util.stream.Collectors.toList; +import static org.junit.jupiter.api.Assertions.*; + +public class TestUtils { + + /** + * Read the resource's contents line-by-line, and use the system's line separator to separate lines. + * Takes care of setting all the end of line character to platform specific ones. + *
+ *
If you wish to read the file as-is, use {@link #readResource(String)} which reads the file stream character-by-character. + */ + public static String readResourceUsingSystemEol(String resourceName) { + return readResource(resourceName, LineSeparator.SYSTEM); + } + + /** + * Read the resource's contents line-by-line, and use the given line separator to separate lines. + *
+ *
If you wish to read the file as-is, use {@link #readResource(String)} which reads the file stream character-by-character. + */ + public static String readResource(String resourceName, LineSeparator lineSeparator) { + if (resourceName.startsWith("/")) { + resourceName = resourceName.substring(1); + } + try (final InputStream resourceAsStream = TestUtils.class.getClassLoader().getResourceAsStream(resourceName)) { + if (resourceAsStream == null) { + fail("resource not found by name: " + resourceName); + } + try (final InputStreamReader reader = new InputStreamReader(resourceAsStream, UTF_8); + final BufferedReader br = new BufferedReader(reader)) { + final StringBuilder builder = new StringBuilder(4096); + String line; + while ((line = br.readLine()) != null) { + builder.append(line).append(lineSeparator.asRawString()); + } + return builder.toString(); + } + } catch (IOException e) { + fail(e); + return null; + } + } + + + /** + * Read the resource's contents as-is. + *
+ *
If you wish to specify the line endings, + * use {@link #readResourceUsingSystemEol(String)} + * or {@link #readResource(String, LineSeparator)} + */ + public static String readResource(String resourceName) { + if (resourceName.startsWith("/")) { + resourceName = resourceName.substring(1); + } + try (final InputStream resourceAsStream = TestUtils.class.getClassLoader().getResourceAsStream(resourceName)) { + if (resourceAsStream == null) { + fail("not found: " + resourceName); + } + try (final InputStreamReader reader = new InputStreamReader(resourceAsStream, UTF_8); + final BufferedReader br = new BufferedReader(reader) + ) { + // Switched to reading char-by-char as opposed to line-by-line. + // This helps to retain the resource's own line endings. + final StringBuilder builder = new StringBuilder(4096); + for (int c = br.read(); c != -1; c = br.read()) { + builder.append((char) c); + } + return builder.toString(); + } + } catch (IOException e) { + fail(e); + return null; + } + } + + /** + * Use this assertion if line endings are important, otherwise use {@link #assertEqualToTextResourceNoEol(String, String)} + */ + public static void assertEqualToTextResource(String resourceName, String actual) { + String expected = readResourceUsingSystemEol(resourceName); + assertEqualsString(expected, actual); + } + + /** + * If line endings are important, use {@link #assertEqualToTextResource(String, String)} + */ + public static void assertEqualToTextResourceNoEol(String resourceName, String actual) { + String expected = readResourceUsingSystemEol(resourceName); + assertEqualsStringIgnoringEol(expected, actual); + } + + public static String readTextResource(Class relativeClass, String resourceName) { + final URL resourceAsStream = relativeClass.getResource(resourceName); + try { + byte[] bytes = Files.readAllBytes(Paths.get(resourceAsStream.toURI())); + return new String(bytes, UTF_8); + } catch (IOException | URISyntaxException e) { + fail(e); + return null; + } + } + + public static void assertInstanceOf(Class expectedType, Object instance) { + assertTrue(expectedType.isAssignableFrom(instance.getClass()), f("%s is not an instance of %s.", instance.getClass(), expectedType)); + } + + /** + * Unzip a zip file into a directory. + */ + public static void unzip(Path zipFile, Path outputFolder) throws IOException { + Log.info("Unzipping %s to %s", () -> zipFile, () -> outputFolder); + + final byte[] buffer = new byte[1024 * 1024]; + + outputFolder.toFile().mkdirs(); + + try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile.toFile()))) { + ZipEntry ze = zis.getNextEntry(); + + while (ze != null) { + final Path newFile = outputFolder.resolve(ze.getName()); + + if (ze.isDirectory()) { + Log.trace("mkdir %s", newFile::toAbsolutePath); + newFile.toFile().mkdirs(); + } else { + Log.info("unzip %s", newFile::toAbsolutePath); + try (FileOutputStream fos = new FileOutputStream(newFile.toFile())) { + int len; + while ((len = zis.read(buffer)) > 0) { + fos.write(buffer, 0, len); + } + } + } + zis.closeEntry(); + ze = zis.getNextEntry(); + } + + } + Log.info("Unzipped %s to %s", () -> zipFile, () -> outputFolder); + } + + /** + * Download a file from a URL to disk. + */ + public static void download(URL url, Path destination) throws IOException { + OkHttpClient client = new OkHttpClient(); + Request request = new Request.Builder() + .url(url) + .build(); + + Response response = client.newCall(request).execute(); + Files.write(destination, response.body().bytes()); + } + + public static String temporaryDirectory() { + return System.getProperty("java.io.tmpdir"); + } + + public static void assertCollections(Collection expected, Collection actual) { + final StringBuilder out = new StringBuilder(); + for (Object e : expected) { + if (actual.contains(e)) { + actual.remove(e); + } else { + out.append("Missing: ").append(e).append(LineSeparator.SYSTEM); + } + } + for (Object a : actual) { + out.append("Unexpected: ").append(a).append(LineSeparator.SYSTEM); + } + + String s = out.toString(); + if (s.isEmpty()) { + return; + } + fail(s); + } + + public static void assertProblems(ParseResult result, String... expectedArg) { + assertProblems(result.getProblems(), expectedArg); + } + + public static void assertProblems(List result, String... expectedArg) { + Set actual = result.stream().map(Problem::toString).collect(Collectors.toSet()); + Set expected = new HashSet<>(asList(expectedArg)); + assertCollections(expected, actual); + } + + public static void assertNoProblems(ParseResult result) { + assertProblems(result); + } + + public static void assertExpressionValid(String expression) { + JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_9)); + ParseResult result = javaParser.parse(ParseStart.EXPRESSION, provider(expression)); + assertTrue(result.isSuccessful(), result.getProblems().toString()); + } + + /** + * Assert that "actual" equals "expected", ignoring line separators. + * @deprecated Use {@link #assertEqualsStringIgnoringEol(String, String)} + */ + @Deprecated + public static void assertEqualsNoEol(String expected, String actual) { + assertEqualsStringIgnoringEol(expected, actual); + } + + /** + * Assert that "actual" equals "expected", ignoring line separators. + * @deprecated Use {@link #assertEqualsStringIgnoringEol(String, String, String)} + */ + @Deprecated + public static void assertEqualsNoEol(String expected, String actual, String message) { + assertEqualsStringIgnoringEol(expected, actual, message); + } + + /** + * Assert that "actual" equals "expected". + *
First checks if the content is equal ignoring line separators. + *
If this passes, then we check if the content is equal - if this fails then we can + * advise that the difference is only in the line separators. + */ + public static void assertEqualsString(String expected, String actual) { + assertEqualsString(expected, actual, ""); + } + + /** + * Assert that "actual" equals "expected". + *
First checks if the content is equal ignoring line separators. + *
If this passes, then we check if the content is equal - if this fails then we can + * advise that the difference is only in the line separators. + */ + public static void assertEqualsString(String expected, String actual, String message) { + // First test equality ignoring EOL chars + assertEqualsStringIgnoringEol(expected, actual, message); + + // If this passes but the next one fails, the failure is due only to EOL differences, allowing a more precise test failure message. + assertEquals( + expected, + actual, + message + String.format(" -- failed due to line separator differences -- Expected: %s, but actual: %s (system eol: %s)", + LineSeparator.detect(expected).asEscapedString(), + LineSeparator.detect(actual).asEscapedString(), + LineSeparator.SYSTEM.asEscapedString() + ) + ); + } + + + /** + * Assert that "actual" equals "expected", ignoring line separators. + */ + public static void assertEqualsStringIgnoringEol(String expected, String actual) { + assertEquals( + normalizeEolInTextBlock(expected, LineSeparator.ARBITRARY), + normalizeEolInTextBlock(actual, LineSeparator.ARBITRARY) + ); + } + + /** + * Assert that "actual" equals "expected", ignoring line separators. + */ + public static void assertEqualsStringIgnoringEol(String expected, String actual, String message) { + assertEquals( + normalizeEolInTextBlock(expected, LineSeparator.ARBITRARY), + normalizeEolInTextBlock(actual, LineSeparator.ARBITRARY), + message + ); + } + + + /** + * Assert that the given string is detected as having the given line separator. + */ + public static void assertLineSeparator(String text, LineSeparator expectedLineSeparator) { + LineSeparator actualLineSeparator = LineSeparator.detect(text); + assertEquals(expectedLineSeparator, actualLineSeparator); + } + + /** + * Does this node's token starting position match the line and col? + */ + public static boolean startsAtPosition(Node node, int line, int col) { + Position begin = getNodeStartTokenPosition(node); + return begin.line == line && begin.column == col; + } + + /** + * Quickly get token starting position of a given node + */ + public static Position getNodeStartTokenPosition(Node node) { + return node.getTokenRange() + .orElseThrow(() -> new IllegalStateException(node + " is missing the token range")) + .toRange() + .orElseThrow(() -> new IllegalStateException(node + "'s token range is missing the range")) + .begin; + } + + /** + * parse a file using a given parser relative to the classpath root + */ + public static CompilationUnit parseFile(JavaParser parser, String filePath) { + try (InputStream in = TestUtils.class.getResourceAsStream(filePath)) { + ParseResult parse = parser.parse(in); + List problems = parse.getProblems(); + if (!problems.isEmpty()) { + throw new IllegalStateException(problems.toString()); + } + return parse.getResult() + .orElseThrow(() -> new IllegalArgumentException("No result when attempting to parse " + filePath)); + } catch (IOException ex) { + throw new IllegalStateException("Error while parsing " + filePath, ex); + } + } + + /** + * parse a file relative to the classpath root + */ + public static CompilationUnit parseFile(String filePath) { + return parseFile(new JavaParser(), filePath); + } + + public static N getNodeStartingAtPosition(List chars, int line, int col) { + List nodesAtPosition = chars.stream() + .filter(expr -> startsAtPosition(expr, line, col)) + .collect(toList()); + + if (nodesAtPosition.size() != 1) { + throw new IllegalArgumentException("Expecting exactly one node to be positioned at " + line + "," + col + " but got " + nodesAtPosition); + } + return nodesAtPosition.get(0); + } + + /** + * Assert that the given string is detected as having the given line separator. + */ + public static void assertLineSeparator(String text, LineSeparator expectedLineSeparator, String message) { + LineSeparator actualLineSeparator = LineSeparator.detect(text); + assertEquals(expectedLineSeparator, actualLineSeparator, message); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/utils/UtilsTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/utils/UtilsTest.java new file mode 100644 index 0000000..2507506 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/utils/UtilsTest.java @@ -0,0 +1,230 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.utils; + +import static com.github.javaparser.utils.Utils.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.io.Reader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Optional; + +import org.junit.jupiter.api.Test; + +class UtilsTest { + + @Test + void testIsNullOrEmpty() { + assertTrue(isNullOrEmpty(null)); + assertTrue(isNullOrEmpty(new ArrayList<>())); + + assertFalse(isNullOrEmpty( + new ArrayList<>(Arrays.asList("foo", "bar")))); + } + + @Test + void testAssertNotNull() { + assertEquals("foo", assertNotNull("foo")); + assertThrows(AssertionError.class, () -> assertNotNull(null)); + } + + @Test + void testAssertNonEmpty() { + assertEquals("foo", assertNonEmpty("foo")); + assertThrows(AssertionError.class, () -> assertNonEmpty("")); + assertThrows(AssertionError.class, () -> assertNonEmpty(null)); + + } + + @Test + void testAssertNonNegative() { + assertEquals((Number) 2, assertNonNegative(2)); + assertThrows(AssertionError.class, () -> assertNonNegative(-2)); + } + + @Test + void testAssertPositive() { + assertEquals((Number) 2, assertPositive(2)); + assertThrows(AssertionError.class, () -> assertPositive(-2)); + } + + @Test + void testEscapeEndOfLines() { + assertEquals("f\\no\\ro", escapeEndOfLines("f\no\ro")); + } + + @Test + void testReaderToString() throws IOException { + Reader reader = new Reader() { + @Override + public int read(char[] chars, int i, int i1) throws IOException { + return 0; + } + + @Override + public void close() throws IOException { + } + }; + assertEquals("", readerToString(reader)); + } + + @Test + void testToCamelCase() { + assertEquals("foo", toCamelCase("foo")); + assertEquals("foo", toCamelCase("Foo")); + assertEquals("foo", toCamelCase("FOO")); + assertEquals("foo", toCamelCase("fOo")); + } + + @Test + void testScreamingToCamelCase() { + assertEquals("abc", screamingToCamelCase("ABC")); + assertEquals("abcDef", screamingToCamelCase("ABC_DEF")); + assertEquals("abc", screamingToCamelCase("ABC_")); + } + + @Test + void screamingEmptyString() { + assertEquals("", camelCaseToScreaming("")); + assertEquals("ABC", camelCaseToScreaming("abc")); + assertEquals("HELLO_HELLO", camelCaseToScreaming("HelloHello")); + assertEquals("APE_TAIL", camelCaseToScreaming("apeTail")); + } + + @Test + void testNextWord() { + assertEquals("foo", nextWord("foo")); + assertEquals("foo", nextWord("foo bar")); + assertEquals("foo", nextWord("foo bar Baz")); + } + + @Test + void testIndent() { + assertEquals("foo", + indent(new StringBuilder("foo"), 0).toString()); + assertEquals("foo\t", + indent(new StringBuilder("foo"), 1).toString()); + assertEquals("foo\t\t", + indent(new StringBuilder("foo"), 2).toString()); + assertEquals("foo\t\t\t", + indent(new StringBuilder("foo"), 3).toString()); + } + + @Test + void capitalizeOnEmptyString() { + assertThrows(IllegalArgumentException.class, () -> capitalize("")); + } + + @Test + void capitalizeOnStringOfOneCharacter() { + assertEquals("F", capitalize("f")); + } + + @Test + void capitalizeOnStringOfTwoCharacters() { + assertEquals("Fo", capitalize("fo")); + } + + @Test + void decapitalizeOnEmptyString() { + assertThrows(IllegalArgumentException.class, () -> decapitalize("")); + } + + @Test + void decapitalizeOnStringOfOneCharacter() { + assertEquals("f", decapitalize("F")); + } + + @Test + void decapitalizeOnStringOfTwoCharacters() { + assertEquals("fo", decapitalize("Fo")); + } + + @Test + void testValueIsNullOrEmpty() { + assertTrue(valueIsNullOrEmpty(null)); + assertTrue(valueIsNullOrEmpty(Optional.empty())); + assertTrue(valueIsNullOrEmpty(new ArrayList<>())); + + assertFalse(valueIsNullOrEmpty( + Optional.ofNullable("foo"))); + assertFalse(valueIsNullOrEmpty( + new ArrayList<>(Arrays.asList("foo", "bar")))); + } + + @Test + void testValueIsNullOrEmptyStringOrOptional() { + assertTrue(valueIsNullOrEmptyStringOrOptional(null)); + assertTrue(valueIsNullOrEmptyStringOrOptional( + Optional.empty())); + + assertFalse(valueIsNullOrEmptyStringOrOptional("foo")); + assertFalse(valueIsNullOrEmptyStringOrOptional("")); + assertFalse(valueIsNullOrEmptyStringOrOptional( + Optional.ofNullable("foo"))); + assertFalse(valueIsNullOrEmptyStringOrOptional( + Optional.ofNullable(""))); + } + + @Test + void testIndexOfElementByObjectIdentity() { + assertEquals(-1, indexOfElementByObjectIdentity( + new ArrayList<>(), "bar")); + assertEquals(1, indexOfElementByObjectIdentity( + new ArrayList<>(Arrays.asList("foo", "bar")), "bar")); + } + + @Test + void testSet() { + assertEquals(new HashSet<>(Arrays.asList("bar", "foo", "baz")), + set("foo", "bar", "baz")); + } + + @Test + void normalizeEolInTextBlock() { + String result = Utils.normalizeEolInTextBlock("\r\n \r \n", "Q"); + assertEquals("Q Q Q", result); + } + + @Test + void testRemoveFileExtension() { + assertEquals("foo", removeFileExtension("foo")); + assertEquals("foo", removeFileExtension("foo.txt")); + } + + @Test + void testTrimTrailingSpaces() { + assertEquals("abc", trimTrailingSpaces("abc")); + assertEquals(" abc", trimTrailingSpaces(" abc")); + assertEquals("abc", trimTrailingSpaces("abc ")); + assertEquals(" abc", trimTrailingSpaces(" abc ")); + assertEquals("abc", trimTrailingSpaces("abc\t\0")); + assertEquals("", trimTrailingSpaces(" ")); + assertEquals("", trimTrailingSpaces("")); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/utils/VisitorListTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/utils/VisitorListTest.java new file mode 100644 index 0000000..fcd75a9 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/utils/VisitorListTest.java @@ -0,0 +1,185 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.utils; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.visitor.ObjectIdentityEqualsVisitor; +import com.github.javaparser.ast.visitor.ObjectIdentityHashCodeVisitor; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import static com.github.javaparser.StaticJavaParser.parse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class VisitorListTest { + + @Test + void visitorAddAll() { + List list = new ArrayList<>(); + list.add(parse("class X{}")); + list.add(parse("class X{}")); + VisitorList vList = new VisitorList<>(new ObjectIdentityHashCodeVisitor(), + new ObjectIdentityEqualsVisitor()); + vList.addAll(list); + for (int i = 0; i < list.size(); i++) + assertEquals(list.get(i), vList.get(i)); + } + + @Test + void visitorAddAllAtIndex() { + List list = new ArrayList<>(); + list.add(parse("class X{}")); + list.add(parse("class Y{}")); + VisitorList vList = new VisitorList<>(new ObjectIdentityHashCodeVisitor(), + new ObjectIdentityEqualsVisitor()); + vList.add(parse("class A{}")); + vList.add(parse("class B{}")); + vList.addAll(2, list); + vList.add(parse("class C{}")); + for (int i = 0; i < list.size(); i++) + assertEquals(list.get(i), vList.get(2 + i)); + } + + @Test + void visitorListContains() { + CompilationUnit x1 = parse("class X{}"); + VisitorList list = new VisitorList<>(new ObjectIdentityHashCodeVisitor(), + new ObjectIdentityEqualsVisitor()); + list.add(x1); + assertTrue(list.contains(x1)); + } + + @Test + void visitorListContainsAll() { + List list = new ArrayList<>(); + list.add(parse("class X{}")); + list.add(parse("class X{}")); + VisitorList vList = new VisitorList<>(new ObjectIdentityHashCodeVisitor(), + new ObjectIdentityEqualsVisitor()); + vList.addAll(list); + assertTrue(vList.size() == 2 && vList.containsAll(list)); + } + + @Test + void visitorListIterator() { + VisitorList list = new VisitorList<>(new ObjectIdentityHashCodeVisitor(), + new ObjectIdentityEqualsVisitor()); + CompilationUnit x1 = parse("class X{}"); + list.add(x1); + CompilationUnit x2 = parse("class X{}"); + list.add(x2); + Iterator itr = list.iterator(); + assertEquals(x1, itr.next()); + itr.remove(); + assertEquals(1, list.size()); + assertEquals(x2, itr.next()); + itr.remove(); + assertEquals(0, list.size()); + } + + @Test + void visitorListListIterator() { + VisitorList list = new VisitorList<>(new ObjectIdentityHashCodeVisitor(), + new ObjectIdentityEqualsVisitor()); + list.add(parse("class X{}")); + list.add(parse("class X{}")); + CompilationUnit x1 = parse("class X{}"); + list.add(x1); + CompilationUnit x2 = parse("class X{}"); + list.add(x2); + Iterator itr = list.listIterator(2); + assertEquals(x1, itr.next()); + itr.remove(); + assertEquals(3, list.size()); + assertEquals(x2, itr.next()); + itr.remove(); + assertEquals(2, list.size()); + } + + @Test + void visitorListRemove() { + CompilationUnit x1 = parse("class X{}"); + VisitorList list = new VisitorList<>(new ObjectIdentityHashCodeVisitor(), + new ObjectIdentityEqualsVisitor()); + list.add(x1); + assertTrue(list.remove(x1)); + } + + @Test + void visitorListRemoveAll() { + List list = new ArrayList<>(); + list.add(parse("class X{}")); + list.add(parse("class X{}")); + VisitorList vList = new VisitorList<>(new ObjectIdentityHashCodeVisitor(), + new ObjectIdentityEqualsVisitor()); + vList.addAll(list); + vList.removeAll(list); + assertEquals(0, vList.size()); + } + + @Test + void visitorListRetainAll() { + List list = new ArrayList<>(); + list.add(parse("class X{}")); + list.add(parse("class X{}")); + VisitorList vList = new VisitorList<>(new ObjectIdentityHashCodeVisitor(), + new ObjectIdentityEqualsVisitor()); + vList.addAll(list); + vList.add(parse("class X{}")); + vList.retainAll(list); + assertEquals(2, vList.size()); + } + + @Test + void visitorListSubList() { + VisitorList list = new VisitorList<>(new ObjectIdentityHashCodeVisitor(), + new ObjectIdentityEqualsVisitor()); + list.add(parse("class X{}")); + list.add(parse("class X{}")); + list.add(parse("class X{}")); + list.add(parse("class X{}")); + assertEquals(4, list.size()); + List subLst = list.subList(1, 3); + assertEquals(2, subLst.size()); + subLst.add(parse("class X{}")); + assertEquals(3, subLst.size()); + assertEquals(5, list.size()); + + } + + @Test + void visitorListToArray() { + List list = new ArrayList<>(); + list.add(parse("class X{}")); + list.add(parse("class X{}")); + List vList = new VisitorList<>(new ObjectIdentityHashCodeVisitor(), + new ObjectIdentityEqualsVisitor()); + vList.addAll(list); + for (CompilationUnit u : vList.toArray(new CompilationUnit[2])) + assertTrue(vList.contains(u)); + } + +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/utils/VisitorMapTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/utils/VisitorMapTest.java new file mode 100644 index 0000000..4874525 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/utils/VisitorMapTest.java @@ -0,0 +1,99 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.utils; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.visitor.ObjectIdentityEqualsVisitor; +import com.github.javaparser.ast.visitor.ObjectIdentityHashCodeVisitor; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.Map; + +import static com.github.javaparser.StaticJavaParser.parse; +import static org.junit.jupiter.api.Assertions.*; + +class VisitorMapTest { + @Test + void normalEqualsDoesDeepCompare() { + CompilationUnit x1 = parse("class X{}"); + CompilationUnit x2 = parse("class X{}"); + + Map map = new HashMap<>(); + map.put(x1, 1); + map.put(x2, 2); + assertEquals(1, map.size()); + } + + @Test + void objectIdentityEqualsDoesShallowCompare() { + CompilationUnit x1 = parse("class X{}"); + CompilationUnit x2 = parse("class X{}"); + + Map map = new VisitorMap<>(new ObjectIdentityHashCodeVisitor(), new ObjectIdentityEqualsVisitor()); + map.put(x1, 1); + map.put(x2, 2); + assertEquals(2, map.size()); + } + + @Test + void visitorMapGet(){ + CompilationUnit x1 = parse("class X{}"); + + Map map = new VisitorMap<>(new ObjectIdentityHashCodeVisitor(), new ObjectIdentityEqualsVisitor()); + map.put(x1, 1); + assertEquals(1, (int)map.get(x1)); + } + + @Test + void visitorMapContainsKey(){ + CompilationUnit x1 = parse("class X{}"); + + Map map = new VisitorMap<>(new ObjectIdentityHashCodeVisitor(), new ObjectIdentityEqualsVisitor()); + map.put(x1, 1); + assertTrue(map.containsKey(x1)); + } + + @Test + void visitorMapPutAll(){ + CompilationUnit x1 = parse("class X{}"); + CompilationUnit x2 = parse("class Y{}"); + Map map = new HashMap<>(); + map.put(x1, 1); + map.put(x2, 2); + Map visitorMap = new VisitorMap<>(new ObjectIdentityHashCodeVisitor(), new ObjectIdentityEqualsVisitor()); + visitorMap.putAll(map); + assertEquals(2, visitorMap.size()); + } + + @Test + void remove(){ + CompilationUnit x1 = parse("class X{}"); + VisitorMap map = new VisitorMap<>(new ObjectIdentityHashCodeVisitor(), new ObjectIdentityEqualsVisitor()); + map.put(x1, 1); + assertTrue(map.containsKey(x1)); + + map.remove(x1); + + assertFalse(map.containsKey(x1)); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/utils/VisitorSetTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/utils/VisitorSetTest.java new file mode 100644 index 0000000..bf32e5a --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/utils/VisitorSetTest.java @@ -0,0 +1,136 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.utils; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.visitor.ObjectIdentityEqualsVisitor; +import com.github.javaparser.ast.visitor.ObjectIdentityHashCodeVisitor; +import org.junit.jupiter.api.Test; + +import java.util.*; + +import static com.github.javaparser.StaticJavaParser.parse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class VisitorSetTest { + + @Test + void normalEqualsDoesDeepCompare() { + Set set = new HashSet<>(); + set.add(parse("class X{}")); + set.add(parse("class X{}")); + assertEquals(1, set.size()); + } + + @Test + void objectIdentityEqualsDoesShallowCompare() { + Set set = new VisitorSet<>(new ObjectIdentityHashCodeVisitor(), + new ObjectIdentityEqualsVisitor()); + set.add(parse("class X{}")); + set.add(parse("class X{}")); + assertEquals(2, set.size()); + } + + @Test + void visitorSetContains() { + CompilationUnit x1 = parse("class X{}"); + Set set = new VisitorSet<>(new ObjectIdentityHashCodeVisitor(), + new ObjectIdentityEqualsVisitor()); + set.add(x1); + assertTrue(set.contains(x1)); + } + + @Test + void visitorSetContainsAll() { + List list = new ArrayList<>(); + list.add(parse("class X{}")); + list.add(parse("class X{}")); + Set set = new VisitorSet<>(new ObjectIdentityHashCodeVisitor(), + new ObjectIdentityEqualsVisitor()); + set.addAll(list); + assertTrue(set.size() == 2 && set.containsAll(list)); + } + + @Test + void visitorSetIterator() { + Set set = new VisitorSet<>(new ObjectIdentityHashCodeVisitor(), + new ObjectIdentityEqualsVisitor()); + CompilationUnit x1 = parse("class X{}"); + set.add(x1); + CompilationUnit x2 = parse("class X{}"); + set.add(x2); + Iterator itr = set.iterator(); + assertEquals(x1, itr.next()); + itr.remove(); + assertEquals(1, set.size()); + assertEquals(x2, itr.next()); + itr.remove(); + assertEquals(0, set.size()); + } + + @Test + void visitorSetRemove() { + CompilationUnit x1 = parse("class X{}"); + Set set = new VisitorSet<>(new ObjectIdentityHashCodeVisitor(), + new ObjectIdentityEqualsVisitor()); + set.add(x1); + assertTrue(set.remove(x1)); + } + + @Test + void visitorSetRemoveAll() { + List list = new ArrayList<>(); + list.add(parse("class X{}")); + list.add(parse("class X{}")); + Set set = new VisitorSet<>(new ObjectIdentityHashCodeVisitor(), + new ObjectIdentityEqualsVisitor()); + set.addAll(list); + set.removeAll(list); + assertEquals(0, set.size()); + } + + @Test + void visitorSetRetainAll() { + List list = new ArrayList<>(); + list.add(parse("class X{}")); + list.add(parse("class X{}")); + Set set = new VisitorSet<>(new ObjectIdentityHashCodeVisitor(), + new ObjectIdentityEqualsVisitor()); + set.addAll(list); + set.add(parse("class X{}")); + set.retainAll(list); + assertEquals(2, set.size()); + } + + @Test + void visitorSetToArray() { + List list = new ArrayList<>(); + list.add(parse("class X{}")); + list.add(parse("class X{}")); + Set set = new VisitorSet<>(new ObjectIdentityHashCodeVisitor(), + new ObjectIdentityEqualsVisitor()); + set.addAll(list); + for (CompilationUnit u : set.toArray(new CompilationUnit[2])) + assertTrue(set.contains(u)); + } +} diff --git a/javaparser-core-testing/src/test/java/com/github/javaparser/version/Java10PostProcessorTest.java b/javaparser-core-testing/src/test/java/com/github/javaparser/version/Java10PostProcessorTest.java new file mode 100644 index 0000000..b773278 --- /dev/null +++ b/javaparser-core-testing/src/test/java/com/github/javaparser/version/Java10PostProcessorTest.java @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2024 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.version; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.ast.type.VarType; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static com.github.javaparser.ParseStart.STATEMENT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_10; +import static com.github.javaparser.Providers.provider; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class Java10PostProcessorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_10)); + + @Test + void varIsAType() { + ParseResult result = javaParser.parse(STATEMENT, provider("var x=\"\";")); + + List allVarTypes = result.getResult().get().findAll(VarType.class); + + assertEquals(1, allVarTypes.size()); + } + + @Test + void expressionThatShouldNotBeInterpretedAsAVarType() { + ParseResult result = javaParser.parse(STATEMENT, provider("var.class.getName();")); + + List allVarTypes = result.getResult().get().findAll(VarType.class); + + assertEquals(0, allVarTypes.size()); + } +} diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/EscapeSequences.java b/javaparser-core-testing/src/test/resources/com/github/javaparser/EscapeSequences.java new file mode 100644 index 0000000..9752994 --- /dev/null +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/EscapeSequences.java @@ -0,0 +1,32 @@ +package com.github.javaparser; + +public class EscapeSequences { + + public static void main(String[] args) { + Object[] chars = { + '\\', '\u005C\u005C', '\u005c\u005c', + "---", + '\n', '\u005cn', '\u005Cn', + "---", + '\r', '\u005cr', '\u005Cr', + "---", + '\t', '\u005ct', '\u005Ct', + "---", + '\b', '\u005cb', '\u005Cb', + "---", + '\f', '\u005cf', '\u005Cf', + "---", + '\'', '\u005c'', // '\u005C'', // that's weird, this last one won't compile + "---", + '\"', '\u005c"', '\u005C"' + }; + for (Object obj : chars) { + if (obj instanceof Character) { + System.out.println(obj + " " + (int) (char) obj); // print the numeric representation + } else { + System.out.println(obj); + } + } + } + +} diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/Sample.java b/javaparser-core-testing/src/test/resources/com/github/javaparser/Sample.java new file mode 100644 index 0000000..c4b3450 --- /dev/null +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/Sample.java @@ -0,0 +1,17 @@ +package com.github.javaparser; + +import java.util.List; + +public class Sample { + + private String name; + + public Sample(String name) { + this.name = name; + } + + public List process() { + List result = new A + } + +} diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/TestFileIso88591.java b/javaparser-core-testing/src/test/resources/com/github/javaparser/TestFileIso88591.java new file mode 100644 index 0000000..1777f94 --- /dev/null +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/TestFileIso88591.java @@ -0,0 +1,7 @@ +package com.github.javaparser; + +public class TestFile { + + public String strïng = "Strange attribute name [check the i]"; + +} diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_core_generators_src_main_java.txt b/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_core_generators_src_main_java.txt new file mode 100644 index 0000000..8a9fcbe --- /dev/null +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_core_generators_src_main_java.txt @@ -0,0 +1 @@ +0 problems in 0 files \ No newline at end of file diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_core_metamodel_generator_src_main_java.txt b/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_core_metamodel_generator_src_main_java.txt new file mode 100644 index 0000000..8a9fcbe --- /dev/null +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_core_metamodel_generator_src_main_java.txt @@ -0,0 +1 @@ +0 problems in 0 files \ No newline at end of file diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_core_src_main_java.txt b/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_core_src_main_java.txt new file mode 100644 index 0000000..8a9fcbe --- /dev/null +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_core_src_main_java.txt @@ -0,0 +1 @@ +0 problems in 0 files \ No newline at end of file diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_core_testing_src_test_java.txt b/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_core_testing_src_test_java.txt new file mode 100644 index 0000000..8a9fcbe --- /dev/null +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_core_testing_src_test_java.txt @@ -0,0 +1 @@ +0 problems in 0 files \ No newline at end of file diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_metamodel_generator_src_main_java.txt b/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_metamodel_generator_src_main_java.txt new file mode 100644 index 0000000..8a9fcbe --- /dev/null +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_metamodel_generator_src_main_java.txt @@ -0,0 +1 @@ +0 problems in 0 files \ No newline at end of file diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_symbol_solver_core_src_main_java.txt b/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_symbol_solver_core_src_main_java.txt new file mode 100644 index 0000000..8a9fcbe --- /dev/null +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_symbol_solver_core_src_main_java.txt @@ -0,0 +1 @@ +0 problems in 0 files \ No newline at end of file diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_symbol_solver_logic_src_main_java.txt b/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_symbol_solver_logic_src_main_java.txt new file mode 100644 index 0000000..8a9fcbe --- /dev/null +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_symbol_solver_logic_src_main_java.txt @@ -0,0 +1 @@ +0 problems in 0 files \ No newline at end of file diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_symbol_solver_model_src_main_java.txt b/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_symbol_solver_model_src_main_java.txt new file mode 100644 index 0000000..8a9fcbe --- /dev/null +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_symbol_solver_model_src_main_java.txt @@ -0,0 +1 @@ +0 problems in 0 files \ No newline at end of file diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_symbol_solver_testing_src_test_java.txt b/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_symbol_solver_testing_src_test_java.txt new file mode 100644 index 0000000..8a9fcbe --- /dev/null +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_symbol_solver_testing_src_test_java.txt @@ -0,0 +1 @@ +0 problems in 0 files \ No newline at end of file diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_testing_src_test_java.txt b/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_testing_src_test_java.txt new file mode 100644 index 0000000..8a9fcbe --- /dev/null +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results_javaparser_testing_src_test_java.txt @@ -0,0 +1 @@ +0 problems in 0 files \ No newline at end of file diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/openjdk_src_repo_test_results.txt b/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/openjdk_src_repo_test_results.txt new file mode 100644 index 0000000..b3d4e57 --- /dev/null +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/openjdk_src_repo_test_results.txt @@ -0,0 +1,655 @@ +langtools-19293ea3999f/test/jdk/javadoc/doclet/testAnchorNames/pkg1/RegClass.java +(line 68,col 16) '_' is a reserved keyword. + +langtools-19293ea3999f/test/jdk/javadoc/doclet/testSourceTab/DoubleTab/C.java +Lexical error at line 33, column 2. Encountered: "t" (116), after : "\\" + +langtools-19293ea3999f/test/jdk/javadoc/doclet/testSourceTab/SingleTab/C.java +Lexical error at line 33, column 2. Encountered: "t" (116), after : "\\" + +langtools-19293ea3999f/test/jdk/javadoc/doclet/testUnnamedPackage/BadSource.java +Parse error. Found "Just" , expected one of ";" "@" "\u001a" "abstract" "class" "default" "enum" "final" "import" "interface" "module" "native" "open" "private" "protected" "public" "static" "strictfp" "synchronized" "transient" "transitive" "volatile" + +langtools-19293ea3999f/test/jdk/javadoc/tool/6964914/Error.java +(line 25,col 12) Parse error. Found "}", expected "(" + +langtools-19293ea3999f/test/jdk/javadoc/tool/6964914/JavacWarning.java +(line 25,col 12) '_' is a reserved keyword. + +langtools-19293ea3999f/test/jdk/javadoc/tool/enum/docComments/pkg1/Operation.java +(line 33,col 1) 'abstract' is not allowed here. + +langtools-19293ea3999f/test/jdk/javadoc/tool/T4994049/FileWithTabs.java +Lexical error at line 25, column 2. Encountered: "t" (116), after : "\\" + +langtools-19293ea3999f/test/tools/javac/6302184/T6302184.java +Lexical error at line 28, column 9. Encountered: "\ufffd" (65533), after : "" + +langtools-19293ea3999f/test/tools/javac/6440583/A.java +(line 25,col 28) Parse error. Found "1" , expected "}" + +langtools-19293ea3999f/test/tools/javac/annotations/AnnotationTypeElementModifiers.java +(line 17,col 5) 'private' is not allowed here. +(line 18,col 5) 'private' is not allowed here. +(line 20,col 5) 'protected' is not allowed here. +(line 21,col 5) 'protected' is not allowed here. +(line 23,col 5) 'static' is not allowed here. +(line 24,col 5) 'static' is not allowed here. +(line 26,col 5) 'final' is not allowed here. +(line 27,col 5) 'final' is not allowed here. +(line 29,col 5) 'synchronized' is not allowed here. +(line 30,col 5) 'synchronized' is not allowed here. +(line 32,col 5) 'volatile' is not allowed here. +(line 33,col 5) 'volatile' is not allowed here. +(line 35,col 5) 'transient' is not allowed here. +(line 36,col 5) 'transient' is not allowed here. +(line 38,col 5) 'native' is not allowed here. +(line 39,col 5) 'native' is not allowed here. +(line 41,col 5) 'strictfp' is not allowed here. +(line 42,col 5) 'strictfp' is not allowed here. +(line 44,col 5) 'default' is not allowed here. +(line 45,col 5) 'default' is not allowed here. + +langtools-19293ea3999f/test/tools/javac/annotations/FinalReceiverTest.java +(line 11,col 43) Parse error. Found ".", expected one of ")" "," "@" "[" +(line 14,col 2) Parse error. Found , expected "}" +(line 14,col 2) Parse error. Found , expected one of ";" "<" "@" "abstract" "boolean" "byte" "char" "class" "default" "double" "enum" "exports" "final" "float" "int" "interface" "long" "module" "native" "open" "opens" "private" "protected" "provides" "public" "requires" "short" "static" "strictfp" "synchronized" "to" "transient" "transitive" "uses" "void" "volatile" "with" "{" "}" + +langtools-19293ea3999f/test/tools/javac/annotations/neg/AnnComma.java +(line 12,col 35) Parse error. Found ")", expected one of "enum" "exports" "module" "open" "opens" "provides" "requires" "strictfp" "to" "transitive" "uses" "with" + +langtools-19293ea3999f/test/tools/javac/annotations/neg/NoDefault.java +(line 8,col 19) Parse error. Found "{", expected one of ";" "default" + +langtools-19293ea3999f/test/tools/javac/annotations/neg/NoDefaultAbstract.java +(line 8,col 5) 'default' is not allowed here. + +langtools-19293ea3999f/test/tools/javac/annotations/neg/NoStatic.java +(line 9,col 18) Parse error. Found "{", expected one of ";" "default" + +langtools-19293ea3999f/test/tools/javac/annotations/neg/NoStaticAbstract.java +(line 9,col 5) 'static' is not allowed here. + +langtools-19293ea3999f/test/tools/javac/annotations/neg/Syntax1.java +(line 17,col 21) Parse error. Found ",", expected one of "!=" "%" "&" "&&" "(" ")" "*" "+" "-" "/" "<" "<=" "==" ">" ">=" "?" "^" "instanceof" "|" "||" + +langtools-19293ea3999f/test/tools/javac/annotations/neg/Z12.java +(line 10,col 15) Parse error. Found "void", expected one of ";" "@" "abstract" "boolean" "byte" "char" "class" "default" "double" "enum" "exports" "final" "float" "int" "interface" "long" "module" "native" "open" "opens" "private" "protected" "provides" "public" "requires" "short" "static" "strictfp" "synchronized" "to" "transient" "transitive" "uses" "volatile" "with" "}" + +langtools-19293ea3999f/test/tools/javac/annotations/neg/Z13.java +(line 11,col 11) Parse error. Found "throws", expected one of ";" "default" + +langtools-19293ea3999f/test/tools/javac/annotations/neg/Z14.java +(line 10,col 12) Parse error. Found "<", expected "{" + +langtools-19293ea3999f/test/tools/javac/annotations/neg/Z2.java +(line 13,col 17) Parse error. Found "default", expected one of ";" "@" "[" "throws" "{" + +langtools-19293ea3999f/test/tools/javac/annotations/neg/Z3.java +(line 13,col 17) Parse error. Found "default", expected one of ";" "@" "[" "throws" "{" + +langtools-19293ea3999f/test/tools/javac/annotations/neg/Z5.java +(line 12,col 12) Parse error. Found "extends", expected "{" + +langtools-19293ea3999f/test/tools/javac/annotations/neg/Z8.java +(line 11,col 10) Parse error. Found "int", expected ")" + +langtools-19293ea3999f/test/tools/javac/annotations/neg/Z9.java +(line 10,col 15) Parse error. Found "<", expected one of ";" "@" "abstract" "boolean" "byte" "char" "class" "default" "double" "enum" "exports" "final" "float" "int" "interface" "long" "module" "native" "open" "opens" "private" "protected" "provides" "public" "requires" "short" "static" "strictfp" "synchronized" "to" "transient" "transitive" "uses" "volatile" "with" "}" + +langtools-19293ea3999f/test/tools/javac/annotations/typeAnnotations/6967002/T6967002.java +(line 33,col 16) Parse error. Found "...", expected one of "!=" "%" "%=" "&" "&&" "&=" "(" ")" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||" + +langtools-19293ea3999f/test/tools/javac/annotations/typeAnnotations/failures/AnnotatedClassExpr.java +(line 12,col 15) Parse error. Found "@", expected one of "!" "(" "enum" "exports" "false" "module" "new" "null" "open" "opens" "provides" "requires" "strictfp" "super" "this" "to" "transitive" "true" "uses" "with" "~" +(line 13,col 8) Parse error. Found "@", expected one of "!" "(" "enum" "exports" "false" "module" "new" "null" "open" "opens" "provides" "requires" "strictfp" "super" "this" "to" "transitive" "true" "uses" "with" "~" +(line 17,col 8) Parse error. Found "@", expected one of "!" "(" "enum" "exports" "false" "module" "new" "null" "open" "opens" "provides" "requires" "strictfp" "super" "this" "to" "transitive" "true" "uses" "with" "~" +(line 18,col 8) Parse error. Found "@", expected one of "!" "(" "enum" "exports" "false" "module" "new" "null" "open" "opens" "provides" "requires" "strictfp" "super" "this" "to" "transitive" "true" "uses" "with" "~" + +langtools-19293ea3999f/test/tools/javac/annotations/typeAnnotations/failures/AnnotatedMethodSelectorTest.java +(line 12,col 14) Parse error. Found ".", expected one of "%=" "&=" "(" "*=" "++" "+=" "--" "-=" "/=" ";" "<<=" "=" ">>=" ">>>=" "^=" "|=" + +langtools-19293ea3999f/test/tools/javac/annotations/typeAnnotations/failures/BadCast.java +(line 12,col 16) Parse error. Found "@", expected one of "!" "(" ")" "enum" "exports" "false" "module" "new" "null" "open" "opens" "provides" "requires" "strictfp" "super" "this" "to" "transitive" "true" "uses" "with" "~" + +langtools-19293ea3999f/test/tools/javac/annotations/typeAnnotations/failures/IncompleteArray.java +(line 11,col 11) Parse error. Found "@", expected one of "enum" "exports" "module" "open" "opens" "provides" "requires" "strictfp" "to" "transitive" "uses" "with" + +langtools-19293ea3999f/test/tools/javac/annotations/typeAnnotations/failures/IndexArray.java +(line 12,col 11) Parse error. Found "@", expected one of "!=" "%" "%=" "&" "&&" "&=" "(" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||" + +langtools-19293ea3999f/test/tools/javac/annotations/typeAnnotations/failures/OldArray.java +(line 12,col 10) Parse error. Found "@", expected one of "]" + +langtools-19293ea3999f/test/tools/javac/annotations/typeAnnotations/failures/StaticFields.java +(line 13,col 10) Parse error. Found "@", expected one of "(" "enum" "exports" "false" "module" "new" "null" "open" "opens" "provides" "requires" "strictfp" "super" "this" "to" "transitive" "true" "uses" "with" +(line 17,col 9) Parse error. Found "@", expected one of "!" "(" "enum" "exports" "false" "module" "new" "null" "open" "opens" "provides" "requires" "strictfp" "super" "this" "to" "transitive" "true" "uses" "with" "~" + +langtools-19293ea3999f/test/tools/javac/api/T6265137a.java +(line 24,col 1) Parse error. Found , expected one of "enum" "exports" "module" "open" "opens" "provides" "requires" "strictfp" "to" "transitive" "uses" "with" + +langtools-19293ea3999f/test/tools/javac/BadAnnotation.java +(line 11,col 21) Parse error. Found "int", expected ")" + +langtools-19293ea3999f/test/tools/javac/BadHexConstant.java +(line 12,col 14) Parse error. Found "xL" , expected one of "!=" "%" "%=" "&" "&&" "&=" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||" + +langtools-19293ea3999f/test/tools/javac/declaration/method/MethodVoidParameter.java +(line 7,col 16) Parse error. Found "void", expected one of ")" "@" "abstract" "boolean" "byte" "char" "default" "double" "enum" "exports" "final" "float" "int" "long" "module" "native" "open" "opens" "private" "protected" "provides" "public" "requires" "short" "static" "strictfp" "synchronized" "to" "transient" "transitive" "uses" "volatile" "with" + +langtools-19293ea3999f/test/tools/javac/defaultMethods/private/Private02.java +(line 13,col 9) Cannot be 'abstract' and also 'private'. + +langtools-19293ea3999f/test/tools/javac/defaultMethods/private/Private07.java +(line 9,col 5) 'private' is not allowed here. + +langtools-19293ea3999f/test/tools/javac/defaultMethods/private/Private08.java +(line 13,col 9) Can have only one of 'public', 'private'. +(line 14,col 9) Cannot be 'abstract' and also 'private'. + +langtools-19293ea3999f/test/tools/javac/defaultMethods/private/Private09.java +(line 9,col 17) Duplicated modifier + +langtools-19293ea3999f/test/tools/javac/defaultMethods/private/Private10.java +(line 11,col 9) Cannot be 'abstract' and also 'private'. +(line 14,col 9) Cannot be 'abstract' and also 'private'. + +langtools-19293ea3999f/test/tools/javac/DefiniteAssignment/ConstantInfiniteWhile.java +Lexical error at line 68, column 0. Encountered: after : "" + +langtools-19293ea3999f/test/tools/javac/diags/examples/AnnotationMustBeNameValue.java +(line 32,col 15) Parse error. Found ",", expected one of "!=" "%" "&" "&&" ")" "*" "+" "-" "/" "<" "<=" "==" ">" ">=" "?" "^" "instanceof" "|" "||" + +langtools-19293ea3999f/test/tools/javac/diags/examples/ArrayAndReceiver.java +(line 27,col 29) Parse error. Found "[", expected one of ")" "," + +langtools-19293ea3999f/test/tools/javac/diags/examples/AssertAsIdentifier2.java +(line 27,col 5) Parse error. Found "assert", expected one of "enum" "exports" "module" "open" "opens" "provides" "requires" "strictfp" "to" "transitive" "uses" "with" + +langtools-19293ea3999f/test/tools/javac/diags/examples/CallMustBeFirst.java +(line 28,col 18) Parse error. Found "super", expected "}" + +langtools-19293ea3999f/test/tools/javac/diags/examples/CantAssignToThis.java +(line 28,col 9) Illegal left hand side of an assignment. + +langtools-19293ea3999f/test/tools/javac/diags/examples/CantExtendIntfAnno.java +(line 28,col 12) Parse error. Found "extends", expected "{" + +langtools-19293ea3999f/test/tools/javac/diags/examples/CatchWithoutTry.java +(line 27,col 14) Parse error. Found "catch", expected "}" +(line 30,col 5) Parse error. Found "}", expected one of ";" "@" "\u001a" "abstract" "class" "default" "enum" "final" "import" "interface" "module" "native" "open" "private" "protected" "public" "static" "strictfp" "synchronized" "transient" "transitive" "volatile" + +langtools-19293ea3999f/test/tools/javac/diags/examples/DefaultAllowedInIntfAnnotationMember.java +(line 27,col 18) Parse error. Found "default", expected one of ";" "@" "[" "throws" "{" + +langtools-19293ea3999f/test/tools/javac/diags/examples/DotClassExpected.java +(line 27,col 11) Parse error. Found "int", expected one of "!" "(" "enum" "exports" "false" "module" "new" "null" "open" "opens" "provides" "requires" "strictfp" "super" "this" "to" "transitive" "true" "uses" "with" "~" + +langtools-19293ea3999f/test/tools/javac/diags/examples/ElseWithoutIf.java +(line 27,col 14) Parse error. Found "else", expected "}" +(line 30,col 5) Parse error. Found "}", expected one of ";" "@" "\u001a" "abstract" "class" "default" "enum" "final" "import" "interface" "module" "native" "open" "private" "protected" "public" "static" "strictfp" "synchronized" "transient" "transitive" "volatile" + +langtools-19293ea3999f/test/tools/javac/diags/examples/EmptyCharLiteral.java +Lexical error at line 27, column 15. Encountered: "\'" (39), after : "\'" + +langtools-19293ea3999f/test/tools/javac/diags/examples/EnumAsIdentifier2.java +(line 27,col 9) 'enum' cannot be used as an identifier as it is a keyword. + +langtools-19293ea3999f/test/tools/javac/diags/examples/Expected2.java +(line 30,col 13) Parse error. Found ";", expected one of "(" "@" "[" + +langtools-19293ea3999f/test/tools/javac/diags/examples/Expected3.java +Parse error. Found "int", expected one of ";" "@" "\u001a" "abstract" "class" "default" "enum" "final" "import" "interface" "module" "native" "open" "private" "protected" "public" "static" "strictfp" "synchronized" "transient" "transitive" "volatile" + +langtools-19293ea3999f/test/tools/javac/diags/examples/ExpectedModule.java +(line 26,col 1) Parse error. Found "class", expected "module" + +langtools-19293ea3999f/test/tools/javac/diags/examples/FinallyWithoutTry.java +(line 27,col 14) Parse error. Found "finally", expected "}" +(line 30,col 5) Parse error. Found "}", expected one of ";" "@" "\u001a" "abstract" "class" "default" "enum" "final" "import" "interface" "module" "native" "open" "private" "protected" "public" "static" "strictfp" "synchronized" "transient" "transitive" "volatile" + +langtools-19293ea3999f/test/tools/javac/diags/examples/ForeachBadInitialization.java +(line 29,col 14) Parse error. Found ":", expected one of "!=" "%" "%=" "&" "&&" "&=" "(" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||" +(line 31,col 2) Parse error. Found , expected "}" +(line 31,col 2) Parse error. Found , expected one of ";" "<" "@" "abstract" "boolean" "byte" "char" "class" "default" "double" "enum" "exports" "final" "float" "int" "interface" "long" "module" "native" "open" "opens" "private" "protected" "provides" "public" "requires" "short" "static" "strictfp" "synchronized" "to" "transient" "transitive" "uses" "void" "volatile" "with" "{" "}" + +langtools-19293ea3999f/test/tools/javac/diags/examples/IdentifierExpected.java +(line 30,col 1) Parse error. Found "{", expected one of "enum" "exports" "module" "open" "opens" "provides" "requires" "strictfp" "to" "transitive" "uses" "with" + +langtools-19293ea3999f/test/tools/javac/diags/examples/IllegalAnnotationDeclaration.java +(line 27,col 5) Parse error. Found "@", expected "}" +(line 29,col 5) Parse error. Found "}", expected one of ";" "@" "\u001a" "abstract" "class" "default" "enum" "final" "import" "interface" "module" "native" "open" "private" "protected" "public" "static" "strictfp" "synchronized" "transient" "transitive" "volatile" + +langtools-19293ea3999f/test/tools/javac/diags/examples/IllegalChar.java +Lexical error at line 27, column 13. Encountered: "`" (96), after : "" + +langtools-19293ea3999f/test/tools/javac/diags/examples/IllegalComboModifiers.java +(line 27,col 5) Can have only one of 'public', 'private'. + +langtools-19293ea3999f/test/tools/javac/diags/examples/IllegalDot.java +(line 27,col 12) Parse error. Found ".", expected one of "..." "@" "enum" "exports" "module" "open" "opens" "provides" "requires" "strictfp" "to" "transitive" "uses" "with" + +langtools-19293ea3999f/test/tools/javac/diags/examples/IllegalEscapeChar.java +Lexical error at line 27, column 18. Encountered: "!" (33), after : "\"\\" + +langtools-19293ea3999f/test/tools/javac/diags/examples/IllegalLineEndInCharLit.java +Lexical error at line 27, column 15. Encountered: "\n" (10), after : "\'" + +langtools-19293ea3999f/test/tools/javac/diags/examples/IllegalNonAsciiDigit.java +(line 27,col 13) Parse error. Found "\\u0660" , expected one of "!=" "%" "%=" "&" "&&" "&=" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||" + +langtools-19293ea3999f/test/tools/javac/diags/examples/IllegalStartOfExpr.java +(line 27,col 11) Parse error. Found "=", expected one of "!" "(" "+" "++" "-" "--" "@" "boolean" "byte" "char" "double" "enum" "exports" "false" "float" "int" "long" "module" "new" "null" "open" "opens" "provides" "requires" "short" "strictfp" "super" "this" "to" "transitive" "true" "uses" "void" "with" "{" "~" + +langtools-19293ea3999f/test/tools/javac/diags/examples/IllegalStartOfStmt.java +(line 29,col 17) Parse error. Found "}", expected one of "(" "++" "--" ";" "@" "assert" "boolean" "break" "byte" "char" "continue" "do" "double" "enum" "exports" "false" "float" "for" "if" "int" "long" "module" "new" "null" "open" "opens" "provides" "requires" "return" "short" "strictfp" "super" "switch" "synchronized" "this" "throw" "to" "transitive" "true" "try" "uses" "void" "while" "with" "{" +(line 31,col 2) Parse error. Found , expected one of "else" "}" +(line 31,col 2) Parse error. Found , expected one of ";" "<" "@" "abstract" "boolean" "byte" "char" "class" "default" "double" "enum" "exports" "final" "float" "int" "interface" "long" "module" "native" "open" "opens" "private" "protected" "provides" "public" "requires" "short" "static" "strictfp" "synchronized" "to" "transient" "transitive" "uses" "void" "volatile" "with" "{" "}" + +langtools-19293ea3999f/test/tools/javac/diags/examples/IllegalStartOfType.java +(line 27,col 27) Parse error. Found ")", expected one of "boolean" "byte" "char" "double" "float" "int" "long" "short" + +langtools-19293ea3999f/test/tools/javac/diags/examples/IllegalUnderscore.java +(line 27,col 13) Parse error. Found "_" , expected one of "!=" "%" "%=" "&" "&&" "&=" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||" + +langtools-19293ea3999f/test/tools/javac/diags/examples/IllegalUnicodeEscape.java +Lexical error at line 27, column 15. Encountered: ";" (59), after : "\\u" + +langtools-19293ea3999f/test/tools/javac/diags/examples/InitializerNotAllowed.java +(line 27,col 5) An interface cannot have initializers. + +langtools-19293ea3999f/test/tools/javac/diags/examples/InterfaceNotAllowed.java +(line 28,col 9) There is no such thing as a local interface. + +langtools-19293ea3999f/test/tools/javac/diags/examples/IntfAnnotationCantHaveTypeParams.java +(line 26,col 12) Parse error. Found "<", expected "{" + +langtools-19293ea3999f/test/tools/javac/diags/examples/IntfAnnotationsCantHaveParams.java +(line 27,col 17) Parse error. Found "int", expected ")" + +langtools-19293ea3999f/test/tools/javac/diags/examples/IntfAnnotationsCantHaveTypeParams.java +(line 26,col 14) Parse error. Found "<", expected one of ";" "@" "abstract" "boolean" "byte" "char" "class" "default" "double" "enum" "exports" "final" "float" "int" "interface" "long" "module" "native" "open" "opens" "private" "protected" "provides" "public" "requires" "short" "static" "strictfp" "synchronized" "to" "transient" "transitive" "uses" "volatile" "with" "}" + +langtools-19293ea3999f/test/tools/javac/diags/examples/InvalidBinaryNumber.java +(line 27,col 13) Parse error. Found "b201000010" , expected one of "!=" "%" "%=" "&" "&&" "&=" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||" + +langtools-19293ea3999f/test/tools/javac/diags/examples/InvalidHexNumber.java +(line 28,col 13) Parse error. Found "xz1357abc" , expected one of "!=" "%" "%=" "&" "&&" "&=" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||" + +langtools-19293ea3999f/test/tools/javac/diags/examples/InvalidModuleDirective/module-info.java +(line 27,col 21) Parse error. Found "resuires" , expected one of "exports" "opens" "provides" "requires" "uses" "}" + +langtools-19293ea3999f/test/tools/javac/diags/examples/LocalEnum.java +(line 28,col 14) Parse error. Found "{", expected one of "," ";" "=" "@" "[" + +langtools-19293ea3999f/test/tools/javac/diags/examples/MalformedFpLit.java +(line 28,col 15) Parse error. Found "e" , expected one of "!=" "%" "%=" "&" "&&" "&=" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||" + +langtools-19293ea3999f/test/tools/javac/diags/examples/ModifierNotAllowed.java +(line 26,col 1) 'synchronized' is not allowed here. + +langtools-19293ea3999f/test/tools/javac/diags/examples/NoAnnotationsOnDotClass.java +(line 30,col 14) Parse error. Found "@", expected one of "!" "(" "enum" "exports" "false" "module" "new" "null" "open" "opens" "provides" "requires" "strictfp" "super" "this" "to" "transitive" "true" "uses" "with" "~" + +langtools-19293ea3999f/test/tools/javac/diags/examples/NotAllowedClass.java +(line 28,col 17) Parse error. Found "class", expected one of "(" "++" "--" ";" "@" "assert" "boolean" "break" "byte" "char" "continue" "do" "double" "enum" "exports" "false" "float" "for" "if" "int" "long" "module" "new" "null" "open" "opens" "provides" "requires" "return" "short" "strictfp" "super" "switch" "synchronized" "this" "throw" "to" "transitive" "true" "try" "uses" "void" "while" "with" "{" +(line 31,col 2) Parse error. Found , expected one of "else" "}" +(line 31,col 2) Parse error. Found , expected one of ";" "<" "@" "abstract" "boolean" "byte" "char" "class" "default" "double" "enum" "exports" "final" "float" "int" "interface" "long" "module" "native" "open" "opens" "private" "protected" "provides" "public" "requires" "short" "static" "strictfp" "synchronized" "to" "transient" "transitive" "uses" "void" "volatile" "with" "{" "}" + +langtools-19293ea3999f/test/tools/javac/diags/examples/NotAllowedVariable.java +(line 28,col 17) Parse error. Found "int", expected one of "(" "enum" "exports" "false" "module" "new" "null" "open" "opens" "provides" "requires" "strictfp" "super" "this" "to" "transitive" "true" "uses" "with" + +langtools-19293ea3999f/test/tools/javac/diags/examples/NotAStatement.java +(line 27,col 14) Parse error. Found "x" , expected "}" + +langtools-19293ea3999f/test/tools/javac/diags/examples/Orphaned.java +(line 27,col 14) Parse error. Found "case", expected "}" + +langtools-19293ea3999f/test/tools/javac/diags/examples/PrematureEOF.java +(line 26,col 20) Parse error. Found , expected one of ";" "<" "@" "abstract" "boolean" "byte" "char" "class" "default" "double" "enum" "exports" "final" "float" "int" "interface" "long" "module" "native" "open" "opens" "private" "protected" "provides" "public" "requires" "short" "static" "strictfp" "synchronized" "to" "transient" "transitive" "uses" "void" "volatile" "with" "{" "}" + +langtools-19293ea3999f/test/tools/javac/diags/examples/ProcessorWrongType/ProcessorWrongType.java +Parse error. Found "clas" , expected one of ";" "@" "\u001a" "abstract" "class" "default" "enum" "final" "import" "interface" "module" "native" "open" "private" "protected" "public" "static" "strictfp" "synchronized" "transient" "transitive" "volatile" + +langtools-19293ea3999f/test/tools/javac/diags/examples/RepeatedModifier.java +(line 27,col 12) Duplicated modifier + +langtools-19293ea3999f/test/tools/javac/diags/examples/ThisAsIdentifier.java +(line 27,col 5) Parse error. Found "this", expected one of "enum" "exports" "module" "open" "opens" "provides" "requires" "strictfp" "to" "transitive" "uses" "with" + +langtools-19293ea3999f/test/tools/javac/diags/examples/ThrowsNotAllowedInAnno.java +(line 27,col 18) Parse error. Found "throws", expected one of ";" "default" + +langtools-19293ea3999f/test/tools/javac/diags/examples/TryWithoutCatchOrFinally.java +(line 29,col 9) Try has no finally, no catch, and no resources. + +langtools-19293ea3999f/test/tools/javac/diags/examples/TryWithoutCatchOrFinallyOrResource.java +(line 28,col 9) Try has no finally, no catch, and no resources. + +langtools-19293ea3999f/test/tools/javac/diags/examples/TypeReqClassArray.java +(line 30,col 34) Parse error. Found ")", expected "[" + +langtools-19293ea3999f/test/tools/javac/diags/examples/UnclosedCharLiteral.java +Lexical error at line 27, column 16. Encountered: ";" (59), after : "\'a" + +langtools-19293ea3999f/test/tools/javac/diags/examples/UnclosedComment.java +Lexical error at line 31, column 0. Encountered: after : "" + +langtools-19293ea3999f/test/tools/javac/diags/examples/UnclosedStringLiteral.java +Lexical error at line 27, column 21. Encountered: "\n" (10), after : "\"abc;" + +langtools-19293ea3999f/test/tools/javac/diags/examples/UnderscoreAsIdentifierError.java +(line 27,col 12) '_' is a reserved keyword. + +langtools-19293ea3999f/test/tools/javac/diags/examples/UnderscoreAsIdentifierWarning.java +(line 28,col 12) '_' is a reserved keyword. + +langtools-19293ea3999f/test/tools/javac/diags/examples/UnderscoreInLambdaExpression.java +(line 26,col 52) '_' is a reserved keyword. + +langtools-19293ea3999f/test/tools/javac/diags/examples/UnexpectedTokenInModuleInfo/module-info.java +Parse error. Found "weak" , expected one of ";" "@" "\u001a" "abstract" "class" "default" "enum" "final" "import" "interface" "module" "native" "open" "private" "protected" "public" "static" "strictfp" "synchronized" "transient" "transitive" "volatile" + +langtools-19293ea3999f/test/tools/javac/diags/examples/VarargsAndReceiver.java +(line 27,col 30) Parse error. Found "this", expected one of "enum" "exports" "module" "open" "opens" "provides" "requires" "strictfp" "to" "transitive" "uses" "with" + +langtools-19293ea3999f/test/tools/javac/Digits.java +(line 11,col 40) Parse error. Found "\\u0663" , expected one of "!=" "%" "%=" "&" "&&" "&=" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||" + +langtools-19293ea3999f/test/tools/javac/enum/EnumAsIdentifier.java +(line 11,col 9) 'enum' cannot be used as an identifier as it is a keyword. + +langtools-19293ea3999f/test/tools/javac/enum/EnumMembersOrder.java +(line 11,col 10) Parse error. Found "d" , expected one of "!=" "%" "%=" "&" "&&" "&=" "(" ")" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||" + +langtools-19293ea3999f/test/tools/javac/enum/ExplicitlyAbstractEnum1.java +(line 9,col 1) 'abstract' is not allowed here. + +langtools-19293ea3999f/test/tools/javac/enum/ExplicitlyAbstractEnum2.java +(line 9,col 1) 'abstract' is not allowed here. + +langtools-19293ea3999f/test/tools/javac/enum/ExplicitlyFinalEnum1.java +(line 9,col 1) 'final' is not allowed here. + +langtools-19293ea3999f/test/tools/javac/enum/ExplicitlyFinalEnum2.java +(line 9,col 1) 'final' is not allowed here. + +langtools-19293ea3999f/test/tools/javac/enum/LocalEnum.java +(line 11,col 14) Parse error. Found "{", expected one of "," ";" "=" "@" "[" +(line 13,col 2) Parse error. Found , expected "}" +(line 13,col 2) Parse error. Found , expected one of ";" "<" "@" "abstract" "boolean" "byte" "char" "class" "default" "double" "enum" "exports" "final" "float" "int" "interface" "long" "module" "native" "open" "opens" "private" "protected" "provides" "public" "requires" "short" "static" "strictfp" "synchronized" "to" "transient" "transitive" "uses" "void" "volatile" "with" "{" "}" + +langtools-19293ea3999f/test/tools/javac/EOI.java +(line 10,col 16) Parse error. Found "foobar\u001a" , expected one of ";" "@" "\u001a" "abstract" "class" "default" "enum" "final" "import" "interface" "module" "native" "open" "private" "protected" "public" "static" "strictfp" "synchronized" "transient" "transitive" "volatile" + +langtools-19293ea3999f/test/tools/javac/ExtendArray.java +(line 11,col 34) Parse error. Found "[", expected one of "," "implements" "{" + +langtools-19293ea3999f/test/tools/javac/ExtraneousEquals.java +(line 10,col 22) Parse error. Found "=", expected one of "!" "(" "+" "++" "-" "--" "@" "]" "boolean" "byte" "char" "double" "enum" "exports" "false" "float" "int" "long" "module" "new" "null" "open" "opens" "provides" "requires" "short" "strictfp" "super" "this" "to" "transitive" "true" "uses" "void" "with" "~" + +langtools-19293ea3999f/test/tools/javac/failover/FailOver01.java +(line 10,col 20) Parse error. Found "}", expected one of "!=" "%" "%=" "&" "&&" "&=" "*" "*=" "+" "+=" "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||" +(line 10,col 26) Parse error. Found , expected "}" +(line 10,col 26) Parse error. Found , expected one of ";" "<" "@" "abstract" "boolean" "byte" "char" "class" "default" "double" "enum" "exports" "final" "float" "int" "interface" "long" "module" "native" "open" "opens" "private" "protected" "provides" "public" "requires" "short" "static" "strictfp" "synchronized" "to" "transient" "transitive" "uses" "void" "volatile" "with" "{" "}" + +langtools-19293ea3999f/test/tools/javac/failover/FailOver15.java +(line 17,col 9) Parse error. Found "}", expected one of "%=" "&=" "*=" "++" "+=" "--" "-=" "/=" ";" "<<=" "=" ">>=" ">>>=" "^=" "|=" +(line 19,col 2) Parse error. Found , expected "}" +(line 19,col 2) Parse error. Found , expected one of ";" "<" "@" "abstract" "boolean" "byte" "char" "class" "default" "double" "enum" "exports" "final" "float" "int" "interface" "long" "module" "native" "open" "opens" "private" "protected" "provides" "public" "requires" "short" "static" "strictfp" "synchronized" "to" "transient" "transitive" "uses" "void" "volatile" "with" "{" "}" + +langtools-19293ea3999f/test/tools/javac/FloatingPointChanges/BadConstructorModifiers.java +(line 12,col 5) 'strictfp' is not allowed here. + +langtools-19293ea3999f/test/tools/javac/generics/typevars/5060485/Compatibility02.java +(line 36,col 9) 'static' is not allowed here. + +langtools-19293ea3999f/test/tools/javac/generics/typevars/6680106/T6680106.java +(line 11,col 24) Parse error. Found "[", expected one of "&" "," ">" + +langtools-19293ea3999f/test/tools/javac/IllegalAnnotation.java +(line 9,col 5) Parse error. Found "@", expected "}" +(line 11,col 5) Parse error. Found "}", expected one of ";" "@" "\u001a" "abstract" "class" "default" "enum" "final" "import" "interface" "module" "native" "open" "private" "protected" "public" "static" "strictfp" "synchronized" "transient" "transitive" "volatile" + +langtools-19293ea3999f/test/tools/javac/incompleteStatements/T8000484.java +(line 9,col 14) Parse error. Found "catch", expected "}" +(line 10,col 29) Parse error. Found "else", expected one of ";" "<" "@" "abstract" "boolean" "byte" "char" "class" "default" "double" "enum" "exports" "final" "float" "int" "interface" "long" "module" "native" "open" "opens" "private" "protected" "provides" "public" "requires" "short" "static" "strictfp" "synchronized" "to" "transient" "transitive" "uses" "void" "volatile" "with" "{" "}" + +langtools-19293ea3999f/test/tools/javac/LabeledDeclaration.java +(line 12,col 8) Parse error. Found "int", expected one of "(" "enum" "exports" "false" "module" "new" "null" "open" "opens" "provides" "requires" "strictfp" "super" "this" "to" "transitive" "true" "uses" "with" + +langtools-19293ea3999f/test/tools/javac/lambda/8131742/T8131742.java +(line 8,col 32) Parse error. Found ".", expected one of ")" "," "@" "[" + +langtools-19293ea3999f/test/tools/javac/lambda/BadLambdaPos.java +(line 18,col 26) Parse error. Found "+", expected one of ")" "," +(line 19,col 26) Parse error. Found "instanceof", expected one of ")" "," +(line 23,col 30) Parse error. Found "+", expected one of "," ";" +(line 24,col 33) Parse error. Found "instanceof", expected one of "," ";" + +langtools-19293ea3999f/test/tools/javac/lambda/BadStatementInLambda.java +(line 18,col 19) Parse error. Found "1" , expected "}" + +langtools-19293ea3999f/test/tools/javac/lambda/funcInterfaces/LambdaTest1_neg1.java +(line 13,col 64) Parse error. Found "}", expected one of "," ";" +(line 15,col 2) Parse error. Found , expected "}" +(line 15,col 2) Parse error. Found , expected one of ";" "<" "@" "abstract" "boolean" "byte" "char" "class" "default" "double" "enum" "exports" "final" "float" "int" "interface" "long" "module" "native" "open" "opens" "private" "protected" "provides" "public" "requires" "short" "static" "strictfp" "synchronized" "to" "transient" "transitive" "uses" "void" "volatile" "with" "{" "}" + +langtools-19293ea3999f/test/tools/javac/lambda/IdentifierTest.java +(line 41,col 11) '_' is a reserved keyword. +(line 44,col 16) '_' is a reserved keyword. +(line 45,col 20) '_' is a reserved keyword. +(line 46,col 22) '_' is a reserved keyword. +(line 51,col 13) '_' is a reserved keyword. +(line 51,col 15) '_' is a reserved keyword. +(line 51,col 23) '_' is a reserved keyword. +(line 53,col 13) '_' is a reserved keyword. +(line 55,col 13) '_' is a reserved keyword. +(line 61,col 21) '_' is a reserved keyword. +(line 62,col 42) '_' is a reserved keyword. +(line 63,col 67) '_' is a reserved keyword. +(line 70,col 13) '_' is a reserved keyword. +(line 71,col 14) '_' is a reserved keyword. +(line 72,col 18) '_' is a reserved keyword. +(line 77,col 22) '_' is a reserved keyword. +(line 79,col 13) '_' is a reserved keyword. +(line 79,col 15) '_' is a reserved keyword. +(line 81,col 13) '_' is a reserved keyword. +(line 81,col 15) '_' is a reserved keyword. +(line 88,col 10) '_' is a reserved keyword. +(line 88,col 38) '_' is a reserved keyword. +(line 94,col 14) '_' is a reserved keyword. +(line 101,col 17) '_' is a reserved keyword. +(line 101,col 26) '_' is a reserved keyword. +(line 118,col 20) '_' is a reserved keyword. +(line 123,col 10) '_' is a reserved keyword. +(line 128,col 17) '_' is a reserved keyword. +(line 131,col 17) '_' is a reserved keyword. +(line 138,col 17) '_' is a reserved keyword. +(line 138,col 24) '_' is a reserved keyword. +(line 138,col 33) '_' is a reserved keyword. +(line 139,col 39) '_' is a reserved keyword. +(line 143,col 13) '_' is a reserved keyword. +(line 144,col 15) '_' is a reserved keyword. +(line 145,col 13) '_' is a reserved keyword. +(line 150,col 15) '_' is a reserved keyword. +(line 151,col 17) '_' is a reserved keyword. +(line 157,col 16) '_' is a reserved keyword. +(line 159,col 25) '_' is a reserved keyword. +(line 168,col 5) '_' is a reserved keyword. +(line 172,col 26) '_' is a reserved keyword. +(line 174,col 19) '_' is a reserved keyword. +(line 180,col 11) '_' is a reserved keyword. + +langtools-19293ea3999f/test/tools/javac/lambda/lambdaExpression/InvalidExpression1.java +(line 15,col 66) Parse error. Found "}", expected one of "!=" "%" "%=" "&" "&&" "&=" "*" "*=" "+" "+=" "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||" +(line 16,col 5) Parse error. Found "}", expected one of "," ";" +(line 17,col 2) Parse error. Found , expected "}" +(line 17,col 2) Parse error. Found , expected one of ";" "<" "@" "abstract" "boolean" "byte" "char" "class" "default" "double" "enum" "exports" "final" "float" "int" "interface" "long" "module" "native" "open" "opens" "private" "protected" "provides" "public" "requires" "short" "static" "strictfp" "synchronized" "to" "transient" "transitive" "uses" "void" "volatile" "with" "{" "}" + +langtools-19293ea3999f/test/tools/javac/lambda/UnderscoreAsIdent.java +(line 30,col 9) '_' is a reserved keyword. +(line 30,col 9) '_' is a reserved keyword. +(line 32,col 8) '_' is a reserved keyword. +(line 32,col 8) '_' is a reserved keyword. +(line 34,col 7) '_' is a reserved keyword. +(line 35,col 12) '_' is a reserved keyword. +(line 36,col 10) '_' is a reserved keyword. +(line 36,col 19) '_' is a reserved keyword. +(line 38,col 16) '_' is a reserved keyword. +(line 41,col 18) '_' is a reserved keyword. +(line 41,col 25) '_' is a reserved keyword. +(line 41,col 33) '_' is a reserved keyword. +(line 44,col 34) '_' is a reserved keyword. +(line 47,col 9) '_' is a reserved keyword. +(line 49,col 19) '_' is a reserved keyword. +(line 51,col 9) '_' is a reserved keyword. +(line 53,col 22) '_' is a reserved keyword. + +langtools-19293ea3999f/test/tools/javac/lambda/VoidLambdaParameter.java +(line 7,col 18) Parse error. Found "void", expected one of "!" "(" ")" "enum" "exports" "false" "module" "new" "null" "open" "opens" "provides" "requires" "strictfp" "super" "this" "to" "transitive" "true" "uses" "with" "~" + +langtools-19293ea3999f/test/tools/javac/literals/BadBinaryLiterals.java +(line 11,col 20) Parse error. Found "2" , expected one of "!=" "%" "%=" "&" "&&" "&=" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||" + +langtools-19293ea3999f/test/tools/javac/literals/BadUnderscoreLiterals.java +(line 15,col 14) Parse error. Found "_" , expected one of "!=" "%" "%=" "&" "&&" "&=" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||" + +langtools-19293ea3999f/test/tools/javac/literals/T6891079.java +(line 8,col 14) Parse error. Found "B" , expected one of "!=" "%" "%=" "&" "&&" "&=" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||" + +langtools-19293ea3999f/test/tools/javac/modules/InvalidModuleDirective/module-info.java +(line 9,col 21) Parse error. Found "resuires" , expected one of "exports" "opens" "provides" "requires" "uses" "}" + +langtools-19293ea3999f/test/tools/javac/overrridecrash/A.java +(line 25,col 5) Can have only one of 'protected', 'private'. + +langtools-19293ea3999f/test/tools/javac/overrridecrash/B.java +(line 12,col 5) Can have only one of 'protected', 'private'. + +langtools-19293ea3999f/test/tools/javac/Parens3.java +(line 12,col 9) Parse error. Found ":", expected one of "%=" "&=" "*=" "++" "+=" "--" "-=" "/=" ";" "<<=" "=" ">>=" ">>>=" "^=" "|=" + +langtools-19293ea3999f/test/tools/javac/ParseConditional.java +(line 23,col 13) Illegal left hand side of an assignment. + +langtools-19293ea3999f/test/tools/javac/parser/7157165/T7157165.java +(line 11,col 19) Parse error. Found "|", expected one of "," ">" + +langtools-19293ea3999f/test/tools/javac/parser/8081769/T8081769.java +(line 9,col 20) Parse error. Found ".", expected one of "!=" "%" "%=" "&" "&&" "&=" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||" +(line 10,col 20) Parse error. Found ".", expected one of "!=" "%" "%=" "&" "&&" "&=" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||" +(line 11,col 20) Parse error. Found ".", expected one of "!=" "%" "%=" "&" "&&" "&=" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||" +(line 12,col 20) Parse error. Found ".", expected one of "!=" "%" "%=" "&" "&&" "&=" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||" +(line 14,col 31) Parse error. Found ".", expected one of "!=" "%" "%=" "&" "&&" "&=" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||" + +langtools-19293ea3999f/test/tools/javac/parser/ErroneousParameters.java +(line 11,col 34) Parse error. Found "...", expected one of ")" "," "@" "[" + +langtools-19293ea3999f/test/tools/javac/parser/MissingClosingBrace.java +(line 13,col 1) Parse error. Found , expected one of "else" "}" +(line 13,col 2) Parse error. Found , expected one of ";" "<" "@" "abstract" "boolean" "byte" "char" "class" "default" "double" "enum" "exports" "final" "float" "int" "interface" "long" "module" "native" "open" "opens" "private" "protected" "provides" "public" "requires" "short" "static" "strictfp" "synchronized" "to" "transient" "transitive" "uses" "void" "volatile" "with" "{" "}" + +langtools-19293ea3999f/test/tools/javac/parser/SingleCommaAnnotationValueFail.java +(line 34,col 11) Parse error. Found "0" , expected "}" + +langtools-19293ea3999f/test/tools/javac/parser/T4881269.java +(line 32,col 10) Parse error. Found ".", expected one of "enum" "exports" "module" "open" "opens" "provides" "requires" "strictfp" "to" "transitive" "uses" "with" + +langtools-19293ea3999f/test/tools/javac/policy/test3/A.java +(line 5,col 36) Parse error. Found "0" , expected "}" + +langtools-19293ea3999f/test/tools/javac/processing/6994946/SyntaxErrorTest.java +(line 14,col 9) Parse error. Found "}", expected "(" + +langtools-19293ea3999f/test/tools/javac/processing/errors/TestParseErrors/ParseErrors.java +(line 37,col 36) Parse error. Found ",", expected one of "..." "@" "enum" "exports" "module" "open" "opens" "provides" "requires" "strictfp" "to" "transitive" "uses" "with" + +langtools-19293ea3999f/test/tools/javac/quid/T6999438.java +Lexical error at line 8, column 9. Encountered: "#" (35), after : "" + +langtools-19293ea3999f/test/tools/javac/rawDiags/Error.java +(line 9,col 17) Parse error. Found , expected "(" + +langtools-19293ea3999f/test/tools/javac/StoreClass.java +(line 12,col 9) Illegal left hand side of an assignment. +(line 13,col 9) Illegal left hand side of an assignment. + +langtools-19293ea3999f/test/tools/javac/SynchronizedClass.java +(line 9,col 1) 'synchronized' is not allowed here. + +langtools-19293ea3999f/test/tools/javac/T4994049/T4994049.java +(line 11,col 5) Parse error. Found "BAR" , expected one of "," ";" "}" + +langtools-19293ea3999f/test/tools/javac/T6882235.java +(line 10,col 11) Parse error. Found ";", expected one of "!" "(" "+" "++" "-" "--" "@" "boolean" "byte" "char" "double" "enum" "exports" "false" "float" "int" "long" "module" "new" "null" "open" "opens" "provides" "requires" "short" "strictfp" "super" "this" "to" "transitive" "true" "uses" "void" "with" "{" "~" + +langtools-19293ea3999f/test/tools/javac/T8026963/TypeAnnotationsCrashWithErroneousTreeTest.java +(line 9,col 19) Parse error. Found "this", expected one of ")" "@" "abstract" "boolean" "byte" "char" "default" "double" "enum" "exports" "final" "float" "int" "long" "module" "native" "open" "opens" "private" "protected" "provides" "public" "requires" "short" "static" "strictfp" "synchronized" "to" "transient" "transitive" "uses" "volatile" "with" + +langtools-19293ea3999f/test/tools/javac/T8171325/NPEClearingLocalClassNameIndexesTest.java +(line 19,col 42) Type arguments may not be primitive. + +langtools-19293ea3999f/test/tools/javac/T8175198/AnnotationsAndFormalParamsTest.java +(line 9,col 14) Parse error. Found "int", expected ")" + +langtools-19293ea3999f/test/tools/javac/T8181464/LambdaInAnnotationsCausesNPETest1.java +(line 10,col 15) Parse error. Found "->", expected one of "!=" "%" "&" "&&" "(" ")" "*" "+" "," "-" "/" "<" "<=" "==" ">" ">=" "?" "^" "instanceof" "|" "||" + +langtools-19293ea3999f/test/tools/javac/T8181464/LambdaInAnnotationsCausesNPETest2.java +(line 10,col 24) Parse error. Found "->", expected one of "!=" "%" "&" "&&" ")" "*" "+" "," "-" "/" "<" "<=" "==" ">" ">=" "?" "^" "instanceof" "|" "||" + +langtools-19293ea3999f/test/tools/javac/TryWithResources/BadTwrSyntax.java +(line 14,col 42) Parse error. Found ";", expected ")" +(line 14,col 43) Parse error. Found ")", expected "}" +(line 16,col 9) Parse error. Found "try", expected one of ";" "<" "@" "abstract" "boolean" "byte" "char" "class" "default" "double" "enum" "exports" "final" "float" "int" "interface" "long" "module" "native" "open" "opens" "private" "protected" "provides" "public" "requires" "short" "static" "strictfp" "synchronized" "to" "transient" "transitive" "uses" "void" "volatile" "with" "{" "}" + +langtools-19293ea3999f/test/tools/javac/TryWithResources/PlainTry.java +(line 11,col 9) Try has no finally, no catch, and no resources. + +langtools-19293ea3999f/test/tools/javac/TryWithResources/ResDeclOutsideTry.java +(line 14,col 14) Parse error. Found "=", expected one of "(" ")" +(line 14,col 48) Parse error. Found ")", expected "}" +(line 15,col 9) Parse error. Found "return", expected one of ";" "<" "@" "abstract" "boolean" "byte" "char" "class" "default" "double" "enum" "exports" "final" "float" "int" "interface" "long" "module" "native" "open" "opens" "private" "protected" "provides" "public" "requires" "short" "static" "strictfp" "synchronized" "to" "transient" "transitive" "uses" "void" "volatile" "with" "{" "}" + +langtools-19293ea3999f/test/tools/javac/TryWithResources/TwrForVariable2.java +(line 13,col 13) Parse error. Found "final", expected one of "(" "@" "boolean" "byte" "char" "double" "enum" "exports" "false" "float" "int" "long" "module" "new" "null" "open" "opens" "provides" "requires" "short" "strictfp" "super" "this" "to" "transitive" "true" "uses" "void" "with" +(line 15,col 9) Parse error. Found "try", expected one of ";" "<" "@" "abstract" "boolean" "byte" "char" "class" "default" "double" "enum" "exports" "final" "float" "int" "interface" "long" "module" "native" "open" "opens" "private" "protected" "provides" "public" "requires" "short" "static" "strictfp" "synchronized" "to" "transient" "transitive" "uses" "void" "volatile" "with" "{" "}" + +langtools-19293ea3999f/test/tools/javac/unicode/FirstChar2.java +Parse error. Found "\\u0070ublic" , expected one of ";" "@" "\u001a" "abstract" "class" "default" "enum" "final" "import" "interface" "module" "native" "open" "private" "protected" "public" "static" "strictfp" "synchronized" "transient" "transitive" "volatile" + +langtools-19293ea3999f/test/tools/javac/unicode/NonasciiDigit.java +(line 13,col 18) Parse error. Found "\\uff11" , expected one of "!=" "%" "%=" "&" "&&" "&=" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||" +(line 16,col 21) Parse error. Found ".0" , expected one of "!=" "%" "%=" "&" "&&" "&=" "(" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||" +(line 17,col 21) Parse error. Found "\\uff11" , expected one of "!=" "%" "%=" "&" "&&" "&=" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||" +(line 18,col 21) Parse error. Found "P\\uff11" , expected one of "!=" "%" "%=" "&" "&&" "&=" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||" +(line 19,col 21) Parse error. Found "E\\uff11" , expected one of "!=" "%" "%=" "&" "&&" "&=" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||" +(line 20,col 19) Parse error. Found ".", expected one of "!" "(" "+" "++" "-" "--" "@" "boolean" "byte" "char" "double" "enum" "exports" "false" "float" "int" "long" "module" "new" "null" "open" "opens" "provides" "requires" "short" "strictfp" "super" "this" "to" "transitive" "true" "uses" "void" "with" "{" "~" +(line 21,col 21) Parse error. Found ".0" , expected one of "!=" "%" "%=" "&" "&&" "&=" "(" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||" + +langtools-19293ea3999f/test/tools/javac/unicode/TripleQuote.java +Lexical error at line 13, column 15. Encountered: "\'" (39), after : "\'" + +langtools-19293ea3999f/test/tools/javac/unicode/UnicodeAtEOL.java +(line 33,col 13) Parse error. Found "\\u000D" , expected "}" + +langtools-19293ea3999f/test/tools/javac/unicode/UnicodeCommentDelimiter.java +(line 44,col 22) Parse error. Found "plugh" , expected one of "," ";" "=" "@" "[" + +langtools-19293ea3999f/test/tools/javac/VoidArray.java +(line 12,col 5) Parse error. Found "[", expected one of "enum" "exports" "module" "open" "opens" "provides" "requires" "strictfp" "to" "transitive" "uses" "with" + +langtools-19293ea3999f/test/tools/javadoc/6964914/Error.java +(line 25,col 12) Parse error. Found "}", expected "(" + +langtools-19293ea3999f/test/tools/javadoc/6964914/JavacWarning.java +(line 25,col 12) '_' is a reserved keyword. + +langtools-19293ea3999f/test/tools/javadoc/enum/docComments/pkg1/Operation.java +(line 33,col 1) 'abstract' is not allowed here. + +langtools-19293ea3999f/test/tools/javadoc/T4994049/FileWithTabs.java +Lexical error at line 25, column 2. Encountered: "t" (116), after : "\\" + +304 problems in 175 files \ No newline at end of file diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/openjdk_src_zip_test_results.txt b/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/openjdk_src_zip_test_results.txt new file mode 100644 index 0000000..8e95fac --- /dev/null +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/bulk_test_results/openjdk_src_zip_test_results.txt @@ -0,0 +1,4 @@ +com/sun/xml/internal/rngom/parse/compact/CompactSyntax.java +Lexical error at line 244, column 38. Encountered: "n" (110), after : "\'\\u005c" + +1 problems in 1 files \ No newline at end of file diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/issue_samples/Issue290.java.txt b/javaparser-core-testing/src/test/resources/com/github/javaparser/issue_samples/Issue290.java.txt new file mode 100644 index 0000000..2b39ff8 --- /dev/null +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/issue_samples/Issue290.java.txt @@ -0,0 +1,34 @@ +package org.test; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.visitor.VoidVisitorAdapter; + +import java.io.File; +import java.io.FileInputStream; + +public class TestComments { + String str = "\\"; + + /** + * Comment that is ignored + */ + public void someTestMethod() {} + + public static void main(String[] args) throws Exception { + // Correct path so that it will point to the file with this code + try (FileInputStream in = new FileInputStream( + new File(".\\src\\main\\java\\org\\test\\TestComments.java"))) { + CompilationUnit compilationUnit = JavaParser.parse(in); + + new VoidVisitorAdapter() { + public void visit(MethodDeclaration method, Object arg) { + System.out.println("Method: " + method.getName()); + System.out.println("Comment: " + method.getComment()); + System.out.println("JavaDoc: " + method.getJavaDoc() + "\n"); + } + }.visit(compilationUnit, null); + } + } +} \ No newline at end of file diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/issue_samples/Issue412.java.expected.txt b/javaparser-core-testing/src/test/resources/com/github/javaparser/issue_samples/Issue412.java.expected.txt new file mode 100644 index 0000000..9bc4779 --- /dev/null +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/issue_samples/Issue412.java.expected.txt @@ -0,0 +1,35 @@ +/* 1 +1 */ +/* +2 +2 + */ +package /* a */ +/* b */ +//c +//d +com.pany/*alma*/ +/*körte*/ +//lófasz +//jóska +.experiment; + +//z +//x +/*y*/ +/*w*/ +/*aa*/ +/*bb*/ +//cc +//dd +import com.github.javaparser.JavaParser; + +public class Main { + + public static void main(String[] args) throws FileNotFoundException, IOException, ParseException { + // try (FileInputStream fisTargetFile = new FileInputStream(new File(FILENAME))) { + // final String content = IOUtils.toString(fisTargetFile, "UTF-8"); + // System.out.println(content); + // } + } +} diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/issue_samples/Issue412.java.txt b/javaparser-core-testing/src/test/resources/com/github/javaparser/issue_samples/Issue412.java.txt new file mode 100644 index 0000000..3a06006 --- /dev/null +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/issue_samples/Issue412.java.txt @@ -0,0 +1,33 @@ +/* 1 +1 *//* +2 +2 + */ +package +/* a *//* b */ +//c +//d +com +/*alma*//*körte*/ +//lófasz +//jóska + . +pany +. +experiment +//z +//x +/*y*//*w*/ +; +/*aa*//*bb*///cc +//dd +import com.github.javaparser.JavaParser; + +public class Main { + public static void main(String[] args) throws FileNotFoundException, IOException, ParseException { +// try (FileInputStream fisTargetFile = new FileInputStream(new File(FILENAME))) { +// final String content = IOUtils.toString(fisTargetFile, "UTF-8"); +// System.out.println(content); +// } + } +} \ No newline at end of file diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/issue_samples/Issue624.java.txt b/javaparser-core-testing/src/test/resources/com/github/javaparser/issue_samples/Issue624.java.txt new file mode 100644 index 0000000..de86d11 --- /dev/null +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/issue_samples/Issue624.java.txt @@ -0,0 +1,14 @@ +package z; +public class A { + + @Override + protected void getDataForCalcul() { + + a.b(c)// + .success(data -> { + // DATA STD MACHINE + dosomething(); + })// + .error(defaultErrorConsumer); + } +} diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/issue_samples/issue1003.java.txt b/javaparser-core-testing/src/test/resources/com/github/javaparser/issue_samples/issue1003.java.txt new file mode 100644 index 0000000..0f8f460 --- /dev/null +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/issue_samples/issue1003.java.txt @@ -0,0 +1,1470 @@ +package com.trigtech.privateme.server.am; + +import android.app.ActivityManager; +import android.app.ActivityManager.RecentTaskInfo; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.pm.ActivityInfo; +import android.os.Handler; +import android.os.IBinder; +import android.util.SparseArray; +import com.trigtech.privateme.client.AppInterface; +import com.trigtech.privateme.client.g; +import com.trigtech.privateme.helper.proto.AppSetting; +import com.trigtech.privateme.helper.proto.AppTaskInfo; +import com.trigtech.privateme.helper.proto.i; +import com.trigtech.privateme.helper.utils.k; +import com.trigtech.privateme.helper.utils.v; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.Set; + +class ActivityStack +{ + private static final String b = ActivityStack.class.getSimpleName(); + final SparseArray

a = new SparseArray(); + private final ActivityManager c; + private final TActivityManagerService d; + private com.trigtech.privateme.helper.utils.a e = new com.trigtech.privateme.helper.utils.a(); + private com.trigtech.privateme.helper.utils.a f = new com.trigtech.privateme.helper.utils.a(); + private com.trigtech.privateme.helper.utils.a> g = new com.trigtech.privateme.helper.utils.a(); + private com.trigtech.privateme.helper.utils.a> h = new com.trigtech.privateme.helper.utils.a(); + + ActivityStack(TActivityManagerService paramTActivityManagerService) + { + this.d = paramTActivityManagerService; + this.c = ((ActivityManager)AppInterface.e().i().getSystemService("activity")); + } + + private Intent a(int paramInt, c paramc, Intent paramIntent, ActivityInfo paramActivityInfo) + { + Intent localIntent1 = new Intent(paramIntent); + j localj = this.d.startProcessIfNeedLocked(paramActivityInfo.processName, paramInt, paramActivityInfo.packageName); + if (localj == null) + return null; + Intent localIntent2 = new Intent(); + localIntent2.setClassName(AppInterface.e().k(), a(localj.i, paramActivityInfo)); + ComponentName localComponentName1 = localIntent1.getComponent(); + if (localComponentName1 == null) + localComponentName1 = k.a(paramActivityInfo); + localIntent2.setType(localComponentName1.flattenToString()); + if (((0x80 & paramActivityInfo.flags) != 0) || (b(localIntent1, 1073741824))) + localIntent2.addFlags(1073741824); + if (paramc != null); + for (ComponentName localComponentName2 = paramc.b; ; localComponentName2 = null) + { + i locali = new i(localIntent1, paramActivityInfo, localComponentName2, paramInt); + localIntent2.putExtra("_PM_|_intent_", locali.a); + localIntent2.putExtra("_PM_|_info_", locali.b); + localIntent2.putExtra("_PM_|_caller_", locali.c); + localIntent2.putExtra("_PM_|_user_id_", locali.d); + return localIntent2; + } + } + + private static c a(p paramp) + { + while (true) + { + int i; + synchronized (paramp.e) + { + i = -1 + paramp.e.size(); + if (i >= 0) + { + c localc = (c)paramp.e.get(i); + if (!localc.i) + return localc; + } + else + { + return null; + } + } + i--; + } + } + + private p a(int paramInt, Intent paramIntent) + { + for (int i = 0; i < this.a.size(); i++) + { + p localp = (p)this.a.valueAt(i); + if ((paramInt == localp.b) && (localp.d != null) && (paramIntent.getComponent().equals(localp.d.getComponent()))) + return localp; + } + return null; + } + + // ERROR // + private static String a(int paramInt, ActivityInfo paramActivityInfo) + { + // Byte code: + // 0: getstatic 214 tbox/com/android/internal/R_Hide$styleable:Window Ltbox/RefStaticObject; + // 3: invokevirtual 219 tbox/RefStaticObject:get ()Ljava/lang/Object; + // 6: checkcast 221 [I + // 9: astore 9 + // 11: getstatic 225 tbox/com/android/internal/R_Hide$styleable:Window_windowIsTranslucent Ltbox/RefStaticInt; + // 14: invokevirtual 229 tbox/RefStaticInt:get ()I + // 17: istore 10 + // 19: getstatic 232 tbox/com/android/internal/R_Hide$styleable:Window_windowIsFloating Ltbox/RefStaticInt; + // 22: invokevirtual 229 tbox/RefStaticInt:get ()I + // 25: istore 11 + // 27: getstatic 235 tbox/com/android/internal/R_Hide$styleable:Window_windowShowWallpaper Ltbox/RefStaticInt; + // 30: invokevirtual 229 tbox/RefStaticInt:get ()I + // 33: istore 12 + // 35: invokestatic 240 com/trigtech/privateme/server/am/h:a ()Lcom/trigtech/privateme/server/am/h; + // 38: aload_1 + // 39: getfield 88 android/content/pm/ActivityInfo:packageName Ljava/lang/String; + // 42: aload_1 + // 43: getfield 243 android/content/pm/ActivityInfo:theme I + // 46: aload 9 + // 48: invokevirtual 246 com/trigtech/privateme/server/am/h:a (Ljava/lang/String;I[I)Lcom/trigtech/privateme/server/am/h$a; + // 51: astore 13 + // 53: aload 13 + // 55: ifnull +154 -> 209 + // 58: aload 13 + // 60: getfield 251 com/trigtech/privateme/server/am/h$a:b Landroid/content/res/TypedArray; + // 63: ifnull +146 -> 209 + // 66: aload 13 + // 68: getfield 251 com/trigtech/privateme/server/am/h$a:b Landroid/content/res/TypedArray; + // 71: iload 12 + // 73: iconst_0 + // 74: invokevirtual 257 android/content/res/TypedArray:getBoolean (IZ)Z + // 77: istore 14 + // 79: iload 14 + // 81: istore 5 + // 83: aload 13 + // 85: getfield 251 com/trigtech/privateme/server/am/h$a:b Landroid/content/res/TypedArray; + // 88: iload 10 + // 90: iconst_0 + // 91: invokevirtual 257 android/content/res/TypedArray:getBoolean (IZ)Z + // 94: istore 17 + // 96: iload 17 + // 98: istore 6 + // 100: aload 13 + // 102: getfield 251 com/trigtech/privateme/server/am/h$a:b Landroid/content/res/TypedArray; + // 105: iload 11 + // 107: iconst_0 + // 108: invokevirtual 257 android/content/res/TypedArray:getBoolean (IZ)Z + // 111: istore 19 + // 113: iload 19 + // 115: istore 7 + // 117: iload 7 + // 119: ifne +16 -> 135 + // 122: iload 6 + // 124: ifne +11 -> 135 + // 127: iconst_0 + // 128: istore 8 + // 130: iload 5 + // 132: ifeq +6 -> 138 + // 135: iconst_1 + // 136: istore 8 + // 138: iload 8 + // 140: ifeq +31 -> 171 + // 143: iload_0 + // 144: invokestatic 262 com/trigtech/privateme/client/stub/a:b (I)Ljava/lang/String; + // 147: areturn + // 148: astore_2 + // 149: iconst_0 + // 150: istore_3 + // 151: iconst_0 + // 152: istore 4 + // 154: aload_2 + // 155: invokevirtual 265 java/lang/Throwable:printStackTrace ()V + // 158: iload_3 + // 159: istore 5 + // 161: iload 4 + // 163: istore 6 + // 165: iconst_0 + // 166: istore 7 + // 168: goto -51 -> 117 + // 171: iload_0 + // 172: invokestatic 267 com/trigtech/privateme/client/stub/a:a (I)Ljava/lang/String; + // 175: areturn + // 176: astore 15 + // 178: iload 5 + // 180: istore 16 + // 182: aload 15 + // 184: astore_2 + // 185: iload 16 + // 187: istore_3 + // 188: iconst_0 + // 189: istore 4 + // 191: goto -37 -> 154 + // 194: astore 18 + // 196: iload 6 + // 198: istore 4 + // 200: iload 5 + // 202: istore_3 + // 203: aload 18 + // 205: astore_2 + // 206: goto -52 -> 154 + // 209: iconst_0 + // 210: istore 5 + // 212: iconst_0 + // 213: istore 6 + // 215: iconst_0 + // 216: istore 7 + // 218: goto -101 -> 117 + // + // Exception table: + // from to target type + // 0 53 148 java/lang/Throwable + // 58 79 148 java/lang/Throwable + // 83 96 176 java/lang/Throwable + // 100 113 194 java/lang/Throwable + } + + private void a() + { + ArrayList localArrayList = new ArrayList(this.c.getRecentTasks(2147483647, 3)); + int i = this.a.size(); + int j = i - 1; + p localp; + int k; + if (i > 0) + { + localp = (p)this.a.valueAt(j); + ListIterator localListIterator = localArrayList.listIterator(); + while (localListIterator.hasNext()) + if (((ActivityManager.RecentTaskInfo)localListIterator.next()).id == localp.a) + { + k = 1; + localListIterator.remove(); + } + } + while (true) + { + if (k == 0) + { + this.a.removeAt(j); + b(localp); + } + i = j; + break; + return; + k = 0; + } + } + + private static void a(Intent paramIntent, int paramInt) + { + paramIntent.setFlags(paramIntent.getFlags() & (paramInt ^ 0xFFFFFFFF)); + } + + private static boolean a(p paramp, ClearTarget paramClearTarget, ComponentName paramComponentName) + { + boolean bool1 = false; + boolean bool3; + switch (e.a[paramClearTarget.ordinal()]) + { + default: + return false; + case 1: + synchronized (paramp.e) + { + Iterator localIterator2 = paramp.e.iterator(); + while (localIterator2.hasNext()) + { + ((c)localIterator2.next()).i = true; + bool1 = true; + } + return bool1; + } + case 2: + synchronized (paramp.e) + { + Iterator localIterator1 = paramp.e.iterator(); + if (localIterator1.hasNext()) + { + c localc = (c)localIterator1.next(); + if (localc.b.equals(paramComponentName)) + { + localc.i = true; + bool3 = true; + break label307; + } + } + else + { + return bool1; + } + } + case 3: + } + while (true) + { + int i; + int j; + boolean bool2; + int k; + synchronized (paramp.e) + { + i = paramp.e.size(); + j = i - 1; + bool2 = false; + if (i <= 0) + break label313; + if (!((c)paramp.e.get(j)).b.equals(paramComponentName)) + break label325; + bool2 = true; + break label313; + int m = k + 1; + if (k < -1 + paramp.e.size()) + { + ((c)paramp.e.get(m)).i = true; + k = m; + continue; + } + return bool2; + } + bool3 = bool1; + label307: bool1 = bool3; + break; + label313: if (bool2) + { + k = j; + continue; + label325: i = j; + } + } + } + + private p b(int paramInt, String paramString) + { + for (int i = 0; i < this.a.size(); i++) + { + p localp = (p)this.a.valueAt(i); + if ((paramInt == localp.b) && (paramString.equals(localp.c))) + return localp; + } + return null; + } + + private void b() + { + int j; + for (int i = this.a.size(); ; i = j) + { + j = i - 1; + if (i <= 0) + break; + Iterator localIterator = ((p)this.a.valueAt(j)).e.iterator(); + while (localIterator.hasNext()) + { + c localc = (c)localIterator.next(); + if (localc.i) + g.a().post(new d(this, localc)); + } + } + } + + private void b(p paramp) + { + Iterator localIterator1 = this.h.keySet().iterator(); + while (localIterator1.hasNext()) + { + Integer localInteger2 = (Integer)localIterator1.next(); + List localList2 = (List)this.h.get(localInteger2); + Iterator localIterator4 = paramp.e.iterator(); + while (localIterator4.hasNext()) + { + c localc2 = (c)localIterator4.next(); + if (localList2.contains(localc2)) + { + v.a(b, "optimizeActivities started, activity: %s", new Object[] { localc2 }); + localList2.remove(localc2); + } + } + } + Iterator localIterator2 = this.g.keySet().iterator(); + while (localIterator2.hasNext()) + { + Integer localInteger1 = (Integer)localIterator2.next(); + List localList1 = (List)this.g.get(localInteger1); + Iterator localIterator3 = paramp.e.iterator(); + while (localIterator3.hasNext()) + { + c localc1 = (c)localIterator3.next(); + if (localList1.contains(localc1)) + { + v.a(b, "optimizeActivities resumed, activity: %s", new Object[] { localc1 }); + localList1.remove(localc1); + } + } + } + } + + private static boolean b(Intent paramIntent, int paramInt) + { + return (paramInt & paramIntent.getFlags()) != 0; + } + + private List e(int paramInt) + { + Object localObject = (List)this.g.get(Integer.valueOf(paramInt)); + if (localObject == null) + { + localObject = new ArrayList(); + this.g.put(Integer.valueOf(paramInt), localObject); + } + return localObject; + } + + private f f(int paramInt) + { + f localf = (f)this.f.get(Integer.valueOf(paramInt)); + if (localf == null) + { + localf = new f(); + this.f.put(Integer.valueOf(paramInt), localf); + } + return localf; + } + + // ERROR // + final int a(int paramInt1, Intent paramIntent, ActivityInfo paramActivityInfo, IBinder paramIBinder, android.os.Bundle paramBundle, String paramString, int paramInt2) + { + // Byte code: + // 0: getstatic 31 com/trigtech/privateme/server/am/ActivityStack:b Ljava/lang/String; + // 3: astore 8 + // 5: iconst_2 + // 6: anewarray 4 java/lang/Object + // 9: astore 9 + // 11: aload 9 + // 13: iconst_0 + // 14: aload_3 + // 15: getfield 402 android/content/pm/ActivityInfo:name Ljava/lang/String; + // 18: aastore + // 19: aload 9 + // 21: iconst_1 + // 22: aload 4 + // 24: aastore + // 25: aload 8 + // 27: ldc_w 404 + // 30: aload 9 + // 32: invokestatic 376 com/trigtech/privateme/helper/utils/v:a (Ljava/lang/String;Ljava/lang/String;[Ljava/lang/Object;)V + // 35: aload_0 + // 36: invokespecial 406 com/trigtech/privateme/server/am/ActivityStack:a ()V + // 39: aload_0 + // 40: iload_1 + // 41: aload 4 + // 43: invokevirtual 409 com/trigtech/privateme/server/am/ActivityStack:a (ILandroid/os/IBinder;)Lcom/trigtech/privateme/server/am/c; + // 46: astore 10 + // 48: aload 10 + // 50: ifnull +594 -> 644 + // 53: aload 10 + // 55: getfield 412 com/trigtech/privateme/server/am/c:a Lcom/trigtech/privateme/server/am/p; + // 58: astore 11 + // 60: getstatic 31 com/trigtech/privateme/server/am/ActivityStack:b Ljava/lang/String; + // 63: ldc_w 414 + // 66: iconst_1 + // 67: anewarray 4 java/lang/Object + // 70: dup + // 71: iconst_0 + // 72: aload 11 + // 74: aastore + // 75: invokestatic 376 com/trigtech/privateme/helper/utils/v:a (Ljava/lang/String;Ljava/lang/String;[Ljava/lang/Object;)V + // 78: getstatic 420 com/trigtech/privateme/server/am/ActivityStack$ReuseTarget:CURRENT Lcom/trigtech/privateme/server/am/ActivityStack$ReuseTarget; + // 81: astore 12 + // 83: getstatic 424 com/trigtech/privateme/server/am/ActivityStack$ClearTarget:NOTHING Lcom/trigtech/privateme/server/am/ActivityStack$ClearTarget; + // 86: astore 13 + // 88: aload_2 + // 89: ldc_w 425 + // 92: invokestatic 135 com/trigtech/privateme/server/am/ActivityStack:b (Landroid/content/Intent;I)Z + // 95: istore 14 + // 97: aload_2 + // 98: invokevirtual 114 android/content/Intent:getComponent ()Landroid/content/ComponentName; + // 101: ifnonnull +36 -> 137 + // 104: getstatic 31 com/trigtech/privateme/server/am/ActivityStack:b Ljava/lang/String; + // 107: ldc_w 427 + // 110: iconst_0 + // 111: anewarray 4 java/lang/Object + // 114: invokestatic 376 com/trigtech/privateme/helper/utils/v:a (Ljava/lang/String;Ljava/lang/String;[Ljava/lang/Object;)V + // 117: aload_2 + // 118: new 121 android/content/ComponentName + // 121: dup + // 122: aload_3 + // 123: getfield 88 android/content/pm/ActivityInfo:packageName Ljava/lang/String; + // 126: aload_3 + // 127: getfield 402 android/content/pm/ActivityInfo:name Ljava/lang/String; + // 130: invokespecial 430 android/content/ComponentName: (Ljava/lang/String;Ljava/lang/String;)V + // 133: invokevirtual 434 android/content/Intent:setComponent (Landroid/content/ComponentName;)Landroid/content/Intent; + // 136: pop + // 137: aload 10 + // 139: ifnull +33 -> 172 + // 142: aload 10 + // 144: getfield 436 com/trigtech/privateme/server/am/c:g I + // 147: iconst_3 + // 148: if_icmpne +24 -> 172 + // 151: getstatic 31 com/trigtech/privateme/server/am/ActivityStack:b Ljava/lang/String; + // 154: ldc_w 438 + // 157: iconst_0 + // 158: anewarray 4 java/lang/Object + // 161: invokestatic 376 com/trigtech/privateme/helper/utils/v:a (Ljava/lang/String;Ljava/lang/String;[Ljava/lang/Object;)V + // 164: aload_2 + // 165: ldc_w 439 + // 168: invokevirtual 139 android/content/Intent:addFlags (I)Landroid/content/Intent; + // 171: pop + // 172: iload 14 + // 174: ifeq +28 -> 202 + // 177: getstatic 31 com/trigtech/privateme/server/am/ActivityStack:b Ljava/lang/String; + // 180: ldc_w 441 + // 183: iconst_0 + // 184: anewarray 4 java/lang/Object + // 187: invokestatic 376 com/trigtech/privateme/helper/utils/v:a (Ljava/lang/String;Ljava/lang/String;[Ljava/lang/Object;)V + // 190: aload_2 + // 191: ldc_w 442 + // 194: invokestatic 444 com/trigtech/privateme/server/am/ActivityStack:a (Landroid/content/Intent;I)V + // 197: getstatic 447 com/trigtech/privateme/server/am/ActivityStack$ClearTarget:TOP Lcom/trigtech/privateme/server/am/ActivityStack$ClearTarget; + // 200: astore 13 + // 202: aload_2 + // 203: ldc_w 448 + // 206: invokestatic 135 com/trigtech/privateme/server/am/ActivityStack:b (Landroid/content/Intent;I)Z + // 209: ifeq +31 -> 240 + // 212: aload_2 + // 213: ldc_w 439 + // 216: invokestatic 135 com/trigtech/privateme/server/am/ActivityStack:b (Landroid/content/Intent;I)Z + // 219: ifeq +431 -> 650 + // 222: getstatic 451 com/trigtech/privateme/server/am/ActivityStack$ClearTarget:TASK Lcom/trigtech/privateme/server/am/ActivityStack$ClearTarget; + // 225: astore 13 + // 227: getstatic 31 com/trigtech/privateme/server/am/ActivityStack:b Ljava/lang/String; + // 230: ldc_w 453 + // 233: iconst_0 + // 234: anewarray 4 java/lang/Object + // 237: invokestatic 376 com/trigtech/privateme/helper/utils/v:a (Ljava/lang/String;Ljava/lang/String;[Ljava/lang/Object;)V + // 240: getstatic 458 android/os/Build$VERSION:SDK_INT I + // 243: bipush 21 + // 245: if_icmplt +31 -> 276 + // 248: aload_3 + // 249: getfield 461 android/content/pm/ActivityInfo:documentLaunchMode I + // 252: tableswitch default:+24 -> 276, 1:+421->673, 2:+434->686 + // 277: getfield 464 android/content/pm/ActivityInfo:launchMode I + // 280: tableswitch default:+28 -> 308, 1:+414->694, 2:+466->746, 3:+509->789 + // 309: ldc_w 465 + // 312: invokestatic 135 com/trigtech/privateme/server/am/ActivityStack:b (Landroid/content/Intent;I)Z + // 315: ifeq +1290 -> 1605 + // 318: aload 13 + // 320: astore 19 + // 322: aconst_null + // 323: astore 17 + // 325: aload 12 + // 327: astore 18 + // 329: iconst_1 + // 330: istore 20 + // 332: aload 19 + // 334: getstatic 424 com/trigtech/privateme/server/am/ActivityStack$ClearTarget:NOTHING Lcom/trigtech/privateme/server/am/ActivityStack$ClearTarget; + // 337: if_acmpne +1261 -> 1598 + // 340: aload_2 + // 341: ldc_w 442 + // 344: invokestatic 135 com/trigtech/privateme/server/am/ActivityStack:b (Landroid/content/Intent;I)Z + // 347: ifeq +1251 -> 1598 + // 350: getstatic 468 com/trigtech/privateme/server/am/ActivityStack$ClearTarget:SPEC_ACTIVITY Lcom/trigtech/privateme/server/am/ActivityStack$ClearTarget; + // 353: astore 21 + // 355: aload 11 + // 357: ifnonnull +16 -> 373 + // 360: aload 18 + // 362: getstatic 420 com/trigtech/privateme/server/am/ActivityStack$ReuseTarget:CURRENT Lcom/trigtech/privateme/server/am/ActivityStack$ReuseTarget; + // 365: if_acmpne +8 -> 373 + // 368: getstatic 471 com/trigtech/privateme/server/am/ActivityStack$ReuseTarget:AFFINITY Lcom/trigtech/privateme/server/am/ActivityStack$ReuseTarget; + // 371: astore 18 + // 373: aload_3 + // 374: invokestatic 474 com/trigtech/privateme/helper/utils/k:a (Landroid/content/pm/ActivityInfo;)Ljava/lang/String; + // 377: astore 22 + // 379: getstatic 31 com/trigtech/privateme/server/am/ActivityStack:b Ljava/lang/String; + // 382: ldc_w 476 + // 385: iconst_2 + // 386: anewarray 4 java/lang/Object + // 389: dup + // 390: iconst_0 + // 391: aload 22 + // 393: aastore + // 394: dup + // 395: iconst_1 + // 396: aload 17 + // 398: aastore + // 399: invokestatic 376 com/trigtech/privateme/helper/utils/v:a (Ljava/lang/String;Ljava/lang/String;[Ljava/lang/Object;)V + // 402: getstatic 478 com/trigtech/privateme/server/am/e:b [I + // 405: aload 18 + // 407: invokevirtual 479 com/trigtech/privateme/server/am/ActivityStack$ReuseTarget:ordinal ()I + // 410: iaload + // 411: istore 23 + // 413: aconst_null + // 414: astore 24 + // 416: iload 23 + // 418: tableswitch default:+26 -> 444, 1:+400->818, 2:+412->830, 3:+423->841 + // 445: aconst_null + // 446: + // 447: aload 22 + // 449: invokevirtual 338 java/lang/String:equals (Ljava/lang/Object;)Z + // 452: ifeq +19 -> 471 + // 455: aload_0 + // 456: getfield 40 com/trigtech/privateme/server/am/ActivityStack:e Lcom/trigtech/privateme/helper/utils/a; + // 459: iload_1 + // 460: invokestatic 385 java/lang/Integer:valueOf (I)Ljava/lang/Integer; + // 463: invokevirtual 366 com/trigtech/privateme/helper/utils/a:get (Ljava/lang/Object;)Ljava/lang/Object; + // 466: checkcast 177 com/trigtech/privateme/server/am/p + // 469: astore 24 + // 471: getstatic 31 com/trigtech/privateme/server/am/ActivityStack:b Ljava/lang/String; + // 474: ldc_w 483 + // 477: iconst_1 + // 478: anewarray 4 java/lang/Object + // 481: dup + // 482: iconst_0 + // 483: aload 24 + // 485: aastore + // 486: invokestatic 376 com/trigtech/privateme/helper/utils/v:a (Ljava/lang/String;Ljava/lang/String;[Ljava/lang/Object;)V + // 489: aload 24 + // 491: ifnonnull +383 -> 874 + // 494: invokestatic 489 android/os/SystemClock:elapsedRealtime ()J + // 497: lstore 53 + // 499: aload_0 + // 500: iload_1 + // 501: aconst_null + // 502: aload_2 + // 503: aload_3 + // 504: invokespecial 491 com/trigtech/privateme/server/am/ActivityStack:a (ILcom/trigtech/privateme/server/am/c;Landroid/content/Intent;Landroid/content/pm/ActivityInfo;)Landroid/content/Intent; + // 507: astore 55 + // 509: aload 55 + // 511: ifnull +68 -> 579 + // 514: aload 55 + // 516: ldc_w 439 + // 519: invokevirtual 139 android/content/Intent:addFlags (I)Landroid/content/Intent; + // 522: pop + // 523: aload 55 + // 525: ldc_w 492 + // 528: invokevirtual 139 android/content/Intent:addFlags (I)Landroid/content/Intent; + // 531: pop + // 532: aload 55 + // 534: ldc_w 493 + // 537: invokevirtual 139 android/content/Intent:addFlags (I)Landroid/content/Intent; + // 540: pop + // 541: getstatic 458 android/os/Build$VERSION:SDK_INT I + // 544: bipush 21 + // 546: if_icmpge +302 -> 848 + // 549: aload 55 + // 551: ldc_w 494 + // 554: invokevirtual 139 android/content/Intent:addFlags (I)Landroid/content/Intent; + // 557: pop + // 558: getstatic 458 android/os/Build$VERSION:SDK_INT I + // 561: bipush 16 + // 563: if_icmplt +297 -> 860 + // 566: invokestatic 58 com/trigtech/privateme/client/AppInterface:e ()Lcom/trigtech/privateme/client/AppInterface; + // 569: invokevirtual 62 com/trigtech/privateme/client/AppInterface:i ()Landroid/content/Context; + // 572: aload 55 + // 574: aload 5 + // 576: invokevirtual 498 android/content/Context:startActivity (Landroid/content/Intent;Landroid/os/Bundle;)V + // 579: getstatic 31 com/trigtech/privateme/server/am/ActivityStack:b Ljava/lang/String; + // 582: astore 56 + // 584: iconst_1 + // 585: anewarray 4 java/lang/Object + // 588: astore 57 + // 590: aload 57 + // 592: iconst_0 + // 593: invokestatic 489 android/os/SystemClock:elapsedRealtime ()J + // 596: lload 53 + // 598: lsub + // 599: invokestatic 503 java/lang/Long:valueOf (J)Ljava/lang/Long; + // 602: aastore + // 603: aload 56 + // 605: ldc_w 505 + // 608: aload 57 + // 610: invokestatic 376 com/trigtech/privateme/helper/utils/v:a (Ljava/lang/String;Ljava/lang/String;[Ljava/lang/Object;)V + // 613: getstatic 31 com/trigtech/privateme/server/am/ActivityStack:b Ljava/lang/String; + // 616: astore 31 + // 618: iconst_1 + // 619: anewarray 4 java/lang/Object + // 622: astore 32 + // 624: aload 32 + // 626: iconst_0 + // 627: aload_3 + // 628: getfield 402 android/content/pm/ActivityInfo:name Ljava/lang/String; + // 631: aastore + // 632: aload 31 + // 634: ldc_w 507 + // 637: aload 32 + // 639: invokestatic 376 com/trigtech/privateme/helper/utils/v:a (Ljava/lang/String;Ljava/lang/String;[Ljava/lang/Object;)V + // 642: iconst_0 + // 643: ireturn + // 644: aconst_null + // 645: astore 11 + // 647: goto -587 -> 60 + // 650: aload_2 + // 651: ldc_w 448 + // 654: invokestatic 444 com/trigtech/privateme/server/am/ActivityStack:a (Landroid/content/Intent;I)V + // 657: getstatic 31 com/trigtech/privateme/server/am/ActivityStack:b Ljava/lang/String; + // 660: ldc_w 509 + // 663: iconst_0 + // 664: anewarray 4 java/lang/Object + // 667: invokestatic 376 com/trigtech/privateme/helper/utils/v:a (Ljava/lang/String;Ljava/lang/String;[Ljava/lang/Object;)V + // 670: goto -430 -> 240 + // 673: getstatic 451 com/trigtech/privateme/server/am/ActivityStack$ClearTarget:TASK Lcom/trigtech/privateme/server/am/ActivityStack$ClearTarget; + // 676: astore 13 + // 678: getstatic 512 com/trigtech/privateme/server/am/ActivityStack$ReuseTarget:DOCUMENT Lcom/trigtech/privateme/server/am/ActivityStack$ReuseTarget; + // 681: astore 12 + // 683: goto -407 -> 276 + // 686: getstatic 515 com/trigtech/privateme/server/am/ActivityStack$ReuseTarget:MULTIPLE Lcom/trigtech/privateme/server/am/ActivityStack$ReuseTarget; + // 689: astore 12 + // 691: goto -415 -> 276 + // 694: aload_2 + // 695: ldc_w 439 + // 698: invokestatic 135 com/trigtech/privateme/server/am/ActivityStack:b (Landroid/content/Intent;I)Z + // 701: ifeq +18 -> 719 + // 704: aload_2 + // 705: ldc_w 492 + // 708: invokestatic 135 com/trigtech/privateme/server/am/ActivityStack:b (Landroid/content/Intent;I)Z + // 711: ifeq +27 -> 738 + // 714: getstatic 515 com/trigtech/privateme/server/am/ActivityStack$ReuseTarget:MULTIPLE Lcom/trigtech/privateme/server/am/ActivityStack$ReuseTarget; + // 717: astore 12 + // 719: aload 13 + // 721: astore 19 + // 723: ldc_w 517 + // 726: astore 17 + // 728: aload 12 + // 730: astore 18 + // 732: iconst_1 + // 733: istore 20 + // 735: goto -403 -> 332 + // 738: getstatic 471 com/trigtech/privateme/server/am/ActivityStack$ReuseTarget:AFFINITY Lcom/trigtech/privateme/server/am/ActivityStack$ReuseTarget; + // 741: astore 12 + // 743: goto -24 -> 719 + // 746: getstatic 447 com/trigtech/privateme/server/am/ActivityStack$ClearTarget:TOP Lcom/trigtech/privateme/server/am/ActivityStack$ClearTarget; + // 749: astore 19 + // 751: aload_2 + // 752: ldc_w 492 + // 755: invokestatic 135 com/trigtech/privateme/server/am/ActivityStack:b (Landroid/content/Intent;I)Z + // 758: ifeq +23 -> 781 + // 761: getstatic 515 com/trigtech/privateme/server/am/ActivityStack$ReuseTarget:MULTIPLE Lcom/trigtech/privateme/server/am/ActivityStack$ReuseTarget; + // 764: astore 63 + // 766: aload 63 + // 768: astore 18 + // 770: ldc_w 519 + // 773: astore 17 + // 775: iconst_0 + // 776: istore 20 + // 778: goto -446 -> 332 + // 781: getstatic 471 com/trigtech/privateme/server/am/ActivityStack$ReuseTarget:AFFINITY Lcom/trigtech/privateme/server/am/ActivityStack$ReuseTarget; + // 784: astore 63 + // 786: goto -20 -> 766 + // 789: getstatic 447 com/trigtech/privateme/server/am/ActivityStack$ClearTarget:TOP Lcom/trigtech/privateme/server/am/ActivityStack$ClearTarget; + // 792: astore 15 + // 794: getstatic 471 com/trigtech/privateme/server/am/ActivityStack$ReuseTarget:AFFINITY Lcom/trigtech/privateme/server/am/ActivityStack$ReuseTarget; + // 797: astore 16 + // 799: ldc_w 521 + // 802: astore 17 + // 804: aload 16 + // 806: astore 18 + // 808: aload 15 + // 810: astore 19 + // 812: iconst_0 + // 813: istore 20 + // 815: goto -483 -> 332 + // 818: aload_0 + // 819: iload_1 + // 820: aload 22 + // 822: invokespecial 523 com/trigtech/privateme/server/am/ActivityStack:b (ILjava/lang/String;)Lcom/trigtech/privateme/server/am/p; + // 825: astore 24 + // 827: goto -383 -> 444 + // 830: aload_0 + // 831: iload_1 + // 832: aload_2 + // 833: invokespecial 525 com/trigtech/privateme/server/am/ActivityStack:a (ILandroid/content/Intent;)Lcom/trigtech/privateme/server/am/p; + // 836: astore 24 + // 838: goto -394 -> 444 + // 841: aload 11 + // 843: astore 24 + // 845: goto -401 -> 444 + // 848: aload 55 + // 850: ldc_w 494 + // 853: invokevirtual 139 android/content/Intent:addFlags (I)Landroid/content/Intent; + // 856: pop + // 857: goto -299 -> 558 + // 860: invokestatic 58 com/trigtech/privateme/client/AppInterface:e ()Lcom/trigtech/privateme/client/AppInterface; + // 863: invokevirtual 62 com/trigtech/privateme/client/AppInterface:i ()Landroid/content/Context; + // 866: aload 55 + // 868: invokevirtual 527 android/content/Context:startActivity (Landroid/content/Intent;)V + // 871: goto -292 -> 579 + // 874: aload_0 + // 875: getfield 74 com/trigtech/privateme/server/am/ActivityStack:c Landroid/app/ActivityManager; + // 878: aload 24 + // 880: getfield 297 com/trigtech/privateme/server/am/p:a I + // 883: iconst_0 + // 884: invokevirtual 531 android/app/ActivityManager:moveTaskToFront (II)V + // 887: iload 14 + // 889: ifne +654 -> 1543 + // 892: aload 24 + // 894: getfield 202 com/trigtech/privateme/server/am/p:d Landroid/content/Intent; + // 897: astore 49 + // 899: aload_2 + // 900: ifnull +637 -> 1537 + // 903: aload 49 + // 905: ifnull +632 -> 1537 + // 908: aload_2 + // 909: invokevirtual 534 android/content/Intent:getAction ()Ljava/lang/String; + // 912: aload 49 + // 914: invokevirtual 534 android/content/Intent:getAction ()Ljava/lang/String; + // 917: invokestatic 539 com/trigtech/privateme/helper/a/f:a (Ljava/lang/Object;Ljava/lang/Object;)Z + // 920: ifne +460 -> 1380 + // 923: iconst_0 + // 924: istore 50 + // 926: iload 50 + // 928: ifeq +615 -> 1543 + // 931: iconst_1 + // 932: istore 25 + // 934: aload 24 + // 936: aload 11 + // 938: if_acmpne +653 -> 1591 + // 941: aload 24 + // 943: invokevirtual 541 com/trigtech/privateme/server/am/p:a ()Z + // 946: ifne +645 -> 1591 + // 949: iconst_0 + // 950: istore 26 + // 952: aload 21 + // 954: getfield 544 com/trigtech/privateme/server/am/ActivityStack$ClearTarget:deliverIntent Z + // 957: ifne +11 -> 968 + // 960: iconst_0 + // 961: istore 27 + // 963: iload 20 + // 965: ifeq +620 -> 1585 + // 968: aload 24 + // 970: aload 21 + // 972: aload_2 + // 973: invokevirtual 114 android/content/Intent:getComponent ()Landroid/content/ComponentName; + // 976: invokestatic 546 com/trigtech/privateme/server/am/ActivityStack:a (Lcom/trigtech/privateme/server/am/p;Lcom/trigtech/privateme/server/am/ActivityStack$ClearTarget;Landroid/content/ComponentName;)Z + // 979: istore 27 + // 981: aload 24 + // 983: invokestatic 548 com/trigtech/privateme/server/am/ActivityStack:a (Lcom/trigtech/privateme/server/am/p;)Lcom/trigtech/privateme/server/am/c; + // 986: astore 45 + // 988: iload 14 + // 990: ifeq +24 -> 1014 + // 993: iload 20 + // 995: ifne +19 -> 1014 + // 998: aload 45 + // 1000: ifnull +14 -> 1014 + // 1003: iload 27 + // 1005: ifeq +9 -> 1014 + // 1008: aload 45 + // 1010: iconst_1 + // 1011: putfield 193 com/trigtech/privateme/server/am/c:i Z + // 1014: aload 45 + // 1016: ifnull +569 -> 1585 + // 1019: aload 45 + // 1021: getfield 193 com/trigtech/privateme/server/am/c:i Z + // 1024: ifne +561 -> 1585 + // 1027: aload 45 + // 1029: getfield 144 com/trigtech/privateme/server/am/c:b Landroid/content/ComponentName; + // 1032: aload_2 + // 1033: invokevirtual 114 android/content/Intent:getComponent ()Landroid/content/ComponentName; + // 1036: invokevirtual 206 android/content/ComponentName:equals (Ljava/lang/Object;)Z + // 1039: ifeq +546 -> 1585 + // 1042: aload 45 + // 1044: ifnull +39 -> 1083 + // 1047: aload 10 + // 1049: ifnull +500 -> 1549 + // 1052: aload 10 + // 1054: getfield 144 com/trigtech/privateme/server/am/c:b Landroid/content/ComponentName; + // 1057: invokevirtual 551 android/content/ComponentName:getPackageName ()Ljava/lang/String; + // 1060: astore 46 + // 1062: aload 45 + // 1064: getfield 554 com/trigtech/privateme/server/am/c:f Lcom/trigtech/privateme/server/am/j; + // 1067: getfield 557 com/trigtech/privateme/server/am/j:e Lcom/trigtech/privateme/client/AppClient; + // 1070: aload 46 + // 1072: aload 45 + // 1074: getfield 560 com/trigtech/privateme/server/am/c:d Landroid/os/IBinder; + // 1077: aload_2 + // 1078: invokeinterface 566 4 0 + // 1083: iconst_1 + // 1084: istore 28 + // 1086: iload 27 + // 1088: ifeq +19 -> 1107 + // 1091: aload_0 + // 1092: getfield 45 com/trigtech/privateme/server/am/ActivityStack:a Landroid/util/SparseArray; + // 1095: astore 43 + // 1097: aload 43 + // 1099: monitorenter + // 1100: aload_0 + // 1101: invokespecial 568 com/trigtech/privateme/server/am/ActivityStack:b ()V + // 1104: aload 43 + // 1106: monitorexit + // 1107: iload 26 + // 1109: ifne -496 -> 613 + // 1112: iload 28 + // 1114: ifne -501 -> 613 + // 1117: aload_0 + // 1118: iload_1 + // 1119: aload 10 + // 1121: aload_2 + // 1122: aload_3 + // 1123: invokespecial 491 com/trigtech/privateme/server/am/ActivityStack:a (ILcom/trigtech/privateme/server/am/c;Landroid/content/Intent;Landroid/content/pm/ActivityInfo;)Landroid/content/Intent; + // 1126: astore 29 + // 1128: aload 29 + // 1130: ifnull -517 -> 613 + // 1133: aload 24 + // 1135: invokestatic 548 com/trigtech/privateme/server/am/ActivityStack:a (Lcom/trigtech/privateme/server/am/p;)Lcom/trigtech/privateme/server/am/c; + // 1138: astore 30 + // 1140: aload 30 + // 1142: ifnull +222 -> 1364 + // 1145: aload_0 + // 1146: aload 24 + // 1148: getfield 200 com/trigtech/privateme/server/am/p:b I + // 1151: aload 30 + // 1153: aload 29 + // 1155: aload_3 + // 1156: invokespecial 491 com/trigtech/privateme/server/am/ActivityStack:a (ILcom/trigtech/privateme/server/am/c;Landroid/content/Intent;Landroid/content/pm/ActivityInfo;)Landroid/content/Intent; + // 1159: ifnull +205 -> 1364 + // 1162: aload 30 + // 1164: getfield 560 com/trigtech/privateme/server/am/c:d Landroid/os/IBinder; + // 1167: astore 33 + // 1169: getstatic 573 tbox/android/app/IActivityManager:startActivity Ltbox/RefMethod; + // 1172: invokevirtual 579 tbox/RefMethod:paramList ()[Ljava/lang/Class; + // 1175: astore 34 + // 1177: aload 34 + // 1179: arraylength + // 1180: anewarray 4 java/lang/Object + // 1183: astore 35 + // 1185: aload 34 + // 1187: iconst_0 + // 1188: aaload + // 1189: getstatic 585 tbox/android/app/IApplicationThread:TYPE Ljava/lang/Class; + // 1192: if_acmpne +20 -> 1212 + // 1195: aload 35 + // 1197: iconst_0 + // 1198: getstatic 590 tbox/android/app/ActivityThread:getApplicationThread Ltbox/RefMethod; + // 1201: invokestatic 592 com/trigtech/privateme/client/AppInterface:g ()Ljava/lang/Object; + // 1204: iconst_0 + // 1205: anewarray 4 java/lang/Object + // 1208: invokevirtual 596 tbox/RefMethod:call (Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object; + // 1211: aastore + // 1212: aload 34 + // 1214: ldc 77 + // 1216: invokestatic 601 com/trigtech/privateme/helper/utils/e:a ([Ljava/lang/Class;Ljava/lang/Class;)I + // 1219: istore 36 + // 1221: aload 34 + // 1223: ldc_w 603 + // 1226: iconst_2 + // 1227: invokestatic 606 com/trigtech/privateme/helper/utils/e:a ([Ljava/lang/Class;Ljava/lang/Class;I)I + // 1230: istore 37 + // 1232: aload 34 + // 1234: ldc_w 608 + // 1237: invokestatic 601 com/trigtech/privateme/helper/utils/e:a ([Ljava/lang/Class;Ljava/lang/Class;)I + // 1240: istore 38 + // 1242: iload 36 + // 1244: iconst_1 + // 1245: iadd + // 1246: istore 39 + // 1248: iload 37 + // 1250: iconst_1 + // 1251: iadd + // 1252: istore 40 + // 1254: iload 37 + // 1256: iconst_2 + // 1257: iadd + // 1258: istore 41 + // 1260: aload 35 + // 1262: iload 36 + // 1264: aload 29 + // 1266: aastore + // 1267: aload 35 + // 1269: iload 37 + // 1271: aload 33 + // 1273: aastore + // 1274: aload 35 + // 1276: iload 40 + // 1278: aload 6 + // 1280: aastore + // 1281: aload 35 + // 1283: iload 41 + // 1285: iload 7 + // 1287: invokestatic 385 java/lang/Integer:valueOf (I)Ljava/lang/Integer; + // 1290: aastore + // 1291: iload 38 + // 1293: iconst_m1 + // 1294: if_icmpeq +10 -> 1304 + // 1297: aload 35 + // 1299: iload 38 + // 1301: aload 5 + // 1303: aastore + // 1304: aload 35 + // 1306: iload 39 + // 1308: aload 29 + // 1310: invokevirtual 611 android/content/Intent:getType ()Ljava/lang/String; + // 1313: aastore + // 1314: getstatic 458 android/os/Build$VERSION:SDK_INT I + // 1317: bipush 18 + // 1319: if_icmplt +16 -> 1335 + // 1322: aload 35 + // 1324: iload 36 + // 1326: iconst_1 + // 1327: isub + // 1328: invokestatic 58 com/trigtech/privateme/client/AppInterface:e ()Lcom/trigtech/privateme/client/AppInterface; + // 1331: invokevirtual 98 com/trigtech/privateme/client/AppInterface:k ()Ljava/lang/String; + // 1334: aastore + // 1335: aload 34 + // 1337: aload 35 + // 1339: invokestatic 616 com/trigtech/privateme/helper/utils/i:a ([Ljava/lang/Class;[Ljava/lang/Object;)V + // 1342: getstatic 573 tbox/android/app/IActivityManager:startActivity Ltbox/RefMethod; + // 1345: getstatic 622 tbox/android/app/ActivityManagerNative:getDefault Ltbox/RefStaticMethod; + // 1348: iconst_0 + // 1349: anewarray 4 java/lang/Object + // 1352: invokevirtual 627 tbox/RefStaticMethod:call ([Ljava/lang/Object;)Ljava/lang/Object; + // 1355: aload 35 + // 1357: checkcast 629 [Ljava/lang/Object; + // 1360: invokevirtual 596 tbox/RefMethod:call (Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object; + // 1363: pop + // 1364: getstatic 31 com/trigtech/privateme/server/am/ActivityStack:b Ljava/lang/String; + // 1367: ldc_w 631 + // 1370: iconst_0 + // 1371: anewarray 4 java/lang/Object + // 1374: invokestatic 376 com/trigtech/privateme/helper/utils/v:a (Ljava/lang/String;Ljava/lang/String;[Ljava/lang/Object;)V + // 1377: goto -764 -> 613 + // 1380: aload_2 + // 1381: invokevirtual 635 android/content/Intent:getData ()Landroid/net/Uri; + // 1384: aload 49 + // 1386: invokevirtual 635 android/content/Intent:getData ()Landroid/net/Uri; + // 1389: invokestatic 539 com/trigtech/privateme/helper/a/f:a (Ljava/lang/Object;Ljava/lang/Object;)Z + // 1392: ifne +9 -> 1401 + // 1395: iconst_0 + // 1396: istore 50 + // 1398: goto -472 -> 926 + // 1401: aload_2 + // 1402: invokevirtual 611 android/content/Intent:getType ()Ljava/lang/String; + // 1405: aload 49 + // 1407: invokevirtual 611 android/content/Intent:getType ()Ljava/lang/String; + // 1410: invokestatic 539 com/trigtech/privateme/helper/a/f:a (Ljava/lang/Object;Ljava/lang/Object;)Z + // 1413: ifne +9 -> 1422 + // 1416: iconst_0 + // 1417: istore 50 + // 1419: goto -493 -> 926 + // 1422: aload_2 + // 1423: invokevirtual 638 android/content/Intent:getPackage ()Ljava/lang/String; + // 1426: astore 51 + // 1428: aload 51 + // 1430: ifnonnull +19 -> 1449 + // 1433: aload_2 + // 1434: invokevirtual 114 android/content/Intent:getComponent ()Landroid/content/ComponentName; + // 1437: ifnull +12 -> 1449 + // 1440: aload_2 + // 1441: invokevirtual 114 android/content/Intent:getComponent ()Landroid/content/ComponentName; + // 1444: invokevirtual 551 android/content/ComponentName:getPackageName ()Ljava/lang/String; + // 1447: astore 51 + // 1449: aload 49 + // 1451: invokevirtual 638 android/content/Intent:getPackage ()Ljava/lang/String; + // 1454: astore 52 + // 1456: aload 52 + // 1458: ifnonnull +21 -> 1479 + // 1461: aload 49 + // 1463: invokevirtual 114 android/content/Intent:getComponent ()Landroid/content/ComponentName; + // 1466: ifnull +13 -> 1479 + // 1469: aload 49 + // 1471: invokevirtual 114 android/content/Intent:getComponent ()Landroid/content/ComponentName; + // 1474: invokevirtual 551 android/content/ComponentName:getPackageName ()Ljava/lang/String; + // 1477: astore 52 + // 1479: aload 51 + // 1481: aload 52 + // 1483: invokestatic 539 com/trigtech/privateme/helper/a/f:a (Ljava/lang/Object;Ljava/lang/Object;)Z + // 1486: ifne +9 -> 1495 + // 1489: iconst_0 + // 1490: istore 50 + // 1492: goto -566 -> 926 + // 1495: aload_2 + // 1496: invokevirtual 114 android/content/Intent:getComponent ()Landroid/content/ComponentName; + // 1499: aload 49 + // 1501: invokevirtual 114 android/content/Intent:getComponent ()Landroid/content/ComponentName; + // 1504: invokestatic 539 com/trigtech/privateme/helper/a/f:a (Ljava/lang/Object;Ljava/lang/Object;)Z + // 1507: ifne +9 -> 1516 + // 1510: iconst_0 + // 1511: istore 50 + // 1513: goto -587 -> 926 + // 1516: aload_2 + // 1517: invokevirtual 641 android/content/Intent:getCategories ()Ljava/util/Set; + // 1520: aload 49 + // 1522: invokevirtual 641 android/content/Intent:getCategories ()Ljava/util/Set; + // 1525: invokestatic 539 com/trigtech/privateme/helper/a/f:a (Ljava/lang/Object;Ljava/lang/Object;)Z + // 1528: ifne +9 -> 1537 + // 1531: iconst_0 + // 1532: istore 50 + // 1534: goto -608 -> 926 + // 1537: iconst_1 + // 1538: istore 50 + // 1540: goto -614 -> 926 + // 1543: iconst_0 + // 1544: istore 25 + // 1546: goto -612 -> 934 + // 1549: ldc_w 643 + // 1552: astore 46 + // 1554: goto -492 -> 1062 + // 1557: astore 48 + // 1559: aload 48 + // 1561: invokevirtual 644 android/os/RemoteException:printStackTrace ()V + // 1564: goto -481 -> 1083 + // 1567: astore 47 + // 1569: aload 47 + // 1571: invokevirtual 645 java/lang/NullPointerException:printStackTrace ()V + // 1574: goto -491 -> 1083 + // 1577: astore 44 + // 1579: aload 43 + // 1581: monitorexit + // 1582: aload 44 + // 1584: athrow + // 1585: iconst_0 + // 1586: istore 28 + // 1588: goto -502 -> 1086 + // 1591: iload 25 + // 1593: istore 26 + // 1595: goto -643 -> 952 + // 1598: aload 19 + // 1600: astore 21 + // 1602: goto -1247 -> 355 + // 1605: aload 13 + // 1607: astore 19 + // 1609: aload 12 + // 1611: astore 18 + // 1613: aconst_null + // 1614: astore 17 + // 1616: iconst_0 + // 1617: istore 20 + // 1619: goto -1287 -> 332 + // + // Exception table: + // from to target type + // 1062 1083 1557 android/os/RemoteException + // 1062 1083 1567 java/lang/NullPointerException + // 1100 1107 1577 finally + // 1579 1582 1577 finally + } + + final c a(int paramInt) + { + List localList = e(paramInt); + if (!localList.isEmpty()) + return (c)localList.get(-1 + localList.size()); + return null; + } + + final c a(int paramInt, IBinder paramIBinder) + { + Object localObject1 = null; + if (paramIBinder != null); + for (int i = 0; ; i++) + { + p localp; + if (i < this.a.size()) + { + localp = (p)this.a.valueAt(i); + if (localp.b != paramInt); + } + else + { + while (true) + { + synchronized (localp.e) + { + Iterator localIterator = localp.e.iterator(); + if (localIterator.hasNext()) + { + localObject3 = (c)localIterator.next(); + if (((c)localObject3).d != paramIBinder) + break label116; + break label119; + } + } + return localObject1; + } + } + } + } + + final void a(int paramInt, String paramString) + { + if (paramInt != -1) + f(paramInt).a(paramString); + while (true) + { + return; + Iterator localIterator = this.f.keySet().iterator(); + while (localIterator.hasNext()) + f(((Integer)localIterator.next()).intValue()).a(paramString); + } + } + + final void a(j paramj) + { + while (true) + { + int j; + synchronized (this.a) + { + a(); + i = this.a.size(); + j = i - 1; + if (i <= 0) + break; + p localp = (p)this.a.valueAt(j); + synchronized (localp.e) + { + Iterator localIterator = localp.e.iterator(); + if (localIterator.hasNext()) + { + c localc = (c)localIterator.next(); + if (localc.f.g != paramj.g) + continue; + localIterator.remove(); + if (localp.e.isEmpty()) + this.a.remove(localp.a); + this.g.remove(localc); + } + } + } + int i = j; + } + } + + final void a(j paramj, ComponentName paramComponentName1, ComponentName paramComponentName2, IBinder paramIBinder, Intent paramIntent, String paramString, int paramInt1, int paramInt2, int paramInt3) + { + v.a(b, "onActivityCreated>>>>>>>>>>>>>>>token: %s", new Object[] { paramIBinder }); + while (true) + { + p localp1; + synchronized (this.a) + { + a(); + localp1 = (p)this.a.get(paramInt1); + if (localp1 == null) + { + localp2 = new p(paramInt1, paramj.j, paramString, paramIntent); + this.a.put(paramInt1, localp2); + c localc = new c(localp2, paramComponentName1, paramComponentName2, paramIBinder, paramj.j, paramj, paramInt2, paramInt3, paramString); + synchronized (localp2.e) + { + localp2.e.add(localc); + return; + } + } + } + p localp2 = localp1; + } + } + + final List b(int paramInt) + { + Object localObject = (List)this.h.get(Integer.valueOf(paramInt)); + if (localObject == null) + { + localObject = new ArrayList(); + this.h.put(Integer.valueOf(paramInt), localObject); + } + return localObject; + } + + final void b(int paramInt, IBinder paramIBinder) + { + v.a(b, "onActivityResumed>>>>>>>>>>>>>>>token: %s", new Object[] { paramIBinder }); + synchronized (this.a) + { + a(); + c localc = a(paramInt, paramIBinder); + v.a(b, "onActivityResumed, r: %s", new Object[] { localc }); + if (localc != null) + if (localc.b != null) + { + a.a(); + a.a(localc.b.getPackageName()); + f localf = f(paramInt); + String str = localc.b.getPackageName(); + localf.a(AppInterface.e().b(str)); + } + synchronized (localc.a.e) + { + localc.a.e.remove(localc); + localc.a.e.add(localc); + this.e.put(Integer.valueOf(paramInt), localc.a); + List localList2 = e(paramInt); + if (!localList2.contains(localc)) + { + v.a(b, "onActivityResumed, add r: %s", new Object[] { localc }); + localList2.add(localc); + } + return; + } + } + } + + final List c(int paramInt) + { + return f(paramInt).a(); + } + + final void c(int paramInt, IBinder paramIBinder) + { + v.a(b, "onActivityStarted>>>>>>>>>>>>>>>token: %s", new Object[] { paramIBinder }); + synchronized (this.a) + { + a(); + c localc = a(paramInt, paramIBinder); + v.a(b, "onActivityStarted, r: %s", new Object[] { localc }); + List localList = b(paramInt); + if ((localc != null) && (!localList.contains(localc))) + { + localList.add(localc); + v.a(b, "onActivityStarted, add r: %s", new Object[] { localc }); + } + return; + } + } + + final AppTaskInfo d(int paramInt) + { + synchronized (this.a) + { + p localp = (p)this.a.get(paramInt); + if (localp != null) + { + int i = localp.e.size(); + if (i <= 0); + ComponentName localComponentName; + for (AppTaskInfo localAppTaskInfo = null; ; localAppTaskInfo = new AppTaskInfo(localp.a, localp.d, localp.d.getComponent(), localComponentName)) + { + return localAppTaskInfo; + localComponentName = ((c)localp.e.get(i - 1)).b; + } + } + return null; + } + } + + final void d(int paramInt, IBinder paramIBinder) + { + v.a(b, "onActivityPaused>>>>>>>>>>>>>>>token: %s", new Object[] { paramIBinder }); + synchronized (this.a) + { + a(); + c localc = a(paramInt, paramIBinder); + v.a(b, "onActivityPaused, r: %s", new Object[] { localc }); + List localList = e(paramInt); + if ((localc != null) && (localList.contains(localc))) + { + localList.remove(localc); + v.a(b, "onActivityPaused, remove r: %s", new Object[] { localc }); + } + return; + } + } + + final void e(int paramInt, IBinder paramIBinder) + { + v.a(b, "onActivityStopped>>>>>>>>>>>>>>>token: %s", new Object[] { paramIBinder }); + synchronized (this.a) + { + a(); + c localc = a(paramInt, paramIBinder); + v.a(b, "onActivityStopped, r: %s", new Object[] { localc }); + List localList = b(paramInt); + if ((localc != null) && (localList.contains(localc))) + { + localList.remove(localc); + v.a(b, "onActivityStopped, remove r: %s", new Object[] { localc }); + } + return; + } + } + + final boolean f(int paramInt, IBinder paramIBinder) + { + v.a(b, "onActivityDestroyed>>>>>>>>>>>>>>>token: %s", new Object[] { paramIBinder }); + synchronized (this.a) + { + c localc = a(paramInt, paramIBinder); + v.a(b, "onActivityDestroyed, r: %s", new Object[] { localc }); + if (localc != null); + synchronized (localc.a.e) + { + localc.a.e.remove(localc); + List localList2 = e(paramInt); + if (localList2.contains(localc)) + { + localList2.remove(localc); + v.a(b, "onActivityDestroyed, remove resumed r: %s", new Object[] { localc }); + } + List localList3 = b(paramInt); + if (localList3.contains(localc)) + { + localList3.remove(localc); + v.a(b, "onActivityDestroyed, remove started r: %s", new Object[] { localc }); + } + a(); + return false; + } + } + } + + final String g(int paramInt, IBinder paramIBinder) + { + synchronized (this.a) + { + c localc = a(paramInt, paramIBinder); + if (localc != null) + { + String str = localc.b.getPackageName(); + return str; + } + return null; + } + } + + final ComponentName h(int paramInt, IBinder paramIBinder) + { + synchronized (this.a) + { + c localc = a(paramInt, paramIBinder); + if (localc != null) + { + ComponentName localComponentName = localc.c; + return localComponentName; + } + return null; + } + } + + public final String i(int paramInt, IBinder paramIBinder) + { + synchronized (this.a) + { + c localc = a(paramInt, paramIBinder); + if (localc != null) + { + ComponentName localComponentName = localc.c; + String str = null; + if (localComponentName != null) + str = localc.c.getPackageName(); + return str; + } + return null; + } + } + + final ComponentName j(int paramInt, IBinder paramIBinder) + { + synchronized (this.a) + { + c localc = a(paramInt, paramIBinder); + if (localc != null) + { + ComponentName localComponentName = localc.b; + return localComponentName; + } + return null; + } + } + + +} + +/* Location: + * Qualified Name: com.trigtech.privateme.server.am.ActivityStack + * Java Class Version: 6 (50.0) + * JD-Core Version: 0.6.1-SNAPSHOT + */ \ No newline at end of file diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/issue_samples/issue_2627/DefaultStrategy.java b/javaparser-core-testing/src/test/resources/com/github/javaparser/issue_samples/issue_2627/DefaultStrategy.java new file mode 100644 index 0000000..fa64ba3 --- /dev/null +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/issue_samples/issue_2627/DefaultStrategy.java @@ -0,0 +1,297 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package groovy.transform.builder; + +import groovy.transform.Undefined; +import org.codehaus.groovy.ast.AnnotatedNode; +import org.codehaus.groovy.ast.AnnotationNode; +import org.codehaus.groovy.ast.ClassNode; +import org.codehaus.groovy.ast.ConstructorNode; +import org.codehaus.groovy.ast.FieldNode; +import org.codehaus.groovy.ast.InnerClassNode; +import org.codehaus.groovy.ast.MethodNode; +import org.codehaus.groovy.ast.Parameter; +import org.codehaus.groovy.ast.expr.Expression; +import org.codehaus.groovy.ast.stmt.BlockStatement; +import org.codehaus.groovy.transform.BuilderASTTransformation; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static org.apache.groovy.ast.tools.ClassNodeUtils.addGeneratedInnerClass; +import static org.apache.groovy.ast.tools.ClassNodeUtils.addGeneratedMethod; +import static org.codehaus.groovy.ast.ClassHelper.OBJECT_TYPE; +import static org.codehaus.groovy.ast.tools.GeneralUtils.args; +import static org.codehaus.groovy.ast.tools.GeneralUtils.assignX; +import static org.codehaus.groovy.ast.tools.GeneralUtils.block; +import static org.codehaus.groovy.ast.tools.GeneralUtils.callX; +import static org.codehaus.groovy.ast.tools.GeneralUtils.constX; +import static org.codehaus.groovy.ast.tools.GeneralUtils.ctorX; +import static org.codehaus.groovy.ast.tools.GeneralUtils.declS; +import static org.codehaus.groovy.ast.tools.GeneralUtils.localVarX; +import static org.codehaus.groovy.ast.tools.GeneralUtils.param; +import static org.codehaus.groovy.ast.tools.GeneralUtils.params; +import static org.codehaus.groovy.ast.tools.GeneralUtils.propX; +import static org.codehaus.groovy.ast.tools.GeneralUtils.returnS; +import static org.codehaus.groovy.ast.tools.GeneralUtils.stmt; +import static org.codehaus.groovy.ast.tools.GeneralUtils.varX; +import static org.codehaus.groovy.ast.tools.GenericsUtils.correctToGenericsSpecRecurse; +import static org.codehaus.groovy.ast.tools.GenericsUtils.createGenericsSpec; +import static org.codehaus.groovy.ast.tools.GenericsUtils.extractSuperClassGenerics; +import static org.codehaus.groovy.ast.tools.GenericsUtils.newClass; +import static org.codehaus.groovy.transform.AbstractASTTransformation.getMemberStringValue; +import static org.codehaus.groovy.transform.BuilderASTTransformation.NO_EXCEPTIONS; +import static org.codehaus.groovy.transform.BuilderASTTransformation.NO_PARAMS; +import static org.objectweb.asm.Opcodes.ACC_PRIVATE; +import static org.objectweb.asm.Opcodes.ACC_PUBLIC; +import static org.objectweb.asm.Opcodes.ACC_STATIC; + +/** + * This strategy is used with the {@link Builder} AST transform to create a builder helper class + * for the fluent creation of instances of a specified class. It can be used at the class, + * static method or constructor levels. + * + * You use it as follows: + *

+ * import groovy.transform.builder.*
+ *
+ * {@code @Builder}
+ * class Person {
+ *     String firstName
+ *     String lastName
+ *     int age
+ * }
+ * def person = Person.builder().firstName("Robert").lastName("Lewandowski").age(21).build()
+ * assert person.firstName == "Robert"
+ * assert person.lastName == "Lewandowski"
+ * assert person.age == 21
+ * 
+ * The {@code prefix} annotation attribute can be used to create setters with a different naming convention. The default is the + * empty string but you could change that to "set" as follows: + *
+ * {@code @groovy.transform.builder.Builder}(prefix='set')
+ * class Person {
+ *     String firstName
+ *     String lastName
+ *     int age
+ * }
+ * def p2 = Person.builder().setFirstName("Robert").setLastName("Lewandowski").setAge(21).build()
+ * 
+ * or using a prefix of 'with' would result in usage like this: + *
+ * def p3 = Person.builder().withFirstName("Robert").withLastName("Lewandowski").withAge(21).build()
+ * 
+ * + * You can also use the {@code @Builder} annotation in combination with this strategy on one or more constructor or + * static method instead of or in addition to using it at the class level. An example with a constructor follows: + *
+ * import groovy.transform.ToString
+ * import groovy.transform.builder.Builder
+ *
+ * {@code @ToString}
+ * class Person {
+ *     String first, last
+ *     int born
+ *
+ *     {@code @Builder}
+ *     Person(String roleName) {
+ *         if (roleName == 'Jack Sparrow') {
+ *             first = 'Johnny'; last = 'Depp'; born = 1963
+ *         }
+ *     }
+ * }
+ * assert Person.builder().roleName("Jack Sparrow").build().toString() == 'Person(Johnny, Depp, 1963)'
+ * 
+ * In this case, the parameter(s) for the constructor or static method become the properties available + * in the builder. For the case of a static method, the return type of the static method becomes the + * class of the instance being created. For static factory methods, this is normally the class containing the + * static method but in general it can be any class. + * + * Note: if using more than one {@code @Builder} annotation, which is only possible when using static method + * or constructor variants, it is up to you to ensure that any generated helper classes or builder methods + * have unique names. E.g. we can modify the previous example to have three builders. At least two of the builders + * in our case will need to set the 'builderClassName' and 'builderMethodName' annotation attributes to ensure + * we have unique names. This is shown in the following example: + *
+ * import groovy.transform.builder.*
+ * import groovy.transform.*
+ *
+ * {@code @ToString}
+ * {@code @Builder}
+ * class Person {
+ *     String first, last
+ *     int born
+ *
+ *     Person(){} // required to retain no-arg constructor
+ *
+ *     {@code @Builder}(builderClassName='MovieBuilder', builderMethodName='byRoleBuilder')
+ *     Person(String roleName) {
+ *         if (roleName == 'Jack Sparrow') {
+ *             this.first = 'Johnny'; this.last = 'Depp'; this.born = 1963
+ *         }
+ *     }
+ *
+ *     {@code @Builder}(builderClassName='SplitBuilder', builderMethodName='splitBuilder')
+ *     static Person split(String name, int year) {
+ *         def parts = name.split(' ')
+ *         new Person(first: parts[0], last: parts[1], born: year)
+ *     }
+ * }
+ *
+ * assert Person.splitBuilder().name("Johnny Depp").year(1963).build().toString() == 'Person(Johnny, Depp, 1963)'
+ * assert Person.byRoleBuilder().roleName("Jack Sparrow").build().toString() == 'Person(Johnny, Depp, 1963)'
+ * assert Person.builder().first("Johnny").last('Depp').born(1963).build().toString() == 'Person(Johnny, Depp, 1963)'
+ * 
+ * + * The 'forClass' annotation attribute for the {@code @Builder} transform isn't applicable for this strategy. + * The 'useSetters' annotation attribute for the {@code @Builder} transform is ignored by this strategy which always uses setters. + */ +public class DefaultStrategy extends BuilderASTTransformation.AbstractBuilderStrategy { + private static final Expression DEFAULT_INITIAL_VALUE = null; + private static final int PUBLIC_STATIC = ACC_PUBLIC | ACC_STATIC; + + public void build(BuilderASTTransformation transform, AnnotatedNode annotatedNode, AnnotationNode anno) { + if (unsupportedAttribute(transform, anno, "forClass")) return; + if (unsupportedAttribute(transform, anno, "force")) return; + if (annotatedNode instanceof ClassNode) { + buildClass(transform, (ClassNode) annotatedNode, anno); + } else if (annotatedNode instanceof MethodNode) { + buildMethod(transform, (MethodNode) annotatedNode, anno); + } + } + + public void buildMethod(BuilderASTTransformation transform, MethodNode mNode, AnnotationNode anno) { + if (transform.getMemberValue(anno, "includes") != null || transform.getMemberValue(anno, "excludes") != null) { + transform.addError("Error during " + BuilderASTTransformation.MY_TYPE_NAME + + " processing: includes/excludes only allowed on classes", anno); + } + ClassNode buildee = mNode.getDeclaringClass(); + ClassNode builder = createBuilder(anno, buildee); + createBuilderFactoryMethod(anno, buildee, builder); + for (Parameter parameter : mNode.getParameters()) { + builder.addField(createFieldCopy(buildee, parameter)); + addGeneratedMethod(builder, createBuilderMethodForProp(builder, new PropertyInfo(parameter.getName(), parameter.getType()), getPrefix(anno))); + } + addGeneratedMethod(builder, createBuildMethodForMethod(anno, buildee, mNode, mNode.getParameters())); + } + + public void buildClass(BuilderASTTransformation transform, ClassNode buildee, AnnotationNode anno) { + List excludes = new ArrayList(); + List includes = new ArrayList(); + includes.add(Undefined.STRING); + if (!getIncludeExclude(transform, anno, buildee, excludes, includes)) return; + if (includes.size() == 1 && Undefined.isUndefined(includes.get(0))) includes = null; + ClassNode builder = createBuilder(anno, buildee); + createBuilderFactoryMethod(anno, buildee, builder); +// List fields = getFields(transform, anno, buildee); + boolean allNames = transform.memberHasValue(anno, "allNames", true); + boolean allProperties = !transform.memberHasValue(anno, "allProperties", false); + List props = getPropertyInfos(transform, anno, buildee, excludes, includes, allNames, allProperties); + for (PropertyInfo pi : props) { + ClassNode correctedType = getCorrectedType(buildee, pi.getType(), builder); + String fieldName = pi.getName(); + builder.addField(createFieldCopy(buildee, fieldName, correctedType)); + addGeneratedMethod(builder, createBuilderMethodForProp(builder, new PropertyInfo(fieldName, correctedType), getPrefix(anno))); + } + addGeneratedMethod(builder, createBuildMethod(anno, buildee, props)); + } + + private static ClassNode getCorrectedType(ClassNode buildee, ClassNode fieldType, ClassNode declaringClass) { + Map genericsSpec = createGenericsSpec(declaringClass); + extractSuperClassGenerics(fieldType, buildee, genericsSpec); + return correctToGenericsSpecRecurse(genericsSpec, fieldType); + } + + private static void createBuilderFactoryMethod(AnnotationNode anno, ClassNode buildee, ClassNode builder) { + addGeneratedInnerClass(buildee, builder); + addGeneratedMethod(buildee, createBuilderMethod(anno, builder)); + } + + private static ClassNode createBuilder(AnnotationNode anno, ClassNode buildee) { + return new InnerClassNode(buildee, getFullName(anno, buildee), PUBLIC_STATIC, OBJECT_TYPE); + } + + private static String getFullName(AnnotationNode anno, ClassNode buildee) { + String builderClassName = getMemberStringValue(anno, "builderClassName", buildee.getNameWithoutPackage() + "Builder"); + return buildee.getName() + "$" + builderClassName; + } + + private static String getPrefix(AnnotationNode anno) { + return getMemberStringValue(anno, "prefix", ""); + } + + private static MethodNode createBuildMethodForMethod(AnnotationNode anno, ClassNode buildee, MethodNode mNode, Parameter[] params) { + String buildMethodName = getMemberStringValue(anno, "buildMethodName", "build"); + final BlockStatement body = new BlockStatement(); + ClassNode returnType; + if (mNode instanceof ConstructorNode) { + returnType = newClass(buildee); + body.addStatement(returnS(ctorX(newClass(mNode.getDeclaringClass()), args(params)))); + } else { + body.addStatement(returnS(callX(newClass(mNode.getDeclaringClass()), mNode.getName(), args(params)))); + returnType = newClass(mNode.getReturnType()); + } + return new MethodNode(buildMethodName, ACC_PUBLIC, returnType, NO_PARAMS, NO_EXCEPTIONS, body); + } + + private static MethodNode createBuilderMethod(AnnotationNode anno, ClassNode builder) { + String builderMethodName = getMemberStringValue(anno, "builderMethodName", "builder"); + final BlockStatement body = new BlockStatement(); + body.addStatement(returnS(ctorX(builder))); + return new MethodNode(builderMethodName, PUBLIC_STATIC, builder, NO_PARAMS, NO_EXCEPTIONS, body); + } + + private static MethodNode createBuildMethod(AnnotationNode anno, ClassNode buildee, List props) { + String buildMethodName = getMemberStringValue(anno, "buildMethodName", "build"); + final BlockStatement body = new BlockStatement(); + body.addStatement(returnS(initializeInstance(buildee, props, body))); + return new MethodNode(buildMethodName, ACC_PUBLIC, newClass(buildee), NO_PARAMS, NO_EXCEPTIONS, body); + } + + private MethodNode createBuilderMethodForProp(ClassNode builder, PropertyInfo pinfo, String prefix) { + ClassNode fieldType = pinfo.getType(); + String fieldName = pinfo.getName(); + String setterName = getSetterName(prefix, fieldName); + return new MethodNode(setterName, ACC_PUBLIC, newClass(builder), params(param(fieldType, fieldName)), NO_EXCEPTIONS, block( + stmt(assignX(propX(varX("this"), constX(fieldName)), varX(fieldName, fieldType))), + returnS(varX("this", builder)) + )); + } + + private static FieldNode createFieldCopy(ClassNode buildee, Parameter param) { + Map genericsSpec = createGenericsSpec(buildee); + extractSuperClassGenerics(param.getType(), buildee, genericsSpec); + ClassNode correctedParamType = correctToGenericsSpecRecurse(genericsSpec, param.getType()); + return new FieldNode(param.getName(), ACC_PRIVATE, correctedParamType, buildee, param.getInitialExpression()); + } + + private static FieldNode createFieldCopy(ClassNode buildee, String fieldName, ClassNode fieldType) { + return new FieldNode(fieldName, ACC_PRIVATE, fieldType, buildee, DEFAULT_INITIAL_VALUE); + } + + private static Expression initializeInstance(ClassNode buildee, List props, BlockStatement body) { + Expression instance = localVarX("_the" + buildee.getNameWithoutPackage(), buildee); + body.addStatement(declS(instance, ctorX(buildee))); + for (PropertyInfo pi : props) { + body.addStatement(stmt(assignX(propX(instance, pi.getName()), varX(pi.getName(), pi.getType())))); + } + return instance; + } +} diff --git a/javaparser-core-testing/src/test/resources/com/github/javaparser/issue_samples/issue_2627/Ops.java b/javaparser-core-testing/src/test/resources/com/github/javaparser/issue_samples/issue_2627/Ops.java new file mode 100644 index 0000000..b108cff --- /dev/null +++ b/javaparser-core-testing/src/test/resources/com/github/javaparser/issue_samples/issue_2627/Ops.java @@ -0,0 +1,7632 @@ +// Copyright 2020 The TensorFlow Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ============================================================================== +// +// This class has been generated, DO NOT EDIT! +// +package org.tensorflow.op; + +import java.nio.charset.Charset; +import java.util.List; +import org.tensorflow.DataType; +import org.tensorflow.EagerSession; +import org.tensorflow.ExecutionEnvironment; +import org.tensorflow.Operand; +import org.tensorflow.Tensor; +import org.tensorflow.op.core.Abort; +import org.tensorflow.op.core.All; +import org.tensorflow.op.core.Any; +import org.tensorflow.op.core.AssertThat; +import org.tensorflow.op.core.Assign; +import org.tensorflow.op.core.AssignAdd; +import org.tensorflow.op.core.AssignAddVariableOp; +import org.tensorflow.op.core.AssignSub; +import org.tensorflow.op.core.AssignSubVariableOp; +import org.tensorflow.op.core.AssignVariableOp; +import org.tensorflow.op.core.Barrier; +import org.tensorflow.op.core.BarrierClose; +import org.tensorflow.op.core.BarrierIncompleteSize; +import org.tensorflow.op.core.BarrierInsertMany; +import org.tensorflow.op.core.BarrierReadySize; +import org.tensorflow.op.core.BarrierTakeMany; +import org.tensorflow.op.core.Batch; +import org.tensorflow.op.core.BatchToSpace; +import org.tensorflow.op.core.BatchToSpaceNd; +import org.tensorflow.op.core.Bitcast; +import org.tensorflow.op.core.BroadcastDynamicShape; +import org.tensorflow.op.core.BroadcastTo; +import org.tensorflow.op.core.Bucketize; +import org.tensorflow.op.core.ClipByValue; +import org.tensorflow.op.core.Concat; +import org.tensorflow.op.core.Constant; +import org.tensorflow.op.core.ConsumeMutexLock; +import org.tensorflow.op.core.ControlTrigger; +import org.tensorflow.op.core.CountUpTo; +import org.tensorflow.op.core.DeepCopy; +import org.tensorflow.op.core.DeleteSessionTensor; +import org.tensorflow.op.core.DestroyResourceOp; +import org.tensorflow.op.core.DestroyTemporaryVariable; +import org.tensorflow.op.core.DynamicPartition; +import org.tensorflow.op.core.DynamicStitch; +import org.tensorflow.op.core.EditDistance; +import org.tensorflow.op.core.Empty; +import org.tensorflow.op.core.EmptyTensorList; +import org.tensorflow.op.core.EnsureShape; +import org.tensorflow.op.core.ExpandDims; +import org.tensorflow.op.core.ExtractVolumePatches; +import org.tensorflow.op.core.Fill; +import org.tensorflow.op.core.Fingerprint; +import org.tensorflow.op.core.Gather; +import org.tensorflow.op.core.GatherNd; +import org.tensorflow.op.core.GetSessionHandle; +import org.tensorflow.op.core.GetSessionTensor; +import org.tensorflow.op.core.Gradients; +import org.tensorflow.op.core.GuaranteeConst; +import org.tensorflow.op.core.HashTable; +import org.tensorflow.op.core.Helpers; +import org.tensorflow.op.core.HistogramFixedWidth; +import org.tensorflow.op.core.Identity; +import org.tensorflow.op.core.IdentityN; +import org.tensorflow.op.core.ImmutableConst; +import org.tensorflow.op.core.Init; +import org.tensorflow.op.core.InitializeTable; +import org.tensorflow.op.core.InitializeTableFromTextFile; +import org.tensorflow.op.core.InplaceAdd; +import org.tensorflow.op.core.InplaceSub; +import org.tensorflow.op.core.InplaceUpdate; +import org.tensorflow.op.core.IsVariableInitialized; +import org.tensorflow.op.core.LinSpace; +import org.tensorflow.op.core.LookupTableExport; +import org.tensorflow.op.core.LookupTableFind; +import org.tensorflow.op.core.LookupTableImport; +import org.tensorflow.op.core.LookupTableInsert; +import org.tensorflow.op.core.LookupTableSize; +import org.tensorflow.op.core.LoopCond; +import org.tensorflow.op.core.MapClear; +import org.tensorflow.op.core.MapIncompleteSize; +import org.tensorflow.op.core.MapPeek; +import org.tensorflow.op.core.MapSize; +import org.tensorflow.op.core.MapStage; +import org.tensorflow.op.core.MapUnstage; +import org.tensorflow.op.core.MapUnstageNoKey; +import org.tensorflow.op.core.Max; +import org.tensorflow.op.core.Merge; +import org.tensorflow.op.core.Min; +import org.tensorflow.op.core.MirrorPad; +import org.tensorflow.op.core.MlirPassthroughOp; +import org.tensorflow.op.core.MutableDenseHashTable; +import org.tensorflow.op.core.MutableHashTable; +import org.tensorflow.op.core.MutableHashTableOfTensors; +import org.tensorflow.op.core.Mutex; +import org.tensorflow.op.core.MutexLock; +import org.tensorflow.op.core.NextIteration; +import org.tensorflow.op.core.NoOp; +import org.tensorflow.op.core.OneHot; +import org.tensorflow.op.core.OnesLike; +import org.tensorflow.op.core.OrderedMapClear; +import org.tensorflow.op.core.OrderedMapIncompleteSize; +import org.tensorflow.op.core.OrderedMapPeek; +import org.tensorflow.op.core.OrderedMapSize; +import org.tensorflow.op.core.OrderedMapStage; +import org.tensorflow.op.core.OrderedMapUnstage; +import org.tensorflow.op.core.OrderedMapUnstageNoKey; +import org.tensorflow.op.core.Pad; +import org.tensorflow.op.core.ParallelConcat; +import org.tensorflow.op.core.ParallelDynamicStitch; +import org.tensorflow.op.core.Placeholder; +import org.tensorflow.op.core.PlaceholderWithDefault; +import org.tensorflow.op.core.Print; +import org.tensorflow.op.core.Prod; +import org.tensorflow.op.core.QuantizedReshape; +import org.tensorflow.op.core.Range; +import org.tensorflow.op.core.Rank; +import org.tensorflow.op.core.ReadVariableOp; +import org.tensorflow.op.core.ReduceAll; +import org.tensorflow.op.core.ReduceAny; +import org.tensorflow.op.core.ReduceMax; +import org.tensorflow.op.core.ReduceMin; +import org.tensorflow.op.core.ReduceProd; +import org.tensorflow.op.core.ReduceSum; +import org.tensorflow.op.core.RefNextIteration; +import org.tensorflow.op.core.RefSelect; +import org.tensorflow.op.core.RefSwitch; +import org.tensorflow.op.core.RemoteFusedGraphExecute; +import org.tensorflow.op.core.Reshape; +import org.tensorflow.op.core.ResourceCountUpTo; +import org.tensorflow.op.core.ResourceGather; +import org.tensorflow.op.core.ResourceGatherNd; +import org.tensorflow.op.core.ResourceScatterAdd; +import org.tensorflow.op.core.ResourceScatterDiv; +import org.tensorflow.op.core.ResourceScatterMax; +import org.tensorflow.op.core.ResourceScatterMin; +import org.tensorflow.op.core.ResourceScatterMul; +import org.tensorflow.op.core.ResourceScatterNdAdd; +import org.tensorflow.op.core.ResourceScatterNdSub; +import org.tensorflow.op.core.ResourceScatterNdUpdate; +import org.tensorflow.op.core.ResourceScatterSub; +import org.tensorflow.op.core.ResourceScatterUpdate; +import org.tensorflow.op.core.ResourceStridedSliceAssign; +import org.tensorflow.op.core.Reverse; +import org.tensorflow.op.core.ReverseSequence; +import org.tensorflow.op.core.Roll; +import org.tensorflow.op.core.Rpc; +import org.tensorflow.op.core.ScatterAdd; +import org.tensorflow.op.core.ScatterDiv; +import org.tensorflow.op.core.ScatterMax; +import org.tensorflow.op.core.ScatterMin; +import org.tensorflow.op.core.ScatterMul; +import org.tensorflow.op.core.ScatterNd; +import org.tensorflow.op.core.ScatterNdAdd; +import org.tensorflow.op.core.ScatterNdNonAliasingAdd; +import org.tensorflow.op.core.ScatterNdSub; +import org.tensorflow.op.core.ScatterNdUpdate; +import org.tensorflow.op.core.ScatterSub; +import org.tensorflow.op.core.ScatterUpdate; +import org.tensorflow.op.core.Select; +import org.tensorflow.op.core.SetDiff1d; +import org.tensorflow.op.core.SetSize; +import org.tensorflow.op.core.ShapeN; +import org.tensorflow.op.core.Size; +import org.tensorflow.op.core.Skipgram; +import org.tensorflow.op.core.Slice; +import org.tensorflow.op.core.Snapshot; +import org.tensorflow.op.core.SpaceToBatchNd; +import org.tensorflow.op.core.Split; +import org.tensorflow.op.core.SplitV; +import org.tensorflow.op.core.Squeeze; +import org.tensorflow.op.core.Stack; +import org.tensorflow.op.core.Stage; +import org.tensorflow.op.core.StageClear; +import org.tensorflow.op.core.StagePeek; +import org.tensorflow.op.core.StageSize; +import org.tensorflow.op.core.StopGradient; +import org.tensorflow.op.core.StridedSlice; +import org.tensorflow.op.core.StridedSliceAssign; +import org.tensorflow.op.core.StridedSliceGrad; +import org.tensorflow.op.core.Sum; +import org.tensorflow.op.core.SwitchCond; +import org.tensorflow.op.core.TemporaryVariable; +import org.tensorflow.op.core.TensorArray; +import org.tensorflow.op.core.TensorArrayClose; +import org.tensorflow.op.core.TensorArrayConcat; +import org.tensorflow.op.core.TensorArrayGather; +import org.tensorflow.op.core.TensorArrayGrad; +import org.tensorflow.op.core.TensorArrayGradWithShape; +import org.tensorflow.op.core.TensorArrayPack; +import org.tensorflow.op.core.TensorArrayRead; +import org.tensorflow.op.core.TensorArrayScatter; +import org.tensorflow.op.core.TensorArraySize; +import org.tensorflow.op.core.TensorArraySplit; +import org.tensorflow.op.core.TensorArrayUnpack; +import org.tensorflow.op.core.TensorArrayWrite; +import org.tensorflow.op.core.TensorListConcat; +import org.tensorflow.op.core.TensorListConcatLists; +import org.tensorflow.op.core.TensorListElementShape; +import org.tensorflow.op.core.TensorListFromTensor; +import org.tensorflow.op.core.TensorListGather; +import org.tensorflow.op.core.TensorListGetItem; +import org.tensorflow.op.core.TensorListLength; +import org.tensorflow.op.core.TensorListPopBack; +import org.tensorflow.op.core.TensorListPushBack; +import org.tensorflow.op.core.TensorListPushBackBatch; +import org.tensorflow.op.core.TensorListReserve; +import org.tensorflow.op.core.TensorListResize; +import org.tensorflow.op.core.TensorListScatter; +import org.tensorflow.op.core.TensorListScatterIntoExistingList; +import org.tensorflow.op.core.TensorListSetItem; +import org.tensorflow.op.core.TensorListSplit; +import org.tensorflow.op.core.TensorListStack; +import org.tensorflow.op.core.TensorScatterNdAdd; +import org.tensorflow.op.core.TensorScatterNdSub; +import org.tensorflow.op.core.TensorScatterNdUpdate; +import org.tensorflow.op.core.TensorStridedSliceUpdate; +import org.tensorflow.op.core.Tile; +import org.tensorflow.op.core.Timestamp; +import org.tensorflow.op.core.TryRpc; +import org.tensorflow.op.core.Unbatch; +import org.tensorflow.op.core.UnbatchGrad; +import org.tensorflow.op.core.Unique; +import org.tensorflow.op.core.UniqueWithCounts; +import org.tensorflow.op.core.UnravelIndex; +import org.tensorflow.op.core.Unstack; +import org.tensorflow.op.core.Unstage; +import org.tensorflow.op.core.VarHandleOp; +import org.tensorflow.op.core.VarIsInitializedOp; +import org.tensorflow.op.core.Variable; +import org.tensorflow.op.core.VariableShape; +import org.tensorflow.op.core.Where; +import org.tensorflow.op.core.Zeros; +import org.tensorflow.op.core.ZerosLike; +import org.tensorflow.tools.Shape; +import org.tensorflow.tools.buffer.BooleanDataBuffer; +import org.tensorflow.tools.buffer.ByteDataBuffer; +import org.tensorflow.tools.buffer.DataBuffer; +import org.tensorflow.tools.buffer.DoubleDataBuffer; +import org.tensorflow.tools.buffer.FloatDataBuffer; +import org.tensorflow.tools.buffer.IntDataBuffer; +import org.tensorflow.tools.buffer.LongDataBuffer; +import org.tensorflow.tools.ndarray.BooleanNdArray; +import org.tensorflow.tools.ndarray.ByteNdArray; +import org.tensorflow.tools.ndarray.DoubleNdArray; +import org.tensorflow.tools.ndarray.FloatNdArray; +import org.tensorflow.tools.ndarray.IntNdArray; +import org.tensorflow.tools.ndarray.LongNdArray; +import org.tensorflow.tools.ndarray.NdArray; +import org.tensorflow.types.TBool; +import org.tensorflow.types.TFloat32; +import org.tensorflow.types.TFloat64; +import org.tensorflow.types.TInt32; +import org.tensorflow.types.TInt64; +import org.tensorflow.types.TString; +import org.tensorflow.types.TUint8; +import org.tensorflow.types.family.TNumber; +import org.tensorflow.types.family.TType; + +/** + * An API for building operations as {@link Op Op}s + *

+ * Any operation wrapper found in the classpath properly annotated as an{@link org.tensorflow.op.annotation.Operator @Operator} is exposed + * by this API or one of its subgroup. + *

Example usage: + *

{@code
+ * try (Graph g = new Graph()) {
+ *   Ops tf = Ops.create(g);
+ *   // Operations are typed classes with convenience
+ *   // builders in Ops.
+ *   Constant three = tf.constant(3);
+ *   // Single-result operations implement the Operand
+ *   // interface, so this works too.
+ *   Operand four = tf.constant(4);
+ *   // Most builders are found within a group, and accept
+ *   // Operand types as operands
+ *   Operand nine = tf.math.add(four, tf.constant(5));
+ *   // Multi-result operations however offer methods to
+ *   // select a particular result for use.
+ *   Operand result = 
+ *       tf.math.add(tf.unique(s, a).y(), b);
+ *   // Optional attributes
+ *   tf.linalg.matMul(a, b, MatMul.transposeA(true));
+ *   // Naming operators
+ *   tf.withName("foo").constant(5); // name "foo"
+ *   // Names can exist in a hierarchy
+ *   Ops sub = tf.withSubScope("sub");
+ *   sub.withName("bar").constant(4); // "sub/bar"
+ * }
+ * }
+ */ +public final class Ops { + public final NnOps nn; + + public final SummaryOps summary; + + public final ImageOps image; + + public final DataOps data; + + public final IoOps io; + + public final DtypesOps dtypes; + + public final LinalgOps linalg; + + public final RandomOps random; + + public final StringsOps strings; + + public final SparseOps sparse; + + public final BitwiseOps bitwise; + + public final MathOps math; + + public final AudioOps audio; + + public final SignalOps signal; + + public final TrainOps train; + + public final QuantizationOps quantization; + + private final Scope scope; + + private Ops(Scope scope) { + this.scope = scope; + nn = new NnOps(scope); + summary = new SummaryOps(scope); + image = new ImageOps(scope); + data = new DataOps(scope); + io = new IoOps(scope); + dtypes = new DtypesOps(scope); + linalg = new LinalgOps(scope); + random = new RandomOps(scope); + strings = new StringsOps(scope); + sparse = new SparseOps(scope); + bitwise = new BitwiseOps(scope); + math = new MathOps(scope); + audio = new AudioOps(scope); + signal = new SignalOps(scope); + train = new TrainOps(scope); + quantization = new QuantizationOps(scope); + } + + /** + * Raise a exception to abort the process when called. + *

+ * If exit_without_error is true, the process will exit normally, + * otherwise it will exit with a SIGABORT signal. + *

+ * Returns nothing but an exception. + * + * @param options carries optional attributes values + * @return a new instance of Abort + */ + public Abort abort(Abort.Options... options) { + return Abort.create(scope, options); + } + + /** + * Computes the "logical and" of elements across dimensions of a tensor. + *

+ * Reduces `input` along the dimensions given in `axis`. Unless + * `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in + * `axis`. If `keep_dims` is true, the reduced dimensions are + * retained with length 1. + * + * @param input The tensor to reduce. + * @param axis The dimensions to reduce. Must be in the range + * `[-rank(input), rank(input))`. + * @param options carries optional attributes values + * @return a new instance of All + */ + public All all(Operand input, Operand axis, + All.Options... options) { + return All.create(scope, input, axis, options); + } + + /** + * Computes the "logical or" of elements across dimensions of a tensor. + *

+ * Reduces `input` along the dimensions given in `axis`. Unless + * `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in + * `axis`. If `keep_dims` is true, the reduced dimensions are + * retained with length 1. + * + * @param input The tensor to reduce. + * @param axis The dimensions to reduce. Must be in the range + * `[-rank(input), rank(input))`. + * @param options carries optional attributes values + * @return a new instance of Any + */ + public Any any(Operand input, Operand axis, + Any.Options... options) { + return Any.create(scope, input, axis, options); + } + + /** + * Creates a constant of {@code int} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. + * @return a float constant + */ + public Constant array(int... data) { + return Constant.arrayOf(scope, data); + } + + /** + * Creates a constant of {@code String} elements, using the default UTF-8 charset. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. + * @return the {@code String} constant + */ + public Constant array(String... data) { + return Constant.arrayOf(scope, data); + } + + /** + * Creates a constant of {@code boolean} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. + * @return a boolean constant + */ + public Constant array(boolean... data) { + return Constant.arrayOf(scope, data); + } + + /** + * Creates a constant of {@code long} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. + * @return a long constant + */ + public Constant array(long... data) { + return Constant.arrayOf(scope, data); + } + + /** + * Creates a constant of {@code float} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. + * @return a float constant + */ + public Constant array(float... data) { + return Constant.arrayOf(scope, data); + } + + /** + * Creates a constant of {@code double} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. + * @return a double constant + */ + public Constant array(double... data) { + return Constant.arrayOf(scope, data); + } + + /** + * Creates a constant of {@code byte} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. + * @return a byte constant + */ + public Constant array(byte... data) { + return Constant.arrayOf(scope, data); + } + + /** + * Creates a constant of {@code String} elements, using the given charset. + * + * @param scope is a scope used to add the underlying operation. + * @param charset charset for encoding/decoding strings bytes. + * @param data An array containing the values to put into the new constant. String elements are + * sequences of bytes from the last array dimension. + * @return the {@code String} constant + */ + public Constant array(Charset charset, String... data) { + return Constant.arrayOf(scope, charset, data); + } + + /** + * Asserts that the given condition is true. + *

+ * If `condition` evaluates to false, print the list of tensors in `data`. + * `summarize` determines how many entries of the tensors to print. + * + * @param condition The condition to evaluate. + * @param data The tensors to print out when condition is false. + * @param options carries optional attributes values + * @return a new instance of AssertThat + */ + public AssertThat assertThat(Operand condition, Iterable> data, + AssertThat.Options... options) { + return AssertThat.create(scope, condition, data, options); + } + + /** + * Update 'ref' by assigning 'value' to it. + *

+ * This operation outputs "ref" after the assignment is done. + * This makes it easier to chain operations that need to use the reset value. + * + * @param data type for {@code outputRef()} output + * @param ref Should be from a `Variable` node. May be uninitialized. + * @param value The value to be assigned to the variable. + * @param options carries optional attributes values + * @return a new instance of Assign + */ + public Assign assign(Operand ref, Operand value, + Assign.Options... options) { + return Assign.create(scope, ref, value, options); + } + + /** + * Update 'ref' by adding 'value' to it. + *

+ * This operation outputs "ref" after the update is done. + * This makes it easier to chain operations that need to use the reset value. + * + * @param data type for {@code outputRef()} output + * @param ref Should be from a `Variable` node. + * @param value The value to be added to the variable. + * @param options carries optional attributes values + * @return a new instance of AssignAdd + */ + public AssignAdd assignAdd(Operand ref, Operand value, + AssignAdd.Options... options) { + return AssignAdd.create(scope, ref, value, options); + } + + /** + * Adds a value to the current value of a variable. + *

+ * Any ReadVariableOp with a control dependency on this op is guaranteed to + * see the incremented value or a subsequent newer one. + * + * @param resource handle to the resource in which to store the variable. + * @param value the value by which the variable will be incremented. + * @return a new instance of AssignAddVariableOp + */ + public AssignAddVariableOp assignAddVariableOp(Operand resource, + Operand value) { + return AssignAddVariableOp.create(scope, resource, value); + } + + /** + * Update 'ref' by subtracting 'value' from it. + *

+ * This operation outputs "ref" after the update is done. + * This makes it easier to chain operations that need to use the reset value. + * + * @param data type for {@code outputRef()} output + * @param ref Should be from a `Variable` node. + * @param value The value to be subtracted to the variable. + * @param options carries optional attributes values + * @return a new instance of AssignSub + */ + public AssignSub assignSub(Operand ref, Operand value, + AssignSub.Options... options) { + return AssignSub.create(scope, ref, value, options); + } + + /** + * Subtracts a value from the current value of a variable. + *

+ * Any ReadVariableOp with a control dependency on this op is guaranteed to + * see the decremented value or a subsequent newer one. + * + * @param resource handle to the resource in which to store the variable. + * @param value the value by which the variable will be incremented. + * @return a new instance of AssignSubVariableOp + */ + public AssignSubVariableOp assignSubVariableOp(Operand resource, + Operand value) { + return AssignSubVariableOp.create(scope, resource, value); + } + + /** + * Assigns a new value to a variable. + *

+ * Any ReadVariableOp with a control dependency on this op is guaranteed to return + * this value or a subsequent newer value of the variable. + * + * @param resource handle to the resource in which to store the variable. + * @param value the value to set the new tensor to use. + * @return a new instance of AssignVariableOp + */ + public AssignVariableOp assignVariableOp(Operand resource, + Operand value) { + return AssignVariableOp.create(scope, resource, value); + } + + /** + * Defines a barrier that persists across different graph executions. + *

+ * A barrier represents a key-value map, where each key is a string, and + * each value is a tuple of tensors. + *

+ * At runtime, the barrier contains 'complete' and 'incomplete' + * elements. A complete element has defined tensors for all components of + * its value tuple, and may be accessed using BarrierTakeMany. An + * incomplete element has some undefined components in its value tuple, + * and may be updated using BarrierInsertMany. + * + * @param componentTypes The type of each component in a value. + * @param options carries optional attributes values + * @return a new instance of Barrier + */ + public Barrier barrier(List> componentTypes, Barrier.Options... options) { + return Barrier.create(scope, componentTypes, options); + } + + /** + * Closes the given barrier. + *

+ * This operation signals that no more new elements will be inserted in the + * given barrier. Subsequent InsertMany that try to introduce a new key will fail. + * Subsequent InsertMany operations that just add missing components to already + * existing elements will continue to succeed. Subsequent TakeMany operations will + * continue to succeed if sufficient completed elements remain in the barrier. + * Subsequent TakeMany operations that would block will fail immediately. + * + * @param handle The handle to a barrier. + * @param options carries optional attributes values + * @return a new instance of BarrierClose + */ + public BarrierClose barrierClose(Operand handle, BarrierClose.Options... options) { + return BarrierClose.create(scope, handle, options); + } + + /** + * Computes the number of incomplete elements in the given barrier. + * + * @param handle The handle to a barrier. + * @return a new instance of BarrierIncompleteSize + */ + public BarrierIncompleteSize barrierIncompleteSize(Operand handle) { + return BarrierIncompleteSize.create(scope, handle); + } + + /** + * For each key, assigns the respective value to the specified component. + *

+ * If a key is not found in the barrier, this operation will create a new + * incomplete element. If a key is found in the barrier, and the element + * already has a value at component_index, this operation will fail with + * INVALID_ARGUMENT, and leave the barrier in an undefined state. + * + * @param handle The handle to a barrier. + * @param keys A one-dimensional tensor of keys, with length n. + * @param values An any-dimensional tensor of values, which are associated with the + * respective keys. The 0th dimension must have length n. + * @param componentIndex The component of the barrier elements that is being assigned. + * @return a new instance of BarrierInsertMany + */ + public BarrierInsertMany barrierInsertMany(Operand handle, + Operand keys, Operand values, Long componentIndex) { + return BarrierInsertMany.create(scope, handle, keys, values, componentIndex); + } + + /** + * Computes the number of complete elements in the given barrier. + * + * @param handle The handle to a barrier. + * @return a new instance of BarrierReadySize + */ + public BarrierReadySize barrierReadySize(Operand handle) { + return BarrierReadySize.create(scope, handle); + } + + /** + * Takes the given number of completed elements from a barrier. + *

+ * This operation concatenates completed-element component tensors along + * the 0th dimension to make a single component tensor. + *

+ * Elements come out of the barrier when they are complete, and in the order + * in which they were placed into the barrier. The indices output provides + * information about the batch in which each element was originally inserted + * into the barrier. + * + * @param handle The handle to a barrier. + * @param numElements A single-element tensor containing the number of elements to + * take. + * @param componentTypes The type of each component in a value. + * @param options carries optional attributes values + * @return a new instance of BarrierTakeMany + */ + public BarrierTakeMany barrierTakeMany(Operand handle, Operand numElements, + List> componentTypes, BarrierTakeMany.Options... options) { + return BarrierTakeMany.create(scope, handle, numElements, componentTypes, options); + } + + /** + * Batches all input tensors nondeterministically. + *

+ * When many instances of this Op are being run concurrently with the same + * container/shared_name in the same device, some will output zero-shaped Tensors + * and others will output Tensors of size up to max_batch_size. + *

+ * All Tensors in in_tensors are batched together (so, for example, labels and + * features should be batched with a single instance of this operation. + *

+ * Each invocation of batch emits an `id` scalar which will be used to identify + * this particular invocation when doing unbatch or its gradient. + *

+ * Each op which emits a non-empty batch will also emit a non-empty batch_index + * Tensor, which, is a [K, 3] matrix where each row contains the invocation's id, + * start, and length of elements of each set of Tensors present in batched_tensors. + *

+ * Batched tensors are concatenated along the first dimension, and all tensors in + * in_tensors must have the first dimension of the same size. + *

+ * in_tensors: The tensors to be batched. + * num_batch_threads: Number of scheduling threads for processing batches of work. + * Determines the number of batches processed in parallel. + * max_batch_size: Batch sizes will never be bigger than this. + * batch_timeout_micros: Maximum number of microseconds to wait before outputting + * an incomplete batch. + * allowed_batch_sizes: Optional list of allowed batch sizes. If left empty, does + * nothing. Otherwise, supplies a list of batch sizes, causing the op to pad + * batches up to one of those sizes. The entries must increase monotonically, and + * the final entry must equal max_batch_size. + * grad_timeout_micros: The timeout to use for the gradient. See Unbatch. + * batched_tensors: Either empty tensors or a batch of concatenated Tensors. + * batch_index: If out_tensors is non-empty, has information to invert it. + * container: Controls the scope of sharing of this batch. + * id: always contains a scalar with a unique ID for this invocation of Batch. + * shared_name: Concurrently running instances of batch in the same device with the + * same container and shared_name will batch their elements together. If left + * empty, the op name will be used as the shared name. + * T: the types of tensors to be batched. + * + * @param inTensors + * @param numBatchThreads + * @param maxBatchSize + * @param batchTimeoutMicros + * @param gradTimeoutMicros + * @param options carries optional attributes values + * @return a new instance of Batch + */ + public Batch batch(Iterable> inTensors, Long numBatchThreads, Long maxBatchSize, + Long batchTimeoutMicros, Long gradTimeoutMicros, Batch.Options... options) { + return Batch.create(scope, inTensors, numBatchThreads, maxBatchSize, batchTimeoutMicros, gradTimeoutMicros, options); + } + + /** + * BatchToSpace for 4-D tensors of type T. + *

+ * This is a legacy version of the more general BatchToSpaceND. + *

+ * Rearranges (permutes) data from batch into blocks of spatial data, followed by + * cropping. This is the reverse transformation of SpaceToBatch. More specifically, + * this op outputs a copy of the input tensor where values from the `batch` + * dimension are moved in spatial blocks to the `height` and `width` dimensions, + * followed by cropping along the `height` and `width` dimensions. + * + * @param data type for {@code output()} output + * @param input 4-D tensor with shape + * `[batchblock_sizeblock_size, height_pad/block_size, width_pad/block_size, + * depth]`. Note that the batch size of the input tensor must be divisible by + * `block_size * block_size`. + * @param crops 2-D tensor of non-negative integers with shape `[2, 2]`. It specifies + * how many elements to crop from the intermediate result across the spatial + * dimensions as follows: + *

+ * crops = [[crop_top, crop_bottom], [crop_left, crop_right]] + * @param blockSize + * @return a new instance of BatchToSpace + */ + public BatchToSpace batchToSpace(Operand input, + Operand crops, Long blockSize) { + return BatchToSpace.create(scope, input, crops, blockSize); + } + + /** + * BatchToSpace for N-D tensors of type T. + *

+ * This operation reshapes the "batch" dimension 0 into `M + 1` dimensions of shape + * `block_shape + [batch]`, interleaves these blocks back into the grid defined by + * the spatial dimensions `[1, ..., M]`, to obtain a result with the same rank as + * the input. The spatial dimensions of this intermediate result are then + * optionally cropped according to `crops` to produce the output. This is the + * reverse of SpaceToBatch. See below for a precise description. + * + * @param data type for {@code output()} output + * @param input N-D with shape `input_shape = [batch] + spatial_shape + remaining_shape`, + * where spatial_shape has M dimensions. + * @param blockShape 1-D with shape `[M]`, all values must be >= 1. + * @param crops 2-D with shape `[M, 2]`, all values must be >= 0. + * `crops[i] = [crop_start, crop_end]` specifies the amount to crop from input + * dimension `i + 1`, which corresponds to spatial dimension `i`. It is + * required that + * `crop_start[i] + crop_end[i] <= block_shape[i] * input_shape[i + 1]`. + *

+ * This operation is equivalent to the following steps: + *

+ * 1. Reshape `input` to `reshaped` of shape: + * [block_shape[0], ..., block_shape[M-1], + * batch / prod(block_shape), + * input_shape[1], ..., input_shape[N-1]] + *

+ * 2. Permute dimensions of `reshaped` to produce `permuted` of shape + * [batch / prod(block_shape), + *

+ * input_shape[1], block_shape[0], + * ..., + * input_shape[M], block_shape[M-1], + *

+ * input_shape[M+1], ..., input_shape[N-1]] + *

+ * 3. Reshape `permuted` to produce `reshaped_permuted` of shape + * [batch / prod(block_shape), + *

+ * input_shape[1] * block_shape[0], + * ..., + * input_shape[M] * block_shape[M-1], + *

+ * input_shape[M+1], + * ..., + * input_shape[N-1]] + *

+ * 4. Crop the start and end of dimensions `[1, ..., M]` of + * `reshaped_permuted` according to `crops` to produce the output of shape: + * [batch / prod(block_shape), + *

+ * input_shape[1] * block_shape[0] - crops[0,0] - crops[0,1], + * ..., + * input_shape[M] * block_shape[M-1] - crops[M-1,0] - crops[M-1,1], + *

+ * input_shape[M+1], ..., input_shape[N-1]] + *

+ * Some examples: + *

+ * (1) For the following input of shape `[4, 1, 1, 1]`, `block_shape = [2, 2]`, and + * `crops = [[0, 0], [0, 0]]`: + *

{@code
+   *  [[[[1]]], [[[2]]], [[[3]]], [[[4]]]]
+   *  }
+ * The output tensor has shape `[1, 2, 2, 1]` and value: + *
{@code
+   *  x = [[[[1], [2]], [[3], [4]]]]
+   *  }
+ * (2) For the following input of shape `[4, 1, 1, 3]`, `block_shape = [2, 2]`, and + * `crops = [[0, 0], [0, 0]]`: + *
{@code
+   *  [[[[1, 2, 3]]], [[[4, 5, 6]]], [[[7, 8, 9]]], [[[10, 11, 12]]]]
+   *  }
+ * The output tensor has shape `[1, 2, 2, 3]` and value: + *
{@code
+   *  x = [[[[1, 2, 3], [4, 5, 6]],
+   *        [[7, 8, 9], [10, 11, 12]]]]
+   *  }
+ * (3) For the following input of shape `[4, 2, 2, 1]`, `block_shape = [2, 2]`, and + * `crops = [[0, 0], [0, 0]]`: + *
{@code
+   *  x = [[[[1], [3]], [[9], [11]]],
+   *       [[[2], [4]], [[10], [12]]],
+   *       [[[5], [7]], [[13], [15]]],
+   *       [[[6], [8]], [[14], [16]]]]
+   *  }
+ * The output tensor has shape `[1, 4, 4, 1]` and value: + *
{@code
+   *  x = [[[[1],   [2],  [3],  [4]],
+   *       [[5],   [6],  [7],  [8]],
+   *       [[9],  [10], [11],  [12]],
+   *       [[13], [14], [15],  [16]]]]
+   *  }
+ * (4) For the following input of shape `[8, 1, 3, 1]`, `block_shape = [2, 2]`, and + * `crops = [[0, 0], [2, 0]]`: + *
{@code
+   *  x = [[[[0], [1], [3]]], [[[0], [9], [11]]],
+   *       [[[0], [2], [4]]], [[[0], [10], [12]]],
+   *       [[[0], [5], [7]]], [[[0], [13], [15]]],
+   *       [[[0], [6], [8]]], [[[0], [14], [16]]]]
+   *  }
+ * The output tensor has shape `[2, 2, 4, 1]` and value: + *
{@code
+   *  x = [[[[1],   [2],  [3],  [4]],
+   *        [[5],   [6],  [7],  [8]]],
+   *       [[[9],  [10], [11],  [12]],
+   *        [[13], [14], [15],  [16]]]]
+   *  }
+ * @return a new instance of BatchToSpaceNd + */ + public BatchToSpaceNd batchToSpaceNd( + Operand input, Operand blockShape, Operand crops) { + return BatchToSpaceNd.create(scope, input, blockShape, crops); + } + + /** + * Bitcasts a tensor from one type to another without copying data. + *

+ * Given a tensor `input`, this operation returns a tensor that has the same buffer + * data as `input` with datatype `type`. + *

+ * If the input datatype `T` is larger than the output datatype `type` then the + * shape changes from [...] to [..., sizeof(`T`)/sizeof(`type`)]. + *

+ * If `T` is smaller than `type`, the operator requires that the rightmost + * dimension be equal to sizeof(`type`)/sizeof(`T`). The shape then goes from + * [..., sizeof(`type`)/sizeof(`T`)] to [...]. + *

+ * tf.bitcast() and tf.cast() work differently when real dtype is casted as a complex dtype + * (e.g. tf.complex64 or tf.complex128) as tf.cast() make imaginary part 0 while tf.bitcast() + * gives module error. + * For example, + *

+ * Example 1: + *

+ * >>> a = [1., 2., 3.] + * >>> equality_bitcast = tf.bitcast(a, tf.complex128) + * Traceback (most recent call last): + * ... + * InvalidArgumentError: Cannot bitcast from 1 to 18 [Op:Bitcast] + * >>> equality_cast = tf.cast(a, tf.complex128) + * >>> print(equality_cast) + * tf.Tensor([1.+0.j 2.+0.j 3.+0.j], shape=(3,), dtype=complex128) + *

+ * Example 2: + *

+ * >>> tf.bitcast(tf.constant(0xffffffff, dtype=tf.uint32), tf.uint8) + * + *

+ * Example 3: + *

+ * >>> x = [1., 2., 3.] + * >>> y = [0., 2., 3.] + * >>> equality= tf.equal(x,y) + * >>> equality_cast = tf.cast(equality,tf.float32) + * >>> equality_bitcast = tf.bitcast(equality_cast,tf.uint8) + * >>> print(equality) + * tf.Tensor([False True True], shape=(3,), dtype=bool) + * >>> print(equality_cast) + * tf.Tensor([0. 1. 1.], shape=(3,), dtype=float32) + * >>> print(equality_bitcast) + * tf.Tensor( + * [[ 0 0 0 0] + * [ 0 0 128 63] + * [ 0 0 128 63]], shape=(3, 4), dtype=uint8) + *

+ * NOTE: Bitcast is implemented as a low-level cast, so machines with different + * endian orderings will give different results. + * + * @param data type for {@code output()} output + * @param input + * @param type + * @return a new instance of Bitcast + */ + public Bitcast bitcast(Operand input, DataType type) { + return Bitcast.create(scope, input, type); + } + + /** + * Return the shape of s0 op s1 with broadcast. + *

+ * Given `s0` and `s1`, tensors that represent shapes, compute `r0`, the + * broadcasted shape. `s0`, `s1` and `r0` are all integer vectors. + * + * @param data type for {@code r0()} output + * @param s0 + * @param s1 + * @return a new instance of BroadcastDynamicShape + */ + public BroadcastDynamicShape broadcastDynamicShape(Operand s0, + Operand s1) { + return BroadcastDynamicShape.create(scope, s0, s1); + } + + /** + * Broadcast an array for a compatible shape. + *

+ * Broadcasting is the process of making arrays to have compatible shapes + * for arithmetic operations. Two shapes are compatible if for each + * dimension pair they are either equal or one of them is one. When trying + * to broadcast a Tensor to a shape, it starts with the trailing dimensions, + * and works its way forward. + *

+ * For example, + *

+ * >>> x = tf.constant([1, 2, 3]) + * >>> y = tf.broadcast_to(x, [3, 3]) + * >>> print(y) + * tf.Tensor( + * [[1 2 3] + * [1 2 3] + * [1 2 3]], shape=(3, 3), dtype=int32) + *

+ * In the above example, the input Tensor with the shape of `[1, 3]` + * is broadcasted to output Tensor with shape of `[3, 3]`. + * + * @param data type for {@code output()} output + * @param input A Tensor to broadcast. + * @param shape An 1-D `int` Tensor. The shape of the desired output. + * @return a new instance of BroadcastTo + */ + public BroadcastTo broadcastTo(Operand input, + Operand shape) { + return BroadcastTo.create(scope, input, shape); + } + + /** + * Bucketizes 'input' based on 'boundaries'. + *

+ * For example, if the inputs are + * boundaries = [0, 10, 100] + * input = [[-5, 10000] + * [150, 10] + * [5, 100]] + *

+ * then the output will be + * output = [[0, 3] + * [3, 2] + * [1, 3]] + * + * @param input Any shape of Tensor contains with int or float type. + * @param boundaries A sorted list of floats gives the boundary of the buckets. + * @return a new instance of Bucketize + */ + public Bucketize bucketize(Operand input, List boundaries) { + return Bucketize.create(scope, input, boundaries); + } + + /** + * Clips tensor values to a specified min and max. + *

+ * Given a tensor `t`, this operation returns a tensor of the same type and + * shape as `t` with its values clipped to `clip_value_min` and `clip_value_max`. + * Any values less than `clip_value_min` are set to `clip_value_min`. Any values + * greater than `clip_value_max` are set to `clip_value_max`. + * + * @param data type for {@code output()} output + * @param t A `Tensor`. + * @param clipValueMin A 0-D (scalar) `Tensor`, or a `Tensor` with the same shape + * as `t`. The minimum value to clip by. + * @param clipValueMax A 0-D (scalar) `Tensor`, or a `Tensor` with the same shape + * as `t`. The maximum value to clip by. + * @return a new instance of ClipByValue + */ + public ClipByValue clipByValue(Operand t, Operand clipValueMin, + Operand clipValueMax) { + return ClipByValue.create(scope, t, clipValueMin, clipValueMax); + } + + /** + * Concatenates tensors along one dimension. + * + * @param data type for {@code output()} output + * @param values List of `N` Tensors to concatenate. Their ranks and types must match, + * and their sizes must match in all dimensions except `concat_dim`. + * @param axis 0-D. The dimension along which to concatenate. Must be in the + * range [-rank(values), rank(values)). + * @return a new instance of Concat + */ + public Concat concat(Iterable> values, + Operand axis) { + return Concat.create(scope, values, axis); + } + + /** + * Creates a rank-1 constant of {@code int} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return an integer constant + */ + public Constant constant(int[] data) { + return Constant.vectorOf(scope, data); + } + + /** + * Creates a rank-3 constant of {@code int} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return an integer constant + */ + public Constant constant(int[][][] data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a constant containing a single {@code double} element. + * + * @param scope is a scope used to add the underlying operation. + * @param data The value to put into the new constant. + * @return a double constant + */ + public Constant constant(double data) { + return Constant.scalarOf(scope, data); + } + + /** + * Creates a rank-5 constant of {@code long} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return a long constant + */ + public Constant constant(long[][][][][] data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a rank-5 constant of {@code boolean} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return a boolean constant + */ + public Constant constant(boolean[][][][][] data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a rank-4 constant of {@code int} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return an integer constant + */ + public Constant constant(int[][][][] data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a rank-6 constant of {@code float} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return a float constant + */ + public Constant constant(float[][][][][][] data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a constant of {@code String} elements that is a copy of a given n-dimensional array, + * using the default UTF-8 encoding. + * + * @param scope is a scope used to add the underlying operation. + * @param data an n-dimensional array of {@code String} elements. + * @return a string constant + */ + public Constant constant(NdArray data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a constant containing a single {@code byte} element. + * + * @param scope is a scope used to add the underlying operation. + * @param data The value to put into the new constant. + * @return a byte constant + */ + public Constant constant(byte data) { + return Constant.scalarOf(scope, data); + } + + /** + * Creates a constant of {@code double} elements that is a copy of a given n-dimensional array. + * + * @param scope is a scope used to add the underlying operation. + * @param data an n-dimensional array of {@code double} elements. + * @return a double constant + */ + public Constant constant(DoubleNdArray data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a rank-3 constant of {@code boolean} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return a boolean constant + */ + public Constant constant(boolean[][][] data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a rank-4 constant of {@code float} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return a float constant + */ + public Constant constant(float[][][][] data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a rank-2 constant of {@code long} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return a long constant + */ + public Constant constant(long[][] data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a constant of {@code long} elements that is a copy of a given n-dimensional array. + * + * @param scope is a scope used to add the underlying operation. + * @param data an n-dimensional array of {@code long} elements. + * @return a long constant + */ + public Constant constant(LongNdArray data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a rank-5 constant of {@code byte} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return a byte constant + */ + public Constant constant(byte[][][][][] data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a rank-2 constant of {@code float} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return a float constant + */ + public Constant constant(float[][] data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a rank-2 constant of {@code byte} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return a byte constant + */ + public Constant constant(byte[][] data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a rank-5 constant of {@code double} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return a double constant + */ + public Constant constant(double[][][][][] data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a rank-3 constant of {@code float} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return a float constant + */ + public Constant constant(float[][][] data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a rank-1 constant of {@code byte} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return a byte constant + */ + public Constant constant(byte[] data) { + return Constant.vectorOf(scope, data); + } + + /** + * Creates a rank-1 constant of {@code float} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return a float constant + */ + public Constant constant(float[] data) { + return Constant.vectorOf(scope, data); + } + + /** + * Creates a rank-2 constant of {@code boolean} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return a boolean constant + */ + public Constant constant(boolean[][] data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a constant of {@code byte} elements that is a copy of a given n-dimensional array. + * + * @param scope is a scope used to add the underlying operation. + * @param data an n-dimensional array of {@code byte} elements. + * @return a byte constant + */ + public Constant constant(ByteNdArray data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a constant of {@code int} elements that is a copy of a given n-dimensional array. + * + * @param scope is a scope used to add the underlying operation. + * @param data an n-dimensional array of {@code int} elements. + * @return an integer constant + */ + public Constant constant(IntNdArray data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a {@code String} constant using the default, UTF-8 encoding. + * + * @param scope is a scope used to add the underlying operation. + * @param data The string to put into the new constant. + * @return a string constant + */ + public Constant constant(String data) { + return Constant.scalarOf(scope, data); + } + + /** + * Creates a rank-4 constant of {@code double} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return a double constant + */ + public Constant constant(double[][][][] data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a rank-2 constant of {@code double} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return a double constant + */ + public Constant constant(double[][] data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a constant containing a single {@code int} element. + * + * @param scope is a scope used to add the underlying operation. + * @param data The value to put into the new constant. + * @return an integer constant + */ + public Constant constant(int data) { + return Constant.scalarOf(scope, data); + } + + /** + * Creates a rank-4 constant of {@code byte} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return a byte constant + */ + public Constant constant(byte[][][][] data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a rank-6 constant of {@code int} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return an integer constant + */ + public Constant constant(int[][][][][][] data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a constant containing a single {@code long} element. + * + * @param scope is a scope used to add the underlying operation. + * @param data The value to put into the new constant. + * @return a long constant + */ + public Constant constant(long data) { + return Constant.scalarOf(scope, data); + } + + /** + * Creates a constant containing a single {@code float} element. + * + * @param scope is a scope used to add the underlying operation. + * @param data The value to put into the new constant. + * @return a float constant + */ + public Constant constant(float data) { + return Constant.scalarOf(scope, data); + } + + /** + * Creates a rank-5 constant of {@code float} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return a float constant + */ + public Constant constant(float[][][][][] data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a rank-3 constant of {@code double} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return a double constant + */ + public Constant constant(double[][][] data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a rank-6 constant of {@code long} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return a long constant + */ + public Constant constant(long[][][][][][] data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a rank-4 constant of {@code long} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return a long constant + */ + public Constant constant(long[][][][] data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a rank-1 constant of {@code long} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return a long constant + */ + public Constant constant(long[] data) { + return Constant.vectorOf(scope, data); + } + + /** + * Creates a rank-1 constant of {@code boolean} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return a boolean constant + */ + public Constant constant(boolean[] data) { + return Constant.vectorOf(scope, data); + } + + /** + * Creates a rank-3 constant of {@code byte} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return a byte constant + */ + public Constant constant(byte[][][] data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a rank-6 constant of {@code byte} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return a byte constant + */ + public Constant constant(byte[][][][][][] data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a rank-2 constant of {@code int} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return an integer constant + */ + public Constant constant(int[][] data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a rank-5 constant of {@code int} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return an integer constant + */ + public Constant constant(int[][][][][] data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a constant of {@code float} elements that is a copy of a given n-dimensional array. + * + * @param scope is a scope used to add the underlying operation. + * @param data an n-dimensional array of {@code float} elements. + * @return a float constant + */ + public Constant constant(FloatNdArray data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a rank-1 constant of {@code double} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return a double constant + */ + public Constant constant(double[] data) { + return Constant.vectorOf(scope, data); + } + + /** + * Creates a rank-6 constant of {@code boolean} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return a boolean constant + */ + public Constant constant(boolean[][][][][][] data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a rank-6 constant of {@code double} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return a double constant + */ + public Constant constant(double[][][][][][] data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a constant containing a single {@code boolean} element. + * + * @param scope is a scope used to add the underlying operation. + * @param data The value to put into the new constant. + * @return a boolean constant + */ + public Constant constant(boolean data) { + return Constant.scalarOf(scope, data); + } + + /** + * Creates a rank-4 constant of {@code boolean} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return a boolean constant + */ + public Constant constant(boolean[][][][] data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a rank-3 constant of {@code long} elements. + * + * @param scope is a scope used to add the underlying operation. + * @param data An array containing the values to put into the new constant. The dimensions of the + * new constant will match those of the array. + * @return a long constant + */ + public Constant constant(long[][][] data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a constant of {@code boolean} elements that is a copy of a given n-dimensional array. + * + * @param scope is a scope used to add the underlying operation. + * @param data an n-dimensional array of {@code boolean} elements. + * @return a boolean constant + */ + public Constant constant(BooleanNdArray data) { + return Constant.tensorOf(scope, data); + } + + /** + * Creates a rank-1 constant of {@code long} elements representing the size of each dimensions of + * the given shape. + * + * @param scope is a scope used to add the underlying operation. + * @param shape a shape + * @return a long constant + */ + public Constant constant(Shape shape) { + return Constant.tensorOf(scope, shape); + } + + /** + * Create a constant from a Tensor. + * + * @param scope is a scope used to add the underlying operation. + * @param tensor a Tensor holding the constant value + * @return a constant of the same data type as `tensor` + */ + public Constant constant(Tensor tensor) { + return Constant.create(scope, tensor); + } + + /** + * Creates a constant of {@code String} elements, using the given charset. + * + * @param scope is a scope used to add the underlying operation. + * @param charset charset for encoding/decoding strings bytes. + * @param data An array containing the values to put into the new constant. String elements are + * sequences of bytes from the last array dimension. + * @return the {@code String} constant + */ + public Constant constant(Charset charset, String[] data) { + return Constant.vectorOf(scope, charset, data); + } + + /** + * Creates a {@code String} constant using a specified encoding. + * + * @param scope is a scope used to add the underlying operation. + * @param charset The encoding from String to bytes. + * @param data The string to put into the new constant. + * @return a string constant + */ + public Constant constant(Charset charset, String data) { + return Constant.scalarOf(scope, charset, data); + } + + /** + * Creates a constant of {@code String} elements that is a copy of a given n-dimensional array, + * using the given encoding. + * + * @param scope is a scope used to add the underlying operation. + * @param charset charset used to encode/decode string bytes. + * @param data an n-dimensional array of {@code String} elements. + * @return a string constant + */ + public Constant constant(Charset charset, NdArray data) { + return Constant.tensorOf(scope, charset, data); + } + + /** + * Create a {@link TInt32} constant with data from the given buffer. + * + * @param scope is a scope used to add the underlying operation. + * @param shape the tensor shape. + * @param data a buffer containing the tensor data. + * @return an integer constant + * @throws IllegalArgumentException If the tensor shape is not compatible with the buffer + */ + public Constant constant(Shape shape, IntDataBuffer data) { + return Constant.tensorOf(scope, shape, data); + } + + /** + * Create a {@link TFloat64} constant with data from the given buffer. + * + * @param scope is a scope used to add the underlying operation. + * @param shape the tensor shape. + * @param data a buffer containing the tensor data. + * @return a double constant + * @throws IllegalArgumentException If the tensor shape is not compatible with the buffer + */ + public Constant constant(Shape shape, DoubleDataBuffer data) { + return Constant.tensorOf(scope, shape, data); + } + + /** + * Create a {@link TBool} constant with data from the given buffer. + * + * @param scope is a scope used to add the underlying operation. + * @param shape the tensor shape. + * @param data a buffer containing the tensor data. + * @return an boolean constant + * @throws IllegalArgumentException If the tensor shape is not compatible with the buffer + */ + public Constant constant(Shape shape, BooleanDataBuffer data) { + return Constant.tensorOf(scope, shape, data); + } + + /** + * Create a {@link TFloat32} constant with data from the given buffer. + * + * @param scope is a scope used to add the underlying operation. + * @param shape the tensor shape. + * @param data a buffer containing the tensor data. + * @return a float constant + * @throws IllegalArgumentException If the tensor shape is not compatible with the buffer + */ + public Constant constant(Shape shape, FloatDataBuffer data) { + return Constant.tensorOf(scope, shape, data); + } + + /** + * Create a {@link TInt64} constant with data from the given buffer. + * + * @param scope is a scope used to add the underlying operation. + * @param shape the tensor shape. + * @param data a buffer containing the tensor data. + * @return a long constant + * @throws IllegalArgumentException If the tensor shape is not compatible with the buffer + */ + public Constant constant(Shape shape, LongDataBuffer data) { + return Constant.tensorOf(scope, shape, data); + } + + /** + * Create a {@link TUint8} constant with data from the given buffer. + * + * @param scope is a scope used to add the underlying operation. + * @param shape the tensor shape. + * @param data a buffer containing the tensor data. + * @return a byte constant + * @throws IllegalArgumentException If the tensor shape is not compatible with the buffer + */ + public Constant constant(Shape shape, ByteDataBuffer data) { + return Constant.tensorOf(scope, shape, data); + } + + /** + * Create a {@link TString} constant with data from the given buffer, using the default UTF-8 + * encoding. + * + * @param scope is a scope used to add the underlying operation. + * @param shape the tensor shape. + * @param data a buffer containing the tensor data. + * @return a string constant + * @throws IllegalArgumentException If the tensor shape is not compatible with the buffer + */ + public Constant constant(Shape shape, DataBuffer data) { + return Constant.tensorOf(scope, shape, data); + } + + /** + * Create a {@link TString} constant with data from the given buffer, using the given encoding. + * + * @param scope is a scope used to add the underlying operation. + * @param charset charset used to encode/decode string bytes. + * @param shape the tensor shape. + * @param data a buffer containing the tensor data. + * @return a string constant + * @throws IllegalArgumentException If the tensor shape is not compatible with the buffer + */ + public Constant constant(Charset charset, Shape shape, DataBuffer data) { + return Constant.tensorOf(scope, charset, shape, data); + } + + /** + * Create a constant with data from the given buffer. + * + * @param scope is a scope used to add the underlying operation. + * @param type the tensor datatype. + * @param shape the tensor shape. + * @param data a buffer containing the tensor data. + * @return a constant of type `type` + * @throws IllegalArgumentException If the tensor datatype or shape is not compatible with the + * buffer + */ + public Constant constant(DataType type, Shape shape, + ByteDataBuffer data) { + return Constant.tensorOf(scope, type, shape, data); + } + + /** + * This op consumes a lock created by `MutexLock`. + *

+ * This op exists to consume a tensor created by `MutexLock` (other than + * direct control dependencies). It should be the only that consumes the tensor, + * and will raise an error if it is not. Its only purpose is to keep the + * mutex lock tensor alive until it is consumed by this op. + *

+ * NOTE: This operation must run on the same device as its input. This may + * be enforced via the `colocate_with` mechanism. + * + * @param mutexLock A tensor returned by `MutexLock`. + * @return a new instance of ConsumeMutexLock + */ + public ConsumeMutexLock consumeMutexLock(Operand mutexLock) { + return ConsumeMutexLock.create(scope, mutexLock); + } + + /** + * Does nothing. Serves as a control trigger for scheduling. + *

+ * Only useful as a placeholder for control edges. + * + * @return a new instance of ControlTrigger + */ + public ControlTrigger controlTrigger() { + return ControlTrigger.create(scope); + } + + /** + * Increments 'ref' until it reaches 'limit'. + * + * @param data type for {@code output()} output + * @param ref Should be from a scalar `Variable` node. + * @param limit If incrementing ref would bring it above limit, instead generates an + * 'OutOfRange' error. + * @return a new instance of CountUpTo + */ + public CountUpTo countUpTo(Operand ref, Long limit) { + return CountUpTo.create(scope, ref, limit); + } + + /** + * Makes a copy of `x`. + * + * @param data type for {@code y()} output + * @param x The source tensor of type `T`. + * @return a new instance of DeepCopy + */ + public DeepCopy deepCopy(Operand x) { + return DeepCopy.create(scope, x); + } + + /** + * Delete the tensor specified by its handle in the session. + * + * @param handle The handle for a tensor stored in the session state. + * @return a new instance of DeleteSessionTensor + */ + public DeleteSessionTensor deleteSessionTensor(Operand handle) { + return DeleteSessionTensor.create(scope, handle); + } + + /** + * Deletes the resource specified by the handle. + *

+ * All subsequent operations using the resource will result in a NotFound + * error status. + * + * @param resource handle to the resource to delete. + * @param options carries optional attributes values + * @return a new instance of DestroyResourceOp + */ + public DestroyResourceOp destroyResourceOp(Operand resource, + DestroyResourceOp.Options... options) { + return DestroyResourceOp.create(scope, resource, options); + } + + /** + * Destroys the temporary variable and returns its final value. + *

+ * Sets output to the value of the Tensor pointed to by 'ref', then destroys + * the temporary variable called 'var_name'. + * All other uses of 'ref' must have executed before this op. + * This is typically achieved by chaining the ref through each assign op, or by + * using control dependencies. + *

+ * Outputs the final value of the tensor pointed to by 'ref'. + * + * @param data type for {@code value()} output + * @param ref A reference to the temporary variable tensor. + * @param varName Name of the temporary variable, usually the name of the matching + * 'TemporaryVariable' op. + * @return a new instance of DestroyTemporaryVariable + */ + public DestroyTemporaryVariable destroyTemporaryVariable(Operand ref, + String varName) { + return DestroyTemporaryVariable.create(scope, ref, varName); + } + + /** + * Partitions `data` into `num_partitions` tensors using indices from `partitions`. + *

+ * For each index tuple `js` of size `partitions.ndim`, the slice `data[js, ...]` + * becomes part of `outputs[partitions[js]]`. The slices with `partitions[js] = i` + * are placed in `outputs[i]` in lexicographic order of `js`, and the first + * dimension of `outputs[i]` is the number of entries in `partitions` equal to `i`. + * In detail, + *

{@code
+   *      outputs[i].shape = [sum(partitions == i)] + data.shape[partitions.ndim:]
+   *
+   *      outputs[i] = pack([data[js, ...] for js if partitions[js] == i])
+   *  }
+ * `data.shape` must start with `partitions.shape`. + *

+ * For example: + *

{@code
+   *      # Scalar partitions.
+   *      partitions = 1
+   *      num_partitions = 2
+   *      data = [10, 20]
+   *      outputs[0] = []  # Empty with shape [0, 2]
+   *      outputs[1] = [[10, 20]]
+   *
+   *      # Vector partitions.
+   *      partitions = [0, 0, 1, 1, 0]
+   *      num_partitions = 2
+   *      data = [10, 20, 30, 40, 50]
+   *      outputs[0] = [10, 20, 50]
+   *      outputs[1] = [30, 40]
+   *  }
+ * See `dynamic_stitch` for an example on how to merge partitions back. + *

+ *

+ * + *
+ * + * @param data type for {@code outputs()} output + * @param data + * @param partitions Any shape. Indices in the range `[0, num_partitions)`. + * @param numPartitions The number of partitions to output. + * @return a new instance of DynamicPartition + */ + public DynamicPartition dynamicPartition(Operand data, + Operand partitions, Long numPartitions) { + return DynamicPartition.create(scope, data, partitions, numPartitions); + } + + /** + * Interleave the values from the `data` tensors into a single tensor. + *

+ * Builds a merged tensor such that + *

{@code
+   *      merged[indices[m][i, ..., j], ...] = data[m][i, ..., j, ...]
+   *  }
+ * For example, if each `indices[m]` is scalar or vector, we have + *
{@code
+   *      # Scalar indices:
+   *      merged[indices[m], ...] = data[m][...]
+   *
+   *      # Vector indices:
+   *      merged[indices[m][i], ...] = data[m][i, ...]
+   *  }
+ * Each `data[i].shape` must start with the corresponding `indices[i].shape`, + * and the rest of `data[i].shape` must be constant w.r.t. `i`. That is, we + * must have `data[i].shape = indices[i].shape + constant`. In terms of this + * `constant`, the output shape is + *

+ * merged.shape = [max(indices)] + constant + *

+ * Values are merged in order, so if an index appears in both `indices[m][i]` and + * `indices[n][j]` for `(m,i) < (n,j)` the slice `data[n][j]` will appear in the + * merged result. If you do not need this guarantee, ParallelDynamicStitch might + * perform better on some devices. + *

+ * For example: + *

{@code
+   *      indices[0] = 6
+   *      indices[1] = [4, 1]
+   *      indices[2] = [[5, 2], [0, 3]]
+   *      data[0] = [61, 62]
+   *      data[1] = [[41, 42], [11, 12]]
+   *      data[2] = [[[51, 52], [21, 22]], [[1, 2], [31, 32]]]
+   *      merged = [[1, 2], [11, 12], [21, 22], [31, 32], [41, 42],
+   *                [51, 52], [61, 62]]
+   *  }
+ * This method can be used to merge partitions created by `dynamic_partition` + * as illustrated on the following example: + *
{@code
+   *      # Apply function (increments x_i) on elements for which a certain condition
+   *      # apply (x_i != -1 in this example).
+   *      x=tf.constant([0.1, -1., 5.2, 4.3, -1., 7.4])
+   *      condition_mask=tf.not_equal(x,tf.constant(-1.))
+   *      partitioned_data = tf.dynamic_partition(
+   *          x, tf.cast(condition_mask, tf.int32) , 2)
+   *      partitioned_data[1] = partitioned_data[1] + 1.0
+   *      condition_indices = tf.dynamic_partition(
+   *          tf.range(tf.shape(x)[0]), tf.cast(condition_mask, tf.int32) , 2)
+   *      x = tf.dynamic_stitch(condition_indices, partitioned_data)
+   *      # Here x=[1.1, -1., 6.2, 5.3, -1, 8.4], the -1. values remain
+   *      # unchanged.
+   *  }
+ *
+ * + *
+ * + * @param data type for {@code merged()} output + * @param indices + * @param data + * @return a new instance of DynamicStitch + */ + public DynamicStitch dynamicStitch(Iterable> indices, + Iterable> data) { + return DynamicStitch.create(scope, indices, data); + } + + /** + * Computes the (possibly normalized) Levenshtein Edit Distance. + *

+ * The inputs are variable-length sequences provided by SparseTensors + * (hypothesis_indices, hypothesis_values, hypothesis_shape) + * and + * (truth_indices, truth_values, truth_shape). + *

+ * The inputs are: + * + * @param hypothesisIndices The indices of the hypothesis list SparseTensor. + * This is an N x R int64 matrix. + * @param hypothesisValues The values of the hypothesis list SparseTensor. + * This is an N-length vector. + * @param hypothesisShape The shape of the hypothesis list SparseTensor. + * This is an R-length vector. + * @param truthIndices The indices of the truth list SparseTensor. + * This is an M x R int64 matrix. + * @param truthValues The values of the truth list SparseTensor. + * This is an M-length vector. + * @param truthShape truth indices, vector. + * @param options carries optional attributes values + * @return a new instance of EditDistance + */ + public EditDistance editDistance(Operand hypothesisIndices, + Operand hypothesisValues, Operand hypothesisShape, Operand truthIndices, + Operand truthValues, Operand truthShape, EditDistance.Options... options) { + return EditDistance.create(scope, hypothesisIndices, hypothesisValues, hypothesisShape, truthIndices, truthValues, truthShape, options); + } + + /** + * Creates a tensor with the given shape. + *

+ * This operation creates a tensor of `shape` and `dtype`. + * + * @param data type for {@code output()} output + * @param shape 1-D. Represents the shape of the output tensor. + * @param dtype + * @param options carries optional attributes values + * @return a new instance of Empty + */ + public Empty empty(Operand shape, DataType dtype, + Empty.Options... options) { + return Empty.create(scope, shape, dtype, options); + } + + /** + * Creates and returns an empty tensor list. + *

+ * All list elements must be tensors of dtype element_dtype and shape compatible + * with element_shape. + *

+ * handle: an empty tensor list. + * element_dtype: the type of elements in the list. + * element_shape: a shape compatible with that of elements in the list. + * + * @param elementShape + * @param maxNumElements + * @param elementDtype + * @return a new instance of EmptyTensorList + */ + public EmptyTensorList emptyTensorList( + Operand elementShape, Operand maxNumElements, DataType elementDtype) { + return EmptyTensorList.create(scope, elementShape, maxNumElements, elementDtype); + } + + /** + * Ensures that the tensor's shape matches the expected shape. + *

+ * Raises an error if the input tensor's shape does not match the specified shape. + * Returns the input tensor otherwise. + * + * @param data type for {@code output()} output + * @param input A tensor, whose shape is to be validated. + * @param shape The expected (possibly partially specified) shape of the input tensor. + * @return a new instance of EnsureShape + */ + public EnsureShape ensureShape(Operand input, Shape shape) { + return EnsureShape.create(scope, input, shape); + } + + /** + * Inserts a dimension of 1 into a tensor's shape. + *

+ * Given a tensor `input`, this operation inserts a dimension of 1 at the + * dimension index `axis` of `input`'s shape. The dimension index `axis` starts at + * zero; if you specify a negative number for `axis` it is counted backward from + * the end. + *

+ * This operation is useful if you want to add a batch dimension to a single + * element. For example, if you have a single image of shape `[height, width, + * channels]`, you can make it a batch of 1 image with `expand_dims(image, 0)`, + * which will make the shape `[1, height, width, channels]`. + *

+ * Other examples: + *

{@code
+   *  # 't' is a tensor of shape [2]
+   *  shape(expand_dims(t, 0)) ==> [1, 2]
+   *  shape(expand_dims(t, 1)) ==> [2, 1]
+   *  shape(expand_dims(t, -1)) ==> [2, 1]
+   *
+   *  # 't2' is a tensor of shape [2, 3, 5]
+   *  shape(expand_dims(t2, 0)) ==> [1, 2, 3, 5]
+   *  shape(expand_dims(t2, 2)) ==> [2, 3, 1, 5]
+   *  shape(expand_dims(t2, 3)) ==> [2, 3, 5, 1]
+   *  }
+ * This operation requires that: + *

+ * `-1-input.dims() <= dim <= input.dims()` + *

+ * This operation is related to `squeeze()`, which removes dimensions of + * size 1. + * + * @param data type for {@code output()} output + * @param input + * @param axis 0-D (scalar). Specifies the dimension index at which to + * expand the shape of `input`. Must be in the range + * `[-rank(input) - 1, rank(input)]`. + * @return a new instance of ExpandDims + */ + public ExpandDims expandDims(Operand input, + Operand axis) { + return ExpandDims.create(scope, input, axis); + } + + /** + * Extract `patches` from `input` and put them in the "depth" output dimension. 3D extension of `extract_image_patches`. + * + * @param data type for {@code patches()} output + * @param input 5-D Tensor with shape `[batch, in_planes, in_rows, in_cols, depth]`. + * @param ksizes The size of the sliding window for each dimension of `input`. + * @param strides 1-D of length 5. How far the centers of two consecutive patches are in + * `input`. Must be: `[1, stride_planes, stride_rows, stride_cols, 1]`. + * @param padding The type of padding algorithm to use. + *

+ * We specify the size-related attributes as: + *

{@code
+   *        ksizes = [1, ksize_planes, ksize_rows, ksize_cols, 1]
+   *        strides = [1, stride_planes, strides_rows, strides_cols, 1]
+   *  }
+ * @return a new instance of ExtractVolumePatches + */ + public ExtractVolumePatches extractVolumePatches(Operand input, + List ksizes, List strides, String padding) { + return ExtractVolumePatches.create(scope, input, ksizes, strides, padding); + } + + /** + * Creates a tensor filled with a scalar value. + *

+ * This operation creates a tensor of shape `dims` and fills it with `value`. + *

+ * For example: + *

{@code
+   *  # Output tensor has shape [2, 3].
+   *  fill([2, 3], 9) ==> [[9, 9, 9]
+   *                       [9, 9, 9]]
+   *  }
+ * `tf.fill` differs from `tf.constant` in a few ways: + *