aboutsummaryrefslogtreecommitdiffstats
path: root/javaparser-testing
diff options
context:
space:
mode:
authorandroid-build-team Robot <android-build-team-robot@google.com>2018-03-04 08:21:35 +0000
committerandroid-build-team Robot <android-build-team-robot@google.com>2018-03-04 08:21:35 +0000
commitb4c1397d5df9370f6358d4f8e9efd27e0f67dec1 (patch)
tree6789ec288d344cf5fd5d057bcf1efc9545b1af28 /javaparser-testing
parent92d661a1d239131fb5c1e019a8f2ac7584d2d3f6 (diff)
parent1afe9e0652b9b53edade5aa276162abe27b32a67 (diff)
downloadplatform_external_javaparser-b4c1397d5df9370f6358d4f8e9efd27e0f67dec1.tar.gz
platform_external_javaparser-b4c1397d5df9370f6358d4f8e9efd27e0f67dec1.tar.bz2
platform_external_javaparser-b4c1397d5df9370f6358d4f8e9efd27e0f67dec1.zip
Snap for 4632767 from 1afe9e0652b9b53edade5aa276162abe27b32a67 to pi-releaseandroid-wear-9.0.0_r9android-wear-9.0.0_r8android-wear-9.0.0_r7android-wear-9.0.0_r6android-wear-9.0.0_r5android-wear-9.0.0_r4android-wear-9.0.0_r3android-wear-9.0.0_r23android-wear-9.0.0_r22android-wear-9.0.0_r21android-wear-9.0.0_r20android-wear-9.0.0_r2android-wear-9.0.0_r19android-wear-9.0.0_r18android-wear-9.0.0_r17android-wear-9.0.0_r16android-wear-9.0.0_r15android-wear-9.0.0_r14android-wear-9.0.0_r13android-wear-9.0.0_r12android-wear-9.0.0_r11android-wear-9.0.0_r10android-wear-9.0.0_r1android-vts-9.0_r9android-vts-9.0_r8android-vts-9.0_r7android-vts-9.0_r6android-vts-9.0_r5android-vts-9.0_r4android-vts-9.0_r14android-vts-9.0_r13android-vts-9.0_r12android-vts-9.0_r11android-vts-9.0_r10android-cts-9.0_r9android-cts-9.0_r8android-cts-9.0_r7android-cts-9.0_r6android-cts-9.0_r5android-cts-9.0_r4android-cts-9.0_r3android-cts-9.0_r2android-cts-9.0_r13android-cts-9.0_r12android-cts-9.0_r11android-cts-9.0_r10android-cts-9.0_r1android-9.0.0_r9android-9.0.0_r8android-9.0.0_r7android-9.0.0_r60android-9.0.0_r6android-9.0.0_r59android-9.0.0_r58android-9.0.0_r57android-9.0.0_r56android-9.0.0_r55android-9.0.0_r54android-9.0.0_r53android-9.0.0_r52android-9.0.0_r51android-9.0.0_r50android-9.0.0_r5android-9.0.0_r49android-9.0.0_r48android-9.0.0_r3android-9.0.0_r2android-9.0.0_r18android-9.0.0_r17android-9.0.0_r10android-9.0.0_r1security-pi-releasepie-vts-releasepie-security-releasepie-s2-releasepie-release-2pie-releasepie-r2-s2-releasepie-r2-s1-releasepie-r2-releasepie-platform-releasepie-gsipie-cuttlefish-testingpie-cts-release
Change-Id: Ibe65883e94ed5a7272dff3f100393987a1cf3da2
Diffstat (limited to 'javaparser-testing')
-rw-r--r--javaparser-testing/javaparser-testing.iml38
-rw-r--r--javaparser-testing/pom.xml116
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/CommentsInserterTest.java103
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/GeneratedJavaParserTokenManagerTest.java37
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/JavaParserTest.java249
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/JavaTokenTest.java77
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/JavadocParserTest.java168
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ParseErrorRecoveryTest.java42
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ParserConfigurationTest.java33
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ProblemTest.java32
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ProvidersTest.java63
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/RangeTest.java100
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/TokenRangeTest.java14
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/CompilationUnitTest.java108
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/DataKeyTest.java53
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/NodeListTest.java329
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/NodePositionTest.java92
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/NodeTest.java414
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/ParseResultTest.java66
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/ReplaceNodeTest.java32
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/body/AnnotationMemberDeclarationTest.java67
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/body/ClassOrInterfaceDeclarationTest.java60
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/body/ConstructorDeclarationTest.java23
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/body/FieldDeclarationTest.java24
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/body/MethodDeclarationTest.java87
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/comments/CommentTest.java72
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/expr/AssignExprTest.java12
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/expr/BinaryExprTest.java12
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/expr/DoubleLiteralExprTest.java37
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/expr/InstanceOfExprTest.java15
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/expr/LambdaExprTest.java41
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/expr/LiteralStringValueExprTest.java166
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/expr/MethodCallExprTest.java22
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/expr/MethodReferenceExprTest.java114
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/expr/NameTest.java83
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/expr/SimpleNameTest.java51
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/expr/StringLiteralExprTest.java14
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/imports/ImportDeclarationTest.java57
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithJavadocTest.java73
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithModifiersTest.java66
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithOptionalScopeTest.java28
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithTraversableScopeTest.java23
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithVariablesTest.java95
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/observer/PropagatingAstObserverTest.java59
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/stmt/BlockStmtTest.java21
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/stmt/IfElseStmtTest.java37
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/stmt/TryStmtTest.java81
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/type/ArrayTypeTest.java188
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/type/TypeTest.java68
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java10ValidatorTest.java108
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java11ValidatorTest.java22
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_0ValidatorTest.java98
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_1ValidatorTest.java292
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_2ValidatorTest.java275
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_3ValidatorTest.java22
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_4ValidatorTest.java70
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java5ValidatorTest.java155
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java6ValidatorTest.java42
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java7ValidatorTest.java107
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java8ValidatorTest.java82
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java9ValidatorTest.java79
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/CloneVisitorTest.java107
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/HashCodeVisitorTest.java24
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/ModifierVisitorTest.java127
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/NoCommentEqualsVisitorTest.java54
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/NoCommentHashCodeVisitorTest.java34
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/TreeVisitorTest.java158
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/bdd/BasicJBehaveTest.java65
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/bdd/CommentParsingTest.java42
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/bdd/ComparingTest.java51
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/bdd/ManipulationTest.java49
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/bdd/ParsingTest.java51
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/bdd/PositionRangeTest.java51
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/bdd/PrettyPrintingTest.java42
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/bdd/TestUtils.java37
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/bdd/VisitorTest.java51
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/CommentParsingSteps.java431
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/ComparingSteps.java61
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/ExistenceOfParentNodeVerifier.java542
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/ManipulationSteps.java286
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/ParsingSteps.java343
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/PositionRangeSteps.java129
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/PrettyPrintingSteps.java114
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/SharedSteps.java163
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/VisitorSteps.java171
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/bdd/visitors/PositionTestVisitor.java553
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/builders/ClassOrInterfaceDeclarationBuildersTest.java70
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/builders/CompilationUnitBuildersTest.java134
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/builders/EnumDeclarationBuildersTest.java56
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/builders/FieldDeclarationBuildersTest.java120
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/builders/NodeWithAnnotationsBuildersTest.java82
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/builders/NodeWithMembersBuildersTest.java133
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/builders/NodeWithParametersBuildersTest.java68
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/builders/NodeWithThrownExceptionsBuildersTest.java48
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/javadoc/JavadocExtractorTest.java67
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/javadoc/JavadocTest.java138
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/javadoc/description/JavadocInlineTagTest.java36
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/manual/BulkParseTest.java120
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/metamodel/BaseNodeMetaModelTest.java25
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/metamodel/PropertyMetaModelTest.java45
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/modules/ModuleDeclarationTest.java181
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/printer/ConcreteSyntaxModelAcceptanceTest.java59
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/printer/ConcreteSyntaxModelTest.java97
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/printer/DotPrinterTest.java79
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/printer/JsonPrinterTest.java75
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/printer/PrettyPrintVisitorTest.java277
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/printer/PrettyPrinterTest.java206
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/printer/TestVisitor.java15
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java41
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/printer/YamlPrinterTest.java94
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/AbstractLexicalPreservingTest.java74
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/DifferenceTest.java428
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/LexicalDifferenceCalculatorTest.java300
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinterTest.java1051
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/TransformationsTest.java143
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/ArrayCreationLevelTransformationsTest.java93
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/CompilationUnitTransformationsTest.java66
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/AnnotationDeclarationTransformationsTest.java126
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/AnnotationMemberDeclarationTransformationsTest.java175
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/ClassOrInterfaceDeclarationTransformationsTest.java194
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/ConstructorDeclarationTransformationsTest.java122
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/EnumConstantDeclarationTransformationsTest.java54
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/EnumDeclarationTransformationsTest.java82
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/FieldDeclarationTransformationsTest.java76
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/InitializerDeclarationTransformationsTest.java61
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/MethodDeclarationTransformationsTest.java122
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/remove/NodeRemovalTest.java71
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/utils/CodeGenerationUtilsTest.java22
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/utils/PairTest.java21
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/utils/SourceRootTest.java38
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/utils/SourceZipTest.java81
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/utils/TestUtils.java155
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/utils/UtilsTest.java92
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/utils/VisitorListTest.java187
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/utils/VisitorMapTest.java80
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/utils/VisitorSetTest.java141
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/version/Java10PostProcessorTest.java28
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/ChangingMethodsFromAClassWithAVisitorTest.java33
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/ChangingMethodsFromAClassWithoutAVisitorTest.java33
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/ClassCreator.java95
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/CreatingACompilationUnitFromScratch.java31
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/CuPrinter.java41
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/MethodChanger_1.java57
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/MethodChanger_2.java73
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/MethodPrinter.java57
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/PrintingTheCompilationUnitToSystemOutputTest.java34
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/TestFileToken.java58
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/VisitingClassMethodsTest.java33
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/removenode/D.java29
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/removenode/ModifierVisitorTest.java65
-rw-r--r--javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/removenode/RemoveDeleteNodeFromAst.java34
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/TestFileIso88591.java7
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/bdd/comment_attribution_scenarios.story498
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/bdd/comment_parsing_scenarios.story281
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/bdd/comparing_scenarios.story19
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/bdd/manipulation_scenarios.story137
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/bdd/parsing_scenarios.story500
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/bdd/position_range_scenarios.story55
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/bdd/pretty_printing_java_concepts.story399
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/bdd/pretty_printing_scenarios.story519
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/bdd/samples/ClassInLatin1.java6
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/bdd/samples/JavaConcepts.java397
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/bdd/samples/package-info.java5
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/bdd/visitor_scenarios.story67
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results.txt1
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/bulk_test_results/openjdk_src_repo_test_results.txt655
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/bulk_test_results/openjdk_src_zip_test_results.txt4
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/issue_samples/Issue290.java.txt34
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/issue_samples/Issue624.java.txt14
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/issue_samples/issue1003.java.txt1470
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/ASimpleClassWithMoreFormatting.java.txt26
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/ASimpleClassWithMoreFormatting_step1.java.txt26
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/ASimpleClassWithMoreFormatting_step2.java.txt29
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/ASimpleClassWithMoreFormatting_step3.java.txt29
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/ASimpleClassWithMoreFormatting_step4.java.txt30
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example10_expected.java.txt11
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example1_expected.java.txt11
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example1_original.java.txt11
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example2_expected.java.txt11
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example3_expected.java.txt11
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example3_original.java.txt11
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example4_expected.java.txt11
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example5_expected.java.txt12
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example6_expected.java.txt10
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example7_expected.java.txt11
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example8_expected.java.txt12
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example9_expected.java.txt10
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example9_original.java.txt11
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example10_expected.java.txt3
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example10_original.java.txt4
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example1_expected.java.txt4
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example1_original.java.txt4
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example2_expected.java.txt4
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example2_original.java.txt4
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example3_expected.java.txt4
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example3_original.java.txt4
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example4_original.java.txt398
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example5_expected.java.txt4
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example5_original.java.txt4
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example6_expected.java.txt4
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example6_original.java.txt4
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example7_expected.java.txt4
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example7_original.java.txt4
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example8_expected.java.txt4
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example8_original.java.txt4
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example9_expected.java.txt4
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example9_original.java.txt4
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param1_expected.java.txt4
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param1_original.java.txt4
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param2_expected.java.txt4
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param3_expected.java.txt4
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param3_original.java.txt4
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param4_expected.java.txt4
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param5_expected.java.txt6
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param5b_expected.java.txt4
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/MethodWithOneStatement.java.txt5
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/printer/JavaConcepts_prettyprinted395
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/printer/PrettyPrintVisitor_prettyprinted1353
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/source_zip/test.txt1
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/source_zip/test.zipbin0 -> 1278 bytes
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/storage/A.java1
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/storage/B.java0
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/storage/PrimaryType.java5
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/storage/PrimaryType2.java1
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/storage/Z.java1
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/utils/.abc/bla.java0
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/utils/Bla.java3
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/utils/module-info.java2
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/utils/source/root/Y.java3
-rw-r--r--javaparser-testing/src/test/resources/com/github/javaparser/wiki_samples/TestFile.java15
-rw-r--r--javaparser-testing/src/test/test_sourcecode/com/github/javaparser/printer/JavaConcepts.java393
-rw-r--r--javaparser-testing/src/test/test_sourcecode/com/github/javaparser/printer/PrettyPrintVisitor.java1413
232 files changed, 25417 insertions, 0 deletions
diff --git a/javaparser-testing/javaparser-testing.iml b/javaparser-testing/javaparser-testing.iml
new file mode 100644
index 000000000..6130e1aa1
--- /dev/null
+++ b/javaparser-testing/javaparser-testing.iml
@@ -0,0 +1,38 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
+ <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
+ <output url="file://$MODULE_DIR$/target/classes" />
+ <output-test url="file://$MODULE_DIR$/target/test-classes" />
+ <content url="file://$MODULE_DIR$">
+ <sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
+ <sourceFolder url="file://$MODULE_DIR$/src/test/resources" type="java-test-resource" />
+ <excludeFolder url="file://$MODULE_DIR$/target" />
+ </content>
+ <orderEntry type="inheritedJdk" />
+ <orderEntry type="sourceFolder" forTests="false" />
+ <orderEntry type="module" module-name="javaparser-core" scope="TEST" />
+ <orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter-api:5.0.0" level="project" />
+ <orderEntry type="library" scope="TEST" name="Maven: org.apiguardian:apiguardian-api:1.0.0" level="project" />
+ <orderEntry type="library" scope="TEST" name="Maven: org.opentest4j:opentest4j:1.0.0" level="project" />
+ <orderEntry type="library" scope="TEST" name="Maven: org.junit.platform:junit-platform-commons:1.0.0" level="project" />
+ <orderEntry type="library" scope="TEST" name="Maven: org.jbehave:jbehave-core:4.1.2" level="project" />
+ <orderEntry type="library" scope="TEST" name="Maven: junit:junit:4.12" level="project" />
+ <orderEntry type="library" scope="TEST" name="Maven: org.hamcrest:hamcrest-core:1.3" level="project" />
+ <orderEntry type="library" scope="TEST" name="Maven: org.hamcrest:hamcrest-library:1.3" level="project" />
+ <orderEntry type="library" scope="TEST" name="Maven: org.hamcrest:hamcrest-integration:1.3" level="project" />
+ <orderEntry type="library" scope="TEST" name="Maven: org.apache.commons:commons-collections4:4.1" level="project" />
+ <orderEntry type="library" scope="TEST" name="Maven: commons-io:commons-io:2.5" level="project" />
+ <orderEntry type="library" scope="TEST" name="Maven: org.apache.commons:commons-lang3:3.4" level="project" />
+ <orderEntry type="library" scope="TEST" name="Maven: org.codehaus.plexus:plexus-utils:3.0.22" level="project" />
+ <orderEntry type="library" scope="TEST" name="Maven: org.freemarker:freemarker:2.3.23" level="project" />
+ <orderEntry type="library" scope="TEST" name="Maven: com.thoughtworks.paranamer:paranamer:2.8" level="project" />
+ <orderEntry type="library" scope="TEST" name="Maven: com.thoughtworks.xstream:xstream:1.4.9" level="project" />
+ <orderEntry type="library" scope="TEST" name="Maven: xmlpull:xmlpull:1.1.3.1" level="project" />
+ <orderEntry type="library" scope="TEST" name="Maven: xpp3:xpp3_min:1.1.4c" level="project" />
+ <orderEntry type="library" scope="TEST" name="Maven: com.google.code.gson:gson:2.8.0" level="project" />
+ <orderEntry type="library" scope="TEST" name="Maven: com.github.valfirst:jbehave-junit-runner:2.1.0" level="project" />
+ <orderEntry type="library" scope="TEST" name="Maven: org.assertj:assertj-core:3.6.2" level="project" />
+ <orderEntry type="library" scope="TEST" name="Maven: com.squareup.okhttp3:okhttp:3.6.0" level="project" />
+ <orderEntry type="library" scope="TEST" name="Maven: com.squareup.okio:okio:1.11.0" level="project" />
+ </component>
+</module> \ No newline at end of file
diff --git a/javaparser-testing/pom.xml b/javaparser-testing/pom.xml
new file mode 100644
index 000000000..7a3a458a7
--- /dev/null
+++ b/javaparser-testing/pom.xml
@@ -0,0 +1,116 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <parent>
+ <artifactId>javaparser-parent</artifactId>
+ <groupId>com.github.javaparser</groupId>
+ <version>3.5.16-SNAPSHOT</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+
+ <artifactId>javaparser-testing</artifactId>
+ <description>The test suite for javaparser-core</description>
+
+ <licenses>
+ <license>
+ <name>GNU Lesser General Public License</name>
+ <url>http://www.gnu.org/licenses/lgpl-3.0.html</url>
+ <distribution>repo</distribution>
+ </license>
+ <license>
+ <name>Apache License, Version 2.0</name>
+ <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
+ <distribution>repo</distribution>
+ <comments>A business-friendly OSS license</comments>
+ </license>
+ </licenses>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.jacoco</groupId>
+ <artifactId>jacoco-maven-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>jacoco-initialize</id>
+ <goals>
+ <goal>prepare-agent</goal>
+ </goals>
+ </execution>
+ <execution>
+ <id>jacoco-site</id>
+ <phase>package</phase>
+ <goals>
+ <goal>report</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <artifactId>maven-resources-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>copy-resources</id>
+ <phase>pre-integration-test</phase>
+ <goals>
+ <goal>copy-resources</goal>
+ </goals>
+ <configuration>
+ <encoding>UTF-8</encoding>
+ <outputDirectory>${basedir}/target/classes</outputDirectory>
+ <resources>
+ <resource>
+ <directory>../javaparser-core/target/classes</directory>
+ <filtering>false</filtering>
+ </resource>
+ </resources>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-deploy-plugin</artifactId>
+ <configuration>
+ <!-- no need to release this module -->
+ <skip>true</skip>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ <dependencies>
+ <dependency>
+ <groupId>com.github.javaparser</groupId>
+ <artifactId>javaparser-core</artifactId>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.jbehave</groupId>
+ <artifactId>jbehave-core</artifactId>
+ <version>4.1.2</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.github.valfirst</groupId>
+ <artifactId>jbehave-junit-runner</artifactId>
+ <version>2.1.0</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.assertj</groupId>
+ <artifactId>assertj-core</artifactId>
+ <version>3.6.2</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.squareup.okhttp3</groupId>
+ <artifactId>okhttp</artifactId>
+ <version>3.6.0</version>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+</project>
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/CommentsInserterTest.java b/javaparser-testing/src/test/java/com/github/javaparser/CommentsInserterTest.java
new file mode 100644
index 000000000..c44a63f50
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/CommentsInserterTest.java
@@ -0,0 +1,103 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser;
+
+import com.github.javaparser.ast.CompilationUnit;
+import com.github.javaparser.ast.comments.CommentsCollection;
+import org.junit.Test;
+
+import java.io.IOException;
+
+import static com.github.javaparser.JavaParser.*;
+import static com.github.javaparser.utils.TestUtils.assertEqualsNoEol;
+import static com.github.javaparser.utils.Utils.EOL;
+import static org.junit.Assert.assertEquals;
+
+public class CommentsInserterTest {
+ private String makeFilename(String sampleName) {
+ return "com/github/javaparser/issue_samples/" + sampleName + ".java.txt";
+ }
+
+ private ParseResult<CompilationUnit> 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
+ public void issue290() throws IOException {
+ ParseResult result = parseSample("Issue290");
+ CommentsCollection cc = (CommentsCollection) result.getCommentsCollection().get();
+ assertEquals(1, cc.getLineComments().size());
+ assertEquals(1, cc.getJavadocComments().size());
+ }
+
+ @Test
+ public void issue624() throws IOException {
+ parseResource(makeFilename("Issue624"));
+ // Should not fail
+ }
+
+ @Test
+ public void issue200EnumConstantsWithCommentsForceVerticalAlignment() {
+ CompilationUnit cu = parse("public enum X {" + EOL +
+ " /** const1 javadoc */" + EOL +
+ " BORDER_CONSTANT," + EOL +
+ " /** const2 javadoc */" + EOL +
+ " ANOTHER_CONSTANT" + EOL +
+ "}");
+ assertEqualsNoEol("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
+ public void issue234LosingCommentsInArrayInitializerExpr() {
+ CompilationUnit cu = parse("@Anno(stuff={" + EOL +
+ " // Just," + EOL +
+ " // an," + EOL +
+ " // example" + EOL +
+ "})" + EOL +
+ "class ABC {" + EOL +
+ "" + EOL +
+ "}");
+
+ assertEqualsNoEol("@Anno(stuff = {// Just,\n" +
+ "// an,\n" +
+ "// example\n" +
+ "})\n" +
+ "class ABC {\n" +
+ "}\n", cu.toString());
+ }
+
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/GeneratedJavaParserTokenManagerTest.java b/javaparser-testing/src/test/java/com/github/javaparser/GeneratedJavaParserTokenManagerTest.java
new file mode 100644
index 000000000..fdecede5c
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/GeneratedJavaParserTokenManagerTest.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser;
+
+import org.junit.Test;
+
+import java.io.IOException;
+
+public class GeneratedJavaParserTokenManagerTest {
+ private String makeFilename(String sampleName) {
+ return "com/github/javaparser/issue_samples/" + sampleName + ".java.txt";
+ }
+
+ @Test
+ public void issue1003() throws IOException {
+ JavaParser.parseResource(makeFilename("issue1003"));
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/JavaParserTest.java b/javaparser-testing/src/test/java/com/github/javaparser/JavaParserTest.java
new file mode 100644
index 000000000..7302e953f
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/JavaParserTest.java
@@ -0,0 +1,249 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser;
+
+import com.github.javaparser.ast.CompilationUnit;
+import com.github.javaparser.ast.body.AnnotationMemberDeclaration;
+import com.github.javaparser.ast.body.MethodDeclaration;
+import com.github.javaparser.ast.expr.ArrayCreationExpr;
+import com.github.javaparser.ast.expr.CastExpr;
+import com.github.javaparser.ast.expr.Expression;
+import com.github.javaparser.ast.expr.LambdaExpr;
+import com.github.javaparser.ast.stmt.*;
+import com.github.javaparser.ast.type.ClassOrInterfaceType;
+import com.github.javaparser.ast.type.IntersectionType;
+import com.github.javaparser.ast.type.Type;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.Optional;
+
+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.utils.CodeGenerationUtils.mavenModuleRoot;
+import static com.github.javaparser.utils.TestUtils.assertInstanceOf;
+import static com.github.javaparser.utils.Utils.EOL;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+public class JavaParserTest {
+
+ @Test
+ public void rangeOfAnnotationMemberDeclarationIsCorrect() {
+ String code = "@interface AD { String foo(); }";
+ CompilationUnit cu = JavaParser.parse(code);
+ AnnotationMemberDeclaration memberDeclaration = cu.getAnnotationDeclarationByName("AD").get().getMember(0).asAnnotationMemberDeclaration();
+ assertEquals(true, memberDeclaration.getRange().isPresent());
+ assertEquals(new Range(new Position(1, 17), new Position(1, 29)), memberDeclaration.getRange().get());
+ }
+
+ @Test
+ public void rangeOfAnnotationMemberDeclarationWithArrayTypeIsCorrect() {
+ String code = "@interface AD { String[] foo(); }";
+ CompilationUnit cu = JavaParser.parse(code);
+ AnnotationMemberDeclaration memberDeclaration = cu.getAnnotationDeclarationByName("AD").get().getMember(0).asAnnotationMemberDeclaration();
+ assertEquals(true, memberDeclaration.getRange().isPresent());
+ assertEquals(new Range(new Position(1, 17), new Position(1, 31)), memberDeclaration.getRange().get());
+ }
+
+ @Test
+ public void rangeOfArrayCreationLevelWithExpressionIsCorrect() {
+ String code = "new int[123][456]";
+ ArrayCreationExpr expression = JavaParser.parseExpression(code);
+ Optional<Range> range;
+
+ range = expression.getLevels().get(0).getRange();
+ assertEquals(true, range.isPresent());
+ assertEquals(new Range(new Position(1, 8), new Position(1, 12)), range.get());
+
+ range = expression.getLevels().get(1).getRange();
+ assertEquals(true, range.isPresent());
+ assertEquals(new Range(new Position(1, 13), new Position(1, 17)), range.get());
+ }
+
+ @Test
+ public void rangeOfArrayCreationLevelWithoutExpressionIsCorrect() {
+ String code = "new int[][]";
+ ArrayCreationExpr expression = JavaParser.parseExpression(code);
+ Optional<Range> range;
+
+ range = expression.getLevels().get(0).getRange();
+ assertEquals(true, range.isPresent());
+ assertEquals(new Range(new Position(1, 8), new Position(1, 9)), range.get());
+
+ range = expression.getLevels().get(1).getRange();
+ assertEquals(true, range.isPresent());
+ assertEquals(new Range(new Position(1, 10), new Position(1, 11)), range.get());
+ }
+
+ @Test
+ public void parseErrorContainsLocation() {
+ ParseResult<CompilationUnit> 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 <EOF>, 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\" \"{\" \"}\" <IDENTIFIER>", problem.getMessage());
+ assertInstanceOf(ParseException.class, problem.getCause().get());
+ }
+
+ @Test
+ public void parseIntersectionType() {
+ String code = "(Runnable & Serializable) (() -> {})";
+ Expression expression = JavaParser.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
+ public void rangeOfIntersectionType() {
+ String code = "class A {" + EOL
+ + " Object f() {" + EOL
+ + " return (Comparator<Map.Entry<K, V>> & Serializable)(c1, c2) -> c1.getKey().compareTo(c2.getKey()); " + EOL
+ + "}}";
+ CompilationUnit cu = JavaParser.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
+ public void rangeOfCast() {
+ String code = "class A {" + EOL
+ + " Object f() {" + EOL
+ + " return (Comparator<Map.Entry<K, V>> & Serializable)(c1, c2) -> c1.getKey().compareTo(c2.getKey()); " + EOL
+ + "}}";
+ CompilationUnit cu = JavaParser.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
+ public void rangeOfCastNonIntersection() {
+ String code = "class A {" + EOL
+ + " Object f() {" + EOL
+ + " return (Comparator<Map.Entry<K, V>> )(c1, c2) -> c1.getKey().compareTo(c2.getKey()); " + EOL
+ + "}}";
+ CompilationUnit cu = JavaParser.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
+ public void rangeOfLambda() {
+ String code = "class A {" + EOL
+ + " Object f() {" + EOL
+ + " return (Comparator<Map.Entry<K, V>> & Serializable)(c1, c2) -> c1.getKey().compareTo(c2.getKey()); " + EOL
+ + "}}";
+ CompilationUnit cu = JavaParser.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
+ public void rangeOfLambdaBody() {
+ String code = "class A {" + EOL
+ + " Object f() {" + EOL
+ + " return (Comparator<Map.Entry<K, V>> & Serializable)(c1, c2) -> c1.getKey().compareTo(c2.getKey()); " + EOL
+ + "}}";
+ CompilationUnit cu = JavaParser.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
+ public void testNotStoringTokens() {
+ JavaParser javaParser = new JavaParser(new ParserConfiguration().setStoreTokens(false));
+ ParseResult<CompilationUnit> result = javaParser.parse(ParseStart.COMPILATION_UNIT, provider("class X{}"));
+ assertEquals(false, result.getTokens().isPresent());
+ }
+
+ @Test(expected = ParseProblemException.class)
+ public void trailingCodeIsAnError() {
+ JavaParser.parseBlock("{} efijqoifjqefj");
+ }
+
+ @Test
+ public void trailingWhitespaceIsIgnored() {
+ BlockStmt blockStmt = JavaParser.parseBlock("{} // hello");
+ assertEquals("{}", blockStmt.getTokenRange().get().toString());
+ }
+
+ @Test
+ public 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 = JavaParser.parse(tokenTypesPath);
+ // -1 to take off the default: case.
+ int switchEntries = tokenTypesCu.findAll(SwitchEntryStmt.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
+ public void parsingInitializedAndUnitializedVarsInForStmt() {
+ ForStmt forStmt = JavaParser.parseStatement("for(int a,b=0;;){}").asForStmt();
+ assertEquals(1, forStmt.getInitialization().size());
+ assertEquals(true, 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());
+ assertEquals(false, forStmt.getInitialization().get(0).asVariableDeclarationExpr().getVariables().get(0).getInitializer().isPresent());
+ assertEquals(true, forStmt.getInitialization().get(0).asVariableDeclarationExpr().getVariables().get(1).getInitializer().isPresent());
+ }
+
+ @Test
+ public void parsingInitializedAndUnitializedVarsInForStmtComplexCase() {
+ // See issue 1281
+ ForStmt forStmt = JavaParser.parseStatement("for(int i, j = array2.length - 1;;){}").asForStmt();
+ assertEquals(1, forStmt.getInitialization().size());
+ assertEquals(true, 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());
+ assertEquals(false, forStmt.getInitialization().get(0).asVariableDeclarationExpr().getVariables().get(0).getInitializer().isPresent());
+ assertEquals(true, forStmt.getInitialization().get(0).asVariableDeclarationExpr().getVariables().get(1).getInitializer().isPresent());
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/JavaTokenTest.java b/javaparser-testing/src/test/java/com/github/javaparser/JavaTokenTest.java
new file mode 100644
index 000000000..e69a76ab0
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/JavaTokenTest.java
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser;
+
+import com.github.javaparser.ast.expr.Expression;
+import org.junit.Test;
+
+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.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+public class JavaTokenTest {
+
+ @Test
+ public void testAFewTokens() {
+ ParseResult<Expression> result = new JavaParser().parse(ParseStart.EXPRESSION, provider("1 +/*2*/1 "));
+ Iterator<JavaToken> 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());
+ assertEquals(false, 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
+ public 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
+ public void testKindEnum() {
+ JavaToken.Kind kind = JavaToken.Kind.valueOf(GeneratedJavaParserConstants.ASSERT);
+
+ assertEquals(JavaToken.Kind.ASSERT, kind);
+ assertEquals(GeneratedJavaParserConstants.ASSERT, kind.getKind());
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/JavadocParserTest.java b/javaparser-testing/src/test/java/com/github/javaparser/JavadocParserTest.java
new file mode 100644
index 000000000..99e138e21
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/JavadocParserTest.java
@@ -0,0 +1,168 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package 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.Assert;
+import org.junit.Test;
+
+import static com.github.javaparser.utils.Utils.EOL;
+import static org.junit.Assert.assertEquals;
+
+public class JavadocParserTest {
+
+ @Test
+ public void parseSimplestContent() {
+ Assert.assertEquals(new Javadoc(JavadocDescription.parseText("A simple line of text")),
+ JavadocParser.parse("A simple line of text"));
+ }
+
+ @Test
+ public 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
+ public void parseSingleLineWithNewLines() {
+ assertEquals(new Javadoc(JavadocDescription.parseText("The string image of the token.")),
+ JavadocParser.parse(EOL +
+ " * The string image of the token." + EOL +
+ " "));
+ }
+
+ @Test
+ public void parseCommentWithNewLines() {
+ String text = EOL +
+ " * The version identifier for this Serializable class." + EOL +
+ " * Increment only if the <i>serialized</i> form of the" + EOL +
+ " * class changes." + EOL +
+ " ";
+ assertEquals(new Javadoc(JavadocDescription.parseText("The version identifier for this Serializable class." + EOL +
+ "Increment only if the <i>serialized</i> form of the" + EOL +
+ "class changes.")),
+ JavadocParser.parse(text));
+ }
+
+ @Test
+ public void parseCommentWithIndentation() {
+ String text = "Returns a new Token object, by default." + EOL +
+ " * However, if you want, you can create and return subclass objects based on the value of ofKind." + EOL +
+ " *" + EOL +
+ " * case MyParserConstants.ID : return new IDToken(ofKind, image);" + EOL +
+ " *" + EOL +
+ " * to the following switch statement. Then you can cast matchedToken";
+ assertEquals(new Javadoc(JavadocDescription.parseText("Returns a new Token object, by default." + EOL +
+ "However, if you want, you can create and return subclass objects based on the value of ofKind." + EOL +
+ EOL +
+ " case MyParserConstants.ID : return new IDToken(ofKind, image);" + EOL +
+ EOL +
+ "to the following switch statement. Then you can cast matchedToken")),
+ JavadocParser.parse(text));
+ }
+
+ @Test
+ public void parseBlockTagsAndEmptyDescription() {
+ String text = EOL +
+ " * @deprecated" + EOL +
+ " * @see #getEndColumn" + EOL +
+ " ";
+ assertEquals(new Javadoc(JavadocDescription.parseText(""))
+ .addBlockTag(new JavadocBlockTag(JavadocBlockTag.Type.DEPRECATED, ""))
+ .addBlockTag(new JavadocBlockTag(JavadocBlockTag.Type.SEE, "#getEndColumn")), JavadocParser.parse(text));
+ }
+
+ @Test
+ public void parseBlockTagsAndProvideTagName() {
+ String expectedText = EOL +
+ " * @unofficial" + 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
+ public void parseParamBlockTags() {
+ String text = EOL +
+ " * Add a field to this and automatically add the import of the type if needed" + EOL +
+ " *" + EOL +
+ " * @param typeClass the type of the field" + EOL +
+ " * @param name the name of the field" + EOL +
+ " * @param modifiers the modifiers like {@link Modifier#PUBLIC}" + EOL +
+ " * @return the {@link FieldDeclaration} created" + 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
+ public void parseMultilineParamBlockTags() {
+ String text = EOL +
+ " * Add a field to this and automatically add the import of the type if needed" + EOL +
+ " *" + EOL +
+ " * @param typeClass the type of the field" + EOL +
+ " * continued in a second line" + EOL +
+ " * @param name the name of the field" + EOL +
+ " * @param modifiers the modifiers like {@link Modifier#PUBLIC}" + EOL +
+ " * @return the {@link FieldDeclaration} created" + 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" + 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
+ public void startsWithAsteriskEmpty() {
+ assertEquals(-1, JavadocParser.startsWithAsterisk(""));
+ }
+
+ @Test
+ public void startsWithAsteriskNoAsterisk() {
+ assertEquals(-1, JavadocParser.startsWithAsterisk(" ciao"));
+ }
+
+ @Test
+ public void startsWithAsteriskAtTheBeginning() {
+ assertEquals(0, JavadocParser.startsWithAsterisk("* ciao"));
+ }
+
+ @Test
+ public void startsWithAsteriskAfterSpaces() {
+ assertEquals(3, JavadocParser.startsWithAsterisk(" * ciao"));
+ }
+
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ParseErrorRecoveryTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ParseErrorRecoveryTest.java
new file mode 100644
index 000000000..b41c28bf4
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ParseErrorRecoveryTest.java
@@ -0,0 +1,42 @@
+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 org.junit.Test;
+
+import static com.github.javaparser.Providers.provider;
+import static com.github.javaparser.ast.Node.Parsedness.UNPARSABLE;
+import static org.junit.Assert.assertEquals;
+
+public class ParseErrorRecoveryTest {
+ private final JavaParser parser = new JavaParser();
+
+ @Test
+ public void compilationUnitRecovery() {
+ CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, provider("XXX")).getResult().get();
+ assertEquals(UNPARSABLE, cu.getParsed());
+ }
+
+ @Test
+ public 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
+ public void bodystatementClosingBraceRecovery() {
+ MethodDeclaration cu = parser.parse(ParseStart.CLASS_BODY, provider("int x(){X X X}")).getResult().get().asMethodDeclaration();
+ Statement xxx = cu.getBody().get();
+ assertEquals(UNPARSABLE, xxx.getParsed());
+ }
+
+ @Test
+ public 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());
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ParserConfigurationTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ParserConfigurationTest.java
new file mode 100644
index 000000000..abc400912
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ParserConfigurationTest.java
@@ -0,0 +1,33 @@
+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.Test;
+
+import static com.github.javaparser.ParseStart.STATEMENT;
+import static com.github.javaparser.ParserConfiguration.LanguageLevel.*;
+import static com.github.javaparser.Providers.provider;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+public class ParserConfigurationTest {
+ @Test
+ public void storeNoTokens() {
+ ParseResult<CompilationUnit> 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
+ public void noProblemsHere() {
+ ParseResult<Statement> result =
+ new JavaParser(new ParserConfiguration().setLanguageLevel(RAW))
+ .parse(STATEMENT, provider("try{}"));
+ assertEquals(true, result.isSuccessful());
+ }
+
+
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ProblemTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ProblemTest.java
new file mode 100644
index 000000000..0654344ba
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ProblemTest.java
@@ -0,0 +1,32 @@
+package com.github.javaparser;
+
+import org.junit.Test;
+
+import static com.github.javaparser.Range.range;
+import static com.github.javaparser.utils.TestUtils.assertInstanceOf;
+import static org.junit.Assert.assertEquals;
+
+public class ProblemTest {
+ @Test
+ public 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
+ public void testVerboseMessage() {
+ Problem problem = new Problem("Parse error", TokenRange.INVALID, null);
+
+ assertEquals("(line ?,col ?) Parse error", problem.getVerboseMessage());
+ }
+
+ @Test
+ public void testVerboseMessageWithoutLocation() {
+ Problem problem = new Problem("Parse error", null, null);
+
+ assertEquals("Parse error", problem.getVerboseMessage());
+ }
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ProvidersTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ProvidersTest.java
new file mode 100644
index 000000000..14b351af9
--- /dev/null
+++ b/javaparser-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-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser;
+
+import com.github.javaparser.ast.CompilationUnit;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.nio.charset.Charset;
+
+import static org.junit.Assert.*;
+
+public class ProvidersTest {
+
+ @Test
+ public void testResourceProvider() throws IOException {
+ Provider provider = Providers.resourceProvider("com/github/javaparser/issue_samples/Issue290.java.txt");
+ assertNotNull(provider);
+ JavaParser parser = new JavaParser();
+ ParseResult<CompilationUnit> parse = parser.parse(ParseStart.COMPILATION_UNIT, provider);
+ assertTrue(parse.isSuccessful());
+ }
+
+ @Test
+ public void testResourceProviderWithWrongEncoding() throws IOException {
+ Provider provider = Providers.resourceProvider("com/github/javaparser/TestFileIso88591.java");
+ assertNotNull(provider);
+ JavaParser parser = new JavaParser();
+ ParseResult<CompilationUnit> parse = parser.parse(ParseStart.COMPILATION_UNIT, provider);
+ assertFalse(parse.isSuccessful());
+ }
+
+ @Test
+ public 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<CompilationUnit> parse = parser.parse(ParseStart.COMPILATION_UNIT, provider);
+ assertTrue(parse.isSuccessful());
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/RangeTest.java b/javaparser-testing/src/test/java/com/github/javaparser/RangeTest.java
new file mode 100644
index 000000000..1d2b49ade
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/RangeTest.java
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser;
+
+import org.junit.Test;
+
+import java.io.IOException;
+
+import static org.junit.Assert.assertEquals;
+
+public class RangeTest {
+
+ @Test
+ public void aRangeContainsItself() throws IOException {
+ Range r = Range.range(1, 1, 3, 10);
+ assertEquals(true, r.contains(r));
+ }
+
+ @Test
+ public void aRangeDoesNotStrictlyContainsItself() throws IOException {
+ Range r = Range.range(1, 1, 3, 10);
+ assertEquals(false, r.strictlyContains(r));
+ }
+
+ @Test
+ public void overlappingButNotContainedRangesAreNotOnContains() throws IOException {
+ Range r1 = Range.range(1, 1, 3, 10);
+ Range r2 = Range.range(2, 1, 7, 10);
+ assertEquals(false, r1.contains(r2));
+ assertEquals(false, r2.contains(r1));
+ }
+
+ @Test
+ public void overlappingButNotContainedRangesAreNotOnStrictlyContains() throws IOException {
+ Range r1 = Range.range(1, 1, 3, 10);
+ Range r2 = Range.range(2, 1, 7, 10);
+ assertEquals(false, r1.strictlyContains(r2));
+ assertEquals(false, r2.strictlyContains(r1));
+ }
+
+ @Test
+ public void unrelatedRangesAreNotOnContains() throws IOException {
+ Range r1 = Range.range(1, 1, 3, 10);
+ Range r2 = Range.range(5, 1, 7, 10);
+ assertEquals(false, r1.contains(r2));
+ assertEquals(false, r2.contains(r1));
+ }
+
+ @Test
+ public void unrelatedRangesAreNotOnStrictlyContains() throws IOException {
+ Range r1 = Range.range(1, 1, 3, 10);
+ Range r2 = Range.range(5, 1, 7, 10);
+ assertEquals(false, r1.strictlyContains(r2));
+ assertEquals(false, r2.strictlyContains(r1));
+ }
+
+ @Test
+ public void strictlyContainedRangesOnContains() throws IOException {
+ Range r1 = Range.range(1, 1, 3, 10);
+ Range r2 = Range.range(2, 1, 3, 4);
+ assertEquals(true, r1.contains(r2));
+ assertEquals(false, r2.contains(r1));
+ }
+
+ @Test
+ public void strictlyContainedRangesOnStrictlyContains() throws IOException {
+ Range r1 = Range.range(1, 1, 3, 10);
+ Range r2 = Range.range(2, 1, 3, 4);
+ assertEquals(true, r1.strictlyContains(r2));
+ assertEquals(false, r2.strictlyContains(r1));
+ }
+
+ @Test
+ public void containsConsiderLines() {
+ Range r1 = Range.range(22, 9, 22, 29);
+ Range r2 = Range.range(26, 19, 26, 28);
+ assertEquals(false, r1.contains(r2));
+ assertEquals(false, r2.contains(r1));
+ }
+
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/TokenRangeTest.java b/javaparser-testing/src/test/java/com/github/javaparser/TokenRangeTest.java
new file mode 100644
index 000000000..d067c8e1f
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/TokenRangeTest.java
@@ -0,0 +1,14 @@
+package com.github.javaparser;
+
+import com.github.javaparser.ast.CompilationUnit;
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+
+public class TokenRangeTest {
+ @Test
+ public void toStringWorks() {
+ CompilationUnit cu = JavaParser.parse("class X {\n\tX(){\n// hello\n}\n}");
+ assertEquals("X(){\n// hello\n}", cu.getClassByName("X").get().getDefaultConstructor().get().getTokenRange().get().toString());
+ }
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/CompilationUnitTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/CompilationUnitTest.java
new file mode 100644
index 000000000..ec17e39b7
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/CompilationUnitTest.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.ast;
+
+import com.github.javaparser.JavaParser;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+import static com.github.javaparser.JavaParser.parse;
+import static com.github.javaparser.utils.CodeGenerationUtils.mavenModuleRoot;
+import static org.junit.Assert.assertEquals;
+
+public class CompilationUnitTest {
+ @Test
+ public 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
+ public 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(expected = RuntimeException.class)
+ public void testGetSourceRootWithBadPackageDeclaration() throws IOException {
+ 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
+ public 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
+ public 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 = JavaParser.parse(testFile);
+
+ assertEquals("PrimaryType", cu.getPrimaryTypeName().get());
+ }
+
+ @Test
+ public void testNoPrimaryTypeName() {
+ CompilationUnit cu = JavaParser.parse("class PrimaryType{}");
+
+ assertEquals(false, cu.getPrimaryTypeName().isPresent());
+ }
+ @Test
+ public 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 = JavaParser.parse(testFile);
+
+ assertEquals("PrimaryType", cu.getPrimaryType().get().getNameAsString());
+ }
+
+ @Test
+ public 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 = JavaParser.parse(testFile);
+
+ assertEquals(false, cu.getPrimaryType().isPresent());
+ }
+
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/DataKeyTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/DataKeyTest.java
new file mode 100644
index 000000000..91163650a
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/DataKeyTest.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.ast;
+
+import com.github.javaparser.ast.expr.SimpleName;
+import org.junit.Test;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
+
+public class DataKeyTest {
+ public static final DataKey<String> ABC = new DataKey<String>() {
+ };
+ public static final DataKey<List<String>> LISTY = new DataKey<List<String>>() {
+ };
+ public static final DataKey<List<String>> DING = new DataKey<List<String>>() {
+ };
+
+ @Test
+ public 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.getData(DING)).isNull();
+ }
+
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/NodeListTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/NodeListTest.java
new file mode 100644
index 000000000..8e4d568bd
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/NodeListTest.java
@@ -0,0 +1,329 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.ast;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
+import com.github.javaparser.ast.body.FieldDeclaration;
+import com.github.javaparser.ast.expr.Name;
+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.Test;
+
+import java.util.Arrays;
+import java.util.EnumSet;
+import java.util.LinkedList;
+import java.util.List;
+
+import static com.github.javaparser.ast.NodeList.nodeList;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+public class NodeListTest {
+
+ private AstObserver createObserver(List<String> 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));
+ }
+ };
+ }
+
+ private FieldDeclaration createIntField(String name) {
+ return new FieldDeclaration(EnumSet.noneOf(Modifier.class), PrimitiveType.intType(), name);
+ }
+
+ @Test
+ public void addAllWithoutIndex() {
+ List<String> changes = new LinkedList<>();
+ String code = "class A { void foo(int p) { }}";
+ CompilationUnit cu = JavaParser.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
+ public void addAllWithIndex() {
+ List<String> changes = new LinkedList<>();
+ String code = "class A { void foo(int p) { }}";
+ CompilationUnit cu = JavaParser.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
+ public void clear() {
+ List<String> changes = new LinkedList<>();
+ String code = "class A { int a; int b; int c; }";
+ CompilationUnit cu = JavaParser.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
+ public void set() {
+ List<String> changes = new LinkedList<>();
+ String code = "class A { int a; int b; int c; }";
+ CompilationUnit cu = JavaParser.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
+ public void removeNode() {
+ List<String> changes = new LinkedList<>();
+ String code = "class A { int a; int b; int c; int d; int e; }";
+ CompilationUnit cu = JavaParser.parse(code);
+ ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get();
+ cd.getMembers().register(createObserver(changes));
+
+ cd.getMembers().remove(cd.getFieldByName("c").get());
+ assertEquals(Arrays.asList("'int c;' REMOVAL in list at 2"), changes);
+ }
+
+ @Test
+ public void removeFirstNode() {
+ List<String> changes = new LinkedList<>();
+ String code = "class A { int a; int b; int c; int d; int e; }";
+ CompilationUnit cu = JavaParser.parse(code);
+ ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get();
+ cd.getMembers().register(createObserver(changes));
+
+ cd.getMembers().removeFirst();
+ assertEquals(Arrays.asList("'int a;' REMOVAL in list at 0"), changes);
+ assertEquals(cd.getMembers().size(), 4);
+
+ for (int i = 3; i >= 0; i--) {
+ assertTrue(cd.getMembers().removeFirst() != null);
+ assertEquals(cd.getMembers().size(), i);
+ }
+
+ assertEquals(cd.getMembers().size(), 0);
+ }
+
+ @Test
+ public void removeLastNode() {
+ List<String> changes = new LinkedList<>();
+ String code = "class A { int a; int b; int c; int d; int e; }";
+ CompilationUnit cu = JavaParser.parse(code);
+ ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get();
+ cd.getMembers().register(createObserver(changes));
+
+ cd.getMembers().removeLast();
+ assertEquals(Arrays.asList("'int e;' REMOVAL in list at 4"), changes);
+ assertEquals(cd.getMembers().size(), 4);
+
+ for (int i = 3; i >= 0; i--) {
+ assertTrue(cd.getMembers().removeLast() != null);
+ assertEquals(cd.getMembers().size(), i);
+ }
+
+ assertEquals(cd.getMembers().size(), 0);
+ }
+
+ @Test
+ public void removeObject() {
+ List<String> changes = new LinkedList<>();
+ String code = "class A { int a; int b; int c; int d; int e; }";
+ CompilationUnit cu = JavaParser.parse(code);
+ ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get();
+ cd.getMembers().register(createObserver(changes));
+
+ cd.getMembers().remove("hi");
+ assertEquals(Arrays.asList(), changes);
+ }
+
+ @Test
+ public void removeAll() {
+ List<String> changes = new LinkedList<>();
+ String code = "class A { int a; int b; int c; int d; int e; }";
+ CompilationUnit cu = JavaParser.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()));
+ assertEquals(Arrays.asList("'int b;' REMOVAL in list at 1",
+ "'int d;' REMOVAL in list at 2"), changes);
+ }
+
+ @Test
+ public void retainAll() {
+ List<String> changes = new LinkedList<>();
+ String code = "class A { int a; int b; int c; int d; int e; }";
+ CompilationUnit cu = JavaParser.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()));
+ assertEquals(Arrays.asList("'int a;' REMOVAL in list at 0",
+ "'int c;' REMOVAL in list at 1",
+ "'int e;' REMOVAL in list at 2"), changes);
+ }
+
+ @Test
+ public void replaceAll() {
+ List<String> changes = new LinkedList<>();
+ String code = "class A { int a; int b; int c; }";
+ CompilationUnit cu = JavaParser.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;
+ });
+ assertEquals(Arrays.asList("'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"), changes);
+ }
+
+ @Test
+ public void removeIf() {
+ List<String> changes = new LinkedList<>();
+ String code = "class A { int a; int longName; int c; }";
+ CompilationUnit cu = JavaParser.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);
+ assertEquals(Arrays.asList("'int longName;' REMOVAL in list at 1"), changes);
+ }
+
+ @Test
+ public void replace() {
+ final NodeList<Name> list = nodeList(new Name("a"), new Name("b"), new Name("c"));
+
+ final boolean replaced = list.replace(new Name("b"), new Name("z"));
+
+ assertEquals(true, replaced);
+ assertEquals(3, list.size());
+ assertEquals("a", list.get(0).asString());
+ assertEquals("z", list.get(1).asString());
+ assertEquals("c", list.get(2).asString());
+ }
+
+ @Test
+ public void toStringTest() {
+ final NodeList<Name> list = nodeList(new Name("abc"), new Name("bcd"), new Name("cde"));
+
+ assertEquals("[abc, bcd, cde]", list.toString());
+ }
+
+ @Test
+ public void addFirst() {
+ final NodeList<Name> list = nodeList(new Name("abc"), new Name("bcd"), new Name("cde"));
+
+ list.addFirst(new Name("xxx"));
+
+ assertEquals("[xxx, abc, bcd, cde]", list.toString());
+ }
+
+ @Test
+ public void addLast() {
+ final NodeList<Name> list = nodeList(new Name("abc"), new Name("bcd"), new Name("cde"));
+
+ list.addLast(new Name("xxx"));
+
+ assertEquals("[abc, bcd, cde, xxx]", list.toString());
+ }
+
+ @Test
+ public void addBefore() {
+ Name n = new Name("bcd");
+ final NodeList<Name> list = nodeList(new Name("abc"), n, new Name("cde"));
+
+ list.addBefore(new Name("xxx"), n);
+
+ assertEquals("[abc, xxx, bcd, cde]", list.toString());
+ }
+
+ @Test
+ public void addAfter() {
+ Name n = new Name("bcd");
+ final NodeList<Name> list = nodeList(new Name("abc"), n, new Name("cde"));
+
+ list.addAfter(new Name("xxx"), n);
+
+ assertEquals("[abc, bcd, xxx, cde]", list.toString());
+ }
+
+ @Test
+ public void addBeforeFirst() {
+ Name abc = new Name("abc");
+ final NodeList<Name> list = nodeList(abc, new Name("bcd"), new Name("cde"));
+
+ list.addBefore(new Name("xxx"), abc);
+
+ assertEquals("[xxx, abc, bcd, cde]", list.toString());
+ }
+
+ @Test
+ public void addAfterLast() {
+ Name cde = new Name("cde");
+ final NodeList<Name> list = nodeList(new Name("abc"), new Name("bcd"), cde);
+
+ list.addAfter(new Name("xxx"), cde);
+
+ assertEquals("[abc, bcd, cde, xxx]", list.toString());
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/NodePositionTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/NodePositionTest.java
new file mode 100644
index 000000000..5ce116de6
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/NodePositionTest.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.ast;
+
+import com.github.javaparser.*;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.util.LinkedList;
+import java.util.List;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+public class NodePositionTest {
+
+ private List<Node> getAllNodes(Node node) {
+ List<Node> nodes = new LinkedList<>();
+ nodes.add(node);
+ node.getChildNodes().forEach(c -> nodes.addAll(getAllNodes(c)));
+ return nodes;
+ }
+
+ @Test
+ public void packageProtectedClassShouldHavePositionSet() throws IOException {
+ ensureAllNodesHaveValidBeginPosition("class A { }");
+ }
+
+ @Test
+ public void packageProtectedInterfaceShouldHavePositionSet() throws IOException {
+ ensureAllNodesHaveValidBeginPosition("interface A { }");
+ }
+
+ @Test
+ public void packageProtectedEnumShouldHavePositionSet() throws IOException {
+ ensureAllNodesHaveValidBeginPosition("enum A { }");
+ }
+
+ @Test
+ public void packageProtectedAnnotationShouldHavePositionSet() throws IOException {
+ ensureAllNodesHaveValidBeginPosition("@interface A { }");
+ }
+
+ @Test
+ public void packageProtectedFieldShouldHavePositionSet() throws IOException {
+ ensureAllNodesHaveValidBeginPosition("public class A { int i; }");
+ }
+
+ @Test
+ public void packageProtectedMethodShouldHavePositionSet() throws IOException {
+ ensureAllNodesHaveValidBeginPosition("public class A { void foo() {} }");
+ }
+
+ @Test
+ public void packageProtectedConstructorShouldHavePositionSet() throws IOException {
+ ensureAllNodesHaveValidBeginPosition("public class A { A() {} }");
+ }
+
+ private void ensureAllNodesHaveValidBeginPosition(final String code) throws IOException {
+ ParseResult<CompilationUnit> res = new JavaParser().parse(ParseStart.COMPILATION_UNIT, Providers.provider(code));
+ assertTrue(res.getProblems().isEmpty());
+
+ CompilationUnit cu = res.getResult().get();
+ getAllNodes(cu).forEach(n -> {
+ assertNotNull(String.format("There should be no node without a range: %s (class: %s)",
+ n, n.getClass().getCanonicalName()), n.getRange());
+ 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-testing/src/test/java/com/github/javaparser/ast/NodeTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/NodeTest.java
new file mode 100644
index 000000000..3201b2910
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/NodeTest.java
@@ -0,0 +1,414 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package 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.expr.Expression;
+import com.github.javaparser.ast.expr.IntegerLiteralExpr;
+import com.github.javaparser.ast.expr.SimpleName;
+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.Test;
+
+import java.util.*;
+import java.util.stream.Collectors;
+
+import static com.github.javaparser.JavaParser.parse;
+import static com.github.javaparser.JavaParser.parseExpression;
+import static com.github.javaparser.utils.Utils.EOL;
+import static org.junit.Assert.*;
+
+public class NodeTest {
+
+ @Test
+ public void registerSubTree() {
+ String code = "class A { int f; void foo(int p) { return 'z'; }}";
+ CompilationUnit cu = parse(code);
+ List<String> 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);
+
+ assertEquals(Arrays.asList(), changes);
+
+ cu.getClassByName("A").get().setName("MyCoolClass");
+ assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass"), changes);
+
+ cu.getClassByName("MyCoolClass").get().getFieldByName("f").get().getVariable(0).setType(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN));
+ assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass",
+ "FieldDeclaration.maximum_common_type changed from int to boolean",
+ "VariableDeclarator.type changed from int to boolean"), changes);
+
+ cu.getClassByName("MyCoolClass").get().getMethodsByName("foo").get(0).getParameterByName("p").get().setName("myParam");
+ assertEquals(Arrays.asList("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"), changes);
+ }
+
+ @Test
+ public void registerWithJustNodeMode() {
+ String code = "class A { int f; void foo(int p) { return 'z'; }}";
+ CompilationUnit cu = parse(code);
+ List<String> 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);
+
+ assertEquals(Arrays.asList(), changes);
+
+ cu.getClassByName("A").get().setName("MyCoolClass");
+ assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass"), changes);
+
+ cu.getClassByName("MyCoolClass").get().getFieldByName("f").get().getVariable(0).setType(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN));
+ assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass"), changes);
+
+ cu.getClassByName("MyCoolClass").get().getMethodsByName("foo").get(0).getParameterByName("p").get().setName("myParam");
+ assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass"), changes);
+
+ cu.getClassByName("MyCoolClass").get().addField("int", "bar").getVariables().get(0).setInitializer("0");
+ assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass"), changes);
+ }
+
+ @Test
+ public void registerWithNodeAndExistingDescendantsMode() {
+ String code = "class A { int f; void foo(int p) { return 'z'; }}";
+ CompilationUnit cu = parse(code);
+ List<String> 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);
+
+ assertEquals(Arrays.asList(), changes);
+
+ cu.getClassByName("A").get().setName("MyCoolClass");
+ assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass"), changes);
+
+ cu.getClassByName("MyCoolClass").get().getFieldByName("f").get().getVariable(0).setType(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN));
+ assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass",
+ "FieldDeclaration.maximum_common_type changed from int to boolean",
+ "VariableDeclarator.type changed from int to boolean"), changes);
+
+ cu.getClassByName("MyCoolClass").get().getMethodsByName("foo").get(0).getParameterByName("p").get().setName("myParam");
+ assertEquals(Arrays.asList("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"), changes);
+
+ cu.getClassByName("MyCoolClass").get().addField("int", "bar").getVariables().get(0).setInitializer("0");
+ assertEquals(Arrays.asList("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"), changes);
+ }
+
+ @Test
+ public void registerWithSelfPropagatingMode() {
+ String code = "class A { int f; void foo(int p) { return 'z'; }}";
+ CompilationUnit cu = parse(code);
+ List<String> 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);
+
+ assertEquals(Arrays.asList(), changes);
+
+ cu.getClassByName("A").get().setName("MyCoolClass");
+ assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass"), changes);
+
+ cu.getClassByName("MyCoolClass").get().getFieldByName("f").get().getVariable(0).setType(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN));
+ assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass",
+ "FieldDeclaration.maximum_common_type changed from int to boolean",
+ "VariableDeclarator.type changed from int to boolean"), changes);
+
+ cu.getClassByName("MyCoolClass").get().getMethodsByName("foo").get(0).getParameterByName("p").get().setName("myParam");
+ assertEquals(Arrays.asList("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"), changes);
+
+ cu.getClassByName("MyCoolClass").get()
+ .addField("int", "bar")
+ .getVariables().get(0).setInitializer("0");
+ assertEquals(Arrays.asList("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"), changes);
+ }
+
+ @Test
+ public void deleteAParameterTriggerNotifications() {
+ String code = "class A { void foo(int p) { }}";
+ CompilationUnit cu = parse(code);
+ List<String> 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();
+ assertEquals(Arrays.asList("removing [int p] from index 0"), changes);
+ }
+
+ @Test
+ public void deleteClassNameDoesNotTriggerNotifications() {
+ String code = "class A { void foo(int p) { }}";
+ CompilationUnit cu = parse(code);
+ List<String> 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
+ assertEquals(false, cu.getClassByName("A").get().getName().remove());
+ assertEquals(Arrays.asList(), changes);
+ }
+
+ @Test
+ public void deleteMethodBodyDoesTriggerNotifications() {
+ String code = "class A { void foo(int p) { }}";
+ CompilationUnit cu = parse(code);
+ List<String> 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);
+
+ assertEquals(true, cu.getClassByName("A").get().getMethodsByName("foo").get(0).getBody().get().remove());
+ assertEquals(Arrays.asList("setting [BODY] to null"), changes);
+ }
+
+ @Test
+ public void removeOrphanCommentPositiveCase() {
+ ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class), false, "A");
+ Comment c = new LineComment("A comment");
+ decl.addOrphanComment(c);
+ assertEquals(1, decl.getOrphanComments().size());
+ assertTrue(decl == c.getParentNode().get());
+ assertTrue(decl.removeOrphanComment(c));
+ assertEquals(0, decl.getOrphanComments().size());
+ assertFalse(c.getParentNode().isPresent());
+ }
+
+ @Test
+ public void removeOrphanCommentNegativeCase() {
+ ClassOrInterfaceDeclaration aClass = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class), false, "A");
+ FieldDeclaration aField = new FieldDeclaration(EnumSet.noneOf(Modifier.class), 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
+ public void hasJavaDocCommentPositiveCaseWithSetJavaDocComment() {
+ ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class),
+ false, "Foo");
+ decl.setJavadocComment("A comment");
+ assertEquals(true, decl.hasJavaDocComment());
+ }
+
+ @Test
+ public void hasJavaDocCommentPositiveCaseWithSetComment() {
+ ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class),
+ false, "Foo");
+ decl.setComment(new JavadocComment("A comment"));
+ assertEquals(true, decl.hasJavaDocComment());
+ }
+
+ @Test
+ public void hasJavaDocCommentNegativeCaseNoComment() {
+ ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class),
+ false, "Foo");
+ assertEquals(false, decl.hasJavaDocComment());
+ }
+
+ @Test
+ public void hasJavaDocCommentNegativeCaseLineComment() {
+ ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class),
+ false, "Foo");
+ decl.setComment(new LineComment("foo"));
+ assertEquals(false, decl.hasJavaDocComment());
+ }
+
+ @Test
+ public void hasJavaDocCommentNegativeCaseBlockComment() {
+ ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class),
+ false, "Foo");
+ decl.setComment(new BlockComment("foo"));
+ assertEquals(false, decl.hasJavaDocComment());
+ }
+
+ @Test
+ public 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", EOL), cu.toString());
+ }
+
+ @Test
+ public 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", EOL));
+ // remove the second swapped=false
+ Node target = unit.getChildNodes().get(0).getChildNodes().get(1).getChildNodes().get(2).getChildNodes().get(2);
+ target.remove();
+ // This will throw an exception if the parents are bad.
+ System.out.println(unit.toString());
+ }
+
+ @Test
+ public 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
+ public 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.findParent(FieldDeclaration.class).get().toString());
+ }
+
+ @Test
+ public void cantFindCompilationUnit() {
+ VariableDeclarator x = new VariableDeclarator();
+ assertFalse(x.findCompilationUnit().isPresent());
+ }
+
+ @Test
+ public void genericWalk() {
+ Expression e = parseExpression("1+1");
+ StringBuilder b = new StringBuilder();
+ e.walk(n -> b.append(n.toString()));
+ assertEquals("1 + 111", b.toString());
+ }
+
+ @Test
+ public 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
+ public void conditionalFindAll() {
+ Expression e = parseExpression("1+2+3");
+ List<IntegerLiteralExpr> ints = e.findAll(IntegerLiteralExpr.class, n -> n.asInt() > 1);
+ assertEquals("[2, 3]", ints.toString());
+ }
+
+ @Test
+ public void typeOnlyFindAll() {
+ Expression e = parseExpression("1+2+3");
+ List<IntegerLiteralExpr> ints = e.findAll(IntegerLiteralExpr.class);
+ assertEquals("[1, 2, 3]", ints.toString());
+ }
+
+ @Test
+ public void typeOnlyFindAllMatchesSubclasses() {
+ Expression e = parseExpression("1+2+3");
+ List<Node> ints = e.findAll(Node.class);
+ assertEquals("[1 + 2 + 3, 1 + 2, 1, 2, 3]", ints.toString());
+ }
+
+ @Test
+ public void conditionalTypedFindFirst() {
+ Expression e = parseExpression("1+2+3");
+ Optional<IntegerLiteralExpr> ints = e.findFirst(IntegerLiteralExpr.class, n -> n.asInt() > 1);
+ assertEquals("Optional[2]", ints.toString());
+ }
+
+ @Test
+ public void typeOnlyFindFirst() {
+ Expression e = parseExpression("1+2+3");
+ Optional<IntegerLiteralExpr> ints = e.findFirst(IntegerLiteralExpr.class);
+ assertEquals("Optional[1]", ints.toString());
+ }
+
+ @Test
+ public void stream() {
+ Expression e = parseExpression("1+2+3");
+ List<IntegerLiteralExpr> 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-testing/src/test/java/com/github/javaparser/ast/ParseResultTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/ParseResultTest.java
new file mode 100644
index 000000000..45d7725bc
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/ParseResultTest.java
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.ast;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.ParseResult;
+import com.github.javaparser.ParserConfiguration;
+import com.github.javaparser.Problem;
+import org.junit.Test;
+
+import static com.github.javaparser.ParseStart.COMPILATION_UNIT;
+import static com.github.javaparser.Providers.provider;
+import static com.github.javaparser.ast.Node.Parsedness.PARSED;
+import static com.github.javaparser.ast.Node.Parsedness.UNPARSABLE;
+import static com.github.javaparser.utils.Utils.EOL;
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class ParseResultTest {
+ private final JavaParser javaParser = new JavaParser(new ParserConfiguration());
+
+ @Test
+ public void whenParsingSucceedsThenWeGetResultsAndNoProblems() {
+ ParseResult<CompilationUnit> 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.getTokens().isPresent()).isTrue();
+
+ assertThat(result.toString()).isEqualTo("Parsing successful");
+ }
+
+ @Test
+ public void whenParsingFailsThenWeGetProblemsAndABadResult() {
+ ParseResult<CompilationUnit> 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\" \"provides\" \"requires\" \"strictfp\" \"to\" \"transitive\" \"uses\" \"with\" <IDENTIFIER>");
+ assertThat(result.getTokens().isPresent()).isTrue();
+
+ assertThat(result.toString()).startsWith("Parsing failed:" + EOL + "(line 1,col 1) Parse error.");
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/ReplaceNodeTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/ReplaceNodeTest.java
new file mode 100644
index 000000000..4e93efce6
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/ReplaceNodeTest.java
@@ -0,0 +1,32 @@
+package com.github.javaparser.ast;
+
+import org.junit.Test;
+
+import static com.github.javaparser.JavaParser.parse;
+import static com.github.javaparser.JavaParser.parsePackageDeclaration;
+import static com.github.javaparser.utils.Utils.EOL;
+import static org.junit.Assert.assertEquals;
+
+public class ReplaceNodeTest {
+ @Test
+ public 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", EOL), cu.toString());
+ }
+
+ @Test
+ public 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", EOL), cu.toString());
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/body/AnnotationMemberDeclarationTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/body/AnnotationMemberDeclarationTest.java
new file mode 100644
index 000000000..e133b501b
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/body/AnnotationMemberDeclarationTest.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package 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.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+public class AnnotationMemberDeclarationTest {
+
+ @Test
+ public void whenSettingNameTheParentOfNameIsAssigned() {
+ AnnotationMemberDeclaration decl = new AnnotationMemberDeclaration();
+ SimpleName name = new SimpleName("foo");
+ decl.setName(name);
+ assertTrue(name.getParentNode().isPresent());
+ assertTrue(decl == name.getParentNode().get());
+ }
+
+ @Test
+ public void removeDefaultValueWhenNoDefaultValueIsPresent() {
+ AnnotationMemberDeclaration decl = new AnnotationMemberDeclaration();
+ SimpleName name = new SimpleName("foo");
+ decl.setName(name);
+
+ decl.removeDefaultValue();
+
+ assertFalse(decl.getDefaultValue().isPresent());
+ }
+
+ @Test
+ public 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-testing/src/test/java/com/github/javaparser/ast/body/ClassOrInterfaceDeclarationTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/body/ClassOrInterfaceDeclarationTest.java
new file mode 100644
index 000000000..52c77f13c
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/body/ClassOrInterfaceDeclarationTest.java
@@ -0,0 +1,60 @@
+package com.github.javaparser.ast.body;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.ast.CompilationUnit;
+import org.junit.Test;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+public class ClassOrInterfaceDeclarationTest {
+ @Test
+ public void staticNestedClass() {
+ CompilationUnit cu = JavaParser.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
+ public void nestedInterface() {
+ CompilationUnit cu = JavaParser.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
+ public void nonStaticNestedClass() {
+ CompilationUnit cu = JavaParser.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
+ public void topClass() {
+ CompilationUnit cu = JavaParser.parse("class X{}");
+ ClassOrInterfaceDeclaration y = cu.getClassByName("X").get();
+
+ assertFalse(y.isInnerClass());
+ assertFalse(y.isNestedType());
+ assertFalse(y.isLocalClassDeclaration());
+ }
+
+ @Test
+ public void localClass() {
+ MethodDeclaration method= (MethodDeclaration)JavaParser.parseBodyDeclaration("void x(){class X{};}");
+ ClassOrInterfaceDeclaration x = method.findFirst(ClassOrInterfaceDeclaration.class).get();
+
+ assertFalse(x.isInnerClass());
+ assertFalse(x.isNestedType());
+ assertTrue(x.isLocalClassDeclaration());
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/body/ConstructorDeclarationTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/body/ConstructorDeclarationTest.java
new file mode 100644
index 000000000..34d3b6254
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/body/ConstructorDeclarationTest.java
@@ -0,0 +1,23 @@
+package com.github.javaparser.ast.body;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.ParseResult;
+import org.junit.Test;
+
+import static com.github.javaparser.ParseStart.CLASS_BODY;
+import static com.github.javaparser.Providers.provider;
+import static com.github.javaparser.utils.TestUtils.assertProblems;
+import static com.github.javaparser.utils.Utils.EOL;
+import static org.junit.Assert.assertEquals;
+
+public class ConstructorDeclarationTest {
+ @Test
+ public void acceptsSuper() {
+ ConstructorDeclaration cons = new ConstructorDeclaration("Cons");
+ cons.createBody().addStatement("super();");
+
+ assertEquals(String.format("public Cons() {%1$s" +
+ " super();%1$s" +
+ "}", EOL), cons.toString());
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/body/FieldDeclarationTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/body/FieldDeclarationTest.java
new file mode 100644
index 000000000..0e263a481
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/body/FieldDeclarationTest.java
@@ -0,0 +1,24 @@
+package com.github.javaparser.ast.body;
+
+import com.github.javaparser.ast.CompilationUnit;
+import org.junit.Test;
+
+import static com.github.javaparser.JavaParser.parse;
+import static org.junit.Assert.assertEquals;
+
+public class FieldDeclarationTest {
+ @Test
+ public 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());
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/body/MethodDeclarationTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/body/MethodDeclarationTest.java
new file mode 100644
index 000000000..1cbab66ad
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/body/MethodDeclarationTest.java
@@ -0,0 +1,87 @@
+package com.github.javaparser.ast.body;
+
+import org.junit.Ignore;
+import org.junit.Test;
+
+import static com.github.javaparser.JavaParser.parseBodyDeclaration;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
+
+public class MethodDeclarationTest {
+ @Test
+ public void annotationsAllowedAfterGenericsAndBeforeReturnType() {
+ parseBodyDeclaration("public <T> @Abc String method() {return null;}");
+ }
+
+ @Test
+ public void annotationsAllowedBeforeGenerics() {
+ parseBodyDeclaration("public @Abc <T> String method() {return null;}");
+ }
+
+ @Test
+ public 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
+ public void explicitReceiverParameters2() {
+ MethodDeclaration method = parseBodyDeclaration("void x(A this) { }").asMethodDeclaration();
+ assertEquals("this", method.getReceiverParameter().get().getNameAsString());
+ }
+
+ @Test
+ public void explicitReceiverParameters3() {
+ MethodDeclaration method = parseBodyDeclaration("void x(A that) { }").asMethodDeclaration();
+ assertFalse(method.getReceiverParameter().isPresent());
+ }
+
+ @Test
+ public void signaturesEqual() {
+ MethodDeclaration method1 = parseBodyDeclaration("void x(String a) { }").asMethodDeclaration();
+ MethodDeclaration method2 = parseBodyDeclaration("int x(String z);").asMethodDeclaration();
+ assertEquals(method1.getSignature(), method2.getSignature());
+ }
+
+ @Test
+ public void signaturesEqualWhenGenericsDiffer() {
+ MethodDeclaration method1 = parseBodyDeclaration("void x(List<Long> a) { }").asMethodDeclaration();
+ MethodDeclaration method2 = parseBodyDeclaration("void x(List<Integer> a) { }").asMethodDeclaration();
+ assertEquals(method1.getSignature(), method2.getSignature());
+ }
+
+ @Test
+ public 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
+ public void signaturesDifferentName() {
+ MethodDeclaration method1 = parseBodyDeclaration("void x(String a) { }").asMethodDeclaration();
+ MethodDeclaration method2 = parseBodyDeclaration("int y(String z);").asMethodDeclaration();
+ assertNotEquals(method1.getSignature(), method2.getSignature());
+ }
+
+ @Test
+ public void signaturesDifferentTypes() {
+ MethodDeclaration method1 = parseBodyDeclaration("void x(String a) { }").asMethodDeclaration();
+ MethodDeclaration method2 = parseBodyDeclaration("int x(int z);").asMethodDeclaration();
+ assertNotEquals(method1.getSignature(), method2.getSignature());
+ }
+
+ @Test
+ public void signaturesDifferentVarargs() {
+ MethodDeclaration method1 = parseBodyDeclaration("int x(int z);").asMethodDeclaration();
+ MethodDeclaration method2 = parseBodyDeclaration("int x(int... z);").asMethodDeclaration();
+ assertNotEquals(method1.getSignature(), method2.getSignature());
+ }
+
+ @Test
+ public void signatureToString() {
+ MethodDeclaration method1 = parseBodyDeclaration("int x(int z, String q);").asMethodDeclaration();
+ assertEquals("x(int, String)", method1.getSignature().toString());
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/comments/CommentTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/comments/CommentTest.java
new file mode 100644
index 000000000..946b76ac1
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/comments/CommentTest.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.ast.comments;
+
+import com.github.javaparser.ast.CompilationUnit;
+import com.github.javaparser.ast.Modifier;
+import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
+import com.github.javaparser.ast.expr.Name;
+import org.junit.Test;
+
+import java.util.EnumSet;
+
+import static com.github.javaparser.JavaParser.parse;
+import static com.github.javaparser.JavaParser.parseName;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+public class CommentTest {
+
+ @Test
+ public void removeOrphanComment() {
+ ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class), 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
+ public void removeAssociatedComment() {
+ ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class), false, "A");
+ Comment c = new LineComment("A comment");
+ decl.setComment(c);
+ assertEquals(true, decl.getComment().isPresent());
+ assertTrue(c.remove());
+ assertEquals(false, decl.getComment().isPresent());
+ }
+
+ @Test
+ public void cannotRemoveCommentNotUsedAnywhere() {
+ Comment c = new LineComment("A comment");
+ assertFalse(c.remove());
+ }
+
+ @Test
+ public void unicodeEscapesArePreservedInComments() {
+ CompilationUnit cu = parse("// xxx\\u2122xxx");
+ Comment comment = cu.getAllContainedComments().get(0);
+ assertEquals(" xxx\\u2122xxx", comment.getContent());
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/AssignExprTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/AssignExprTest.java
new file mode 100644
index 000000000..55e87f5e5
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/AssignExprTest.java
@@ -0,0 +1,12 @@
+package com.github.javaparser.ast.expr;
+
+import org.junit.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+public class AssignExprTest {
+ @Test
+ public void convertOperator() {
+ assertEquals(BinaryExpr.Operator.PLUS, AssignExpr.Operator.PLUS.toBinaryOperator().get());
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/BinaryExprTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/BinaryExprTest.java
new file mode 100644
index 000000000..9975ef307
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/BinaryExprTest.java
@@ -0,0 +1,12 @@
+package com.github.javaparser.ast.expr;
+
+import org.junit.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+public class BinaryExprTest {
+ @Test
+ public void convertOperator() {
+ assertEquals(AssignExpr.Operator.PLUS, BinaryExpr.Operator.PLUS.toAssignOperator().get());
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/DoubleLiteralExprTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/DoubleLiteralExprTest.java
new file mode 100644
index 000000000..9c5464394
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/DoubleLiteralExprTest.java
@@ -0,0 +1,37 @@
+package com.github.javaparser.ast.expr;
+
+import org.junit.Test;
+
+import static com.github.javaparser.JavaParser.parseExpression;
+
+public class DoubleLiteralExprTest {
+ @Test
+ public void test1() {
+ float x = 0x0.00_00_02p-126f;
+ parseExpression("0x0.00_00_02p-126f");
+ }
+
+ @Test
+ public void test2() {
+ double x = 0x0.000_000_000_000_1p-1_022;
+ parseExpression("0x0.000_000_000_000_1p-1_022");
+ }
+
+ @Test
+ public void test3() {
+ double a = 0x1.p+1;
+ parseExpression("0x1.p+1");
+ }
+
+ @Test
+ public void test4() {
+ double a = 0x.0p0;
+ parseExpression("0x.0p0");
+ }
+
+ @Test
+ public void test5() {
+ double x = 0x0_0.0_0p-1_0;
+ parseExpression("0x0_0.0_0p-1_0");
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/InstanceOfExprTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/InstanceOfExprTest.java
new file mode 100644
index 000000000..0d8a5b9a7
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/InstanceOfExprTest.java
@@ -0,0 +1,15 @@
+package com.github.javaparser.ast.expr;
+
+import com.github.javaparser.JavaParser;
+import org.junit.Test;
+
+import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
+
+public class InstanceOfExprTest {
+ @Test
+ public void annotationsOnTheType() {
+ InstanceOfExpr expr = JavaParser.parseExpression("s instanceof @A @DA String");
+
+ assertThat(expr.getType().getAnnotations()).containsExactly(new MarkerAnnotationExpr("A"), new MarkerAnnotationExpr("DA"));
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/LambdaExprTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/LambdaExprTest.java
new file mode 100644
index 000000000..082906b15
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/LambdaExprTest.java
@@ -0,0 +1,41 @@
+package com.github.javaparser.ast.expr;
+
+import com.github.javaparser.TokenRange;
+import com.github.javaparser.ast.Node;
+import org.junit.Test;
+
+import static com.github.javaparser.JavaParser.parseExpression;
+import static org.junit.Assert.*;
+
+public class LambdaExprTest {
+ @Test
+ public void lambdaRange1(){
+ Expression expression = parseExpression("x -> y");
+ assertRange("x", "y", expression);
+ }
+
+ @Test
+ public 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
+ public void getExpressionBody(){
+ LambdaExpr lambdaExpr = parseExpression("x -> y").asLambdaExpr();
+ assertEquals("Optional[y]", lambdaExpr.getExpressionBody().toString());
+ }
+
+ @Test
+ public void getNoExpressionBody(){
+ LambdaExpr lambdaExpr = parseExpression("x -> {y;}").asLambdaExpr();
+ assertEquals("Optional.empty", lambdaExpr.getExpressionBody().toString());
+ }
+
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/LiteralStringValueExprTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/LiteralStringValueExprTest.java
new file mode 100644
index 000000000..1b9dfef1a
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/LiteralStringValueExprTest.java
@@ -0,0 +1,166 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2017 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the 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 org.assertj.core.data.Percentage;
+import org.junit.Test;
+
+import static com.github.javaparser.JavaParser.*;
+import static org.assertj.core.api.Assertions.assertThat;
+
+@SuppressWarnings("OctalInteger")
+public class LiteralStringValueExprTest {
+
+ @Test
+ public 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
+ public 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
+ public 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
+ public 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
+ public 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
+ public 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-testing/src/test/java/com/github/javaparser/ast/expr/MethodCallExprTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/MethodCallExprTest.java
new file mode 100644
index 000000000..258576420
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/MethodCallExprTest.java
@@ -0,0 +1,22 @@
+package com.github.javaparser.ast.expr;
+
+import org.junit.Test;
+
+import static com.github.javaparser.JavaParser.parseExpression;
+import static java.util.Optional.empty;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+public class MethodCallExprTest {
+
+ @Test
+ public 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());
+ }
+
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/MethodReferenceExprTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/MethodReferenceExprTest.java
new file mode 100644
index 000000000..6f0643ba4
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/MethodReferenceExprTest.java
@@ -0,0 +1,114 @@
+package com.github.javaparser.ast.expr;
+
+import org.junit.Test;
+
+import static com.github.javaparser.utils.TestUtils.assertExpressionValid;
+import static org.junit.Assert.assertTrue;
+
+public class MethodReferenceExprTest {
+
+ @Test
+ public void methodReferenceExprHasAlwaysAScope() {
+ assertTrue(new MethodReferenceExpr().getScope() != null);
+ }
+
+ @Test
+ public void reference1() {
+ assertExpressionValid("String::length");
+ }
+
+ @Test
+ public void reference2() {
+ assertExpressionValid("System::currentTimeMillis // static method");
+ }
+
+ @Test
+ public void reference3() {
+ assertExpressionValid("List<String>::size // explicit type arguments for generic type");
+ }
+
+ @Test
+ public void reference4() {
+ assertExpressionValid("List::size // inferred type arguments for generic type");
+ }
+
+ @Test
+ public void reference5() {
+ assertExpressionValid("int[]::clone");
+ }
+
+ @Test
+ public void reference6() {
+ assertExpressionValid("T::tvarMember");
+ }
+
+ @Test
+ public void reference7() {
+ assertExpressionValid("System.out::println");
+ }
+
+ @Test
+ public void reference8() {
+ assertExpressionValid("\"abc\"::length");
+ }
+
+ @Test
+ public void reference9() {
+ assertExpressionValid("foo[x]::bar");
+ }
+
+ @Test
+ public void reference10() {
+ assertExpressionValid("(test ? list.replaceAll(String::trim) : list) :: iterator");
+ }
+
+ @Test
+ public void reference10Annotated1() {
+ assertExpressionValid("(test ? list.replaceAll(@A String::trim) : list) :: iterator");
+ }
+
+ @Test
+ public void reference11() {
+ assertExpressionValid("String::valueOf // overload resolution needed");
+ }
+
+ @Test
+ public void reference12() {
+ assertExpressionValid("Arrays::sort // type arguments inferred from context");
+ }
+
+ @Test
+ public void reference13() {
+ assertExpressionValid("Arrays::<String>sort // explicit type arguments");
+ }
+
+ @Test
+ public void reference14() {
+ assertExpressionValid("ArrayList<String>::new // constructor for parameterized type");
+ }
+
+ @Test
+ public void reference15() {
+ assertExpressionValid("ArrayList::new // inferred type arguments");
+ }
+
+ @Test
+ public void reference16() {
+ assertExpressionValid("Foo::<Integer>new // explicit type arguments");
+ }
+
+ @Test
+ public void reference17() {
+ assertExpressionValid("Bar<String>::<Integer>new // generic class, generic constructor");
+ }
+
+ @Test
+ public void reference18() {
+ assertExpressionValid("Outer.Inner::new // inner class constructor");
+ }
+
+ @Test
+ public void reference19() {
+ assertExpressionValid("int[]::new // array creation");
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/NameTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/NameTest.java
new file mode 100644
index 000000000..6df3a6833
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/NameTest.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2017 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the 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.Test;
+
+import static com.github.javaparser.JavaParser.*;
+import static com.github.javaparser.utils.Utils.EOL;
+import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
+import static org.junit.Assert.assertEquals;
+
+public class NameTest {
+ @Test
+ public void outerNameExprIsTheRightMostIdentifier() {
+ Name name = parseName("a.b.c");
+ assertEquals("c", name.getIdentifier());
+ }
+
+ @Test
+ public void parsingAndUnparsingWorks() {
+ Name name = parseName("a.b.c");
+ assertEquals("a.b.c", name.asString());
+ }
+
+ @Test(expected = ParseProblemException.class)
+ public void parsingEmptyNameThrowsException() {
+ parseName("");
+ }
+
+ @Test
+ public void nameCanHaveAnnotationsInside() {
+ Name name = parseName("a.@A b. @C c");
+ assertEquals("a.b.c", name.asString());
+ assertThat(name.getAnnotations()).containsExactly(new MarkerAnnotationExpr("C"));
+ assertThat(name.getQualifier().get().getAnnotations()).containsExactly(new MarkerAnnotationExpr("A"));
+
+ assertEquals("a.@A b.@C c", name.toString());
+ assertEquals("a.@A b.@C c", ConcreteSyntaxModel.genericPrettyPrint(name));
+ }
+
+ @Test
+ public void importName() {
+ ImportDeclaration importDeclaration = parseImport("import java.@Abc util.List;");
+
+ assertThat(importDeclaration.getName().getQualifier().get().getAnnotations()).containsExactly(new MarkerAnnotationExpr("Abc"));
+
+ assertEquals("import java.@Abc util.List;" + EOL, importDeclaration.toString());
+ assertEquals("import java.@Abc util.List;" + EOL, ConcreteSyntaxModel.genericPrettyPrint(importDeclaration));
+ }
+
+ @Test
+ public void packageName() {
+ CompilationUnit cu = parse("package @Abc p1.p2;");
+
+ assertThat(cu.getPackageDeclaration().get().getName().getQualifier().get().getAnnotations()).containsExactly(new MarkerAnnotationExpr("Abc"));
+
+ assertEquals("package @Abc p1.p2;" + EOL + EOL, cu.toString());
+ assertEquals("package @Abc p1.p2;" + EOL + EOL, ConcreteSyntaxModel.genericPrettyPrint(cu));
+ }
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/SimpleNameTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/SimpleNameTest.java
new file mode 100644
index 000000000..f7e028563
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/SimpleNameTest.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2017 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the 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.Test;
+
+import static com.github.javaparser.JavaParser.parseSimpleName;
+import static junit.framework.TestCase.assertEquals;
+
+public class SimpleNameTest {
+
+ @Test
+ public void defaultConstructorSetsIdentifierToEmpty() {
+ assertEquals("empty", new SimpleName().getIdentifier());
+ }
+
+ @Test(expected = AssertionError.class)
+ public void identifierMustNotBeEmpty() {
+ new SimpleName("");
+ }
+
+ @Test(expected = AssertionError.class)
+ public void identifierMustNotBeNull() {
+ new SimpleName(null);
+ }
+
+ @Test
+ public void unicodeEscapesArePreservedInIdentifiers() {
+ SimpleName name = parseSimpleName("xxx\\u2122xxx");
+ assertEquals("xxx\\u2122xxx", name.asString());
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/StringLiteralExprTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/StringLiteralExprTest.java
new file mode 100644
index 000000000..50a9bfcfa
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/StringLiteralExprTest.java
@@ -0,0 +1,14 @@
+package com.github.javaparser.ast.expr;
+
+import org.junit.Test;
+
+import static com.github.javaparser.JavaParser.parseExpression;
+import static org.junit.Assert.*;
+
+public class StringLiteralExprTest {
+ @Test
+ public void unicodeEscapesArePreservedInStrings() {
+ StringLiteralExpr omega = parseExpression("\"xxx\\u03a9xxx\"");
+ assertEquals("xxx\\u03a9xxx", omega.getValue());
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/imports/ImportDeclarationTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/imports/ImportDeclarationTest.java
new file mode 100644
index 000000000..ca821fbe9
--- /dev/null
+++ b/javaparser-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-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.ast.imports;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.ast.ImportDeclaration;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+public class ImportDeclarationTest {
+ @Test
+ public void singleTypeImportDeclaration() {
+ ImportDeclaration i = JavaParser.parseImport("import a.b.c.X;");
+ assertEquals("a.b.c.X", i.getNameAsString());
+ }
+
+ @Test
+ public void typeImportOnDemandDeclaration() {
+ ImportDeclaration i = JavaParser.parseImport("import a.b.c.D.*;");
+ assertEquals("a.b.c.D", i.getName().toString());
+ assertEquals("D", i.getName().getIdentifier());
+ }
+
+ @Test
+ public void singleStaticImportDeclaration() {
+ ImportDeclaration i = JavaParser.parseImport("import static a.b.c.X.def;");
+ assertEquals("a.b.c.X", i.getName().getQualifier().get().asString());
+ assertEquals("def", i.getName().getIdentifier());
+ }
+
+ @Test
+ public void staticImportOnDemandDeclaration() {
+ ImportDeclaration i = JavaParser.parseImport("import static a.b.c.X.*;");
+ assertEquals("a.b.c.X", i.getNameAsString());
+ }
+
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithJavadocTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithJavadocTest.java
new file mode 100644
index 000000000..37728e76b
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithJavadocTest.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2017 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the 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.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.Test;
+
+import java.util.EnumSet;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+public class NodeWithJavadocTest {
+
+ @Test
+ public void removeJavaDocNegativeCaseNoComment() {
+ ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class),
+ false, "Foo");
+ assertEquals(false, decl.removeJavaDocComment());
+ }
+
+ @Test
+ public void removeJavaDocNegativeCaseCommentNotJavaDoc() {
+ ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class),
+ false, "Foo");
+ decl.setComment(new LineComment("A comment"));
+ assertEquals(false, decl.removeJavaDocComment());
+ assertTrue(decl.getComment().isPresent());
+ }
+
+ @Test
+ public void removeJavaDocPositiveCase() {
+ ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class),
+ false, "Foo");
+ decl.setComment(new JavadocComment("A comment"));
+ assertEquals(true, decl.removeJavaDocComment());
+ assertFalse(decl.getComment().isPresent());
+ }
+
+ @Test
+ public void getJavadocOnMethodWithLineCommentShouldReturnEmptyOptional() {
+ MethodDeclaration method = new MethodDeclaration();
+ method.setLineComment("Lorem Ipsum.");
+
+ assertFalse(method.getJavadocComment().isPresent());
+ assertFalse(method.getJavadoc().isPresent());
+ }
+
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithModifiersTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithModifiersTest.java
new file mode 100644
index 000000000..20c302dd0
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithModifiersTest.java
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2017 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the 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.body.ClassOrInterfaceDeclaration;
+import com.github.javaparser.ast.body.MethodDeclaration;
+import com.github.javaparser.ast.comments.JavadocComment;
+import com.github.javaparser.ast.comments.LineComment;
+import com.github.javaparser.ast.observer.AstObserverAdapter;
+import com.github.javaparser.ast.observer.ObservableProperty;
+import org.junit.Test;
+
+import java.util.EnumSet;
+import java.util.LinkedList;
+import java.util.List;
+
+import static org.junit.Assert.*;
+
+public class NodeWithModifiersTest {
+
+ @Test
+ public void addModifierWorks() {
+ ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class),
+ false, "Foo");
+ decl.addModifier(Modifier.PUBLIC);
+ assertEquals(EnumSet.of(Modifier.PUBLIC), decl.getModifiers());
+ }
+
+ @Test
+ public void addModifierTriggerNotification() {
+ List<String> changes = new LinkedList<>();
+ ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class),
+ 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(Modifier.PUBLIC);
+ assertEquals(1, changes.size());
+ assertEquals("property MODIFIERS is changed to [PUBLIC]", changes.get(0));
+ }
+
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithOptionalScopeTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithOptionalScopeTest.java
new file mode 100644
index 000000000..ad7e8bd7e
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithOptionalScopeTest.java
@@ -0,0 +1,28 @@
+package com.github.javaparser.ast.nodeTypes;
+
+import com.github.javaparser.ast.expr.*;
+import org.junit.Test;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+public class NodeWithOptionalScopeTest {
+
+ @Test
+ public void commonExpressionWhichHaveInterfaceNodeWithOptionalScope() {
+ NodeWithOptionalScope methodCallExpr = new MethodCallExpr(new NameExpr("A"), "call");
+ NodeWithOptionalScope objectCreationExpr = new ObjectCreationExpr();
+
+ assertTrue(methodCallExpr.getScope().isPresent());
+ assertFalse(objectCreationExpr.getScope().isPresent());
+ }
+
+ @Test
+ public void removeScope() {
+ MethodCallExpr methodCallExpr = new MethodCallExpr(new NameExpr("A"), "method");
+
+ methodCallExpr.removeScope();
+
+ assertFalse(methodCallExpr.getScope().isPresent());
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithTraversableScopeTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithTraversableScopeTest.java
new file mode 100644
index 000000000..59aaf4e63
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithTraversableScopeTest.java
@@ -0,0 +1,23 @@
+package com.github.javaparser.ast.nodeTypes;
+
+import com.github.javaparser.ast.expr.FieldAccessExpr;
+import com.github.javaparser.ast.expr.MethodCallExpr;
+import org.junit.Test;
+
+import static com.github.javaparser.JavaParser.parseExpression;
+import static com.github.javaparser.utils.TestUtils.assertInstanceOf;
+import static org.junit.Assert.assertFalse;
+
+public class NodeWithTraversableScopeTest {
+ @Test
+ public 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-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithVariablesTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithVariablesTest.java
new file mode 100644
index 000000000..b736333c1
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithVariablesTest.java
@@ -0,0 +1,95 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.ast.nodeTypes;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.ast.expr.VariableDeclarationExpr;
+import com.github.javaparser.ast.type.PrimitiveType;
+import org.junit.Test;
+
+import static com.github.javaparser.JavaParser.*;
+import static org.junit.Assert.assertEquals;
+
+public class NodeWithVariablesTest {
+
+ @Test
+ public void getCommonTypeWorksForNormalVariables() {
+ VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a,b");
+ assertEquals(PrimitiveType.intType(), declaration.getCommonType());
+ }
+
+ @Test
+ public void getCommonTypeWorksForArrayTypes() {
+ parseVariableDeclarationExpr("int a[],b[]").getCommonType();
+ }
+
+ @Test(expected = AssertionError.class)
+ public void getCommonTypeFailsOnArrayDifferences() {
+ parseVariableDeclarationExpr("int a[],b[][]").getCommonType();
+ }
+
+ @Test(expected = AssertionError.class)
+ public void getCommonTypeFailsOnDodgySetterUsage() {
+ VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a,b");
+ declaration.getVariable(1).setType(String.class);
+ declaration.getCommonType();
+ }
+
+ @Test(expected = AssertionError.class)
+ public void getCommonTypeFailsOnInvalidEmptyVariableList() {
+ VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a");
+ declaration.getVariables().clear();
+ declaration.getCommonType();
+ }
+
+ @Test
+ public void getElementTypeWorksForNormalVariables() {
+ VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a,b");
+ assertEquals(PrimitiveType.intType(), declaration.getElementType());
+ }
+
+ @Test
+ public void getElementTypeWorksForArrayTypes() {
+ VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a[],b[]");
+ assertEquals(PrimitiveType.intType(), declaration.getElementType());
+ }
+
+ @Test
+ public void getElementTypeIsOkayWithArrayDifferences() {
+ parseVariableDeclarationExpr("int a[],b[][]").getElementType();
+ }
+
+ @Test(expected = AssertionError.class)
+ public void getElementTypeFailsOnDodgySetterUsage() {
+ VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a,b");
+ declaration.getVariable(1).setType(String.class);
+ declaration.getElementType();
+ }
+
+ @Test(expected = AssertionError.class)
+ public void getElementTypeFailsOnInvalidEmptyVariableList() {
+ VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a");
+ declaration.getVariables().clear();
+ declaration.getElementType();
+ }
+
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/observer/PropagatingAstObserverTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/observer/PropagatingAstObserverTest.java
new file mode 100644
index 000000000..b590f32ab
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/observer/PropagatingAstObserverTest.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.ast.observer;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.ast.CompilationUnit;
+import com.github.javaparser.ast.Node;
+import com.github.javaparser.ast.body.FieldDeclaration;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+
+public class PropagatingAstObserverTest {
+ @Test
+ public void verifyPropagation() {
+ String code = "class A { }";
+ CompilationUnit cu = JavaParser.parse(code);
+ List<String> 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);
+ assertEquals(true, 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-testing/src/test/java/com/github/javaparser/ast/stmt/BlockStmtTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/stmt/BlockStmtTest.java
new file mode 100644
index 000000000..5e5976ab8
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/stmt/BlockStmtTest.java
@@ -0,0 +1,21 @@
+package com.github.javaparser.ast.stmt;
+
+import com.github.javaparser.ast.expr.Expression;
+import com.github.javaparser.ast.expr.MethodCallExpr;
+import com.github.javaparser.ast.expr.NameExpr;
+import org.junit.Test;
+
+public class BlockStmtTest {
+ @Test
+ public void issue748AddingIdenticalStatementsDoesParentingRight() {
+ BlockStmt blockStmt = new BlockStmt();
+ Expression exp = new NameExpr("x");
+ MethodCallExpr expression = new MethodCallExpr(exp, "y");
+
+ blockStmt.addStatement(expression);
+ blockStmt.addStatement(expression.clone());
+ // This fails when the issue exists:
+ String s = blockStmt.toString();
+ }
+
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/stmt/IfElseStmtTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/stmt/IfElseStmtTest.java
new file mode 100644
index 000000000..5775bd049
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/stmt/IfElseStmtTest.java
@@ -0,0 +1,37 @@
+package com.github.javaparser.ast.stmt;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.ast.expr.Expression;
+import com.github.javaparser.ast.expr.MethodCallExpr;
+import com.github.javaparser.ast.expr.NameExpr;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+public class IfElseStmtTest {
+
+ @Test
+ public void issue1247withElseSingleStmt() {
+ IfStmt ifStmt = (IfStmt) JavaParser.parseStatement("if (cond) doSomething(); else doSomethingElse();");
+ assertEquals(false, ifStmt.hasElseBlock());
+ assertEquals(true, ifStmt.hasElseBranch());
+ assertEquals(false, ifStmt.hasCascadingIfStmt());
+ }
+
+ @Test
+ public void issue1247withElseBlockStmt() {
+ IfStmt ifStmt = (IfStmt) JavaParser.parseStatement("if (cond) doSomething(); else { doSomethingElse(); }");
+ assertEquals(true, ifStmt.hasElseBlock());
+ assertEquals(true, ifStmt.hasElseBranch());
+ assertEquals(false, ifStmt.hasCascadingIfStmt());
+ }
+
+ @Test
+ public void issue1247withElseSingleStmtWhichIsAnIf() {
+ IfStmt ifStmt = (IfStmt) JavaParser.parseStatement("if (cond1) doSomething(); else if (cond2) doSomethingElse();");
+ assertEquals(false, ifStmt.hasElseBlock());
+ assertEquals(true, ifStmt.hasElseBranch());
+ assertEquals(true, ifStmt.hasCascadingIfStmt());
+ }
+
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/stmt/TryStmtTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/stmt/TryStmtTest.java
new file mode 100644
index 000000000..1a63b21f7
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/stmt/TryStmtTest.java
@@ -0,0 +1,81 @@
+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 com.github.javaparser.ast.validator.Java9Validator;
+import org.junit.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.Assert.assertTrue;
+
+public class TryStmtTest {
+ @Test
+ public void simpleTest() {
+ TryStmt tryStmt = parse9("try(Reader x = new FileReader()){}");
+ assertInstanceOf(VariableDeclarationExpr.class, tryStmt.getResources().get(0));
+ }
+
+ @Test
+ public void multipleTest() {
+ TryStmt tryStmt = parse9("try(Reader x = new FileReader(); Reader x = new FileReader()){}");
+ assertInstanceOf(VariableDeclarationExpr.class, tryStmt.getResources().get(0));
+
+ }
+
+ @Test
+ public void modifiersTest() {
+ TryStmt tryStmt = parse9("try(final @A Reader x = new FileReader()){}");
+ assertInstanceOf(VariableDeclarationExpr.class, tryStmt.getResources().get(0));
+
+ }
+
+ @Test
+ public void simpleVariable() {
+ TryStmt tryStmt = parse9("try(a){}");
+ assertInstanceOf(NameExpr.class, tryStmt.getResources().get(0));
+
+ }
+
+ @Test
+ public void twoSimpleVariables() {
+ TryStmt tryStmt = parse9("try(a;b){}");
+ assertInstanceOf(NameExpr.class, tryStmt.getResources().get(0));
+ assertInstanceOf(NameExpr.class, tryStmt.getResources().get(1));
+
+ }
+
+ @Test
+ public void complexVariable() {
+ TryStmt tryStmt = parse9("try(a.b.c){}");
+ assertInstanceOf(FieldAccessExpr.class, tryStmt.getResources().get(0));
+
+ }
+
+ @Test
+ public void superAccess() {
+ TryStmt tryStmt = parse9("try(super.a){}");
+ assertInstanceOf(FieldAccessExpr.class, tryStmt.getResources().get(0));
+
+ }
+
+ @Test
+ public void outerClassAccess() {
+ TryStmt tryStmt = parse9("try(X.this.a){}");
+ assertInstanceOf(FieldAccessExpr.class, tryStmt.getResources().get(0));
+
+ }
+
+ private <T> T parse9(String code) {
+ JavaParser parser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_9));
+ ParseResult<Statement> result = parser.parse(ParseStart.STATEMENT, provider(code));
+ assertTrue(result.toString(), result.isSuccessful());
+ return (T) result.getResult().get();
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/type/ArrayTypeTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/type/ArrayTypeTest.java
new file mode 100644
index 000000000..3fdee8e43
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/type/ArrayTypeTest.java
@@ -0,0 +1,188 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.ast.type;
+
+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.Name;
+import com.github.javaparser.ast.expr.VariableDeclarationExpr;
+import com.github.javaparser.ast.stmt.ExpressionStmt;
+import com.github.javaparser.printer.ConcreteSyntaxModel;
+import org.assertj.core.api.Assertions;
+import org.junit.Test;
+
+import static com.github.javaparser.JavaParser.*;
+import static com.github.javaparser.utils.Utils.EOL;
+import static org.assertj.core.api.Assertions.*;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.assertEquals;
+
+public class ArrayTypeTest {
+ @Test
+ public 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("A")));
+ assertThat(arrayType2.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("B")));
+ assertThat(arrayType3.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("X")));
+ assertThat(arrayType4.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("Y")));
+
+ assertThat(elementType.getType()).isEqualTo(PrimitiveType.Primitive.INT);
+ assertThat(fieldDeclaration.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("C")));
+
+ assertThat(arrayType1.getParentNode().get().getParentNode().get()).isSameAs(fieldDeclaration);
+ }
+
+ @Test
+ public 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("A")));
+ assertThat(arrayType2.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("B")));
+ assertThat(arrayType3.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("X")));
+ assertThat(arrayType4.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("Y")));
+
+ assertThat(elementType.getType()).isEqualTo(PrimitiveType.Primitive.INT);
+ assertThat(variableDeclarationExpr.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("C")));
+
+ assertThat(arrayType1.getParentNode().get().getParentNode().get()).isSameAs(variableDeclarationExpr);
+ }
+
+ @Test
+ public 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("A")));
+ assertThat(arrayType2.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("B")));
+ assertThat(methodDeclaration.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("C")));
+
+ assertThat(methodDeclaration.getType().getParentNode().get()).isSameAs(methodDeclaration);
+ }
+
+ @Test
+ public 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("A")));
+ assertThat(innerArrayType.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("B")));
+ assertThat(parameter.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("C")));
+
+ assertThat(parameter.getType().getParentNode().get()).isSameAs(parameter);
+ }
+
+ @Test
+ public 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 int[][] a;", variableDeclarationStatement.toString());
+ }
+
+ @Test
+ public void setFieldDeclarationWithArrays() {
+ FieldDeclaration fieldDeclaration = parseBodyDeclaration("int[][] a[][];").asFieldDeclaration();
+ fieldDeclaration.getVariable(0).setType(new ArrayType(new ArrayType(parseClassOrInterfaceType("Blob"))));
+
+ assertEquals("Blob[][] a;", fieldDeclaration.toString());
+ }
+
+ @Test
+ public void setMethodDeclarationWithArrays() {
+ MethodDeclaration method = parseBodyDeclaration("int[][] a()[][] {}").asMethodDeclaration();
+ method.setType(new ArrayType(new ArrayType(parseClassOrInterfaceType("Blob"))));
+
+ assertEquals("Blob[][] a() {" + EOL + "}", method.toString());
+ }
+
+ @Test
+ public void fieldDeclarationWithArraysHasCorrectOrigins() {
+ FieldDeclaration fieldDeclaration = parseBodyDeclaration("int[] a[];").asFieldDeclaration();
+
+ Type outerType = fieldDeclaration.getVariables().get(0).getType();
+ assertEquals(ArrayType.Origin.TYPE, outerType.asArrayType().getOrigin());
+ assertEquals(ArrayType.Origin.NAME, outerType.asArrayType().getComponentType().asArrayType().getOrigin());
+ }
+
+ @Test
+ public void methodDeclarationWithArraysHasCorrectOrigins() {
+ MethodDeclaration method = (MethodDeclaration) parseBodyDeclaration("int[] a()[] {}");
+
+ Type outerType = method.getType();
+ assertEquals(ArrayType.Origin.TYPE, outerType.asArrayType().getOrigin());
+ assertEquals(ArrayType.Origin.NAME, outerType.asArrayType().getComponentType().asArrayType().getOrigin());
+ }
+
+ @Test
+ public 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) {" + EOL + "}", method.toString());
+ }
+
+ @Test
+ public void getArrayCreationType() {
+ ArrayCreationExpr expr = parseExpression("new int[]");
+ ArrayType outerType = expr.createdType().asArrayType();
+ Type innerType = outerType.getComponentType();
+ assertThat(innerType).isEqualTo(expr.getElementType());
+ }
+
+ @Test
+ public 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));
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/type/TypeTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/type/TypeTest.java
new file mode 100644
index 000000000..17244f383
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/type/TypeTest.java
@@ -0,0 +1,68 @@
+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.Java5Validator;
+import org.junit.Test;
+
+import static com.github.javaparser.JavaParser.parseType;
+import static com.github.javaparser.JavaParser.parseVariableDeclarationExpr;
+import static com.github.javaparser.ParseStart.VARIABLE_DECLARATION_EXPR;
+import static com.github.javaparser.ParserConfiguration.LanguageLevel.*;
+import static com.github.javaparser.Providers.provider;
+import static org.junit.Assert.*;
+
+public class TypeTest {
+ @Test
+ public void asString() {
+ assertEquals("int", typeAsString("int x"));
+ assertEquals("List<Long>", typeAsString("List<Long> x"));
+ assertEquals("String", typeAsString("@A String x"));
+ assertEquals("List<? extends Object>", typeAsString("List<? extends Object> x"));
+ }
+
+ @Test(expected = ParseProblemException.class)
+ public void primitiveTypeArgumentDefaultValidator() {
+ typeAsString("List<long> x;");
+ }
+
+ @Test
+ public void primitiveTypeArgumentLenientValidator() {
+ ParserConfiguration config = new ParserConfiguration()
+ .setLanguageLevel(RAW);
+ config.getPostProcessors().add(new Java5Validator() {{
+ remove(noPrimitiveGenericArguments);
+ }}.postProcessor());
+
+ ParseResult<VariableDeclarationExpr> result = new JavaParser(config).parse(
+ VARIABLE_DECLARATION_EXPR, provider("List<long> x"));
+ assertTrue(result.isSuccessful());
+
+ VariableDeclarationExpr decl = result.getResult().get();
+ assertEquals("List<long>", decl.getVariable(0).getType().asString());
+ }
+
+ private String typeAsString(String s) {
+ return parseVariableDeclarationExpr(s).getVariable(0).getType().asString();
+ }
+
+ @Test
+ public 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
+ public void issue1251() {
+ final Type type = parseType("TypeUtilsTest<String>.Tester");
+ assertEquals("TypeUtilsTest<String>.Tester", type.toString());
+ }
+
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java10ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java10ValidatorTest.java
new file mode 100644
index 000000000..8c2b93568
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java10ValidatorTest.java
@@ -0,0 +1,108 @@
+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.Ignore;
+import org.junit.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;
+
+public class Java10ValidatorTest {
+ public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_10));
+
+ @Test
+ public void varAllowedInLocalVariableDeclaration() {
+ ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("var a = 5;"));
+ assertNoProblems(result);
+ }
+
+ @Test
+ public void varAllowedInForEach() {
+ ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("for(var a : as){}"));
+ assertNoProblems(result);
+ }
+
+ @Test
+ public void varAllowedInOldFor() {
+ ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("for(var a = 5;a<9;a++){}"));
+ assertNoProblems(result);
+ }
+
+ @Test
+ public void varNotAllowedInCast() {
+ ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("int a = (var)20;"));
+ assertNoProblems(result);
+ }
+
+ @Test
+ public void varNotAllowedInTryWithResources() {
+ ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("try(var f = new FileReader(\"\")){ }catch (Exception e){ }"));
+ assertProblems(result, "(line 1,col 5) \"var\" is not allowed here.");
+ }
+
+ @Test
+ public void varNotAllowedInField() {
+ ParseResult<BodyDeclaration<?>> result = javaParser.parse(CLASS_BODY, provider("var a = 20;"));
+ assertProblems(result, "(line 1,col 1) \"var\" is not allowed here.");
+ }
+
+ @Test
+ public void varNotAllowedInTypeArguments() {
+ ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("new X<var>();"));
+ assertProblems(result, "(line 1,col 7) \"var\" is not allowed here.");
+ }
+
+ @Test
+ public void varNotAllowedInLambdaParameters() {
+ ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("x((var x) -> null);"));
+ assertProblems(result, "(line 1,col 4) \"var\" is not allowed here.");
+ }
+
+ @Test
+ public void emptyInitializerNotAllowed() {
+ ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("var a;"));
+ assertProblems(result, "(line 1,col 1) \"var\" needs an initializer.");
+ }
+
+ @Test
+ public void multipleVariablesNotAllowed() {
+ ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("var a=1, b=2;"));
+ assertProblems(result, "(line 1,col 1) \"var\" only takes a single variable.");
+ }
+
+ @Test
+ public void nullVariablesNotAllowed() {
+ ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("var a=null;"));
+ assertProblems(result, "(line 1,col 1) \"var\" cannot infer type from just null.");
+ }
+
+ @Test
+ public void arrayDimensionBracketsNotAllowed() {
+ ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("var a=new String[]{};"));
+ assertProblems(result, "(line 1,col 1) \"var\" cannot infer array types.");
+ }
+
+ // This is pretty hard to impossible to implement correctly with just the AST.
+ @Ignore
+ @Test
+ public void selfReferenceNotAllowed() {
+ ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("var a=a;"));
+ assertProblems(result, "");
+ }
+
+ // Can be implemented once https://github.com/javaparser/javaparser/issues/1434 is implemented.
+ @Ignore
+ @Test
+ public void polyExpressionAsInitializerNotAllowed() {
+ ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("var a=new ArrayList<>();"));
+ assertProblems(result, "");
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java11ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java11ValidatorTest.java
new file mode 100644
index 000000000..1e1f8c0f8
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java11ValidatorTest.java
@@ -0,0 +1,22 @@
+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.Test;
+
+import static com.github.javaparser.ParseStart.STATEMENT;
+import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_11_PREVIEW;
+import static com.github.javaparser.Providers.provider;
+import static com.github.javaparser.utils.TestUtils.assertNoProblems;
+
+public class Java11ValidatorTest {
+ public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_11_PREVIEW));
+
+ @Test
+ public void varAllowedInLocalVariableDeclaration() {
+ ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("x((var x, var y) -> x+y);"));
+ assertNoProblems(result);
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_0ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_0ValidatorTest.java
new file mode 100644
index 000000000..7160bcfb9
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_0ValidatorTest.java
@@ -0,0 +1,98 @@
+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.ArrayCreationExpr;
+import com.github.javaparser.ast.expr.Expression;
+import com.github.javaparser.ast.stmt.Statement;
+import com.github.javaparser.ast.type.PrimitiveType;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static com.github.javaparser.ParseStart.*;
+import static com.github.javaparser.ParserConfiguration.LanguageLevel.*;
+import static com.github.javaparser.Providers.provider;
+import static com.github.javaparser.utils.TestUtils.assertNoProblems;
+import static com.github.javaparser.utils.TestUtils.assertProblems;
+import static org.junit.Assert.assertEquals;
+
+public class Java1_0ValidatorTest {
+ public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_1_0));
+
+ @Test
+ public void tryWithoutResources() {
+ ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("try(X x=new Y()){}"));
+ assertProblems(result,
+ "(line 1,col 1) Catch with resource is not supported.",
+ "(line 1,col 1) Try has no finally and no catch.");
+ }
+
+ @Test
+ public void classExtendingMoreThanOne() {
+ ParseResult<CompilationUnit> 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
+ public void interfaceUsingImplements() {
+ ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("interface X implements Y {}"));
+ assertProblems(result, "(line 1,col 24) An interface cannot implement other interfaces.");
+ }
+
+ @Test
+ public void interfaceWithInitializer() {
+ ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("interface X {{}}"));
+ assertProblems(result, "(line 1,col 14) An interface cannot have initializers.");
+ }
+
+ @Test
+ public void defaultInClass() {
+ ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X {default void a(){};}"));
+ assertProblems(result, "(line 1,col 10) 'default' is not allowed here.");
+ }
+
+ @Test
+ public void leftHandAssignmentCannotBeAConditional() {
+ ParseResult<Expression> result = javaParser.parse(EXPRESSION, provider("(1==2)=3"));
+ assertProblems(result, "(line 1,col 1) Illegal left hand side of an assignment.");
+ }
+
+ @Test
+ public void leftHandAssignmentCannotBeEmptyBraces() {
+ ParseResult<Expression> 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.");
+ }
+
+ @Test
+ public void leftHandAssignmentCanBeInBraces() {
+ ParseResult<Expression> result = javaParser.parse(EXPRESSION, provider("(i) += (i) += 1"));
+ assertNoProblems(result);
+ }
+
+ @Test
+ public void noInnerClasses() {
+ ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{class Y{}}"));
+ assertProblems(result, "(line 1,col 9) inner classes or interfaces are not supported.");
+ }
+
+ @Test
+ public void noReflection() {
+ ParseResult<Expression> result = javaParser.parse(EXPRESSION, provider("Abc.class"));
+ assertProblems(result, "(line 1,col 1) Reflection is not supported.");
+ }
+
+ @Test
+ public void nonEmptyList() {
+ ArrayCreationExpr expr = new ArrayCreationExpr(PrimitiveType.booleanType());
+ List<Problem> problems= new ArrayList<>();
+ new Java1_0Validator().accept(expr, new ProblemReporter(problems::add));
+ assertEquals("ArrayCreationExpr.levels can not be empty.", problems.get(0).getMessage());
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_1ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_1ValidatorTest.java
new file mode 100644
index 000000000..6331d9ab1
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_1ValidatorTest.java
@@ -0,0 +1,292 @@
+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.Test;
+
+import static com.github.javaparser.ParseStart.COMPILATION_UNIT;
+import static com.github.javaparser.ParseStart.EXPRESSION;
+import static com.github.javaparser.ParseStart.STATEMENT;
+import static com.github.javaparser.ParserConfiguration.LanguageLevel.*;
+import static com.github.javaparser.Providers.provider;
+import static com.github.javaparser.utils.TestUtils.assertNoProblems;
+import static com.github.javaparser.utils.TestUtils.assertProblems;
+
+public 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
+ public void topClass() {
+ ParseResult<CompilationUnit> 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
+ public void nestedClass() {
+ ParseResult<CompilationUnit> 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
+ public void localClass() {
+ ParseResult<CompilationUnit> 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
+ public void topInterface() {
+ ParseResult<CompilationUnit> 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
+ public void nestedInterface() {
+ ParseResult<CompilationUnit> 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
+ public void constructor() {
+ ParseResult<CompilationUnit> 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
+ public void constructorParameter() {
+ ParseResult<CompilationUnit> 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
+ public void classMethod() {
+ ParseResult<CompilationUnit> 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
+ public void interfaceMethod() {
+ ParseResult<CompilationUnit> 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
+ public void methodParameter() {
+ ParseResult<CompilationUnit> 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
+ public void field() {
+ ParseResult<CompilationUnit> 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
+ public void localVariable() {
+ ParseResult<CompilationUnit> 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
+ public void catchParameter() {
+ ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{int x(){ try{}catch(" + allModifiers + " Integer x){}}}"));
+ assertProblems(result,
+ "(line 1,col 144) Can have only one of 'public', 'protected', 'private'.",
+ "(line 1,col 144) Can have only one of 'final', 'abstract'.",
+ "(line 1,col 144) 'transient' is not allowed here.",
+ "(line 1,col 144) 'volatile' is not allowed here.",
+ "(line 1,col 144) 'synchronized' is not allowed here.",
+ "(line 1,col 144) 'native' is not allowed here.",
+ "(line 1,col 144) 'default' is not allowed here.",
+ "(line 1,col 144) 'strictfp' is not allowed here.",
+ "(line 1,col 144) 'abstract' is not allowed here.",
+ "(line 1,col 144) 'static' is not allowed here.",
+ "(line 1,col 144) 'transitive' is not allowed here.",
+ "(line 1,col 144) 'private' is not allowed here.",
+ "(line 1,col 144) 'public' is not allowed here.",
+ "(line 1,col 144) 'protected' is not allowed here."
+ );
+ }
+
+ @Test
+ public void innerClasses() {
+ ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{class Y{}}"));
+ assertNoProblems(result);
+ }
+
+ @Test
+ public void localInterface() {
+ ParseResult<CompilationUnit> 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."
+ );
+ }
+
+ @Test
+ public void reflection() {
+ ParseResult<Expression> result = javaParser.parse(EXPRESSION, provider("Abc.class"));
+ assertNoProblems(result);
+ }
+
+ @Test
+ public void strictfpAllowedAsIdentifier() {
+ ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("int strictfp;"));
+ assertNoProblems(result);
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_2ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_2ValidatorTest.java
new file mode 100644
index 000000000..3ae7018fe
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_2ValidatorTest.java
@@ -0,0 +1,275 @@
+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.Test;
+
+import static com.github.javaparser.ParseStart.COMPILATION_UNIT;
+import static com.github.javaparser.ParseStart.STATEMENT;
+import static com.github.javaparser.ParserConfiguration.LanguageLevel.*;
+import static com.github.javaparser.Providers.provider;
+import static com.github.javaparser.utils.TestUtils.assertProblems;
+
+public 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
+ public void topClass() {
+ ParseResult<CompilationUnit> 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
+ public void nestedClass() {
+ ParseResult<CompilationUnit> 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
+ public void localClass() {
+ ParseResult<CompilationUnit> 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
+ public void topInterface() {
+ ParseResult<CompilationUnit> 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
+ public void nestedInterface() {
+ ParseResult<CompilationUnit> 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
+ public void constructor() {
+ ParseResult<CompilationUnit> 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
+ public void constructorParameter() {
+ ParseResult<CompilationUnit> 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
+ public void classMethod() {
+ ParseResult<CompilationUnit> 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
+ public void interfaceMethod() {
+ ParseResult<CompilationUnit> 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
+ public void methodParameter() {
+ ParseResult<CompilationUnit> 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
+ public void field() {
+ ParseResult<CompilationUnit> 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
+ public void localVariable() {
+ ParseResult<CompilationUnit> 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
+ public void catchParameter() {
+ ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{int x(){ try{}catch(" + allModifiers + " Integer x){}}}"));
+ assertProblems(result,
+ "(line 1,col 144) Can have only one of 'public', 'protected', 'private'.",
+ "(line 1,col 144) Can have only one of 'final', 'abstract'.",
+ "(line 1,col 144) Can have only one of 'native', 'strictfp'.",
+ "(line 1,col 144) 'transient' is not allowed here.",
+ "(line 1,col 144) 'volatile' is not allowed here.",
+ "(line 1,col 144) 'synchronized' is not allowed here.",
+ "(line 1,col 144) 'native' is not allowed here.",
+ "(line 1,col 144) 'default' is not allowed here.",
+ "(line 1,col 144) 'strictfp' is not allowed here.",
+ "(line 1,col 144) 'abstract' is not allowed here.",
+ "(line 1,col 144) 'static' is not allowed here.",
+ "(line 1,col 144) 'transitive' is not allowed here.",
+ "(line 1,col 144) 'private' is not allowed here.",
+ "(line 1,col 144) 'public' is not allowed here.",
+ "(line 1,col 144) 'protected' is not allowed here."
+ );
+ }
+
+ @Test
+ public void strictfpNotAllowedAsIdentifier() {
+ ParseResult<Statement> 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-testing/src/test/java/com/github/javaparser/ast/validator/Java1_3ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_3ValidatorTest.java
new file mode 100644
index 000000000..b10114abf
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_3ValidatorTest.java
@@ -0,0 +1,22 @@
+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.Test;
+
+import static com.github.javaparser.ParseStart.STATEMENT;
+import static com.github.javaparser.ParserConfiguration.LanguageLevel.*;
+import static com.github.javaparser.Providers.provider;
+import static com.github.javaparser.utils.TestUtils.assertProblems;
+
+public class Java1_3ValidatorTest {
+ public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_1_3));
+
+ @Test
+ public void noAssert() {
+ ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("assert a;"));
+ assertProblems(result, "(line 1,col 1) 'assert' keyword is not supported.");
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_4ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_4ValidatorTest.java
new file mode 100644
index 000000000..ed0be99fe
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_4ValidatorTest.java
@@ -0,0 +1,70 @@
+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.Test;
+
+import static com.github.javaparser.ParseStart.*;
+import static com.github.javaparser.ParserConfiguration.LanguageLevel.*;
+import static com.github.javaparser.Providers.provider;
+import static com.github.javaparser.utils.TestUtils.assertNoProblems;
+import static com.github.javaparser.utils.TestUtils.assertProblems;
+
+public class Java1_4ValidatorTest {
+ public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_1_4));
+
+ @Test
+ public void yesAssert() {
+ ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("assert a;"));
+ assertNoProblems(result);
+ }
+
+ @Test
+ public void noGenerics() {
+ ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X<A>{List<String> b;}"));
+ assertProblems(result,
+ "(line 1,col 12) Generics are not supported.",
+ "(line 1,col 1) Generics are not supported."
+ );
+ }
+
+ @Test
+ public void noAnnotations() {
+ ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("@Abc @Def() @Ghi(a=3) @interface X{}"));
+ assertProblems(result,
+ "(line 1,col 6) Annotations are not supported.",
+ "(line 1,col 13) Annotations are not supported.",
+ "(line 1,col 1) Annotations are not supported."
+ );
+ }
+
+ @Test
+ public void novarargs() {
+ ParseResult<Parameter> result = javaParser.parse(PARAMETER, provider("String... x"));
+ assertProblems(result, "(line 1,col 1) Varargs are not supported.");
+ }
+
+ @Test
+ public void noforeach() {
+ ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("for(X x: xs){}"));
+ assertProblems(result, "(line 1,col 1) For-each loops are not supported.");
+ }
+
+ @Test
+ public void staticImport() {
+ ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("import static x;import static x.*;import x.X;import x.*;"));
+ assertProblems(result,
+ "(line 1,col 17) Static imports are not supported.",
+ "(line 1,col 1) Static imports are not supported.");
+ }
+
+ @Test
+ public void enumAllowedAsIdentifier() {
+ ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("int enum;"));
+ assertNoProblems(result);
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java5ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java5ValidatorTest.java
new file mode 100644
index 000000000..315167fda
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java5ValidatorTest.java
@@ -0,0 +1,155 @@
+package com.github.javaparser.ast.validator;
+
+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.CompilationUnit;
+import com.github.javaparser.ast.body.Parameter;
+import com.github.javaparser.ast.stmt.Statement;
+import org.junit.Test;
+
+import static com.github.javaparser.ParseStart.*;
+import static com.github.javaparser.ParseStart.COMPILATION_UNIT;
+import static com.github.javaparser.ParserConfiguration.LanguageLevel.*;
+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;
+
+public class Java5ValidatorTest {
+ public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_5));
+
+ @Test
+ public void genericsWithoutDiamond() {
+ ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X<A>{List<String> b = new ArrayList<>();}"));
+ assertProblems(result, "(line 1,col 33) The diamond operator is not supported.");
+ }
+
+ @Test
+ public void topAnnotationDeclaration() {
+ ParseResult<CompilationUnit> 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
+ public void nestedAnnotationDeclaration() {
+ ParseResult<CompilationUnit> 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
+ public void annotationMember() {
+ ParseResult<CompilationUnit> 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
+ public void topEnum() {
+ ParseResult<CompilationUnit> 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
+ public void nestedEnum() {
+ ParseResult<CompilationUnit> 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
+ public void varargs() {
+ ParseResult<Parameter> result = javaParser.parse(PARAMETER, provider("String... x"));
+ assertNoProblems(result);
+ }
+
+ @Test
+ public void foreach() {
+ ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("for(X x: xs){}"));
+ assertNoProblems(result);
+ }
+
+ @Test
+ public void staticImport() {
+ ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("import static x;import static x.*;import x.X;import x.*;"));
+ assertNoProblems(result);
+ }
+
+ @Test
+ public void noPrimitiveTypeArguments() {
+ ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X extends Y<int> {}"));
+ assertProblems(result, "(line 1,col 17) Type arguments may not be primitive.");
+ }
+
+ @Test
+ public void enumAllowedAsIdentifier() {
+ ParseResult<Statement> 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.");
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java6ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java6ValidatorTest.java
new file mode 100644
index 000000000..d066abe07
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java6ValidatorTest.java
@@ -0,0 +1,42 @@
+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.Test;
+
+import static com.github.javaparser.ParseStart.EXPRESSION;
+import static com.github.javaparser.ParseStart.STATEMENT;
+import static com.github.javaparser.ParserConfiguration.LanguageLevel.*;
+import static com.github.javaparser.Providers.provider;
+import static com.github.javaparser.utils.TestUtils.assertProblems;
+
+public class Java6ValidatorTest {
+ public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_6));
+
+ @Test
+ public void noStringsInSwitch() {
+ ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("switch(x){case \"abc\": ;}"));
+ assertProblems(result, "(line 1,col 16) Strings in switch statements are not supported.");
+ }
+
+ @Test
+ public void nobinaryIntegerLiterals() {
+ ParseResult<Expression> result = javaParser.parse(EXPRESSION, provider("0b01"));
+ assertProblems(result, "(line 1,col 1) Binary literal values are not supported.");
+ }
+
+ @Test
+ public void noUnderscoresInIntegerLiterals() {
+ ParseResult<Expression> result = javaParser.parse(EXPRESSION, provider("1_000_000"));
+ assertProblems(result, "(line 1,col 1) Underscores in literal values are not supported.");
+ }
+
+ @Test
+ public void noMultiCatch() {
+ ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("try{}catch(Abc|Def e){}"));
+ assertProblems(result, "(line 1,col 12) Multi-catch is not supported.");
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java7ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java7ValidatorTest.java
new file mode 100644
index 000000000..a2a03f837
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java7ValidatorTest.java
@@ -0,0 +1,107 @@
+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 org.junit.Test;
+
+import java.util.*;
+
+import static com.github.javaparser.ParseStart.COMPILATION_UNIT;
+import static com.github.javaparser.ParseStart.EXPRESSION;
+import static com.github.javaparser.ParseStart.STATEMENT;
+import static com.github.javaparser.ParserConfiguration.LanguageLevel.*;
+import static com.github.javaparser.Providers.provider;
+import static com.github.javaparser.utils.TestUtils.assertNoProblems;
+import static com.github.javaparser.utils.TestUtils.assertProblems;
+
+public class Java7ValidatorTest {
+ public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_7));
+
+ @Test
+ public void generics() {
+ ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X<A>{List<String> b = new ArrayList<>();}"));
+ assertNoProblems(result);
+ }
+
+ @Test
+ public void defaultMethodWithoutBody() {
+ ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("interface X {default void a();}"));
+ assertProblems(result, "(line 1,col 14) 'default' is not allowed here.");
+ }
+
+ @Test
+ public void tryWithoutAnything() {
+ ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("try{}"));
+ assertProblems(result, "(line 1,col 1) Try has no finally, no catch, and no resources.");
+ }
+
+ @Test
+ public void tryWithResourceVariableDeclaration() {
+ ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("try(Reader r = new Reader()){}"));
+ assertNoProblems(result);
+ }
+
+ @Test
+ public void tryWithResourceReference() {
+ ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("try(a.b.c){}"));
+ assertProblems(result, "(line 1,col 1) Try with resources only supports variable declarations.");
+ }
+
+ @Test
+ public void stringsInSwitch() {
+ ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("switch(x){case \"abc\": ;}"));
+ assertNoProblems(result);
+ }
+
+ @Test
+ public void binaryIntegerLiterals() {
+ ParseResult<Expression> result = javaParser.parse(EXPRESSION, provider("0b01"));
+ assertNoProblems(result);
+ }
+
+ @Test
+ public void underscoresInIntegerLiterals() {
+ ParseResult<Expression> result = javaParser.parse(EXPRESSION, provider("1_000_000"));
+ assertNoProblems(result);
+ }
+
+ @Test
+ public void multiCatch() {
+ ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("try{}catch(Abc|Def e){}"));
+ assertNoProblems(result);
+ }
+
+ @Test
+ public void multiCatchWithoutElements() {
+ UnionType unionType = new UnionType();
+
+ List<Problem> problems = new ArrayList<>();
+ new Java7Validator().accept(unionType, new ProblemReporter(problems::add));
+
+ assertProblems(problems, "UnionType.elements can not be empty.");
+ }
+
+ @Test
+ public void multiCatchWithOneElement() {
+ UnionType unionType = new UnionType();
+ unionType.getElements().add(new ClassOrInterfaceType());
+
+ List<Problem> problems = new ArrayList<>();
+ new Java7Validator().accept(unionType, new ProblemReporter(problems::add));
+
+ assertProblems(problems, "Union type (multi catch) must have at least two elements.");
+ }
+
+ @Test
+ public void noLambdas() {
+ ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("a(() -> 1);"));
+ assertProblems(result, "(line 1,col 3) Lambdas are not supported.");
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java8ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java8ValidatorTest.java
new file mode 100644
index 000000000..216fb5b13
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java8ValidatorTest.java
@@ -0,0 +1,82 @@
+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.Test;
+
+import static com.github.javaparser.ParseStart.COMPILATION_UNIT;
+import static com.github.javaparser.ParseStart.STATEMENT;
+import static com.github.javaparser.ParserConfiguration.LanguageLevel.*;
+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;
+
+public class Java8ValidatorTest {
+ public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_8));
+
+ @Test
+ public void localInterface() {
+ ParseResult<CompilationUnit> 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.");
+ }
+
+ @Test
+ public void lambdaParameter() {
+ ParseResult<CompilationUnit> 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
+ public void interfaceMethod() {
+ ParseResult<CompilationUnit> 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
+ public void defaultMethodWithoutBody() {
+ ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("interface X {default void a();}"));
+ assertProblems(result, "(line 1,col 14) 'default' methods must have a body.");
+ }
+
+ @Test
+ public void lambdas() {
+ ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("a(() -> 1);"));
+ assertNoProblems(result);
+ }
+
+ @Test
+ public void noModules() {
+ ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("open module x {}"));
+ assertProblems(result, "(line 1,col 1) Modules are not supported.");
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java9ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java9ValidatorTest.java
new file mode 100644
index 000000000..911f6a984
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java9ValidatorTest.java
@@ -0,0 +1,79 @@
+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.Test;
+
+import static com.github.javaparser.ParseStart.COMPILATION_UNIT;
+import static com.github.javaparser.ParseStart.STATEMENT;
+import static com.github.javaparser.ParserConfiguration.LanguageLevel.*;
+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;
+
+public class Java9ValidatorTest {
+ public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_9));
+
+ @Test
+ public void underscoreIdentifiers() {
+ ParseResult<Statement> 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
+ public void moduleRequires() {
+ ParseResult<CompilationUnit> 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
+ public void interfaceMethod() {
+ ParseResult<CompilationUnit> 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
+ public void modules() {
+ ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("open module x {}"));
+ assertNoProblems(result);
+ }
+
+ @Test
+ public void tryWithResourceReference() {
+ ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("try(a.b.c){}"));
+ assertNoProblems(result);
+ }
+
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/CloneVisitorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/CloneVisitorTest.java
new file mode 100644
index 000000000..e59661170
--- /dev/null
+++ b/javaparser-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-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package 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.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.Iterator;
+
+import static com.github.javaparser.JavaParser.*;
+import static org.junit.Assert.assertEquals;
+
+public class CloneVisitorTest {
+ CompilationUnit cu;
+
+ @Before
+ public void setUp() {
+ cu = new CompilationUnit();
+ }
+
+ @After
+ public void teardown() {
+ cu = null;
+ }
+
+ @Test
+ public void cloneJavaDocTest() {
+ NodeList<BodyDeclaration<?>> 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<TypeDeclaration<?>> 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<TypeDeclaration<?>> typeDeclarationListClone = cuClone.getTypes();
+ Iterator<TypeDeclaration<?>> typeItr = typeDeclarationListClone.iterator();
+ TypeDeclaration<?> typeDeclaration;
+ while (typeItr.hasNext()) {
+ typeDeclaration = typeItr.next();
+ if (typeDeclaration.getMembers() == null) {
+ assertEquals(typeDeclaration.getComment().get().getContent(), " javadoc");
+ } else {
+ Iterator<BodyDeclaration<?>> bodyItr = typeDeclaration.getMembers().iterator();
+ while (bodyItr.hasNext()) {
+ BodyDeclaration<?> bodyDeclaration = bodyItr.next();
+ assertEquals(bodyDeclaration.getComment().get().getContent(), " javadoc");
+ }
+ }
+ }
+ }
+
+ @Test
+ public void cloneAnnotationOnWildcardTypeArgument() {
+ Type type = parseType("List<@C ? extends Object>").clone();
+ assertEquals("List<@C ? extends Object>", type.toString());
+ }
+
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/HashCodeVisitorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/HashCodeVisitorTest.java
new file mode 100644
index 000000000..679fb1d62
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/HashCodeVisitorTest.java
@@ -0,0 +1,24 @@
+package com.github.javaparser.ast.visitor;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.ast.CompilationUnit;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+
+public class HashCodeVisitorTest {
+ @Test
+ public void testEquals() {
+ CompilationUnit p1 = JavaParser.parse("class X { }");
+ CompilationUnit p2 = JavaParser.parse("class X { }");
+ assertEquals(p1.hashCode(), p2.hashCode());
+ }
+
+ @Test
+ public void testNotEquals() {
+ CompilationUnit p1 = JavaParser.parse("class X { }");
+ CompilationUnit p2 = JavaParser.parse("class Y { }");
+ assertNotEquals(p1.hashCode(), p2.hashCode());
+ }
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/ModifierVisitorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/ModifierVisitorTest.java
new file mode 100644
index 000000000..ada0c6f98
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/ModifierVisitorTest.java
@@ -0,0 +1,127 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.ast.visitor;
+
+import com.github.javaparser.JavaParser;
+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 org.junit.Test;
+
+import static com.github.javaparser.JavaParser.parseExpression;
+import static com.github.javaparser.utils.Utils.EOL;
+import static org.junit.Assert.assertEquals;
+
+public class ModifierVisitorTest {
+ @Test
+ public void makeSureParentListsCanBeModified() {
+ NodeList<StringLiteralExpr> 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<Void>() {
+ @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
+ public void binaryExprReturnsLeftExpressionWhenRightSideIsRemoved() {
+ Expression expression = parseExpression("1+2");
+ Visitable result = expression.accept(new ModifierVisitor<Void>() {
+ public Visitable visit(IntegerLiteralExpr integerLiteralExpr, Void arg) {
+ if (integerLiteralExpr.getValue().equals("1")) {
+ return null;
+ }
+ return integerLiteralExpr;
+ }
+ }, null);
+ assertEquals("2", result.toString());
+ }
+
+ @Test
+ public void binaryExprReturnsRightExpressionWhenLeftSideIsRemoved() {
+ final Expression expression = parseExpression("1+2");
+ final Visitable result = expression.accept(new ModifierVisitor<Void>() {
+ public Visitable visit(IntegerLiteralExpr integerLiteralExpr, Void arg) {
+ if (integerLiteralExpr.getValue().equals("2")) {
+ return null;
+ }
+ return integerLiteralExpr;
+ }
+ }, null);
+ assertEquals("1", result.toString());
+ }
+
+ @Test
+ public void fieldDeclarationCantSurviveWithoutVariables() {
+ final BodyDeclaration<?> bodyDeclaration = JavaParser.parseBodyDeclaration("int x=1;");
+
+ final Visitable result = bodyDeclaration.accept(new ModifierVisitor<Void>() {
+ public Visitable visit(VariableDeclarator x, Void arg) {
+ return null;
+ }
+ }, null);
+
+ assertEquals(null, result);
+ }
+
+ @Test
+ public void variableDeclarationCantSurviveWithoutVariables() {
+ final BodyDeclaration<?> bodyDeclaration = JavaParser.parseBodyDeclaration("void x() {int x=1;}");
+
+ final Visitable result = bodyDeclaration.accept(new ModifierVisitor<Void>() {
+ public Visitable visit(VariableDeclarator x, Void arg) {
+ return null;
+ }
+ }, null);
+
+ assertEquals("void x() {" + EOL + "}", result.toString());
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/NoCommentEqualsVisitorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/NoCommentEqualsVisitorTest.java
new file mode 100644
index 000000000..1e2cdf810
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/NoCommentEqualsVisitorTest.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.ast.visitor;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.ast.CompilationUnit;
+
+public class NoCommentEqualsVisitorTest {
+
+ @Test
+ public void testEquals() {
+ CompilationUnit p1 = JavaParser.parse("class X { }");
+ CompilationUnit p2 = JavaParser.parse("class X { }");
+ assertTrue(NoCommentEqualsVisitor.equals(p1, p2));
+ }
+
+ @Test
+ public void testEqualsWithDifferentComments() {
+ CompilationUnit p1 = JavaParser.parse("/* a */ class X { /** b */} //c");
+ CompilationUnit p2 = JavaParser.parse("/* b */ class X { } //c");
+ assertTrue(NoCommentEqualsVisitor.equals(p1, p2));
+ }
+
+ @Test
+ public void testNotEquals() {
+ CompilationUnit p1 = JavaParser.parse("class X { }");
+ CompilationUnit p2 = JavaParser.parse("class Y { }");
+ assertFalse(NoCommentEqualsVisitor.equals(p1, p2));
+ }
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/NoCommentHashCodeVisitorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/NoCommentHashCodeVisitorTest.java
new file mode 100644
index 000000000..506566984
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/NoCommentHashCodeVisitorTest.java
@@ -0,0 +1,34 @@
+package com.github.javaparser.ast.visitor;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.ast.CompilationUnit;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+
+public class NoCommentHashCodeVisitorTest {
+
+ @Test
+ public void testEquals() {
+ CompilationUnit p1 = JavaParser.parse("class X { }");
+ CompilationUnit p2 = JavaParser.parse("class X { }");
+ assertEquals(p1.hashCode(), p2.hashCode());
+ }
+
+ @Test
+ public void testEqualsWithDifferentComments() {
+ CompilationUnit p1 = JavaParser.parse("/* a */ class X { /** b */} //c");
+ CompilationUnit p2 = JavaParser.parse("/* b */ class X { } //c");
+ assertEquals(p1.hashCode(), p2.hashCode());
+ assertEquals(p1.getComments().size(), 3);
+ assertEquals(p2.getComments().size(), 2);
+ }
+
+ @Test
+ public void testNotEquals() {
+ CompilationUnit p1 = JavaParser.parse("class X { }");
+ CompilationUnit p2 = JavaParser.parse("class Y { }");
+ assertNotEquals(p1.hashCode(), p2.hashCode());
+ }
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/TreeVisitorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/TreeVisitorTest.java
new file mode 100644
index 000000000..53d375336
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/TreeVisitorTest.java
@@ -0,0 +1,158 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.ast.visitor;
+
+import com.github.javaparser.JavaParser;
+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.Test;
+
+import static com.github.javaparser.utils.TestUtils.assertEqualsNoEol;
+import static org.junit.Assert.assertEquals;
+
+public class TreeVisitorTest {
+ @Test
+ public void isValidBreadthFirstTraversal() {
+ Expression expression = JavaParser.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
+ public void issue743ConcurrentModificationProblem() {
+ Expression expression = JavaParser.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
+ public void isValidPreOrderTraversal() {
+ StringBuilder result = new StringBuilder();
+ new TreeVisitor() {
+ @Override
+ public void process(Node node) {
+ result.append("<").append(node).append("> ");
+ }
+ }.visitPreOrder(JavaParser.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
+ public void isValidPostOrderTraversal() {
+ StringBuilder result = new StringBuilder();
+ new TreeVisitor() {
+ @Override
+ public void process(Node node) {
+ result.append("<").append(node).append("> ");
+ }
+ }.visitPostOrder(JavaParser.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
+ public 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(JavaParser.parseExpression("new int[]{1,2,3,4}"));
+ }
+
+ @Test
+ public 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(JavaParser.parseExpression("new int[]{1,2,3,4}"));
+ }
+
+ @Test
+ public void parents() {
+ CompilationUnit cu = JavaParser.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());
+ assertEqualsNoEol("class X {\n" +
+ "\n" +
+ " int x = 1;\n" +
+ "}", visitor.next().toString());
+ assertEqualsNoEol("class X {\n" +
+ "\n" +
+ " int x = 1;\n" +
+ "}\n", visitor.next().toString());
+ assertEquals(false, visitor.hasNext());
+ }
+
+ @Test
+ public void isValidDirectChildrenTraversal() {
+ Expression expression = JavaParser.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-testing/src/test/java/com/github/javaparser/bdd/BasicJBehaveTest.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/BasicJBehaveTest.java
new file mode 100644
index 000000000..4e0fe6a6e
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/BasicJBehaveTest.java
@@ -0,0 +1,65 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.bdd;
+
+
+import com.github.valfirst.jbehave.junit.monitoring.JUnitReportingRunner;
+import org.jbehave.core.configuration.Configuration;
+import org.jbehave.core.configuration.MostUsefulConfiguration;
+import org.jbehave.core.failures.FailingUponPendingStep;
+import org.jbehave.core.io.LoadFromClasspath;
+import org.jbehave.core.io.StoryFinder;
+import org.jbehave.core.junit.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;
+
+ public BasicJBehaveTest(String storiesPath) {
+ this.storiesPath = storiesPath;
+ JUnitReportingRunner.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<String> storyPaths() {
+ return new StoryFinder().findPaths(codeLocationFromClass(this.getClass()), storiesPath, "");
+ }
+
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/bdd/CommentParsingTest.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/CommentParsingTest.java
new file mode 100644
index 000000000..1ff3619f2
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/CommentParsingTest.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.bdd;
+
+import com.github.javaparser.bdd.steps.CommentParsingSteps;
+import com.github.valfirst.jbehave.junit.monitoring.JUnitReportingRunner;
+import org.jbehave.core.steps.InjectableStepsFactory;
+import org.jbehave.core.steps.InstanceStepsFactory;
+import org.junit.runner.RunWith;
+
+@RunWith(JUnitReportingRunner.class)
+public class CommentParsingTest extends BasicJBehaveTest {
+
+ @Override
+ public InjectableStepsFactory stepsFactory() {
+ return new InstanceStepsFactory(configuration(), new CommentParsingSteps());
+ }
+
+ public CommentParsingTest() {
+ super("**/bdd/comment*.story");
+ }
+}
+
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/bdd/ComparingTest.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/ComparingTest.java
new file mode 100644
index 000000000..4ecafd764
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/ComparingTest.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.bdd;
+
+import com.github.javaparser.bdd.steps.ComparingSteps;
+import com.github.javaparser.bdd.steps.SharedSteps;
+import com.github.valfirst.jbehave.junit.monitoring.JUnitReportingRunner;
+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(JUnitReportingRunner.class)
+public class ComparingTest extends BasicJBehaveTest {
+
+ @Override
+ public InjectableStepsFactory stepsFactory() {
+ Map<String, Object> state = new HashMap<>();
+
+ return new InstanceStepsFactory(configuration(),
+ new SharedSteps(state),
+ new ComparingSteps());
+ }
+
+ public ComparingTest() {
+ super("**/bdd/comparing*.story");
+ }
+}
+
+
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/bdd/ManipulationTest.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/ManipulationTest.java
new file mode 100644
index 000000000..0f24632e9
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/ManipulationTest.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.bdd;
+
+import com.github.javaparser.bdd.steps.ManipulationSteps;
+import com.github.javaparser.bdd.steps.SharedSteps;
+import com.github.valfirst.jbehave.junit.monitoring.JUnitReportingRunner;
+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(JUnitReportingRunner.class)
+public class ManipulationTest extends BasicJBehaveTest {
+
+ @Override
+ public InjectableStepsFactory stepsFactory() {
+ Map<String, Object> state = new HashMap<>();
+
+ return new InstanceStepsFactory(configuration(),
+ new SharedSteps(state),
+ new ManipulationSteps(state));
+ }
+
+ public ManipulationTest() {
+ super("**/bdd/manipulation*.story");
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/bdd/ParsingTest.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/ParsingTest.java
new file mode 100644
index 000000000..d05d57a85
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/ParsingTest.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.bdd;
+
+import com.github.javaparser.bdd.steps.ParsingSteps;
+import com.github.javaparser.bdd.steps.SharedSteps;
+import com.github.valfirst.jbehave.junit.monitoring.JUnitReportingRunner;
+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(JUnitReportingRunner.class)
+public class ParsingTest extends BasicJBehaveTest {
+
+ @Override
+ public InjectableStepsFactory stepsFactory() {
+ Map<String, Object> state = new HashMap<>();
+
+ return new InstanceStepsFactory(configuration(),
+ new SharedSteps(state),
+ new ParsingSteps(state));
+ }
+
+ public ParsingTest() {
+ super("**/bdd/parsing*.story");
+ }
+}
+
+
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/bdd/PositionRangeTest.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/PositionRangeTest.java
new file mode 100644
index 000000000..e7f5b2849
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/PositionRangeTest.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.bdd;
+
+import com.github.javaparser.bdd.steps.PositionRangeSteps;
+import com.github.javaparser.bdd.steps.SharedSteps;
+import com.github.valfirst.jbehave.junit.monitoring.JUnitReportingRunner;
+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(JUnitReportingRunner.class)
+public class PositionRangeTest extends BasicJBehaveTest {
+
+ @Override
+ public InjectableStepsFactory stepsFactory() {
+ Map<String, Object> state = new HashMap<>();
+
+ return new InstanceStepsFactory(configuration(),
+ new SharedSteps(state),
+ new PositionRangeSteps());
+ }
+
+ public PositionRangeTest() {
+ super("**/bdd/position_range*.story");
+ }
+}
+
+
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/bdd/PrettyPrintingTest.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/PrettyPrintingTest.java
new file mode 100644
index 000000000..7540d3b9d
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/PrettyPrintingTest.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.bdd;
+
+import com.github.javaparser.bdd.steps.PrettyPrintingSteps;
+import com.github.valfirst.jbehave.junit.monitoring.JUnitReportingRunner;
+import org.jbehave.core.steps.InjectableStepsFactory;
+import org.jbehave.core.steps.InstanceStepsFactory;
+import org.junit.runner.RunWith;
+
+@RunWith(JUnitReportingRunner.class)
+public class PrettyPrintingTest extends BasicJBehaveTest {
+
+ @Override
+ public InjectableStepsFactory stepsFactory() {
+ return new InstanceStepsFactory(configuration(), new PrettyPrintingSteps());
+ }
+
+ public PrettyPrintingTest() {
+ super("**/bdd/pretty_printing*.story");
+ }
+}
+
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/bdd/TestUtils.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/TestUtils.java
new file mode 100644
index 000000000..784a113de
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/TestUtils.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.bdd;
+
+import java.io.InputStream;
+
+public class TestUtils {
+
+ public static InputStream getSampleStream(String sampleName) {
+ InputStream is = TestUtils.class.getClassLoader().getResourceAsStream("com/github/javaparser/bdd/samples/"
+ + sampleName + ".java");
+ if (is == null) {
+ throw new RuntimeException("Example not found, check your test. Sample name: " + sampleName);
+ }
+ return is;
+ }
+
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/bdd/VisitorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/VisitorTest.java
new file mode 100644
index 000000000..442c2edcf
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/VisitorTest.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.bdd;
+
+import com.github.javaparser.bdd.steps.SharedSteps;
+import com.github.javaparser.bdd.steps.VisitorSteps;
+import com.github.valfirst.jbehave.junit.monitoring.JUnitReportingRunner;
+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(JUnitReportingRunner.class)
+public class VisitorTest extends BasicJBehaveTest {
+
+ @Override
+ public InjectableStepsFactory stepsFactory() {
+ Map<String, Object> state = new HashMap<>();
+ return new InstanceStepsFactory(configuration(),
+ new SharedSteps(state),
+ new VisitorSteps(state));
+ }
+
+ public VisitorTest() {
+ super("**/bdd/visitor*.story");
+ }
+}
+
+
+
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/CommentParsingSteps.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/CommentParsingSteps.java
new file mode 100644
index 000000000..3257c4342
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/CommentParsingSteps.java
@@ -0,0 +1,431 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.bdd.steps;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.ParseResult;
+import com.github.javaparser.ParserConfiguration;
+import com.github.javaparser.Range;
+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.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.io.IOException;
+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.bdd.TestUtils.getSampleStream;
+import static com.github.javaparser.bdd.steps.SharedSteps.getMemberByTypeAndPosition;
+import static org.hamcrest.CoreMatchers.*;
+import static org.hamcrest.text.IsEqualIgnoringWhiteSpace.equalToIgnoringWhiteSpace;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.fail;
+
+public class CommentParsingSteps {
+
+ private CompilationUnit compilationUnit;
+ private CommentsCollection commentsCollection;
+ private String sourceUnderTest;
+ private ParserConfiguration configuration = new ParserConfiguration();
+ private PrettyPrinter 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) throws IOException {
+ sourceUnderTest = null;
+ ParseResult<CompilationUnit> parseResult = new JavaParser(new ParserConfiguration()).parse(COMPILATION_UNIT, provider(getSampleStream(sampleName), Charset.forName(encoding)));
+ commentsCollection = parseResult.getCommentsCollection().orElse(new CommentsCollection());
+ }
+
+ @When("the class is parsed by the comment parser")
+ public void whenTheClassIsParsedByTheCommentParser() throws IOException {
+ ParseResult<CompilationUnit> 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.setDoNotConsiderAnnotationsAsNodeStartForCodeAttribution(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<CompilationUnit> 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<CompilationUnit> 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 extends Comment> T getCommentAt(Set<T> set, int index) {
+ Iterator<T> 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(equalToIgnoringWhiteSpace(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(equalToIgnoringWhiteSpace(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(equalToIgnoringWhiteSpace(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(equalToIgnoringWhiteSpace(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(equalToIgnoringWhiteSpace(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(), equalToIgnoringWhiteSpace(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(equalToIgnoringWhiteSpace(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(equalToIgnoringWhiteSpace(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(equalToIgnoringWhiteSpace(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(equalToIgnoringWhiteSpace(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-testing/src/test/java/com/github/javaparser/bdd/steps/ComparingSteps.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/ComparingSteps.java
new file mode 100644
index 000000000..4b789a797
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/ComparingSteps.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.bdd.steps;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.ast.CompilationUnit;
+import org.jbehave.core.annotations.Given;
+import org.jbehave.core.annotations.Then;
+
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+public class ComparingSteps {
+
+ private CompilationUnit first;
+ private CompilationUnit second;
+
+ /*
+ * Given steps
+ */
+
+ @Given("the first class:$classSrc")
+ public void givenTheFirstClass(String classSrc) {
+ this.first = JavaParser.parse(classSrc.trim());
+ }
+
+ @Given("the second class:$classSrc")
+ public void givenTheSecondClass(String classSrc) {
+ this.second = JavaParser.parse(classSrc.trim());
+ }
+
+ /*
+ * Then steps
+ */
+
+ @Then("they are equals")
+ public void thenTheyAreEquals() {
+ assertThat(first, is(equalTo(second)));
+ }
+
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/ExistenceOfParentNodeVerifier.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/ExistenceOfParentNodeVerifier.java
new file mode 100644
index 000000000..27d81b57f
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/ExistenceOfParentNodeVerifier.java
@@ -0,0 +1,542 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.bdd.steps;
+
+import com.github.javaparser.HasParentNode;
+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.stmt.*;
+import com.github.javaparser.ast.type.*;
+import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
+
+import static org.hamcrest.Matchers.notNullValue;
+import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.assertThat;
+
+/**
+ * The <code>ExistenceOfParentNodeVerifier</code> 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<Void> {
+ 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(SwitchEntryStmt 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(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-testing/src/test/java/com/github/javaparser/bdd/steps/ManipulationSteps.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/ManipulationSteps.java
new file mode 100644
index 000000000..557bf0d60
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/ManipulationSteps.java
@@ -0,0 +1,286 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.bdd.steps;
+
+import com.github.javaparser.JavaParser;
+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.ClassOrInterfaceType;
+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.EnumSet;
+import java.util.Map;
+
+import static com.github.javaparser.JavaParser.parseClassOrInterfaceType;
+import static com.github.javaparser.JavaParser.parseName;
+import static com.github.javaparser.ast.NodeList.nodeList;
+import static com.github.javaparser.ast.type.PrimitiveType.*;
+import static com.github.javaparser.bdd.steps.SharedSteps.getMethodByPositionAndClassPosition;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertThat;
+
+public class ManipulationSteps {
+
+ /* Fields used to maintain step state within this step class */
+ private BlockStmt blockStmt;
+ private Statement statement;
+ private TryStmt tryStmt;
+ private NodeList<Expression> 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<String, Object> state;
+
+ public ManipulationSteps(Map<String, Object> 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 = JavaParser.parseBlock(value);
+ }
+
+ @When("is the String \"$value\" is parsed by the JavaParser using parseStatement")
+ public void whenIsTheStringIsParsedByTheJavaParserUsingParseStatement(String value) {
+ statement = JavaParser.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(EnumSet.of(Modifier.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);
+ EnumSet<Modifier> modifiers = EnumSet.of(Modifier.PUBLIC);
+ MethodDeclaration method = new MethodDeclaration(modifiers, new VoidType(), methodName);
+ modifiers.add(Modifier.STATIC);
+ 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() throws CloneNotSupportedException {
+ 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<Void> {
+ @Override
+ public void visit(MethodDeclaration n, Void arg) {
+ n.setName(n.getNameAsString().toUpperCase());
+ }
+ }
+
+ private static class AddNewIntParameterCalledValueVisitor extends VoidVisitorAdapter<Void> {
+ @Override
+ public void visit(MethodDeclaration n, Void arg) {
+ n.addParameter(intType(), "value");
+ }
+ }
+}
+
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/ParsingSteps.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/ParsingSteps.java
new file mode 100644
index 000000000..01631c6c0
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/ParsingSteps.java
@@ -0,0 +1,343 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.bdd.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.bdd.steps.SharedSteps.getMemberByTypeAndPosition;
+import static com.github.javaparser.bdd.steps.SharedSteps.getMethodByPositionAndClassPosition;
+import static java.lang.String.format;
+import static org.hamcrest.core.Is.is;
+import static org.hamcrest.core.IsNull.notNullValue;
+import static org.junit.Assert.*;
+
+public class ParsingSteps {
+
+ private Map<String, Object> state;
+
+ public ParsingSteps(Map<String, Object> 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<CompilationUnit> 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<? extends Node> nodeType) {
+ CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1");
+ List<? extends Node> 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-testing/src/test/java/com/github/javaparser/bdd/steps/PositionRangeSteps.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/PositionRangeSteps.java
new file mode 100644
index 000000000..0d7fd896d
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/PositionRangeSteps.java
@@ -0,0 +1,129 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.bdd.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.Position.pos;
+import static com.github.javaparser.Range.range;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.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 = pos(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 = pos(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-testing/src/test/java/com/github/javaparser/bdd/steps/PrettyPrintingSteps.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/PrettyPrintingSteps.java
new file mode 100644
index 000000000..1dcd802a5
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/PrettyPrintingSteps.java
@@ -0,0 +1,114 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.bdd.steps;
+
+import com.github.javaparser.ParseException;
+import com.github.javaparser.ast.CompilationUnit;
+import com.github.javaparser.ast.Node;
+import com.github.javaparser.ast.visitor.ModifierVisitor;
+import com.github.javaparser.printer.PrettyPrinterConfiguration;
+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.JavaParser.*;
+import static com.github.javaparser.utils.Utils.readerToString;
+import static org.junit.Assert.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, ParseException {
+ 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<Void>() {
+ }).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-testing/src/test/java/com/github/javaparser/bdd/steps/SharedSteps.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/SharedSteps.java
new file mode 100644
index 000000000..53b7c4434
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/SharedSteps.java
@@ -0,0 +1,163 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.bdd.steps;
+
+import com.github.javaparser.JavaParser;
+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 org.hamcrest.core.Is.is;
+import static org.hamcrest.core.IsEqual.equalTo;
+import static org.hamcrest.core.IsNot.not;
+import static org.hamcrest.text.IsEqualIgnoringWhiteSpace.equalToIgnoringWhiteSpace;
+import static org.junit.Assert.assertThat;
+
+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<String, Object> state;
+
+ public SharedSteps(Map<String, Object> 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", JavaParser.parse(classSrc.trim()));
+ }
+
+ @When("the following source is parsed (trimming space):$classSrc")
+ public void whenTheFollowingSourceIsParsedTrimmingSpace(String classSrc) {
+ state.put("cu1", JavaParser.parse(classSrc.trim()));
+ }
+
+ @When("the following sources is parsed by the second CompilationUnit:$classSrc")
+ public void whenTheFollowingSourcesIsParsedBytTheSecondCompilationUnit(String classSrc) {
+ state.put("cu2", JavaParser.parse(classSrc.trim()));
+ }
+
+ @When("file \"$fileName\" is parsed")
+ public void whenTheJavaFileIsParsed(String fileName) throws IOException, URISyntaxException {
+ URL url = getClass().getResource("../samples/" + fileName);
+ CompilationUnit compilationUnit = JavaParser.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(equalToIgnoringWhiteSpace(classSrc)));
+ }
+
+ public static <T extends BodyDeclaration<?>> T getMemberByTypeAndPosition(TypeDeclaration<?> typeDeclaration, int position, Class<T> 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-testing/src/test/java/com/github/javaparser/bdd/steps/VisitorSteps.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/VisitorSteps.java
new file mode 100644
index 000000000..ba20eaf16
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/VisitorSteps.java
@@ -0,0 +1,171 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.bdd.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.bdd.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<AtomicReference<String>> toUpperCaseVariableNameVisitor;
+ private VoidVisitorAdapter<AtomicReference<String>> collectVariableNameVisitor;
+ private PositionTestVisitor positionTestVisitor;
+ private GenericVisitorAdapter<String, Void> nameReturningVisitor;
+ private GenericListVisitorAdapter<String, Void> allNameReturningVisitor;
+ private AtomicReference<String> collectedVariableName;
+ private String returnedVariableName;
+ private List<String> returnedVariableNames;
+
+ /* Map that maintains shares state across step classes. If manipulating the objects in the map you must update the state */
+ private Map<String, Object> state;
+
+ public VisitorSteps(Map<String, Object> state) {
+ this.state = state;
+ }
+
+ @Given("a VoidVisitorAdapter with a visit method that changes variable names to uppercase")
+ public void givenAVoidVisitorAdapterWithAVisitMethodThatChangesVariableNamesToUppercase() {
+ toUpperCaseVariableNameVisitor = new VoidVisitorAdapter<AtomicReference<String>>() {
+ @Override
+ public void visit(VariableDeclarator n, AtomicReference<String> arg) {
+ n.setName(n.getNameAsString().toUpperCase());
+ }
+ };
+ }
+
+ @Given("a VoidVisitorAdapter with a visit method and collects the variable names")
+ public void givenAVoidVisitorAdapterWithAVisitMethodThatCollectsTheVariableName() {
+ collectVariableNameVisitor = new VoidVisitorAdapter<AtomicReference<String>>() {
+ @Override
+ public void visit(VariableDeclarator n, AtomicReference<String> arg) {
+ arg.set(arg.get() + n.getName() + ";");
+ }
+
+ @Override
+ public void visit(Parameter n, AtomicReference<String> arg) {
+ arg.set(arg.get() + n.getName() + ";");
+ }
+ };
+ }
+
+ @Given("a GenericVisitorAdapter with a visit method that returns variable names")
+ public void givenAGenericVisitorAdapterWithAVisitMethodThatReturnsVariableNames() {
+ nameReturningVisitor = new GenericVisitorAdapter<String, Void>() {
+ @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<String, Void>() {
+ @Override
+ public List<String> 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-testing/src/test/java/com/github/javaparser/bdd/visitors/PositionTestVisitor.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/visitors/PositionTestVisitor.java
new file mode 100644
index 000000000..bfa331fd8
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/visitors/PositionTestVisitor.java
@@ -0,0 +1,553 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.bdd.visitors;
+
+import com.github.javaparser.Position;
+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.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<Object> {
+
+ 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 SwitchEntryStmt 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 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-testing/src/test/java/com/github/javaparser/builders/ClassOrInterfaceDeclarationBuildersTest.java b/javaparser-testing/src/test/java/com/github/javaparser/builders/ClassOrInterfaceDeclarationBuildersTest.java
new file mode 100644
index 000000000..aff535476
--- /dev/null
+++ b/javaparser-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-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.builders;
+
+import com.github.javaparser.ast.CompilationUnit;
+import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.List;
+import java.util.function.Function;
+
+import static com.github.javaparser.utils.Utils.EOL;
+import static org.junit.Assert.assertEquals;
+
+public class ClassOrInterfaceDeclarationBuildersTest {
+ CompilationUnit cu;
+
+ @Before
+ public void setup() {
+ cu = new CompilationUnit();
+ }
+
+ @After
+ public void teardown() {
+ cu = null;
+ }
+
+ @Test
+ public void testAddExtends() {
+ ClassOrInterfaceDeclaration testClass = cu.addClass("test");
+ testClass.addExtendedType(List.class);
+ assertEquals(1, cu.getImports().size());
+ assertEquals("import " + List.class.getName() + ";" + EOL,
+ cu.getImport(0).toString());
+ assertEquals(1, testClass.getExtendedTypes().size());
+ assertEquals(List.class.getSimpleName(), testClass.getExtendedTypes(0).getNameAsString());
+ }
+
+ @Test
+ public void testAddImplements() {
+ ClassOrInterfaceDeclaration testClass = cu.addClass("test");
+ testClass.addImplementedType(Function.class);
+ assertEquals(1, cu.getImports().size());
+ assertEquals("import " + Function.class.getName() + ";" + EOL,
+ cu.getImport(0).toString());
+ assertEquals(1, testClass.getImplementedTypes().size());
+ assertEquals(Function.class.getSimpleName(), testClass.getImplementedTypes(0).getNameAsString());
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/builders/CompilationUnitBuildersTest.java b/javaparser-testing/src/test/java/com/github/javaparser/builders/CompilationUnitBuildersTest.java
new file mode 100644
index 000000000..11ac7e957
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/builders/CompilationUnitBuildersTest.java
@@ -0,0 +1,134 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.builders;
+
+import static com.github.javaparser.utils.Utils.EOL;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.List;
+import java.util.Map;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import com.github.javaparser.ast.CompilationUnit;
+import com.github.javaparser.ast.Modifier;
+import com.github.javaparser.ast.body.AnnotationDeclaration;
+import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
+import com.github.javaparser.ast.body.EnumDeclaration;
+
+public class CompilationUnitBuildersTest {
+ private final CompilationUnit cu = new CompilationUnit();
+
+ @Test
+ public void testAddImport() {
+ cu.addImport(Map.class);
+ cu.addImport(Map.class);
+ cu.addImport(List.class);
+ assertEquals(2, cu.getImports().size());
+ cu.addImport("myImport");
+ assertEquals(3, cu.getImports().size());
+ assertEquals("import " + Map.class.getName() + ";" + EOL, cu.getImport(0).toString());
+ assertEquals("import " + List.class.getName() + ";" + EOL, cu.getImport(1).toString());
+ assertEquals("import myImport;" + EOL, cu.getImport(2).toString());
+ }
+
+ class testInnerClass {
+
+ }
+
+ @Test
+ public void testAddImportAnonymousClass() {
+ cu.addImport(testInnerClass.class);
+ assertEquals("import " + testInnerClass.class.getName().replace("$", ".") + ";" + EOL,
+ cu.getImport(0).toString());
+ }
+
+ @Test(expected = RuntimeException.class)
+ public void testAddImportInnerClass() {
+ Object anonymous = new Object() {
+
+ };
+ cu.addImport(anonymous.getClass());
+ }
+
+ @Test
+ public void testAddClass() {
+ ClassOrInterfaceDeclaration myClassDeclaration = cu.addClass("testClass", Modifier.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
+ public 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
+ public 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
+ public 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
+ public void testGetClassByName() {
+ assertEquals(cu.addClass("test"), cu.getClassByName("test").get());
+ }
+
+ @Test
+ public void testGetInterfaceByName() {
+ assertEquals(cu.addInterface("test"), cu.getInterfaceByName("test").get());
+ }
+
+ @Test
+ public void testGetEnumByName() {
+ assertEquals(cu.addEnum("test"), cu.getEnumByName("test").get());
+ }
+
+ @Test
+ public void testGetAnnotationDeclarationByName() {
+ assertEquals(cu.addAnnotationDeclaration("test"), cu.getAnnotationDeclarationByName("test").get());
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/builders/EnumDeclarationBuildersTest.java b/javaparser-testing/src/test/java/com/github/javaparser/builders/EnumDeclarationBuildersTest.java
new file mode 100644
index 000000000..048307d75
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/builders/EnumDeclarationBuildersTest.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.builders;
+
+import com.github.javaparser.ast.CompilationUnit;
+import com.github.javaparser.ast.body.EnumDeclaration;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.function.Function;
+
+import static com.github.javaparser.utils.Utils.EOL;
+import static org.junit.Assert.assertEquals;
+
+public class EnumDeclarationBuildersTest {
+ private final CompilationUnit cu = new CompilationUnit();
+
+ @Test
+ public void testAddImplements() {
+ EnumDeclaration testEnum = cu.addEnum("test");
+ testEnum.addImplementedType(Function.class);
+ assertEquals(1, cu.getImports().size());
+ assertEquals("import " + Function.class.getName() + ";" + EOL,
+ cu.getImport(0).toString());
+ assertEquals(1, testEnum.getImplementedTypes().size());
+ assertEquals(Function.class.getSimpleName(), testEnum.getImplementedTypes(0).getNameAsString());
+ }
+
+ @Test
+ public 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-testing/src/test/java/com/github/javaparser/builders/FieldDeclarationBuildersTest.java b/javaparser-testing/src/test/java/com/github/javaparser/builders/FieldDeclarationBuildersTest.java
new file mode 100644
index 000000000..7824addd1
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/builders/FieldDeclarationBuildersTest.java
@@ -0,0 +1,120 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package 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.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.List;
+
+import static com.github.javaparser.ast.type.PrimitiveType.intType;
+import static org.junit.Assert.assertEquals;
+
+public class FieldDeclarationBuildersTest {
+ private final CompilationUnit cu = new CompilationUnit();
+ private ClassOrInterfaceDeclaration testClass = cu.addClass("testClass");
+ private EnumDeclaration testEnum = cu.addEnum("testEnum");
+
+ @Test(expected = IllegalStateException.class)
+ public void testOrphanFieldGetter() {
+ new FieldDeclaration().createGetter();
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void testOrphanFieldSetter() {
+ new FieldDeclaration().createSetter();
+ }
+
+ @Test
+ public void testCreateGetterInAClass() {
+ testClass.addPrivateField(int.class, "myField").createGetter();
+ assertEquals(2, testClass.getMembers().size());
+ assertEquals(MethodDeclaration.class, testClass.getMember(1).getClass());
+ List<MethodDeclaration> 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
+ public void testCreateSetterInAClass() {
+ testClass.addPrivateField(int.class, "myField").createSetter();
+ assertEquals(2, testClass.getMembers().size());
+ assertEquals(MethodDeclaration.class, testClass.getMember(1).getClass());
+ List<MethodDeclaration> 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
+ public void testCreateGetterInEnum() {
+ testEnum.addPrivateField(int.class, "myField").createGetter();
+ assertEquals(2, testEnum.getMembers().size());
+ assertEquals(MethodDeclaration.class, testEnum.getMember(1).getClass());
+ List<MethodDeclaration> 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
+ public void testCreateSetterInEnum() {
+ testEnum.addPrivateField(int.class, "myField").createSetter();
+ assertEquals(2, testEnum.getMembers().size());
+ assertEquals(MethodDeclaration.class, testEnum.getMember(1).getClass());
+ List<MethodDeclaration> 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(expected = IllegalStateException.class)
+ public void testCreateGetterWithANonValidField() {
+ FieldDeclaration myPrivateField = testClass.addPrivateField(int.class, "myField");
+ myPrivateField.getVariables().add(new VariableDeclarator(intType(), "secondField"));
+ myPrivateField.createGetter();
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void testCreateSetterWithANonValidField() {
+ FieldDeclaration myPrivateField = testClass.addPrivateField(int.class, "myField");
+ myPrivateField.getVariables().add(new VariableDeclarator(intType(), "secondField"));
+ myPrivateField.createSetter();
+ }
+
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/builders/NodeWithAnnotationsBuildersTest.java b/javaparser-testing/src/test/java/com/github/javaparser/builders/NodeWithAnnotationsBuildersTest.java
new file mode 100644
index 000000000..b72201631
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/builders/NodeWithAnnotationsBuildersTest.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.builders;
+
+import com.github.javaparser.ast.CompilationUnit;
+import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
+import com.github.javaparser.ast.expr.NormalAnnotationExpr;
+import com.github.javaparser.ast.expr.SingleMemberAnnotationExpr;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+public class NodeWithAnnotationsBuildersTest {
+ private CompilationUnit cu = new CompilationUnit();
+ private ClassOrInterfaceDeclaration testClass = cu.addClass("testClass"); ;
+
+ @interface hey {
+
+ }
+
+ @Test
+ public 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
+ public void testAddMarkerAnnotation() {
+ testClass.addMarkerAnnotation("test");
+ assertEquals(1, testClass.getAnnotations().size());
+ }
+
+ @Test
+ public void testAddSingleMemberAnnotation() {
+ testClass.addSingleMemberAnnotation("test", "value");
+ assertEquals(1, testClass.getAnnotations().size());
+ assertEquals("value", testClass.getAnnotation(0).asSingleMemberAnnotationExpr().getMemberValue().toString());
+ }
+
+ @Test
+ public void testIsAnnotationPresent() {
+ testClass.addMarkerAnnotation(hey.class);
+ assertTrue(testClass.isAnnotationPresent(hey.class));
+ }
+
+ @Test
+ public void testGetAnnotationByName() {
+ NormalAnnotationExpr annotation = testClass.addAndGetAnnotation(hey.class);
+ assertEquals(annotation, testClass.getAnnotationByName("hey").get());
+ }
+
+ @Test
+ public void testGetAnnotationByClass() {
+ NormalAnnotationExpr annotation = testClass.addAndGetAnnotation(hey.class);
+ assertEquals(annotation, testClass.getAnnotationByClass(hey.class).get());
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/builders/NodeWithMembersBuildersTest.java b/javaparser-testing/src/test/java/com/github/javaparser/builders/NodeWithMembersBuildersTest.java
new file mode 100644
index 000000000..4ac1f0681
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/builders/NodeWithMembersBuildersTest.java
@@ -0,0 +1,133 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.builders;
+
+import com.github.javaparser.ast.CompilationUnit;
+import com.github.javaparser.ast.Modifier;
+import com.github.javaparser.ast.body.*;
+import com.github.javaparser.ast.type.ClassOrInterfaceType;
+import org.junit.Test;
+
+import java.util.List;
+
+import static com.github.javaparser.JavaParser.parseClassOrInterfaceType;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+public class NodeWithMembersBuildersTest {
+ private final CompilationUnit cu = new CompilationUnit();
+ private final ClassOrInterfaceDeclaration classDeclaration = cu.addClass("test");
+
+ @Test
+ public void testAddField() {
+ FieldDeclaration addField = classDeclaration.addField(int.class, "fieldName", Modifier.PRIVATE);
+ assertEquals(1, classDeclaration.getMembers().size());
+ assertEquals(addField, classDeclaration.getMember(0));
+ assertEquals("fieldName", addField.getVariable(0).getNameAsString());
+ }
+
+ @Test
+ public void testAddMethod() {
+ MethodDeclaration addMethod = classDeclaration.addMethod("foo", Modifier.PUBLIC);
+ assertEquals(1, classDeclaration.getMembers().size());
+ assertEquals(addMethod, classDeclaration.getMember(0));
+ assertEquals("foo", addMethod.getNameAsString());
+ }
+
+ @Test
+ public void testAddCtor() {
+ ConstructorDeclaration addCtor = classDeclaration.addConstructor(Modifier.PUBLIC);
+ assertEquals(1, classDeclaration.getMembers().size());
+ assertEquals(addCtor, classDeclaration.getMember(0));
+ assertEquals(classDeclaration.getName(), addCtor.getName());
+ }
+
+ @Test
+ public 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
+ public void testGetMethodsWithName() {
+ MethodDeclaration addMethod = classDeclaration.addMethod("foo", Modifier.PUBLIC);
+ MethodDeclaration addMethod2 = classDeclaration.addMethod("foo", Modifier.PUBLIC).addParameter(int.class, "overload");
+ List<MethodDeclaration> methodsByName = classDeclaration.getMethodsByName("foo");
+ assertEquals(2, methodsByName.size());
+ assertTrue(methodsByName.contains(addMethod));
+ assertTrue(methodsByName.contains(addMethod2));
+ }
+
+ @Test
+ public void testGetMethods() {
+ MethodDeclaration addMethod = classDeclaration.addMethod("foo", Modifier.PUBLIC);
+ MethodDeclaration addMethod2 = classDeclaration.addMethod("foo", Modifier.PUBLIC).addParameter(int.class, "overload");
+
+ List<MethodDeclaration> methods = classDeclaration.getMethods();
+
+ assertEquals(2, methods.size());
+ assertTrue(methods.contains(addMethod));
+ assertTrue(methods.contains(addMethod2));
+ }
+
+ @Test
+ public void testGetMethodsWithParameterTypes() {
+ classDeclaration.addMethod("foo", Modifier.PUBLIC);
+ MethodDeclaration addMethod2 = classDeclaration.addMethod("foo", Modifier.PUBLIC).addParameter(int.class, "overload");
+ ClassOrInterfaceType type = parseClassOrInterfaceType("List");
+ type.setTypeArguments(parseClassOrInterfaceType("String"));
+ MethodDeclaration methodWithListParam = classDeclaration.addMethod("fooList", Modifier.PUBLIC).addParameter(type, "overload");
+ MethodDeclaration addMethod3 = classDeclaration.addMethod("foo2", Modifier.PUBLIC).addParameter(int.class, "overload");
+
+ List<MethodDeclaration> methodsByParam = classDeclaration.getMethodsByParameterTypes(int.class);
+ assertEquals(2, methodsByParam.size());
+ assertTrue(methodsByParam.contains(addMethod2));
+ assertTrue(methodsByParam.contains(addMethod3));
+ List<MethodDeclaration> methodsByParam2 = classDeclaration.getMethodsByParameterTypes("List<String>");
+ assertEquals(1, methodsByParam2.size());
+ assertTrue(methodsByParam2.contains(methodWithListParam));
+ }
+
+ @Test
+ public void testGetFieldWithName() {
+ FieldDeclaration addField = classDeclaration.addField(int.class, "fieldName", Modifier.PRIVATE);
+ classDeclaration.addField(float.class, "secondField", Modifier.PRIVATE);
+ FieldDeclaration fieldByName = classDeclaration.getFieldByName("fieldName").get();
+ assertEquals(addField, fieldByName);
+ }
+
+ @Test
+ public void testGetFields() {
+ FieldDeclaration firstField = classDeclaration.addField(int.class, "fieldName", Modifier.PRIVATE);
+ FieldDeclaration secondField = classDeclaration.addField(float.class, "secondField", Modifier.PRIVATE);
+
+ List<FieldDeclaration> fields = classDeclaration.getFields();
+
+ assertTrue(fields.contains(firstField));
+ assertTrue(fields.contains(secondField));
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/builders/NodeWithParametersBuildersTest.java b/javaparser-testing/src/test/java/com/github/javaparser/builders/NodeWithParametersBuildersTest.java
new file mode 100644
index 000000000..87d0a2553
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/builders/NodeWithParametersBuildersTest.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.builders;
+
+import com.github.javaparser.ast.CompilationUnit;
+import com.github.javaparser.ast.Modifier;
+import com.github.javaparser.ast.body.MethodDeclaration;
+import com.github.javaparser.ast.body.Parameter;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.List;
+
+import static com.github.javaparser.utils.Utils.EOL;
+import static org.junit.Assert.assertEquals;
+
+public class NodeWithParametersBuildersTest {
+ private final CompilationUnit cu = new CompilationUnit();
+
+ @Test
+ public void testAddParameter() {
+ MethodDeclaration addMethod = cu.addClass("test").addMethod("foo", Modifier.PUBLIC);
+ addMethod.addParameter(int.class, "yay");
+ Parameter myNewParam = addMethod.addAndGetParameter(List.class, "myList");
+ assertEquals(1, cu.getImports().size());
+ assertEquals("import " + List.class.getName() + ";" + 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
+ public void testGetParamByName() {
+ MethodDeclaration addMethod = cu.addClass("test").addMethod("foo", Modifier.PUBLIC);
+ Parameter addAndGetParameter = addMethod.addAndGetParameter(int.class, "yay");
+ assertEquals(addAndGetParameter, addMethod.getParameterByName("yay").get());
+ }
+
+ @Test
+ public void testGetParamByType() {
+ MethodDeclaration addMethod = cu.addClass("test").addMethod("foo", Modifier.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-testing/src/test/java/com/github/javaparser/builders/NodeWithThrownExceptionsBuildersTest.java b/javaparser-testing/src/test/java/com/github/javaparser/builders/NodeWithThrownExceptionsBuildersTest.java
new file mode 100644
index 000000000..79756065a
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/builders/NodeWithThrownExceptionsBuildersTest.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.builders;
+
+import com.github.javaparser.ast.CompilationUnit;
+import com.github.javaparser.ast.Modifier;
+import com.github.javaparser.ast.body.MethodDeclaration;
+import com.github.javaparser.ast.type.ClassOrInterfaceType;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import static com.github.javaparser.JavaParser.parseClassOrInterfaceType;
+import static org.junit.Assert.assertEquals;
+
+public class NodeWithThrownExceptionsBuildersTest {
+ private final CompilationUnit cu = new CompilationUnit();
+
+ @Test
+ public void testThrows() {
+ MethodDeclaration addMethod = cu.addClass("test").addMethod("foo", Modifier.PUBLIC);
+ addMethod.addThrownException(IllegalStateException.class);
+ assertEquals(1, addMethod.getThrownExceptions().size());
+ assertEquals(true, addMethod.isThrown(IllegalStateException.class));
+ addMethod.addThrownException(parseClassOrInterfaceType("Test"));
+ assertEquals(2, addMethod.getThrownExceptions().size());
+ assertEquals("Test", addMethod.getThrownException(1).toString());
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/javadoc/JavadocExtractorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/javadoc/JavadocExtractorTest.java
new file mode 100644
index 000000000..59740b3b0
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/javadoc/JavadocExtractorTest.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.javadoc;
+
+import com.github.javaparser.JavaParser;
+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.apache.commons.io.Charsets;
+import org.junit.Test;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.nio.charset.StandardCharsets;
+
+public class JavadocExtractorTest {
+
+ @Test
+ public void canParseAllJavadocsInJavaParser() throws FileNotFoundException {
+ processDir(new File(".."));
+ }
+
+ private void processFile(File file) throws FileNotFoundException {
+ try {
+ CompilationUnit cu = JavaParser.parse(file, StandardCharsets.UTF_8);
+ new VoidVisitorAdapter<Object>() {
+ @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-testing/src/test/java/com/github/javaparser/javadoc/JavadocTest.java b/javaparser-testing/src/test/java/com/github/javaparser/javadoc/JavadocTest.java
new file mode 100644
index 000000000..7377dfb86
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/javadoc/JavadocTest.java
@@ -0,0 +1,138 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.javadoc;
+
+import com.github.javaparser.JavaParser;
+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 org.junit.Test;
+
+import static com.github.javaparser.utils.Utils.EOL;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+public class JavadocTest {
+
+ @Test
+ public void toTextForEmptyJavadoc() {
+ Javadoc javadoc = new Javadoc(new JavadocDescription());
+ assertEquals("", javadoc.toText());
+ }
+
+ @Test
+ public void toTextForJavadocWithTwoLinesOfJustDescription() {
+ Javadoc javadoc = new Javadoc(JavadocDescription.parseText("first line" + EOL + "second line"));
+ assertEquals("first line" + EOL + "second line" + EOL, javadoc.toText());
+ }
+
+ @Test
+ public void toTextForJavadocWithTwoLinesOfJustDescriptionAndOneBlockTag() {
+ Javadoc javadoc = new Javadoc(JavadocDescription.parseText("first line" + EOL + "second line"));
+ javadoc.addBlockTag("foo", "something useful");
+ assertEquals("first line" + EOL + "second line" + EOL + EOL + "@foo something useful" + EOL, javadoc.toText());
+ }
+
+ @Test
+ public void toCommentForEmptyJavadoc() {
+ Javadoc javadoc = new Javadoc(new JavadocDescription());
+ assertEquals(new JavadocComment("" + EOL + "\t\t "), javadoc.toComment("\t\t"));
+ }
+
+ @Test
+ public void toCommentorJavadocWithTwoLinesOfJustDescription() {
+ Javadoc javadoc = new Javadoc(JavadocDescription.parseText("first line" + EOL + "second line"));
+ assertEquals(new JavadocComment("" + EOL + "\t\t * first line" + EOL + "\t\t * second line" + EOL + "\t\t "), javadoc.toComment("\t\t"));
+ }
+
+ @Test
+ public void toCommentForJavadocWithTwoLinesOfJustDescriptionAndOneBlockTag() {
+ Javadoc javadoc = new Javadoc(JavadocDescription.parseText("first line" + EOL + "second line"));
+ javadoc.addBlockTag("foo", "something useful");
+ assertEquals(new JavadocComment("" + EOL + "\t\t * first line" + EOL + "\t\t * second line" + EOL + "\t\t * " + EOL + "\t\t * @foo something useful" + EOL + "\t\t "), javadoc.toComment("\t\t"));
+ }
+
+ @Test
+ public void descriptionAndBlockTagsAreRetrievable() {
+ Javadoc javadoc = JavaParser.parseJavadoc("first line" + EOL + "second line" + EOL + EOL + "@param node a node" + EOL + "@return result the result");
+ assertEquals("first line" + EOL + "second line", javadoc.getDescription().toText());
+ assertEquals(2, javadoc.getBlockTags().size());
+ }
+
+ @Test
+ public void inlineTagsAreParsable() {
+ String docText =
+ "Returns the {@link TOFilename}s of all files that existed during the requested" + EOL +
+ "{@link TOVersion}." + EOL +
+ "" + EOL +
+ "@param versionID the id of the {@link TOVersion}." + EOL +
+ "@return the filenames" + EOL +
+ "@throws InvalidIDException if the {@link IPersistence} doesn't recognize the given versionID." + EOL;
+ String javadoc = JavaParser.parseJavadoc(docText).toText();
+ assertTrue(javadoc.contains("{@link TOVersion}"));
+ }
+
+ @Test
+ public void emptyLinesBetweenBlockTagsGetsFiltered() {
+ String comment = " * The type of the Object to be mapped." + EOL +
+ " * This interface maps the given Objects to existing ones in the database and" + EOL +
+ " * saves them." + EOL +
+ " * " + EOL +
+ " * @author censored" + EOL +
+ " * " + EOL +
+ " * @param <T>" + EOL;
+ Javadoc javadoc = JavaParser.parseJavadoc(comment);
+ assertEquals(2, javadoc.getBlockTags().size());
+ }
+
+ @Test
+ public 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
+ public void descriptionModificationWorks() {
+ JavadocDescription description = new JavadocDescription();
+
+ assertEquals(0, description.getElements().size());
+
+ JavadocDescriptionElement inlineTag = new JavadocInlineTag("inheritDoc", JavadocInlineTag.Type.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());
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/javadoc/description/JavadocInlineTagTest.java b/javaparser-testing/src/test/java/com/github/javaparser/javadoc/description/JavadocInlineTagTest.java
new file mode 100644
index 000000000..128eb61f2
--- /dev/null
+++ b/javaparser-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-2017 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the 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.Test;
+
+import static org.junit.Assert.assertEquals;
+
+public class JavadocInlineTagTest {
+
+ @Test
+ public void javadocInlineTagShouldPersistCustomTagNames() {
+ String tag = JavadocInlineTag.fromText("{@foo something}").toText();
+
+ assertEquals(tag, "@foo something");
+ }
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/manual/BulkParseTest.java b/javaparser-testing/src/test/java/com/github/javaparser/manual/BulkParseTest.java
new file mode 100644
index 000000000..b09651f7d
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/manual/BulkParseTest.java
@@ -0,0 +1,120 @@
+package com.github.javaparser.manual;
+
+import com.github.javaparser.ParserConfiguration;
+import com.github.javaparser.Problem;
+import com.github.javaparser.utils.CodeGenerationUtils;
+import com.github.javaparser.utils.Log;
+import com.github.javaparser.utils.SourceRoot;
+import com.github.javaparser.utils.SourceZip;
+import org.junit.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.JAVA_10;
+import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_9;
+import static com.github.javaparser.utils.CodeGenerationUtils.f;
+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;
+
+public 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 = CodeGenerationUtils.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));
+ }
+
+ @Test
+ public void parseOwnSourceCode() throws IOException {
+ bulkTest(
+ new SourceRoot(CodeGenerationUtils.mavenModuleRoot(BulkParseTest.class).resolve("..")),
+ "javaparser_test_results.txt",
+ new ParserConfiguration().setLanguageLevel(JAVA_9));
+ }
+
+ public void bulkTest(SourceRoot sourceRoot, String testResultsFileName, ParserConfiguration configuration) throws IOException {
+ sourceRoot.setParserConfiguration(configuration);
+ TreeMap<Path, List<Problem>> 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<Path, List<Problem>> 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<Path, List<Problem>> results, String testResultsFileName) throws IOException {
+ Log.info("Writing results...");
+
+ Path testResults = CodeGenerationUtils.mavenModuleRoot(BulkParseTest.class).resolve(Paths.get("..", "javaparser-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<Path, List<Problem>> 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()));
+ }
+
+ Log.info("Results are in %s", testResults);
+ }
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/metamodel/BaseNodeMetaModelTest.java b/javaparser-testing/src/test/java/com/github/javaparser/metamodel/BaseNodeMetaModelTest.java
new file mode 100644
index 000000000..06a586caf
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/metamodel/BaseNodeMetaModelTest.java
@@ -0,0 +1,25 @@
+package com.github.javaparser.metamodel;
+
+import com.github.javaparser.ast.expr.StringLiteralExpr;
+import org.junit.Test;
+
+import java.util.Optional;
+
+import static org.junit.Assert.assertEquals;
+
+class TestMetaModel extends BaseNodeMetaModel {
+
+ public TestMetaModel() {
+ super(Optional.empty(), StringLiteralExpr.class, "stri", "com.japa", true, true);
+ }
+}
+
+public class BaseNodeMetaModelTest {
+ @Test
+ public void testGetters() {
+ TestMetaModel test = new TestMetaModel();
+
+ assertEquals("testMetaModel", test.getMetaModelFieldName());
+ }
+
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/metamodel/PropertyMetaModelTest.java b/javaparser-testing/src/test/java/com/github/javaparser/metamodel/PropertyMetaModelTest.java
new file mode 100644
index 000000000..2333d8101
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/metamodel/PropertyMetaModelTest.java
@@ -0,0 +1,45 @@
+package com.github.javaparser.metamodel;
+
+import com.github.javaparser.ast.Modifier;
+import com.github.javaparser.ast.body.BodyDeclaration;
+import org.junit.Test;
+
+import java.util.Optional;
+
+import static org.junit.Assert.assertEquals;
+
+public class PropertyMetaModelTest {
+ @Test
+ public void whenPropertyIsVerySimpleThenTypeInfoIsCorrect() {
+ PropertyMetaModel bert = new PropertyMetaModel(null, "bert", int.class, Optional.empty(), false, false, false, false, false);
+ assertEquals("int", bert.getTypeName());
+ assertEquals("int", bert.getTypeNameGenerified());
+ assertEquals("int", bert.getTypeNameForGetter());
+ assertEquals("int", bert.getTypeNameForSetter());
+ }
+
+ @Test
+ public void whenPropertyIsVeryComplexThenTypeInfoIsCorrect() {
+ PropertyMetaModel bert = new PropertyMetaModel(null, "bert", BodyDeclaration.class, Optional.empty(), true, false, true, false, true);
+ assertEquals("BodyDeclaration", bert.getTypeName());
+ assertEquals("BodyDeclaration<?>", bert.getTypeNameGenerified());
+ assertEquals("Optional<NodeList<BodyDeclaration<?>>>", bert.getTypeNameForGetter());
+ assertEquals("NodeList<BodyDeclaration<?>>", bert.getTypeNameForSetter());
+ }
+
+ @Test
+ public void whenPropertyIsAnEnumThenTypeInfoIsCorrect() {
+ PropertyMetaModel bert = new PropertyMetaModel(null, "bert", Modifier.class, Optional.empty(), false, false, false, true, false);
+ assertEquals("Modifier", bert.getTypeName());
+ assertEquals("Modifier", bert.getTypeNameGenerified());
+ assertEquals("EnumSet<Modifier>", bert.getTypeNameForGetter());
+ assertEquals("EnumSet<Modifier>", bert.getTypeNameForSetter());
+ }
+
+ @Test
+ public void metaModelFieldName() {
+ PropertyMetaModel bert = new PropertyMetaModel(null, "bert", Modifier.class, Optional.empty(), false, false, false, true, false);
+ assertEquals("bertPropertyMetaModel", bert.getMetaModelFieldName());
+ }
+
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/modules/ModuleDeclarationTest.java b/javaparser-testing/src/test/java/com/github/javaparser/modules/ModuleDeclarationTest.java
new file mode 100644
index 000000000..80ebe557e
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/modules/ModuleDeclarationTest.java
@@ -0,0 +1,181 @@
+package com.github.javaparser.modules;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.JavaToken;
+import com.github.javaparser.ParseStart;
+import com.github.javaparser.ParserConfiguration;
+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.ast.type.ClassOrInterfaceType;
+import com.github.javaparser.printer.ConcreteSyntaxModel;
+import org.junit.Test;
+
+import static com.github.javaparser.GeneratedJavaParserConstants.IDENTIFIER;
+import static com.github.javaparser.JavaParser.parseClassOrInterfaceType;
+import static com.github.javaparser.JavaParser.parseName;
+import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_9;
+import static com.github.javaparser.Providers.provider;
+import static com.github.javaparser.utils.Utils.EOL;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.assertEquals;
+
+public class ModuleDeclarationTest {
+ public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_9));
+
+ private final CompilationUnit parse(String code) {
+ return javaParser.parse(ParseStart.COMPILATION_UNIT, provider(code)).getResult().get();
+ }
+
+ @Test
+ public void moduleInfoKeywordsAreSeenAsIdentifiers() {
+ CompilationUnit cu = parse("class module { }");
+ JavaToken moduleToken = cu.getClassByName("module").get().getName().getTokenRange().get().getBegin();
+ assertEquals(IDENTIFIER, moduleToken.getKind());
+ }
+
+ @Test
+ public void issue988RequireTransitiveShouldRequireAModuleCalledTransitive() {
+ CompilationUnit cu = parse("module X { requires transitive; }");
+ ModuleRequiresStmt requiresTransitive = (ModuleRequiresStmt) cu.getModule().get().getModuleStmts().get(0);
+ assertEquals("transitive", requiresTransitive.getNameAsString());
+ assertEquals(IDENTIFIER, requiresTransitive.getName().getTokenRange().get().getBegin().getKind());
+ }
+
+ @Test
+ public 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());
+ assertEquals(false, 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")));
+
+ ModuleRequiresStmt moduleRequiresStmt = module.getModuleStmts().get(0).asModuleRequiresStmt();
+ assertThat(moduleRequiresStmt.getNameAsString()).isEqualTo("A.B");
+ assertThat(moduleRequiresStmt.getModifiers()).isEmpty();
+
+ ModuleExportsStmt moduleExportsStmt = module.getModuleStmts().get(5).asModuleExportsStmt();
+ assertThat(moduleExportsStmt.getNameAsString()).isEqualTo("R.S");
+ assertThat(moduleExportsStmt.getModuleNames()).containsExactly(parseName("T1.U1"), parseName("T2.U2"));
+
+ ModuleOpensStmt moduleOpensStmt = module.getModuleStmts().get(7).asModuleOpensStmt();
+ assertThat(moduleOpensStmt.getNameAsString()).isEqualTo("R.S");
+ assertThat(moduleOpensStmt.getModuleNames()).containsExactly(parseName("T1.U1"), parseName("T2.U2"));
+
+ ModuleUsesStmt moduleUsesStmt = module.getModuleStmts().get(8).asModuleUsesStmt();
+ assertThat(moduleUsesStmt.getType().toString()).isEqualTo("V.W");
+
+ ModuleProvidesStmt moduleProvidesStmt = module.getModuleStmts().get(9).asModuleProvidesStmt();
+ assertThat(moduleProvidesStmt.getType().toString()).isEqualTo("X.Y");
+ assertThat(moduleProvidesStmt.getWithTypes()).containsExactly(
+ new ClassOrInterfaceType(parseClassOrInterfaceType("Z1"), "Z2"),
+ new ClassOrInterfaceType(parseClassOrInterfaceType("Z3"), "Z4"));
+
+ }
+
+ @Test
+ public void jlsExample2HasAnOpenModule() {
+ CompilationUnit cu = parse("open module M.N {}");
+
+ ModuleDeclaration module = cu.getModule().get();
+ assertEquals("M.N", module.getNameAsString());
+ assertEquals(true, module.isOpen());
+ }
+
+ @Test
+ public 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 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) @Foo(2) @Bar " + EOL +
+ "module M.N {" + EOL +
+ " requires A.B;" + EOL +
+ " requires transitive C.D;" + EOL +
+ " requires static E.F;" + EOL +
+ " requires static transitive G.H;" + EOL +
+ " exports P.Q;" + EOL +
+ " exports R.S to T1.U1, T2.U2;" + EOL +
+ " opens P.Q;" + EOL +
+ " opens R.S to T1.U1, T2.U2;" + EOL +
+ " uses V.W;" + EOL +
+ " provides X.Y with Z1.Z2, Z3.Z4;" + EOL +
+ "}" + EOL, cu.toString());
+
+ }
+
+ @Test
+ public 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) @Foo(2) @Bar" + EOL +
+ "open module M.N {" + EOL +
+ " requires A.B;" + EOL +
+ " requires transitive C.D;" + EOL +
+ " requires static E.F;" + EOL +
+ " requires static transitive G.H;" + EOL +
+ " exports P.Q;" + EOL +
+ " exports R.S to T1.U1, T2.U2;" + EOL +
+ " opens P.Q;" + EOL +
+ " opens R.S to T1.U1, T2.U2;" + EOL +
+ " uses V.W;" + EOL +
+ " provides X.Y with Z1.Z2, Z3.Z4;" + EOL +
+ "}" + EOL, ConcreteSyntaxModel.genericPrettyPrint(cu));
+
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/ConcreteSyntaxModelAcceptanceTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/ConcreteSyntaxModelAcceptanceTest.java
new file mode 100644
index 000000000..af47a9d9d
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/ConcreteSyntaxModelAcceptanceTest.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.printer;
+
+import com.github.javaparser.JavaParser;
+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.Test;
+
+import java.io.IOException;
+import java.nio.file.Path;
+
+import static org.junit.Assert.assertEquals;
+
+public 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
+ public void printingExamplePrettyPrintVisitor() throws IOException {
+ CompilationUnit cu = JavaParser.parse(rootDir.resolve("com/github/javaparser/printer/PrettyPrintVisitor.java"));
+ assertEquals(prettyPrintedExpectation("PrettyPrintVisitor"), prettyPrint(cu));
+ }
+
+ @Test
+ public void printingExampleJavaConcepts() throws IOException {
+ CompilationUnit cu = JavaParser.parse(rootDir.resolve("com/github/javaparser/printer/JavaConcepts.java"));
+ assertEquals(prettyPrintedExpectation("JavaConcepts"), prettyPrint(cu));
+ }
+
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/ConcreteSyntaxModelTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/ConcreteSyntaxModelTest.java
new file mode 100644
index 000000000..b08f90b92
--- /dev/null
+++ b/javaparser-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-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.printer;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.ast.Node;
+import com.github.javaparser.ast.expr.ClassExpr;
+import org.junit.Test;
+
+import static com.github.javaparser.utils.Utils.EOL;
+import static org.junit.Assert.assertEquals;
+
+public class ConcreteSyntaxModelTest {
+
+ private String print(Node node) {
+ return ConcreteSyntaxModel.genericPrettyPrint(node);
+ }
+
+ @Test
+ public void printSimpleClassExpr() {
+ ClassExpr expr = JavaParser.parseExpression("Foo.class");
+ assertEquals("Foo.class", print(expr));
+ }
+
+ @Test
+ public void printArrayClassExpr() {
+ ClassExpr expr = JavaParser.parseExpression("Foo[].class");
+ assertEquals("Foo[].class", print(expr));
+ }
+
+ @Test
+ public void printGenericClassExpr() {
+ ClassExpr expr = JavaParser.parseExpression("Foo<String>.class");
+ assertEquals("Foo<String>.class", print(expr));
+ }
+
+ @Test
+ public void printSimplestClass() {
+ Node node = JavaParser.parse("class A {}");
+ assertEquals("class A {" + EOL +
+ "}" + EOL, print(node));
+ }
+
+ @Test
+ public void printAClassWithField() {
+ Node node = JavaParser.parse("class A { int a; }");
+ assertEquals("class A {" + EOL
+ + EOL +
+ " int a;" + EOL +
+ "}" + EOL, print(node));
+ }
+
+ @Test
+ public void printParameters() {
+ Node node = JavaParser.parseBodyDeclaration("int x(int y, int z) {}");
+ assertEquals("int x(int y, int z) {" + EOL + "}", print(node));
+ }
+
+ @Test
+ public void printReceiverParameter() {
+ Node node = JavaParser.parseBodyDeclaration("int x(X A.B.this, int y, int z) {}");
+ assertEquals("int x(X A.B.this, int y, int z) {" + EOL + "}", print(node));
+ }
+
+ @Test
+ public void printAnEmptyInterface() {
+ Node node = JavaParser.parse("interface A {}");
+ assertEquals("interface A {" + EOL +
+ "}" + EOL, print(node));
+ }
+
+ @Test
+ public void printAnEmptyInterfaceWithModifier() {
+ Node node = JavaParser.parse("public interface A {}");
+ assertEquals("public interface A {" + EOL +
+ "}" + EOL, print(node));
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/DotPrinterTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/DotPrinterTest.java
new file mode 100644
index 000000000..ca11465a6
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/DotPrinterTest.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.printer;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.ast.expr.Expression;
+
+public class DotPrinterTest {
+ @Test
+ public 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 = JavaParser.parseExpression("x(1,1)");
+ String output = dotPrinter.output(expression);
+ assertEquals(expectedOutput, output);
+ }
+
+ @Test
+ public 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 = JavaParser.parseExpression("1+1");
+ String output = dotPrinter.output(expression);
+ assertEquals(expectedOutput, output);
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/JsonPrinterTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/JsonPrinterTest.java
new file mode 100644
index 000000000..7e26254a4
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/JsonPrinterTest.java
@@ -0,0 +1,75 @@
+package com.github.javaparser.printer;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.ast.CompilationUnit;
+import com.github.javaparser.ast.expr.Expression;
+import org.junit.Test;
+
+import static com.github.javaparser.JavaParser.*;
+import static com.github.javaparser.utils.Utils.EOL;
+import static org.junit.Assert.*;
+
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.io.Writer;
+import java.io.BufferedWriter;
+
+public class JsonPrinterTest {
+ @Test
+ public void testWithType() {
+ JsonPrinter jsonPrinter = new JsonPrinter(true);
+ Expression expression = parseExpression("x(1,1)");
+
+ String output = jsonPrinter.output(expression);
+
+ assertEquals("{\"type\":\"MethodCallExpr\",\"name\":{\"type\":\"SimpleName\",\"identifier\":\"x\"},\"arguments\":[{\"type\":\"IntegerLiteralExpr\",\"value\":\"1\"},{\"type\":\"IntegerLiteralExpr\",\"value\":\"1\"}]}", output);
+ }
+
+ @Test
+ public void testWithoutType() {
+ JsonPrinter jsonPrinter = new JsonPrinter(false);
+ Expression expression = parseExpression("1+1");
+
+ String output = jsonPrinter.output(expression);
+
+ assertEquals("{\"operator\":\"PLUS\",\"left\":{\"value\":\"1\"},\"right\":{\"value\":\"1\"}}", output);
+ }
+
+ @Test
+ public void testEscaping() {
+ JsonPrinter jsonPrinter = new JsonPrinter(false);
+ CompilationUnit expression = parse("class X {//hi\"" + EOL + "int x;}");
+
+ String output = jsonPrinter.output(expression);
+
+ assertEquals("{\"types\":[{\"isInterface\":\"false\",\"name\":{\"identifier\":\"X\",\"comment\":{\"content\":\"hi\\\"\"}},\"members\":[{\"variables\":[{\"name\":{\"identifier\":\"x\"},\"type\":{\"type\":\"INT\"}}]}]}]}", output);
+ }
+
+ @Test
+ public void issue1338() {
+ String code = "class Test {" +
+ " public void method() {" +
+ " String.format(\"I'm using %s\", \"JavaParser\");" +
+ " }" +
+ "}";
+ CompilationUnit unit = parse(code);
+ JsonPrinter printer = new JsonPrinter(true);
+ printer.output(unit);
+ }
+
+ @Test
+ public void issue1421() {
+ // Handle multi-line strings in JSON output
+ String code = "/* \n" +
+ "* Some comment\n" +
+ "*/\n" +
+ "public class Test {}";
+ CompilationUnit unit = parse(code);
+ JsonPrinter printer = new JsonPrinter(true);
+
+ String output = printer.output(unit);
+
+ assertEquals("{\"type\":\"CompilationUnit\",\"types\":[{\"type\":\"ClassOrInterfaceDeclaration\",\"isInterface\":\"false\",\"name\":{\"type\":\"SimpleName\",\"identifier\":\"Test\"},\"comment\":{\"type\":\"BlockComment\",\"content\":\" \\n* Some comment\\n\"}}]}", output);
+ }
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/PrettyPrintVisitorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/PrettyPrintVisitorTest.java
new file mode 100644
index 000000000..df1168ed1
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/PrettyPrintVisitorTest.java
@@ -0,0 +1,277 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.printer;
+
+import com.github.javaparser.JavaParser;
+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.type.Type;
+import org.junit.Test;
+
+import static com.github.javaparser.utils.TestUtils.assertEqualsNoEol;
+import static com.github.javaparser.utils.Utils.EOL;
+import static org.junit.Assert.assertEquals;
+
+public class PrettyPrintVisitorTest {
+
+ @Test
+ public void getMaximumCommonTypeWithoutAnnotations() {
+ VariableDeclarationExpr vde1 = JavaParser.parseVariableDeclarationExpr("int a[], b[]");
+ assertEquals("int[]", vde1.getMaximumCommonType().get().toString());
+
+ VariableDeclarationExpr vde2 = JavaParser.parseVariableDeclarationExpr("int[][] a[], b[]");
+ assertEquals("int[][][]", vde2.getMaximumCommonType().get().toString());
+
+ VariableDeclarationExpr vde3 = JavaParser.parseVariableDeclarationExpr("int[][] a, b[]");
+ assertEquals("int[][]", vde3.getMaximumCommonType().get().toString());
+ }
+
+ @Test
+ public void getMaximumCommonTypeWithAnnotations() {
+ VariableDeclarationExpr vde1 = JavaParser.parseVariableDeclarationExpr("int a @Foo [], b[]");
+ assertEquals("int", vde1.getMaximumCommonType().get().toString());
+
+ VariableDeclarationExpr vde2 = JavaParser.parseVariableDeclarationExpr("int[]@Foo [] a[], b[]");
+ assertEquals("int[] @Foo [][]", vde2.getMaximumCommonType().get().toString());
+ }
+
+ private String print(Node node) {
+ return new PrettyPrinter().print(node);
+ }
+
+ @Test
+ public void printSimpleClassExpr() {
+ ClassExpr expr = JavaParser.parseExpression("Foo.class");
+ assertEquals("Foo.class", print(expr));
+ }
+
+ @Test
+ public void printArrayClassExpr() {
+ ClassExpr expr = JavaParser.parseExpression("Foo[].class");
+ assertEquals("Foo[].class", print(expr));
+ }
+
+ @Test
+ public void printGenericClassExpr() {
+ ClassExpr expr = JavaParser.parseExpression("Foo<String>.class");
+ assertEquals("Foo<String>.class", print(expr));
+ }
+
+ @Test
+ public void printSimplestClass() {
+ Node node = JavaParser.parse("class A {}");
+ assertEquals("class A {" + EOL +
+ "}" + EOL, print(node));
+ }
+
+ @Test
+ public void printAClassWithField() {
+ Node node = JavaParser.parse("class A { int a; }");
+ assertEquals("class A {" + EOL
+ + EOL +
+ " int a;" + EOL +
+ "}" + EOL, print(node));
+ }
+
+ @Test
+ public void printAReceiverParameter() {
+ Node node = JavaParser.parseBodyDeclaration("int x(@O X A.B.this, int y) { }");
+ assertEquals("int x(@O X A.B.this, int y) {" + EOL + "}", print(node));
+ }
+
+ @Test
+ public void printLambdaIntersectionTypeAssignment() {
+ String code = "class A {" + EOL +
+ " void f() {" + EOL +
+ " Runnable r = (Runnable & Serializable) (() -> {});" + EOL +
+ " r = (Runnable & Serializable)() -> {};" + EOL +
+ " r = (Runnable & I)() -> {};" + EOL +
+ " }}";
+ CompilationUnit cu = JavaParser.parse(code);
+ MethodDeclaration methodDeclaration = (MethodDeclaration) cu.getType(0).getMember(0);
+
+ assertEquals("Runnable r = (Runnable & Serializable) (() -> {" + EOL + "});", print(methodDeclaration.getBody().get().getStatements().get(0)));
+ }
+
+ @Test
+ public void printIntersectionType() {
+ String code = "(Runnable & Serializable) (() -> {})";
+ Expression expression = JavaParser.parseExpression(code);
+ Type type = ((CastExpr) expression).getType();
+
+ assertEquals("Runnable & Serializable", print(type));
+ }
+
+ @Test
+ public void printLambdaIntersectionTypeReturn() {
+ String code = "class A {" + EOL
+ + " Object f() {" + EOL
+ + " return (Comparator<Map.Entry<K, V>> & Serializable)(c1, c2) -> c1.getKey().compareTo(c2.getKey()); " + EOL
+ + "}}";
+ CompilationUnit cu = JavaParser.parse(code);
+ MethodDeclaration methodDeclaration = (MethodDeclaration) cu.getType(0).getMember(0);
+
+ assertEquals("return (Comparator<Map.Entry<K, V>> & Serializable) (c1, c2) -> c1.getKey().compareTo(c2.getKey());", print(methodDeclaration.getBody().get().getStatements().get(0)));
+ }
+
+ @Test
+ public void printClassWithoutJavaDocButWithComment() {
+ String code = String.format("/** javadoc */ public class A { %s// stuff%s}", EOL, EOL);
+ CompilationUnit cu = JavaParser.parse(code);
+ PrettyPrinterConfiguration ignoreJavaDoc = new PrettyPrinterConfiguration().setPrintJavadoc(false);
+ String content = cu.toString(ignoreJavaDoc);
+ assertEquals(String.format("public class A {%s // stuff%s}%s", EOL, EOL, EOL), content);
+ }
+
+ @Test
+ public void printImportsDefaultOrder() {
+ String code = "import x.y.z;import a.b.c;import static b.c.d;class c {}";
+ CompilationUnit cu = JavaParser.parse(code);
+ String content = cu.toString();
+ assertEqualsNoEol("import x.y.z;\n" +
+ "import a.b.c;\n" +
+ "import static b.c.d;\n" +
+ "\n" +
+ "class c {\n" +
+ "}\n", content);
+ }
+
+ @Test
+ public void printImportsOrdered() {
+ String code = "import x.y.z;import a.b.c;import static b.c.d;class c {}";
+ CompilationUnit cu = JavaParser.parse(code);
+ PrettyPrinterConfiguration orderImports = new PrettyPrinterConfiguration().setOrderImports(true);
+ String content = cu.toString(orderImports);
+ assertEqualsNoEol("import static b.c.d;\n" +
+ "import a.b.c;\n" +
+ "import x.y.z;\n" +
+ "\n" +
+ "class c {\n" +
+ "}\n", content);
+ }
+
+ @Test
+ public void multilineJavadocGetsFormatted() {
+ CompilationUnit cu = new CompilationUnit();
+ cu.addClass("X").addMethod("abc").setJavadocComment("line1\n line2 *\n * line3");
+
+ assertEqualsNoEol("public class X {\n" +
+ "\n" +
+ " /**\n" +
+ " * line1\n" +
+ " * line2 *\n" +
+ " * line3\n" +
+ " */\n" +
+ " void abc() {\n" +
+ " }\n" +
+ "}\n", cu.toString());
+ }
+
+ @Test
+ public void emptyJavadocGetsFormatted() {
+ CompilationUnit cu = new CompilationUnit();
+ cu.addClass("X").addMethod("abc").setJavadocComment("");
+
+ assertEqualsNoEol("public class X {\n" +
+ "\n" +
+ " /**\n" +
+ " */\n" +
+ " void abc() {\n" +
+ " }\n" +
+ "}\n", cu.toString());
+ }
+
+ @Test
+ public void multilineJavadocWithLotsOfEmptyLinesGetsFormattedNeatly() {
+ CompilationUnit cu = new CompilationUnit();
+ cu.addClass("X").addMethod("abc").setJavadocComment("\n\n\n ab\n\n\n cd\n\n\n");
+
+ assertEqualsNoEol("public class X {\n" +
+ "\n" +
+ " /**\n" +
+ " * ab\n" +
+ " *\n" +
+ " * cd\n" +
+ " */\n" +
+ " void abc() {\n" +
+ " }\n" +
+ "}\n", cu.toString());
+ }
+
+ @Test
+ public void singlelineJavadocGetsFormatted() {
+ CompilationUnit cu = new CompilationUnit();
+ cu.addClass("X").addMethod("abc").setJavadocComment("line1");
+
+ assertEqualsNoEol("public class X {\n" +
+ "\n" +
+ " /**\n" +
+ " * line1\n" +
+ " */\n" +
+ " void abc() {\n" +
+ " }\n" +
+ "}\n", cu.toString());
+ }
+
+ @Test
+ public void singlelineCommentGetsFormatted() {
+ CompilationUnit cu = new CompilationUnit();
+ cu.addClass("X").addMethod("abc").setComment(new LineComment(" line1 \n "));
+
+ assertEqualsNoEol("public class X {\n" +
+ "\n" +
+ " // line1\n" +
+ " void abc() {\n" +
+ " }\n" +
+ "}\n", cu.toString());
+ }
+
+ @Test
+ public void blockcommentGetsNoFormatting() {
+ CompilationUnit cu = JavaParser.parse("class A {\n" +
+ " public void helloWorld(String greeting, String name) {\n" +
+ " //sdfsdfsdf\n" +
+ " //sdfds\n" +
+ " /*\n" +
+ " dgfdgfdgfdgfdgfd\n" +
+ " */\n" +
+ " }\n" +
+ "}\n");
+
+ assertEqualsNoEol("class A {\n" +
+ "\n" +
+ " public void helloWorld(String greeting, String name) {\n" +
+ " // sdfsdfsdf\n" +
+ " // sdfds\n" +
+ " /*\n" +
+ " dgfdgfdgfdgfdgfd\n" +
+ " */\n" +
+ " }\n" +
+ "}\n", cu.toString());
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/PrettyPrinterTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/PrettyPrinterTest.java
new file mode 100644
index 000000000..fef360925
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/PrettyPrinterTest.java
@@ -0,0 +1,206 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.printer;
+
+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.expr.VariableDeclarationExpr;
+import com.github.javaparser.ast.type.PrimitiveType;
+import org.junit.Test;
+
+import static com.github.javaparser.JavaParser.*;
+import static com.github.javaparser.utils.TestUtils.assertEqualsNoEol;
+import static org.junit.Assert.assertEquals;
+
+public class PrettyPrinterTest {
+
+ private String prettyPrintField(String code) {
+ CompilationUnit cu = parse(code);
+ return new PrettyPrinter().print(cu.findFirst(FieldDeclaration.class).get());
+ }
+
+ private String prettyPrintVar(String code) {
+ CompilationUnit cu = parse(code);
+ return new PrettyPrinter().print(cu.findAll(VariableDeclarationExpr.class).get(0));
+ }
+
+ @Test
+ public 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
+ public 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);
+ PrettyPrinter printer = new PrettyPrinter(new PrettyPrinterConfiguration().setVisitorFactory(TestVisitor::new));
+ return printer.print(cu.findFirst(ClassOrInterfaceDeclaration.class).get());
+ }
+
+ @Test
+ public void printUseTestVisitor() {
+ String code;
+ code = "class A { void foo(){ int a, b[]; }}";
+ assertEquals("test", prettyPrintConfigurable(code));
+ }
+
+ @Test
+ public void prettyColumnAlignParameters_enabled() {
+ PrettyPrinterConfiguration config = new PrettyPrinterConfiguration()
+ .setIndent("\t")
+ .setColumnAlignParameters(true);
+
+ final String EOL = config.getEndOfLineCharacter();
+
+ String code = "class Example { void foo(Object arg0,Object arg1){ myMethod(1, 2, 3, 5, Object.class); } }";
+ String expected = "class Example {" + EOL +
+ "" + EOL +
+ "\tvoid foo(Object arg0, Object arg1) {" + EOL +
+ "\t\tmyMethod(1," + EOL +
+ "\t\t 2," + EOL +
+ "\t\t 3," + EOL +
+ "\t\t 5," + EOL +
+ "\t\t Object.class);" + EOL +
+ "\t}" + EOL +
+ "}" + EOL +
+ "";
+
+ assertEquals(expected, new PrettyPrinter(config).print(parse(code)));
+ }
+
+ @Test
+ public void prettyColumnAlignParameters_disabled() {
+ PrettyPrinterConfiguration config = new PrettyPrinterConfiguration();
+ final String EOL = config.getEndOfLineCharacter();
+
+ 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 PrettyPrinter(config).print(parse(code)));
+ }
+
+ @Test
+ public void prettyAlignMethodCallChains_enabled() {
+ PrettyPrinterConfiguration config = new PrettyPrinterConfiguration()
+ .setIndent("\t")
+ .setColumnAlignFirstMethodChain(true);
+
+ final String EOL = config.getEndOfLineCharacter();
+
+ 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 +
+ "\tvoid foo() {" + EOL +
+ "\t\tIntStream.range(0, 10)" + EOL +
+ "\t\t .filter(x -> x % 2 == 0)" + EOL +
+ "\t\t .map(x -> x * IntStream.of(1, 3, 5, 1)" + EOL +
+ "\t\t .sum())" + EOL +
+ "\t\t .forEach(System.out::println);" + EOL +
+ "\t}" + EOL +
+ "}" + EOL +
+ "";
+
+ assertEquals(expected, new PrettyPrinter(config).print(parse(code)));
+ }
+
+ @Test
+ public void prettyAlignMethodCallChains_disabled() {
+ PrettyPrinterConfiguration config = new PrettyPrinterConfiguration();
+ final String EOL = config.getEndOfLineCharacter();
+
+ 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, new PrettyPrinter(config).print(parse(code)));
+ }
+
+ @Test
+ public void enumConstantsHorizontally() {
+ CompilationUnit cu = parse("enum X{A, B, C, D, E}");
+ assertEqualsNoEol("enum X {\n\n A, B, C, D, E\n}\n", new PrettyPrinter().print(cu));
+ }
+
+ @Test
+ public void enumConstantsVertically() {
+ CompilationUnit cu = parse("enum X{A, B, C, D, E, F}");
+ assertEqualsNoEol("enum X {\n\n A,\n B,\n C,\n D,\n E,\n F\n}\n", new PrettyPrinter().print(cu));
+ }
+
+ @Test
+ public 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());
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/TestVisitor.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/TestVisitor.java
new file mode 100644
index 000000000..6cbe32808
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/TestVisitor.java
@@ -0,0 +1,15 @@
+package com.github.javaparser.printer;
+
+import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
+
+public class TestVisitor extends PrettyPrintVisitor {
+
+ public TestVisitor(PrettyPrinterConfiguration prettyPrinterConfiguration) {
+ super(prettyPrinterConfiguration);
+ }
+
+ @Override
+ public void visit(final ClassOrInterfaceDeclaration n, final Void arg) {
+ printer.print("test");
+ }
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java
new file mode 100644
index 000000000..b64989122
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java
@@ -0,0 +1,41 @@
+package com.github.javaparser.printer;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.ast.expr.Expression;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+public class XmlPrinterTest {
+ @Test
+ public void testWithType() {
+ Expression expression = JavaParser.parseExpression("1+1");
+ XmlPrinter xmlOutput = new XmlPrinter(true);
+
+ String output = xmlOutput.output(expression);
+
+ assertEquals("<root type='BinaryExpr' operator='PLUS'><left type='IntegerLiteralExpr' value='1'></left><right type='IntegerLiteralExpr' value='1'></right></root>", output);
+ }
+
+ @Test
+ public void testWithoutType() {
+ Expression expression = JavaParser.parseExpression("1+1");
+
+ XmlPrinter xmlOutput = new XmlPrinter(false);
+
+ String output = xmlOutput.output(expression);
+
+ assertEquals("<root operator='PLUS'><left value='1'></left><right value='1'></right></root>", output);
+ }
+
+ @Test
+ public void testList() {
+ Expression expression = JavaParser.parseExpression("a(1,2)");
+
+ XmlPrinter xmlOutput = new XmlPrinter(true);
+
+ String output = xmlOutput.output(expression);
+
+ assertEquals("<root type='MethodCallExpr'><name type='SimpleName' identifier='a'></name><arguments><argument type='IntegerLiteralExpr' value='1'></argument><argument type='IntegerLiteralExpr' value='2'></argument></arguments></root>", output);
+ }
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/YamlPrinterTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/YamlPrinterTest.java
new file mode 100644
index 000000000..435cd8198
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/YamlPrinterTest.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.printer;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.ast.expr.Expression;
+
+public class YamlPrinterTest {
+
+ @Test
+ public void testWithType() {
+ String expectedOutput = "---" + System.lineSeparator();
+ expectedOutput += "root(Type=MethodCallExpr): " + System.lineSeparator();
+ expectedOutput += " name(Type=SimpleName): " + System.lineSeparator();
+ expectedOutput += " identifier: \"x\"" + System.lineSeparator();
+ expectedOutput += " arguments: " + System.lineSeparator();
+ expectedOutput += " - argument(Type=IntegerLiteralExpr): " + System.lineSeparator();
+ expectedOutput += " value: \"1\"" + System.lineSeparator();
+ expectedOutput += " - argument(Type=IntegerLiteralExpr): " + System.lineSeparator();
+ expectedOutput += " value: \"1\"" + System.lineSeparator();
+ expectedOutput += "...";
+
+ YamlPrinter yamlPrinter = new YamlPrinter(true);
+ Expression expression = JavaParser.parseExpression("x(1,1)");
+ String output = yamlPrinter.output(expression);
+ assertEquals(expectedOutput, output);
+ }
+
+ @Test
+ public void testWithoutType() {
+ String expectedOutput = "---" + System.lineSeparator();
+ expectedOutput += "root: " + System.lineSeparator();
+ expectedOutput += " operator: \"PLUS\"" + System.lineSeparator();
+ expectedOutput += " left: " + System.lineSeparator();
+ expectedOutput += " value: \"1\"" + System.lineSeparator();
+ expectedOutput += " right: " + System.lineSeparator();
+ expectedOutput += " value: \"1\"" + System.lineSeparator();
+ expectedOutput += "...";
+
+ YamlPrinter yamlPrinter = new YamlPrinter(false);
+ Expression expression = JavaParser.parseExpression("1+1");
+ String output = yamlPrinter.output(expression);
+ assertEquals(expectedOutput, output);
+ }
+
+ @Test
+ public void testWithColonFollowedBySpaceInValue() {
+ String expectedOutput = "---" + System.lineSeparator();
+ expectedOutput += "root(Type=StringLiteralExpr): " + System.lineSeparator();
+ expectedOutput += " value: \"a\\\\: b\"" + System.lineSeparator();
+ expectedOutput += "...";
+
+ YamlPrinter yamlPrinter = new YamlPrinter(true);
+ Expression expression = JavaParser.parseExpression("\"a\\\\: b\"");
+ String output = yamlPrinter.output(expression);
+ assertEquals(expectedOutput, output);
+ }
+
+ @Test
+ public void testWithColonFollowedByLineSeparatorInValue() {
+ String expectedOutput = "---" + System.lineSeparator();
+ expectedOutput += "root(Type=StringLiteralExpr): " + System.lineSeparator();
+ expectedOutput += " value: \"a\\\\:\\\\nb\"" + System.lineSeparator();
+ expectedOutput += "...";
+
+ YamlPrinter yamlPrinter = new YamlPrinter(true);
+ Expression expression = JavaParser.parseExpression("\"a\\\\:\\\\nb\"");
+ String output = yamlPrinter.output(expression);
+ assertEquals(expectedOutput, output);
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/AbstractLexicalPreservingTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/AbstractLexicalPreservingTest.java
new file mode 100644
index 000000000..108845772
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/AbstractLexicalPreservingTest.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.printer.lexicalpreservation;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.ast.CompilationUnit;
+import com.github.javaparser.ast.Node;
+import com.github.javaparser.ast.expr.Expression;
+import org.junit.Before;
+
+import java.io.IOException;
+
+import static com.github.javaparser.utils.TestUtils.readResource;
+import static org.junit.Assert.assertEquals;
+
+public abstract class AbstractLexicalPreservingTest {
+
+ protected CompilationUnit cu;
+ protected Expression expression;
+
+ protected void considerCode(String code) {
+ cu = LexicalPreservingPrinter.setup(JavaParser.parse(code));
+ }
+
+ protected void considerExpression(String code) {
+ expression = LexicalPreservingPrinter.setup(JavaParser.parseExpression(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);
+ assertEquals(expectedCode, actualCode);
+ }
+
+ protected void assertUnchanged(String exampleName) throws IOException {
+ String code = considerExample(exampleName + "_original");
+ assertEquals(code, LexicalPreservingPrinter.print(cu != null ? cu : expression));
+ }
+
+ protected void assertTransformedToString(String expectedPartialCode, Node node) {
+ String actualCode = LexicalPreservingPrinter.print(node);
+ assertEquals(expectedPartialCode, actualCode);
+ }
+
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/DifferenceTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/DifferenceTest.java
new file mode 100644
index 000000000..2fb98c1f5
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/DifferenceTest.java
@@ -0,0 +1,428 @@
+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.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.Test;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.EnumSet;
+
+import static com.github.javaparser.TokenTypes.eolTokenKind;
+import static com.github.javaparser.TokenTypes.spaceTokenKind;
+import static com.github.javaparser.printer.lexicalpreservation.Difference.DifferenceElement.*;
+import static org.junit.Assert.assertEquals;
+
+public class DifferenceTest extends AbstractLexicalPreservingTest {
+
+ @Test
+ public void calculateDifferenceEmpty() {
+ LexicalDifferenceCalculator.CalculatedSyntaxModel a = new LexicalDifferenceCalculator.CalculatedSyntaxModel(Collections.emptyList());
+ LexicalDifferenceCalculator.CalculatedSyntaxModel b = new LexicalDifferenceCalculator.CalculatedSyntaxModel(Collections.emptyList());
+ Difference diff = Difference.calculate(a, b);
+ assertEquals(0, diff.getElements().size());
+ }
+
+ @Test
+ public 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)));
+ Difference diff = Difference.calculate(a, b);
+ assertEquals(4, diff.getElements().size());
+ assertEquals(added(new CsmToken(GeneratedJavaParserConstants.LPAREN)), diff.getElements().get(0));
+ assertEquals(added(new CsmChild(n1)), diff.getElements().get(1));
+ assertEquals(added(new CsmToken(GeneratedJavaParserConstants.RPAREN)), diff.getElements().get(2));
+ assertEquals(added(new CsmChild(n2)), diff.getElements().get(3));
+ }
+
+ @Test
+ public 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());
+ Difference diff = Difference.calculate(a, b);
+ assertEquals(4, diff.getElements().size());
+ assertEquals(removed(new CsmToken(GeneratedJavaParserConstants.LPAREN)), diff.getElements().get(0));
+ assertEquals(removed(new CsmChild(n1)), diff.getElements().get(1));
+ assertEquals(removed(new CsmToken(GeneratedJavaParserConstants.RPAREN)), diff.getElements().get(2));
+ assertEquals(removed(new CsmChild(n2)), diff.getElements().get(3));
+ }
+
+ @Test
+ public 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);
+ Difference diff = Difference.calculate(csmOriginal, csmChanged);
+ assertEquals(3, diff.getElements().size());
+ assertEquals(added(new CsmChild(packageDeclaration)), diff.getElements().get(0));
+ assertEquals(kept(new CsmChild(cu.getType(0))), diff.getElements().get(1));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(2));
+ }
+
+ @Test
+ public 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, EnumSet.noneOf(Modifier.class), EnumSet.of(Modifier.PUBLIC));
+ Difference diff = Difference.calculate(csmOriginal, csmChanged);
+ diff.removeIndentationElements();
+ int i = 0;
+ assertEquals(added(new CsmToken(GeneratedJavaParserConstants.PUBLIC)), diff.getElements().get(i++));
+ assertEquals(added(new CsmToken(spaceTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.AT)), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.INTERFACE)), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getName())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.LBRACE)), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getMember(0))), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getMember(1))), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getMember(2))), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getMember(3))), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getMember(4))), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getMember(5))), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.RBRACE)), diff.getElements().get(i++));
+ assertEquals(i, diff.getElements().size());
+ }
+
+ @Test
+ public 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);
+ Difference diff = Difference.calculate(csmOriginal, csmChanged);
+ diff.removeIndentationElements();
+ int i = 0;
+ assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.AT)), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.INTERFACE)), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++));
+ assertEquals(removed(new CsmChild(annotationDeclaration.getName())), diff.getElements().get(i++));
+ assertEquals(added(new CsmChild(newName)), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.LBRACE)), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getMember(0))), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getMember(1))), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getMember(2))), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getMember(3))), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getMember(4))), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getMember(5))), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.RBRACE)), diff.getElements().get(i++));
+ assertEquals(i, diff.getElements().size());
+ }
+
+ @Test
+ public 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);
+ Difference diff = Difference.calculate(csmOriginal, csmChanged);
+ diff.removeIndentationElements();
+ int i = 0;
+ assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.PUBLIC)), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.AT)), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.INTERFACE)), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getName())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.LBRACE)), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getMember(0))), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getMember(1))), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getMember(2))), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getMember(3))), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getMember(4))), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getMember(5))), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.RBRACE)), diff.getElements().get(i++));
+ assertEquals(i, diff.getElements().size());
+ }
+
+ @Test
+ public 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);
+ Difference diff = Difference.calculate(csmOriginal, csmChanged);
+ diff.removeIndentationElements();
+ int i = 0;
+ assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.PUBLIC)), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.AT)), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.INTERFACE)), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getName())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.LBRACE)), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getMember(0))), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getMember(1))), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getMember(2))), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getMember(3))), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getMember(4))), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getMember(5))), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.RBRACE)), diff.getElements().get(i++));
+ assertEquals(i, diff.getElements().size());
+ }
+
+ @Test
+ public 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, EnumSet.of(Modifier.PUBLIC), EnumSet.noneOf(Modifier.class));
+ Difference diff = Difference.calculate(csmOriginal, csmChanged);
+ diff.removeIndentationElements();
+ int i = 0;
+ assertEquals(removed(new CsmToken(GeneratedJavaParserConstants.PUBLIC)), diff.getElements().get(i++));
+ assertEquals(removed(new CsmToken(spaceTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.AT)), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.INTERFACE)), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getName())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.LBRACE)), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getMember(0))), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getMember(1))), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getMember(2))), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getMember(3))), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getMember(4))), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(annotationDeclaration.getMember(5))), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.RBRACE)), diff.getElements().get(i++));
+ assertEquals(i, diff.getElements().size());
+ }
+
+ @Test
+ public 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);
+ Difference diff = Difference.calculate(csmOriginal, csmChanged);
+ int i = 0;
+ assertEquals(kept(new CsmChild(md.getType())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(md.getName())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.LPAREN)), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.RPAREN)), diff.getElements().get(i++));
+ assertEquals(removed(new CsmToken(spaceTokenKind())), diff.getElements().get(i++));
+ assertEquals(removed(new CsmToken(GeneratedJavaParserConstants._DEFAULT)), diff.getElements().get(i++));
+ assertEquals(removed(new CsmToken(spaceTokenKind())), diff.getElements().get(i++));
+ assertEquals(removed(new CsmChild(md.getDefaultValue().get())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.SEMICOLON)), diff.getElements().get(i++));
+ assertEquals(i, diff.getElements().size());
+ }
+
+ @Test
+ public 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);
+ Difference diff = Difference.calculate(csmOriginal, csmChanged);
+ int i = 0;
+ assertEquals(kept(new CsmChild(md.getType())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(md.getName())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.LPAREN)), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.RPAREN)), diff.getElements().get(i++));
+ assertEquals(added(new CsmToken(spaceTokenKind())), diff.getElements().get(i++));
+ assertEquals(added(new CsmToken(GeneratedJavaParserConstants._DEFAULT)), diff.getElements().get(i++));
+ assertEquals(added(new CsmToken(spaceTokenKind())), diff.getElements().get(i++));
+ assertEquals(added(new CsmChild(defaultValue)), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.SEMICOLON)), diff.getElements().get(i++));
+ assertEquals(i, diff.getElements().size());
+ }
+
+ @Test
+ public void addedModifierToConstructorDeclaration() {
+ ConstructorDeclaration cd = considerCd("A(){}");
+ LexicalDifferenceCalculator.CalculatedSyntaxModel csmOriginal = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(cd);
+ LexicalDifferenceCalculator.CalculatedSyntaxModel csmChanged = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterPropertyChange(cd, ObservableProperty.MODIFIERS,
+ EnumSet.noneOf(Modifier.class), EnumSet.of(Modifier.PUBLIC));
+ Difference diff = Difference.calculate(csmOriginal, csmChanged);
+ int i = 0;
+ assertEquals(added(new CsmToken(GeneratedJavaParserConstants.PUBLIC)), diff.getElements().get(i++));
+ assertEquals(added(new CsmToken(spaceTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(cd.getName())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.LPAREN)), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.RPAREN)), diff.getElements().get(i++));
+ assertEquals(kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++));
+ assertEquals(kept(new CsmChild(cd.getBody())), diff.getElements().get(i++));
+ assertEquals(i, diff.getElements().size());
+ }
+
+ @Test
+ public void replacingNameForEnumConstantDeclaration() throws IOException {
+ 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);
+ Difference diff = Difference.calculate(csmOriginal, csmChanged);
+ int i = 0;
+ assertEquals(Difference.DifferenceElement.removed(new CsmChild(ecd.getName())), diff.getElements().get(i++));
+ assertEquals(Difference.DifferenceElement.added(new CsmChild(newName)), diff.getElements().get(i++));
+ assertEquals(i, diff.getElements().size());
+ }
+
+ @Test
+ public 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);
+ Difference diff = Difference.calculate(csmOriginal, csmChanged);
+ int i = 0;
+ assertEquals(Difference.DifferenceElement.kept(new CsmToken(GeneratedJavaParserConstants.LBRACE)), diff.getElements().get(i++));
+ assertEquals(Difference.DifferenceElement.kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(Difference.DifferenceElement.added(new CsmIndent()), diff.getElements().get(i++));
+ assertEquals(Difference.DifferenceElement.added(new CsmChild(s)), diff.getElements().get(i++));
+ assertEquals(Difference.DifferenceElement.added(new CsmToken(eolTokenKind())), diff.getElements().get(i++));
+ assertEquals(Difference.DifferenceElement.added(new CsmUnindent()), diff.getElements().get(i++));
+ assertEquals(Difference.DifferenceElement.kept(new CsmToken(GeneratedJavaParserConstants.RBRACE)), diff.getElements().get(i++));
+ assertEquals(i, diff.getElements().size());
+ }
+
+ @Test
+ public 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);
+ Difference diff = Difference.calculate(csmOriginal, csmChanged);
+ int i = 0;
+ assertEquals(Difference.DifferenceElement.kept(new CsmToken(GeneratedJavaParserConstants.PUBLIC)), diff.getElements().get(i++));
+ assertEquals(Difference.DifferenceElement.kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++));
+ assertEquals(Difference.DifferenceElement.kept(new CsmChild(md.getType())), diff.getElements().get(i++));
+ assertEquals(Difference.DifferenceElement.kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++));
+ assertEquals(Difference.DifferenceElement.kept(new CsmChild(md.getName())), diff.getElements().get(i++));
+ assertEquals(Difference.DifferenceElement.kept(new CsmToken(GeneratedJavaParserConstants.LPAREN)), diff.getElements().get(i++));
+ assertEquals(Difference.DifferenceElement.removed(new CsmChild(md.getParameter(0))), diff.getElements().get(i++));
+ assertEquals(Difference.DifferenceElement.kept(new CsmToken(GeneratedJavaParserConstants.RPAREN)), diff.getElements().get(i++));
+ assertEquals(Difference.DifferenceElement.kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++));
+ assertEquals(Difference.DifferenceElement.kept(new CsmChild(md.getBody().get())), diff.getElements().get(i++));
+ assertEquals(i, diff.getElements().size());
+ }
+
+ @Test
+ public 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);
+ Difference diff = Difference.calculate(csmOriginal, csmChanged);
+ int i = 0;
+ assertEquals(Difference.DifferenceElement.kept(new CsmToken(GeneratedJavaParserConstants.PUBLIC)), diff.getElements().get(i++));
+ assertEquals(Difference.DifferenceElement.kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++));
+ assertEquals(Difference.DifferenceElement.kept(new CsmChild(md.getType())), diff.getElements().get(i++));
+ assertEquals(Difference.DifferenceElement.kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++));
+ assertEquals(Difference.DifferenceElement.kept(new CsmChild(md.getName())), diff.getElements().get(i++));
+ assertEquals(Difference.DifferenceElement.kept(new CsmToken(GeneratedJavaParserConstants.LPAREN)), diff.getElements().get(i++));
+ assertEquals(Difference.DifferenceElement.added(new CsmChild(newParameter)), diff.getElements().get(i++));
+ assertEquals(Difference.DifferenceElement.kept(new CsmToken(GeneratedJavaParserConstants.RPAREN)), diff.getElements().get(i++));
+ assertEquals(Difference.DifferenceElement.kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++));
+ assertEquals(Difference.DifferenceElement.kept(new CsmChild(md.getBody().get())), diff.getElements().get(i++));
+ assertEquals(i, diff.getElements().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-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/LexicalDifferenceCalculatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/LexicalDifferenceCalculatorTest.java
new file mode 100644
index 000000000..d3e5490c0
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/LexicalDifferenceCalculatorTest.java
@@ -0,0 +1,300 @@
+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.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 org.junit.Test;
+
+import java.io.IOException;
+import java.util.EnumSet;
+
+import static com.github.javaparser.TokenTypes.eolTokenKind;
+import static com.github.javaparser.TokenTypes.spaceTokenKind;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+public class LexicalDifferenceCalculatorTest extends AbstractLexicalPreservingTest {
+
+ @Test
+ public 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 LexicalDifferenceCalculator.CsmChild(cu.getType(0)), csmOriginal.elements.get(0));
+ assertEquals(new CsmToken(eolTokenKind()), csmOriginal.elements.get(1));
+ }
+
+ @Test
+ public 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 LexicalDifferenceCalculator.CsmChild(packageDeclaration), csmChanged.elements.get(0));
+ assertEquals(new LexicalDifferenceCalculator.CsmChild(cu.getType(0)), csmChanged.elements.get(1));
+ assertEquals(new CsmToken(eolTokenKind()), csmChanged.elements.get(2));
+ }
+
+ @Test
+ public 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 LexicalDifferenceCalculator.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 LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(0)), csm.elements.get(i++));
+ assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++));
+ assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(1)), csm.elements.get(i++));
+ assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++));
+ assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(2)), csm.elements.get(i++));
+ assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++));
+ assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(3)), csm.elements.get(i++));
+ assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++));
+ assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(4)), csm.elements.get(i++));
+ assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++));
+ assertEquals(new LexicalDifferenceCalculator.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
+ public 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, EnumSet.noneOf(Modifier.class), EnumSet.of(Modifier.PUBLIC));
+ csm.removeIndentationElements();
+ int i = 0;
+ assertEquals(new CsmToken(GeneratedJavaParserConstants.PUBLIC), 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 LexicalDifferenceCalculator.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 LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(0)), csm.elements.get(i++));
+ assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++));
+ assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(1)), csm.elements.get(i++));
+ assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++));
+ assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(2)), csm.elements.get(i++));
+ assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++));
+ assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(3)), csm.elements.get(i++));
+ assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++));
+ assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(4)), csm.elements.get(i++));
+ assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++));
+ assertEquals(new LexicalDifferenceCalculator.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
+ public 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 LexicalDifferenceCalculator.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 LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(0)), csm.elements.get(i++));
+ assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++));
+ assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(1)), csm.elements.get(i++));
+ assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++));
+ assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(2)), csm.elements.get(i++));
+ assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++));
+ assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(3)), csm.elements.get(i++));
+ assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++));
+ assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(4)), csm.elements.get(i++));
+ assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++));
+ assertEquals(new LexicalDifferenceCalculator.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
+ public void annotationDeclaratioJavadocExampleOriginal() 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 CsmToken(GeneratedJavaParserConstants.PUBLIC), 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 LexicalDifferenceCalculator.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 LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(0)), csm.elements.get(i++));
+ assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++));
+ assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(1)), csm.elements.get(i++));
+ assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++));
+ assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(2)), csm.elements.get(i++));
+ assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++));
+ assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(3)), csm.elements.get(i++));
+ assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++));
+ assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(4)), csm.elements.get(i++));
+ assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++));
+ assertEquals(new LexicalDifferenceCalculator.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
+ public void annotationDeclaratioJavadocExampleAddingJavadoc() 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 CsmToken(GeneratedJavaParserConstants.PUBLIC), 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 LexicalDifferenceCalculator.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 LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(0)), csm.elements.get(i++));
+ assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++));
+ assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(1)), csm.elements.get(i++));
+ assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++));
+ assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(2)), csm.elements.get(i++));
+ assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++));
+ assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(3)), csm.elements.get(i++));
+ assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++));
+ assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(4)), csm.elements.get(i++));
+ assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++));
+ assertEquals(new LexicalDifferenceCalculator.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
+ public void simpleEnumConstantDeclaration() throws IOException {
+ EnumConstantDeclaration ecd = considerEcd("A");
+ LexicalDifferenceCalculator.CalculatedSyntaxModel csm = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(ecd);
+
+ int i = 0;
+ assertEquals(new LexicalDifferenceCalculator.CsmChild(ecd.getName()), csm.elements.get(i++));
+ assertEquals(i, csm.elements.size());
+ }
+
+ @Test
+ public 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
+ public 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
+ ));
+ Difference diff = ldc.calculateListAdditionDifference(
+ ObservableProperty.STATEMENTS,
+ setter.getBody().get().getStatements(),
+ 0,
+ assignStatement);
+ int index = 0;
+ assertEquals(Difference.DifferenceElement.kept(CsmElement.token(GeneratedJavaParserConstants.LBRACE)), diff.getElements().get(index++));
+ assertEquals(Difference.DifferenceElement.kept(CsmElement.newline()), diff.getElements().get(index++));
+ assertEquals(Difference.DifferenceElement.added(CsmElement.indent()), diff.getElements().get(index++));
+ assertTrue(isAddedChild(diff.getElements().get(index++), ExpressionStmt.class));
+ assertEquals(Difference.DifferenceElement.added(CsmElement.newline()), diff.getElements().get(index++));
+ assertEquals(Difference.DifferenceElement.added(CsmElement.unindent()), diff.getElements().get(index++));
+ assertEquals(Difference.DifferenceElement.kept(CsmElement.token(GeneratedJavaParserConstants.RBRACE)), diff.getElements().get(index++));
+ assertEquals(index, diff.getElements().size());
+ }
+
+ private boolean isAddedChild(Difference.DifferenceElement element, Class<? extends Node> childClass) {
+ return element.isAdded() && isChild(element.getElement(), childClass);
+ }
+
+ private boolean isChild(CsmElement element, Class<? extends Node> childClass) {
+ return element instanceof LexicalDifferenceCalculator.CsmChild && childClass.isInstance(((LexicalDifferenceCalculator.CsmChild)element).getChild());
+ }
+
+ protected EnumConstantDeclaration considerEcd(String code) {
+ considerCode("enum A { " + code + " }");
+ return ((EnumDeclaration)cu.getType(0)).getEntries().get(0);
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinterTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinterTest.java
new file mode 100644
index 000000000..796da14a2
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinterTest.java
@@ -0,0 +1,1051 @@
+package com.github.javaparser.printer.lexicalpreservation;
+
+import com.github.javaparser.*;
+import com.github.javaparser.ast.*;
+import com.github.javaparser.ast.body.*;
+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 org.junit.Test;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import static com.github.javaparser.printer.lexicalpreservation.LexicalPreservingPrinter.NODE_TEXT_DATA;
+import static com.github.javaparser.utils.TestUtils.assertEqualsNoEol;
+import static com.github.javaparser.utils.Utils.EOL;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+public class LexicalPreservingPrinterTest extends AbstractLexicalPreservingTest {
+ private NodeText getTextForNode(Node node) {
+ return node.getData(NODE_TEXT_DATA);
+ }
+
+
+ //
+ // Tests on TextNode definition
+ //
+
+ @Test
+ public void checkNodeTextCreatedForSimplestClass() {
+ considerCode("class A {}");
+
+ // CU
+ assertEquals(1, getTextForNode(cu).numberOfElements());
+ assertEquals(true, 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());
+ assertEquals(true, getTextForNode(classA).getTextElement(6) instanceof TokenTextElement);
+ assertEquals(GeneratedJavaParserConstants.EOF, ((TokenTextElement)getTextForNode(classA).getTextElement(6)).getTokenKind());
+ }
+
+ @Test
+ public 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
+ public 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
+ public 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
+ public 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
+ public 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
+ public 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
+ public void checkNodeTextCreatedGenericType() {
+ String code = "class A {ParseResult<T> 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
+ public 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
+ public 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
+ public 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
+ public void checkNodeTextCreatedAnnotationMemberDeclarationArrayType() {
+ String code = "public @interface ClassPreamble { String[] author(); }";
+ considerCode(code);
+
+ AnnotationDeclaration ad = cu.getAnnotationDeclarationByName("ClassPreamble").get();
+ AnnotationMemberDeclaration md = (AnnotationMemberDeclaration)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
+ public void checkNodeTextCreatedAnnotationMemberDeclarationWithComment() throws IOException {
+ considerExample("AnnotationDeclaration_Example3_original");
+
+ AnnotationMemberDeclaration md = (AnnotationMemberDeclaration)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
+ public void checkNodeTextCreatedArrayCreationLevelWithoutExpression() throws IOException {
+ considerExpression("new int[]");
+
+ ArrayCreationExpr 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
+ public void checkNodeTextCreatedArrayCreationLevelWith() throws IOException {
+ considerExpression("new int[123]");
+
+ ArrayCreationExpr 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
+ public void findIndentationForAnnotationMemberDeclarationWithoutComment() throws IOException {
+ considerExample("AnnotationDeclaration_Example3_original");
+ Node node = cu.getAnnotationDeclarationByName("ClassPreamble").get().getMember(4);
+ List<TokenTextElement> indentation = LexicalPreservingPrinter.findIndentation(node);
+ assertEquals(Arrays.asList(" ", " ", " "), indentation.stream().map(TokenTextElement::expand).collect(Collectors.toList()));
+ }
+
+ @Test
+ public void findIndentationForAnnotationMemberDeclarationWithComment() throws IOException {
+ considerExample("AnnotationDeclaration_Example3_original");
+ Node node = cu.getAnnotationDeclarationByName("ClassPreamble").get().getMember(5);
+ List<TokenTextElement> indentation = LexicalPreservingPrinter.findIndentation(node);
+ assertEquals(Arrays.asList(" ", " ", " "), indentation.stream().map(TokenTextElement::expand).collect(Collectors.toList()));
+ }
+
+ //
+ // Tests on printing
+ //
+
+ @Test
+ public void printASuperSimpleCUWithoutChanges() {
+ String code = "class A {}";
+ considerCode(code);
+
+ assertEquals(code, LexicalPreservingPrinter.print(cu));
+ }
+
+ @Test
+ public void printASuperSimpleClassWithAFieldAdded() {
+ String code = "class A {}";
+ considerCode(code);
+
+ ClassOrInterfaceDeclaration classA = cu.getClassByName("A").get();
+ classA.addField("int", "myField");
+ assertEquals("class A {" + EOL + " int myField;"+EOL+"}", LexicalPreservingPrinter.print(classA));
+ }
+
+ @Test
+ public void printASuperSimpleClassWithoutChanges() {
+ String code = "class A {}";
+ considerCode(code);
+
+ assertEquals(code, LexicalPreservingPrinter.print(cu.getClassByName("A").get()));
+ }
+
+ @Test
+ public void printASimpleCUWithoutChanges() {
+ String code = "class /*a comment*/ A {\t\t"+EOL+" int f;"+EOL+EOL+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
+ public void printASimpleClassRemovingAField() {
+ String code = "class /*a comment*/ A {\t\t"+EOL+" int f;"+EOL+EOL+EOL+" void foo(int p ) { return 'z' \t; }}";
+ considerCode(code);
+
+ ClassOrInterfaceDeclaration c = cu.getClassByName("A").get();
+ c.getMembers().remove(0);
+ assertEquals("class /*a comment*/ A {\t\t"+ EOL +
+ EOL +
+ " void foo(int p ) { return 'z' \t; }}", LexicalPreservingPrinter.print(c));
+ }
+
+ @Test
+ public 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
+ public 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
+ public 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
+ public 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
+ public 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
+ public 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<Statement> 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) {"+EOL +
+ " 10 + 2;"+ EOL +
+ "}", LexicalPreservingPrinter.print(m));
+ }
+
+ @Test
+ public 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
+ public 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
+ public 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
+ public void checkAnnidatedTypeParametersPrinting() {
+ String code = "class A { private final Stack<Iterator<Triple>> its = new Stack<Iterator<Triple>>(); }";
+ considerCode(code);
+ assertEquals("class A { private final Stack<Iterator<Triple>> its = new Stack<Iterator<Triple>>(); }", LexicalPreservingPrinter.print(cu));
+ }
+
+ @Test
+ public 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
+ public 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
+ public 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
+ public 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
+ public 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
+ public void printLambaWithUntypedParams() {
+ String code = "class A {Function<String,String> f = a -> a;}";
+ considerCode(code);
+
+ assertEquals("class A {Function<String,String> f = a -> a;}", LexicalPreservingPrinter.print(cu));
+ }
+
+ @Test
+ public void printAModuleInfoSpecificKeywordUsedAsIdentifier1() {
+ considerCode("class module { }");
+
+ cu.getClassByName("module").get().setName("xyz");
+
+ assertEquals("class xyz { }", LexicalPreservingPrinter.print(cu));
+ }
+
+ @Test
+ public 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
+ public void reactToSetPackageDeclarationOnCuStartingWithComment() {
+ considerCode("// Hey, this is a comment\n" +
+ "\n" +
+ "\n" +
+ "// Another one\n" +
+ "\n" +
+ "class A {}");
+ cu.setPackageDeclaration("org.javaparser.lexicalpreservation.examples");
+ }
+
+ @Test
+ public void printLambdaIntersectionTypeAssignment() {
+ String code = "class A {" + EOL +
+ " void f() {" + EOL +
+ " Runnable r = (Runnable & Serializable) (() -> {});" + EOL +
+ " r = (Runnable & Serializable)() -> {};" + EOL +
+ " r = (Runnable & I)() -> {};" + EOL +
+ " }}";
+ considerCode(code);
+
+ assertEquals(code, LexicalPreservingPrinter.print(cu));
+ }
+
+ @Test
+ public void printLambdaIntersectionTypeReturn() {
+ String code = "class A {" + EOL
+ + " Object f() {" + EOL
+ + " return (Comparator<Map.Entry<K, V>> & Serializable)(c1, c2) -> c1.getKey().compareTo(c2.getKey()); " + EOL
+ + "}}";
+ considerCode(code);
+
+ assertEquals(code, LexicalPreservingPrinter.print(cu));
+ }
+
+ // See issue #855
+ @Test
+ public void handleOverrideAnnotation() {
+ String code = "public class TestPage extends Page {" + EOL +
+ EOL +
+ " protected void test() {}" + EOL +
+ EOL +
+ " @Override" + EOL +
+ " protected void initializePage() {}" + EOL +
+ "}";
+
+ CompilationUnit cu = JavaParser.parse(code);
+ LexicalPreservingPrinter.setup(cu);
+
+ 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 {" + EOL +
+ EOL +
+ " @Override()" + EOL +
+ " protected void test() {}" + EOL +
+ EOL +
+ " @Override" + EOL +
+ " protected void initializePage() {}" + EOL +
+ "}", LexicalPreservingPrinter.print(cu));
+ }
+
+ @Test
+ public void preserveSpaceAsIsForASimpleClassWithMoreFormatting() throws IOException {
+ considerExample("ASimpleClassWithMoreFormatting");
+ assertEquals(readExample("ASimpleClassWithMoreFormatting"), LexicalPreservingPrinter.print(cu));
+ }
+
+ @Test
+ public void renameASimpleClassWithMoreFormatting() throws IOException {
+ considerExample("ASimpleClassWithMoreFormatting");
+
+ cu.getClassByName("ASimpleClass").get()
+ .setName("MyRenamedClass");
+ assertEquals(readExample("ASimpleClassWithMoreFormatting_step1"), LexicalPreservingPrinter.print(cu));
+ }
+
+ @Test
+ public void theLexicalPreservationStringForAnAddedMethodShouldBeIndented() throws IOException {
+ considerExample("ASimpleClassWithMoreFormatting");
+
+ cu.getClassByName("ASimpleClass").get()
+ .setName("MyRenamedClass");
+ MethodDeclaration setter = cu
+ .getClassByName("MyRenamedClass").get()
+ .addMethod("setAField", Modifier.PUBLIC);
+ assertEquals("public void setAField() {" + EOL +
+ " }", LexicalPreservingPrinter.print(setter));
+ }
+
+ @Test
+ public void addMethodToASimpleClassWithMoreFormatting() throws IOException {
+ considerExample("ASimpleClassWithMoreFormatting");
+
+ cu.getClassByName("ASimpleClass").get()
+ .setName("MyRenamedClass");
+ MethodDeclaration setter = cu
+ .getClassByName("MyRenamedClass").get()
+ .addMethod("setAField", Modifier.PUBLIC);
+ assertEquals(readExample("ASimpleClassWithMoreFormatting_step2"), LexicalPreservingPrinter.print(cu));
+ }
+
+ @Test
+ public void addingParameterToAnAddedMethodInASimpleClassWithMoreFormatting() throws IOException {
+ considerExample("ASimpleClassWithMoreFormatting");
+
+ cu.getClassByName("ASimpleClass").get()
+ .setName("MyRenamedClass");
+ MethodDeclaration setter = cu
+ .getClassByName("MyRenamedClass").get()
+ .addMethod("setAField", Modifier.PUBLIC);
+ setter.addParameter("boolean", "aField");
+ assertEquals(readExample("ASimpleClassWithMoreFormatting_step3"), LexicalPreservingPrinter.print(cu));
+ }
+
+ @Test
+ public 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
+ public 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
+ public void addingStatementToAnAddedMethodInASimpleClassWithMoreFormatting() throws IOException {
+ considerExample("ASimpleClassWithMoreFormatting");
+
+ cu.getClassByName("ASimpleClass").get()
+ .setName("MyRenamedClass");
+ MethodDeclaration setter = cu
+ .getClassByName("MyRenamedClass").get()
+ .addMethod("setAField", Modifier.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
+ )));
+ assertEquals(readExample("ASimpleClassWithMoreFormatting_step4"), LexicalPreservingPrinter.print(cu));
+ }
+
+ @Test
+ public 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
+ public 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++).isToken(GeneratedJavaParserConstants.PUBLIC));
+ 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
+ public 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++).isToken(GeneratedJavaParserConstants.PUBLIC));
+ 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
+ public 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(
+ JavaParser.parseClassOrInterfaceType("String"),
+ "test2",
+ new StringLiteralExpr("")))
+ ));
+ assertEquals("public void someMethod() {" + EOL
+ + " String test = \"\";" + EOL
+ + " String test2 = \"\";" + EOL
+ + " }", LexicalPreservingPrinter.print(methodDeclaration));
+ }
+
+ // See issue #866
+ @Test
+ public void moveOverrideAnnotations() {
+ String code = "public class TestPage extends Page {" + EOL +
+ EOL +
+ " protected void test() {}" + EOL +
+ EOL +
+ " protected @Override void initializePage() {}" + EOL +
+ "}";
+
+ CompilationUnit cu = JavaParser.parse(code);
+ LexicalPreservingPrinter.setup(cu);
+
+ 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 {" + EOL +
+ EOL +
+ " protected void test() {}" + EOL +
+ EOL +
+ " @Override" + EOL +
+ " protected void initializePage() {}" + EOL +
+ "}", LexicalPreservingPrinter.print(cu));
+ }
+
+ // See issue #866
+ @Test
+ public void moveOrAddOverrideAnnotations() {
+ String code = "public class TestPage extends Page {" + EOL +
+ EOL +
+ " protected void test() {}" + EOL +
+ EOL +
+ " protected @Override void initializePage() {}" + EOL +
+ "}";
+
+ CompilationUnit cu = JavaParser.parse(code);
+ LexicalPreservingPrinter.setup(cu);
+
+ 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 {" + EOL +
+ EOL +
+ " @Override" + EOL +
+ " protected void test() {}" + EOL +
+ EOL +
+ " @Override" + EOL +
+ " protected void initializePage() {}" + EOL +
+ "}", LexicalPreservingPrinter.print(cu));
+ }
+
+ // See issue #865
+ @Test
+ public void handleAddingMarkerAnnotation() {
+ String code = "public class TestPage extends Page {" + EOL +
+ EOL +
+ " protected void test() {}" + EOL +
+ EOL +
+ " @Override" + EOL +
+ " protected void initializePage() {}" + EOL +
+ "}";
+
+ CompilationUnit cu = JavaParser.parse(code);
+ LexicalPreservingPrinter.setup(cu);
+
+ 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 {" + EOL +
+ EOL +
+ " @Override" + EOL +
+ " protected void test() {}" + EOL +
+ EOL +
+ " @Override" + EOL +
+ " protected void initializePage() {}" + EOL +
+ "}", LexicalPreservingPrinter.print(cu));
+ }
+
+ // See issue #865
+ @Test
+ public void handleOverrideMarkerAnnotation() {
+ String code = "public class TestPage extends Page {" + EOL +
+ EOL +
+ " protected void test() {}" + EOL +
+ EOL +
+ " protected void initializePage() {}" + EOL +
+ "}";
+
+ CompilationUnit cu = JavaParser.parse(code);
+ LexicalPreservingPrinter.setup(cu);
+
+ cu.getTypes()
+ .forEach(type -> type.getMembers()
+ .forEach(member ->
+ member.ifMethodDeclaration(methodDeclaration -> methodDeclaration.addMarkerAnnotation("Override")
+ )));
+ assertEquals("public class TestPage extends Page {" + EOL +
+ EOL +
+ " @Override" + EOL +
+ " protected void test() {}" + EOL +
+ EOL +
+ " @Override" + EOL +
+ " protected void initializePage() {}" + EOL +
+ "}", LexicalPreservingPrinter.print(cu));
+ }
+
+ // See issue #865
+ @Test
+ public void handleOverrideAnnotationAlternative() {
+ String code = "public class TestPage extends Page {" + EOL +
+ EOL +
+ " protected void test() {}" + EOL +
+ EOL +
+ " protected void initializePage() {}" + EOL +
+ "}";
+
+ CompilationUnit cu = JavaParser.parse(code);
+ LexicalPreservingPrinter.setup(cu);
+
+ cu.getTypes()
+ .forEach(type -> type.getMembers()
+ .forEach(member -> member.ifMethodDeclaration(methodDeclaration -> methodDeclaration.addAnnotation("Override"))));
+ assertEquals("public class TestPage extends Page {" + EOL +
+ EOL +
+ " @Override()" + EOL +
+ " protected void test() {}" + EOL +
+ EOL +
+ " @Override()" + EOL +
+ " protected void initializePage() {}" + EOL +
+ "}", LexicalPreservingPrinter.print(cu));
+ }
+
+ @Test
+ public void invokeModifierVisitor() {
+ String code = "class A {" + EOL
+ + " Object f() {" + EOL
+ + " return (Comparator<Map.Entry<K, V>> & Serializable)(c1, c2) -> c1.getKey().compareTo(c2.getKey()); " + EOL
+ + "}}";
+ CompilationUnit cu = JavaParser.parse(code);
+ LexicalPreservingPrinter.setup(cu);
+ cu.accept(new ModifierVisitor<>(), null);
+ }
+
+ @Test
+ public void handleDeprecatedAnnotationFinalClass() {
+ String code = "public final class A {}";
+
+ CompilationUnit cu = JavaParser.parse(code);
+ LexicalPreservingPrinter.setup(cu);
+
+ cu.getTypes().forEach(type -> type.addAndGetAnnotation(Deprecated.class));
+
+ assertEquals("@Deprecated()" + EOL +
+ "public final class A {}" , LexicalPreservingPrinter.print(cu));
+
+ }
+
+ @Test
+ public void handleDeprecatedAnnotationAbstractClass() {
+ String code = "public abstract class A {}";
+
+ CompilationUnit cu = JavaParser.parse(code);
+ LexicalPreservingPrinter.setup(cu);
+
+ cu.getTypes().forEach(type -> type.addAndGetAnnotation(Deprecated.class));
+
+ assertEquals("@Deprecated()" + EOL +
+ "public abstract class A {}" , LexicalPreservingPrinter.print(cu));
+ }
+
+ @Test
+ public void issue1244() {
+ String code = "public class Foo {" + EOL + EOL
+ + "// Some comment" + EOL + EOL // does work with only one \n
+ + "public void writeExternal() {}" + EOL + "}";
+ CompilationUnit originalCu = JavaParser.parse(code);
+ CompilationUnit cu = LexicalPreservingPrinter.setup(originalCu);
+
+ cu.findAll(ClassOrInterfaceDeclaration.class).stream().forEach(c -> {
+ List<MethodDeclaration> methods = c.getMethodsByName("writeExternal");
+ for (MethodDeclaration method : methods) {
+ c.remove(method);
+ }
+ });
+ assertEqualsNoEol("public class Foo {\n" +
+ "// Some comment\n\n" +
+ "}", LexicalPreservingPrinter.print(cu));
+ }
+
+ static class AddFooCallModifierVisitor extends ModifierVisitor<Void> {
+ @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
+ public void testInvokeModifierVisitor() throws IOException {
+ String code = "class A {" + EOL +
+ " public String message = \"hello\";" + EOL +
+ " void bar() {" + EOL +
+ " System.out.println(\"hello\");" + EOL +
+ " }" + EOL +
+ "}";
+
+ CompilationUnit cu = JavaParser.parse(code);
+ LexicalPreservingPrinter.setup(cu);
+ cu.accept(new AddFooCallModifierVisitor(), null);
+ }
+
+ static class CallModifierVisitor extends ModifierVisitor<Void> {
+ @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
+ public void invokeModifierVisitorIssue1297() {
+ String code = "class A {" + EOL +
+ " public void bar() {" + EOL +
+ " System.out.println(\"hello\");" + EOL +
+ " System.out.println(\"hello\");" + EOL +
+ " // comment" + EOL +
+ " }" + EOL +
+ "}";
+
+ CompilationUnit cu = JavaParser.parse(code);
+ LexicalPreservingPrinter.setup(cu);
+ cu.accept(new CallModifierVisitor(), null);
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/TransformationsTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/TransformationsTest.java
new file mode 100644
index 000000000..ec89dd1ff
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/TransformationsTest.java
@@ -0,0 +1,143 @@
+package com.github.javaparser.printer.lexicalpreservation;
+
+import com.github.javaparser.ast.Modifier;
+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.ReturnStmt;
+import com.github.javaparser.ast.type.ArrayType;
+import com.github.javaparser.ast.type.PrimitiveType;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.util.EnumSet;
+
+/**
+ * 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.
+ */
+public class TransformationsTest extends AbstractLexicalPreservingTest {
+
+ @Test
+ public void unchangedSimpleClasses() throws IOException {
+ assertUnchanged("Example1");
+ assertUnchanged("Example2");
+ }
+
+ @Test
+ public void unchangedComplexFile() throws IOException {
+ assertUnchanged("Example4");
+ }
+
+ @Test
+ public void example1() throws IOException {
+ considerExample("Example1_original");
+ cu.getClassByName("A").get().getFieldByName("a").get().setModifiers(EnumSet.of(Modifier.STATIC));
+ assertTransformed("Example1", cu);
+ }
+
+ @Test
+ public void example2() throws IOException {
+ considerExample("Example2_original");
+ cu.getClassByName("A").get().getFieldByName("a").get().getVariable(0).setInitializer("10");
+ assertTransformed("Example2", cu);
+ }
+
+ @Test
+ public void example3() throws IOException {
+ considerExample("Example3_original");
+ cu.getClassByName("A").get().getFieldByName("a").get().getVariable(0).setInitializer((Expression) null);
+ assertTransformed("Example3", cu);
+ }
+
+ @Test
+ public void example5() throws IOException {
+ considerExample("Example5_original");
+ cu.getClassByName("A").get().getFieldByName("a").get().getVariable(0).setInitializer(new NullLiteralExpr());
+ assertTransformed("Example5", cu);
+ }
+
+ @Test
+ public void example6() throws IOException {
+ considerExample("Example6_original");
+ cu.getClassByName("A").get().getFieldByName("a").get().getVariable(0).setName("someOtherName");
+ assertTransformed("Example6", cu);
+ }
+
+ @Test
+ public 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
+ public void example8() throws IOException {
+ considerExample("Example8_original");
+ FieldDeclaration fd = (FieldDeclaration) cu.getClassByName("A").get().getMember(0).asFieldDeclaration();
+ fd.addVariable(new VariableDeclarator(PrimitiveType.intType(), "b"));
+ assertTransformed("Example8", cu);
+ }
+
+ @Test
+ public void example9() throws IOException {
+ considerExample("Example9_original");
+ FieldDeclaration fd = (FieldDeclaration) cu.getClassByName("A").get().getMember(0).asFieldDeclaration();
+ fd.addVariable(new VariableDeclarator(new ArrayType(PrimitiveType.intType()), "b"));
+ assertTransformed("Example9", cu);
+ }
+
+ @Test
+ public void example10() throws IOException {
+ considerExample("Example10_original");
+ cu.getClassByName("A").get().getMembers().remove(0);
+ assertTransformed("Example10", cu);
+ }
+
+ @Test
+ public void exampleParam1() throws IOException {
+ considerExample("Example_param1_original");
+ MethodDeclaration md = (MethodDeclaration) cu.getClassByName("A").get().getMember(0).asMethodDeclaration();
+ md.addParameter("int", "p1");
+ assertTransformed("Example_param1", cu);
+ }
+
+ @Test
+ public void exampleParam2() throws IOException {
+ considerExample("Example_param1_original");
+ MethodDeclaration md = (MethodDeclaration) cu.getClassByName("A").get().getMember(0).asMethodDeclaration();
+ md.addParameter(new ArrayType(PrimitiveType.intType()), "p1");
+ md.addParameter("char", "p2");
+ assertTransformed("Example_param2", cu);
+ }
+
+ @Test
+ public void exampleParam3() throws IOException {
+ considerExample("Example_param3_original");
+ MethodDeclaration md = (MethodDeclaration) cu.getClassByName("A").get().getMember(0).asMethodDeclaration();
+ md.getParameters().remove(0);
+ assertTransformed("Example_param3", cu);
+ }
+
+ @Test
+ public void exampleParam4() throws IOException {
+ considerExample("Example_param3_original");
+ MethodDeclaration md = (MethodDeclaration) cu.getClassByName("A").get().getMember(0).asMethodDeclaration();
+ md.getParameters().remove(1);
+ assertTransformed("Example_param4", cu);
+ }
+
+ @Test
+ public void exampleParam5() throws IOException {
+ considerExample("Example_param3_original");
+ MethodDeclaration md = (MethodDeclaration) 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")));
+ assertTransformed("Example_param5", cu);
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/ArrayCreationLevelTransformationsTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/ArrayCreationLevelTransformationsTest.java
new file mode 100644
index 000000000..93cff347e
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/ArrayCreationLevelTransformationsTest.java
@@ -0,0 +1,93 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package 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.Test;
+
+import java.io.IOException;
+
+/**
+ * Transforming ArrayCreationLevel and verifying the LexicalPreservation works as expected.
+ */
+public class ArrayCreationLevelTransformationsTest extends AbstractLexicalPreservingTest {
+
+ protected ArrayCreationLevel consider(String code) {
+ considerExpression("new int" + code);
+ ArrayCreationExpr arrayCreationExpr = expression.asArrayCreationExpr();
+ return arrayCreationExpr.getLevels().get(0);
+ }
+
+ // Dimension
+
+ @Test
+ public void addingDimension() throws IOException {
+ ArrayCreationLevel it = consider("[]");
+ it.setDimension(new IntegerLiteralExpr("10"));
+ assertTransformedToString("[10]", it);
+ }
+
+ @Test
+ public void removingDimension() throws IOException {
+ ArrayCreationLevel it = consider("[10]");
+ it.removeDimension();
+ assertTransformedToString("[]", it);
+ }
+
+ @Test
+ public void replacingDimension() throws IOException {
+ ArrayCreationLevel it = consider("[10]");
+ it.setDimension(new IntegerLiteralExpr("12"));
+ assertTransformedToString("[12]", it);
+ }
+
+ // Annotations
+
+ @Test
+ public void addingAnnotation() throws IOException {
+ ArrayCreationLevel it = consider("[]");
+ it.addAnnotation("myAnno");
+ assertTransformedToString("@myAnno()"+ Utils.EOL+"[]", it);
+ }
+
+ @Test
+ public void removingAnnotation() throws IOException {
+ ArrayCreationLevel it = consider("@myAnno []");
+ it.getAnnotations().remove(0);
+ assertTransformedToString("[]", it);
+ }
+
+ @Test
+ public void replacingAnnotation() throws IOException {
+ ArrayCreationLevel it = consider("@myAnno []");
+ it.getAnnotations().set(0, new NormalAnnotationExpr(new Name("myOtherAnno"), new NodeList<>()));
+ assertTransformedToString("@myOtherAnno() []", it);
+ }
+
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/CompilationUnitTransformationsTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/CompilationUnitTransformationsTest.java
new file mode 100644
index 000000000..304037829
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/CompilationUnitTransformationsTest.java
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package 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.Test;
+
+import java.io.IOException;
+
+import static com.github.javaparser.utils.Utils.EOL;
+
+/**
+ * Transforming CompilationUnit and verifying the LexicalPreservation works as expected.
+ */
+public class CompilationUnitTransformationsTest extends AbstractLexicalPreservingTest {
+
+ // packageDeclaration
+
+ @Test
+ public void addingPackageDeclaration() throws IOException {
+ considerCode("class A {}");
+ cu.setPackageDeclaration(new PackageDeclaration(new Name(new Name("foo"), "bar")));
+ assertTransformedToString("package foo.bar;"+ EOL + EOL + "class A {}", cu);
+ }
+
+ @Test
+ public void removingPackageDeclaration() throws IOException {
+ considerCode("package foo.bar; class A {}");
+ cu.removePackageDeclaration();
+ assertTransformedToString("class A {}", cu);
+ }
+
+ @Test
+ public void replacingPackageDeclaration() throws IOException {
+ considerCode("package foo.bar; class A {}");
+ cu.setPackageDeclaration(new PackageDeclaration(new Name(new Name("foo2"), "baz")));
+ assertTransformedToString("package foo2.baz;" +
+ EOL + EOL +
+ " class A {}", cu);
+ }
+
+ // imports
+
+ // types
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/AnnotationDeclarationTransformationsTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/AnnotationDeclarationTransformationsTest.java
new file mode 100644
index 000000000..a2ffd40a1
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/AnnotationDeclarationTransformationsTest.java
@@ -0,0 +1,126 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.printer.lexicalpreservation.transformations.ast.body;
+
+import com.github.javaparser.ast.Modifier;
+import com.github.javaparser.ast.body.AnnotationMemberDeclaration;
+import com.github.javaparser.ast.type.PrimitiveType;
+import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.util.EnumSet;
+
+import static org.junit.Assert.assertEquals;
+
+/**
+ * Transforming AnnotationDeclaration and verifying the LexicalPreservation works as expected.
+ */
+public class AnnotationDeclarationTransformationsTest extends AbstractLexicalPreservingTest {
+
+ @Test
+ public void unchangedExamples() throws IOException {
+ assertUnchanged("AnnotationDeclaration_Example1");
+ assertUnchanged("AnnotationDeclaration_Example3");
+ assertUnchanged("AnnotationDeclaration_Example9");
+ }
+
+ // name
+
+ @Test
+ public void changingName() throws IOException {
+ considerExample("AnnotationDeclaration_Example1_original");
+ cu.getAnnotationDeclarationByName("ClassPreamble").get().setName("NewName");
+ assertTransformed("AnnotationDeclaration_Example1", cu);
+ }
+
+ // modifiers
+
+ @Test
+ public void addingModifiers() throws IOException {
+ considerExample("AnnotationDeclaration_Example1_original");
+ cu.getAnnotationDeclarationByName("ClassPreamble").get().setModifiers(EnumSet.of(Modifier.PUBLIC));
+ assertTransformed("AnnotationDeclaration_Example2", cu);
+ }
+
+ @Test
+ public void removingModifiers() throws IOException {
+ considerExample("AnnotationDeclaration_Example3_original");
+ cu.getAnnotationDeclarationByName("ClassPreamble").get().setModifiers(EnumSet.noneOf(Modifier.class));
+ assertTransformed("AnnotationDeclaration_Example3", cu);
+ }
+
+ @Test
+ public void replacingModifiers() throws IOException {
+ considerExample("AnnotationDeclaration_Example3_original");
+ cu.getAnnotationDeclarationByName("ClassPreamble").get().setModifiers(EnumSet.of(Modifier.PROTECTED));
+ assertTransformed("AnnotationDeclaration_Example4", cu);
+ }
+
+ // members
+
+ @Test
+ public void addingMember() throws IOException {
+ considerExample("AnnotationDeclaration_Example3_original");
+ cu.getAnnotationDeclarationByName("ClassPreamble").get().addMember(new AnnotationMemberDeclaration(EnumSet.noneOf(Modifier.class), PrimitiveType.intType(), "foo", null));
+ assertTransformed("AnnotationDeclaration_Example5", cu);
+ }
+
+ @Test
+ public void removingMember() throws IOException {
+ considerExample("AnnotationDeclaration_Example3_original");
+ cu.getAnnotationDeclarationByName("ClassPreamble").get().getMember(2).remove();
+ assertTransformed("AnnotationDeclaration_Example6", cu);
+ }
+
+ @Test
+ public void replacingMember() throws IOException {
+ considerExample("AnnotationDeclaration_Example3_original");
+ cu.getAnnotationDeclarationByName("ClassPreamble").get().setMember(2, new AnnotationMemberDeclaration(EnumSet.noneOf(Modifier.class), PrimitiveType.intType(), "foo", null));
+ assertTransformed("AnnotationDeclaration_Example7", cu);
+ }
+
+ // javadoc
+
+ @Test
+ public void addingJavadoc() throws IOException {
+ considerExample("AnnotationDeclaration_Example3_original");
+ cu.getAnnotationDeclarationByName("ClassPreamble").get().setJavadocComment("Cool this annotation!");
+ assertTransformed("AnnotationDeclaration_Example8", cu);
+ }
+
+ @Test
+ public void removingJavadoc() throws IOException {
+ considerExample("AnnotationDeclaration_Example9_original");
+ boolean removed = cu.getAnnotationDeclarationByName("ClassPreamble").get().getJavadocComment().get().remove();
+ assertEquals(true, removed);
+ assertTransformed("AnnotationDeclaration_Example9", cu);
+ }
+
+ @Test
+ public 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-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/AnnotationMemberDeclarationTransformationsTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/AnnotationMemberDeclarationTransformationsTest.java
new file mode 100644
index 000000000..6b5552807
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/AnnotationMemberDeclarationTransformationsTest.java
@@ -0,0 +1,175 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package 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.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.Test;
+
+import java.util.EnumSet;
+
+import static com.github.javaparser.utils.Utils.EOL;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * Transforming AnnotationMemberDeclaration and verifying the LexicalPreservation works as expected.
+ */
+public class AnnotationMemberDeclarationTransformationsTest extends AbstractLexicalPreservingTest {
+
+ protected AnnotationMemberDeclaration consider(String code) {
+ considerCode("@interface AD { " + code + " }");
+ return cu.getAnnotationDeclarationByName("AD").get().getMember(0).asAnnotationMemberDeclaration();
+ }
+
+ // Name
+
+ @Test
+ public void changingName() {
+ AnnotationMemberDeclaration md = consider("int foo();");
+ md.setName("bar");
+ assertTransformedToString("int bar();", md);
+ }
+
+ // Type
+
+ @Test
+ public void changingType() {
+ AnnotationMemberDeclaration md = consider("int foo();");
+ md.setType("String");
+ assertTransformedToString("String foo();", md);
+ }
+
+ // Modifiers
+
+ @Test
+ public void addingModifiers() {
+ AnnotationMemberDeclaration md = consider("int foo();");
+ md.setModifiers(EnumSet.of(Modifier.PUBLIC));
+ assertTransformedToString("public int foo();", md);
+ }
+
+ @Test
+ public void removingModifiers() {
+ AnnotationMemberDeclaration md = consider("public int foo();");
+ md.setModifiers(EnumSet.noneOf(Modifier.class));
+ assertTransformedToString("int foo();", md);
+ }
+
+ @Test
+ public void replacingModifiers() {
+ AnnotationMemberDeclaration md = consider("public int foo();");
+ md.setModifiers(EnumSet.of(Modifier.PROTECTED));
+ assertTransformedToString("protected int foo();", md);
+ }
+
+ // Default value
+
+ @Test
+ public void addingDefaultValue() {
+ AnnotationMemberDeclaration md = consider("int foo();");
+ md.setDefaultValue(new IntegerLiteralExpr("10"));
+ assertTransformedToString("int foo() default 10;", md);
+ }
+
+ @Test
+ public void removingDefaultValue() {
+ AnnotationMemberDeclaration md = consider("int foo() default 10;");
+ assertEquals(true, md.getDefaultValue().get().remove());
+ assertTransformedToString("int foo();", md);
+ }
+
+ @Test
+ public void replacingDefaultValue() {
+ AnnotationMemberDeclaration md = consider("int foo() default 10;");
+ md.setDefaultValue(new IntegerLiteralExpr("11"));
+ assertTransformedToString("int foo() default 11;", md);
+ }
+
+ // Annotations
+
+ @Test
+ public void addingAnnotation() {
+ AnnotationMemberDeclaration it = consider("int foo();");
+ it.addAnnotation("myAnno");
+ assertTransformedToString("@myAnno()" + EOL + "int foo();", it);
+ }
+
+ @Test
+ public void addingTwoAnnotations() {
+ AnnotationMemberDeclaration it = consider("int foo();");
+ it.addAnnotation("myAnno");
+ it.addAnnotation("myAnno2");
+ assertTransformedToString("@myAnno()" + EOL + "@myAnno2()" + EOL + "int foo();", it);
+ }
+
+ @Test
+ public void removingAnnotationOnSomeLine() {
+ AnnotationMemberDeclaration it = consider("@myAnno int foo();");
+ it.getAnnotations().remove(0);
+ assertTransformedToString("int foo();", it);
+ }
+
+ @Test
+ public void removingAnnotationOnPrevLine() {
+ AnnotationMemberDeclaration it = consider("@myAnno" + EOL + "int foo();");
+ it.getAnnotations().remove(0);
+ assertTransformedToString("int foo();", it);
+ }
+
+ @Test
+ public 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
+ public void addingJavadoc() {
+ AnnotationMemberDeclaration it = consider("int foo();");
+ it.setJavadocComment("Cool this annotation!");
+ assertTransformedToString("@interface AD { /** Cool this annotation!*/" + EOL +
+ "int foo(); }", it.getParentNode().get());
+ }
+
+ @Test
+ public void removingJavadoc() {
+ AnnotationMemberDeclaration it = consider("/** Cool this annotation!*/ int foo();");
+ assertTrue(it.getJavadocComment().get().remove());
+ assertTransformedToString("@interface AD { int foo(); }", it.getParentNode().get());
+ }
+
+ @Test
+ public 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-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/ClassOrInterfaceDeclarationTransformationsTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/ClassOrInterfaceDeclarationTransformationsTest.java
new file mode 100644
index 000000000..1be80378d
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/ClassOrInterfaceDeclarationTransformationsTest.java
@@ -0,0 +1,194 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package 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.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.Test;
+
+import java.io.IOException;
+import java.util.EnumSet;
+
+import static com.github.javaparser.JavaParser.parseClassOrInterfaceType;
+import static com.github.javaparser.utils.Utils.EOL;
+
+/**
+ * Transforming ClassOrInterfaceDeclaration and verifying the LexicalPreservation works as expected.
+ */
+public class ClassOrInterfaceDeclarationTransformationsTest extends AbstractLexicalPreservingTest {
+
+ protected ClassOrInterfaceDeclaration consider(String code) {
+ considerCode(code);
+ return cu.getType(0).asClassOrInterfaceDeclaration();
+ }
+
+ // Name
+
+ @Test
+ public void settingName() throws IOException {
+ ClassOrInterfaceDeclaration cid = consider("class A {}");
+ cid.setName("B");
+ assertTransformedToString("class B {}", cid);
+ }
+
+ // isInterface
+
+ @Test
+ public void classToInterface() throws IOException {
+ ClassOrInterfaceDeclaration cid = consider("class A {}");
+ cid.setInterface(true);
+ assertTransformedToString("interface A {}", cid);
+ }
+
+ @Test
+ public void interfaceToClass() throws IOException {
+ ClassOrInterfaceDeclaration cid = consider("interface A {}");
+ cid.setInterface(false);
+ assertTransformedToString("class A {}", cid);
+ }
+
+ // typeParameters
+
+ @Test
+ public void addingTypeParameterWhenThereAreNone() throws IOException {
+ ClassOrInterfaceDeclaration cid = consider("class A {}");
+ cid.addTypeParameter(new TypeParameter("T", new NodeList<>()));
+ assertTransformedToString("class A<T> {}", cid);
+ }
+
+ @Test
+ public void addingTypeParameterAsFirstWhenThereAreSome() throws IOException {
+ ClassOrInterfaceDeclaration cid = consider("class A<U> {}");
+ cid.getTypeParameters().addFirst(new TypeParameter("T", new NodeList<>()));
+ assertTransformedToString("class A<T, U> {}", cid);
+ }
+
+ @Test
+ public void addingTypeParameterAsLastWhenThereAreSome() throws IOException {
+ ClassOrInterfaceDeclaration cid = consider("class A<U> {}");
+ cid.addTypeParameter(new TypeParameter("T", new NodeList<>()));
+ assertTransformedToString("class A<U, T> {}", cid);
+ }
+
+ // extendedTypes
+
+ @Test
+ public void addingExtendedTypes() throws IOException {
+ ClassOrInterfaceDeclaration cid = consider("class A {}");
+ cid.addExtendedType("Foo");
+ assertTransformedToString("class A extends Foo {}", cid);
+ }
+
+ @Test
+ public void removingExtendedTypes() throws IOException {
+ ClassOrInterfaceDeclaration cid = consider("public class A extends Foo {}");
+ cid.getExtendedTypes().remove(0);
+ assertTransformedToString("public class A {}", cid);
+ }
+
+ @Test
+ public void replacingExtendedTypes() throws IOException {
+ ClassOrInterfaceDeclaration cid = consider("public class A extends Foo {}");
+ cid.getExtendedTypes().set(0, parseClassOrInterfaceType("Bar"));
+ assertTransformedToString("public class A extends Bar {}", cid);
+ }
+
+ // implementedTypes
+
+ @Test
+ public void addingImplementedTypes() throws IOException {
+ ClassOrInterfaceDeclaration cid = consider("class A {}");
+ cid.addImplementedType("Foo");
+ assertTransformedToString("class A implements Foo {}", cid);
+ }
+
+ @Test
+ public void removingImplementedTypes() throws IOException {
+ ClassOrInterfaceDeclaration cid = consider("public class A implements Foo {}");
+ cid.getImplementedTypes().remove(0);
+ assertTransformedToString("public class A {}", cid);
+ }
+
+ @Test
+ public void replacingImplementedTypes() throws IOException {
+ ClassOrInterfaceDeclaration cid = consider("public class A implements Foo {}");
+ cid.getImplementedTypes().set(0, parseClassOrInterfaceType("Bar"));
+ assertTransformedToString("public class A implements Bar {}", cid);
+ }
+
+ // Modifiers
+
+ @Test
+ public void addingModifiers() throws IOException {
+ ClassOrInterfaceDeclaration cid = consider("class A {}");
+ cid.setModifiers(EnumSet.of(Modifier.PUBLIC));
+ assertTransformedToString("public class A {}", cid);
+ }
+
+ @Test
+ public void removingModifiers() throws IOException {
+ ClassOrInterfaceDeclaration cid = consider("public class A {}");
+ cid.setModifiers(EnumSet.noneOf(Modifier.class));
+ assertTransformedToString("class A {}", cid);
+ }
+
+ @Test
+ public void replacingModifiers() throws IOException {
+ ClassOrInterfaceDeclaration cid = consider("public class A {}");
+ cid.setModifiers(EnumSet.of(Modifier.PROTECTED));
+ assertTransformedToString("protected class A {}", cid);
+ }
+
+ // members
+
+ @Test
+ public void addingField() throws IOException {
+ ClassOrInterfaceDeclaration cid = consider("class A {}");
+ cid.addField("int", "foo");
+ assertTransformedToString("class A {" + EOL + " int foo;" + EOL + "}", cid);
+ }
+
+ @Test
+ public void removingField() throws IOException {
+ ClassOrInterfaceDeclaration cid = consider("public class A { int foo; }");
+ cid.getMembers().remove(0);
+ assertTransformedToString("public class A {}", cid);
+ }
+
+ @Test
+ public void replacingFieldWithAnotherField() throws IOException {
+ ClassOrInterfaceDeclaration cid = consider("public class A {float f;}");
+ cid.getMembers().set(0, new FieldDeclaration(EnumSet.noneOf(Modifier.class), new VariableDeclarator(PrimitiveType.intType(), "bar")));
+ assertTransformedToString("public class A {int bar;}", cid);
+ }
+
+ // Annotations
+
+ // Javadoc
+
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/ConstructorDeclarationTransformationsTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/ConstructorDeclarationTransformationsTest.java
new file mode 100644
index 000000000..6889a70ef
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/ConstructorDeclarationTransformationsTest.java
@@ -0,0 +1,122 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.printer.lexicalpreservation.transformations.ast.body;
+
+import com.github.javaparser.ast.Modifier;
+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.Test;
+
+import java.io.IOException;
+import java.util.EnumSet;
+
+/**
+ * Transforming ConstructorDeclaration and verifying the LexicalPreservation works as expected.
+ */
+public class ConstructorDeclarationTransformationsTest extends AbstractLexicalPreservingTest {
+
+ protected ConstructorDeclaration consider(String code) {
+ considerCode("class A { " + code + " }");
+ return cu.getType(0).getMembers().get(0).asConstructorDeclaration();
+ }
+
+ // Name
+
+ @Test
+ public void settingName() throws IOException {
+ ConstructorDeclaration cd = consider("A(){}");
+ cd.setName("B");
+ assertTransformedToString("B(){}", cd);
+ }
+
+ // JavaDoc
+
+ // Modifiers
+
+ @Test
+ public void addingModifiers() throws IOException {
+ ConstructorDeclaration cd = consider("A(){}");
+ cd.setModifiers(EnumSet.of(Modifier.PUBLIC));
+ assertTransformedToString("public A(){}", cd);
+ }
+
+ @Test
+ public void removingModifiers() throws IOException {
+ ConstructorDeclaration cd = consider("public A(){}");
+ cd.setModifiers(EnumSet.noneOf(Modifier.class));
+ assertTransformedToString("A(){}", cd);
+ }
+
+ @Test
+ public void replacingModifiers() throws IOException {
+ ConstructorDeclaration cd = consider("public A(){}");
+ cd.setModifiers(EnumSet.of(Modifier.PROTECTED));
+ assertTransformedToString("protected A(){}", cd);
+ }
+
+ // Parameters
+
+ @Test
+ public void addingParameters() throws IOException {
+ ConstructorDeclaration cd = consider("A(){}");
+ cd.addParameter(PrimitiveType.doubleType(), "d");
+ assertTransformedToString("A(double d){}", cd);
+ }
+
+ @Test
+ public void removingOnlyParameter() throws IOException {
+ ConstructorDeclaration cd = consider("public A(double d){}");
+ cd.getParameters().remove(0);
+ assertTransformedToString("public A(){}", cd);
+ }
+
+ @Test
+ public void removingFirstParameterOfMany() throws IOException {
+ ConstructorDeclaration cd = consider("public A(double d, float f){}");
+ cd.getParameters().remove(0);
+ assertTransformedToString("public A(float f){}", cd);
+ }
+
+ @Test
+ public void removingLastParameterOfMany() throws IOException {
+ ConstructorDeclaration cd = consider("public A(double d, float f){}");
+ cd.getParameters().remove(1);
+ assertTransformedToString("public A(double d){}", cd);
+ }
+
+ @Test
+ public void replacingOnlyParameter() throws IOException {
+ 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-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/EnumConstantDeclarationTransformationsTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/EnumConstantDeclarationTransformationsTest.java
new file mode 100644
index 000000000..dff71cc3c
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/EnumConstantDeclarationTransformationsTest.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.printer.lexicalpreservation.transformations.ast.body;
+
+import com.github.javaparser.ast.body.EnumConstantDeclaration;
+import com.github.javaparser.ast.body.EnumDeclaration;
+import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest;
+import org.junit.Test;
+
+import java.io.IOException;
+
+/**
+ * Transforming EnumConstantDeclaration and verifying the LexicalPreservation works as expected.
+ */
+public class EnumConstantDeclarationTransformationsTest extends AbstractLexicalPreservingTest {
+
+ protected EnumConstantDeclaration consider(String code) {
+ considerCode("enum A { " + code + " }");
+ return cu.getType(0).asEnumDeclaration().getEntries().get(0);
+ }
+
+ // Name
+
+ @Test
+ public void settingName() throws IOException {
+ EnumConstantDeclaration ecd = consider("A");
+ ecd.setName("B");
+ assertTransformedToString("B", ecd);
+ }
+
+ // Annotations
+
+ // Javadoc
+
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/EnumDeclarationTransformationsTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/EnumDeclarationTransformationsTest.java
new file mode 100644
index 000000000..e2a8fa3df
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/EnumDeclarationTransformationsTest.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.printer.lexicalpreservation.transformations.ast.body;
+
+import com.github.javaparser.ast.Modifier;
+import com.github.javaparser.ast.body.EnumDeclaration;
+import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.util.EnumSet;
+
+/**
+ * Transforming EnumDeclaration and verifying the LexicalPreservation works as expected.
+ */
+public class EnumDeclarationTransformationsTest extends AbstractLexicalPreservingTest {
+
+ protected EnumDeclaration consider(String code) {
+ considerCode(code);
+ return cu.getType(0).asEnumDeclaration();
+ }
+
+ // Name
+
+ @Test
+ public void settingName() throws IOException {
+ EnumDeclaration cid = consider("enum A { E1, E2 }");
+ cid.setName("B");
+ assertTransformedToString("enum B { E1, E2 }", cid);
+ }
+
+ // implementedTypes
+
+ // Modifiers
+
+ @Test
+ public void addingModifiers() throws IOException {
+ EnumDeclaration ed = consider("enum A { E1, E2 }");
+ ed.setModifiers(EnumSet.of(Modifier.PUBLIC));
+ assertTransformedToString("public enum A { E1, E2 }", ed);
+ }
+
+ @Test
+ public void removingModifiers() throws IOException {
+ EnumDeclaration ed = consider("public enum A { E1, E2 }");
+ ed.setModifiers(EnumSet.noneOf(Modifier.class));
+ assertTransformedToString("enum A { E1, E2 }", ed);
+ }
+
+ @Test
+ public void replacingModifiers() throws IOException {
+ EnumDeclaration ed = consider("public enum A { E1, E2 }");
+ ed.setModifiers(EnumSet.of(Modifier.PROTECTED));
+ assertTransformedToString("protected enum A { E1, E2 }", ed);
+ }
+
+ // members
+
+ // Annotations
+
+ // Javadoc
+
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/FieldDeclarationTransformationsTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/FieldDeclarationTransformationsTest.java
new file mode 100644
index 000000000..994f5d8b6
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/FieldDeclarationTransformationsTest.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.printer.lexicalpreservation.transformations.ast.body;
+
+import com.github.javaparser.ast.Modifier;
+import com.github.javaparser.ast.body.FieldDeclaration;
+import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.util.EnumSet;
+
+/**
+ * Transforming FieldDeclaration and verifying the LexicalPreservation works as expected.
+ */
+public class FieldDeclarationTransformationsTest extends AbstractLexicalPreservingTest {
+
+ protected FieldDeclaration consider(String code) {
+ considerCode("class A { " + code + " }");
+ return cu.getType(0).getMembers().get(0).asFieldDeclaration();
+ }
+
+ // JavaDoc
+
+ // Modifiers
+
+ @Test
+ public void addingModifiers() {
+ FieldDeclaration it = consider("int A;");
+ it.setModifiers(EnumSet.of(Modifier.PUBLIC));
+ assertTransformedToString("public int A;", it);
+ }
+
+ @Test
+ public void removingModifiers() {
+ FieldDeclaration it = consider("public int A;");
+ it.setModifiers(EnumSet.noneOf(Modifier.class));
+ assertTransformedToString("int A;", it);
+ }
+
+ @Test
+ public void replacingModifiers() {
+ FieldDeclaration it = consider("int A;");
+ it.setModifiers(EnumSet.of(Modifier.PROTECTED));
+ assertTransformedToString("protected int A;", it);
+ }
+
+ @Test
+ public 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);
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/InitializerDeclarationTransformationsTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/InitializerDeclarationTransformationsTest.java
new file mode 100644
index 000000000..738acb36d
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/InitializerDeclarationTransformationsTest.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package 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.Test;
+
+import java.io.IOException;
+
+/**
+ * Transforming InitializerDeclaration and verifying the LexicalPreservation works as expected.
+ */
+public 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
+ public void instanceToStatic() throws IOException {
+ InitializerDeclaration it = consider("{ /*some comment*/ }");
+ it.setStatic(true);
+ assertTransformedToString("static { /*some comment*/ }", it);
+ }
+
+ @Test
+ public void staticToInstance() throws IOException {
+ InitializerDeclaration it = consider("static { /*some comment*/ }");
+ it.setStatic(false);
+ assertTransformedToString("{ /*some comment*/ }", it);
+ }
+
+ // Annotations
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/MethodDeclarationTransformationsTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/MethodDeclarationTransformationsTest.java
new file mode 100644
index 000000000..1f94f3868
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/MethodDeclarationTransformationsTest.java
@@ -0,0 +1,122 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.printer.lexicalpreservation.transformations.ast.body;
+
+import com.github.javaparser.ast.Modifier;
+import com.github.javaparser.ast.body.MethodDeclaration;
+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.Test;
+
+import java.io.IOException;
+import java.util.EnumSet;
+
+/**
+ * Transforming MethodDeclaration and verifying the LexicalPreservation works as expected.
+ */
+public class MethodDeclarationTransformationsTest extends AbstractLexicalPreservingTest {
+
+ protected MethodDeclaration consider(String code) {
+ considerCode("class A { " + code + " }");
+ return cu.getType(0).getMembers().get(0).asMethodDeclaration();
+ }
+
+ // Name
+
+ @Test
+ public void settingName() throws IOException {
+ MethodDeclaration it = consider("void A(){}");
+ it.setName("B");
+ assertTransformedToString("void B(){}", it);
+ }
+
+ // JavaDoc
+
+ // Modifiers
+
+ @Test
+ public void addingModifiers() throws IOException {
+ MethodDeclaration it = consider("void A(){}");
+ it.setModifiers(EnumSet.of(Modifier.PUBLIC));
+ assertTransformedToString("public void A(){}", it);
+ }
+
+ @Test
+ public void removingModifiers() throws IOException {
+ MethodDeclaration it = consider("public void A(){}");
+ it.setModifiers(EnumSet.noneOf(Modifier.class));
+ assertTransformedToString("void A(){}", it);
+ }
+
+ @Test
+ public void replacingModifiers() throws IOException {
+ MethodDeclaration it = consider("public void A(){}");
+ it.setModifiers(EnumSet.of(Modifier.PROTECTED));
+ assertTransformedToString("protected void A(){}", it);
+ }
+
+ // Parameters
+
+ @Test
+ public void addingParameters() throws IOException {
+ MethodDeclaration it = consider("void foo(){}");
+ it.addParameter(PrimitiveType.doubleType(), "d");
+ assertTransformedToString("void foo(double d){}", it);
+ }
+
+ @Test
+ public void removingOnlyParameter() throws IOException {
+ MethodDeclaration it = consider("public void foo(double d){}");
+ it.getParameters().remove(0);
+ assertTransformedToString("public void foo(){}", it);
+ }
+
+ @Test
+ public void removingFirstParameterOfMany() throws IOException {
+ MethodDeclaration it = consider("public void foo(double d, float f){}");
+ it.getParameters().remove(0);
+ assertTransformedToString("public void foo(float f){}", it);
+ }
+
+ @Test
+ public void removingLastParameterOfMany() throws IOException {
+ MethodDeclaration it = consider("public void foo(double d, float f){}");
+ it.getParameters().remove(1);
+ assertTransformedToString("public void foo(double d){}", it);
+ }
+
+ @Test
+ public void replacingOnlyParameter() throws IOException {
+ 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
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/remove/NodeRemovalTest.java b/javaparser-testing/src/test/java/com/github/javaparser/remove/NodeRemovalTest.java
new file mode 100644
index 000000000..6620bb1c8
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/remove/NodeRemovalTest.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.remove;
+
+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.stmt.BlockStmt;
+import com.github.javaparser.ast.stmt.Statement;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+public class NodeRemovalTest {
+ private final CompilationUnit cu = new CompilationUnit();
+
+ @Test
+ public void testRemoveClassFromCompilationUnit() {
+ ClassOrInterfaceDeclaration testClass = cu.addClass("test");
+ assertEquals(1, cu.getTypes().size());
+ boolean remove = testClass.remove();
+ assertEquals(true, remove);
+ assertEquals(0, cu.getTypes().size());
+ }
+
+ @Test
+ public void testRemoveFieldFromClass() {
+ ClassOrInterfaceDeclaration testClass = cu.addClass("test");
+
+ FieldDeclaration addField = testClass.addField(String.class, "test");
+ assertEquals(1, testClass.getMembers().size());
+ boolean remove = addField.remove();
+ assertEquals(true, remove);
+ assertEquals(0, testClass.getMembers().size());
+ }
+
+ @Test
+ public void testRemoveStatementFromMethodBody() {
+ ClassOrInterfaceDeclaration testClass = cu.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();
+ assertEquals(true, remove);
+ assertEquals(0, methodBody.getStatements().size());
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/utils/CodeGenerationUtilsTest.java b/javaparser-testing/src/test/java/com/github/javaparser/utils/CodeGenerationUtilsTest.java
new file mode 100644
index 000000000..dafe7ad0c
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/utils/CodeGenerationUtilsTest.java
@@ -0,0 +1,22 @@
+package com.github.javaparser.utils;
+
+import org.junit.Test;
+
+import static com.github.javaparser.utils.CodeGenerationUtils.*;
+import static org.junit.Assert.*;
+
+public class CodeGenerationUtilsTest {
+ @Test
+ public void setters() {
+ assertEquals("setValue", setterName("value"));
+ assertEquals("setBlue", setterName("isBlue"));
+ }
+
+ @Test
+ public void getters() {
+ assertEquals("getValue", getterName(Object.class, "value"));
+ assertEquals("isBlue", getterName(Boolean.class, "isBlue"));
+ assertEquals("isBlue", getterName(Boolean.class, "blue"));
+ }
+
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/utils/PairTest.java b/javaparser-testing/src/test/java/com/github/javaparser/utils/PairTest.java
new file mode 100644
index 000000000..2a5b84aa2
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/utils/PairTest.java
@@ -0,0 +1,21 @@
+package com.github.javaparser.utils;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+public class PairTest {
+ @Test
+ public void testToString() {
+ Pair<String, String> pair = new Pair<>("abc", "def");
+
+ assertEquals("<abc, def>", pair.toString());
+ }
+
+ @Test
+ public void testToStringNulls() {
+ Pair<String, String> pair = new Pair<>(null, null);
+
+ assertEquals("<null, null>", pair.toString());
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/utils/SourceRootTest.java b/javaparser-testing/src/test/java/com/github/javaparser/utils/SourceRootTest.java
new file mode 100644
index 000000000..a0bb50e2e
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/utils/SourceRootTest.java
@@ -0,0 +1,38 @@
+package com.github.javaparser.utils;
+
+import com.github.javaparser.ParseResult;
+import com.github.javaparser.ast.CompilationUnit;
+import org.junit.Test;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+public class SourceRootTest {
+ private final Path root = CodeGenerationUtils.classLoaderRoot(SourceRootTest.class).resolve("com/github/javaparser/utils/");
+ private final SourceRoot sourceRoot = new SourceRoot(root);
+
+ @Test
+ public void parseTestDirectory() throws IOException {
+
+ List<ParseResult<CompilationUnit>> parseResults = sourceRoot.tryToParse();
+ List<CompilationUnit> units = sourceRoot.getCompilationUnits();
+
+ assertEquals(2, units.size());
+ assertTrue(units.stream().allMatch(unit -> !unit.getTypes().isEmpty() || unit.getModule().isPresent()));
+ assertTrue(parseResults.stream().anyMatch(cu -> cu.getResult().get().getStorage().get().getPath().toString().contains("source" + File.separator + "root")));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void fileAsRootIsNotAllowed() {
+ Path path = CodeGenerationUtils.classLoaderRoot(SourceRootTest.class).resolve("/com/github/javaparser/utils/Bla.java");
+ new SourceRoot(path);
+ }
+
+
+
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/utils/SourceZipTest.java b/javaparser-testing/src/test/java/com/github/javaparser/utils/SourceZipTest.java
new file mode 100644
index 000000000..05e80aba0
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/utils/SourceZipTest.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.utils;
+
+import com.github.javaparser.ParseResult;
+import com.github.javaparser.ast.CompilationUnit;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.net.URISyntaxException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+public class SourceZipTest {
+
+ private final Path testDir = CodeGenerationUtils.mavenModuleRoot(SourceZipTest.class)
+ .resolve(Paths.get("..", "javaparser-testing", "src", "test", "resources", "com", "github", "javaparser",
+ "source_zip"))
+ .normalize();
+
+ @Test
+ public void parseTestDirectory() throws URISyntaxException, IOException {
+ SourceZip sourceZip = new SourceZip(testDir.resolve("test.zip"));
+ List<Pair<Path, ParseResult<CompilationUnit>>> results = sourceZip.parse();
+ assertEquals(3, results.size());
+ List<CompilationUnit> units = new ArrayList<>();
+ for (Pair<Path, ParseResult<CompilationUnit>> pr : results) {
+ units.add(pr.b.getResult().get());
+ }
+ assertTrue(units.stream().noneMatch(unit -> unit.getTypes().isEmpty()));
+ }
+
+ @Test
+ public void parseTestDirectoryWithCallback() throws URISyntaxException, IOException {
+ SourceZip sourceZip = new SourceZip(testDir.resolve("test.zip"));
+ List<Pair<Path, ParseResult<CompilationUnit>>> results = new ArrayList<>();
+
+ sourceZip.parse((path, result) -> results.add(new Pair<>(path, result)));
+
+ assertEquals(3, results.size());
+ List<CompilationUnit> units = new ArrayList<>();
+ for (Pair<Path, ParseResult<CompilationUnit>> pr : results) {
+ units.add(pr.b.getResult().get());
+ }
+ assertTrue(units.stream().noneMatch(unit -> unit.getTypes().isEmpty()));
+ }
+
+ @Test(expected = IOException.class)
+ public void dirAsZipIsNotAllowed() throws IOException {
+ new SourceZip(testDir.resolve("test")).parse();
+ }
+
+ @Test(expected = IOException.class)
+ public void fileAsZipIsNotAllowed() throws IOException {
+ new SourceZip(testDir.resolve("test.txt")).parse();
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/utils/TestUtils.java b/javaparser-testing/src/test/java/com/github/javaparser/utils/TestUtils.java
new file mode 100644
index 000000000..24f17670a
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/utils/TestUtils.java
@@ -0,0 +1,155 @@
+package com.github.javaparser.utils;
+
+import com.github.javaparser.*;
+import com.github.javaparser.ast.expr.Expression;
+import com.github.javaparser.ast.validator.Java9Validator;
+import okhttp3.OkHttpClient;
+import okhttp3.Request;
+import okhttp3.Response;
+
+import java.io.*;
+import java.net.URL;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.*;
+import java.util.stream.Collectors;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+import static com.github.javaparser.ParserConfiguration.LanguageLevel.*;
+import static com.github.javaparser.Providers.provider;
+import static com.github.javaparser.utils.CodeGenerationUtils.f;
+import static com.github.javaparser.utils.Utils.EOL;
+import static com.github.javaparser.utils.Utils.normalizeEolInTextBlock;
+import static java.util.Arrays.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
+
+public class TestUtils {
+ /**
+ * Takes care of setting all the end of line character to platform specific ones.
+ */
+ public static String readResource(String resourceName) throws IOException {
+ 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)) {
+ final StringBuilder builder = new StringBuilder();
+ String line;
+ while ((line = br.readLine()) != null) {
+ builder.append(line).append(Utils.EOL);
+ }
+ return builder.toString();
+ }
+ }
+ }
+
+ public static void assertInstanceOf(Class<?> expectedType, Object instance) {
+ assertEquals(true, 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(EOL);
+ }
+ }
+ for (Object a : actual) {
+ out.append("Unexpected: ").append(a).append(EOL);
+ }
+
+ 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<Problem> result, String... expectedArg) {
+ Set<String> actual = result.stream().map(Problem::toString).collect(Collectors.toSet());
+ Set<String> 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<Expression> result = javaParser.parse(ParseStart.EXPRESSION, provider(expression));
+ assertEquals(true, result.isSuccessful(), result.getProblems().toString());
+ }
+
+ /**
+ * Assert that "actual" equals "expected", and that any EOL characters in "actual" are correct for the platform.
+ */
+ public static void assertEqualsNoEol(String expected, String actual) {
+ assertEquals(normalizeEolInTextBlock(expected, EOL), actual);
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/utils/UtilsTest.java b/javaparser-testing/src/test/java/com/github/javaparser/utils/UtilsTest.java
new file mode 100644
index 000000000..21ecf4cc2
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/utils/UtilsTest.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.utils;
+
+import org.junit.Test;
+
+import static com.github.javaparser.utils.Utils.*;
+import static org.junit.Assert.assertEquals;
+
+public class UtilsTest {
+
+ @Test
+ public void testScreamingToCamelCase() {
+ assertEquals("abc", screamingToCamelCase("ABC"));
+ assertEquals("abcDef", screamingToCamelCase("ABC_DEF"));
+ assertEquals("abc", screamingToCamelCase("ABC_"));
+ }
+
+ @Test
+ public void screamingEmptyString() {
+ assertEquals("", camelCaseToScreaming(""));
+ assertEquals("ABC", camelCaseToScreaming("abc"));
+ assertEquals("HELLO_HELLO", camelCaseToScreaming("HelloHello"));
+ assertEquals("APE_TAIL", camelCaseToScreaming("apeTail"));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void capitalizeOnEmptyString() {
+ capitalize("");
+ }
+
+ @Test
+ public void capitalizeOnStringOfOneCharacter() {
+ assertEquals("F", capitalize("f"));
+ }
+
+ @Test
+ public void capitalizeOnStringOfTwoCharacters() {
+ assertEquals("Fo", capitalize("fo"));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void decapitalizeOnEmptyString() {
+ decapitalize("");
+ }
+
+ @Test
+ public void decapitalizeOnStringOfOneCharacter() {
+ assertEquals("f", decapitalize("F"));
+ }
+
+ @Test
+ public void decapitalizeOnStringOfTwoCharacters() {
+ assertEquals("fo", decapitalize("Fo"));
+ }
+
+ @Test
+ public void normalizeEolInTextBlock() {
+ String result = Utils.normalizeEolInTextBlock("\r\n \r \n", "Q");
+ assertEquals("Q Q Q", result);
+ }
+
+ @Test
+ public 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-testing/src/test/java/com/github/javaparser/utils/VisitorListTest.java b/javaparser-testing/src/test/java/com/github/javaparser/utils/VisitorListTest.java
new file mode 100644
index 000000000..c0944ec07
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/utils/VisitorListTest.java
@@ -0,0 +1,187 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.utils;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+
+import org.junit.Test;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.ast.CompilationUnit;
+import com.github.javaparser.ast.visitor.ObjectIdentityEqualsVisitor;
+import com.github.javaparser.ast.visitor.ObjectIdentityHashCodeVisitor;
+
+public class VisitorListTest {
+
+ @Test
+ public void visitorAddAll() {
+ List<CompilationUnit> list = new ArrayList<>();
+ list.add(JavaParser.parse("class X{}"));
+ list.add(JavaParser.parse("class X{}"));
+ VisitorList<CompilationUnit> 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
+ public void visitorAddAllAtIndex() {
+ List<CompilationUnit> list = new ArrayList<>();
+ list.add(JavaParser.parse("class X{}"));
+ list.add(JavaParser.parse("class Y{}"));
+ VisitorList<CompilationUnit> vList = new VisitorList<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ vList.add(JavaParser.parse("class A{}"));
+ vList.add(JavaParser.parse("class B{}"));
+ vList.addAll(2, list);
+ vList.add(JavaParser.parse("class C{}"));
+ for (int i = 0; i < list.size(); i++)
+ assertEquals(list.get(i), vList.get(2 + i));
+ }
+
+ @Test
+ public void visitorListContains() {
+ CompilationUnit x1 = JavaParser.parse("class X{}");
+ VisitorList<CompilationUnit> list = new VisitorList<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ list.add(x1);
+ assertTrue(list.contains(x1));
+ }
+
+ @Test
+ public void visitorListContainsAll() {
+ List<CompilationUnit> list = new ArrayList<>();
+ list.add(JavaParser.parse("class X{}"));
+ list.add(JavaParser.parse("class X{}"));
+ VisitorList<CompilationUnit> vList = new VisitorList<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ vList.addAll(list);
+ assertTrue(vList.size() == 2 && vList.containsAll(list));
+ }
+
+ @Test
+ public void visitorListIterator() {
+ VisitorList<CompilationUnit> list = new VisitorList<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ CompilationUnit x1 = JavaParser.parse("class X{}");
+ list.add(x1);
+ CompilationUnit x2 = JavaParser.parse("class X{}");
+ list.add(x2);
+ Iterator<CompilationUnit> itr = list.iterator();
+ assertEquals(x1, itr.next());
+ itr.remove();
+ assertTrue(list.size() == 1);
+ assertEquals(x2, itr.next());
+ itr.remove();
+ assertTrue(list.size() == 0);
+ }
+
+ @Test
+ public void visitorListListIterator() {
+ VisitorList<CompilationUnit> list = new VisitorList<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ list.add(JavaParser.parse("class X{}"));
+ list.add(JavaParser.parse("class X{}"));
+ CompilationUnit x1 = JavaParser.parse("class X{}");
+ list.add(x1);
+ CompilationUnit x2 = JavaParser.parse("class X{}");
+ list.add(x2);
+ Iterator<CompilationUnit> itr = list.listIterator(2);
+ assertEquals(x1, itr.next());
+ itr.remove();
+ assertTrue(list.size() == 3);
+ assertEquals(x2, itr.next());
+ itr.remove();
+ assertTrue(list.size() == 2);
+ }
+
+ @Test
+ public void visitorListRemove() {
+ CompilationUnit x1 = JavaParser.parse("class X{}");
+ VisitorList<CompilationUnit> list = new VisitorList<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ list.add(x1);
+ assertTrue(list.remove(x1));
+ }
+
+ @Test
+ public void visitorListRemoveAll() {
+ List<CompilationUnit> list = new ArrayList<>();
+ list.add(JavaParser.parse("class X{}"));
+ list.add(JavaParser.parse("class X{}"));
+ VisitorList<CompilationUnit> vList = new VisitorList<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ vList.addAll(list);
+ vList.removeAll(list);
+ assertTrue(vList.size() == 0);
+ }
+
+ @Test
+ public void visitorListRetainAll() {
+ List<CompilationUnit> list = new ArrayList<>();
+ list.add(JavaParser.parse("class X{}"));
+ list.add(JavaParser.parse("class X{}"));
+ VisitorList<CompilationUnit> vList = new VisitorList<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ vList.addAll(list);
+ vList.add(JavaParser.parse("class X{}"));
+ vList.retainAll(list);
+ assertTrue(vList.size() == 2);
+ }
+
+ @Test
+ public void visitorListSubList() {
+ VisitorList<CompilationUnit> list = new VisitorList<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ list.add(JavaParser.parse("class X{}"));
+ list.add(JavaParser.parse("class X{}"));
+ list.add(JavaParser.parse("class X{}"));
+ list.add(JavaParser.parse("class X{}"));
+ assertTrue(list.size() == 4);
+ List<CompilationUnit> subLst = list.subList(1, 3);
+ assertTrue(subLst.size() == 2);
+ subLst.add(JavaParser.parse("class X{}"));
+ assertTrue(subLst.size() == 3);
+ assertTrue(list.size() == 5);
+
+ }
+
+ @Test
+ public void visitorListToArray() {
+ List<CompilationUnit> list = new ArrayList<>();
+ list.add(JavaParser.parse("class X{}"));
+ list.add(JavaParser.parse("class X{}"));
+ List<CompilationUnit> 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-testing/src/test/java/com/github/javaparser/utils/VisitorMapTest.java b/javaparser-testing/src/test/java/com/github/javaparser/utils/VisitorMapTest.java
new file mode 100644
index 000000000..03d4b7b65
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/utils/VisitorMapTest.java
@@ -0,0 +1,80 @@
+package com.github.javaparser.utils;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.ast.CompilationUnit;
+import com.github.javaparser.ast.visitor.ObjectIdentityEqualsVisitor;
+import com.github.javaparser.ast.visitor.ObjectIdentityHashCodeVisitor;
+import org.junit.Test;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+public class VisitorMapTest {
+ @Test
+ public void normalEqualsDoesDeepCompare() {
+ CompilationUnit x1 = JavaParser.parse("class X{}");
+ CompilationUnit x2 = JavaParser.parse("class X{}");
+
+ Map<CompilationUnit, Integer> map = new HashMap<>();
+ map.put(x1, 1);
+ map.put(x2, 2);
+ assertEquals(1, map.size());
+ }
+
+ @Test
+ public void objectIdentityEqualsDoesShallowCompare() {
+ CompilationUnit x1 = JavaParser.parse("class X{}");
+ CompilationUnit x2 = JavaParser.parse("class X{}");
+
+ Map<CompilationUnit, Integer> map = new VisitorMap<>(new ObjectIdentityHashCodeVisitor(), new ObjectIdentityEqualsVisitor());
+ map.put(x1, 1);
+ map.put(x2, 2);
+ assertEquals(2, map.size());
+ }
+
+ @Test
+ public void visitorMapGet(){
+ CompilationUnit x1 = JavaParser.parse("class X{}");
+
+ Map<CompilationUnit, Integer> map = new VisitorMap<>(new ObjectIdentityHashCodeVisitor(), new ObjectIdentityEqualsVisitor());
+ map.put(x1, 1);
+ assertEquals(1, (int)map.get(x1));
+ }
+
+ @Test
+ public void visitorMapContainsKey(){
+ CompilationUnit x1 = JavaParser.parse("class X{}");
+
+ Map<CompilationUnit, Integer> map = new VisitorMap<>(new ObjectIdentityHashCodeVisitor(), new ObjectIdentityEqualsVisitor());
+ map.put(x1, 1);
+ assertTrue(map.containsKey(x1));
+ }
+
+ @Test
+ public void visitorMapPutAll(){
+ CompilationUnit x1 = JavaParser.parse("class X{}");
+ CompilationUnit x2 = JavaParser.parse("class Y{}");
+ Map<CompilationUnit, Integer> map = new HashMap<>();
+ map.put(x1, 1);
+ map.put(x2, 2);
+ Map<CompilationUnit, Integer> visitorMap = new VisitorMap<>(new ObjectIdentityHashCodeVisitor(), new ObjectIdentityEqualsVisitor());
+ visitorMap.putAll(map);
+ assertEquals(2, visitorMap.size());
+ }
+
+ @Test
+ public void remove(){
+ CompilationUnit x1 = JavaParser.parse("class X{}");
+ VisitorMap<CompilationUnit, Integer> 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-testing/src/test/java/com/github/javaparser/utils/VisitorSetTest.java b/javaparser-testing/src/test/java/com/github/javaparser/utils/VisitorSetTest.java
new file mode 100644
index 000000000..1d7730b97
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/utils/VisitorSetTest.java
@@ -0,0 +1,141 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.utils;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+
+import org.junit.Test;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.ast.CompilationUnit;
+import com.github.javaparser.ast.visitor.ObjectIdentityEqualsVisitor;
+import com.github.javaparser.ast.visitor.ObjectIdentityHashCodeVisitor;
+
+public class VisitorSetTest {
+
+ @Test
+ public void normalEqualsDoesDeepCompare() {
+ Set<CompilationUnit> set = new HashSet<>();
+ set.add(JavaParser.parse("class X{}"));
+ set.add(JavaParser.parse("class X{}"));
+ assertEquals(1, set.size());
+ }
+
+ @Test
+ public void objectIdentityEqualsDoesShallowCompare() {
+ Set<CompilationUnit> set = new VisitorSet<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ set.add(JavaParser.parse("class X{}"));
+ set.add(JavaParser.parse("class X{}"));
+ assertEquals(2, set.size());
+ }
+
+ @Test
+ public void visitorSetContains() {
+ CompilationUnit x1 = JavaParser.parse("class X{}");
+ Set<CompilationUnit> set = new VisitorSet<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ set.add(x1);
+ assertTrue(set.contains(x1));
+ }
+
+ @Test
+ public void visitorSetContainsAll() {
+ List<CompilationUnit> list = new ArrayList<>();
+ list.add(JavaParser.parse("class X{}"));
+ list.add(JavaParser.parse("class X{}"));
+ Set<CompilationUnit> set = new VisitorSet<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ set.addAll(list);
+ assertTrue(set.size() == 2 && set.containsAll(list));
+ }
+
+ @Test
+ public void visitorSetIterator() {
+ Set<CompilationUnit> set = new VisitorSet<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ CompilationUnit x1 = JavaParser.parse("class X{}");
+ set.add(x1);
+ CompilationUnit x2 = JavaParser.parse("class X{}");
+ set.add(x2);
+ Iterator<CompilationUnit> itr = set.iterator();
+ assertEquals(x1, itr.next());
+ itr.remove();
+ assertTrue(set.size() == 1);
+ assertEquals(x2, itr.next());
+ itr.remove();
+ assertTrue(set.size() == 0);
+ }
+
+ @Test
+ public void visitorSetRemove() {
+ CompilationUnit x1 = JavaParser.parse("class X{}");
+ Set<CompilationUnit> set = new VisitorSet<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ set.add(x1);
+ assertTrue(set.remove(x1));
+ }
+
+ @Test
+ public void visitorSetRemoveAll() {
+ List<CompilationUnit> list = new ArrayList<>();
+ list.add(JavaParser.parse("class X{}"));
+ list.add(JavaParser.parse("class X{}"));
+ Set<CompilationUnit> set = new VisitorSet<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ set.addAll(list);
+ set.removeAll(list);
+ assertTrue(set.size() == 0);
+ }
+
+ @Test
+ public void visitorSetRetainAll() {
+ List<CompilationUnit> list = new ArrayList<>();
+ list.add(JavaParser.parse("class X{}"));
+ list.add(JavaParser.parse("class X{}"));
+ Set<CompilationUnit> set = new VisitorSet<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ set.addAll(list);
+ set.add(JavaParser.parse("class X{}"));
+ set.retainAll(list);
+ assertTrue(set.size() == 2);
+ }
+
+ @Test
+ public void visitorSetToArray() {
+ List<CompilationUnit> list = new ArrayList<>();
+ list.add(JavaParser.parse("class X{}"));
+ list.add(JavaParser.parse("class X{}"));
+ Set<CompilationUnit> 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-testing/src/test/java/com/github/javaparser/version/Java10PostProcessorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/version/Java10PostProcessorTest.java
new file mode 100644
index 000000000..4f9af2748
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/version/Java10PostProcessorTest.java
@@ -0,0 +1,28 @@
+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.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;
+
+public class Java10PostProcessorTest {
+ public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_10));
+
+ @Test
+ public void varIsAType() {
+ ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("var x=\"\";"));
+
+ List<VarType> allVarTypes = result.getResult().get().findAll(VarType.class);
+
+ assertEquals(1, allVarTypes.size());
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/ChangingMethodsFromAClassWithAVisitorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/ChangingMethodsFromAClassWithAVisitorTest.java
new file mode 100644
index 000000000..677cfcc51
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/ChangingMethodsFromAClassWithAVisitorTest.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.wiki_samples;
+
+import org.junit.Test;
+
+public class ChangingMethodsFromAClassWithAVisitorTest {
+ @Test
+ public void printingTheCompilationUnitToSystemOutput() throws Exception {
+ try (TestFileToken f = new TestFileToken("test.java")) {
+ MethodChanger_1.main(new String[]{});
+ }
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/ChangingMethodsFromAClassWithoutAVisitorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/ChangingMethodsFromAClassWithoutAVisitorTest.java
new file mode 100644
index 000000000..9301ff58b
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/ChangingMethodsFromAClassWithoutAVisitorTest.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.wiki_samples;
+
+import org.junit.Test;
+
+public class ChangingMethodsFromAClassWithoutAVisitorTest {
+ @Test
+ public void printingTheCompilationUnitToSystemOutput() throws Exception {
+ try (TestFileToken f = new TestFileToken("test.java")) {
+ MethodChanger_2.main(new String[]{});
+ }
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/ClassCreator.java b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/ClassCreator.java
new file mode 100644
index 000000000..1e1d91b59
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/ClassCreator.java
@@ -0,0 +1,95 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.wiki_samples;
+
+import com.github.javaparser.ast.CompilationUnit;
+import com.github.javaparser.ast.Modifier;
+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.expr.*;
+import com.github.javaparser.ast.stmt.BlockStmt;
+import com.github.javaparser.ast.type.ClassOrInterfaceType;
+import com.github.javaparser.ast.type.VoidType;
+
+import java.util.EnumSet;
+
+import static com.github.javaparser.JavaParser.parseClassOrInterfaceType;
+import static com.github.javaparser.JavaParser.parseName;
+
+public class ClassCreator {
+
+ public static void main(String[] args) throws Exception {
+ // creates the compilation unit
+ CompilationUnit cu = createCU();
+
+ // prints the created compilation unit
+ System.out.println(cu.toString());
+ }
+
+ /**
+ * creates the compilation unit
+ */
+ private static CompilationUnit createCU() {
+ CompilationUnit cu = new CompilationUnit();
+ // set the package
+ cu.setPackageDeclaration(new PackageDeclaration(parseName("java.parser.test")));
+
+ // or a shortcut
+ cu.setPackageDeclaration("java.parser.test");
+
+ // create the type declaration
+ ClassOrInterfaceDeclaration type = cu.addClass("GeneratedClass");
+
+ // create a method
+ EnumSet<Modifier> modifiers = EnumSet.of(Modifier.PUBLIC);
+ MethodDeclaration method = new MethodDeclaration(modifiers, new VoidType(), "main");
+ modifiers.add(Modifier.STATIC);
+ method.setModifiers(modifiers);
+ type.addMember(method);
+
+ // or a shortcut
+ MethodDeclaration main2 = type.addMethod("main2", Modifier.PUBLIC, Modifier.STATIC);
+
+ // add a parameter to the method
+ Parameter param = new Parameter(parseClassOrInterfaceType("String"), "args");
+ param.setVarArgs(true);
+ method.addParameter(param);
+
+ // or a shortcut
+ main2.addAndGetParameter(String.class, "args").setVarArgs(true);
+
+ // add a body to the method
+ BlockStmt block = new BlockStmt();
+ method.setBody(block);
+
+ // add a statement to the method body
+ NameExpr clazz = new NameExpr("System");
+ FieldAccessExpr field = new FieldAccessExpr(clazz, "out");
+ MethodCallExpr call = new MethodCallExpr(field, "println");
+ call.addArgument(new StringLiteralExpr("Hello World!"));
+ block.addStatement(call);
+
+ return cu;
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/CreatingACompilationUnitFromScratch.java b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/CreatingACompilationUnitFromScratch.java
new file mode 100644
index 000000000..fa256d2ff
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/CreatingACompilationUnitFromScratch.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.wiki_samples;
+
+import org.junit.Test;
+
+public class CreatingACompilationUnitFromScratch {
+ @Test
+ public void printingTheCompilationUnitToSystemOutput() throws Exception {
+ ClassCreator.main(new String[]{});
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/CuPrinter.java b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/CuPrinter.java
new file mode 100644
index 000000000..89653f4f6
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/CuPrinter.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.wiki_samples;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.ast.CompilationUnit;
+
+import java.io.FileInputStream;
+
+public class CuPrinter {
+
+ public static void main(String[] args) throws Exception {
+ // creates an input stream for the file to be parsed
+ FileInputStream in = new FileInputStream("test.java");
+
+ // parse the file
+ CompilationUnit cu = JavaParser.parse(in);
+
+ // prints the resulting compilation unit to default system output
+ System.out.println(cu.toString());
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/MethodChanger_1.java b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/MethodChanger_1.java
new file mode 100644
index 000000000..1d64866e1
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/MethodChanger_1.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.wiki_samples;
+
+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;
+
+public class MethodChanger_1 {
+
+ public static void main(String[] args) throws Exception {
+ // parse a file
+ CompilationUnit cu = JavaParser.parse(new File("test.java"));
+
+ // visit and change the methods names and parameters
+ cu.accept(new MethodChangerVisitor(), null);
+
+ // prints the changed compilation unit
+ System.out.println(cu);
+ }
+
+ /**
+ * Simple visitor implementation for visiting MethodDeclaration nodes.
+ */
+ private static class MethodChangerVisitor extends VoidVisitorAdapter<Void> {
+ @Override
+ public void visit(MethodDeclaration n, Void arg) {
+ // change the name of the method to upper case
+ n.setName(n.getNameAsString().toUpperCase());
+
+ // add a new parameter to the method
+ n.addParameter("int", "value");
+ }
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/MethodChanger_2.java b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/MethodChanger_2.java
new file mode 100644
index 000000000..bf0c72d7a
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/MethodChanger_2.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.wiki_samples;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.ast.CompilationUnit;
+import com.github.javaparser.ast.NodeList;
+import com.github.javaparser.ast.body.BodyDeclaration;
+import com.github.javaparser.ast.body.MethodDeclaration;
+import com.github.javaparser.ast.body.TypeDeclaration;
+
+import java.io.FileInputStream;
+
+import static com.github.javaparser.ast.type.PrimitiveType.intType;
+
+public class MethodChanger_2 {
+
+ public static void main(String[] args) throws Exception {
+ // creates an input stream for the file to be parsed
+ FileInputStream in = new FileInputStream("test.java");
+
+ // parse the file
+ CompilationUnit cu = JavaParser.parse(in);
+
+ // change the methods names and parameters
+ changeMethods(cu);
+
+ // prints the changed compilation unit
+ System.out.println(cu.toString());
+ }
+
+ private static void changeMethods(CompilationUnit cu) {
+ // Go through all the types in the file
+ NodeList<TypeDeclaration<?>> types = cu.getTypes();
+ for (TypeDeclaration<?> type : types) {
+ // Go through all fields, methods, etc. in this type
+ NodeList<BodyDeclaration<?>> members = type.getMembers();
+ for (BodyDeclaration<?> member : members) {
+ if (member instanceof MethodDeclaration) {
+ MethodDeclaration method = (MethodDeclaration) member;
+ changeMethod(method);
+ }
+ }
+ }
+ }
+
+ private static void changeMethod(MethodDeclaration n) {
+ // change the name of the method to upper case
+ n.setName(n.getNameAsString().toUpperCase());
+
+ // create the new parameter
+ n.addParameter(intType(), "value");
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/MethodPrinter.java b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/MethodPrinter.java
new file mode 100644
index 000000000..8e1e5bf98
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/MethodPrinter.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.wiki_samples;
+
+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.FileInputStream;
+
+public class MethodPrinter {
+
+ public static void main(String[] args) throws Exception {
+ // creates an input stream for the file to be parsed
+ FileInputStream in = new FileInputStream("test.java");
+
+ // parse it
+ CompilationUnit cu = JavaParser.parse(in);
+
+ // visit and print the methods names
+ cu.accept(new MethodVisitor(), null);
+ }
+
+ /**
+ * Simple visitor implementation for visiting MethodDeclaration nodes.
+ */
+ private static class MethodVisitor extends VoidVisitorAdapter<Void> {
+ @Override
+ public void visit(MethodDeclaration n, Void arg) {
+ /* here you can access the attributes of the method.
+ this method will be called for all methods in this
+ CompilationUnit, including inner class methods */
+ System.out.println(n.getName());
+ super.visit(n, arg);
+ }
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/PrintingTheCompilationUnitToSystemOutputTest.java b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/PrintingTheCompilationUnitToSystemOutputTest.java
new file mode 100644
index 000000000..26a907e27
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/PrintingTheCompilationUnitToSystemOutputTest.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.wiki_samples;
+
+import org.junit.Test;
+
+public class PrintingTheCompilationUnitToSystemOutputTest {
+ @Test
+ public void printingTheCompilationUnitToSystemOutput() throws Exception {
+ try (TestFileToken f = new TestFileToken("test.java")) {
+ CuPrinter.main(new String[]{});
+ }
+ }
+
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/TestFileToken.java b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/TestFileToken.java
new file mode 100644
index 000000000..3227c3d8f
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/TestFileToken.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.wiki_samples;
+
+import org.apache.commons.io.IOUtils;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import static org.junit.Assert.*;
+
+/**
+ * Creates a temporary test file that a sample can use. This way we don't have to rewrite the samples to fit them into
+ * these tests.
+ */
+public class TestFileToken implements AutoCloseable {
+ private final String filename;
+
+ public TestFileToken(String filename) {
+ this.filename = filename;
+ try {
+ try (InputStream i = getClass().getResourceAsStream("TestFile.java"); OutputStream o = new FileOutputStream(filename)) {
+ assertNotNull(i);
+ IOUtils.copy(i, o);
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ fail(e.getMessage());
+ }
+ }
+
+ @Override
+ public void close() {
+ boolean deleted = new File(filename).delete();
+ assertTrue(deleted);
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/VisitingClassMethodsTest.java b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/VisitingClassMethodsTest.java
new file mode 100644
index 000000000..599912411
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/VisitingClassMethodsTest.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.wiki_samples;
+
+import org.junit.Test;
+
+public class VisitingClassMethodsTest {
+ @Test
+ public void testCode() throws Exception {
+ try (TestFileToken f = new TestFileToken("test.java")) {
+ MethodPrinter.main(new String[]{});
+ }
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/removenode/D.java b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/removenode/D.java
new file mode 100644
index 000000000..dd925bc35
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/removenode/D.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.wiki_samples.removenode;
+
+public class D {
+
+ public void foo(int e) {
+ int a = 20;
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/removenode/ModifierVisitorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/removenode/ModifierVisitorTest.java
new file mode 100644
index 000000000..d522c9625
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/removenode/ModifierVisitorTest.java
@@ -0,0 +1,65 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.wiki_samples.removenode;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.ast.CompilationUnit;
+import com.github.javaparser.ast.Node;
+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.visitor.ModifierVisitor;
+
+import java.io.FileInputStream;
+
+public class ModifierVisitorTest {
+
+ public static void main(String... args) throws Exception {
+ // parse the file
+ CompilationUnit cu = JavaParser.parse(new FileInputStream("forGitHubTest.java"));
+
+ // The visitor should remove all a=20 variable declarations.
+ cu.accept(new MyVisitor(), null);
+
+ System.out.println(cu.toString());
+ }
+}
+
+class MyVisitor extends ModifierVisitor<Void> {
+ @Override
+ public Node visit(VariableDeclarator declarator, Void args) {
+ if (declarator.getNameAsString().equals("a")
+ // the initializer is optional, first check if there is one
+ && declarator.getInitializer().isPresent()) {
+ Expression expression = declarator.getInitializer().get();
+ // We're looking for a literal integer.
+ if (expression instanceof IntegerLiteralExpr) {
+ // We found one. Is it literal integer 20?
+ if (((IntegerLiteralExpr) expression).getValue().equals("20")) {
+ // Returning null means "remove this VariableDeclarator"
+ return null;
+ }
+ }
+ }
+ return declarator;
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/removenode/RemoveDeleteNodeFromAst.java b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/removenode/RemoveDeleteNodeFromAst.java
new file mode 100644
index 000000000..72756e94f
--- /dev/null
+++ b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/removenode/RemoveDeleteNodeFromAst.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.wiki_samples.removenode;
+
+import com.github.javaparser.wiki_samples.TestFileToken;
+import org.junit.Test;
+
+public class RemoveDeleteNodeFromAst {
+ @Test
+ public void testCode1() throws Exception {
+ try (TestFileToken f = new TestFileToken("forGitHubTest.java")) {
+ ModifierVisitorTest.main();
+ }
+ }
+}
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/TestFileIso88591.java b/javaparser-testing/src/test/resources/com/github/javaparser/TestFileIso88591.java
new file mode 100644
index 000000000..1777f949b
--- /dev/null
+++ b/javaparser-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-testing/src/test/resources/com/github/javaparser/bdd/comment_attribution_scenarios.story b/javaparser-testing/src/test/resources/com/github/javaparser/bdd/comment_attribution_scenarios.story
new file mode 100644
index 000000000..e509fc998
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/bdd/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-testing/src/test/resources/com/github/javaparser/bdd/comment_parsing_scenarios.story b/javaparser-testing/src/test/resources/com/github/javaparser/bdd/comment_parsing_scenarios.story
new file mode 100644
index 000000000..e41d6e497
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/bdd/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|25|
+|7|18|7|35|
+|8|9|8|25|
+|9|9|9|26|
+
+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|20|
+|7|5|7|28|
+|9|5|9|20|
+|19|5|19|21|
+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-testing/src/test/resources/com/github/javaparser/bdd/comparing_scenarios.story b/javaparser-testing/src/test/resources/com/github/javaparser/bdd/comparing_scenarios.story
new file mode 100644
index 000000000..fea7785ba
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/bdd/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<String> data = new ArrayList();
+ data.forEach( s -> System.out.println(s));
+ }
+}
+Given the second class:
+public class ArrayListGenericDemo {
+
+ public static void main(String[] args) {
+ ArrayList<String> data = new ArrayList();
+ data.forEach( s -> System.out.println(s));
+ }
+}
+Then they are equals
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/bdd/manipulation_scenarios.story b/javaparser-testing/src/test/resources/com/github/javaparser/bdd/manipulation_scenarios.story
new file mode 100644
index 000000000..ea2827961
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/bdd/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-testing/src/test/resources/com/github/javaparser/bdd/parsing_scenarios.story b/javaparser-testing/src/test/resources/com/github/javaparser/bdd/parsing_scenarios.story
new file mode 100644
index 000000000..9f6ee243d
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/bdd/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<String> /*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<String> 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<String> /*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<String> 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<CharSequence> stream = Stream.generate((Supplier<CharSequence>) () -> "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<Integer,String> f1 = (Integer i) -> String.valueOf(i);
+ Function<Integer,String> f2 = (i) -> String.valueOf(i);
+ Function<Integer,String> 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<Integer, Integer, String> 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 <T> Predicate<T> 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<ChronoLocalDate> DATE_ORDER =
+ (Comparator<ChronoLocalDate>) (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<ChronoLocalDate> DATE_ORDER =
+ (Comparator<ChronoLocalDate> & 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<ChronoLocalDate> & 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<String> 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<String> 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<Ok, Error> either = new Either<Ok, Error>();
+}
+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::<IVariable<?>>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-testing/src/test/resources/com/github/javaparser/bdd/position_range_scenarios.story b/javaparser-testing/src/test/resources/com/github/javaparser/bdd/position_range_scenarios.story
new file mode 100644
index 000000000..410e45625
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/bdd/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-testing/src/test/resources/com/github/javaparser/bdd/pretty_printing_java_concepts.story b/javaparser-testing/src/test/resources/com/github/javaparser/bdd/pretty_printing_java_concepts.story
new file mode 100644
index 000000000..2b7af19c1
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/bdd/pretty_printing_java_concepts.story
@@ -0,0 +1,399 @@
+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<T extends List<int[]>, 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<String>[][] arrLS = (List<String>[][]) new List<?>[10][];
+
+ {
+ int z = 0, y = 0;
+ int a = (z) + y;
+ a = (+z) + y;
+ byte b = (byte) +y;
+ }
+
+ List<String> 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 <T, E> JavaConcepts(int x) {
+ this.arr[0] = x;
+ T val1 = null;
+ E val2 = null;
+ super.<T, E>check2(val1, val2);
+ boolean b = true, y = false;
+ abstract class X {
+
+ int i = 0;
+
+ public <D> 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 <T> JavaConcepts(String str) {
+ }
+
+ private class QWE extends JavaConcepts<List<int[]>, String> {
+
+ @Deprecated
+ final int z = 0;
+
+ int i = (int) -1;
+
+ public QWE(String... x) {
+ <String>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<? extends Number> x = new ArrayList<Integer>();
+ 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<T extends Integer & Serializable> implements XXX, Serializable {
+
+ public <ABC> A(Integer integer, ABC string) throws Exception, IOException {
+ }
+ }
+
+ private <Y> void x(Map<? extends X, ? super T> x) {
+ @Deprecated Comparator c = new Comparator() {
+
+ public int compare(Object o1, Object o2) {
+ try {
+ A<Integer> a = new <String> A<Integer>(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 <A, B> void check2(A val1, B val2) {
+ }
+}
+
+interface XXX extends Serializable, Cloneable {
+}
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/bdd/pretty_printing_scenarios.story b/javaparser-testing/src/test/resources/com/github/javaparser/bdd/pretty_printing_scenarios.story
new file mode 100644
index 000000000..5450cb0de
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/bdd/pretty_printing_scenarios.story
@@ -0,0 +1,519 @@
+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<Integer> 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<Integer> 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;
+ b=3;
+}
+When the block is parsed by the Java parser
+Then it is printed as:
+{
+ a = 2;
+ b = 3;
+}
+
+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-testing/src/test/resources/com/github/javaparser/bdd/samples/ClassInLatin1.java b/javaparser-testing/src/test/resources/com/github/javaparser/bdd/samples/ClassInLatin1.java
new file mode 100644
index 000000000..096c70ad9
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/bdd/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-testing/src/test/resources/com/github/javaparser/bdd/samples/JavaConcepts.java b/javaparser-testing/src/test/resources/com/github/javaparser/bdd/samples/JavaConcepts.java
new file mode 100644
index 000000000..8e6dc924e
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/bdd/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<T extends List<int[]>, 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<String>[][] arrLS = (List<String>[][]) new List<?>[10][];
+
+ ;
+
+ {
+ int z = 0, y = 0;
+ int a = (z) + y;
+ a = (+z) + y;
+ byte b = (byte) +y;
+ }
+
+ List<String> 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 <T, E> JavaConcepts(int x) {
+ this.arr[0] = x;
+ T val1 = null;
+ E val2 = null;
+ super.<T, E>check2(val1, val2);
+ boolean b = true, y = false;
+ abstract class X {
+
+ int i = 0;
+
+ public <D> 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 <T> JavaConcepts(String str) {
+ }
+
+ private class QWE extends JavaConcepts<List<int[]>, String> {
+
+ @Deprecated
+ final int z = 0;
+
+ int i = (int) -1;
+
+ public QWE(String... x) {
+ <String>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<? extends Number> x = new ArrayList<Integer>();
+ 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<T extends Integer & Serializable> implements XXX, Serializable {
+
+ public <ABC> A(Integer integer, ABC string) throws Exception, IOException {
+ }
+ }
+
+ private <Y> void x(Map<? extends X, ? super T> x) {
+ @Deprecated Comparator c = new Comparator() {
+
+ public int compare(Object o1, Object o2) {
+ try {
+ A<Integer> a = new <String>A<Integer>(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 <A, B> void check2(A val1, B val2) {
+ }
+}
+
+interface XXX extends Serializable, Cloneable {
+}
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/bdd/samples/package-info.java b/javaparser-testing/src/test/resources/com/github/javaparser/bdd/samples/package-info.java
new file mode 100644
index 000000000..5703eb45a
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/bdd/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-testing/src/test/resources/com/github/javaparser/bdd/visitor_scenarios.story b/javaparser-testing/src/test/resources/com/github/javaparser/bdd/visitor_scenarios.story
new file mode 100644
index 000000000..634a9f28f
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/bdd/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-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results.txt b/javaparser-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results.txt
new file mode 100644
index 000000000..8a9fcbee5
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/bulk_test_results/javaparser_test_results.txt
@@ -0,0 +1 @@
+0 problems in 0 files \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/bulk_test_results/openjdk_src_repo_test_results.txt b/javaparser-testing/src/test/resources/com/github/javaparser/bulk_test_results/openjdk_src_repo_test_results.txt
new file mode 100644
index 000000000..b3d4e574e
--- /dev/null
+++ b/javaparser-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" <IDENTIFIER>, expected one of ";" "@" "\u001a" "abstract" "class" "default" "enum" "final" "import" "interface" "module" "native" "open" "private" "protected" "public" "static" "strictfp" "synchronized" "transient" "transitive" "volatile" <EOF>
+
+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" <INTEGER_LITERAL>, 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 <EOF>, expected "}"
+(line 14,col 2) Parse error. Found <EOF>, 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" "{" "}" <IDENTIFIER>
+
+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" <IDENTIFIER>
+
+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" "}" <IDENTIFIER>
+
+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" "}" <IDENTIFIER>
+
+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" "~" <CHARACTER_LITERAL> <FLOATING_POINT_LITERAL> <IDENTIFIER> <INTEGER_LITERAL> <LONG_LITERAL> <STRING_LITERAL>
+(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" "~" <CHARACTER_LITERAL> <FLOATING_POINT_LITERAL> <IDENTIFIER> <INTEGER_LITERAL> <LONG_LITERAL> <STRING_LITERAL>
+(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" "~" <CHARACTER_LITERAL> <FLOATING_POINT_LITERAL> <IDENTIFIER> <INTEGER_LITERAL> <LONG_LITERAL> <STRING_LITERAL>
+(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" "~" <CHARACTER_LITERAL> <FLOATING_POINT_LITERAL> <IDENTIFIER> <INTEGER_LITERAL> <LONG_LITERAL> <STRING_LITERAL>
+
+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" "~" <CHARACTER_LITERAL> <FLOATING_POINT_LITERAL> <IDENTIFIER> <INTEGER_LITERAL> <LONG_LITERAL> <STRING_LITERAL>
+
+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" <IDENTIFIER>
+
+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" <CHARACTER_LITERAL> <FLOATING_POINT_LITERAL> <IDENTIFIER> <INTEGER_LITERAL> <LONG_LITERAL> <STRING_LITERAL>
+(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" "~" <CHARACTER_LITERAL> <FLOATING_POINT_LITERAL> <IDENTIFIER> <INTEGER_LITERAL> <LONG_LITERAL> <STRING_LITERAL>
+
+langtools-19293ea3999f/test/tools/javac/api/T6265137a.java
+(line 24,col 1) Parse error. Found <EOF>, expected one of "enum" "exports" "module" "open" "opens" "provides" "requires" "strictfp" "to" "transitive" "uses" "with" <IDENTIFIER>
+
+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" <IDENTIFIER>, 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" <IDENTIFIER>
+
+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: <EOF> 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" <IDENTIFIER>
+
+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" <EOF>
+
+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" "~" <CHARACTER_LITERAL> <FLOATING_POINT_LITERAL> <IDENTIFIER> <INTEGER_LITERAL> <LONG_LITERAL> <STRING_LITERAL>
+
+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" <EOF>
+
+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" <EOF>
+
+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" <EOF>
+
+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 <EOF>, expected "}"
+(line 31,col 2) Parse error. Found <EOF>, 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" "{" "}" <IDENTIFIER>
+
+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" <IDENTIFIER>
+
+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" <EOF>
+
+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" <IDENTIFIER>
+
+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" <IDENTIFIER>, 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" "{" "~" <CHARACTER_LITERAL> <FLOATING_POINT_LITERAL> <IDENTIFIER> <INTEGER_LITERAL> <LONG_LITERAL> <STRING_LITERAL>
+
+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" "{" <CHARACTER_LITERAL> <FLOATING_POINT_LITERAL> <IDENTIFIER> <INTEGER_LITERAL> <LONG_LITERAL> <STRING_LITERAL>
+(line 31,col 2) Parse error. Found <EOF>, expected one of "else" "}"
+(line 31,col 2) Parse error. Found <EOF>, 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" "{" "}" <IDENTIFIER>
+
+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 "_" <IDENTIFIER>, 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" "}" <IDENTIFIER>
+
+langtools-19293ea3999f/test/tools/javac/diags/examples/InvalidBinaryNumber.java
+(line 27,col 13) Parse error. Found "b201000010" <IDENTIFIER>, expected one of "!=" "%" "%=" "&" "&&" "&=" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||"
+
+langtools-19293ea3999f/test/tools/javac/diags/examples/InvalidHexNumber.java
+(line 28,col 13) Parse error. Found "xz1357abc" <IDENTIFIER>, expected one of "!=" "%" "%=" "&" "&&" "&=" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||"
+
+langtools-19293ea3999f/test/tools/javac/diags/examples/InvalidModuleDirective/module-info.java
+(line 27,col 21) Parse error. Found "resuires" <IDENTIFIER>, 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" <IDENTIFIER>, 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" "~" <CHARACTER_LITERAL> <FLOATING_POINT_LITERAL> <IDENTIFIER> <INTEGER_LITERAL> <LONG_LITERAL> <STRING_LITERAL>
+
+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" "{" <CHARACTER_LITERAL> <FLOATING_POINT_LITERAL> <IDENTIFIER> <INTEGER_LITERAL> <LONG_LITERAL> <STRING_LITERAL>
+(line 31,col 2) Parse error. Found <EOF>, expected one of "else" "}"
+(line 31,col 2) Parse error. Found <EOF>, 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" "{" "}" <IDENTIFIER>
+
+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" <CHARACTER_LITERAL> <FLOATING_POINT_LITERAL> <IDENTIFIER> <INTEGER_LITERAL> <LONG_LITERAL> <STRING_LITERAL>
+
+langtools-19293ea3999f/test/tools/javac/diags/examples/NotAStatement.java
+(line 27,col 14) Parse error. Found "x" <IDENTIFIER>, 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 <EOF>, 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" "{" "}" <IDENTIFIER>
+
+langtools-19293ea3999f/test/tools/javac/diags/examples/ProcessorWrongType/ProcessorWrongType.java
+Parse error. Found "clas" <IDENTIFIER>, expected one of ";" "@" "\u001a" "abstract" "class" "default" "enum" "final" "import" "interface" "module" "native" "open" "private" "protected" "public" "static" "strictfp" "synchronized" "transient" "transitive" "volatile" <EOF>
+
+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" <IDENTIFIER>
+
+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: <EOF> 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" <IDENTIFIER>, expected one of ";" "@" "\u001a" "abstract" "class" "default" "enum" "final" "import" "interface" "module" "native" "open" "private" "protected" "public" "static" "strictfp" "synchronized" "transient" "transitive" "volatile" <EOF>
+
+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" <IDENTIFIER>
+
+langtools-19293ea3999f/test/tools/javac/Digits.java
+(line 11,col 40) Parse error. Found "\\u0663" <IDENTIFIER>, 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" <IDENTIFIER>, 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 <EOF>, expected "}"
+(line 13,col 2) Parse error. Found <EOF>, 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" "{" "}" <IDENTIFIER>
+
+langtools-19293ea3999f/test/tools/javac/EOI.java
+(line 10,col 16) Parse error. Found "foobar\u001a" <IDENTIFIER>, expected one of ";" "@" "\u001a" "abstract" "class" "default" "enum" "final" "import" "interface" "module" "native" "open" "private" "protected" "public" "static" "strictfp" "synchronized" "transient" "transitive" "volatile" <EOF>
+
+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" "~" <CHARACTER_LITERAL> <FLOATING_POINT_LITERAL> <IDENTIFIER> <INTEGER_LITERAL> <LONG_LITERAL> <STRING_LITERAL>
+
+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 <EOF>, expected "}"
+(line 10,col 26) Parse error. Found <EOF>, 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" "{" "}" <IDENTIFIER>
+
+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 <EOF>, expected "}"
+(line 19,col 2) Parse error. Found <EOF>, 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" "{" "}" <IDENTIFIER>
+
+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" <EOF>
+
+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" "{" "}" <IDENTIFIER>
+
+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" <CHARACTER_LITERAL> <FLOATING_POINT_LITERAL> <IDENTIFIER> <INTEGER_LITERAL> <LONG_LITERAL> <STRING_LITERAL>
+
+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" <INTEGER_LITERAL>, 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 <EOF>, expected "}"
+(line 15,col 2) Parse error. Found <EOF>, 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" "{" "}" <IDENTIFIER>
+
+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 <EOF>, expected "}"
+(line 17,col 2) Parse error. Found <EOF>, 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" "{" "}" <IDENTIFIER>
+
+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" "~" <CHARACTER_LITERAL> <FLOATING_POINT_LITERAL> <IDENTIFIER> <INTEGER_LITERAL> <LONG_LITERAL> <STRING_LITERAL>
+
+langtools-19293ea3999f/test/tools/javac/literals/BadBinaryLiterals.java
+(line 11,col 20) Parse error. Found "2" <INTEGER_LITERAL>, expected one of "!=" "%" "%=" "&" "&&" "&=" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||"
+
+langtools-19293ea3999f/test/tools/javac/literals/BadUnderscoreLiterals.java
+(line 15,col 14) Parse error. Found "_" <IDENTIFIER>, expected one of "!=" "%" "%=" "&" "&&" "&=" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||"
+
+langtools-19293ea3999f/test/tools/javac/literals/T6891079.java
+(line 8,col 14) Parse error. Found "B" <IDENTIFIER>, expected one of "!=" "%" "%=" "&" "&&" "&=" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||"
+
+langtools-19293ea3999f/test/tools/javac/modules/InvalidModuleDirective/module-info.java
+(line 9,col 21) Parse error. Found "resuires" <IDENTIFIER>, 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 <EOF>, expected one of "else" "}"
+(line 13,col 2) Parse error. Found <EOF>, 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" "{" "}" <IDENTIFIER>
+
+langtools-19293ea3999f/test/tools/javac/parser/SingleCommaAnnotationValueFail.java
+(line 34,col 11) Parse error. Found "0" <INTEGER_LITERAL>, 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" <IDENTIFIER>
+
+langtools-19293ea3999f/test/tools/javac/policy/test3/A.java
+(line 5,col 36) Parse error. Found "0" <INTEGER_LITERAL>, 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" <IDENTIFIER>
+
+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 <EOF>, 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" <IDENTIFIER>, 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" "{" "~" <CHARACTER_LITERAL> <FLOATING_POINT_LITERAL> <IDENTIFIER> <INTEGER_LITERAL> <LONG_LITERAL> <STRING_LITERAL>
+
+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" <IDENTIFIER>
+
+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" "{" "}" <IDENTIFIER>
+
+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" "{" "}" <IDENTIFIER>
+
+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" <CHARACTER_LITERAL> <FLOATING_POINT_LITERAL> <IDENTIFIER> <INTEGER_LITERAL> <LONG_LITERAL> <STRING_LITERAL>
+(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" "{" "}" <IDENTIFIER>
+
+langtools-19293ea3999f/test/tools/javac/unicode/FirstChar2.java
+Parse error. Found "\\u0070ublic" <IDENTIFIER>, expected one of ";" "@" "\u001a" "abstract" "class" "default" "enum" "final" "import" "interface" "module" "native" "open" "private" "protected" "public" "static" "strictfp" "synchronized" "transient" "transitive" "volatile" <EOF>
+
+langtools-19293ea3999f/test/tools/javac/unicode/NonasciiDigit.java
+(line 13,col 18) Parse error. Found "\\uff11" <IDENTIFIER>, expected one of "!=" "%" "%=" "&" "&&" "&=" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||"
+(line 16,col 21) Parse error. Found ".0" <FLOATING_POINT_LITERAL>, expected one of "!=" "%" "%=" "&" "&&" "&=" "(" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||"
+(line 17,col 21) Parse error. Found "\\uff11" <IDENTIFIER>, expected one of "!=" "%" "%=" "&" "&&" "&=" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||"
+(line 18,col 21) Parse error. Found "P\\uff11" <IDENTIFIER>, expected one of "!=" "%" "%=" "&" "&&" "&=" "*" "*=" "+" "+=" "," "-" "-=" "->" "/" "/=" "::" ";" "<" "<<=" "<=" "=" "==" ">" ">=" ">>=" ">>>=" "?" "^" "^=" "instanceof" "|" "|=" "||"
+(line 19,col 21) Parse error. Found "E\\uff11" <IDENTIFIER>, 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" "{" "~" <CHARACTER_LITERAL> <FLOATING_POINT_LITERAL> <IDENTIFIER> <INTEGER_LITERAL> <LONG_LITERAL> <STRING_LITERAL>
+(line 21,col 21) Parse error. Found ".0" <FLOATING_POINT_LITERAL>, 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" <IDENTIFIER>, expected "}"
+
+langtools-19293ea3999f/test/tools/javac/unicode/UnicodeCommentDelimiter.java
+(line 44,col 22) Parse error. Found "plugh" <IDENTIFIER>, 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" <IDENTIFIER>
+
+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-testing/src/test/resources/com/github/javaparser/bulk_test_results/openjdk_src_zip_test_results.txt b/javaparser-testing/src/test/resources/com/github/javaparser/bulk_test_results/openjdk_src_zip_test_results.txt
new file mode 100644
index 000000000..8e95fac36
--- /dev/null
+++ b/javaparser-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-testing/src/test/resources/com/github/javaparser/issue_samples/Issue290.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/issue_samples/Issue290.java.txt
new file mode 100644
index 000000000..2b39ff895
--- /dev/null
+++ b/javaparser-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<Object>() {
+ 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-testing/src/test/resources/com/github/javaparser/issue_samples/Issue624.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/issue_samples/Issue624.java.txt
new file mode 100644
index 000000000..de86d112d
--- /dev/null
+++ b/javaparser-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-testing/src/test/resources/com/github/javaparser/issue_samples/issue1003.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/issue_samples/issue1003.java.txt
new file mode 100644
index 000000000..0f8f460f2
--- /dev/null
+++ b/javaparser-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<p> a = new SparseArray();
+ private final ActivityManager c;
+ private final TActivityManagerService d;
+ private com.trigtech.privateme.helper.utils.a<Integer, p> e = new com.trigtech.privateme.helper.utils.a();
+ private com.trigtech.privateme.helper.utils.a<Integer, f> f = new com.trigtech.privateme.helper.utils.a();
+ private com.trigtech.privateme.helper.utils.a<Integer, List<c>> g = new com.trigtech.privateme.helper.utils.a();
+ private com.trigtech.privateme.helper.utils.a<Integer, List<c>> 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<c> 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:<init> (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: <illegal opcode>
+ // 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<c> 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<AppSetting> 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-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/ASimpleClassWithMoreFormatting.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/ASimpleClassWithMoreFormatting.java.txt
new file mode 100644
index 000000000..400c026d1
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/ASimpleClassWithMoreFormatting.java.txt
@@ -0,0 +1,26 @@
+package com.github.javaparser.examples;
+
+
+/**
+ * A class with some uncommon formatting, to check the lexical preservation
+ */
+public class
+ASimpleClass
+{
+
+ boolean aField;
+
+ public ASimpleClass(boolean aField)
+ {
+ this.aField = aField;
+ }
+
+
+ // Some empty lines
+
+
+ public boolean getAField()
+ {
+ return aField;
+ }
+}
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/ASimpleClassWithMoreFormatting_step1.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/ASimpleClassWithMoreFormatting_step1.java.txt
new file mode 100644
index 000000000..0ce70e62d
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/ASimpleClassWithMoreFormatting_step1.java.txt
@@ -0,0 +1,26 @@
+package com.github.javaparser.examples;
+
+
+/**
+ * A class with some uncommon formatting, to check the lexical preservation
+ */
+public class
+MyRenamedClass
+{
+
+ boolean aField;
+
+ public ASimpleClass(boolean aField)
+ {
+ this.aField = aField;
+ }
+
+
+ // Some empty lines
+
+
+ public boolean getAField()
+ {
+ return aField;
+ }
+}
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/ASimpleClassWithMoreFormatting_step2.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/ASimpleClassWithMoreFormatting_step2.java.txt
new file mode 100644
index 000000000..84ceb290f
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/ASimpleClassWithMoreFormatting_step2.java.txt
@@ -0,0 +1,29 @@
+package com.github.javaparser.examples;
+
+
+/**
+ * A class with some uncommon formatting, to check the lexical preservation
+ */
+public class
+MyRenamedClass
+{
+
+ boolean aField;
+
+ public ASimpleClass(boolean aField)
+ {
+ this.aField = aField;
+ }
+
+
+ // Some empty lines
+
+
+ public boolean getAField()
+ {
+ return aField;
+ }
+
+ public void setAField() {
+ }
+}
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/ASimpleClassWithMoreFormatting_step3.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/ASimpleClassWithMoreFormatting_step3.java.txt
new file mode 100644
index 000000000..56d5940fe
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/ASimpleClassWithMoreFormatting_step3.java.txt
@@ -0,0 +1,29 @@
+package com.github.javaparser.examples;
+
+
+/**
+ * A class with some uncommon formatting, to check the lexical preservation
+ */
+public class
+MyRenamedClass
+{
+
+ boolean aField;
+
+ public ASimpleClass(boolean aField)
+ {
+ this.aField = aField;
+ }
+
+
+ // Some empty lines
+
+
+ public boolean getAField()
+ {
+ return aField;
+ }
+
+ public void setAField(boolean aField) {
+ }
+}
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/ASimpleClassWithMoreFormatting_step4.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/ASimpleClassWithMoreFormatting_step4.java.txt
new file mode 100644
index 000000000..646533401
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/ASimpleClassWithMoreFormatting_step4.java.txt
@@ -0,0 +1,30 @@
+package com.github.javaparser.examples;
+
+
+/**
+ * A class with some uncommon formatting, to check the lexical preservation
+ */
+public class
+MyRenamedClass
+{
+
+ boolean aField;
+
+ public ASimpleClass(boolean aField)
+ {
+ this.aField = aField;
+ }
+
+
+ // Some empty lines
+
+
+ public boolean getAField()
+ {
+ return aField;
+ }
+
+ public void setAField(boolean aField) {
+ this.aField = aField;
+ }
+}
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example10_expected.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example10_expected.java.txt
new file mode 100644
index 000000000..131378890
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example10_expected.java.txt
@@ -0,0 +1,11 @@
+// some example
+/** Super extra cool this annotation!!!*/
+public @interface ClassPreamble {
+ String author();
+ String date();
+ int currentRevision() default 1;
+ String lastModified() default "N/A";
+ String lastModifiedBy() default "N/A";
+ // Note use of array
+ String[] reviewers();
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example1_expected.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example1_expected.java.txt
new file mode 100644
index 000000000..33545c2cc
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example1_expected.java.txt
@@ -0,0 +1,11 @@
+// some example
+
+@interface NewName {
+ String author();
+ String date();
+ int currentRevision() default 1;
+ String lastModified() default "N/A";
+ String lastModifiedBy() default "N/A";
+ // Note use of array
+ String[] reviewers();
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example1_original.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example1_original.java.txt
new file mode 100644
index 000000000..e2ec99c9c
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example1_original.java.txt
@@ -0,0 +1,11 @@
+// some example
+
+@interface ClassPreamble {
+ String author();
+ String date();
+ int currentRevision() default 1;
+ String lastModified() default "N/A";
+ String lastModifiedBy() default "N/A";
+ // Note use of array
+ String[] reviewers();
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example2_expected.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example2_expected.java.txt
new file mode 100644
index 000000000..2f4a81371
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example2_expected.java.txt
@@ -0,0 +1,11 @@
+// some example
+
+public @interface ClassPreamble {
+ String author();
+ String date();
+ int currentRevision() default 1;
+ String lastModified() default "N/A";
+ String lastModifiedBy() default "N/A";
+ // Note use of array
+ String[] reviewers();
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example3_expected.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example3_expected.java.txt
new file mode 100644
index 000000000..e2ec99c9c
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example3_expected.java.txt
@@ -0,0 +1,11 @@
+// some example
+
+@interface ClassPreamble {
+ String author();
+ String date();
+ int currentRevision() default 1;
+ String lastModified() default "N/A";
+ String lastModifiedBy() default "N/A";
+ // Note use of array
+ String[] reviewers();
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example3_original.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example3_original.java.txt
new file mode 100644
index 000000000..2f4a81371
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example3_original.java.txt
@@ -0,0 +1,11 @@
+// some example
+
+public @interface ClassPreamble {
+ String author();
+ String date();
+ int currentRevision() default 1;
+ String lastModified() default "N/A";
+ String lastModifiedBy() default "N/A";
+ // Note use of array
+ String[] reviewers();
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example4_expected.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example4_expected.java.txt
new file mode 100644
index 000000000..8d1c03cf1
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example4_expected.java.txt
@@ -0,0 +1,11 @@
+// some example
+
+protected @interface ClassPreamble {
+ String author();
+ String date();
+ int currentRevision() default 1;
+ String lastModified() default "N/A";
+ String lastModifiedBy() default "N/A";
+ // Note use of array
+ String[] reviewers();
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example5_expected.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example5_expected.java.txt
new file mode 100644
index 000000000..1faad9965
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example5_expected.java.txt
@@ -0,0 +1,12 @@
+// some example
+
+public @interface ClassPreamble {
+ String author();
+ String date();
+ int currentRevision() default 1;
+ String lastModified() default "N/A";
+ String lastModifiedBy() default "N/A";
+ // Note use of array
+ String[] reviewers();
+ int foo();
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example6_expected.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example6_expected.java.txt
new file mode 100644
index 000000000..9690ec424
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example6_expected.java.txt
@@ -0,0 +1,10 @@
+// some example
+
+public @interface ClassPreamble {
+ String author();
+ String date();
+ String lastModified() default "N/A";
+ String lastModifiedBy() default "N/A";
+ // Note use of array
+ String[] reviewers();
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example7_expected.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example7_expected.java.txt
new file mode 100644
index 000000000..9bc5a6148
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example7_expected.java.txt
@@ -0,0 +1,11 @@
+// some example
+
+public @interface ClassPreamble {
+ String author();
+ String date();
+ int foo();
+ String lastModified() default "N/A";
+ String lastModifiedBy() default "N/A";
+ // Note use of array
+ String[] reviewers();
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example8_expected.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example8_expected.java.txt
new file mode 100644
index 000000000..2a5fd934f
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example8_expected.java.txt
@@ -0,0 +1,12 @@
+// some example
+
+/** Cool this annotation!*/
+public @interface ClassPreamble {
+ String author();
+ String date();
+ int currentRevision() default 1;
+ String lastModified() default "N/A";
+ String lastModifiedBy() default "N/A";
+ // Note use of array
+ String[] reviewers();
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example9_expected.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example9_expected.java.txt
new file mode 100644
index 000000000..a5deb801b
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example9_expected.java.txt
@@ -0,0 +1,10 @@
+// some example
+public @interface ClassPreamble {
+ String author();
+ String date();
+ int currentRevision() default 1;
+ String lastModified() default "N/A";
+ String lastModifiedBy() default "N/A";
+ // Note use of array
+ String[] reviewers();
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example9_original.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example9_original.java.txt
new file mode 100644
index 000000000..cd7edcded
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/AnnotationDeclaration_Example9_original.java.txt
@@ -0,0 +1,11 @@
+// some example
+/**Cool this annotation!*/
+public @interface ClassPreamble {
+ String author();
+ String date();
+ int currentRevision() default 1;
+ String lastModified() default "N/A";
+ String lastModifiedBy() default "N/A";
+ // Note use of array
+ String[] reviewers();
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example10_expected.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example10_expected.java.txt
new file mode 100644
index 000000000..d1edb056f
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example10_expected.java.txt
@@ -0,0 +1,3 @@
+// This is my class, with my comment
+class A {
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example10_original.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example10_original.java.txt
new file mode 100644
index 000000000..2021255a9
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example10_original.java.txt
@@ -0,0 +1,4 @@
+// This is my class, with my comment
+class A {
+ int a = 10;
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example1_expected.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example1_expected.java.txt
new file mode 100644
index 000000000..e6c1ee7ab
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example1_expected.java.txt
@@ -0,0 +1,4 @@
+// This is my class, with my comment
+class A {
+ static int a;
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example1_original.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example1_original.java.txt
new file mode 100644
index 000000000..5b62bcf7e
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example1_original.java.txt
@@ -0,0 +1,4 @@
+// This is my class, with my comment
+class A {
+ int a;
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example2_expected.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example2_expected.java.txt
new file mode 100644
index 000000000..2021255a9
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example2_expected.java.txt
@@ -0,0 +1,4 @@
+// This is my class, with my comment
+class A {
+ int a = 10;
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example2_original.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example2_original.java.txt
new file mode 100644
index 000000000..5b62bcf7e
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example2_original.java.txt
@@ -0,0 +1,4 @@
+// This is my class, with my comment
+class A {
+ int a;
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example3_expected.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example3_expected.java.txt
new file mode 100644
index 000000000..5b62bcf7e
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example3_expected.java.txt
@@ -0,0 +1,4 @@
+// This is my class, with my comment
+class A {
+ int a;
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example3_original.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example3_original.java.txt
new file mode 100644
index 000000000..2021255a9
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example3_original.java.txt
@@ -0,0 +1,4 @@
+// This is my class, with my comment
+class A {
+ int a = 10;
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example4_original.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example4_original.java.txt
new file mode 100644
index 000000000..da4651db2
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example4_original.java.txt
@@ -0,0 +1,398 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser;
+
+import com.github.javaparser.ast.CompilationUnit;
+import com.github.javaparser.ast.Node;
+import com.github.javaparser.ast.body.BodyDeclaration;
+import com.github.javaparser.ast.comments.CommentsCollection;
+import com.github.javaparser.ast.expr.AnnotationExpr;
+import com.github.javaparser.ast.expr.Expression;
+import com.github.javaparser.ast.expr.VariableDeclarationExpr;
+import com.github.javaparser.ast.imports.ImportDeclaration;
+import com.github.javaparser.ast.stmt.BlockStmt;
+import com.github.javaparser.ast.stmt.Statement;
+import com.github.javaparser.ast.type.ClassOrInterfaceType;
+
+import java.io.*;
+import java.nio.charset.Charset;
+import java.nio.file.Path;
+
+import static com.github.javaparser.ParseStart.*;
+import static com.github.javaparser.Providers.UTF8;
+import static com.github.javaparser.Providers.provider;
+import static com.github.javaparser.Providers.resourceProvider;
+import static com.github.javaparser.utils.Utils.assertNotNull;
+
+/**
+ * Parse Java source code and creates Abstract Syntax Trees.
+ *
+ * @author Júlio Vilmar Gesser
+ */
+public final class JavaParser {
+ private static final JavaParser defaultInstance = new JavaParser();
+
+ private final CommentsInserter commentsInserter;
+ private final ParserConfiguration configuration;
+
+ private ASTParser astParser = null;
+
+ /**
+ * Instantiate the parser with default configuration. Note that parsing can also be done with the static methods on
+ * this class.
+ * Creating an instance will reduce setup time between parsing files.
+ */
+ public JavaParser() {
+ this(new ParserConfiguration());
+ }
+
+ /**
+ * Instantiate the parser. Note that parsing can also be done with the static methods on this class.
+ * Creating an instance will reduce setup time between parsing files.
+ */
+ public JavaParser(ParserConfiguration configuration) {
+ this.configuration = configuration;
+ commentsInserter = new CommentsInserter(configuration);
+ }
+
+ private ASTParser getParserForProvider(Provider provider) {
+ if (astParser == null) {
+ astParser = new ASTParser(provider);
+ } else {
+ astParser.reset(provider);
+ }
+ astParser.setTabSize(configuration.getTabSize());
+ return astParser;
+ }
+
+ /**
+ * Parses source code.
+ * It takes the source code from a Provider.
+ * The start indicates what can be found in the source code (compilation unit, block, import...)
+ *
+ * @param start refer to the constants in ParseStart to see what can be parsed.
+ * @param provider refer to Providers to see how you can read source.
+ * @param <N> the subclass of Node that is the result of parsing in the start.
+ * @return the parse result, a collection of encountered problems, and some extra data.
+ */
+ public <N extends Node> ParseResult<N> parse(ParseStart<N> start, Provider provider) {
+ assertNotNull(start);
+ assertNotNull(provider);
+ try {
+ final ASTParser parser = getParserForProvider(provider);
+ N resultNode = start.parse(parser);
+ if (configuration.isAttributeComments()) {
+ final CommentsCollection comments = parser.getCommentsCollection();
+ commentsInserter.insertComments(resultNode, comments.copy().getComments());
+ }
+
+ return new ParseResult<>(resultNode, parser.problems, parser.getTokens(),
+ parser.getCommentsCollection());
+ } catch (Exception e) {
+ return new ParseResult<>(e);
+ } finally {
+ try {
+ provider.close();
+ } catch (IOException e) {
+ // Since we're done parsing and have our result, we don't care about any errors.
+ }
+ }
+ }
+
+ /**
+ * Parses the Java code contained in the {@link InputStream} and returns a
+ * {@link CompilationUnit} that represents it.
+ *
+ * @param in {@link InputStream} containing Java source code
+ * @param encoding encoding of the source code
+ * @return CompilationUnit representing the Java source code
+ * @throws ParseProblemException if the source code has parser errors
+ */
+ public static CompilationUnit parse(final InputStream in, Charset encoding) {
+ return simplifiedParse(COMPILATION_UNIT, provider(in, encoding));
+ }
+
+ /**
+ * Parses the Java code contained in the {@link InputStream} and returns a
+ * {@link CompilationUnit} that represents it.<br>
+ * Note: Uses UTF-8 encoding
+ *
+ * @param in {@link InputStream} containing Java source code
+ * @return CompilationUnit representing the Java source code
+ * @throws ParseProblemException if the source code has parser errors
+ */
+ public static CompilationUnit parse(final InputStream in) {
+ return parse(in, UTF8);
+ }
+
+ /**
+ * Parses the Java code contained in a {@link File} and returns a
+ * {@link CompilationUnit} that represents it.
+ *
+ * @param file {@link File} containing Java source code
+ * @param encoding encoding of the source code
+ * @return CompilationUnit representing the Java source code
+ * @throws ParseProblemException if the source code has parser errors
+ * @throws FileNotFoundException the file was not found
+ */
+ public static CompilationUnit parse(final File file, final Charset encoding) throws FileNotFoundException {
+ return simplifiedParse(COMPILATION_UNIT, provider(file, encoding));
+ }
+
+ /**
+ * Parses the Java code contained in a {@link File} and returns a
+ * {@link CompilationUnit} that represents it.<br>
+ * Note: Uses UTF-8 encoding
+ *
+ * @param file {@link File} containing Java source code
+ * @return CompilationUnit representing the Java source code
+ * @throws ParseProblemException if the source code has parser errors
+ * @throws FileNotFoundException the file was not found
+ */
+ public static CompilationUnit parse(final File file) throws FileNotFoundException {
+ return simplifiedParse(COMPILATION_UNIT, provider(file));
+ }
+
+ /**
+ * Parses the Java code contained in a file and returns a
+ * {@link CompilationUnit} that represents it.
+ *
+ * @param path path to a file containing Java source code
+ * @param encoding encoding of the source code
+ * @return CompilationUnit representing the Java source code
+ * @throws IOException the path could not be accessed
+ * @throws ParseProblemException if the source code has parser errors
+ */
+ public static CompilationUnit parse(final Path path, final Charset encoding) throws IOException {
+ return simplifiedParse(COMPILATION_UNIT, provider(path, encoding));
+ }
+
+ /**
+ * Parses the Java code contained in a file and returns a
+ * {@link CompilationUnit} that represents it.<br>
+ * Note: Uses UTF-8 encoding
+ *
+ * @param path path to a file containing Java source code
+ * @return CompilationUnit representing the Java source code
+ * @throws ParseProblemException if the source code has parser errors
+ * @throws IOException the path could not be accessed
+ */
+ public static CompilationUnit parse(final Path path) throws IOException {
+ return simplifiedParse(COMPILATION_UNIT, provider(path));
+ }
+
+ /**
+ * Parses the Java code contained in a resource and returns a
+ * {@link CompilationUnit} that represents it.<br>
+ * Note: Uses UTF-8 encoding
+ *
+ * @param path path to a resource containing Java source code. As resource is
+ * accessed through a class loader, a leading "/" is not allowed in pathToResource
+ * @return CompilationUnit representing the Java source code
+ * @throws ParseProblemException if the source code has parser errors
+ * @throws IOException the path could not be accessed
+ */
+ public static CompilationUnit parseResource(final String path) throws IOException {
+ return simplifiedParse(COMPILATION_UNIT, resourceProvider(path));
+ }
+
+ /**
+ * Parses the Java code contained in a resource and returns a
+ * {@link CompilationUnit} that represents it.<br>
+ *
+ * @param path path to a resource containing Java source code. As resource is
+ * accessed through a class loader, a leading "/" is not allowed in pathToResource
+ * @param encoding encoding of the source code
+ * @return CompilationUnit representing the Java source code
+ * @throws ParseProblemException if the source code has parser errors
+ * @throws IOException the path could not be accessed
+ */
+ public static CompilationUnit parseResource(final String path, Charset encoding) throws IOException {
+ return simplifiedParse(COMPILATION_UNIT, resourceProvider(path, encoding));
+ }
+
+ /**
+ * Parses the Java code contained in a resource and returns a
+ * {@link CompilationUnit} that represents it.<br>
+ *
+ * @param classLoader the classLoader that is asked to load the resource
+ * @param path path to a resource containing Java source code. As resource is
+ * accessed through a class loader, a leading "/" is not allowed in pathToResource
+ * @return CompilationUnit representing the Java source code
+ * @throws ParseProblemException if the source code has parser errors
+ * @throws IOException the path could not be accessed
+ */
+ public static CompilationUnit parseResource(final ClassLoader classLoader, final String path, Charset encoding) throws IOException {
+ return simplifiedParse(COMPILATION_UNIT, resourceProvider(classLoader, path, encoding));
+ }
+
+ /**
+ * Parses Java code from a Reader and returns a
+ * {@link CompilationUnit} that represents it.<br>
+ *
+ * @param reader the reader containing Java source code
+ * @return CompilationUnit representing the Java source code
+ * @throws ParseProblemException if the source code has parser errors
+ */
+ public static CompilationUnit parse(final Reader reader) {
+ return simplifiedParse(COMPILATION_UNIT, provider(reader));
+ }
+
+ /**
+ * Parses the Java code contained in code and returns a
+ * {@link CompilationUnit} that represents it.
+ *
+ * @param code Java source code
+ * @return CompilationUnit representing the Java source code
+ * @throws ParseProblemException if the source code has parser errors
+ */
+ public static CompilationUnit parse(String code) {
+ return simplifiedParse(COMPILATION_UNIT, provider(code));
+ }
+
+ /**
+ * Parses the Java block contained in a {@link String} and returns a
+ * {@link BlockStmt} that represents it.
+ *
+ * @param blockStatement {@link String} containing Java block code
+ * @return BlockStmt representing the Java block
+ * @throws ParseProblemException if the source code has parser errors
+ */
+ public static BlockStmt parseBlock(final String blockStatement) {
+ return simplifiedParse(BLOCK, provider(blockStatement));
+ }
+
+ /**
+ * Parses the Java statement contained in a {@link String} and returns a
+ * {@link Statement} that represents it.
+ *
+ * @param statement {@link String} containing Java statement code
+ * @return Statement representing the Java statement
+ * @throws ParseProblemException if the source code has parser errors
+ */
+ public static Statement parseStatement(final String statement) {
+ return simplifiedParse(STATEMENT, provider(statement));
+ }
+
+ private static <T extends Node> T simplifiedParse(ParseStart<T> context, Provider provider) {
+ ParseResult<T> result = defaultInstance.parse(context, provider);
+ if (result.isSuccessful()) {
+ return result.getResult().get();
+ }
+ throw new ParseProblemException(result.getProblems());
+ }
+
+ /**
+ * Parses the Java import contained in a {@link String} and returns a
+ * {@link ImportDeclaration} that represents it.
+ *
+ * @param importDeclaration {@link String} containing Java import code
+ * @return ImportDeclaration representing the Java import declaration
+ * @throws ParseProblemException if the source code has parser errors
+ */
+ public static ImportDeclaration parseImport(final String importDeclaration) {
+ return simplifiedParse(IMPORT_DECLARATION, provider(importDeclaration));
+ }
+
+ /**
+ * Parses the Java expression contained in a {@link String} and returns a
+ * {@link Expression} that represents it.
+ *
+ * @param expression {@link String} containing Java expression
+ * @return Expression representing the Java expression
+ * @throws ParseProblemException if the source code has parser errors
+ */
+ @SuppressWarnings("unchecked")
+ public static <T extends Expression> T parseExpression(final String expression) {
+ return (T) simplifiedParse(EXPRESSION, provider(expression));
+ }
+
+ /**
+ * Parses the Java annotation contained in a {@link String} and returns a
+ * {@link AnnotationExpr} that represents it.
+ *
+ * @param annotation {@link String} containing Java annotation
+ * @return AnnotationExpr representing the Java annotation
+ * @throws ParseProblemException if the source code has parser errors
+ */
+ public static AnnotationExpr parseAnnotation(final String annotation) {
+ return simplifiedParse(ANNOTATION, provider(annotation));
+ }
+
+ /**
+ * Parses the Java annotation body declaration(e.g fields or methods) contained in a
+ * {@link String} and returns a {@link BodyDeclaration} that represents it.
+ *
+ * @param body {@link String} containing Java body declaration
+ * @return BodyDeclaration representing the Java annotation
+ * @throws ParseProblemException if the source code has parser errors
+ */
+ public static BodyDeclaration<?> parseAnnotationBodyDeclaration(final String body) {
+ return simplifiedParse(ANNOTATION_BODY, provider(body));
+ }
+
+ /**
+ * Parses a Java class body declaration(e.g fields or methods) and returns a
+ * {@link BodyDeclaration} that represents it.
+ *
+ * @param body the body of a class
+ * @return BodyDeclaration representing the Java class body
+ * @throws ParseProblemException if the source code has parser errors
+ */
+ public static BodyDeclaration<?> parseClassBodyDeclaration(String body) {
+ return simplifiedParse(CLASS_BODY, provider(body));
+ }
+
+ /**
+ * Parses a Java interface body declaration(e.g fields or methods) and returns a
+ * {@link BodyDeclaration} that represents it.
+ *
+ * @param body the body of an interface
+ * @return BodyDeclaration representing the Java interface body
+ * @throws ParseProblemException if the source code has parser errors
+ */
+ public static BodyDeclaration parseInterfaceBodyDeclaration(String body) {
+ return simplifiedParse(INTERFACE_BODY, provider(body));
+ }
+
+ /**
+ * Parses a Java type name and returns a {@link ClassOrInterfaceType} that represents it.
+ *
+ * @param type the type name like a.b.c.X or Y
+ * @return ClassOrInterfaceType representing the type
+ * @throws ParseProblemException if the source code has parser errors
+ */
+ public static ClassOrInterfaceType parseClassOrInterfaceType(String type) {
+ return simplifiedParse(CLASS_OR_INTERFACE_TYPE, provider(type));
+ }
+
+ /**
+ * Parses a variable declaration expression and returns a {@link com.github.javaparser.ast.expr.VariableDeclarationExpr} that represents it.
+ *
+ * @param declaration a variable declaration like <code>int x=2;</code>
+ * @return VariableDeclarationExpr representing the type
+ * @throws ParseProblemException if the source code has parser errors
+ */
+ public static VariableDeclarationExpr parseVariableDeclarationExpr(String declaration) {
+ return simplifiedParse(VARIABLE_DECLARATION_EXPR, provider(declaration));
+ }
+}
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example5_expected.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example5_expected.java.txt
new file mode 100644
index 000000000..18a5420bf
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example5_expected.java.txt
@@ -0,0 +1,4 @@
+// This is my class, with my comment
+class A {
+ int a = null;
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example5_original.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example5_original.java.txt
new file mode 100644
index 000000000..2021255a9
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example5_original.java.txt
@@ -0,0 +1,4 @@
+// This is my class, with my comment
+class A {
+ int a = 10;
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example6_expected.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example6_expected.java.txt
new file mode 100644
index 000000000..91a79fe47
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example6_expected.java.txt
@@ -0,0 +1,4 @@
+// This is my class, with my comment
+class A {
+ int someOtherName = 10;
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example6_original.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example6_original.java.txt
new file mode 100644
index 000000000..2021255a9
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example6_original.java.txt
@@ -0,0 +1,4 @@
+// This is my class, with my comment
+class A {
+ int a = 10;
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example7_expected.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example7_expected.java.txt
new file mode 100644
index 000000000..ee17fd362
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example7_expected.java.txt
@@ -0,0 +1,4 @@
+// This is my class, with my comment
+class A {
+ int[] a = 10;
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example7_original.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example7_original.java.txt
new file mode 100644
index 000000000..2021255a9
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example7_original.java.txt
@@ -0,0 +1,4 @@
+// This is my class, with my comment
+class A {
+ int a = 10;
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example8_expected.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example8_expected.java.txt
new file mode 100644
index 000000000..b8b73509a
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example8_expected.java.txt
@@ -0,0 +1,4 @@
+// This is my class, with my comment
+class A {
+ int a = 10, b;
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example8_original.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example8_original.java.txt
new file mode 100644
index 000000000..2021255a9
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example8_original.java.txt
@@ -0,0 +1,4 @@
+// This is my class, with my comment
+class A {
+ int a = 10;
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example9_expected.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example9_expected.java.txt
new file mode 100644
index 000000000..e23818f83
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example9_expected.java.txt
@@ -0,0 +1,4 @@
+// This is my class, with my comment
+class A {
+ int a = 10, b[];
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example9_original.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example9_original.java.txt
new file mode 100644
index 000000000..2021255a9
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example9_original.java.txt
@@ -0,0 +1,4 @@
+// This is my class, with my comment
+class A {
+ int a = 10;
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param1_expected.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param1_expected.java.txt
new file mode 100644
index 000000000..867c4a134
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param1_expected.java.txt
@@ -0,0 +1,4 @@
+// This is my class, with my comment
+class A {
+ void foo(int p1) { }
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param1_original.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param1_original.java.txt
new file mode 100644
index 000000000..d90f55ebb
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param1_original.java.txt
@@ -0,0 +1,4 @@
+// This is my class, with my comment
+class A {
+ void foo() { }
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param2_expected.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param2_expected.java.txt
new file mode 100644
index 000000000..81a85e755
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param2_expected.java.txt
@@ -0,0 +1,4 @@
+// This is my class, with my comment
+class A {
+ void foo(int[] p1, char p2) { }
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param3_expected.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param3_expected.java.txt
new file mode 100644
index 000000000..88c866ac4
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param3_expected.java.txt
@@ -0,0 +1,4 @@
+// This is my class, with my comment
+class A {
+ void foo(char p2) { }
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param3_original.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param3_original.java.txt
new file mode 100644
index 000000000..a833bd9de
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param3_original.java.txt
@@ -0,0 +1,4 @@
+// This is my class, with my comment
+class A {
+ void foo(int p1, char p2) { }
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param4_expected.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param4_expected.java.txt
new file mode 100644
index 000000000..867c4a134
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param4_expected.java.txt
@@ -0,0 +1,4 @@
+// This is my class, with my comment
+class A {
+ void foo(int p1) { }
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param5_expected.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param5_expected.java.txt
new file mode 100644
index 000000000..f883e128e
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param5_expected.java.txt
@@ -0,0 +1,6 @@
+// This is my class, with my comment
+class A {
+ int foo(int p1, char p2) {
+ return p1;
+ }
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param5b_expected.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param5b_expected.java.txt
new file mode 100644
index 000000000..9e3a4fa4c
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/Example_param5b_expected.java.txt
@@ -0,0 +1,4 @@
+// This is my class, with my comment
+class A {
+ int foo(int p1, char p2) { }
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/MethodWithOneStatement.java.txt b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/MethodWithOneStatement.java.txt
new file mode 100644
index 000000000..a3db955a9
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/lexical_preservation_samples/MethodWithOneStatement.java.txt
@@ -0,0 +1,5 @@
+class A {
+ public void someMethod() {
+ String test = "";
+ }
+}
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/printer/JavaConcepts_prettyprinted b/javaparser-testing/src/test/resources/com/github/javaparser/printer/JavaConcepts_prettyprinted
new file mode 100644
index 000000000..c83d8e48f
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/printer/JavaConcepts_prettyprinted
@@ -0,0 +1,395 @@
+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<T extends List<int[]>, 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<String>[][] arrLS = (List<String>[][]) new List<?>[10][];
+
+ {
+ int z = 0, y = 0;
+ int a = (z) + y;
+ a = (+z) + y;
+ byte b = (byte) +y;
+ }
+
+ List<String> 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 <T, E> JavaConcepts(int x) {
+ this.arr[0] = x;
+ T val1 = null;
+ E val2 = null;
+ super.<T, E>check2(val1, val2);
+ boolean b = true, y = false;
+ abstract class X {
+
+ int i = 0;
+
+ public <D> 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 <T> JavaConcepts(String str) {
+ }
+
+ private class QWE extends JavaConcepts<List<int[]>, String> {
+
+ @Deprecated
+ final int z = 0;
+
+ int i = (int) -1;
+
+ public QWE(String... x) {
+ <String>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<? extends Number> x = new ArrayList<Integer>();
+ 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<T extends Integer & Serializable> implements XXX, Serializable {
+
+ public <ABC> A(Integer integer, ABC string) throws Exception, IOException {
+ }
+ }
+
+ private <Y> void x(Map<? extends X, ? super T> x) {
+ @Deprecated Comparator c = new Comparator() {
+
+ public int compare(Object o1, Object o2) {
+ try {
+ A<Integer> a = new <String> A<Integer>(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 <A, B> void check2(A val1, B val2) {
+ }
+}
+
+interface XXX extends Serializable, Cloneable {
+}
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/printer/PrettyPrintVisitor_prettyprinted b/javaparser-testing/src/test/resources/com/github/javaparser/printer/PrettyPrintVisitor_prettyprinted
new file mode 100644
index 000000000..90048cf50
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/printer/PrettyPrintVisitor_prettyprinted
@@ -0,0 +1,1353 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+package com.github.javaparser.printer;
+
+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.nodeTypes.NodeWithTypeArguments;
+import com.github.javaparser.ast.nodeTypes.NodeWithVariables;
+import com.github.javaparser.ast.stmt.*;
+import com.github.javaparser.ast.type.*;
+import com.github.javaparser.ast.visitor.VoidVisitor;
+import java.util.EnumSet;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.stream.Collectors;
+import static com.github.javaparser.utils.PositionUtils.sortByBeginPosition;
+import static com.github.javaparser.utils.Utils.isNullOrEmpty;
+
+/**
+ * Outputs the AST as formatted Java source code.
+ *
+ * @author Julio Vilmar Gesser
+ */
+public class PrettyPrintVisitor implements VoidVisitor<Void> {
+
+ protected final PrettyPrinterConfiguration configuration;
+
+ protected final SourcePrinter printer;
+
+ public PrettyPrintVisitor(PrettyPrinterConfiguration prettyPrinterConfiguration) {
+ configuration = prettyPrinterConfiguration;
+ printer = new SourcePrinter(configuration.getIndent());
+ }
+
+ public String getSource() {
+ return printer.getSource();
+ }
+
+ private void printModifiers(final EnumSet<Modifier> modifiers) {
+ if (modifiers.size() > 0) {
+ printer.print(modifiers.stream().map(Modifier::asString).collect(Collectors.joining(" ")) + " ");
+ }
+ }
+
+ private void printMembers(final NodeList<BodyDeclaration<?>> members, final Void arg) {
+ for (final BodyDeclaration<?> member : members) {
+ printer.println();
+ member.accept(this, arg);
+ printer.println();
+ }
+ }
+
+ private void printMemberAnnotations(final NodeList<AnnotationExpr> annotations, final Void arg) {
+ if (annotations.isEmpty()) {
+ return;
+ }
+ for (final AnnotationExpr a : annotations) {
+ a.accept(this, arg);
+ printer.println();
+ }
+ }
+
+ private void printAnnotations(final NodeList<AnnotationExpr> annotations, boolean prefixWithASpace, final Void arg) {
+ if (annotations.isEmpty()) {
+ return;
+ }
+ if (prefixWithASpace) {
+ printer.print(" ");
+ }
+ for (AnnotationExpr annotation : annotations) {
+ annotation.accept(this, arg);
+ printer.print(" ");
+ }
+ }
+
+ private void printTypeArgs(final NodeWithTypeArguments<?> nodeWithTypeArguments, final Void arg) {
+ NodeList<Type> typeArguments = nodeWithTypeArguments.getTypeArguments().orElse(null);
+ if (!isNullOrEmpty(typeArguments)) {
+ printer.print("<");
+ for (final Iterator<Type> i = typeArguments.iterator(); i.hasNext(); ) {
+ final Type t = i.next();
+ t.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ printer.print(">");
+ }
+ }
+
+ private void printTypeParameters(final NodeList<TypeParameter> args, final Void arg) {
+ if (!isNullOrEmpty(args)) {
+ printer.print("<");
+ for (final Iterator<TypeParameter> i = args.iterator(); i.hasNext(); ) {
+ final TypeParameter t = i.next();
+ t.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ printer.print(">");
+ }
+ }
+
+ private void printArguments(final NodeList<Expression> args, final Void arg) {
+ printer.print("(");
+ if (!isNullOrEmpty(args)) {
+ for (final Iterator<Expression> i = args.iterator(); i.hasNext(); ) {
+ final Expression e = i.next();
+ e.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ }
+ printer.print(")");
+ }
+
+ private void printJavaComment(final Comment javacomment, final Void arg) {
+ if (javacomment != null) {
+ javacomment.accept(this, arg);
+ }
+ }
+
+ @Override
+ public void visit(final CompilationUnit n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ if (n.getPackageDeclaration().isPresent()) {
+ n.getPackageDeclaration().get().accept(this, arg);
+ }
+ n.getImports().accept(this, arg);
+ if (!n.getImports().isEmpty()) {
+ printer.println();
+ }
+ for (final Iterator<TypeDeclaration<?>> i = n.getTypes().iterator(); i.hasNext(); ) {
+ i.next().accept(this, arg);
+ printer.println();
+ if (i.hasNext()) {
+ printer.println();
+ }
+ }
+ printOrphanCommentsEnding(n);
+ }
+
+ @Override
+ public void visit(final PackageDeclaration n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printAnnotations(n.getAnnotations(), false, arg);
+ printer.print("package ");
+ n.getName().accept(this, arg);
+ printer.println(";");
+ printer.println();
+ printOrphanCommentsEnding(n);
+ }
+
+ @Override
+ public void visit(final NameExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ n.getName().accept(this, arg);
+ printOrphanCommentsEnding(n);
+ }
+
+ @Override
+ public void visit(final Name n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ if (n.getQualifier().isPresent()) {
+ n.getQualifier().get().accept(this, arg);
+ printer.print(".");
+ }
+ printer.print(n.getIdentifier());
+ printOrphanCommentsEnding(n);
+ }
+
+ @Override
+ public void visit(SimpleName n, Void arg) {
+ printer.print(n.getIdentifier());
+ }
+
+ @Override
+ public void visit(final ClassOrInterfaceDeclaration n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printMemberAnnotations(n.getAnnotations(), arg);
+ printModifiers(n.getModifiers());
+ if (n.isInterface()) {
+ printer.print("interface ");
+ } else {
+ printer.print("class ");
+ }
+ n.getName().accept(this, arg);
+ printTypeParameters(n.getTypeParameters(), arg);
+ if (!n.getExtendedTypes().isEmpty()) {
+ printer.print(" extends ");
+ for (final Iterator<ClassOrInterfaceType> i = n.getExtendedTypes().iterator(); i.hasNext(); ) {
+ final ClassOrInterfaceType c = i.next();
+ c.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ }
+ if (!n.getImplementedTypes().isEmpty()) {
+ printer.print(" implements ");
+ for (final Iterator<ClassOrInterfaceType> i = n.getImplementedTypes().iterator(); i.hasNext(); ) {
+ final ClassOrInterfaceType c = i.next();
+ c.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ }
+ printer.println(" {");
+ printer.indent();
+ if (!isNullOrEmpty(n.getMembers())) {
+ printMembers(n.getMembers(), arg);
+ }
+ printOrphanCommentsEnding(n);
+ printer.unindent();
+ printer.print("}");
+ }
+
+ @Override
+ public void visit(final JavadocComment n, final Void arg) {
+ printer.print("/**");
+ printer.print(n.getContent());
+ printer.println("*/");
+ }
+
+ @Override
+ public void visit(final ClassOrInterfaceType n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ if (n.getScope().isPresent()) {
+ n.getScope().get().accept(this, arg);
+ printer.print(".");
+ }
+ for (AnnotationExpr ae : n.getAnnotations()) {
+ ae.accept(this, arg);
+ printer.print(" ");
+ }
+ n.getName().accept(this, arg);
+ if (n.isUsingDiamondOperator()) {
+ printer.print("<>");
+ } else {
+ printTypeArgs(n, arg);
+ }
+ }
+
+ @Override
+ public void visit(final TypeParameter n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ for (AnnotationExpr ann : n.getAnnotations()) {
+ ann.accept(this, arg);
+ printer.print(" ");
+ }
+ n.getName().accept(this, arg);
+ if (!isNullOrEmpty(n.getTypeBound())) {
+ printer.print(" extends ");
+ for (final Iterator<ClassOrInterfaceType> i = n.getTypeBound().iterator(); i.hasNext(); ) {
+ final ClassOrInterfaceType c = i.next();
+ c.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(" & ");
+ }
+ }
+ }
+ }
+
+ @Override
+ public void visit(final PrimitiveType n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printAnnotations(n.getAnnotations(), true, arg);
+ printer.print(n.getType().asString());
+ }
+
+ @Override
+ public void visit(final ArrayType n, final Void arg) {
+ final List<ArrayType> arrayTypeBuffer = new LinkedList<>();
+ Type type = n;
+ while (type instanceof ArrayType) {
+ final ArrayType arrayType = (ArrayType) type;
+ arrayTypeBuffer.add(arrayType);
+ type = arrayType.getComponentType();
+ }
+ type.accept(this, arg);
+ for (ArrayType arrayType : arrayTypeBuffer) {
+ printAnnotations(arrayType.getAnnotations(), true, arg);
+ printer.print("[]");
+ }
+ }
+
+ @Override
+ public void visit(final ArrayCreationLevel n, final Void arg) {
+ printAnnotations(n.getAnnotations(), true, arg);
+ printer.print("[");
+ if (n.getDimension().isPresent()) {
+ n.getDimension().get().accept(this, arg);
+ }
+ printer.print("]");
+ }
+
+ @Override
+ public void visit(final IntersectionType n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printAnnotations(n.getAnnotations(), false, arg);
+ boolean isFirst = true;
+ for (ReferenceType element : n.getElements()) {
+ element.accept(this, arg);
+ if (isFirst) {
+ isFirst = false;
+ } else {
+ printer.print(" & ");
+ }
+ }
+ }
+
+ @Override
+ public void visit(final UnionType n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printAnnotations(n.getAnnotations(), true, arg);
+ boolean isFirst = true;
+ for (ReferenceType element : n.getElements()) {
+ if (isFirst) {
+ isFirst = false;
+ } else {
+ printer.print(" | ");
+ }
+ element.accept(this, arg);
+ }
+ }
+
+ @Override
+ public void visit(final WildcardType n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printAnnotations(n.getAnnotations(), false, arg);
+ printer.print("?");
+ if (n.getExtendedTypes().isPresent()) {
+ printer.print(" extends ");
+ n.getExtendedTypes().get().accept(this, arg);
+ }
+ if (n.getSuperTypes().isPresent()) {
+ printer.print(" super ");
+ n.getSuperTypes().get().accept(this, arg);
+ }
+ }
+
+ @Override
+ public void visit(final UnknownType n, final Void arg) {
+ // Nothing to print
+ }
+
+ @Override
+ public void visit(final FieldDeclaration n, final Void arg) {
+ printOrphanCommentsBeforeThisChildNode(n);
+ printJavaComment(n.getComment(), arg);
+ printMemberAnnotations(n.getAnnotations(), arg);
+ printModifiers(n.getModifiers());
+ if (!n.getVariables().isEmpty()) {
+ n.getMaximumCommonType().accept(this, arg);
+ }
+ printer.print(" ");
+ for (final Iterator<VariableDeclarator> i = n.getVariables().iterator(); i.hasNext(); ) {
+ final VariableDeclarator var = i.next();
+ var.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ printer.print(";");
+ }
+
+ @Override
+ public void visit(final VariableDeclarator n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ n.getName().accept(this, arg);
+ Type commonType = n.getAncestorOfType(NodeWithVariables.class).get().getMaximumCommonType();
+ Type type = n.getType();
+ ArrayType arrayType = null;
+ for (int i = commonType.getArrayLevel(); i < type.getArrayLevel(); i++) {
+ if (arrayType == null) {
+ arrayType = (ArrayType) type;
+ } else {
+ arrayType = (ArrayType) arrayType.getComponentType();
+ }
+ printAnnotations(arrayType.getAnnotations(), true, arg);
+ printer.print("[]");
+ }
+ if (n.getInitializer().isPresent()) {
+ printer.print(" = ");
+ n.getInitializer().get().accept(this, arg);
+ }
+ }
+
+ @Override
+ public void visit(final ArrayInitializerExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("{");
+ if (!isNullOrEmpty(n.getValues())) {
+ printer.print(" ");
+ for (final Iterator<Expression> i = n.getValues().iterator(); i.hasNext(); ) {
+ final Expression expr = i.next();
+ expr.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ printer.print(" ");
+ }
+ printer.print("}");
+ }
+
+ @Override
+ public void visit(final VoidType n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printAnnotations(n.getAnnotations(), false, arg);
+ printer.print("void");
+ }
+
+ @Override
+ public void visit(final ArrayAccessExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ n.getName().accept(this, arg);
+ printer.print("[");
+ n.getIndex().accept(this, arg);
+ printer.print("]");
+ }
+
+ @Override
+ public void visit(final ArrayCreationExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("new ");
+ n.getElementType().accept(this, arg);
+ for (ArrayCreationLevel level : n.getLevels()) {
+ level.accept(this, arg);
+ }
+ if (n.getInitializer().isPresent()) {
+ printer.print(" ");
+ n.getInitializer().get().accept(this, arg);
+ }
+ }
+
+ @Override
+ public void visit(final AssignExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ n.getTarget().accept(this, arg);
+ printer.print(" ");
+ printer.print(n.getOperator().asString());
+ printer.print(" ");
+ n.getValue().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final BinaryExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ n.getLeft().accept(this, arg);
+ printer.print(" ");
+ printer.print(n.getOperator().asString());
+ printer.print(" ");
+ n.getRight().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final CastExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("(");
+ n.getType().accept(this, arg);
+ printer.print(") ");
+ n.getExpression().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final ClassExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ n.getType().accept(this, arg);
+ printer.print(".class");
+ }
+
+ @Override
+ public void visit(final ConditionalExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ n.getCondition().accept(this, arg);
+ printer.print(" ? ");
+ n.getThenExpr().accept(this, arg);
+ printer.print(" : ");
+ n.getElseExpr().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final EnclosedExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("(");
+ if (n.getInner().isPresent()) {
+ n.getInner().get().accept(this, arg);
+ }
+ printer.print(")");
+ }
+
+ @Override
+ public void visit(final FieldAccessExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ if (n.getScope().isPresent())
+ n.getScope().get().accept(this, arg);
+ printer.print(".");
+ n.getName().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final InstanceOfExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ n.getExpression().accept(this, arg);
+ printer.print(" instanceof ");
+ n.getType().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final CharLiteralExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("'");
+ printer.print(n.getValue());
+ printer.print("'");
+ }
+
+ @Override
+ public void visit(final DoubleLiteralExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print(n.getValue());
+ }
+
+ @Override
+ public void visit(final IntegerLiteralExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print(n.getValue());
+ }
+
+ @Override
+ public void visit(final LongLiteralExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print(n.getValue());
+ }
+
+ @Override
+ public void visit(final StringLiteralExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("\"");
+ printer.print(n.getValue());
+ printer.print("\"");
+ }
+
+ @Override
+ public void visit(final BooleanLiteralExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print(String.valueOf(n.getValue()));
+ }
+
+ @Override
+ public void visit(final NullLiteralExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("null");
+ }
+
+ @Override
+ public void visit(final ThisExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ if (n.getClassExpr().isPresent()) {
+ n.getClassExpr().get().accept(this, arg);
+ printer.print(".");
+ }
+ printer.print("this");
+ }
+
+ @Override
+ public void visit(final SuperExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ if (n.getClassExpr().isPresent()) {
+ n.getClassExpr().get().accept(this, arg);
+ printer.print(".");
+ }
+ printer.print("super");
+ }
+
+ @Override
+ public void visit(final MethodCallExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ if (n.getScope().isPresent()) {
+ n.getScope().get().accept(this, arg);
+ printer.print(".");
+ }
+ printTypeArgs(n, arg);
+ n.getName().accept(this, arg);
+ printArguments(n.getArguments(), arg);
+ }
+
+ @Override
+ public void visit(final ObjectCreationExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ if (n.getScope().isPresent()) {
+ n.getScope().get().accept(this, arg);
+ printer.print(".");
+ }
+ printer.print("new ");
+ printTypeArgs(n, arg);
+ if (!isNullOrEmpty(n.getTypeArguments().orElse(null))) {
+ printer.print(" ");
+ }
+ n.getType().accept(this, arg);
+ printArguments(n.getArguments(), arg);
+ if (n.getAnonymousClassBody().isPresent()) {
+ printer.println(" {");
+ printer.indent();
+ printMembers(n.getAnonymousClassBody().get(), arg);
+ printer.unindent();
+ printer.print("}");
+ }
+ }
+
+ @Override
+ public void visit(final UnaryExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ if (n.getOperator().isPrefix()) {
+ printer.print(n.getOperator().asString());
+ }
+ n.getExpression().accept(this, arg);
+ if (n.getOperator().isPostfix()) {
+ printer.print(n.getOperator().asString());
+ }
+ }
+
+ @Override
+ public void visit(final ConstructorDeclaration n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printMemberAnnotations(n.getAnnotations(), arg);
+ printModifiers(n.getModifiers());
+ printTypeParameters(n.getTypeParameters(), arg);
+ if (n.isGeneric()) {
+ printer.print(" ");
+ }
+ n.getName().accept(this, arg);
+ printer.print("(");
+ if (!n.getParameters().isEmpty()) {
+ for (final Iterator<Parameter> i = n.getParameters().iterator(); i.hasNext(); ) {
+ final Parameter p = i.next();
+ p.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ }
+ printer.print(")");
+ if (!isNullOrEmpty(n.getThrownExceptions())) {
+ printer.print(" throws ");
+ for (final Iterator<ReferenceType> i = n.getThrownExceptions().iterator(); i.hasNext(); ) {
+ final ReferenceType name = i.next();
+ name.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ }
+ printer.print(" ");
+ n.getBody().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final MethodDeclaration n, final Void arg) {
+ printOrphanCommentsBeforeThisChildNode(n);
+ printJavaComment(n.getComment(), arg);
+ printMemberAnnotations(n.getAnnotations(), arg);
+ printModifiers(n.getModifiers());
+ if (n.isDefault()) {
+ printer.print("default ");
+ }
+ printTypeParameters(n.getTypeParameters(), arg);
+ if (!isNullOrEmpty(n.getTypeParameters())) {
+ printer.print(" ");
+ }
+ n.getType().accept(this, arg);
+ printer.print(" ");
+ n.getName().accept(this, arg);
+ printer.print("(");
+ if (!isNullOrEmpty(n.getParameters())) {
+ for (final Iterator<Parameter> i = n.getParameters().iterator(); i.hasNext(); ) {
+ final Parameter p = i.next();
+ p.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ }
+ printer.print(")");
+ if (!isNullOrEmpty(n.getThrownExceptions())) {
+ printer.print(" throws ");
+ for (final Iterator<ReferenceType> i = n.getThrownExceptions().iterator(); i.hasNext(); ) {
+ final ReferenceType name = i.next();
+ name.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ }
+ if (!n.getBody().isPresent()) {
+ printer.print(";");
+ } else {
+ printer.print(" ");
+ n.getBody().get().accept(this, arg);
+ }
+ }
+
+ @Override
+ public void visit(final Parameter n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printAnnotations(n.getAnnotations(), false, arg);
+ printModifiers(n.getModifiers());
+ if (n.getType() != null) {
+ n.getType().accept(this, arg);
+ }
+ if (n.isVarArgs()) {
+ printer.print("...");
+ }
+ printer.print(" ");
+ n.getName().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final ExplicitConstructorInvocationStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ if (n.isThis()) {
+ printTypeArgs(n, arg);
+ printer.print("this");
+ } else {
+ if (n.getExpression().isPresent()) {
+ n.getExpression().get().accept(this, arg);
+ printer.print(".");
+ }
+ printTypeArgs(n, arg);
+ printer.print("super");
+ }
+ printArguments(n.getArguments(), arg);
+ printer.print(";");
+ }
+
+ @Override
+ public void visit(final VariableDeclarationExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printAnnotations(n.getAnnotations(), false, arg);
+ printModifiers(n.getModifiers());
+ if (!n.getVariables().isEmpty()) {
+ n.getMaximumCommonType().accept(this, arg);
+ }
+ printer.print(" ");
+ for (final Iterator<VariableDeclarator> i = n.getVariables().iterator(); i.hasNext(); ) {
+ final VariableDeclarator v = i.next();
+ v.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ }
+
+ @Override
+ public void visit(final LocalClassDeclarationStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ n.getClassDeclaration().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final AssertStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("assert ");
+ n.getCheck().accept(this, arg);
+ if (n.getMessage().isPresent()) {
+ printer.print(" : ");
+ n.getMessage().get().accept(this, arg);
+ }
+ printer.print(";");
+ }
+
+ @Override
+ public void visit(final BlockStmt n, final Void arg) {
+ printOrphanCommentsBeforeThisChildNode(n);
+ printJavaComment(n.getComment(), arg);
+ printer.println("{");
+ if (n.getStatements() != null) {
+ printer.indent();
+ for (final Statement s : n.getStatements()) {
+ s.accept(this, arg);
+ printer.println();
+ }
+ printer.unindent();
+ }
+ printOrphanCommentsEnding(n);
+ printer.print("}");
+ }
+
+ @Override
+ public void visit(final LabeledStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ n.getLabel().accept(this, arg);
+ printer.print(": ");
+ n.getStatement().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final EmptyStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print(";");
+ }
+
+ @Override
+ public void visit(final ExpressionStmt n, final Void arg) {
+ printOrphanCommentsBeforeThisChildNode(n);
+ printJavaComment(n.getComment(), arg);
+ n.getExpression().accept(this, arg);
+ printer.print(";");
+ }
+
+ @Override
+ public void visit(final SwitchStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("switch(");
+ n.getSelector().accept(this, arg);
+ printer.println(") {");
+ if (n.getEntries() != null) {
+ printer.indent();
+ for (final SwitchEntryStmt e : n.getEntries()) {
+ e.accept(this, arg);
+ }
+ printer.unindent();
+ }
+ printer.print("}");
+ }
+
+ @Override
+ public void visit(final SwitchEntryStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ if (n.getLabel().isPresent()) {
+ printer.print("case ");
+ n.getLabel().get().accept(this, arg);
+ printer.print(":");
+ } else {
+ printer.print("default:");
+ }
+ printer.println();
+ printer.indent();
+ if (n.getStatements() != null) {
+ for (final Statement s : n.getStatements()) {
+ s.accept(this, arg);
+ printer.println();
+ }
+ }
+ printer.unindent();
+ }
+
+ @Override
+ public void visit(final BreakStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("break");
+ n.getLabel().ifPresent( l -> printer.print(" ").print(l.getIdentifier()));
+ printer.print(";");
+ }
+
+ @Override
+ public void visit(final ReturnStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("return");
+ if (n.getExpression().isPresent()) {
+ printer.print(" ");
+ n.getExpression().get().accept(this, arg);
+ }
+ printer.print(";");
+ }
+
+ @Override
+ public void visit(final EnumDeclaration n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printMemberAnnotations(n.getAnnotations(), arg);
+ printModifiers(n.getModifiers());
+ printer.print("enum ");
+ n.getName().accept(this, arg);
+ if (!n.getImplementedTypes().isEmpty()) {
+ printer.print(" implements ");
+ for (final Iterator<ClassOrInterfaceType> i = n.getImplementedTypes().iterator(); i.hasNext(); ) {
+ final ClassOrInterfaceType c = i.next();
+ c.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ }
+ printer.println(" {");
+ printer.indent();
+ if (n.getEntries() != null) {
+ printer.println();
+ for (final Iterator<EnumConstantDeclaration> i = n.getEntries().iterator(); i.hasNext(); ) {
+ final EnumConstantDeclaration e = i.next();
+ e.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ }
+ if (!n.getMembers().isEmpty()) {
+ printer.println(";");
+ printMembers(n.getMembers(), arg);
+ } else {
+ if (!n.getEntries().isEmpty()) {
+ printer.println();
+ }
+ }
+ printer.unindent();
+ printer.print("}");
+ }
+
+ @Override
+ public void visit(final EnumConstantDeclaration n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printMemberAnnotations(n.getAnnotations(), arg);
+ n.getName().accept(this, arg);
+ if (!n.getArguments().isEmpty()) {
+ printArguments(n.getArguments(), arg);
+ }
+ if (!n.getClassBody().isEmpty()) {
+ printer.println(" {");
+ printer.indent();
+ printMembers(n.getClassBody(), arg);
+ printer.unindent();
+ printer.println("}");
+ }
+ }
+
+ @Override
+ public void visit(final EmptyMemberDeclaration n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print(";");
+ }
+
+ @Override
+ public void visit(final InitializerDeclaration n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ if (n.isStatic()) {
+ printer.print("static ");
+ }
+ n.getBody().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final IfStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("if (");
+ n.getCondition().accept(this, arg);
+ final boolean thenBlock = n.getThenStmt() instanceof BlockStmt;
+ if (// block statement should start on the same line
+ thenBlock)
+ printer.print(") ");
+ else {
+ printer.println(")");
+ printer.indent();
+ }
+ n.getThenStmt().accept(this, arg);
+ if (!thenBlock)
+ printer.unindent();
+ if (n.getElseStmt().isPresent()) {
+ if (thenBlock)
+ printer.print(" ");
+ else
+ printer.println();
+ final boolean elseIf = n.getElseStmt().orElse(null) instanceof IfStmt;
+ final boolean elseBlock = n.getElseStmt().orElse(null) instanceof BlockStmt;
+ if (// put chained if and start of block statement on a same level
+ elseIf || elseBlock)
+ printer.print("else ");
+ else {
+ printer.println("else");
+ printer.indent();
+ }
+ if (n.getElseStmt().isPresent())
+ n.getElseStmt().get().accept(this, arg);
+ if (!(elseIf || elseBlock))
+ printer.unindent();
+ }
+ }
+
+ @Override
+ public void visit(final WhileStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("while (");
+ n.getCondition().accept(this, arg);
+ printer.print(") ");
+ n.getBody().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final ContinueStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("continue");
+ n.getLabel().ifPresent( l -> printer.print(" ").print(l.getIdentifier()));
+ printer.print(";");
+ }
+
+ @Override
+ public void visit(final DoStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("do ");
+ n.getBody().accept(this, arg);
+ printer.print(" while (");
+ n.getCondition().accept(this, arg);
+ printer.print(");");
+ }
+
+ @Override
+ public void visit(final ForeachStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("for (");
+ n.getVariable().accept(this, arg);
+ printer.print(" : ");
+ n.getIterable().accept(this, arg);
+ printer.print(") ");
+ n.getBody().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final ForStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("for (");
+ if (n.getInitialization() != null) {
+ for (final Iterator<Expression> i = n.getInitialization().iterator(); i.hasNext(); ) {
+ final Expression e = i.next();
+ e.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ }
+ printer.print("; ");
+ if (n.getCompare().isPresent()) {
+ n.getCompare().get().accept(this, arg);
+ }
+ printer.print("; ");
+ if (n.getUpdate() != null) {
+ for (final Iterator<Expression> i = n.getUpdate().iterator(); i.hasNext(); ) {
+ final Expression e = i.next();
+ e.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ }
+ printer.print(") ");
+ n.getBody().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final ThrowStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("throw ");
+ n.getExpression().accept(this, arg);
+ printer.print(";");
+ }
+
+ @Override
+ public void visit(final SynchronizedStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("synchronized (");
+ n.getExpression().accept(this, arg);
+ printer.print(") ");
+ n.getBody().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final TryStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("try ");
+ if (!n.getResources().isEmpty()) {
+ printer.print("(");
+ Iterator<VariableDeclarationExpr> resources = n.getResources().iterator();
+ boolean first = true;
+ while (resources.hasNext()) {
+ visit(resources.next(), arg);
+ if (resources.hasNext()) {
+ printer.print(";");
+ printer.println();
+ if (first) {
+ printer.indent();
+ }
+ }
+ first = false;
+ }
+ if (n.getResources().size() > 1) {
+ printer.unindent();
+ }
+ printer.print(") ");
+ }
+ if (n.getTryBlock().isPresent()) {
+ n.getTryBlock().get().accept(this, arg);
+ }
+ for (final CatchClause c : n.getCatchClauses()) {
+ c.accept(this, arg);
+ }
+ if (n.getFinallyBlock().isPresent()) {
+ printer.print(" finally ");
+ n.getFinallyBlock().get().accept(this, arg);
+ }
+ }
+
+ @Override
+ public void visit(final CatchClause n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print(" catch (");
+ n.getParameter().accept(this, arg);
+ printer.print(") ");
+ n.getBody().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final AnnotationDeclaration n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printMemberAnnotations(n.getAnnotations(), arg);
+ printModifiers(n.getModifiers());
+ printer.print("@interface ");
+ n.getName().accept(this, arg);
+ printer.println(" {");
+ printer.indent();
+ if (n.getMembers() != null) {
+ printMembers(n.getMembers(), arg);
+ }
+ printer.unindent();
+ printer.print("}");
+ }
+
+ @Override
+ public void visit(final AnnotationMemberDeclaration n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printMemberAnnotations(n.getAnnotations(), arg);
+ printModifiers(n.getModifiers());
+ n.getType().accept(this, arg);
+ printer.print(" ");
+ n.getName().accept(this, arg);
+ printer.print("()");
+ if (n.getDefaultValue().isPresent()) {
+ printer.print(" default ");
+ n.getDefaultValue().get().accept(this, arg);
+ }
+ printer.print(";");
+ }
+
+ @Override
+ public void visit(final MarkerAnnotationExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("@");
+ n.getName().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final SingleMemberAnnotationExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("@");
+ n.getName().accept(this, arg);
+ printer.print("(");
+ n.getMemberValue().accept(this, arg);
+ printer.print(")");
+ }
+
+ @Override
+ public void visit(final NormalAnnotationExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("@");
+ n.getName().accept(this, arg);
+ printer.print("(");
+ if (n.getPairs() != null) {
+ for (final Iterator<MemberValuePair> i = n.getPairs().iterator(); i.hasNext(); ) {
+ final MemberValuePair m = i.next();
+ m.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ }
+ printer.print(")");
+ }
+
+ @Override
+ public void visit(final MemberValuePair n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ n.getName().accept(this, arg);
+ printer.print(" = ");
+ n.getValue().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final LineComment n, final Void arg) {
+ if (!configuration.isPrintComments()) {
+ return;
+ }
+ printer.print("//");
+ String tmp = n.getContent();
+ tmp = tmp.replace('\r', ' ');
+ tmp = tmp.replace('\n', ' ');
+ printer.println(tmp);
+ }
+
+ @Override
+ public void visit(final BlockComment n, final Void arg) {
+ if (!configuration.isPrintComments()) {
+ return;
+ }
+ printer.print("/*").print(n.getContent()).println("*/");
+ }
+
+ @Override
+ public void visit(LambdaExpr n, Void arg) {
+ printJavaComment(n.getComment(), arg);
+ final NodeList<Parameter> parameters = n.getParameters();
+ final boolean printPar = n.isEnclosingParameters();
+ if (printPar) {
+ printer.print("(");
+ }
+ for (Iterator<Parameter> i = parameters.iterator(); i.hasNext(); ) {
+ Parameter p = i.next();
+ p.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ if (printPar) {
+ printer.print(")");
+ }
+ printer.print(" -> ");
+ final Statement body = n.getBody();
+ if (body instanceof ExpressionStmt) {
+ // Print the expression directly
+ ((ExpressionStmt) body).getExpression().accept(this, arg);
+ } else {
+ body.accept(this, arg);
+ }
+ }
+
+ @Override
+ public void visit(MethodReferenceExpr n, Void arg) {
+ printJavaComment(n.getComment(), arg);
+ Expression scope = n.getScope();
+ String identifier = n.getIdentifier();
+ if (scope != null) {
+ n.getScope().accept(this, arg);
+ }
+ printer.print("::");
+ printTypeArgs(n, arg);
+ if (identifier != null) {
+ printer.print(identifier);
+ }
+ }
+
+ @Override
+ public void visit(TypeExpr n, Void arg) {
+ printJavaComment(n.getComment(), arg);
+ if (n.getType() != null) {
+ n.getType().accept(this, arg);
+ }
+ }
+
+ @Override
+ public void visit(NodeList n, Void arg) {
+ for (Object node : n) {
+ ((Node) node).accept(this, arg);
+ }
+ }
+
+ @Override
+ public void visit(final ImportDeclaration n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("import ");
+ if (n.isStatic()) {
+ printer.print("static ");
+ }
+ n.getName().accept(this, arg);
+ if (n.isAsterisk()) {
+ printer.print(".*");
+ }
+ printer.println(";");
+ printOrphanCommentsEnding(n);
+ }
+
+ private void printOrphanCommentsBeforeThisChildNode(final Node node) {
+ if (node instanceof Comment)
+ return;
+ Node parent = node.getParentNode().orElse(null);
+ if (parent == null)
+ return;
+ List<Node> everything = new LinkedList<>();
+ everything.addAll(parent.getChildNodes());
+ sortByBeginPosition(everything);
+ int positionOfTheChild = -1;
+ for (int i = 0; i < everything.size(); i++) {
+ if (everything.get(i) == node)
+ positionOfTheChild = i;
+ }
+ if (positionOfTheChild == -1) {
+ throw new AssertionError("I am not a child of my parent.");
+ }
+ int positionOfPreviousChild = -1;
+ for (int i = positionOfTheChild - 1; i >= 0 && positionOfPreviousChild == -1; i--) {
+ if (!(everything.get(i) instanceof Comment))
+ positionOfPreviousChild = i;
+ }
+ for (int i = positionOfPreviousChild + 1; i < positionOfTheChild; i++) {
+ Node nodeToPrint = everything.get(i);
+ if (!(nodeToPrint instanceof Comment))
+ throw new RuntimeException("Expected comment, instead " + nodeToPrint.getClass() + ". Position of previous child: " + positionOfPreviousChild + ", position of child " + positionOfTheChild);
+ nodeToPrint.accept(this, null);
+ }
+ }
+
+ private void printOrphanCommentsEnding(final Node node) {
+ List<Node> everything = new LinkedList<>();
+ everything.addAll(node.getChildNodes());
+ sortByBeginPosition(everything);
+ if (everything.isEmpty()) {
+ return;
+ }
+ int commentsAtEnd = 0;
+ boolean findingComments = true;
+ while (findingComments && commentsAtEnd < everything.size()) {
+ Node last = everything.get(everything.size() - 1 - commentsAtEnd);
+ findingComments = (last instanceof Comment);
+ if (findingComments) {
+ commentsAtEnd++;
+ }
+ }
+ for (int i = 0; i < commentsAtEnd; i++) {
+ everything.get(everything.size() - commentsAtEnd + i).accept(this, null);
+ }
+ }
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/source_zip/test.txt b/javaparser-testing/src/test/resources/com/github/javaparser/source_zip/test.txt
new file mode 100644
index 000000000..487e034d6
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/source_zip/test.txt
@@ -0,0 +1 @@
+foo bar qux \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/source_zip/test.zip b/javaparser-testing/src/test/resources/com/github/javaparser/source_zip/test.zip
new file mode 100644
index 000000000..dd9b18a34
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/source_zip/test.zip
Binary files differ
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/storage/A.java b/javaparser-testing/src/test/resources/com/github/javaparser/storage/A.java
new file mode 100644
index 000000000..d0fc413a3
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/storage/A.java
@@ -0,0 +1 @@
+package com.blablabla.root; \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/storage/B.java b/javaparser-testing/src/test/resources/com/github/javaparser/storage/B.java
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/storage/B.java
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/storage/PrimaryType.java b/javaparser-testing/src/test/resources/com/github/javaparser/storage/PrimaryType.java
new file mode 100644
index 000000000..bac9587fb
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/storage/PrimaryType.java
@@ -0,0 +1,5 @@
+package com.github.javaparser.storage;
+
+public class PrimaryType {
+
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/storage/PrimaryType2.java b/javaparser-testing/src/test/resources/com/github/javaparser/storage/PrimaryType2.java
new file mode 100644
index 000000000..81bcf0b1a
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/storage/PrimaryType2.java
@@ -0,0 +1 @@
+package com.github.javaparser.storage;
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/storage/Z.java b/javaparser-testing/src/test/resources/com/github/javaparser/storage/Z.java
new file mode 100644
index 000000000..0bf8867dd
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/storage/Z.java
@@ -0,0 +1 @@
+package com.github.javaparser.storage; \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/utils/.abc/bla.java b/javaparser-testing/src/test/resources/com/github/javaparser/utils/.abc/bla.java
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/utils/.abc/bla.java
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/utils/Bla.java b/javaparser-testing/src/test/resources/com/github/javaparser/utils/Bla.java
new file mode 100644
index 000000000..21adb8808
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/utils/Bla.java
@@ -0,0 +1,3 @@
+class X {
+
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/utils/module-info.java b/javaparser-testing/src/test/resources/com/github/javaparser/utils/module-info.java
new file mode 100644
index 000000000..2592490c4
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/utils/module-info.java
@@ -0,0 +1,2 @@
+module M.N {
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/utils/source/root/Y.java b/javaparser-testing/src/test/resources/com/github/javaparser/utils/source/root/Y.java
new file mode 100644
index 000000000..fb9b0d7b0
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/utils/source/root/Y.java
@@ -0,0 +1,3 @@
+class Y {
+
+} \ No newline at end of file
diff --git a/javaparser-testing/src/test/resources/com/github/javaparser/wiki_samples/TestFile.java b/javaparser-testing/src/test/resources/com/github/javaparser/wiki_samples/TestFile.java
new file mode 100644
index 000000000..77dcb5aff
--- /dev/null
+++ b/javaparser-testing/src/test/resources/com/github/javaparser/wiki_samples/TestFile.java
@@ -0,0 +1,15 @@
+package com.github.javaparser.wiki_samples;
+
+public class TestFile {
+ public void foo(int e) {
+ int a = 20;
+ }
+
+ public void abc() {
+
+ }
+
+ public int def() {
+ return 10;
+ }
+}
diff --git a/javaparser-testing/src/test/test_sourcecode/com/github/javaparser/printer/JavaConcepts.java b/javaparser-testing/src/test/test_sourcecode/com/github/javaparser/printer/JavaConcepts.java
new file mode 100644
index 000000000..2a53e5f5b
--- /dev/null
+++ b/javaparser-testing/src/test/test_sourcecode/com/github/javaparser/printer/JavaConcepts.java
@@ -0,0 +1,393 @@
+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<T extends List<int[]>, 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<String>[][] arrLS = (List<String>[][]) new List<?>[10][];
+
+ {
+ int z = 0, y = 0;
+ int a = (z) + y;
+ a = (+z) + y;
+ byte b = (byte) +y;
+ }
+
+ List<String> 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 <T, E> JavaConcepts(int x) {
+ this.arr[0] = x;
+ T val1 = null;
+ E val2 = null;
+ super.<T, E>check2(val1, val2);
+ boolean b = true, y = false;
+ abstract class X {
+
+ int i = 0;
+
+ public <D> 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 <T> JavaConcepts(String str) {
+ }
+
+ private class QWE extends JavaConcepts<List<int[]>, String> {
+
+ @Deprecated
+ final int z = 0;
+
+ int i = (int) -1;
+
+ public QWE(String... x) {
+ <String>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<? extends Number> x = new ArrayList<Integer>();
+ 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<T extends Integer & Serializable> implements XXX, Serializable {
+
+ public <ABC> A(Integer integer, ABC string) throws Exception, IOException {
+ }
+ }
+
+ private <Y> void x(Map<? extends X, ? super T> x) {
+ @Deprecated Comparator c = new Comparator() {
+
+ public int compare(Object o1, Object o2) {
+ try {
+ A<Integer> a = new <String>A<Integer>(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 <A, B> void check2(A val1, B val2) {
+ }
+}
+
+interface XXX extends Serializable, Cloneable {
+}
diff --git a/javaparser-testing/src/test/test_sourcecode/com/github/javaparser/printer/PrettyPrintVisitor.java b/javaparser-testing/src/test/test_sourcecode/com/github/javaparser/printer/PrettyPrintVisitor.java
new file mode 100644
index 000000000..4a4c9f07c
--- /dev/null
+++ b/javaparser-testing/src/test/test_sourcecode/com/github/javaparser/printer/PrettyPrintVisitor.java
@@ -0,0 +1,1413 @@
+/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.printer;
+
+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.nodeTypes.NodeWithTypeArguments;
+import com.github.javaparser.ast.nodeTypes.NodeWithVariables;
+import com.github.javaparser.ast.stmt.*;
+import com.github.javaparser.ast.type.*;
+import com.github.javaparser.ast.visitor.VoidVisitor;
+
+import java.util.EnumSet;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import static com.github.javaparser.utils.PositionUtils.sortByBeginPosition;
+import static com.github.javaparser.utils.Utils.isNullOrEmpty;
+
+/**
+ * Outputs the AST as formatted Java source code.
+ *
+ * @author Julio Vilmar Gesser
+ */
+public class PrettyPrintVisitor implements VoidVisitor<Void> {
+ protected final PrettyPrinterConfiguration configuration;
+ protected final SourcePrinter printer;
+
+ public PrettyPrintVisitor(PrettyPrinterConfiguration prettyPrinterConfiguration) {
+ configuration = prettyPrinterConfiguration;
+ printer = new SourcePrinter(configuration.getIndent());
+ }
+
+ public String getSource() {
+ return printer.getSource();
+ }
+
+ private void printModifiers(final EnumSet<Modifier> modifiers) {
+ if (modifiers.size() > 0) {
+ printer.print(modifiers.stream().map(Modifier::asString).collect(Collectors.joining(" ")) + " ");
+ }
+ }
+
+ private void printMembers(final NodeList<BodyDeclaration<?>> members, final Void arg) {
+ for (final BodyDeclaration<?> member : members) {
+ printer.println();
+ member.accept(this, arg);
+ printer.println();
+ }
+ }
+
+ private void printMemberAnnotations(final NodeList<AnnotationExpr> annotations, final Void arg) {
+ if (annotations.isEmpty()) {
+ return;
+ }
+ for (final AnnotationExpr a : annotations) {
+ a.accept(this, arg);
+ printer.println();
+ }
+ }
+
+ private void printAnnotations(final NodeList<AnnotationExpr> annotations, boolean prefixWithASpace,
+ final Void arg) {
+ if (annotations.isEmpty()) {
+ return;
+ }
+ if (prefixWithASpace) {
+ printer.print(" ");
+ }
+ for (AnnotationExpr annotation : annotations) {
+ annotation.accept(this, arg);
+ printer.print(" ");
+ }
+ }
+
+ private void printTypeArgs(final NodeWithTypeArguments<?> nodeWithTypeArguments, final Void arg) {
+ NodeList<Type> typeArguments = nodeWithTypeArguments.getTypeArguments().orElse(null);
+ if (!isNullOrEmpty(typeArguments)) {
+ printer.print("<");
+ for (final Iterator<Type> i = typeArguments.iterator(); i.hasNext(); ) {
+ final Type t = i.next();
+ t.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ printer.print(">");
+ }
+ }
+
+ private void printTypeParameters(final NodeList<TypeParameter> args, final Void arg) {
+ if (!isNullOrEmpty(args)) {
+ printer.print("<");
+ for (final Iterator<TypeParameter> i = args.iterator(); i.hasNext(); ) {
+ final TypeParameter t = i.next();
+ t.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ printer.print(">");
+ }
+ }
+
+ private void printArguments(final NodeList<Expression> args, final Void arg) {
+ printer.print("(");
+ if (!isNullOrEmpty(args)) {
+ for (final Iterator<Expression> i = args.iterator(); i.hasNext(); ) {
+ final Expression e = i.next();
+ e.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ }
+ printer.print(")");
+ }
+
+ private void printJavaComment(final Comment javacomment, final Void arg) {
+ if (javacomment != null) {
+ javacomment.accept(this, arg);
+ }
+ }
+
+ @Override
+ public void visit(final CompilationUnit n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+
+ if (n.getPackageDeclaration().isPresent()) {
+ n.getPackageDeclaration().get().accept(this, arg);
+ }
+
+ n.getImports().accept(this, arg);
+ if (!n.getImports().isEmpty()) {
+ printer.println();
+ }
+
+ for (final Iterator<TypeDeclaration<?>> i = n.getTypes().iterator(); i.hasNext(); ) {
+ i.next().accept(this, arg);
+ printer.println();
+ if (i.hasNext()) {
+ printer.println();
+ }
+ }
+
+ printOrphanCommentsEnding(n);
+ }
+
+ @Override
+ public void visit(final PackageDeclaration n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printAnnotations(n.getAnnotations(), false, arg);
+ printer.print("package ");
+ n.getName().accept(this, arg);
+ printer.println(";");
+ printer.println();
+
+ printOrphanCommentsEnding(n);
+ }
+
+ @Override
+ public void visit(final NameExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ n.getName().accept(this, arg);
+
+ printOrphanCommentsEnding(n);
+ }
+
+ @Override
+ public void visit(final Name n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ if (n.getQualifier().isPresent()) {
+ n.getQualifier().get().accept(this, arg);
+ printer.print(".");
+ }
+ printer.print(n.getIdentifier());
+
+ printOrphanCommentsEnding(n);
+ }
+
+ @Override
+ public void visit(SimpleName n, Void arg) {
+ printer.print(n.getIdentifier());
+ }
+
+ @Override
+ public void visit(final ClassOrInterfaceDeclaration n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printMemberAnnotations(n.getAnnotations(), arg);
+ printModifiers(n.getModifiers());
+
+ if (n.isInterface()) {
+ printer.print("interface ");
+ } else {
+ printer.print("class ");
+ }
+
+ n.getName().accept(this, arg);
+
+ printTypeParameters(n.getTypeParameters(), arg);
+
+ if (!n.getExtendedTypes().isEmpty()) {
+ printer.print(" extends ");
+ for (final Iterator<ClassOrInterfaceType> i = n.getExtendedTypes().iterator(); i.hasNext(); ) {
+ final ClassOrInterfaceType c = i.next();
+ c.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ }
+
+ if (!n.getImplementedTypes().isEmpty()) {
+ printer.print(" implements ");
+ for (final Iterator<ClassOrInterfaceType> i = n.getImplementedTypes().iterator(); i.hasNext(); ) {
+ final ClassOrInterfaceType c = i.next();
+ c.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ }
+
+ printer.println(" {");
+ printer.indent();
+ if (!isNullOrEmpty(n.getMembers())) {
+ printMembers(n.getMembers(), arg);
+ }
+
+ printOrphanCommentsEnding(n);
+
+ printer.unindent();
+ printer.print("}");
+ }
+
+ @Override
+ public void visit(final JavadocComment n, final Void arg) {
+ printer.print("/**");
+ printer.print(n.getContent());
+ printer.println("*/");
+ }
+
+ @Override
+ public void visit(final ClassOrInterfaceType n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+
+ if (n.getScope().isPresent()) {
+ n.getScope().get().accept(this, arg);
+ printer.print(".");
+ }
+ for (AnnotationExpr ae : n.getAnnotations()) {
+ ae.accept(this, arg);
+ printer.print(" ");
+ }
+
+ n.getName().accept(this, arg);
+
+ if (n.isUsingDiamondOperator()) {
+ printer.print("<>");
+ } else {
+ printTypeArgs(n, arg);
+ }
+ }
+
+ @Override
+ public void visit(final TypeParameter n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ for (AnnotationExpr ann : n.getAnnotations()) {
+ ann.accept(this, arg);
+ printer.print(" ");
+ }
+ n.getName().accept(this, arg);
+ if (!isNullOrEmpty(n.getTypeBound())) {
+ printer.print(" extends ");
+ for (final Iterator<ClassOrInterfaceType> i = n.getTypeBound().iterator(); i.hasNext(); ) {
+ final ClassOrInterfaceType c = i.next();
+ c.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(" & ");
+ }
+ }
+ }
+ }
+
+ @Override
+ public void visit(final PrimitiveType n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printAnnotations(n.getAnnotations(), true, arg);
+ printer.print(n.getType().asString());
+ }
+
+ @Override
+ public void visit(final ArrayType n, final Void arg) {
+ final List<ArrayType> arrayTypeBuffer = new LinkedList<>();
+ Type type = n;
+ while (type instanceof ArrayType) {
+ final ArrayType arrayType = (ArrayType) type;
+ arrayTypeBuffer.add(arrayType);
+ type = arrayType.getComponentType();
+ }
+
+ type.accept(this, arg);
+ for (ArrayType arrayType : arrayTypeBuffer) {
+ printAnnotations(arrayType.getAnnotations(), true, arg);
+ printer.print("[]");
+ }
+ }
+
+ @Override
+ public void visit(final ArrayCreationLevel n, final Void arg) {
+ printAnnotations(n.getAnnotations(), true, arg);
+ printer.print("[");
+ if (n.getDimension().isPresent()) {
+ n.getDimension().get().accept(this, arg);
+ }
+ printer.print("]");
+ }
+
+ @Override
+ public void visit(final IntersectionType n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printAnnotations(n.getAnnotations(), false, arg);
+ boolean isFirst = true;
+ for (ReferenceType element : n.getElements()) {
+ element.accept(this, arg);
+ if (isFirst) {
+ isFirst = false;
+ } else {
+ printer.print(" & ");
+ }
+ }
+ }
+
+ @Override
+ public void visit(final UnionType n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printAnnotations(n.getAnnotations(), true, arg);
+ boolean isFirst = true;
+ for (ReferenceType element : n.getElements()) {
+ if (isFirst) {
+ isFirst = false;
+ } else {
+ printer.print(" | ");
+ }
+ element.accept(this, arg);
+ }
+ }
+
+ @Override
+ public void visit(final WildcardType n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printAnnotations(n.getAnnotations(), false, arg);
+ printer.print("?");
+ if (n.getExtendedTypes().isPresent()) {
+ printer.print(" extends ");
+ n.getExtendedTypes().get().accept(this, arg);
+ }
+ if (n.getSuperTypes().isPresent()) {
+ printer.print(" super ");
+ n.getSuperTypes().get().accept(this, arg);
+ }
+ }
+
+ @Override
+ public void visit(final UnknownType n, final Void arg) {
+ // Nothing to print
+ }
+
+ @Override
+ public void visit(final FieldDeclaration n, final Void arg) {
+ printOrphanCommentsBeforeThisChildNode(n);
+
+ printJavaComment(n.getComment(), arg);
+ printMemberAnnotations(n.getAnnotations(), arg);
+ printModifiers(n.getModifiers());
+ if (!n.getVariables().isEmpty()) {
+ n.getMaximumCommonType().accept(this, arg);
+ }
+
+ printer.print(" ");
+ for (final Iterator<VariableDeclarator> i = n.getVariables().iterator(); i.hasNext(); ) {
+ final VariableDeclarator var = i.next();
+ var.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+
+ printer.print(";");
+ }
+
+ @Override
+ public void visit(final VariableDeclarator n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ n.getName().accept(this, arg);
+
+ Type commonType = n.getAncestorOfType(NodeWithVariables.class).get().getMaximumCommonType();
+
+ Type type = n.getType();
+
+ ArrayType arrayType = null;
+
+ for (int i = commonType.getArrayLevel(); i < type.getArrayLevel(); i++) {
+ if (arrayType == null) {
+ arrayType = (ArrayType) type;
+ } else {
+ arrayType = (ArrayType) arrayType.getComponentType();
+ }
+ printAnnotations(arrayType.getAnnotations(), true, arg);
+ printer.print("[]");
+ }
+
+ if (n.getInitializer().isPresent()) {
+ printer.print(" = ");
+ n.getInitializer().get().accept(this, arg);
+ }
+ }
+
+ @Override
+ public void visit(final ArrayInitializerExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("{");
+ if (!isNullOrEmpty(n.getValues())) {
+ printer.print(" ");
+ for (final Iterator<Expression> i = n.getValues().iterator(); i.hasNext(); ) {
+ final Expression expr = i.next();
+ expr.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ printer.print(" ");
+ }
+ printer.print("}");
+ }
+
+ @Override
+ public void visit(final VoidType n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printAnnotations(n.getAnnotations(), false, arg);
+ printer.print("void");
+ }
+
+ @Override
+ public void visit(final ArrayAccessExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ n.getName().accept(this, arg);
+ printer.print("[");
+ n.getIndex().accept(this, arg);
+ printer.print("]");
+ }
+
+ @Override
+ public void visit(final ArrayCreationExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("new ");
+ n.getElementType().accept(this, arg);
+ for (ArrayCreationLevel level : n.getLevels()) {
+ level.accept(this, arg);
+ }
+ if (n.getInitializer().isPresent()) {
+ printer.print(" ");
+ n.getInitializer().get().accept(this, arg);
+ }
+ }
+
+ @Override
+ public void visit(final AssignExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ n.getTarget().accept(this, arg);
+ printer.print(" ");
+ printer.print(n.getOperator().asString());
+ printer.print(" ");
+ n.getValue().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final BinaryExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ n.getLeft().accept(this, arg);
+ printer.print(" ");
+ printer.print(n.getOperator().asString());
+ printer.print(" ");
+ n.getRight().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final CastExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("(");
+ n.getType().accept(this, arg);
+ printer.print(") ");
+ n.getExpression().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final ClassExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ n.getType().accept(this, arg);
+ printer.print(".class");
+ }
+
+ @Override
+ public void visit(final ConditionalExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ n.getCondition().accept(this, arg);
+ printer.print(" ? ");
+ n.getThenExpr().accept(this, arg);
+ printer.print(" : ");
+ n.getElseExpr().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final EnclosedExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("(");
+ if (n.getInner().isPresent()) {
+ n.getInner().get().accept(this, arg);
+ }
+ printer.print(")");
+ }
+
+ @Override
+ public void visit(final FieldAccessExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ if (n.getScope().isPresent())
+ n.getScope().get().accept(this, arg);
+ printer.print(".");
+ n.getName().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final InstanceOfExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ n.getExpression().accept(this, arg);
+ printer.print(" instanceof ");
+ n.getType().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final CharLiteralExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("'");
+ printer.print(n.getValue());
+ printer.print("'");
+ }
+
+ @Override
+ public void visit(final DoubleLiteralExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print(n.getValue());
+ }
+
+ @Override
+ public void visit(final IntegerLiteralExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print(n.getValue());
+ }
+
+ @Override
+ public void visit(final LongLiteralExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print(n.getValue());
+ }
+
+ @Override
+ public void visit(final StringLiteralExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("\"");
+ printer.print(n.getValue());
+ printer.print("\"");
+ }
+
+ @Override
+ public void visit(final BooleanLiteralExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print(String.valueOf(n.getValue()));
+ }
+
+ @Override
+ public void visit(final NullLiteralExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("null");
+ }
+
+ @Override
+ public void visit(final ThisExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ if (n.getClassExpr().isPresent()) {
+ n.getClassExpr().get().accept(this, arg);
+ printer.print(".");
+ }
+ printer.print("this");
+ }
+
+ @Override
+ public void visit(final SuperExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ if (n.getClassExpr().isPresent()) {
+ n.getClassExpr().get().accept(this, arg);
+ printer.print(".");
+ }
+ printer.print("super");
+ }
+
+ @Override
+ public void visit(final MethodCallExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ if (n.getScope().isPresent()) {
+ n.getScope().get().accept(this, arg);
+ printer.print(".");
+ }
+ printTypeArgs(n, arg);
+ n.getName().accept(this, arg);
+ printArguments(n.getArguments(), arg);
+ }
+
+ @Override
+ public void visit(final ObjectCreationExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ if (n.getScope().isPresent()) {
+ n.getScope().get().accept(this, arg);
+ printer.print(".");
+ }
+
+ printer.print("new ");
+
+ printTypeArgs(n, arg);
+ if (!isNullOrEmpty(n.getTypeArguments().orElse(null))) {
+ printer.print(" ");
+ }
+
+ n.getType().accept(this, arg);
+
+ printArguments(n.getArguments(), arg);
+
+ if (n.getAnonymousClassBody().isPresent()) {
+ printer.println(" {");
+ printer.indent();
+ printMembers(n.getAnonymousClassBody().get(), arg);
+ printer.unindent();
+ printer.print("}");
+ }
+ }
+
+ @Override
+ public void visit(final UnaryExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ if (n.getOperator().isPrefix()) {
+ printer.print(n.getOperator().asString());
+ }
+
+ n.getExpression().accept(this, arg);
+
+ if (n.getOperator().isPostfix()) {
+ printer.print(n.getOperator().asString());
+ }
+ }
+
+ @Override
+ public void visit(final ConstructorDeclaration n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printMemberAnnotations(n.getAnnotations(), arg);
+ printModifiers(n.getModifiers());
+
+ printTypeParameters(n.getTypeParameters(), arg);
+ if (n.isGeneric()) {
+ printer.print(" ");
+ }
+ n.getName().accept(this, arg);
+
+ printer.print("(");
+ if (!n.getParameters().isEmpty()) {
+ for (final Iterator<Parameter> i = n.getParameters().iterator(); i.hasNext(); ) {
+ final Parameter p = i.next();
+ p.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ }
+ printer.print(")");
+
+ if (!isNullOrEmpty(n.getThrownExceptions())) {
+ printer.print(" throws ");
+ for (final Iterator<ReferenceType> i = n.getThrownExceptions().iterator(); i.hasNext(); ) {
+ final ReferenceType name = i.next();
+ name.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ }
+ printer.print(" ");
+ n.getBody().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final MethodDeclaration n, final Void arg) {
+ printOrphanCommentsBeforeThisChildNode(n);
+
+ printJavaComment(n.getComment(), arg);
+ printMemberAnnotations(n.getAnnotations(), arg);
+ printModifiers(n.getModifiers());
+ if (n.isDefault()) {
+ printer.print("default ");
+ }
+ printTypeParameters(n.getTypeParameters(), arg);
+ if (!isNullOrEmpty(n.getTypeParameters())) {
+ printer.print(" ");
+ }
+
+ n.getType().accept(this, arg);
+ printer.print(" ");
+ n.getName().accept(this, arg);
+
+ printer.print("(");
+ if (!isNullOrEmpty(n.getParameters())) {
+ for (final Iterator<Parameter> i = n.getParameters().iterator(); i.hasNext(); ) {
+ final Parameter p = i.next();
+ p.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ }
+ printer.print(")");
+
+ if (!isNullOrEmpty(n.getThrownExceptions())) {
+ printer.print(" throws ");
+ for (final Iterator<ReferenceType> i = n.getThrownExceptions().iterator(); i.hasNext(); ) {
+ final ReferenceType name = i.next();
+ name.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ }
+ if (!n.getBody().isPresent()) {
+ printer.print(";");
+ } else {
+ printer.print(" ");
+ n.getBody().get().accept(this, arg);
+ }
+ }
+
+ @Override
+ public void visit(final Parameter n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printAnnotations(n.getAnnotations(), false, arg);
+ printModifiers(n.getModifiers());
+ if (n.getType() != null) {
+ n.getType().accept(this, arg);
+ }
+ if (n.isVarArgs()) {
+ printer.print("...");
+ }
+ printer.print(" ");
+ n.getName().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final ExplicitConstructorInvocationStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ if (n.isThis()) {
+ printTypeArgs(n, arg);
+ printer.print("this");
+ } else {
+ if (n.getExpression().isPresent()) {
+ n.getExpression().get().accept(this, arg);
+ printer.print(".");
+ }
+ printTypeArgs(n, arg);
+ printer.print("super");
+ }
+ printArguments(n.getArguments(), arg);
+ printer.print(";");
+ }
+
+ @Override
+ public void visit(final VariableDeclarationExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printAnnotations(n.getAnnotations(), false, arg);
+ printModifiers(n.getModifiers());
+
+ if (!n.getVariables().isEmpty()) {
+ n.getMaximumCommonType().accept(this, arg);
+ }
+ printer.print(" ");
+
+ for (final Iterator<VariableDeclarator> i = n.getVariables().iterator(); i.hasNext(); ) {
+ final VariableDeclarator v = i.next();
+ v.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ }
+
+ @Override
+ public void visit(final LocalClassDeclarationStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ n.getClassDeclaration().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final AssertStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("assert ");
+ n.getCheck().accept(this, arg);
+ if (n.getMessage().isPresent()) {
+ printer.print(" : ");
+ n.getMessage().get().accept(this, arg);
+ }
+ printer.print(";");
+ }
+
+ @Override
+ public void visit(final BlockStmt n, final Void arg) {
+ printOrphanCommentsBeforeThisChildNode(n);
+ printJavaComment(n.getComment(), arg);
+ printer.println("{");
+ if (n.getStatements() != null) {
+ printer.indent();
+ for (final Statement s : n.getStatements()) {
+ s.accept(this, arg);
+ printer.println();
+ }
+ printer.unindent();
+ }
+ printOrphanCommentsEnding(n);
+ printer.print("}");
+
+ }
+
+ @Override
+ public void visit(final LabeledStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ n.getLabel().accept(this, arg);
+ printer.print(": ");
+ n.getStatement().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final EmptyStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print(";");
+ }
+
+ @Override
+ public void visit(final ExpressionStmt n, final Void arg) {
+ printOrphanCommentsBeforeThisChildNode(n);
+ printJavaComment(n.getComment(), arg);
+ n.getExpression().accept(this, arg);
+ printer.print(";");
+ }
+
+ @Override
+ public void visit(final SwitchStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("switch(");
+ n.getSelector().accept(this, arg);
+ printer.println(") {");
+ if (n.getEntries() != null) {
+ printer.indent();
+ for (final SwitchEntryStmt e : n.getEntries()) {
+ e.accept(this, arg);
+ }
+ printer.unindent();
+ }
+ printer.print("}");
+
+ }
+
+ @Override
+ public void visit(final SwitchEntryStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ if (n.getLabel().isPresent()) {
+ printer.print("case ");
+ n.getLabel().get().accept(this, arg);
+ printer.print(":");
+ } else {
+ printer.print("default:");
+ }
+ printer.println();
+ printer.indent();
+ if (n.getStatements() != null) {
+ for (final Statement s : n.getStatements()) {
+ s.accept(this, arg);
+ printer.println();
+ }
+ }
+ printer.unindent();
+ }
+
+ @Override
+ public void visit(final BreakStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("break");
+ n.getLabel().ifPresent(l -> printer.print(" ").print(l.getIdentifier()));
+ printer.print(";");
+ }
+
+ @Override
+ public void visit(final ReturnStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("return");
+ if (n.getExpression().isPresent()) {
+ printer.print(" ");
+ n.getExpression().get().accept(this, arg);
+ }
+ printer.print(";");
+ }
+
+ @Override
+ public void visit(final EnumDeclaration n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printMemberAnnotations(n.getAnnotations(), arg);
+ printModifiers(n.getModifiers());
+
+ printer.print("enum ");
+ n.getName().accept(this, arg);
+
+ if (!n.getImplementedTypes().isEmpty()) {
+ printer.print(" implements ");
+ for (final Iterator<ClassOrInterfaceType> i = n.getImplementedTypes().iterator(); i.hasNext(); ) {
+ final ClassOrInterfaceType c = i.next();
+ c.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ }
+
+ printer.println(" {");
+ printer.indent();
+ if (n.getEntries() != null) {
+ printer.println();
+ for (final Iterator<EnumConstantDeclaration> i = n.getEntries().iterator(); i.hasNext(); ) {
+ final EnumConstantDeclaration e = i.next();
+ e.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ }
+ if (!n.getMembers().isEmpty()) {
+ printer.println(";");
+ printMembers(n.getMembers(), arg);
+ } else {
+ if (!n.getEntries().isEmpty()) {
+ printer.println();
+ }
+ }
+ printer.unindent();
+ printer.print("}");
+ }
+
+ @Override
+ public void visit(final EnumConstantDeclaration n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printMemberAnnotations(n.getAnnotations(), arg);
+ n.getName().accept(this, arg);
+
+ if (!n.getArguments().isEmpty()) {
+ printArguments(n.getArguments(), arg);
+ }
+
+ if (!n.getClassBody().isEmpty()) {
+ printer.println(" {");
+ printer.indent();
+ printMembers(n.getClassBody(), arg);
+ printer.unindent();
+ printer.println("}");
+ }
+ }
+
+ @Override
+ public void visit(final EmptyMemberDeclaration n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print(";");
+ }
+
+ @Override
+ public void visit(final InitializerDeclaration n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ if (n.isStatic()) {
+ printer.print("static ");
+ }
+ n.getBody().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final IfStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("if (");
+ n.getCondition().accept(this, arg);
+ final boolean thenBlock = n.getThenStmt() instanceof BlockStmt;
+ if (thenBlock) // block statement should start on the same line
+ printer.print(") ");
+ else {
+ printer.println(")");
+ printer.indent();
+ }
+ n.getThenStmt().accept(this, arg);
+ if (!thenBlock)
+ printer.unindent();
+ if (n.getElseStmt().isPresent()) {
+ if (thenBlock)
+ printer.print(" ");
+ else
+ printer.println();
+ final boolean elseIf = n.getElseStmt().orElse(null) instanceof IfStmt;
+ final boolean elseBlock = n.getElseStmt().orElse(null) instanceof BlockStmt;
+ if (elseIf || elseBlock) // put chained if and start of block statement on a same level
+ printer.print("else ");
+ else {
+ printer.println("else");
+ printer.indent();
+ }
+ if (n.getElseStmt().isPresent())
+ n.getElseStmt().get().accept(this, arg);
+ if (!(elseIf || elseBlock))
+ printer.unindent();
+ }
+ }
+
+ @Override
+ public void visit(final WhileStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("while (");
+ n.getCondition().accept(this, arg);
+ printer.print(") ");
+ n.getBody().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final ContinueStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("continue");
+ n.getLabel().ifPresent(l -> printer.print(" ").print(l.getIdentifier()));
+ printer.print(";");
+ }
+
+ @Override
+ public void visit(final DoStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("do ");
+ n.getBody().accept(this, arg);
+ printer.print(" while (");
+ n.getCondition().accept(this, arg);
+ printer.print(");");
+ }
+
+ @Override
+ public void visit(final ForeachStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("for (");
+ n.getVariable().accept(this, arg);
+ printer.print(" : ");
+ n.getIterable().accept(this, arg);
+ printer.print(") ");
+ n.getBody().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final ForStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("for (");
+ if (n.getInitialization() != null) {
+ for (final Iterator<Expression> i = n.getInitialization().iterator(); i.hasNext(); ) {
+ final Expression e = i.next();
+ e.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ }
+ printer.print("; ");
+ if (n.getCompare().isPresent()) {
+ n.getCompare().get().accept(this, arg);
+ }
+ printer.print("; ");
+ if (n.getUpdate() != null) {
+ for (final Iterator<Expression> i = n.getUpdate().iterator(); i.hasNext(); ) {
+ final Expression e = i.next();
+ e.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ }
+ printer.print(") ");
+ n.getBody().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final ThrowStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("throw ");
+ n.getExpression().accept(this, arg);
+ printer.print(";");
+ }
+
+ @Override
+ public void visit(final SynchronizedStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("synchronized (");
+ n.getExpression().accept(this, arg);
+ printer.print(") ");
+ n.getBody().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final TryStmt n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("try ");
+ if (!n.getResources().isEmpty()) {
+ printer.print("(");
+ Iterator<VariableDeclarationExpr> resources = n.getResources().iterator();
+ boolean first = true;
+ while (resources.hasNext()) {
+ visit(resources.next(), arg);
+ if (resources.hasNext()) {
+ printer.print(";");
+ printer.println();
+ if (first) {
+ printer.indent();
+ }
+ }
+ first = false;
+ }
+ if (n.getResources().size() > 1) {
+ printer.unindent();
+ }
+ printer.print(") ");
+ }
+ if (n.getTryBlock().isPresent()) {
+ n.getTryBlock().get().accept(this, arg);
+ }
+ for (final CatchClause c : n.getCatchClauses()) {
+ c.accept(this, arg);
+ }
+ if (n.getFinallyBlock().isPresent()) {
+ printer.print(" finally ");
+ n.getFinallyBlock().get().accept(this, arg);
+ }
+ }
+
+ @Override
+ public void visit(final CatchClause n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print(" catch (");
+ n.getParameter().accept(this, arg);
+ printer.print(") ");
+ n.getBody().accept(this, arg);
+
+ }
+
+ @Override
+ public void visit(final AnnotationDeclaration n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printMemberAnnotations(n.getAnnotations(), arg);
+ printModifiers(n.getModifiers());
+
+ printer.print("@interface ");
+ n.getName().accept(this, arg);
+ printer.println(" {");
+ printer.indent();
+ if (n.getMembers() != null) {
+ printMembers(n.getMembers(), arg);
+ }
+ printer.unindent();
+ printer.print("}");
+ }
+
+ @Override
+ public void visit(final AnnotationMemberDeclaration n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printMemberAnnotations(n.getAnnotations(), arg);
+ printModifiers(n.getModifiers());
+
+ n.getType().accept(this, arg);
+ printer.print(" ");
+ n.getName().accept(this, arg);
+ printer.print("()");
+ if (n.getDefaultValue().isPresent()) {
+ printer.print(" default ");
+ n.getDefaultValue().get().accept(this, arg);
+ }
+ printer.print(";");
+ }
+
+ @Override
+ public void visit(final MarkerAnnotationExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("@");
+ n.getName().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final SingleMemberAnnotationExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("@");
+ n.getName().accept(this, arg);
+ printer.print("(");
+ n.getMemberValue().accept(this, arg);
+ printer.print(")");
+ }
+
+ @Override
+ public void visit(final NormalAnnotationExpr n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("@");
+ n.getName().accept(this, arg);
+ printer.print("(");
+ if (n.getPairs() != null) {
+ for (final Iterator<MemberValuePair> i = n.getPairs().iterator(); i.hasNext(); ) {
+ final MemberValuePair m = i.next();
+ m.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ }
+ printer.print(")");
+ }
+
+ @Override
+ public void visit(final MemberValuePair n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ n.getName().accept(this, arg);
+ printer.print(" = ");
+ n.getValue().accept(this, arg);
+ }
+
+ @Override
+ public void visit(final LineComment n, final Void arg) {
+ if (!configuration.isPrintComments()) {
+ return;
+ }
+ printer.print("//");
+ String tmp = n.getContent();
+ tmp = tmp.replace('\r', ' ');
+ tmp = tmp.replace('\n', ' ');
+ printer.println(tmp);
+ }
+
+ @Override
+ public void visit(final BlockComment n, final Void arg) {
+ if (!configuration.isPrintComments()) {
+ return;
+ }
+ printer.print("/*").print(n.getContent()).println("*/");
+ }
+
+ @Override
+ public void visit(LambdaExpr n, Void arg) {
+ printJavaComment(n.getComment(), arg);
+
+ final NodeList<Parameter> parameters = n.getParameters();
+ final boolean printPar = n.isEnclosingParameters();
+
+ if (printPar) {
+ printer.print("(");
+ }
+ for (Iterator<Parameter> i = parameters.iterator(); i.hasNext(); ) {
+ Parameter p = i.next();
+ p.accept(this, arg);
+ if (i.hasNext()) {
+ printer.print(", ");
+ }
+ }
+ if (printPar) {
+ printer.print(")");
+ }
+
+ printer.print(" -> ");
+ final Statement body = n.getBody();
+ if (body instanceof ExpressionStmt) {
+ // Print the expression directly
+ ((ExpressionStmt) body).getExpression().accept(this, arg);
+ } else {
+ body.accept(this, arg);
+ }
+ }
+
+ @Override
+ public void visit(MethodReferenceExpr n, Void arg) {
+ printJavaComment(n.getComment(), arg);
+ Expression scope = n.getScope();
+ String identifier = n.getIdentifier();
+ if (scope != null) {
+ n.getScope().accept(this, arg);
+ }
+
+ printer.print("::");
+ printTypeArgs(n, arg);
+ if (identifier != null) {
+ printer.print(identifier);
+ }
+
+ }
+
+ @Override
+ public void visit(TypeExpr n, Void arg) {
+ printJavaComment(n.getComment(), arg);
+ if (n.getType() != null) {
+ n.getType().accept(this, arg);
+ }
+ }
+
+ @Override
+ public void visit(NodeList n, Void arg) {
+ for (Object node : n) {
+ ((Node) node).accept(this, arg);
+ }
+ }
+
+ @Override
+ public void visit(final ImportDeclaration n, final Void arg) {
+ printJavaComment(n.getComment(), arg);
+ printer.print("import ");
+ if (n.isStatic()) {
+ printer.print("static ");
+ }
+ n.getName().accept(this, arg);
+ if (n.isAsterisk()) {
+ printer.print(".*");
+ }
+ printer.println(";");
+
+ printOrphanCommentsEnding(n);
+ }
+
+ private void printOrphanCommentsBeforeThisChildNode(final Node node) {
+ if (node instanceof Comment) return;
+
+ Node parent = node.getParentNode().orElse(null);
+ if (parent == null) return;
+ List<Node> everything = new LinkedList<>();
+ everything.addAll(parent.getChildNodes());
+ sortByBeginPosition(everything);
+ int positionOfTheChild = -1;
+ for (int i = 0; i < everything.size(); i++) {
+ if (everything.get(i) == node) positionOfTheChild = i;
+ }
+ if (positionOfTheChild == -1) {
+ throw new AssertionError("I am not a child of my parent.");
+ }
+ int positionOfPreviousChild = -1;
+ for (int i = positionOfTheChild - 1; i >= 0 && positionOfPreviousChild == -1; i--) {
+ if (!(everything.get(i) instanceof Comment)) positionOfPreviousChild = i;
+ }
+ for (int i = positionOfPreviousChild + 1; i < positionOfTheChild; i++) {
+ Node nodeToPrint = everything.get(i);
+ if (!(nodeToPrint instanceof Comment))
+ throw new RuntimeException(
+ "Expected comment, instead " + nodeToPrint.getClass() + ". Position of previous child: "
+ + positionOfPreviousChild + ", position of child " + positionOfTheChild);
+ nodeToPrint.accept(this, null);
+ }
+ }
+
+ private void printOrphanCommentsEnding(final Node node) {
+ List<Node> everything = new LinkedList<>();
+ everything.addAll(node.getChildNodes());
+ sortByBeginPosition(everything);
+ if (everything.isEmpty()) {
+ return;
+ }
+
+ int commentsAtEnd = 0;
+ boolean findingComments = true;
+ while (findingComments && commentsAtEnd < everything.size()) {
+ Node last = everything.get(everything.size() - 1 - commentsAtEnd);
+ findingComments = (last instanceof Comment);
+ if (findingComments) {
+ commentsAtEnd++;
+ }
+ }
+ for (int i = 0; i < commentsAtEnd; i++) {
+ everything.get(everything.size() - commentsAtEnd + i).accept(this, null);
+ }
+ }
+
+}