From 9e48794b991bd485c26ed7cbb2fb22f06c743ad7 Mon Sep 17 00:00:00 2001 From: Sam Cao Date: Wed, 31 Jan 2024 13:44:27 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=B3=20chore:=20Update=20dependencies?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/kotlinScripting.xml | 6 - .idea/modules.xml | 1 + build.gradle.kts | 221 +-- gradle/wrapper/gradle-wrapper.properties | 18 +- scripts/node/jaspiler/index.d.ts | 1674 ++++++++--------- scripts/node/jaspiler/jaspiler.js | 736 ++++---- scripts/node/package-lock.json | 877 ++++----- scripts/node/test/test_argv.js | 50 +- scripts/node/test/test_transform.js | 1114 +++++------ scripts/node/tutorials/01_quick_start.js | 68 +- scripts/node/tutorials/02_play_with_types.js | 108 +- .../node/tutorials/03_builtin_annotations.js | 130 +- scripts/node/tutorials/04_parse_argv.js | 86 +- settings.gradle.kts | 38 +- .../caoccao/jaspiler/JaspilerCompiler.java | 2 +- .../caoccao/jaspiler/JaspilerContract.java | 2 +- .../com/caoccao/jaspiler/JaspilerMain.java | 2 +- .../contexts/BaseJaspilerContext.java | 2 +- .../jaspiler/contexts/JaspilerDocContext.java | 2 +- .../contexts/JaspilerParseContext.java | 2 +- .../contexts/JaspilerTransformContext.java | 2 +- .../jaspiler/contexts/package-info.java | 2 +- .../jaspiler/enums/JaspilerExitCode.java | 86 +- .../caoccao/jaspiler/enums/JavaKeyword.java | 206 +- .../exceptions/JaspilerArgumentException.java | 54 +- .../exceptions/JaspilerCheckedException.java | 54 +- .../JaspilerExecutionException.java | 54 +- .../JaspilerNotImplementedException.java | 62 +- .../JaspilerNotSupportedException.java | 62 +- .../exceptions/JaspilerParseException.java | 54 +- .../JaspilerUncheckedException.java | 62 +- .../jaspiler/exceptions/package-info.java | 2 +- .../com/caoccao/jaspiler/package-info.java | 2 +- .../jaspiler/styles/BaseStyleWriter.java | 534 +++--- .../caoccao/jaspiler/styles/IStyleWriter.java | 236 +-- .../jaspiler/styles/StandardStyleWriter.java | 186 +- .../caoccao/jaspiler/styles/StyleOptions.java | 184 +- .../jaspiler/trees/IJTAnnotatable.java | 2 +- .../com/caoccao/jaspiler/trees/IJTTree.java | 2 +- .../jaspiler/trees/JTAnnotatedType.java | 2 +- .../caoccao/jaspiler/trees/JTAnnotation.java | 2 +- .../caoccao/jaspiler/trees/JTArrayAccess.java | 2 +- .../caoccao/jaspiler/trees/JTArrayType.java | 2 +- .../com/caoccao/jaspiler/trees/JTAssert.java | 2 +- .../com/caoccao/jaspiler/trees/JTAssign.java | 2 +- .../caoccao/jaspiler/trees/JTAssignOp.java | 2 +- .../com/caoccao/jaspiler/trees/JTBinary.java | 2 +- .../jaspiler/trees/JTBindingPattern.java | 2 +- .../com/caoccao/jaspiler/trees/JTBlock.java | 2 +- .../com/caoccao/jaspiler/trees/JTBreak.java | 2 +- .../com/caoccao/jaspiler/trees/JTCase.java | 2 +- .../caoccao/jaspiler/trees/JTCaseLabel.java | 2 +- .../com/caoccao/jaspiler/trees/JTCatch.java | 2 +- .../caoccao/jaspiler/trees/JTCharacter.java | 2 +- .../caoccao/jaspiler/trees/JTClassDecl.java | 2 +- .../jaspiler/trees/JTCompilationUnit.java | 2 +- .../caoccao/jaspiler/trees/JTConditional.java | 2 +- .../caoccao/jaspiler/trees/JTContinue.java | 2 +- .../jaspiler/trees/JTDefaultCaseLabel.java | 2 +- .../caoccao/jaspiler/trees/JTDirective.java | 2 +- .../caoccao/jaspiler/trees/JTDoWhileLoop.java | 2 +- .../jaspiler/trees/JTEnhancedForLoop.java | 2 +- .../caoccao/jaspiler/trees/JTErroneous.java | 2 +- .../com/caoccao/jaspiler/trees/JTExports.java | 2 +- .../caoccao/jaspiler/trees/JTExpression.java | 2 +- .../jaspiler/trees/JTExpressionStatement.java | 2 +- .../caoccao/jaspiler/trees/JTFieldAccess.java | 2 +- .../com/caoccao/jaspiler/trees/JTFlags.java | 2 +- .../com/caoccao/jaspiler/trees/JTFloat.java | 2 +- .../com/caoccao/jaspiler/trees/JTForLoop.java | 2 +- .../trees/JTFunctionalExpression.java | 2 +- .../jaspiler/trees/JTGuardedPattern.java | 2 +- .../com/caoccao/jaspiler/trees/JTIdent.java | 218 +-- .../java/com/caoccao/jaspiler/trees/JTIf.java | 2 +- .../com/caoccao/jaspiler/trees/JTImport.java | 2 +- .../caoccao/jaspiler/trees/JTInstanceOf.java | 258 +-- .../jaspiler/trees/JTLabeledStatement.java | 242 +-- .../com/caoccao/jaspiler/trees/JTLambda.java | 280 +-- .../com/caoccao/jaspiler/trees/JTLiteral.java | 444 ++--- .../jaspiler/trees/JTMemberReference.java | 318 ++-- .../caoccao/jaspiler/trees/JTMethodDecl.java | 566 +++--- .../jaspiler/trees/JTMethodInvocation.java | 250 +-- .../caoccao/jaspiler/trees/JTModifiers.java | 316 ++-- .../caoccao/jaspiler/trees/JTModuleDecl.java | 292 +-- .../com/caoccao/jaspiler/trees/JTName.java | 2 +- .../caoccao/jaspiler/trees/JTNewArray.java | 346 ++-- .../caoccao/jaspiler/trees/JTNewClass.java | 330 ++-- .../com/caoccao/jaspiler/trees/JTOpens.java | 2 +- .../jaspiler/trees/JTOperatorExpression.java | 2 +- .../caoccao/jaspiler/trees/JTPackageDecl.java | 268 +-- .../com/caoccao/jaspiler/trees/JTParens.java | 204 +- .../trees/JTParenthesizedPattern.java | 206 +- .../com/caoccao/jaspiler/trees/JTPattern.java | 2 +- .../jaspiler/trees/JTPolyExpression.java | 104 +- .../caoccao/jaspiler/trees/JTPolyKind.java | 56 +- .../caoccao/jaspiler/trees/JTPosition.java | 164 +- .../jaspiler/trees/JTPrimitiveType.java | 216 +-- .../caoccao/jaspiler/trees/JTProvides.java | 224 +-- .../caoccao/jaspiler/trees/JTRequires.java | 280 +-- .../com/caoccao/jaspiler/trees/JTReturn.java | 230 +-- .../com/caoccao/jaspiler/trees/JTSkip.java | 2 +- .../caoccao/jaspiler/trees/JTStatement.java | 2 +- .../com/caoccao/jaspiler/trees/JTSwitch.java | 224 +-- .../jaspiler/trees/JTSwitchExpression.java | 240 +-- .../jaspiler/trees/JTSynchronized.java | 244 +-- .../com/caoccao/jaspiler/trees/JTThrow.java | 204 +- .../com/caoccao/jaspiler/trees/JTTree.java | 1004 +++++----- .../caoccao/jaspiler/trees/JTTreeFactory.java | 466 ++--- .../com/caoccao/jaspiler/trees/JTTry.java | 292 +-- .../caoccao/jaspiler/trees/JTTypeApply.java | 226 +-- .../caoccao/jaspiler/trees/JTTypeCast.java | 244 +-- .../jaspiler/trees/JTTypeIntersection.java | 190 +- .../jaspiler/trees/JTTypeParameter.java | 252 +-- .../caoccao/jaspiler/trees/JTTypeUnion.java | 190 +- .../com/caoccao/jaspiler/trees/JTUnary.java | 240 +-- .../com/caoccao/jaspiler/trees/JTUses.java | 204 +- .../jaspiler/trees/JTVariableDecl.java | 416 ++-- .../caoccao/jaspiler/trees/JTWhileLoop.java | 244 +-- .../caoccao/jaspiler/trees/JTWildcard.java | 238 +-- .../com/caoccao/jaspiler/trees/JTYield.java | 204 +- .../caoccao/jaspiler/trees/package-info.java | 2 +- .../jaspiler/utils/BaseLoggingObject.java | 2 +- .../caoccao/jaspiler/utils/ForEachUtils.java | 2 +- .../jaspiler/utils/JavaFileStringObject.java | 2 +- .../com/caoccao/jaspiler/utils/JsonUtils.java | 2 +- .../caoccao/jaspiler/utils/SystemUtils.java | 72 +- .../caoccao/jaspiler/utils/package-info.java | 2 +- .../com/caoccao/jaspiler/v8/V8Jaspiler.java | 2 +- .../jaspiler/v8/V8JaspilerDocScanner.java | 2 +- .../jaspiler/v8/V8JaspilerOptions.java | 2 +- .../v8/V8JaspilerTransformScanner.java | 2 +- .../jaspiler/v8/V8PatchedFileExecutor.java | 2 +- .../visiters/BaseJaspilerDocScanner.java | 2 +- .../visiters/BaseJaspilerParseScanner.java | 2 +- .../BaseJaspilerTransformScanner.java | 2 +- .../jaspiler/visiters/package-info.java | 2 +- src/main/resources/log4j.properties | 16 + .../com/caoccao/jaspiler/BaseTestSuite.java | 2 +- .../jaspiler/TestJaspilerCompiler.java | 2 +- .../jaspiler/TestJaspilerContract.java | 2 +- .../caoccao/jaspiler/TestJaspilerMain.java | 2 +- .../mock/MockAllInOnePublicClass.java | 2 +- .../caoccao/jaspiler/mock/MockForScan.java | 2 +- .../jaspiler/mock/MockIgnorePublicClass.java | 2 +- .../jaspiler/mock/MockPublicAnnotation.java | 2 +- .../jaspiler/trees/TestJTAnnotation.java | 2 +- .../jaspiler/trees/TestJTClassDecl.java | 2 +- .../jaspiler/trees/TestJTCompilationUnit.java | 2 +- .../caoccao/jaspiler/trees/TestJTImport.java | 2 +- .../jaspiler/trees/TestJTMethodDecl.java | 4 +- .../jaspiler/trees/TestJTPackageDecl.java | 2 +- .../jaspiler/trees/TestJTVariableDecl.java | 2 +- .../com/caoccao/jaspiler/utils/MockUtils.java | 2 +- .../jaspiler/visiters/DummyDocScanner.java | 2 +- .../visiters/DummyTransformScanner.java | 2 +- src/test/resources/log4j.properties | 16 + 156 files changed, 9212 insertions(+), 9161 deletions(-) delete mode 100644 .idea/kotlinScripting.xml diff --git a/.idea/kotlinScripting.xml b/.idea/kotlinScripting.xml deleted file mode 100644 index 3f1aa66..0000000 --- a/.idea/kotlinScripting.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml index 6a3d849..6eabc86 100644 --- a/.idea/modules.xml +++ b/.idea/modules.xml @@ -3,6 +3,7 @@ + \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts index 59e78a1..03d99ac 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,107 +1,114 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import org.gradle.internal.os.OperatingSystem - -object Config { - object Projects { - // https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 - const val COMMONS_COLLECTIONS4 = "org.apache.commons:commons-collections4:${Versions.COMMONS_COLLECTIONS4}" - - // https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 - const val COMMONS_LANG3 = "org.apache.commons:commons-lang3:${Versions.COMMONS_LANG3}" - - // https://mvnrepository.com/artifact/org.apache.commons/commons-text - const val COMMONS_TEXT = "org.apache.commons:commons-text:${Versions.COMMONS_TEXT}" - - // https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind - const val JACKSON_DATABIND = "com.fasterxml.jackson.core:jackson-databind:${Versions.JACKSON}" - - // https://mvnrepository.com/artifact/com.fasterxml.jackson.datatype/jackson-datatype-jsr310 - const val JACKSON_DATATYPE_JSR310 = "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:${Versions.JACKSON}" - - const val JAVET = "com.caoccao.javet:javet:${Versions.JAVET}" - const val JAVET_MACOS = "com.caoccao.javet:javet-macos:${Versions.JAVET}" - const val JUNIT_BOM = "org.junit:junit-bom:${Versions.JUNIT}" - const val JUNIT_JUPITER = "org.junit.jupiter:junit-jupiter" - - const val SLF4J_API = "org.slf4j:slf4j-api:${Versions.SLF4J}" - const val SLF4J_LOG4J12 = "org.slf4j:slf4j-log4j12:${Versions.SLF4J}" - } - - object Versions { - const val COMMONS_COLLECTIONS4 = "4.4" - const val COMMONS_LANG3 = "3.12.0" - const val COMMONS_TEXT = "1.10.0" - const val JACKSON = "2.15.2" - const val JAVET = "2.2.1" - const val JUNIT = "5.9.1" - const val SLF4J = "2.0.7" - } -} - -plugins { - id("java") -} - -group = "com.caoccao.jaspiler" -version = "0.1.0" - -repositories { - mavenCentral() -} - -dependencies { - implementation(Config.Projects.COMMONS_COLLECTIONS4) - implementation(Config.Projects.COMMONS_LANG3) - implementation(Config.Projects.COMMONS_TEXT) - implementation(Config.Projects.JACKSON_DATABIND) - implementation(Config.Projects.JACKSON_DATATYPE_JSR310) - if (OperatingSystem.current().isMacOsX) { - implementation(Config.Projects.JAVET_MACOS) - } else { - implementation(Config.Projects.JAVET) - } - implementation(Config.Projects.SLF4J_API) - implementation(Config.Projects.SLF4J_LOG4J12) - testImplementation(platform(Config.Projects.JUNIT_BOM)) - testImplementation(Config.Projects.JUNIT_JUPITER) -} - -tasks.jar { - manifest { - attributes["Main-Class"] = "com.caoccao.jaspiler.JaspilerMain" - } - val dependencies = configurations - .runtimeClasspath - .get() - .map(::zipTree) - from(dependencies) - duplicatesStrategy = DuplicatesStrategy.EXCLUDE - exclude("META-INF/*.SF", "META-INF/*.DSA", "META-INF/*.RSA") -} - -tasks.test { - useJUnitPlatform { - excludeTags("manual") - } -} - -tasks.register("manualTest") { - useJUnitPlatform { - includeTags("manual") - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.gradle.internal.os.OperatingSystem + +object Config { + object Projects { + // https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 + const val COMMONS_COLLECTIONS4 = "org.apache.commons:commons-collections4:${Versions.COMMONS_COLLECTIONS4}" + + // https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 + const val COMMONS_LANG3 = "org.apache.commons:commons-lang3:${Versions.COMMONS_LANG3}" + + // https://mvnrepository.com/artifact/org.apache.commons/commons-text + const val COMMONS_TEXT = "org.apache.commons:commons-text:${Versions.COMMONS_TEXT}" + + // https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind + const val JACKSON_DATABIND = "com.fasterxml.jackson.core:jackson-databind:${Versions.JACKSON}" + + // https://mvnrepository.com/artifact/com.fasterxml.jackson.datatype/jackson-datatype-jsr310 + const val JACKSON_DATATYPE_JSR310 = "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:${Versions.JACKSON}" + + const val JAVET = "com.caoccao.javet:javet:${Versions.JAVET}" + const val JAVET_MACOS = "com.caoccao.javet:javet-macos:${Versions.JAVET}" + + // https://mvnrepository.com/artifact/org.junit/junit-bom + const val JUNIT_BOM = "org.junit:junit-bom:${Versions.JUNIT}" + + // https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter + const val JUNIT_JUPITER = "org.junit.jupiter:junit-jupiter" + + // https://mvnrepository.com/artifact/org.slf4j/slf4j-api + const val SLF4J_API = "org.slf4j:slf4j-api:${Versions.SLF4J}" + + // https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 + const val SLF4J_LOG4J12 = "org.slf4j:slf4j-log4j12:${Versions.SLF4J}" + } + + object Versions { + const val COMMONS_COLLECTIONS4 = "4.4" + const val COMMONS_LANG3 = "3.14.0" + const val COMMONS_TEXT = "1.11.0" + const val JACKSON = "2.16.1" + const val JAVET = "3.0.3" + const val JUNIT = "5.10.1" + const val SLF4J = "2.0.11" + } +} + +plugins { + id("java") +} + +group = "com.caoccao.jaspiler" +version = "0.1.0" + +repositories { + mavenCentral() +} + +dependencies { + implementation(Config.Projects.COMMONS_COLLECTIONS4) + implementation(Config.Projects.COMMONS_LANG3) + implementation(Config.Projects.COMMONS_TEXT) + implementation(Config.Projects.JACKSON_DATABIND) + implementation(Config.Projects.JACKSON_DATATYPE_JSR310) + if (OperatingSystem.current().isMacOsX) { + implementation(Config.Projects.JAVET_MACOS) + } else { + implementation(Config.Projects.JAVET) + } + implementation(Config.Projects.SLF4J_API) + implementation(Config.Projects.SLF4J_LOG4J12) + testImplementation(platform(Config.Projects.JUNIT_BOM)) + testImplementation(Config.Projects.JUNIT_JUPITER) +} + +tasks.jar { + manifest { + attributes["Main-Class"] = "com.caoccao.jaspiler.JaspilerMain" + } + val dependencies = configurations + .runtimeClasspath + .get() + .map(::zipTree) + from(dependencies) + duplicatesStrategy = DuplicatesStrategy.EXCLUDE + exclude("META-INF/*.SF", "META-INF/*.DSA", "META-INF/*.RSA") +} + +tasks.test { + useJUnitPlatform { + excludeTags("manual") + } +} + +tasks.register("manualTest") { + useJUnitPlatform { + includeTags("manual") + } +} diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 88d090e..a087a04 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,22 @@ +# +# Copyright (c) 2024. caoccao.com Sam Cao +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + #Fri Apr 14 10:45:06 CST 2023 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/scripts/node/jaspiler/index.d.ts b/scripts/node/jaspiler/index.d.ts index 1a85e83..9eb5793 100644 --- a/scripts/node/jaspiler/index.d.ts +++ b/scripts/node/jaspiler/index.d.ts @@ -1,837 +1,837 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Usage: - * Please put this file along with your project - * and add the following line to your JS/TS files. - * You will get the intellisense in VS Code. - * - * /// - */ - -/// - -enum JTBodyKind { - EXPRESSION, - STATEMENT, -} - -enum JTCaseKind { - STATEMENT, - RULE, -} - -enum JTKind { - AND, // BinaryTree - AND_ASSIGNMENT, // CompoundAssignmentTree - ANNOTATED_TYPE, // AnnotatedTypeTree - ANNOTATION, // AnnotationTree - ANNOTATION_TYPE, // ClassTree - ARRAY_ACCESS, // ArrayAccessTree - ARRAY_TYPE, // ArrayTypeTree - ASSERT, // AssertTree - ASSIGNMENT, // AssignmentTree - BINDING_PATTERN, // BindingPatternTree - BITWISE_COMPLEMENT, // UnaryTree - BLOCK, // BlockTree - BOOLEAN_LITERAL, // LiteralTree - BREAK, // BreakTree - CASE, // CaseTree - CATCH, // CatchTree - CHAR_LITERAL, // LiteralTree - CLASS, // ClassTree - COMPILATION_UNIT, // CompilationUnitTree - CONDITIONAL_AND, // BinaryTree - CONDITIONAL_EXPRESSION, // ConditionalExpressionTree - CONDITIONAL_OR, // BinaryTree - CONTINUE, // ContinueTree - DEFAULT_CASE_LABEL, // DefaultCaseLabelTree - DIVIDE, // BinaryTree - DIVIDE_ASSIGNMENT, // CompoundAssignmentTree - DO_WHILE_LOOP, // DoWhileLoopTree - DOUBLE_LITERAL, // LiteralTree - EMPTY_STATEMENT, // EmptyStatementTree - ENHANCED_FOR_LOOP, // EnhancedForLoopTree - ENUM, // ClassTree - EQUAL_TO, // BinaryTree - ERRONEOUS, // ErroneousTree - EXPORTS, // ExportsTree - EXPRESSION_STATEMENT, // ExpressionStatementTree - EXTENDS_WILDCARD, // WildcardTree - FLOAT_LITERAL, // LiteralTree - FOR_LOOP, // ForLoopTree - GREATER_THAN, // BinaryTree - GREATER_THAN_EQUAL, // BinaryTree - GUARDED_PATTERN, // GuardedPatternTree - IDENTIFIER, // IdentifierTree - IF, // IfTree - IMPORT, // ImportTree - INSTANCE_OF, // InstanceOfTree - INT_LITERAL, // LiteralTree - INTERFACE, // ClassTree - INTERSECTION_TYPE, // IntersectionTypeTree - LABELED_STATEMENT, // LabeledStatementTree - LAMBDA_EXPRESSION, // LambdaExpressionTree - LEFT_SHIFT, // BinaryTree - LEFT_SHIFT_ASSIGNMENT, // CompoundAssignmentTree - LESS_THAN, // BinaryTree - LESS_THAN_EQUAL, // BinaryTree - LOGICAL_COMPLEMENT, // UnaryTree - LONG_LITERAL, // LiteralTree - MEMBER_REFERENCE, // MemberReferenceTree - MEMBER_SELECT, // MemberSelectTree - METHOD, // MethodTree - METHOD_INVOCATION, // MethodInvocationTree - MINUS, // BinaryTree - MINUS_ASSIGNMENT, // CompoundAssignmentTree - MODIFIERS, // ModifiersTree - MODULE, // ModuleTree - MULTIPLY, // BinaryTree - MULTIPLY_ASSIGNMENT, // CompoundAssignmentTree - NEW_ARRAY, // NewArrayTree - NEW_CLASS, // NewClassTree - NOT_EQUAL_TO, // BinaryTree - NULL_LITERAL, // LiteralTree - OPENS, // OpensTree - OR, // BinaryTree - OR_ASSIGNMENT, // CompoundAssignmentTree - OTHER, // null - PACKAGE, // PackageTree - PARAMETERIZED_TYPE, // ParameterizedTypeTree - PARENTHESIZED, // ParenthesizedTree - PARENTHESIZED_PATTERN, // ParenthesizedPatternTree - PLUS, // BinaryTree - PLUS_ASSIGNMENT, // CompoundAssignmentTree - POSTFIX_DECREMENT, // UnaryTree - POSTFIX_INCREMENT, // UnaryTree - PREFIX_DECREMENT, // UnaryTree - PREFIX_INCREMENT, // UnaryTree - PRIMITIVE_TYPE, // PrimitiveTypeTree - PROVIDES, // ProvidesTree - RECORD, // ClassTree - REMAINDER, // BinaryTree - REMAINDER_ASSIGNMENT, // CompoundAssignmentTree - REQUIRES, // RequiresTree - RETURN, // ReturnTree - RIGHT_SHIFT, // BinaryTree - RIGHT_SHIFT_ASSIGNMENT, // CompoundAssignmentTree - STRING_LITERAL, // LiteralTree - SUPER_WILDCARD, // WildcardTree - SWITCH, // SwitchTree - SWITCH_EXPRESSION, // SwitchExpressionTree - SYNCHRONIZED, // SynchronizedTree - THROW, // ThrowTree - TRY, // TryTree - TYPE_ANNOTATION, // AnnotationTree - TYPE_CAST, // TypeCastTree - TYPE_PARAMETER, // TypeParameterTree - UNARY_MINUS, // UnaryTree - UNARY_PLUS, // UnaryTree - UNBOUNDED_WILDCARD, // WildcardTree - UNION_TYPE, // UnionTypeTree - UNSIGNED_RIGHT_SHIFT, // BinaryTree - UNSIGNED_RIGHT_SHIFT_ASSIGNMENT, // CompoundAssignmentTree - USES, // UsesTree - VARIABLE, // VariableTree - WHILE_LOOP, // WhileLoopTree - XOR, // BinaryTree - XOR_ASSIGNMENT, // CompoundAssignmentTree - YIELD, // YieldTree -} - -enum JTModifier { - PUBLIC = 'public', - PROTECTED = 'protected', - PRIVATE = 'private', - ABSTRACT = 'abstract', - DEFAULT = 'default', - STATIC = 'static', - SEALED = 'sealed', - NON_SEALED = 'non-sealed', - FINAL = 'final', - TRANSIENT = 'transient', - VOLATILE = 'volatile', - SYNCHRONIZED = 'synchronized', - NATIVE = 'native', - STRICTFP = 'strictfp', -} - -enum JTReferenceMode { - INVOKE, // Method references - NEW, // Constructor references -} - -enum JTTypeKind { - BOOLEAN, - BYTE, - SHORT, - INT, - LONG, - CHAR, - FLOAT, - DOUBLE, - VOID, - NONE, - NULL, - ARRAY, - DECLARED, - ERROR, - TYPEVAR, - WILDCARD, - PACKAGE, - EXECUTABLE, - OTHER, - UNION, - INTERSECTION, - MODULE, -} - -interface JTAnnotatedType extends JTExpression { - annotations: JTAnnotation[]; - underlyingType: JTExpression; -} - -interface JTAnnotation extends JTExpression { - arguments: JTExpression[]; - annotationType: JTTree; -} - -interface JTArrayAccess extends JTExpression { - expression: JTExpression; - index: JTExpression; -} - -interface JTArrayType extends JTExpression { - type: JTExpression; -} - -interface JTAssert extends JTExpression { - condition: JTExpression; - detail: JTExpression; -} - -interface JTAssign extends JTExpression { - expression: JTExpression; - variable: JTExpression; -} - -interface JTAssignOp extends JTOperatorExpression { - expression: JTExpression; - kind: JTKind.AND_ASSIGNMENT | JTKind.DIVIDE_ASSIGNMENT | JTKind.LEFT_SHIFT_ASSIGNMENT | JTKind.MINUS_ASSIGNMENT | JTKind.MULTIPLY_ASSIGNMENT | JTKind.OR_ASSIGNMENT | JTKind.PLUS_ASSIGNMENT | JTKind.REMAINDER_ASSIGNMENT | JTKind.RIGHT_SHIFT_ASSIGNMENT | JTKind.UNSIGNED_RIGHT_SHIFT_ASSIGNMENT | JTKind.XOR_ASSIGNMENT; - variable: JTExpression; -} - -interface JTBinary extends JTOperatorExpression { - kind: JTKind.AND | JTKind.CONDITIONAL_AND | JTKind.CONDITIONAL_OR | JTKind.DIVIDE | JTKind.EQUAL_TO | JTKind.GREATER_THAN | JTKind.GREATER_THAN_EQUAL | JTKind.LEFT_SHIFT | JTKind.LESS_THAN | JTKind.LESS_THAN_EQUAL | JTKind.MINUS | JTKind.MULTIPLY | JTKind.NOT_EQUAL_TO | JTKind.OR | JTKind.PLUS | JTKind.REMAINDER | JTKind.RIGHT_SHIFT | JTKind.UNSIGNED_RIGHT_SHIFT | JTKind.XOR; - leftOperand: JTExpression; - rightOperand: JTExpression; -} - -interface JTBindingPattern extends JTPattern { - variable: JTVariableDecl; -} - -interface JTBlock extends JTStatement { - statements: JTStatement[]; - static: boolean; -} - -interface JTBreak extends JTStatement { - label: JTName; -} - -interface JTCaseLabel> extends JTTree { -} - -interface JTCase extends JTStatement { - body: JTTree[]; - caseKind: JTCaseKind; - labels: JTCaseLabel; - statements: JTExpression[]; -} - -interface JTCatch extends JTTree { - block: JTBlock; - parameter: JTVariableDecl; -} - -interface JTCharacter { - readonly value: string; -} - -interface JTClassDecl extends JTStatement { - extendsClause: JTExpression; - implementsClauses: JTExpression[]; - kind: JTKind.ANNOTATION_TYPE | JTKind.CLASS | JTKind.ENUM | JTKind.INTERFACE | JTKind.RECORD; - members: JTTree[]; - modifiers: JTModifiers; - permitsClauses: JTExpression[]; - simpleName: JTName; - typeParameters: JTTypeParameter[]; -} - -interface JTCompilationUnit extends JTTree { - imports: JTImport[]; - module: JTModuleDecl; - package: JTPackageDecl; - readonly sourceFile: string; - typeDecls: JTTree[]; -} - -interface JTConditional extends JTPolyExpression { - condition: JTExpression; - falseExpression: JTExpression; - trueExpression: JTExpression; -} - -interface JTContinue extends JTStatement { - label: JTName; -} - -interface JTDefaultCaseLabel extends JTCaseLabel { -} - -interface JTDirective> extends JTTree { -} - -interface JTDoWhileLoop extends JTStatement { - condition: JTExpression; - statement: JTStatement; -} - -interface JTSkip extends JTStatement { -} - -interface JTEnhancedForLoop extends JTStatement { - expression: JTExpression; - statement: JTStatement; - variable: JTVariableDecl; -} - -interface JTErroneous extends JTExpression { - errorTree: JTTree; -} - -interface JTExports extends JTDirective { - moduleNames: JTExpression; - packageName: JTExpression; -} - -interface JTExpression> extends JTCaseLabel { -} - -interface JTExpressionStatement extends JTStatement { - expression: JTExpression; -} - -interface JTFloat { - readonly value: number; -} - -interface JTForLoop extends JTStatement { - condition: JTExpression; - initializer: JTStatement[]; - statement: JTStatement; - update: JTExpressionStatement[]; -} - -interface JTFunctionalExpression> extends JTPolyExpression { - body: JTTree; - bodyKind: JTBodyKind; - parameters: JTVariableDecl[]; -} - -interface JTGuardedPattern extends JTPattern { - expression: JTExpression; - pattern: JTPattern; -} - -interface JTFieldAccess extends JTExpression { - expression: JTExpression; - identifier: JTName; -} - -interface JTIdent extends JTExpression { - name: JTName; -} - -interface JTImport extends JTTree { - qualifiedIdentifier: JTTree; - staticImport: boolean; -} - -interface JTIf extends JTStatement { - condition: JTExpression; - elseStatement: JTStatement; - thenStatement: JTStatement; -} - -interface JTInstanceOf extends JTExpression { - expression: JTExpression; - pattern: JTTree; -} - -interface JTLabeledStatement extends JTStatement { - label: JTName; - statement: JTStatement; -} - -interface JTLambda extends JTFunctionalExpression { - body: JTTree; - bodyKind: JTBodyKind; - parameters: JTVariableDecl[]; -} - -interface JTLiteral extends JTExpression { - kind: JTKind.BOOLEAN_LITERAL | JTKind.CHAR_LITERAL | JTKind.DOUBLE_LITERAL | JTKind.FLOAT_LITERAL | JTKind.INT_LITERAL | JTKind.LONG_LITERAL | JTKind.NULL_LITERAL | JTKind.STRING_LITERAL; - value: number | string | boolean | JTFloat | JTCharacter | null; -} - -interface JTMemberReference extends JTFunctionalExpression { - mode: JTReferenceMode; - name: JTName; - qualifiedExpression: JTExpression; - typeArguments: JTExpression[]; -} - -interface JTMethodDecl extends JTTree { - body: JTBlock; - defaultValue: JTExpression; - modifiers: JTModifiers; - name: JTName; - parameters: JTVariableDecl[]; - receiverParameter: JTVariableDecl; - returnType: JTExpression; - throwExpressions: JTExpression[]; - typeParameters: JTTypeParameter[]; -} - -interface JTMethodInvocation extends JTPolyExpression { - arguments: JTExpression[]; - methodSelect: JTExpression; - typeArguments: JTExpression[]; -} - -interface JTModifiers extends JTTree { - annotations: JTAnnotation[]; - flags: JTModifier[]; -} - -interface JTModuleDecl extends JTTree { - annotations: JTAnnotation[]; - name: JTExpression; - directives: JTDirective; -} - -interface JTNewArray extends JTExpression { - annotations: JTAnnotation[]; - dimAnnotations: JTAnnotation[][]; - dimensions: JTExpression[]; - initializers: JTExpression[]; - type: JTExpression; -} - -interface JTNewClass extends JTPolyExpression { - arguments: JTExpression[]; - classBody: JTClassDecl; - enclosingExpression: JTExpression; - identifier: JTExpression; - typeArguments: JTExpression[]; -} - -interface JTOpens extends JTDirective { - moduleNames: JTExpression[]; - packageName: JTExpression; -} - -interface JTName { - value: string; -} - -interface JTOperatorExpression> extends JTExpression { -} - -interface JTPackageDecl extends JTTree { - annotations: JTAnnotation[]; - packageName: JTExpression; -} - -interface JTParens extends JTExpression { - expression: JTExpression; -} - -interface JTParenthesizedPattern extends JTPattern { - pattern: JTPattern; -} - -interface JTPattern> extends JTCaseLabel { -} - -interface JTPolyExpression> extends JTExpression { -} - -interface JTPrimitiveType extends JTExpression { - primitiveTypeKind: JTTypeKind; -} - -interface JTProvides extends JTDirective { - implementationNames: JTExpression[]; - serviceName: JTExpression; -} - -interface JTRequires extends JTDirective { - moduleName: JTExpression; - static: boolean; - transitive: boolean; -} - -interface JTReturn extends JTStatement { - expression: JTExpression; -} - -interface JTSwitch extends JTStatement { - cases: JTCase[]; - expression: JTExpression; -} - -interface JTSwitchExpression extends JTPolyExpression { - cases: JTCase[]; - expression: JTExpression; -} - -interface JTSynchronized extends JTStatement { - block: JTBlock; - expression: JTExpression; -} - -interface JTStatement> extends JTTree { -} - -interface JTThrow extends JTStatement { - expression: JTExpression; -} - -interface JTTry extends JTStatement { - block: JTBlock; - catches: JTCatch[]; - finallyBlock: JTBlock; - resources: JTTree[]; -} - -interface JTTree> { - readonly className: string; - readonly classSimpleName: string; - readonly kind: JTKind; - readonly parentTree: JTTree; - isActionChange(): boolean; - isActionIgnore(): boolean; - isActionNoChange(): boolean; - setActionChange(): boolean; - setActionIgnore(): boolean; - setActionNoChange(): boolean; - toString(): string; -} - -interface JTTypeApply extends JTExpression { - type: JTExpression; - typeArguments: JTExpression[]; -} - -interface JTTypeCast extends JTExpression { - expression: JTExpression; - type: JTTree; -} - -interface JTTypeIntersection extends JTExpression { - bounds: JTExpression; -} - -interface JTTypeParameter extends JTTree { - annotations: JTAnnotation[]; - bound: JTExpression; - name: JTName; -} - -interface JTTypeUnion extends JTExpression { - typeAlternatives: JTExpression; -} - -interface JTUnary extends JTOperatorExpression { - expression: JTExpression; - kind: JTKind.BITWISE_COMPLEMENT | JTKind.LOGICAL_COMPLEMENT | JTKind.POSTFIX_DECREMENT | JTKind.POSTFIX_INCREMENT | JTKind.PREFIX_DECREMENT | JTKind.PREFIX_INCREMENT | JTKind.UNARY_MINUS | JTKind.UNARY_PLUS; -} - -interface JTUses extends JTDirective { - serviceName: JTExpression; -} - -interface JTVariableDecl extends JTStatement { - initializer: JTExpression; - modifiers: JTModifiers; - name: JTName; - nameExpression: JTExpression; - type: JTExpression; -} - -interface JTWhileLoop extends JTStatement { - condition: JTExpression; - statement: JTStatement; -} - -interface JTWildcard extends JTExpression { - bound: JTTree; - kind: JTKind.EXTENDS_WILDCARD | JTKind.SUPER_WILDCARD | JTKind.UNBOUNDED_WILDCARD; -} - -interface JTYield extends JTStatement { - value: JTExpression; -} - -interface TransformOptions { - /** - * Include the AST in the returned object - * - * Default: `false` - */ - ast?: boolean | null | undefined; - /** - * Enable code generation - * - * Default: `true` - */ - code?: boolean | null | undefined; - /** - * Context for evaluation - * - * Default: undefined - */ - context?: object | null | undefined; - /** - * Specify the file name in source type 'string' mode - * - * Default: `undefined` - */ - fileName?: string | null | undefined; - /** - * List of plugins to load and use - * - * Default: `[]` - */ - plugins?: TransformOptionsPlugin[] | null | undefined; - /** - * Type of the source - * - * Default: `file` - */ - sourceType?: 'string' | 'file'; - /** - * Transform style - * - * Default: null - */ - style?: TransformOptionStyle; -} - -interface TransformOptionsPlugin { - visitor: TransformOptionsPluginVisitor; -} - -interface TransformOptionsPluginVisitor { - AnnotatedType(node: JTAnnotatedType, context?: object | null | undefined): void; - Annotation(node: JTAnnotation, context?: object | null | undefined): void; - ArrayAccess(node: JTArrayAccess, context?: object | null | undefined): void; - ArrayType(node: JTArrayType, context?: object | null | undefined): void; - Assert(node: JTAssert, context?: object | null | undefined): void; - Assignment(node: JTAssign, context?: object | null | undefined): void; - Binary(node: JTBinary, context?: object | null | undefined): void; - BindingPattern(node: JTBindingPattern, context?: object | null | undefined): void; - Block(node: JTBlock, context?: object | null | undefined): void; - Break(node: JTBreak, context?: object | null | undefined): void; - Case(node: JTCase, context?: object | null | undefined): void; - Catch(node: JTCatch, context?: object | null | undefined): void; - Class(node: JTClassDecl, context?: object | null | undefined): void; - CompilationUnit(node: JTCompilationUnit, context?: object | null | undefined): void; - CompoundAssignment(node: JTAssignOp, context?: object | null | undefined): void; - ConditionalExpression(node: JTConditional, context?: object | null | undefined): void; - Continue(node: JTContinue, context?: object | null | undefined): void; - DefaultCaseLabel(node: JTDefaultCaseLabel, context?: object | null | undefined): void; - DoWhileLoop(node: JTDoWhileLoop, context?: object | null | undefined): void; - EmptyStatement(node: JTSkip, context?: object | null | undefined): void; - EnhancedForLoop(node: JTEnhancedForLoop, context?: object | null | undefined): void; - Erroneous(node: JTErroneous, context?: object | null | undefined): void; - Exports(node: JTExports, context?: object | null | undefined): void; - ExpressionStatement(node: JTExpressionStatement, context?: object | null | undefined): void; - ForLoop(node: JTForLoop, context?: object | null | undefined): void; - GuardedPattern(node: JTGuardedPattern, context?: object | null | undefined): void; - Identifier(node: JTIdent, context?: object | null | undefined): void; - If(node: JTIf, context?: object | null | undefined): void; - Import(node: JTImport, context?: object | null | undefined): void; - InstanceOf(node: JTInstanceOf, context?: object | null | undefined): void; - IntersectionType(node: JTTypeIntersection, context?: object | null | undefined): void; - LabeledStatement(node: JTLabeledStatement, context?: object | null | undefined): void; - LambdaExpression(node: JTLambda, context?: object | null | undefined): void; - Literal(node: JTLiteral, context?: object | null | undefined): void; - MemberReference(node: JTMemberReference, context?: object | null | undefined): void; - MemberSelect(node: JTFieldAccess, context?: object | null | undefined): void; - Method(node: JTMethodDecl, context?: object | null | undefined): void; - MethodInvocation(node: JTMethodInvocation, context?: object | null | undefined): void; - Modifiers(node: JTModifiers, context?: object | null | undefined): void; - Module(node: JTModuleDecl, context?: object | null | undefined): void; - NewArray(node: JTNewArray, context?: object | null | undefined): void; - NewClass(node: JTNewClass, context?: object | null | undefined): void; - Opens(node: JTOpens, context?: object | null | undefined): void; - Other(node: JTTree, context?: object | null | undefined): void; - Package(node: JTPackageDecl, context?: object | null | undefined): void; - ParameterizedType(node: JTTypeApply, context?: object | null | undefined): void; - Parenthesized(node: JTParens, context?: object | null | undefined): void; - ParenthesizedPattern(node: JTParenthesizedPattern, context?: object | null | undefined): void; - PrimitiveType(node: JTPrimitiveType, context?: object | null | undefined): void; - Provides(node: JTProvides, context?: object | null | undefined): void; - Requires(node: JTRequires, context?: object | null | undefined): void; - Return(node: JTReturn, context?: object | null | undefined): void; - Scan(node: JTTree, context?: object | null | undefined): void; - Switch(node: JTSwitch, context?: object | null | undefined): void; - SwitchExpression(node: JTSwitchExpression, context?: object | null | undefined): void; - Synchronized(node: JTSynchronized, context?: object | null | undefined): void; - Throw(node: JTThrow, context?: object | null | undefined): void; - Try(node: JTTry, context?: object | null | undefined): void; - TypeCast(node: JTTypeCast, context?: object | null | undefined): void; - TypeParameter(node: JTTypeParameter, context?: object | null | undefined): void; - Unary(node: JTUnary, context?: object | null | undefined): void; - UnionType(node: JTTypeUnion, context?: object | null | undefined): void; - Uses(node: JTUses, context?: object | null | undefined): void; - Variable(node: JTVariableDecl, context?: object | null | undefined): void; - WhileLoop(node: JTWhileLoop, context?: object | null | undefined): void; - Wildcard(node: JTWildcard, context?: object | null | undefined): void; - Yield(node: JTYield, context?: object | null | undefined): void; -} - -interface TransformOptionStyle { - /** - * Size of the continuation indent - * - * Default: 8 - */ - continuationIndentSize?: number | null | undefined; - /** - * Size of the indent - * - * Default: 4 - */ - indentSize?: number | null | undefined; - /** - * Preserve the copyrights or not - * - * Default: true - */ - preserveCopyrights?: boolean | null | undefined; - /** - * Style type - * - * Default: 'standard' - */ - type?: 'compact' | 'standard' | null | undefined; - /** - * Wrap if the line length is greater than - * - * Default: 120 - */ - wordWrapColumn?: number | null | undefined; -} - -interface TransformResult { - ast?: JTCompilationUnit | undefined; - code?: string | undefined; -} - -declare namespace jaspiler { - export const argv: Array; - - export function createCharacter(value: string): JTCharacter; - export function createFieldAccess(...values: string[]): JTFieldAccess; - export function createFloat(value: string): JTFloat; - export function createIdent(value: string): JTIdent; - export function createLiteral(value: string): JTLiteral; - export function createName(value: string): JTName; - - export function newAnnotatedType(): JTAnnotatedType; - export function newAnnotation(): JTAnnotation; - export function newArrayAccess(): JTArrayAccess; - export function newArrayType(): JTArrayType; - export function newAssert(): JTAssert; - export function newAssign(): JTAssign; - export function newAssignOp(): JTAssignOp; - export function newBinary(): JTBinary; - export function newBindingPattern(): JTBindingPattern; - export function newBlock(): JTBlock; - export function newBreak(): JTBreak; - export function newCase(): JTCase; - export function newCatch(): JTCatch; - export function newClassDecl(): JTClassDecl; - export function newConditional(): JTConditional; - export function newContinue(): JTContinue; - export function newDefaultCaseLabel(): JTDefaultCaseLabel; - export function newDoWhileLoop(): JTDoWhileLoop; - export function newEnhancedForLoop(): JTEnhancedForLoop; - export function newErroneous(): JTErroneous; - export function newExports(): JTExports; - export function newExpressionStatement(): JTExpressionStatement; - export function newFieldAccess(): JTFieldAccess; - export function newForLoop(): JTForLoop; - export function newGuardedPattern(): JTGuardedPattern; - export function newIdent(): JTIdent; - export function newIf(): JTIf; - export function newImport(): JTImport; - export function newInstanceOf(): JTInstanceOf; - export function newLabeledStatement(): JTLabeledStatement; - export function newLambda(): JTLambda; - export function newLiteral(): JTLiteral; - export function newMemberReference(): JTMemberReference; - export function newMethodDecl(): JTMethodDecl; - export function newMethodInvocation(): JTMethodInvocation; - export function newModifiers(): JTModifiers; - export function newModuleDecl(): JTModuleDecl; - export function newNewArray(): JTNewArray; - export function newNewClass(): JTNewClass; - export function newOpens(): JTOpens; - export function newPackageDecl(): JTPackageDecl; - export function newParens(): JTParens; - export function newParenthesizedPattern(): JTParenthesizedPattern; - export function newPrimitiveType(): JTPrimitiveType; - export function newProvides(): JTProvides; - export function newRequires(): JTRequires; - export function newReturn(): JTReturn; - export function newSkip(): JTSkip; - export function newSwitch(): JTSwitch; - export function newSwitchExpression(): JTSwitchExpression; - export function newSynchronized(): JTSynchronized; - export function newThrow(): JTThrow; - export function newTry(): JTTry; - export function newTypeApply(): JTTypeApply; - export function newTypeCast(): JTTypeCast; - export function newTypeIntersection(): JTTypeIntersection; - export function newTypeParameter(): JTTypeParameter; - export function newTypeUnion(): JTTypeUnion; - export function newUnary(): JTUnary; - export function newUses(): JTUses; - export function newVariableDecl(): JTVariableDecl; - export function newWhileLoop(): JTWhileLoop; - export function newWildcard(): JTWildcard; - export function newYield(): JTYield; - - export function transformSync(source: string, options?: TransformOptions): TransformResult; -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * Usage: + * Please put this file along with your project + * and add the following line to your JS/TS files. + * You will get the intellisense in VS Code. + * + * /// + */ + +/// + +enum JTBodyKind { + EXPRESSION, + STATEMENT, +} + +enum JTCaseKind { + STATEMENT, + RULE, +} + +enum JTKind { + AND, // BinaryTree + AND_ASSIGNMENT, // CompoundAssignmentTree + ANNOTATED_TYPE, // AnnotatedTypeTree + ANNOTATION, // AnnotationTree + ANNOTATION_TYPE, // ClassTree + ARRAY_ACCESS, // ArrayAccessTree + ARRAY_TYPE, // ArrayTypeTree + ASSERT, // AssertTree + ASSIGNMENT, // AssignmentTree + BINDING_PATTERN, // BindingPatternTree + BITWISE_COMPLEMENT, // UnaryTree + BLOCK, // BlockTree + BOOLEAN_LITERAL, // LiteralTree + BREAK, // BreakTree + CASE, // CaseTree + CATCH, // CatchTree + CHAR_LITERAL, // LiteralTree + CLASS, // ClassTree + COMPILATION_UNIT, // CompilationUnitTree + CONDITIONAL_AND, // BinaryTree + CONDITIONAL_EXPRESSION, // ConditionalExpressionTree + CONDITIONAL_OR, // BinaryTree + CONTINUE, // ContinueTree + DEFAULT_CASE_LABEL, // DefaultCaseLabelTree + DIVIDE, // BinaryTree + DIVIDE_ASSIGNMENT, // CompoundAssignmentTree + DO_WHILE_LOOP, // DoWhileLoopTree + DOUBLE_LITERAL, // LiteralTree + EMPTY_STATEMENT, // EmptyStatementTree + ENHANCED_FOR_LOOP, // EnhancedForLoopTree + ENUM, // ClassTree + EQUAL_TO, // BinaryTree + ERRONEOUS, // ErroneousTree + EXPORTS, // ExportsTree + EXPRESSION_STATEMENT, // ExpressionStatementTree + EXTENDS_WILDCARD, // WildcardTree + FLOAT_LITERAL, // LiteralTree + FOR_LOOP, // ForLoopTree + GREATER_THAN, // BinaryTree + GREATER_THAN_EQUAL, // BinaryTree + GUARDED_PATTERN, // GuardedPatternTree + IDENTIFIER, // IdentifierTree + IF, // IfTree + IMPORT, // ImportTree + INSTANCE_OF, // InstanceOfTree + INT_LITERAL, // LiteralTree + INTERFACE, // ClassTree + INTERSECTION_TYPE, // IntersectionTypeTree + LABELED_STATEMENT, // LabeledStatementTree + LAMBDA_EXPRESSION, // LambdaExpressionTree + LEFT_SHIFT, // BinaryTree + LEFT_SHIFT_ASSIGNMENT, // CompoundAssignmentTree + LESS_THAN, // BinaryTree + LESS_THAN_EQUAL, // BinaryTree + LOGICAL_COMPLEMENT, // UnaryTree + LONG_LITERAL, // LiteralTree + MEMBER_REFERENCE, // MemberReferenceTree + MEMBER_SELECT, // MemberSelectTree + METHOD, // MethodTree + METHOD_INVOCATION, // MethodInvocationTree + MINUS, // BinaryTree + MINUS_ASSIGNMENT, // CompoundAssignmentTree + MODIFIERS, // ModifiersTree + MODULE, // ModuleTree + MULTIPLY, // BinaryTree + MULTIPLY_ASSIGNMENT, // CompoundAssignmentTree + NEW_ARRAY, // NewArrayTree + NEW_CLASS, // NewClassTree + NOT_EQUAL_TO, // BinaryTree + NULL_LITERAL, // LiteralTree + OPENS, // OpensTree + OR, // BinaryTree + OR_ASSIGNMENT, // CompoundAssignmentTree + OTHER, // null + PACKAGE, // PackageTree + PARAMETERIZED_TYPE, // ParameterizedTypeTree + PARENTHESIZED, // ParenthesizedTree + PARENTHESIZED_PATTERN, // ParenthesizedPatternTree + PLUS, // BinaryTree + PLUS_ASSIGNMENT, // CompoundAssignmentTree + POSTFIX_DECREMENT, // UnaryTree + POSTFIX_INCREMENT, // UnaryTree + PREFIX_DECREMENT, // UnaryTree + PREFIX_INCREMENT, // UnaryTree + PRIMITIVE_TYPE, // PrimitiveTypeTree + PROVIDES, // ProvidesTree + RECORD, // ClassTree + REMAINDER, // BinaryTree + REMAINDER_ASSIGNMENT, // CompoundAssignmentTree + REQUIRES, // RequiresTree + RETURN, // ReturnTree + RIGHT_SHIFT, // BinaryTree + RIGHT_SHIFT_ASSIGNMENT, // CompoundAssignmentTree + STRING_LITERAL, // LiteralTree + SUPER_WILDCARD, // WildcardTree + SWITCH, // SwitchTree + SWITCH_EXPRESSION, // SwitchExpressionTree + SYNCHRONIZED, // SynchronizedTree + THROW, // ThrowTree + TRY, // TryTree + TYPE_ANNOTATION, // AnnotationTree + TYPE_CAST, // TypeCastTree + TYPE_PARAMETER, // TypeParameterTree + UNARY_MINUS, // UnaryTree + UNARY_PLUS, // UnaryTree + UNBOUNDED_WILDCARD, // WildcardTree + UNION_TYPE, // UnionTypeTree + UNSIGNED_RIGHT_SHIFT, // BinaryTree + UNSIGNED_RIGHT_SHIFT_ASSIGNMENT, // CompoundAssignmentTree + USES, // UsesTree + VARIABLE, // VariableTree + WHILE_LOOP, // WhileLoopTree + XOR, // BinaryTree + XOR_ASSIGNMENT, // CompoundAssignmentTree + YIELD, // YieldTree +} + +enum JTModifier { + PUBLIC = 'public', + PROTECTED = 'protected', + PRIVATE = 'private', + ABSTRACT = 'abstract', + DEFAULT = 'default', + STATIC = 'static', + SEALED = 'sealed', + NON_SEALED = 'non-sealed', + FINAL = 'final', + TRANSIENT = 'transient', + VOLATILE = 'volatile', + SYNCHRONIZED = 'synchronized', + NATIVE = 'native', + STRICTFP = 'strictfp', +} + +enum JTReferenceMode { + INVOKE, // Method references + NEW, // Constructor references +} + +enum JTTypeKind { + BOOLEAN, + BYTE, + SHORT, + INT, + LONG, + CHAR, + FLOAT, + DOUBLE, + VOID, + NONE, + NULL, + ARRAY, + DECLARED, + ERROR, + TYPEVAR, + WILDCARD, + PACKAGE, + EXECUTABLE, + OTHER, + UNION, + INTERSECTION, + MODULE, +} + +interface JTAnnotatedType extends JTExpression { + annotations: JTAnnotation[]; + underlyingType: JTExpression; +} + +interface JTAnnotation extends JTExpression { + arguments: JTExpression[]; + annotationType: JTTree; +} + +interface JTArrayAccess extends JTExpression { + expression: JTExpression; + index: JTExpression; +} + +interface JTArrayType extends JTExpression { + type: JTExpression; +} + +interface JTAssert extends JTExpression { + condition: JTExpression; + detail: JTExpression; +} + +interface JTAssign extends JTExpression { + expression: JTExpression; + variable: JTExpression; +} + +interface JTAssignOp extends JTOperatorExpression { + expression: JTExpression; + kind: JTKind.AND_ASSIGNMENT | JTKind.DIVIDE_ASSIGNMENT | JTKind.LEFT_SHIFT_ASSIGNMENT | JTKind.MINUS_ASSIGNMENT | JTKind.MULTIPLY_ASSIGNMENT | JTKind.OR_ASSIGNMENT | JTKind.PLUS_ASSIGNMENT | JTKind.REMAINDER_ASSIGNMENT | JTKind.RIGHT_SHIFT_ASSIGNMENT | JTKind.UNSIGNED_RIGHT_SHIFT_ASSIGNMENT | JTKind.XOR_ASSIGNMENT; + variable: JTExpression; +} + +interface JTBinary extends JTOperatorExpression { + kind: JTKind.AND | JTKind.CONDITIONAL_AND | JTKind.CONDITIONAL_OR | JTKind.DIVIDE | JTKind.EQUAL_TO | JTKind.GREATER_THAN | JTKind.GREATER_THAN_EQUAL | JTKind.LEFT_SHIFT | JTKind.LESS_THAN | JTKind.LESS_THAN_EQUAL | JTKind.MINUS | JTKind.MULTIPLY | JTKind.NOT_EQUAL_TO | JTKind.OR | JTKind.PLUS | JTKind.REMAINDER | JTKind.RIGHT_SHIFT | JTKind.UNSIGNED_RIGHT_SHIFT | JTKind.XOR; + leftOperand: JTExpression; + rightOperand: JTExpression; +} + +interface JTBindingPattern extends JTPattern { + variable: JTVariableDecl; +} + +interface JTBlock extends JTStatement { + statements: JTStatement[]; + static: boolean; +} + +interface JTBreak extends JTStatement { + label: JTName; +} + +interface JTCaseLabel> extends JTTree { +} + +interface JTCase extends JTStatement { + body: JTTree[]; + caseKind: JTCaseKind; + labels: JTCaseLabel; + statements: JTExpression[]; +} + +interface JTCatch extends JTTree { + block: JTBlock; + parameter: JTVariableDecl; +} + +interface JTCharacter { + readonly value: string; +} + +interface JTClassDecl extends JTStatement { + extendsClause: JTExpression; + implementsClauses: JTExpression[]; + kind: JTKind.ANNOTATION_TYPE | JTKind.CLASS | JTKind.ENUM | JTKind.INTERFACE | JTKind.RECORD; + members: JTTree[]; + modifiers: JTModifiers; + permitsClauses: JTExpression[]; + simpleName: JTName; + typeParameters: JTTypeParameter[]; +} + +interface JTCompilationUnit extends JTTree { + imports: JTImport[]; + module: JTModuleDecl; + package: JTPackageDecl; + readonly sourceFile: string; + typeDecls: JTTree[]; +} + +interface JTConditional extends JTPolyExpression { + condition: JTExpression; + falseExpression: JTExpression; + trueExpression: JTExpression; +} + +interface JTContinue extends JTStatement { + label: JTName; +} + +interface JTDefaultCaseLabel extends JTCaseLabel { +} + +interface JTDirective> extends JTTree { +} + +interface JTDoWhileLoop extends JTStatement { + condition: JTExpression; + statement: JTStatement; +} + +interface JTSkip extends JTStatement { +} + +interface JTEnhancedForLoop extends JTStatement { + expression: JTExpression; + statement: JTStatement; + variable: JTVariableDecl; +} + +interface JTErroneous extends JTExpression { + errorTree: JTTree; +} + +interface JTExports extends JTDirective { + moduleNames: JTExpression; + packageName: JTExpression; +} + +interface JTExpression> extends JTCaseLabel { +} + +interface JTExpressionStatement extends JTStatement { + expression: JTExpression; +} + +interface JTFloat { + readonly value: number; +} + +interface JTForLoop extends JTStatement { + condition: JTExpression; + initializer: JTStatement[]; + statement: JTStatement; + update: JTExpressionStatement[]; +} + +interface JTFunctionalExpression> extends JTPolyExpression { + body: JTTree; + bodyKind: JTBodyKind; + parameters: JTVariableDecl[]; +} + +interface JTGuardedPattern extends JTPattern { + expression: JTExpression; + pattern: JTPattern; +} + +interface JTFieldAccess extends JTExpression { + expression: JTExpression; + identifier: JTName; +} + +interface JTIdent extends JTExpression { + name: JTName; +} + +interface JTImport extends JTTree { + qualifiedIdentifier: JTTree; + staticImport: boolean; +} + +interface JTIf extends JTStatement { + condition: JTExpression; + elseStatement: JTStatement; + thenStatement: JTStatement; +} + +interface JTInstanceOf extends JTExpression { + expression: JTExpression; + pattern: JTTree; +} + +interface JTLabeledStatement extends JTStatement { + label: JTName; + statement: JTStatement; +} + +interface JTLambda extends JTFunctionalExpression { + body: JTTree; + bodyKind: JTBodyKind; + parameters: JTVariableDecl[]; +} + +interface JTLiteral extends JTExpression { + kind: JTKind.BOOLEAN_LITERAL | JTKind.CHAR_LITERAL | JTKind.DOUBLE_LITERAL | JTKind.FLOAT_LITERAL | JTKind.INT_LITERAL | JTKind.LONG_LITERAL | JTKind.NULL_LITERAL | JTKind.STRING_LITERAL; + value: number | string | boolean | JTFloat | JTCharacter | null; +} + +interface JTMemberReference extends JTFunctionalExpression { + mode: JTReferenceMode; + name: JTName; + qualifiedExpression: JTExpression; + typeArguments: JTExpression[]; +} + +interface JTMethodDecl extends JTTree { + body: JTBlock; + defaultValue: JTExpression; + modifiers: JTModifiers; + name: JTName; + parameters: JTVariableDecl[]; + receiverParameter: JTVariableDecl; + returnType: JTExpression; + throwExpressions: JTExpression[]; + typeParameters: JTTypeParameter[]; +} + +interface JTMethodInvocation extends JTPolyExpression { + arguments: JTExpression[]; + methodSelect: JTExpression; + typeArguments: JTExpression[]; +} + +interface JTModifiers extends JTTree { + annotations: JTAnnotation[]; + flags: JTModifier[]; +} + +interface JTModuleDecl extends JTTree { + annotations: JTAnnotation[]; + name: JTExpression; + directives: JTDirective; +} + +interface JTNewArray extends JTExpression { + annotations: JTAnnotation[]; + dimAnnotations: JTAnnotation[][]; + dimensions: JTExpression[]; + initializers: JTExpression[]; + type: JTExpression; +} + +interface JTNewClass extends JTPolyExpression { + arguments: JTExpression[]; + classBody: JTClassDecl; + enclosingExpression: JTExpression; + identifier: JTExpression; + typeArguments: JTExpression[]; +} + +interface JTOpens extends JTDirective { + moduleNames: JTExpression[]; + packageName: JTExpression; +} + +interface JTName { + value: string; +} + +interface JTOperatorExpression> extends JTExpression { +} + +interface JTPackageDecl extends JTTree { + annotations: JTAnnotation[]; + packageName: JTExpression; +} + +interface JTParens extends JTExpression { + expression: JTExpression; +} + +interface JTParenthesizedPattern extends JTPattern { + pattern: JTPattern; +} + +interface JTPattern> extends JTCaseLabel { +} + +interface JTPolyExpression> extends JTExpression { +} + +interface JTPrimitiveType extends JTExpression { + primitiveTypeKind: JTTypeKind; +} + +interface JTProvides extends JTDirective { + implementationNames: JTExpression[]; + serviceName: JTExpression; +} + +interface JTRequires extends JTDirective { + moduleName: JTExpression; + static: boolean; + transitive: boolean; +} + +interface JTReturn extends JTStatement { + expression: JTExpression; +} + +interface JTSwitch extends JTStatement { + cases: JTCase[]; + expression: JTExpression; +} + +interface JTSwitchExpression extends JTPolyExpression { + cases: JTCase[]; + expression: JTExpression; +} + +interface JTSynchronized extends JTStatement { + block: JTBlock; + expression: JTExpression; +} + +interface JTStatement> extends JTTree { +} + +interface JTThrow extends JTStatement { + expression: JTExpression; +} + +interface JTTry extends JTStatement { + block: JTBlock; + catches: JTCatch[]; + finallyBlock: JTBlock; + resources: JTTree[]; +} + +interface JTTree> { + readonly className: string; + readonly classSimpleName: string; + readonly kind: JTKind; + readonly parentTree: JTTree; + isActionChange(): boolean; + isActionIgnore(): boolean; + isActionNoChange(): boolean; + setActionChange(): boolean; + setActionIgnore(): boolean; + setActionNoChange(): boolean; + toString(): string; +} + +interface JTTypeApply extends JTExpression { + type: JTExpression; + typeArguments: JTExpression[]; +} + +interface JTTypeCast extends JTExpression { + expression: JTExpression; + type: JTTree; +} + +interface JTTypeIntersection extends JTExpression { + bounds: JTExpression; +} + +interface JTTypeParameter extends JTTree { + annotations: JTAnnotation[]; + bound: JTExpression; + name: JTName; +} + +interface JTTypeUnion extends JTExpression { + typeAlternatives: JTExpression; +} + +interface JTUnary extends JTOperatorExpression { + expression: JTExpression; + kind: JTKind.BITWISE_COMPLEMENT | JTKind.LOGICAL_COMPLEMENT | JTKind.POSTFIX_DECREMENT | JTKind.POSTFIX_INCREMENT | JTKind.PREFIX_DECREMENT | JTKind.PREFIX_INCREMENT | JTKind.UNARY_MINUS | JTKind.UNARY_PLUS; +} + +interface JTUses extends JTDirective { + serviceName: JTExpression; +} + +interface JTVariableDecl extends JTStatement { + initializer: JTExpression; + modifiers: JTModifiers; + name: JTName; + nameExpression: JTExpression; + type: JTExpression; +} + +interface JTWhileLoop extends JTStatement { + condition: JTExpression; + statement: JTStatement; +} + +interface JTWildcard extends JTExpression { + bound: JTTree; + kind: JTKind.EXTENDS_WILDCARD | JTKind.SUPER_WILDCARD | JTKind.UNBOUNDED_WILDCARD; +} + +interface JTYield extends JTStatement { + value: JTExpression; +} + +interface TransformOptions { + /** + * Include the AST in the returned object + * + * Default: `false` + */ + ast?: boolean | null | undefined; + /** + * Enable code generation + * + * Default: `true` + */ + code?: boolean | null | undefined; + /** + * Context for evaluation + * + * Default: undefined + */ + context?: object | null | undefined; + /** + * Specify the file name in source type 'string' mode + * + * Default: `undefined` + */ + fileName?: string | null | undefined; + /** + * List of plugins to load and use + * + * Default: `[]` + */ + plugins?: TransformOptionsPlugin[] | null | undefined; + /** + * Type of the source + * + * Default: `file` + */ + sourceType?: 'string' | 'file'; + /** + * Transform style + * + * Default: null + */ + style?: TransformOptionStyle; +} + +interface TransformOptionsPlugin { + visitor: TransformOptionsPluginVisitor; +} + +interface TransformOptionsPluginVisitor { + AnnotatedType(node: JTAnnotatedType, context?: object | null | undefined): void; + Annotation(node: JTAnnotation, context?: object | null | undefined): void; + ArrayAccess(node: JTArrayAccess, context?: object | null | undefined): void; + ArrayType(node: JTArrayType, context?: object | null | undefined): void; + Assert(node: JTAssert, context?: object | null | undefined): void; + Assignment(node: JTAssign, context?: object | null | undefined): void; + Binary(node: JTBinary, context?: object | null | undefined): void; + BindingPattern(node: JTBindingPattern, context?: object | null | undefined): void; + Block(node: JTBlock, context?: object | null | undefined): void; + Break(node: JTBreak, context?: object | null | undefined): void; + Case(node: JTCase, context?: object | null | undefined): void; + Catch(node: JTCatch, context?: object | null | undefined): void; + Class(node: JTClassDecl, context?: object | null | undefined): void; + CompilationUnit(node: JTCompilationUnit, context?: object | null | undefined): void; + CompoundAssignment(node: JTAssignOp, context?: object | null | undefined): void; + ConditionalExpression(node: JTConditional, context?: object | null | undefined): void; + Continue(node: JTContinue, context?: object | null | undefined): void; + DefaultCaseLabel(node: JTDefaultCaseLabel, context?: object | null | undefined): void; + DoWhileLoop(node: JTDoWhileLoop, context?: object | null | undefined): void; + EmptyStatement(node: JTSkip, context?: object | null | undefined): void; + EnhancedForLoop(node: JTEnhancedForLoop, context?: object | null | undefined): void; + Erroneous(node: JTErroneous, context?: object | null | undefined): void; + Exports(node: JTExports, context?: object | null | undefined): void; + ExpressionStatement(node: JTExpressionStatement, context?: object | null | undefined): void; + ForLoop(node: JTForLoop, context?: object | null | undefined): void; + GuardedPattern(node: JTGuardedPattern, context?: object | null | undefined): void; + Identifier(node: JTIdent, context?: object | null | undefined): void; + If(node: JTIf, context?: object | null | undefined): void; + Import(node: JTImport, context?: object | null | undefined): void; + InstanceOf(node: JTInstanceOf, context?: object | null | undefined): void; + IntersectionType(node: JTTypeIntersection, context?: object | null | undefined): void; + LabeledStatement(node: JTLabeledStatement, context?: object | null | undefined): void; + LambdaExpression(node: JTLambda, context?: object | null | undefined): void; + Literal(node: JTLiteral, context?: object | null | undefined): void; + MemberReference(node: JTMemberReference, context?: object | null | undefined): void; + MemberSelect(node: JTFieldAccess, context?: object | null | undefined): void; + Method(node: JTMethodDecl, context?: object | null | undefined): void; + MethodInvocation(node: JTMethodInvocation, context?: object | null | undefined): void; + Modifiers(node: JTModifiers, context?: object | null | undefined): void; + Module(node: JTModuleDecl, context?: object | null | undefined): void; + NewArray(node: JTNewArray, context?: object | null | undefined): void; + NewClass(node: JTNewClass, context?: object | null | undefined): void; + Opens(node: JTOpens, context?: object | null | undefined): void; + Other(node: JTTree, context?: object | null | undefined): void; + Package(node: JTPackageDecl, context?: object | null | undefined): void; + ParameterizedType(node: JTTypeApply, context?: object | null | undefined): void; + Parenthesized(node: JTParens, context?: object | null | undefined): void; + ParenthesizedPattern(node: JTParenthesizedPattern, context?: object | null | undefined): void; + PrimitiveType(node: JTPrimitiveType, context?: object | null | undefined): void; + Provides(node: JTProvides, context?: object | null | undefined): void; + Requires(node: JTRequires, context?: object | null | undefined): void; + Return(node: JTReturn, context?: object | null | undefined): void; + Scan(node: JTTree, context?: object | null | undefined): void; + Switch(node: JTSwitch, context?: object | null | undefined): void; + SwitchExpression(node: JTSwitchExpression, context?: object | null | undefined): void; + Synchronized(node: JTSynchronized, context?: object | null | undefined): void; + Throw(node: JTThrow, context?: object | null | undefined): void; + Try(node: JTTry, context?: object | null | undefined): void; + TypeCast(node: JTTypeCast, context?: object | null | undefined): void; + TypeParameter(node: JTTypeParameter, context?: object | null | undefined): void; + Unary(node: JTUnary, context?: object | null | undefined): void; + UnionType(node: JTTypeUnion, context?: object | null | undefined): void; + Uses(node: JTUses, context?: object | null | undefined): void; + Variable(node: JTVariableDecl, context?: object | null | undefined): void; + WhileLoop(node: JTWhileLoop, context?: object | null | undefined): void; + Wildcard(node: JTWildcard, context?: object | null | undefined): void; + Yield(node: JTYield, context?: object | null | undefined): void; +} + +interface TransformOptionStyle { + /** + * Size of the continuation indent + * + * Default: 8 + */ + continuationIndentSize?: number | null | undefined; + /** + * Size of the indent + * + * Default: 4 + */ + indentSize?: number | null | undefined; + /** + * Preserve the copyrights or not + * + * Default: true + */ + preserveCopyrights?: boolean | null | undefined; + /** + * Style type + * + * Default: 'standard' + */ + type?: 'compact' | 'standard' | null | undefined; + /** + * Wrap if the line length is greater than + * + * Default: 120 + */ + wordWrapColumn?: number | null | undefined; +} + +interface TransformResult { + ast?: JTCompilationUnit | undefined; + code?: string | undefined; +} + +declare namespace jaspiler { + export const argv: Array; + + export function createCharacter(value: string): JTCharacter; + export function createFieldAccess(...values: string[]): JTFieldAccess; + export function createFloat(value: string): JTFloat; + export function createIdent(value: string): JTIdent; + export function createLiteral(value: string): JTLiteral; + export function createName(value: string): JTName; + + export function newAnnotatedType(): JTAnnotatedType; + export function newAnnotation(): JTAnnotation; + export function newArrayAccess(): JTArrayAccess; + export function newArrayType(): JTArrayType; + export function newAssert(): JTAssert; + export function newAssign(): JTAssign; + export function newAssignOp(): JTAssignOp; + export function newBinary(): JTBinary; + export function newBindingPattern(): JTBindingPattern; + export function newBlock(): JTBlock; + export function newBreak(): JTBreak; + export function newCase(): JTCase; + export function newCatch(): JTCatch; + export function newClassDecl(): JTClassDecl; + export function newConditional(): JTConditional; + export function newContinue(): JTContinue; + export function newDefaultCaseLabel(): JTDefaultCaseLabel; + export function newDoWhileLoop(): JTDoWhileLoop; + export function newEnhancedForLoop(): JTEnhancedForLoop; + export function newErroneous(): JTErroneous; + export function newExports(): JTExports; + export function newExpressionStatement(): JTExpressionStatement; + export function newFieldAccess(): JTFieldAccess; + export function newForLoop(): JTForLoop; + export function newGuardedPattern(): JTGuardedPattern; + export function newIdent(): JTIdent; + export function newIf(): JTIf; + export function newImport(): JTImport; + export function newInstanceOf(): JTInstanceOf; + export function newLabeledStatement(): JTLabeledStatement; + export function newLambda(): JTLambda; + export function newLiteral(): JTLiteral; + export function newMemberReference(): JTMemberReference; + export function newMethodDecl(): JTMethodDecl; + export function newMethodInvocation(): JTMethodInvocation; + export function newModifiers(): JTModifiers; + export function newModuleDecl(): JTModuleDecl; + export function newNewArray(): JTNewArray; + export function newNewClass(): JTNewClass; + export function newOpens(): JTOpens; + export function newPackageDecl(): JTPackageDecl; + export function newParens(): JTParens; + export function newParenthesizedPattern(): JTParenthesizedPattern; + export function newPrimitiveType(): JTPrimitiveType; + export function newProvides(): JTProvides; + export function newRequires(): JTRequires; + export function newReturn(): JTReturn; + export function newSkip(): JTSkip; + export function newSwitch(): JTSwitch; + export function newSwitchExpression(): JTSwitchExpression; + export function newSynchronized(): JTSynchronized; + export function newThrow(): JTThrow; + export function newTry(): JTTry; + export function newTypeApply(): JTTypeApply; + export function newTypeCast(): JTTypeCast; + export function newTypeIntersection(): JTTypeIntersection; + export function newTypeParameter(): JTTypeParameter; + export function newTypeUnion(): JTTypeUnion; + export function newUnary(): JTUnary; + export function newUses(): JTUses; + export function newVariableDecl(): JTVariableDecl; + export function newWhileLoop(): JTWhileLoop; + export function newWildcard(): JTWildcard; + export function newYield(): JTYield; + + export function transformSync(source: string, options?: TransformOptions): TransformResult; +} diff --git a/scripts/node/jaspiler/jaspiler.js b/scripts/node/jaspiler/jaspiler.js index 53cbc61..b34a7aa 100644 --- a/scripts/node/jaspiler/jaspiler.js +++ b/scripts/node/jaspiler/jaspiler.js @@ -1,368 +1,368 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Usage: - * Please put this file along with your project - * and add the following lines selectively to your JS files. - * You will get the intellisense in VS Code. - * - * const { JTBodyKind, JTCaseKind, JTKind, JTModifier, JTReferenceMode, JTTypeKind } = require('./jaspiler/jaspiler'); - * const { PluginContractIgnore, PluginContractChangeMethod } = require('./jaspiler/jaspiler'); - */ - -const vm = require('vm'); - -const JTBodyKind = Object.freeze({ - EXPRESSION: 'EXPRESSION', - STATEMENT: 'STATEMENT', -}); - -const JTCaseKind = Object.freeze({ - STATEMENT: 'STATEMENT', - RULE: 'RULE', -}); - -const JTKind = Object.freeze({ - AND: 'AND', // BinaryTree - AND_ASSIGNMENT: 'AND_ASSIGNMENT', // CompoundAssignmentTree - ANNOTATED_TYPE: 'ANNOTATED_TYPE', // AnnotatedTypeTree - ANNOTATION: 'ANNOTATION', // AnnotationTree - ANNOTATION_TYPE: 'ANNOTATION_TYPE', // ClassTree - ARRAY_ACCESS: 'ARRAY_ACCESS', // ArrayAccessTree - ARRAY_TYPE: 'ARRAY_TYPE', // ArrayTypeTree - ASSERT: 'ASSERT', // AssertTree - ASSIGNMENT: 'ASSIGNMENT', // AssignmentTree - BINDING_PATTERN: 'BINDING_PATTERN', // BindingPatternTree - BITWISE_COMPLEMENT: 'BITWISE_COMPLEMENT', // UnaryTree - BLOCK: 'BLOCK', // BlockTree - BOOLEAN_LITERAL: 'BOOLEAN_LITERAL', // LiteralTree - BREAK: 'BREAK', // BreakTree - CASE: 'CASE', // CaseTree - CATCH: 'CATCH', // CatchTree - CHAR_LITERAL: 'CHAR_LITERAL', // LiteralTree - CLASS: 'CLASS', // ClassTree - COMPILATION_UNIT: 'COMPILATION_UNIT', // CompilationUnitTree - CONDITIONAL_AND: 'CONDITIONAL_AND', // BinaryTree - CONDITIONAL_EXPRESSION: 'CONDITIONAL_EXPRESSION', // ConditionalExpressionTree - CONDITIONAL_OR: 'CONDITIONAL_OR', // BinaryTree - CONTINUE: 'CONTINUE', // ContinueTree - DEFAULT_CASE_LABEL: 'DEFAULT_CASE_LABEL', // DefaultCaseLabelTree - DIVIDE: 'DIVIDE', // BinaryTree - DIVIDE_ASSIGNMENT: 'DIVIDE_ASSIGNMENT', // CompoundAssignmentTree - DO_WHILE_LOOP: 'DO_WHILE_LOOP', // DoWhileLoopTree - DOUBLE_LITERAL: 'DOUBLE_LITERAL', // LiteralTree - EMPTY_STATEMENT: 'EMPTY_STATEMENT', // EmptyStatementTree - ENHANCED_FOR_LOOP: 'ENHANCED_FOR_LOOP', // EnhancedForLoopTree - ENUM: 'ENUM', // ClassTree - EQUAL_TO: 'EQUAL_TO', // BinaryTree - ERRONEOUS: 'ERRONEOUS', // ErroneousTree - EXPORTS: 'EXPORTS', // ExportsTree - EXPRESSION_STATEMENT: 'EXPRESSION_STATEMENT', // ExpressionStatementTree - EXTENDS_WILDCARD: 'EXTENDS_WILDCARD', // WildcardTree - FLOAT_LITERAL: 'FLOAT_LITERAL', // LiteralTree - FOR_LOOP: 'FOR_LOOP', // ForLoopTree - GREATER_THAN: 'GREATER_THAN', // BinaryTree - GREATER_THAN_EQUAL: 'GREATER_THAN_EQUAL', // BinaryTree - GUARDED_PATTERN: 'GUARDED_PATTERN', // GuardedPatternTree - IDENTIFIER: 'IDENTIFIER', // IdentifierTree - IF: 'IF', // IfTree - IMPORT: 'IMPORT', // ImportTree - INSTANCE_OF: 'INSTANCE_OF', // InstanceOfTree - INT_LITERAL: 'INT_LITERAL', // LiteralTree - INTERFACE: 'INTERFACE', // ClassTree - INTERSECTION_TYPE: 'INTERSECTION_TYPE', // IntersectionTypeTree - LABELED_STATEMENT: 'LABELED_STATEMENT', // LabeledStatementTree - LAMBDA_EXPRESSION: 'LAMBDA_EXPRESSION', // LambdaExpressionTree - LEFT_SHIFT: 'LEFT_SHIFT', // BinaryTree - LEFT_SHIFT_ASSIGNMENT: 'LEFT_SHIFT_ASSIGNMENT', // CompoundAssignmentTree - LESS_THAN: 'LESS_THAN', // BinaryTree - LESS_THAN_EQUAL: 'LESS_THAN_EQUAL', // BinaryTree - LOGICAL_COMPLEMENT: 'LOGICAL_COMPLEMENT', // UnaryTree - LONG_LITERAL: 'LONG_LITERAL', // LiteralTree - MEMBER_REFERENCE: 'MEMBER_REFERENCE', // MemberReferenceTree - MEMBER_SELECT: 'MEMBER_SELECT', // MemberSelectTree - METHOD: 'METHOD', // MethodTree - METHOD_INVOCATION: 'METHOD_INVOCATION', // MethodInvocationTree - MINUS: 'MINUS', // BinaryTree - MINUS_ASSIGNMENT: 'MINUS_ASSIGNMENT', // CompoundAssignmentTree - MODIFIERS: 'MODIFIERS', // ModifiersTree - MODULE: 'MODULE', // ModuleTree - MULTIPLY: 'MULTIPLY', // BinaryTree - MULTIPLY_ASSIGNMENT: 'MULTIPLY_ASSIGNMENT', // CompoundAssignmentTree - NEW_ARRAY: 'NEW_ARRAY', // NewArrayTree - NEW_CLASS: 'NEW_CLASS', // NewClassTree - NOT_EQUAL_TO: 'NOT_EQUAL_TO', // BinaryTree - NULL_LITERAL: 'NULL_LITERAL', // LiteralTree - OPENS: 'OPENS', // OpensTree - OR: 'OR', // BinaryTree - OR_ASSIGNMENT: 'OR_ASSIGNMENT', // CompoundAssignmentTree - OTHER: 'OTHER', // null - PACKAGE: 'PACKAGE', // PackageTree - PARAMETERIZED_TYPE: 'PARAMETERIZED_TYPE', // ParameterizedTypeTree - PARENTHESIZED: 'PARENTHESIZED', // ParenthesizedTree - PARENTHESIZED_PATTERN: 'PARENTHESIZED_PATTERN', // ParenthesizedPatternTree - PLUS: 'PLUS', // BinaryTree - PLUS_ASSIGNMENT: 'PLUS_ASSIGNMENT', // CompoundAssignmentTree - POSTFIX_DECREMENT: 'POSTFIX_DECREMENT', // UnaryTree - POSTFIX_INCREMENT: 'POSTFIX_INCREMENT', // UnaryTree - PREFIX_DECREMENT: 'PREFIX_DECREMENT', // UnaryTree - PREFIX_INCREMENT: 'PREFIX_INCREMENT', // UnaryTree - PRIMITIVE_TYPE: 'PRIMITIVE_TYPE', // PrimitiveTypeTree - PROVIDES: 'PROVIDES', // ProvidesTree - RECORD: 'RECORD', // ClassTree - REMAINDER: 'REMAINDER', // BinaryTree - REMAINDER_ASSIGNMENT: 'REMAINDER_ASSIGNMENT', // CompoundAssignmentTree - REQUIRES: 'REQUIRES', // RequiresTree - RETURN: 'RETURN', // ReturnTree - RIGHT_SHIFT: 'RIGHT_SHIFT', // BinaryTree - RIGHT_SHIFT_ASSIGNMENT: 'RIGHT_SHIFT_ASSIGNMENT', // CompoundAssignmentTree - STRING_LITERAL: 'STRING_LITERAL', // LiteralTree - SUPER_WILDCARD: 'SUPER_WILDCARD', // WildcardTree - SWITCH: 'SWITCH', // SwitchTree - SWITCH_EXPRESSION: 'SWITCH_EXPRESSION', // SwitchExpressionTree - SYNCHRONIZED: 'SYNCHRONIZED', // SynchronizedTree - THROW: 'THROW', // ThrowTree - TRY: 'TRY', // TryTree - TYPE_ANNOTATION: 'TYPE_ANNOTATION', // AnnotationTree - TYPE_CAST: 'TYPE_CAST', // TypeCastTree - TYPE_PARAMETER: 'TYPE_PARAMETER', // TypeParameterTree - UNARY_MINUS: 'UNARY_MINUS', // UnaryTree - UNARY_PLUS: 'UNARY_PLUS', // UnaryTree - UNBOUNDED_WILDCARD: 'UNBOUNDED_WILDCARD', // WildcardTree - UNION_TYPE: 'UNION_TYPE', // UnionTypeTree - UNSIGNED_RIGHT_SHIFT: 'UNSIGNED_RIGHT_SHIFT', // BinaryTree - UNSIGNED_RIGHT_SHIFT_ASSIGNMENT: 'UNSIGNED_RIGHT_SHIFT_ASSIGNMENT', // CompoundAssignmentTree - USES: 'USES', // UsesTree - VARIABLE: 'VARIABLE', // VariableTree - WHILE_LOOP: 'WHILE_LOOP', // WhileLoopTree - XOR: 'XOR', // BinaryTree - XOR_ASSIGNMENT: 'XOR_ASSIGNMENT', // CompoundAssignmentTree - YIELD: 'YIELD', // YieldTree -}); - -const JTModifier = Object.freeze({ - PUBLIC: 'public', - PROTECTED: 'protected', - PRIVATE: 'private', - ABSTRACT: 'abstract', - DEFAULT: 'default', - STATIC: 'static', - SEALED: 'sealed', - NON_SEALED: 'non-sealed', - FINAL: 'final', - TRANSIENT: 'transient', - VOLATILE: 'volatile', - SYNCHRONIZED: 'synchronized', - NATIVE: 'native', - STRICTFP: 'strictfp', -}); - -const JTReferenceMode = Object.freeze({ - INVOKE: 'INVOKE', - NEW: 'NEW', -}); - -const JTTypeKind = Object.freeze({ - BOOLEAN: 'BOOLEAN', - BYTE: 'BYTE', - SHORT: 'SHORT', - INT: 'INT', - LONG: 'LONG', - CHAR: 'CHAR', - FLOAT: 'FLOAT', - DOUBLE: 'DOUBLE', - VOID: 'VOID', - NONE: 'NONE', - NULL: 'NULL', - ARRAY: 'ARRAY', - DECLARED: 'DECLARED', - ERROR: 'ERROR', - TYPEVAR: 'TYPEVAR', - WILDCARD: 'WILDCARD', - PACKAGE: 'PACKAGE', - EXECUTABLE: 'EXECUTABLE', - OTHER: 'OTHER', - UNION: 'UNION', - INTERSECTION: 'INTERSECTION', - MODULE: 'MODULE', -}); - -function canBeIgnoredByAnnotations(annotations, context) { - const annotation = findAnnotation(annotations, 'JaspilerContract.Ignore'); - return evaluateAnnotationAttribute(annotation, context, 'condition', true, false); -} - -function evaluateAnnotationAttribute(annotation, context, attributeName, defaultValueForAttributeFound, defaultValueForAttributeNotFound) { - if (annotation) { - const attributeValue = getAnnotationAttributeValueByName(annotation, attributeName); - if (attributeValue && attributeValue.kind == JTKind.STRING_LITERAL) { - const script = new vm.Script(attributeValue.value); - if (!(context instanceof Object)) { - context = {}; - } - if (!vm.isContext(context)) { - vm.createContext(context); - } - return script.runInContext(context); - } - return defaultValueForAttributeFound; - } - return defaultValueForAttributeNotFound; -} - -function findAnnotation(annotations, annotationName) { - if (annotations) { - return annotations.find(annotation => annotation.annotationType.toString() == annotationName); - } - return undefined; -} - -function getAnnotationAttributeValueByName(annotation, attributeName) { - if (annotation) { - const args = annotation.arguments; - for (let i = 0; i < args.length; ++i) { - const arg = args[i]; - if (arg.kind == JTKind.ASSIGNMENT && arg.variable.toString() == attributeName) { - return arg.expression; - } - } - } - return undefined; -} - -function getChangeInstructionByAnnotations(annotations, context) { - const annotation = findAnnotation(annotations, 'JaspilerContract.Change'); - if (evaluateAnnotationAttribute(annotation, context, 'condition', true, false)) { - return evaluateAnnotationAttribute(annotation, context, 'instruction', undefined, undefined); - } - return undefined; -} - -const PluginContractIgnore = Object.freeze({ - visitor: Object.freeze({ - AnnotatedType(node, context) { - if (canBeIgnoredByAnnotations(node.annotations, context)) { - node.setActionIgnore(); - } - }, - CompilationUnit(node, context) { - const typeDeclIgnored = node.typeDecls.find(typeDecl => { - if (typeDecl.classSimpleName == 'JTClassDecl') { - const modifiers = typeDecl.modifiers; - if (modifiers && modifiers.flags.includes(JTModifier.PUBLIC)) { - return canBeIgnoredByAnnotations(modifiers.annotations, context); - } - } - return false; - }); - if (typeDeclIgnored) { - node.setActionIgnore(); - } - }, - Class(node, context) { - if (canBeIgnoredByAnnotations(node.modifiers?.annotations, context)) { - node.setActionIgnore(); - } - }, - Method(node, context) { - if (canBeIgnoredByAnnotations(node.modifiers?.annotations, context)) { - node.setActionIgnore(); - } - }, - Module(node, context) { - if (canBeIgnoredByAnnotations(node.annotations, context)) { - node.setActionIgnore(); - } - }, - NewArray(node, context) { - if (canBeIgnoredByAnnotations(node.annotations, context)) { - node.setActionIgnore(); - } - }, - Package(node, context) { - if (canBeIgnoredByAnnotations(node.annotations, context)) { - node.setActionIgnore(); - } - }, - TypeParameter(node, context) { - if (canBeIgnoredByAnnotations(node.annotations, context)) { - node.setActionIgnore(); - } - }, - Variable(node, context) { - if (canBeIgnoredByAnnotations(node.modifiers?.annotations, context)) { - node.setActionIgnore(); - } - }, - }), -}); - -const PluginContractChangeMethod = Object.freeze({ - visitor: Object.freeze({ - Method(node, context) { - const instruction = getChangeInstructionByAnnotations(node.modifiers?.annotations, context); - if (instruction) { - if (instruction.type == 'clear') { - const body = node.body; - // There is no need to clear the method if the body is absent. - if (body) { - const returnType = node.returnType; - const blockStatement = jaspiler.newBlock(); - const isPrimitiveType = returnType.classSimpleName == 'JTPrimitiveType'; - const primitiveTypeKind = isPrimitiveType ? returnType.primitiveTypeKind : null; - if (!isPrimitiveType || primitiveTypeKind != JTTypeKind.VOID) { - const returnStatement = jaspiler.newReturn(); - const literalExpression = jaspiler.createLiteral(null); - if (isPrimitiveType) { - let kind = JTKind.NULL_LITERAL; - switch (primitiveTypeKind) { - case JTTypeKind.BOOLEAN: kind = JTKind.BOOLEAN_LITERAL; break; - case JTTypeKind.CHAR: kind = JTKind.CHAR_LITERAL; break; - case JTTypeKind.DOUBLE: kind = JTKind.DOUBLE_LITERAL; break; - case JTTypeKind.FLOAT: kind = JTKind.FLOAT_LITERAL; break; - case JTTypeKind.INT: kind = JTKind.INT_LITERAL; break; - case JTTypeKind.LONG: kind = JTKind.LONG_LITERAL; break; - case JTTypeKind.NULL: kind = JTKind.NULL_LITERAL; break; - } - literalExpression.kind = kind; - } - returnStatement.expression = literalExpression; - blockStatement.statements = [returnStatement]; - } - node.body = blockStatement; - } - } - } - }, - }), -}); - -module.exports = Object.freeze({ - helpers: Object.freeze({ - evaluateAnnotationAttribute: evaluateAnnotationAttribute, - findAnnotation: findAnnotation, - getAnnotationAttributeValueByName: getAnnotationAttributeValueByName, - }), - JTBodyKind: JTBodyKind, - JTCaseKind: JTCaseKind, - JTKind: JTKind, - JTModifier: JTModifier, - JTReferenceMode: JTReferenceMode, - JTTypeKind: JTTypeKind, - PluginContractIgnore: PluginContractIgnore, - PluginContractChangeMethod: PluginContractChangeMethod, -}); +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * Usage: + * Please put this file along with your project + * and add the following lines selectively to your JS files. + * You will get the intellisense in VS Code. + * + * const { JTBodyKind, JTCaseKind, JTKind, JTModifier, JTReferenceMode, JTTypeKind } = require('./jaspiler/jaspiler'); + * const { PluginContractIgnore, PluginContractChangeMethod } = require('./jaspiler/jaspiler'); + */ + +const vm = require('vm'); + +const JTBodyKind = Object.freeze({ + EXPRESSION: 'EXPRESSION', + STATEMENT: 'STATEMENT', +}); + +const JTCaseKind = Object.freeze({ + STATEMENT: 'STATEMENT', + RULE: 'RULE', +}); + +const JTKind = Object.freeze({ + AND: 'AND', // BinaryTree + AND_ASSIGNMENT: 'AND_ASSIGNMENT', // CompoundAssignmentTree + ANNOTATED_TYPE: 'ANNOTATED_TYPE', // AnnotatedTypeTree + ANNOTATION: 'ANNOTATION', // AnnotationTree + ANNOTATION_TYPE: 'ANNOTATION_TYPE', // ClassTree + ARRAY_ACCESS: 'ARRAY_ACCESS', // ArrayAccessTree + ARRAY_TYPE: 'ARRAY_TYPE', // ArrayTypeTree + ASSERT: 'ASSERT', // AssertTree + ASSIGNMENT: 'ASSIGNMENT', // AssignmentTree + BINDING_PATTERN: 'BINDING_PATTERN', // BindingPatternTree + BITWISE_COMPLEMENT: 'BITWISE_COMPLEMENT', // UnaryTree + BLOCK: 'BLOCK', // BlockTree + BOOLEAN_LITERAL: 'BOOLEAN_LITERAL', // LiteralTree + BREAK: 'BREAK', // BreakTree + CASE: 'CASE', // CaseTree + CATCH: 'CATCH', // CatchTree + CHAR_LITERAL: 'CHAR_LITERAL', // LiteralTree + CLASS: 'CLASS', // ClassTree + COMPILATION_UNIT: 'COMPILATION_UNIT', // CompilationUnitTree + CONDITIONAL_AND: 'CONDITIONAL_AND', // BinaryTree + CONDITIONAL_EXPRESSION: 'CONDITIONAL_EXPRESSION', // ConditionalExpressionTree + CONDITIONAL_OR: 'CONDITIONAL_OR', // BinaryTree + CONTINUE: 'CONTINUE', // ContinueTree + DEFAULT_CASE_LABEL: 'DEFAULT_CASE_LABEL', // DefaultCaseLabelTree + DIVIDE: 'DIVIDE', // BinaryTree + DIVIDE_ASSIGNMENT: 'DIVIDE_ASSIGNMENT', // CompoundAssignmentTree + DO_WHILE_LOOP: 'DO_WHILE_LOOP', // DoWhileLoopTree + DOUBLE_LITERAL: 'DOUBLE_LITERAL', // LiteralTree + EMPTY_STATEMENT: 'EMPTY_STATEMENT', // EmptyStatementTree + ENHANCED_FOR_LOOP: 'ENHANCED_FOR_LOOP', // EnhancedForLoopTree + ENUM: 'ENUM', // ClassTree + EQUAL_TO: 'EQUAL_TO', // BinaryTree + ERRONEOUS: 'ERRONEOUS', // ErroneousTree + EXPORTS: 'EXPORTS', // ExportsTree + EXPRESSION_STATEMENT: 'EXPRESSION_STATEMENT', // ExpressionStatementTree + EXTENDS_WILDCARD: 'EXTENDS_WILDCARD', // WildcardTree + FLOAT_LITERAL: 'FLOAT_LITERAL', // LiteralTree + FOR_LOOP: 'FOR_LOOP', // ForLoopTree + GREATER_THAN: 'GREATER_THAN', // BinaryTree + GREATER_THAN_EQUAL: 'GREATER_THAN_EQUAL', // BinaryTree + GUARDED_PATTERN: 'GUARDED_PATTERN', // GuardedPatternTree + IDENTIFIER: 'IDENTIFIER', // IdentifierTree + IF: 'IF', // IfTree + IMPORT: 'IMPORT', // ImportTree + INSTANCE_OF: 'INSTANCE_OF', // InstanceOfTree + INT_LITERAL: 'INT_LITERAL', // LiteralTree + INTERFACE: 'INTERFACE', // ClassTree + INTERSECTION_TYPE: 'INTERSECTION_TYPE', // IntersectionTypeTree + LABELED_STATEMENT: 'LABELED_STATEMENT', // LabeledStatementTree + LAMBDA_EXPRESSION: 'LAMBDA_EXPRESSION', // LambdaExpressionTree + LEFT_SHIFT: 'LEFT_SHIFT', // BinaryTree + LEFT_SHIFT_ASSIGNMENT: 'LEFT_SHIFT_ASSIGNMENT', // CompoundAssignmentTree + LESS_THAN: 'LESS_THAN', // BinaryTree + LESS_THAN_EQUAL: 'LESS_THAN_EQUAL', // BinaryTree + LOGICAL_COMPLEMENT: 'LOGICAL_COMPLEMENT', // UnaryTree + LONG_LITERAL: 'LONG_LITERAL', // LiteralTree + MEMBER_REFERENCE: 'MEMBER_REFERENCE', // MemberReferenceTree + MEMBER_SELECT: 'MEMBER_SELECT', // MemberSelectTree + METHOD: 'METHOD', // MethodTree + METHOD_INVOCATION: 'METHOD_INVOCATION', // MethodInvocationTree + MINUS: 'MINUS', // BinaryTree + MINUS_ASSIGNMENT: 'MINUS_ASSIGNMENT', // CompoundAssignmentTree + MODIFIERS: 'MODIFIERS', // ModifiersTree + MODULE: 'MODULE', // ModuleTree + MULTIPLY: 'MULTIPLY', // BinaryTree + MULTIPLY_ASSIGNMENT: 'MULTIPLY_ASSIGNMENT', // CompoundAssignmentTree + NEW_ARRAY: 'NEW_ARRAY', // NewArrayTree + NEW_CLASS: 'NEW_CLASS', // NewClassTree + NOT_EQUAL_TO: 'NOT_EQUAL_TO', // BinaryTree + NULL_LITERAL: 'NULL_LITERAL', // LiteralTree + OPENS: 'OPENS', // OpensTree + OR: 'OR', // BinaryTree + OR_ASSIGNMENT: 'OR_ASSIGNMENT', // CompoundAssignmentTree + OTHER: 'OTHER', // null + PACKAGE: 'PACKAGE', // PackageTree + PARAMETERIZED_TYPE: 'PARAMETERIZED_TYPE', // ParameterizedTypeTree + PARENTHESIZED: 'PARENTHESIZED', // ParenthesizedTree + PARENTHESIZED_PATTERN: 'PARENTHESIZED_PATTERN', // ParenthesizedPatternTree + PLUS: 'PLUS', // BinaryTree + PLUS_ASSIGNMENT: 'PLUS_ASSIGNMENT', // CompoundAssignmentTree + POSTFIX_DECREMENT: 'POSTFIX_DECREMENT', // UnaryTree + POSTFIX_INCREMENT: 'POSTFIX_INCREMENT', // UnaryTree + PREFIX_DECREMENT: 'PREFIX_DECREMENT', // UnaryTree + PREFIX_INCREMENT: 'PREFIX_INCREMENT', // UnaryTree + PRIMITIVE_TYPE: 'PRIMITIVE_TYPE', // PrimitiveTypeTree + PROVIDES: 'PROVIDES', // ProvidesTree + RECORD: 'RECORD', // ClassTree + REMAINDER: 'REMAINDER', // BinaryTree + REMAINDER_ASSIGNMENT: 'REMAINDER_ASSIGNMENT', // CompoundAssignmentTree + REQUIRES: 'REQUIRES', // RequiresTree + RETURN: 'RETURN', // ReturnTree + RIGHT_SHIFT: 'RIGHT_SHIFT', // BinaryTree + RIGHT_SHIFT_ASSIGNMENT: 'RIGHT_SHIFT_ASSIGNMENT', // CompoundAssignmentTree + STRING_LITERAL: 'STRING_LITERAL', // LiteralTree + SUPER_WILDCARD: 'SUPER_WILDCARD', // WildcardTree + SWITCH: 'SWITCH', // SwitchTree + SWITCH_EXPRESSION: 'SWITCH_EXPRESSION', // SwitchExpressionTree + SYNCHRONIZED: 'SYNCHRONIZED', // SynchronizedTree + THROW: 'THROW', // ThrowTree + TRY: 'TRY', // TryTree + TYPE_ANNOTATION: 'TYPE_ANNOTATION', // AnnotationTree + TYPE_CAST: 'TYPE_CAST', // TypeCastTree + TYPE_PARAMETER: 'TYPE_PARAMETER', // TypeParameterTree + UNARY_MINUS: 'UNARY_MINUS', // UnaryTree + UNARY_PLUS: 'UNARY_PLUS', // UnaryTree + UNBOUNDED_WILDCARD: 'UNBOUNDED_WILDCARD', // WildcardTree + UNION_TYPE: 'UNION_TYPE', // UnionTypeTree + UNSIGNED_RIGHT_SHIFT: 'UNSIGNED_RIGHT_SHIFT', // BinaryTree + UNSIGNED_RIGHT_SHIFT_ASSIGNMENT: 'UNSIGNED_RIGHT_SHIFT_ASSIGNMENT', // CompoundAssignmentTree + USES: 'USES', // UsesTree + VARIABLE: 'VARIABLE', // VariableTree + WHILE_LOOP: 'WHILE_LOOP', // WhileLoopTree + XOR: 'XOR', // BinaryTree + XOR_ASSIGNMENT: 'XOR_ASSIGNMENT', // CompoundAssignmentTree + YIELD: 'YIELD', // YieldTree +}); + +const JTModifier = Object.freeze({ + PUBLIC: 'public', + PROTECTED: 'protected', + PRIVATE: 'private', + ABSTRACT: 'abstract', + DEFAULT: 'default', + STATIC: 'static', + SEALED: 'sealed', + NON_SEALED: 'non-sealed', + FINAL: 'final', + TRANSIENT: 'transient', + VOLATILE: 'volatile', + SYNCHRONIZED: 'synchronized', + NATIVE: 'native', + STRICTFP: 'strictfp', +}); + +const JTReferenceMode = Object.freeze({ + INVOKE: 'INVOKE', + NEW: 'NEW', +}); + +const JTTypeKind = Object.freeze({ + BOOLEAN: 'BOOLEAN', + BYTE: 'BYTE', + SHORT: 'SHORT', + INT: 'INT', + LONG: 'LONG', + CHAR: 'CHAR', + FLOAT: 'FLOAT', + DOUBLE: 'DOUBLE', + VOID: 'VOID', + NONE: 'NONE', + NULL: 'NULL', + ARRAY: 'ARRAY', + DECLARED: 'DECLARED', + ERROR: 'ERROR', + TYPEVAR: 'TYPEVAR', + WILDCARD: 'WILDCARD', + PACKAGE: 'PACKAGE', + EXECUTABLE: 'EXECUTABLE', + OTHER: 'OTHER', + UNION: 'UNION', + INTERSECTION: 'INTERSECTION', + MODULE: 'MODULE', +}); + +function canBeIgnoredByAnnotations(annotations, context) { + const annotation = findAnnotation(annotations, 'JaspilerContract.Ignore'); + return evaluateAnnotationAttribute(annotation, context, 'condition', true, false); +} + +function evaluateAnnotationAttribute(annotation, context, attributeName, defaultValueForAttributeFound, defaultValueForAttributeNotFound) { + if (annotation) { + const attributeValue = getAnnotationAttributeValueByName(annotation, attributeName); + if (attributeValue && attributeValue.kind == JTKind.STRING_LITERAL) { + const script = new vm.Script(attributeValue.value); + if (!(context instanceof Object)) { + context = {}; + } + if (!vm.isContext(context)) { + vm.createContext(context); + } + return script.runInContext(context); + } + return defaultValueForAttributeFound; + } + return defaultValueForAttributeNotFound; +} + +function findAnnotation(annotations, annotationName) { + if (annotations) { + return annotations.find(annotation => annotation.annotationType.toString() == annotationName); + } + return undefined; +} + +function getAnnotationAttributeValueByName(annotation, attributeName) { + if (annotation) { + const args = annotation.arguments; + for (let i = 0; i < args.length; ++i) { + const arg = args[i]; + if (arg.kind == JTKind.ASSIGNMENT && arg.variable.toString() == attributeName) { + return arg.expression; + } + } + } + return undefined; +} + +function getChangeInstructionByAnnotations(annotations, context) { + const annotation = findAnnotation(annotations, 'JaspilerContract.Change'); + if (evaluateAnnotationAttribute(annotation, context, 'condition', true, false)) { + return evaluateAnnotationAttribute(annotation, context, 'instruction', undefined, undefined); + } + return undefined; +} + +const PluginContractIgnore = Object.freeze({ + visitor: Object.freeze({ + AnnotatedType(node, context) { + if (canBeIgnoredByAnnotations(node.annotations, context)) { + node.setActionIgnore(); + } + }, + CompilationUnit(node, context) { + const typeDeclIgnored = node.typeDecls.find(typeDecl => { + if (typeDecl.classSimpleName == 'JTClassDecl') { + const modifiers = typeDecl.modifiers; + if (modifiers && modifiers.flags.includes(JTModifier.PUBLIC)) { + return canBeIgnoredByAnnotations(modifiers.annotations, context); + } + } + return false; + }); + if (typeDeclIgnored) { + node.setActionIgnore(); + } + }, + Class(node, context) { + if (canBeIgnoredByAnnotations(node.modifiers?.annotations, context)) { + node.setActionIgnore(); + } + }, + Method(node, context) { + if (canBeIgnoredByAnnotations(node.modifiers?.annotations, context)) { + node.setActionIgnore(); + } + }, + Module(node, context) { + if (canBeIgnoredByAnnotations(node.annotations, context)) { + node.setActionIgnore(); + } + }, + NewArray(node, context) { + if (canBeIgnoredByAnnotations(node.annotations, context)) { + node.setActionIgnore(); + } + }, + Package(node, context) { + if (canBeIgnoredByAnnotations(node.annotations, context)) { + node.setActionIgnore(); + } + }, + TypeParameter(node, context) { + if (canBeIgnoredByAnnotations(node.annotations, context)) { + node.setActionIgnore(); + } + }, + Variable(node, context) { + if (canBeIgnoredByAnnotations(node.modifiers?.annotations, context)) { + node.setActionIgnore(); + } + }, + }), +}); + +const PluginContractChangeMethod = Object.freeze({ + visitor: Object.freeze({ + Method(node, context) { + const instruction = getChangeInstructionByAnnotations(node.modifiers?.annotations, context); + if (instruction) { + if (instruction.type == 'clear') { + const body = node.body; + // There is no need to clear the method if the body is absent. + if (body) { + const returnType = node.returnType; + const blockStatement = jaspiler.newBlock(); + const isPrimitiveType = returnType.classSimpleName == 'JTPrimitiveType'; + const primitiveTypeKind = isPrimitiveType ? returnType.primitiveTypeKind : null; + if (!isPrimitiveType || primitiveTypeKind != JTTypeKind.VOID) { + const returnStatement = jaspiler.newReturn(); + const literalExpression = jaspiler.createLiteral(null); + if (isPrimitiveType) { + let kind = JTKind.NULL_LITERAL; + switch (primitiveTypeKind) { + case JTTypeKind.BOOLEAN: kind = JTKind.BOOLEAN_LITERAL; break; + case JTTypeKind.CHAR: kind = JTKind.CHAR_LITERAL; break; + case JTTypeKind.DOUBLE: kind = JTKind.DOUBLE_LITERAL; break; + case JTTypeKind.FLOAT: kind = JTKind.FLOAT_LITERAL; break; + case JTTypeKind.INT: kind = JTKind.INT_LITERAL; break; + case JTTypeKind.LONG: kind = JTKind.LONG_LITERAL; break; + case JTTypeKind.NULL: kind = JTKind.NULL_LITERAL; break; + } + literalExpression.kind = kind; + } + returnStatement.expression = literalExpression; + blockStatement.statements = [returnStatement]; + } + node.body = blockStatement; + } + } + } + }, + }), +}); + +module.exports = Object.freeze({ + helpers: Object.freeze({ + evaluateAnnotationAttribute: evaluateAnnotationAttribute, + findAnnotation: findAnnotation, + getAnnotationAttributeValueByName: getAnnotationAttributeValueByName, + }), + JTBodyKind: JTBodyKind, + JTCaseKind: JTCaseKind, + JTKind: JTKind, + JTModifier: JTModifier, + JTReferenceMode: JTReferenceMode, + JTTypeKind: JTTypeKind, + PluginContractIgnore: PluginContractIgnore, + PluginContractChangeMethod: PluginContractChangeMethod, +}); diff --git a/scripts/node/package-lock.json b/scripts/node/package-lock.json index aedb341..b21d6b7 100644 --- a/scripts/node/package-lock.json +++ b/scripts/node/package-lock.json @@ -1,438 +1,439 @@ -{ - "name": "node", - "lockfileVersion": 2, - "requires": true, - "packages": { - "": { - "dependencies": { - "yargs": "^17.7.2" - }, - "devDependencies": { - "chai": "^4.3.7" - } - }, - "node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "engines": { - "node": ">=8" - } - }, - "node_modules/ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "dependencies": { - "color-convert": "^2.0.1" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/assertion-error": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz", - "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==", - "dev": true, - "engines": { - "node": "*" - } - }, - "node_modules/chai": { - "version": "4.3.7", - "resolved": "https://registry.npmjs.org/chai/-/chai-4.3.7.tgz", - "integrity": "sha512-HLnAzZ2iupm25PlN0xFreAlBA5zaBSv3og0DdeGA4Ar6h6rJ3A0rolRUKJhSF2V10GZKDgWF/VmAEsNWjCRB+A==", - "dev": true, - "dependencies": { - "assertion-error": "^1.1.0", - "check-error": "^1.0.2", - "deep-eql": "^4.1.2", - "get-func-name": "^2.0.0", - "loupe": "^2.3.1", - "pathval": "^1.1.1", - "type-detect": "^4.0.5" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/check-error": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.2.tgz", - "integrity": "sha512-BrgHpW9NURQgzoNyjfq0Wu6VFO6D7IZEmJNdtgNqpzGG8RuNFHt2jQxWlAs4HMe119chBnv+34syEZtc6IhLtA==", - "dev": true, - "engines": { - "node": "*" - } - }, - "node_modules/cliui": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", - "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", - "dependencies": { - "string-width": "^4.2.0", - "strip-ansi": "^6.0.1", - "wrap-ansi": "^7.0.0" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "dependencies": { - "color-name": "~1.1.4" - }, - "engines": { - "node": ">=7.0.0" - } - }, - "node_modules/color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" - }, - "node_modules/deep-eql": { - "version": "4.1.3", - "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-4.1.3.tgz", - "integrity": "sha512-WaEtAOpRA1MQ0eohqZjpGD8zdI0Ovsm8mmFhaDN8dvDZzyoUMcYDnf5Y6iu7HTXxf8JDS23qWa4a+hKCDyOPzw==", - "dev": true, - "dependencies": { - "type-detect": "^4.0.0" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" - }, - "node_modules/escalade": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", - "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", - "engines": { - "node": ">=6" - } - }, - "node_modules/get-caller-file": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", - "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", - "engines": { - "node": "6.* || 8.* || >= 10.*" - } - }, - "node_modules/get-func-name": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.0.tgz", - "integrity": "sha512-Hm0ixYtaSZ/V7C8FJrtZIuBBI+iSgL+1Aq82zSu8VQNB4S3Gk8e7Qs3VwBDJAhmRZcFqkl3tQu36g/Foh5I5ig==", - "dev": true, - "engines": { - "node": "*" - } - }, - "node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "engines": { - "node": ">=8" - } - }, - "node_modules/loupe": { - "version": "2.3.6", - "resolved": "https://registry.npmjs.org/loupe/-/loupe-2.3.6.tgz", - "integrity": "sha512-RaPMZKiMy8/JruncMU5Bt6na1eftNoo++R4Y+N2FrxkDVTrGvcyzFTsaGif4QTeKESheMGegbhw6iUAq+5A8zA==", - "dev": true, - "dependencies": { - "get-func-name": "^2.0.0" - } - }, - "node_modules/pathval": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/pathval/-/pathval-1.1.1.tgz", - "integrity": "sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ==", - "dev": true, - "engines": { - "node": "*" - } - }, - "node_modules/require-directory": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", - "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/string-width": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/type-detect": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", - "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", - "dev": true, - "engines": { - "node": ">=4" - } - }, - "node_modules/wrap-ansi": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", - "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", - "dependencies": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" - } - }, - "node_modules/y18n": { - "version": "5.0.8", - "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", - "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", - "engines": { - "node": ">=10" - } - }, - "node_modules/yargs": { - "version": "17.7.2", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", - "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", - "dependencies": { - "cliui": "^8.0.1", - "escalade": "^3.1.1", - "get-caller-file": "^2.0.5", - "require-directory": "^2.1.1", - "string-width": "^4.2.3", - "y18n": "^5.0.5", - "yargs-parser": "^21.1.1" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/yargs-parser": { - "version": "21.1.1", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", - "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", - "engines": { - "node": ">=12" - } - } - }, - "dependencies": { - "ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==" - }, - "ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "requires": { - "color-convert": "^2.0.1" - } - }, - "assertion-error": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz", - "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==", - "dev": true - }, - "chai": { - "version": "4.3.7", - "resolved": "https://registry.npmjs.org/chai/-/chai-4.3.7.tgz", - "integrity": "sha512-HLnAzZ2iupm25PlN0xFreAlBA5zaBSv3og0DdeGA4Ar6h6rJ3A0rolRUKJhSF2V10GZKDgWF/VmAEsNWjCRB+A==", - "dev": true, - "requires": { - "assertion-error": "^1.1.0", - "check-error": "^1.0.2", - "deep-eql": "^4.1.2", - "get-func-name": "^2.0.0", - "loupe": "^2.3.1", - "pathval": "^1.1.1", - "type-detect": "^4.0.5" - } - }, - "check-error": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.2.tgz", - "integrity": "sha512-BrgHpW9NURQgzoNyjfq0Wu6VFO6D7IZEmJNdtgNqpzGG8RuNFHt2jQxWlAs4HMe119chBnv+34syEZtc6IhLtA==", - "dev": true - }, - "cliui": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", - "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", - "requires": { - "string-width": "^4.2.0", - "strip-ansi": "^6.0.1", - "wrap-ansi": "^7.0.0" - } - }, - "color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "requires": { - "color-name": "~1.1.4" - } - }, - "color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" - }, - "deep-eql": { - "version": "4.1.3", - "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-4.1.3.tgz", - "integrity": "sha512-WaEtAOpRA1MQ0eohqZjpGD8zdI0Ovsm8mmFhaDN8dvDZzyoUMcYDnf5Y6iu7HTXxf8JDS23qWa4a+hKCDyOPzw==", - "dev": true, - "requires": { - "type-detect": "^4.0.0" - } - }, - "emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" - }, - "escalade": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", - "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==" - }, - "get-caller-file": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", - "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==" - }, - "get-func-name": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.0.tgz", - "integrity": "sha512-Hm0ixYtaSZ/V7C8FJrtZIuBBI+iSgL+1Aq82zSu8VQNB4S3Gk8e7Qs3VwBDJAhmRZcFqkl3tQu36g/Foh5I5ig==", - "dev": true - }, - "is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==" - }, - "loupe": { - "version": "2.3.6", - "resolved": "https://registry.npmjs.org/loupe/-/loupe-2.3.6.tgz", - "integrity": "sha512-RaPMZKiMy8/JruncMU5Bt6na1eftNoo++R4Y+N2FrxkDVTrGvcyzFTsaGif4QTeKESheMGegbhw6iUAq+5A8zA==", - "dev": true, - "requires": { - "get-func-name": "^2.0.0" - } - }, - "pathval": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/pathval/-/pathval-1.1.1.tgz", - "integrity": "sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ==", - "dev": true - }, - "require-directory": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", - "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==" - }, - "string-width": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "requires": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - } - }, - "strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "requires": { - "ansi-regex": "^5.0.1" - } - }, - "type-detect": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", - "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", - "dev": true - }, - "wrap-ansi": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", - "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", - "requires": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - } - }, - "y18n": { - "version": "5.0.8", - "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", - "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==" - }, - "yargs": { - "version": "17.7.2", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", - "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", - "requires": { - "cliui": "^8.0.1", - "escalade": "^3.1.1", - "get-caller-file": "^2.0.5", - "require-directory": "^2.1.1", - "string-width": "^4.2.3", - "y18n": "^5.0.5", - "yargs-parser": "^21.1.1" - } - }, - "yargs-parser": { - "version": "21.1.1", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", - "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==" - } - } -} +{ + "name": "node", + "lockfileVersion": 2, + "requires": true, + "packages": { + "": { + "name": "node", + "dependencies": { + "yargs": "^17.7.2" + }, + "devDependencies": { + "chai": "^4.3.7" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/assertion-error": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz", + "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==", + "dev": true, + "engines": { + "node": "*" + } + }, + "node_modules/chai": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/chai/-/chai-4.3.7.tgz", + "integrity": "sha512-HLnAzZ2iupm25PlN0xFreAlBA5zaBSv3og0DdeGA4Ar6h6rJ3A0rolRUKJhSF2V10GZKDgWF/VmAEsNWjCRB+A==", + "dev": true, + "dependencies": { + "assertion-error": "^1.1.0", + "check-error": "^1.0.2", + "deep-eql": "^4.1.2", + "get-func-name": "^2.0.0", + "loupe": "^2.3.1", + "pathval": "^1.1.1", + "type-detect": "^4.0.5" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/check-error": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.2.tgz", + "integrity": "sha512-BrgHpW9NURQgzoNyjfq0Wu6VFO6D7IZEmJNdtgNqpzGG8RuNFHt2jQxWlAs4HMe119chBnv+34syEZtc6IhLtA==", + "dev": true, + "engines": { + "node": "*" + } + }, + "node_modules/cliui": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, + "node_modules/deep-eql": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-4.1.3.tgz", + "integrity": "sha512-WaEtAOpRA1MQ0eohqZjpGD8zdI0Ovsm8mmFhaDN8dvDZzyoUMcYDnf5Y6iu7HTXxf8JDS23qWa4a+hKCDyOPzw==", + "dev": true, + "dependencies": { + "type-detect": "^4.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" + }, + "node_modules/escalade": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", + "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", + "engines": { + "node": ">=6" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-func-name": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.2.tgz", + "integrity": "sha512-8vXOvuE167CtIc3OyItco7N/dpRtBbYOsPsXCz7X/PMnlGjYjSGuZJgM1Y7mmew7BKf9BqvLX2tnOVy1BBUsxQ==", + "dev": true, + "engines": { + "node": "*" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "engines": { + "node": ">=8" + } + }, + "node_modules/loupe": { + "version": "2.3.6", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-2.3.6.tgz", + "integrity": "sha512-RaPMZKiMy8/JruncMU5Bt6na1eftNoo++R4Y+N2FrxkDVTrGvcyzFTsaGif4QTeKESheMGegbhw6iUAq+5A8zA==", + "dev": true, + "dependencies": { + "get-func-name": "^2.0.0" + } + }, + "node_modules/pathval": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-1.1.1.tgz", + "integrity": "sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ==", + "dev": true, + "engines": { + "node": "*" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/type-detect": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", + "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "engines": { + "node": ">=10" + } + }, + "node_modules/yargs": { + "version": "17.7.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", + "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "engines": { + "node": ">=12" + } + } + }, + "dependencies": { + "ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==" + }, + "ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "requires": { + "color-convert": "^2.0.1" + } + }, + "assertion-error": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz", + "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==", + "dev": true + }, + "chai": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/chai/-/chai-4.3.7.tgz", + "integrity": "sha512-HLnAzZ2iupm25PlN0xFreAlBA5zaBSv3og0DdeGA4Ar6h6rJ3A0rolRUKJhSF2V10GZKDgWF/VmAEsNWjCRB+A==", + "dev": true, + "requires": { + "assertion-error": "^1.1.0", + "check-error": "^1.0.2", + "deep-eql": "^4.1.2", + "get-func-name": "^2.0.0", + "loupe": "^2.3.1", + "pathval": "^1.1.1", + "type-detect": "^4.0.5" + } + }, + "check-error": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.2.tgz", + "integrity": "sha512-BrgHpW9NURQgzoNyjfq0Wu6VFO6D7IZEmJNdtgNqpzGG8RuNFHt2jQxWlAs4HMe119chBnv+34syEZtc6IhLtA==", + "dev": true + }, + "cliui": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", + "requires": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, + "deep-eql": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-4.1.3.tgz", + "integrity": "sha512-WaEtAOpRA1MQ0eohqZjpGD8zdI0Ovsm8mmFhaDN8dvDZzyoUMcYDnf5Y6iu7HTXxf8JDS23qWa4a+hKCDyOPzw==", + "dev": true, + "requires": { + "type-detect": "^4.0.0" + } + }, + "emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" + }, + "escalade": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", + "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==" + }, + "get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==" + }, + "get-func-name": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.2.tgz", + "integrity": "sha512-8vXOvuE167CtIc3OyItco7N/dpRtBbYOsPsXCz7X/PMnlGjYjSGuZJgM1Y7mmew7BKf9BqvLX2tnOVy1BBUsxQ==", + "dev": true + }, + "is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==" + }, + "loupe": { + "version": "2.3.6", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-2.3.6.tgz", + "integrity": "sha512-RaPMZKiMy8/JruncMU5Bt6na1eftNoo++R4Y+N2FrxkDVTrGvcyzFTsaGif4QTeKESheMGegbhw6iUAq+5A8zA==", + "dev": true, + "requires": { + "get-func-name": "^2.0.0" + } + }, + "pathval": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-1.1.1.tgz", + "integrity": "sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ==", + "dev": true + }, + "require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==" + }, + "string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "requires": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + } + }, + "strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "requires": { + "ansi-regex": "^5.0.1" + } + }, + "type-detect": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", + "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", + "dev": true + }, + "wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "requires": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + } + }, + "y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==" + }, + "yargs": { + "version": "17.7.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", + "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", + "requires": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + } + }, + "yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==" + } + } +} diff --git a/scripts/node/test/test_argv.js b/scripts/node/test/test_argv.js index 2e77c00..15367c1 100644 --- a/scripts/node/test/test_argv.js +++ b/scripts/node/test/test_argv.js @@ -1,25 +1,25 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -const { assert } = require('chai'); - -const argv = jaspiler.argv; - -assert.equal(4, argv.length); -assert.include(argv[0], 'test_argv.js'); -assert.equal('-a', argv[1]); -assert.equal('b', argv[2]); -assert.equal('-c', argv[3]); +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +const { assert } = require('chai'); + +const argv = jaspiler.argv; + +assert.equal(4, argv.length); +assert.include(argv[0], 'test_argv.js'); +assert.equal('-a', argv[1]); +assert.equal('b', argv[2]); +assert.equal('-c', argv[3]); diff --git a/scripts/node/test/test_transform.js b/scripts/node/test/test_transform.js index 205fd97..c1803bf 100644 --- a/scripts/node/test/test_transform.js +++ b/scripts/node/test/test_transform.js @@ -1,557 +1,557 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/// - -const { assert } = require('chai'); -const path = require('path'); -const process = require('process'); -const { JTKind, PluginContractIgnore, PluginContractChangeMethod } = require('../jaspiler/jaspiler'); - -const workingDirectory = process.cwd(); -const pathMockAllInOnePublicClass = path.join( - workingDirectory, - '../../../src/test/java/com/caoccao/jaspiler/mock/MockAllInOnePublicClass.java'); -const pathMockForScan = path.join( - workingDirectory, - '../../../src/test/java/com/caoccao/jaspiler/mock/MockForScan.java'); -const pathMockPublicAnnotation = path.join( - workingDirectory, - '../../../src/test/java/com/caoccao/jaspiler/mock/MockPublicAnnotation.java'); - -// AST - -function testAstForFile() { - const result = jaspiler.transformSync(pathMockPublicAnnotation, { ast: true }); - // Assert { ast, code } - assert.isObject(result); - assert.isObject(result.ast); - const expectedLine = 'public @interface MockPublicAnnotation {'; - assert.include(result.code, expectedLine, 'The code string should be generated'); - assert.include(result.ast.toString(), expectedLine, 'The ast.toString() should work'); - assert.include('' + result.ast, expectedLine, 'The ast[Symbol.toPrimitive]() should work'); - // Assert ast - const ast = result.ast; - assert.equal(JTKind.COMPILATION_UNIT, ast.kind); - const astImports = ast.imports; - assert.isArray(astImports); - assert.equal(2, astImports.length); - const astModule = ast.module; - assert.isNull(astModule); - const astPackage = ast.package; - assert.isObject(astPackage); - assert.equal('package com.caoccao.jaspiler.mock;', astPackage.toString()); - const packageName = astPackage.packageName; - assert.isObject(packageName); - assert.equal('com.caoccao.jaspiler.mock', packageName.toString()); - const typeDecls = ast.typeDecls; - assert.isArray(typeDecls); - assert.equal(1, typeDecls.length); - assert.include(typeDecls[0].toString(), expectedLine, 'The typeDecls[0].toString() should work'); - assert.equal(pathMockPublicAnnotation, ast.sourceFile, 'The source file should match'); -} - -function testAstForString() { - const result = jaspiler.transformSync( - `package a.b.c; - public class A { - } - `, - { ast: true, fileName: 'A', sourceType: 'string' }); - // Assert { ast, code } - assert.isObject(result); - assert.isObject(result.ast); - assert.include(result.code, 'public class A'); - // Assert ast - const ast = result.ast; - assert.equal(JTKind.COMPILATION_UNIT, ast.kind); -} - -// Contract.Ignore - -function testContractIgnoreCompilationUnit() { - const result = jaspiler.transformSync( - `package a.b.c; - @JaspilerContract.Ignore - public class A { - } - `, - { plugins: [PluginContractIgnore], ast: true, fileName: 'A', sourceType: 'string' }); - // Assert { ast, code } - assert.isObject(result); - assert.isTrue(result.ast.isActionIgnore()); - assert.isUndefined(result.code); -} - -function testContractIgnoreClass() { - const result = jaspiler.transformSync( - `package a.b.c; - @JaspilerContract.Ignore - class A { - } - `, - { plugins: [PluginContractIgnore], ast: true, fileName: 'A', sourceType: 'string' }); - // Assert { ast, code } - assert.isObject(result); - assert.isFalse(result.ast.isActionIgnore()); - assert.include(result.code, 'package a.b.c;'); - assert.notInclude(result.code, 'class A'); -} - -function testContractIgnoreMethod() { - const result = jaspiler.transformSync( - `package a.b.c; - public class A { - @JaspilerContract.Ignore - public void test() {} - } - `, - { plugins: [PluginContractIgnore], ast: true, fileName: 'A', sourceType: 'string' }); - // Assert { ast, code } - assert.isObject(result); - assert.include(result.code, 'public class A {'); - assert.notInclude(result.code, 'public void test()'); -} - -function testContractIgnoreProperty() { - const context = { hideB: false }; - const result = jaspiler.transformSync( - `package a.b.c; - public class A { - @JaspilerContract.Ignore - private int a; - @JaspilerContract.Ignore(condition = "hideB") - private int b; - } - `, - { plugins: [PluginContractIgnore], context: context, ast: true, fileName: 'A', sourceType: 'string' }); - // Assert { ast, code } - assert.isObject(result); - assert.include(result.code, 'public class A {'); - assert.notInclude(result.code, 'private int a;'); - assert.include(result.code, 'private int b;'); -} - -function testContractChangeMethod() { - const context = { options: {} }; - const result = jaspiler.transformSync( - `package a.b.c; - public class A { - @JaspilerContract.Change(instruction = "options = { type: 'clear' }") - public void testVoid() { 1 + 1; } - @JaspilerContract.Change(instruction = "options = { type: 'clear' }") - public boolean testBoolean() { return true; } - @JaspilerContract.Change(instruction = "options = { type: 'clear' }") - public char testChar() { return 'a'; } - @JaspilerContract.Change(instruction = "options = { type: 'clear' }") - public double testDouble() { return 1.23D; } - @JaspilerContract.Change(instruction = "options = { type: 'clear' }") - public float testFloat() { return 1.23F; } - @JaspilerContract.Change(instruction = "options = { type: 'clear' }") - public int testInt() { return 1; } - @JaspilerContract.Change(instruction = "options = { type: 'clear' }") - public long testLong() { return 1L; } - @JaspilerContract.Change(instruction = "options = { type: 'clear' }") - public Object testObject() { return new Object(); } - @JaspilerContract.Change(instruction = "options = { type: 'clear' }") - public String testString() { return "123"; } - } - `, - { plugins: [PluginContractChangeMethod], context: context, ast: true, fileName: 'A', sourceType: 'string' }); - // Assert { ast, code } - assert.isObject(result); - assert.include(result.code, 'public void testVoid() {\n }'); - assert.include(result.code, 'public boolean testBoolean() {\n return false;\n }'); - assert.include(result.code, 'public char testChar() {\n return \'\\0\';\n }'); - assert.include(result.code, 'public double testDouble() {\n return 0D;\n }'); - assert.include(result.code, 'public float testFloat() {\n return 0F;\n }'); - assert.include(result.code, 'public int testInt() {\n return 0;\n }'); - assert.include(result.code, 'public long testLong() {\n return 0L;\n }'); - assert.include(result.code, 'public Object testObject() {\n return null;\n }'); - assert.include(result.code, 'public String testString() {\n return null;\n }'); -} - -// Package - -function testIgnorePackage() { - const result = jaspiler.transformSync(pathMockPublicAnnotation, { - plugins: [{ - visitor: { - Package(node) { - assert.equal(0, node.annotations.length); - assert.isTrue(node.isActionNoChange()); - assert.isFalse(node.isActionChange()); - assert.isFalse(node.isActionIgnore()); - assert.isTrue(node.setActionIgnore()); - assert.isFalse(node.isActionNoChange()); - assert.isFalse(node.isActionChange()); - assert.isTrue(node.isActionIgnore()); - }, - }, - }], - }); - assert.notInclude(result.code, 'package com.caoccao.jaspiler.mock;'); -} - -function testReplacePackage() { - const result = jaspiler.transformSync(pathMockPublicAnnotation, { - plugins: [{ - visitor: { - Package(node) { - assert.equal(JTKind.PACKAGE, node.kind); - assert.equal('com.caoccao.jaspiler.trees.JTPackageDecl', node.className); - assert.equal('JTPackageDecl', node.classSimpleName); - assert.equal('package com.caoccao.jaspiler.mock;', node.toString()); - const compilationUnit = node.parentTree; - assert.equal('com.caoccao.jaspiler.trees.JTCompilationUnit', compilationUnit.className); - assert.equal('JTCompilationUnit', compilationUnit.classSimpleName); - assert.isNotNull(compilationUnit); - const packageDecl = jaspiler.newPackageDecl(); - assert.equal('com.caoccao.jaspiler.trees.JTPackageDecl', packageDecl.className); - assert.equal('JTPackageDecl', packageDecl.classSimpleName); - packageDecl.packageName = jaspiler.createFieldAccess('abc', 'def', 'ghi'); - compilationUnit.package = packageDecl; - }, - }, - }], - }); - assert.include(result.code, 'package abc.def.ghi;'); -} - -function testReplacePackageName() { - const result = jaspiler.transformSync(pathMockPublicAnnotation, { - plugins: [{ - visitor: { - Package(node) { - assert.isTrue(node.isActionNoChange()); - node.packageName = jaspiler.createFieldAccess('abc', 'def', 'ghi'); - assert.isTrue(node.isActionChange()); - }, - }, - }], - }); - assert.include(result.code, 'package abc.def.ghi;'); -} - -// Imports - -function testImports() { - const result = jaspiler.transformSync(pathMockPublicAnnotation, { - plugins: [{ - visitor: { - CompilationUnit(node) { - assert.equal(JTKind.COMPILATION_UNIT, node.kind); - assert.equal(pathMockPublicAnnotation, node.sourceFile, 'The source file should match'); - const imports = node.imports; - assert.equal(2, imports.length); - imports.push(imports.shift()); - const newImport = jaspiler.newImport(); - newImport.qualifiedIdentifier = jaspiler.createFieldAccess('abc', 'def', 'ghi'); - newImport.staticImport = true; - imports.push(newImport); - node.imports = imports; - }, - }, - }], - }); - assert.include( - result.code, - 'import java.lang.annotation.Inherited;\n' - + 'import java.lang.annotation.Documented;\n' - + 'import static abc.def.ghi;\n'); -} - -// Class - -function testClass() { - const simpleNames = [] - const result = jaspiler.transformSync(pathMockAllInOnePublicClass, { - plugins: [{ - visitor: { - Class(node) { - assert.equal('com.caoccao.jaspiler.trees.JTClassDecl', node.className); - const modifiers = node.modifiers; - assert.equal('com.caoccao.jaspiler.trees.JTModifiers', modifiers.className); - const simpleName = node.simpleName.value; - simpleNames.push(simpleName); - if ('MockAnnotation' == simpleName) { - assert.equal(JTKind.ANNOTATION_TYPE, node.kind); - const annotations = modifiers.annotations; - assert.equal(4, annotations.length); - annotations.push(annotations.shift()); - assert.equal('@Inherited', annotations[0].toString()); - assert.equal('com.caoccao.jaspiler.trees.JTIdent', annotations[0].annotationType.className); - assert.equal('Inherited', annotations[0].annotationType.name.value); - assert.equal(0, annotations[0].arguments.length); - assert.equal('Retention', annotations[1].annotationType.name.value); - assert.equal(1, annotations[1].arguments.length); - annotations[0].annotationType = jaspiler.createIdent('NotInherited'); - const args = annotations[1].arguments; - args.push(jaspiler.createFieldAccess('aaa', 'bbb')); - annotations[1].arguments = args; - modifiers.annotations = annotations; - assert.equal(0, node.typeParameters.length); - assert.isNull(node.extendsClause); - assert.equal(0, node.implementsClauses.length); - assert.equal(0, node.permitsClauses.length); - assert.equal(2, node.members.length); - assert.equal('String[] names() default {"A", "B"};', node.members[0].toString()); - } else if ('MockAllInOnePublicClass' == simpleName) { - assert.equal(JTKind.CLASS, node.kind); - assert.isNotNull(node.extendsClause); - assert.equal('Object', node.extendsClause.toString()); - assert.equal(2, node.implementsClauses.length); - assert.equal('Serializable', node.implementsClauses[0].toString()); - assert.equal(1, node.permitsClauses.length); - assert.equal('MockChild', node.permitsClauses[0].toString()); - assert.equal(8, node.members.length); - assert.equal('private String a;', node.members[1].toString()); - } else if ('MockChild' == simpleName) { - node.simpleName = jaspiler.createName('NewMockChild'); - } else if ('MockChild1' == simpleName) { - node.simpleName = jaspiler.createName('NewMockChild1'); - } - }, - }, - }], - }); - assert.equal('MockAnnotation,MockAllInOnePublicClass,,MockChild,MockChild1', simpleNames.join(',')); - assert.include(result.code, '@NotInherited\n' - + '@Retention(RetentionPolicy.RUNTIME, aaa.bbb)\n' - + '@Target(ElementType.ANNOTATION_TYPE)\n' - + '@Documented\n'); - assert.include(result.code, 'final class NewMockChild extends MockAllInOnePublicClass {'); -} - -// Identifier - -function testIdentifier() { - const values = []; - const result = jaspiler.transformSync(pathMockPublicAnnotation, { - plugins: [{ - visitor: { - Identifier(node) { - const value = node.name.value; - values.push(value); - if (value == 'Inherited') { - node.name = jaspiler.createName('NotInherited'); - } - }, - }, - }], - }); - assert.equal('com,java,java,Documented,Inherited,String,String', values.join(',')); - assert.include(result.code, '@NotInherited'); -} - -// Import - -function testImport() { - const values = []; - const result = jaspiler.transformSync(pathMockPublicAnnotation, { - plugins: [{ - visitor: { - Import(node) { - assert.isFalse(node.staticImport); - values.push(node.qualifiedIdentifier.toString()); - node.staticImport = true; - }, - }, - }], - }); - assert.equal(2, values.length); - assert.equal('java.lang.annotation.Documented', values[0]); - assert.equal('java.lang.annotation.Inherited', values[1]); - assert.include( - result.code, - 'import static java.lang.annotation.Documented;\n' - + 'import static java.lang.annotation.Inherited;\n'); -} - -// Variable -function testVariable() { - const result = jaspiler.transformSync(pathMockAllInOnePublicClass, { - plugins: [{ - visitor: { - Variable(node) { - const value = node.name.value; - if ('x' == value) { - node.name = jaspiler.createName('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'); - } else if ('y' == value) { - node.name = jaspiler.createName('yy'); - } else if ('a' == value) { - node.name = jaspiler.createName('aa'); - } else if ('c' == value) { - node.name = jaspiler.createName('cc'); - } - }, - }, - }], - }); - assert.include(result.code, '\n private String aa;\n'); - assert.include(result.code, '\n @SuppressWarnings("unchecked")\n'); - assert.include( - result.code, - '\n @SuppressWarnings("unchecked")\n' - + ' public final void Test(T xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, @Deprecated int yy)\n' - + ' throws IOException, NoClassDefFoundError {\n'); - assert.include(result.code, '\n int cc = 5;\n'); -} - -// Method - -function testMethod() { - const methodNames = []; - const result = jaspiler.transformSync(pathMockAllInOnePublicClass, { - plugins: [{ - visitor: { - Method(node) { - assert.equal('com.caoccao.jaspiler.trees.JTMethodDecl', node.className); - const methodName = node.name.value; - methodNames.push(methodName); - if (methodName == 'names') { - const modifiers = node.modifiers; - assert.isEmpty(modifiers.toString()); - assert.isEmpty(modifiers.annotations); - assert.isEmpty(modifiers.flags); - assert.isEmpty(node.parameters); - assert.isNull(node.receiverParameter); - assert.isEmpty(node.returnType); - assert.isEmpty(node.throwExpressions); - assert.isEmpty(node.typeParameters); - assert.equal('com.caoccao.jaspiler.trees.JTNewArray', node.defaultValue.className); - assert.equal('{"A", "B"}', node.defaultValue.toString()); - node.defaultValue = jaspiler.createFieldAccess('ABC'); - } else if (methodName == 'value') { - assert.equal('com.caoccao.jaspiler.trees.JTLiteral', node.defaultValue.className); - assert.equal(JTKind.STRING_LITERAL, node.defaultValue.kind); - } else if (methodName == 'Test') { - assert.equal(1, node.modifiers.annotations.length); - assert.equal(2, node.modifiers.flags.length); - assert.equal(1, node.typeParameters.length); - assert.equal('T', node.typeParameters[0].toString()); - assert.equal('void', node.returnType.toString()); - assert.equal(2, node.throwExpressions.length); - assert.equal(2, node.parameters.length); - } - }, - }, - }], - }); - assert.equal('names,value,Test,add,close', methodNames.join(',')); - assert.include(result.code, '\n String[] names() default ABC;\n'); -} - -// Block -function testBlock() { - const values = []; - jaspiler.transformSync(pathMockAllInOnePublicClass, { - plugins: [{ - visitor: { - Block(node) { - const value = node.toString(); - if (value.includes('System.out.println("static block");')) { - values.push(value); - assert.equal(1, node.statements.length); - assert.isTrue(node.static); - } else if (value.includes('put("a", 1);')) { - values.push(value); - assert.equal(2, node.statements.length); - assert.isFalse(node.static); - } - }, - }, - }], - }); - assert.equal(2, values.length); -} - -// Other - -function testOther() { - let count = 0; - jaspiler.transformSync(pathMockForScan, { - plugins: [{ - visitor: { - Other(node) { - count++; - }, - }, - }], - }); - assert.equal(0, count, 'There should not be other nodes'); -} - -// Scan - -function testScan() { - const classSimpleNameSet = new Set(); - jaspiler.transformSync(pathMockForScan, { - plugins: [{ - visitor: { - Scan(node) { - if (node) { - classSimpleNameSet.add(node.classSimpleName); - } - }, - }, - }], - }); - const expectedClassSimpleNameSet = new Set([ - 'JTCompilationUnit', 'JTPackageDecl', 'JTFieldAccess', 'JTIdent', 'JTImport', - 'JTClassDecl', 'JTModifiers', 'JTMethodDecl', 'JTArrayType', 'JTNewArray', - 'JTPrimitiveType', 'JTBlock', 'JTAnnotation', 'JTLiteral', 'JTVariableDecl', - 'JTExpressionStatement', 'JTForLoop', 'JTBinary', 'JTUnary', 'JTReturn', - 'JTNewClass', 'JTIf', 'JTAssign', - 'JTSwitch', 'JTCase', 'JTBreak', - 'JTMethodInvocation', 'JTWhileLoop', 'JTDoWhileLoop', 'JTParens']); - const unexpectedClassSimpleNames = - [...classSimpleNameSet].filter(name => !expectedClassSimpleNameSet.has(name)); - assert.equal(0, unexpectedClassSimpleNames.length, - 'Unexpected [\'' + unexpectedClassSimpleNames.join('\',\'') + '\']'); -} - -// AST -testAstForFile(); -testAstForString(); -// Contract.Ignore -testContractIgnoreCompilationUnit(); -testContractIgnoreClass(); -testContractIgnoreMethod(); -testContractIgnoreProperty(); -testContractChangeMethod(); -// Package -testIgnorePackage(); -testReplacePackage(); -testReplacePackageName(); -// Imports -testImports(); -// Class -testClass(); -// Identifier -testIdentifier(); -// Import -testImport(); -// Variable -testVariable(); -// Method -testMethod(); -// Block -testBlock(); -// Other -testOther(); -// Scan -testScan(); +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/// + +const { assert } = require('chai'); +const path = require('path'); +const process = require('process'); +const { JTKind, PluginContractIgnore, PluginContractChangeMethod } = require('../jaspiler/jaspiler'); + +const workingDirectory = process.cwd(); +const pathMockAllInOnePublicClass = path.join( + workingDirectory, + '../../../src/test/java/com/caoccao/jaspiler/mock/MockAllInOnePublicClass.java'); +const pathMockForScan = path.join( + workingDirectory, + '../../../src/test/java/com/caoccao/jaspiler/mock/MockForScan.java'); +const pathMockPublicAnnotation = path.join( + workingDirectory, + '../../../src/test/java/com/caoccao/jaspiler/mock/MockPublicAnnotation.java'); + +// AST + +function testAstForFile() { + const result = jaspiler.transformSync(pathMockPublicAnnotation, { ast: true }); + // Assert { ast, code } + assert.isObject(result); + assert.isObject(result.ast); + const expectedLine = 'public @interface MockPublicAnnotation {'; + assert.include(result.code, expectedLine, 'The code string should be generated'); + assert.include(result.ast.toString(), expectedLine, 'The ast.toString() should work'); + assert.include('' + result.ast, expectedLine, 'The ast[Symbol.toPrimitive]() should work'); + // Assert ast + const ast = result.ast; + assert.equal(JTKind.COMPILATION_UNIT, ast.kind); + const astImports = ast.imports; + assert.isArray(astImports); + assert.equal(2, astImports.length); + const astModule = ast.module; + assert.isNull(astModule); + const astPackage = ast.package; + assert.isObject(astPackage); + assert.equal('package com.caoccao.jaspiler.mock;', astPackage.toString()); + const packageName = astPackage.packageName; + assert.isObject(packageName); + assert.equal('com.caoccao.jaspiler.mock', packageName.toString()); + const typeDecls = ast.typeDecls; + assert.isArray(typeDecls); + assert.equal(1, typeDecls.length); + assert.include(typeDecls[0].toString(), expectedLine, 'The typeDecls[0].toString() should work'); + assert.equal(pathMockPublicAnnotation, ast.sourceFile, 'The source file should match'); +} + +function testAstForString() { + const result = jaspiler.transformSync( + `package a.b.c; + public class A { + } + `, + { ast: true, fileName: 'A', sourceType: 'string' }); + // Assert { ast, code } + assert.isObject(result); + assert.isObject(result.ast); + assert.include(result.code, 'public class A'); + // Assert ast + const ast = result.ast; + assert.equal(JTKind.COMPILATION_UNIT, ast.kind); +} + +// Contract.Ignore + +function testContractIgnoreCompilationUnit() { + const result = jaspiler.transformSync( + `package a.b.c; + @JaspilerContract.Ignore + public class A { + } + `, + { plugins: [PluginContractIgnore], ast: true, fileName: 'A', sourceType: 'string' }); + // Assert { ast, code } + assert.isObject(result); + assert.isTrue(result.ast.isActionIgnore()); + assert.isUndefined(result.code); +} + +function testContractIgnoreClass() { + const result = jaspiler.transformSync( + `package a.b.c; + @JaspilerContract.Ignore + class A { + } + `, + { plugins: [PluginContractIgnore], ast: true, fileName: 'A', sourceType: 'string' }); + // Assert { ast, code } + assert.isObject(result); + assert.isFalse(result.ast.isActionIgnore()); + assert.include(result.code, 'package a.b.c;'); + assert.notInclude(result.code, 'class A'); +} + +function testContractIgnoreMethod() { + const result = jaspiler.transformSync( + `package a.b.c; + public class A { + @JaspilerContract.Ignore + public void test() {} + } + `, + { plugins: [PluginContractIgnore], ast: true, fileName: 'A', sourceType: 'string' }); + // Assert { ast, code } + assert.isObject(result); + assert.include(result.code, 'public class A {'); + assert.notInclude(result.code, 'public void test()'); +} + +function testContractIgnoreProperty() { + const context = { hideB: false }; + const result = jaspiler.transformSync( + `package a.b.c; + public class A { + @JaspilerContract.Ignore + private int a; + @JaspilerContract.Ignore(condition = "hideB") + private int b; + } + `, + { plugins: [PluginContractIgnore], context: context, ast: true, fileName: 'A', sourceType: 'string' }); + // Assert { ast, code } + assert.isObject(result); + assert.include(result.code, 'public class A {'); + assert.notInclude(result.code, 'private int a;'); + assert.include(result.code, 'private int b;'); +} + +function testContractChangeMethod() { + const context = { options: {} }; + const result = jaspiler.transformSync( + `package a.b.c; + public class A { + @JaspilerContract.Change(instruction = "options = { type: 'clear' }") + public void testVoid() { 1 + 1; } + @JaspilerContract.Change(instruction = "options = { type: 'clear' }") + public boolean testBoolean() { return true; } + @JaspilerContract.Change(instruction = "options = { type: 'clear' }") + public char testChar() { return 'a'; } + @JaspilerContract.Change(instruction = "options = { type: 'clear' }") + public double testDouble() { return 1.23D; } + @JaspilerContract.Change(instruction = "options = { type: 'clear' }") + public float testFloat() { return 1.23F; } + @JaspilerContract.Change(instruction = "options = { type: 'clear' }") + public int testInt() { return 1; } + @JaspilerContract.Change(instruction = "options = { type: 'clear' }") + public long testLong() { return 1L; } + @JaspilerContract.Change(instruction = "options = { type: 'clear' }") + public Object testObject() { return new Object(); } + @JaspilerContract.Change(instruction = "options = { type: 'clear' }") + public String testString() { return "123"; } + } + `, + { plugins: [PluginContractChangeMethod], context: context, ast: true, fileName: 'A', sourceType: 'string' }); + // Assert { ast, code } + assert.isObject(result); + assert.include(result.code, 'public void testVoid() {\n }'); + assert.include(result.code, 'public boolean testBoolean() {\n return false;\n }'); + assert.include(result.code, 'public char testChar() {\n return \'\\0\';\n }'); + assert.include(result.code, 'public double testDouble() {\n return 0D;\n }'); + assert.include(result.code, 'public float testFloat() {\n return 0F;\n }'); + assert.include(result.code, 'public int testInt() {\n return 0;\n }'); + assert.include(result.code, 'public long testLong() {\n return 0L;\n }'); + assert.include(result.code, 'public Object testObject() {\n return null;\n }'); + assert.include(result.code, 'public String testString() {\n return null;\n }'); +} + +// Package + +function testIgnorePackage() { + const result = jaspiler.transformSync(pathMockPublicAnnotation, { + plugins: [{ + visitor: { + Package(node) { + assert.equal(0, node.annotations.length); + assert.isTrue(node.isActionNoChange()); + assert.isFalse(node.isActionChange()); + assert.isFalse(node.isActionIgnore()); + assert.isTrue(node.setActionIgnore()); + assert.isFalse(node.isActionNoChange()); + assert.isFalse(node.isActionChange()); + assert.isTrue(node.isActionIgnore()); + }, + }, + }], + }); + assert.notInclude(result.code, 'package com.caoccao.jaspiler.mock;'); +} + +function testReplacePackage() { + const result = jaspiler.transformSync(pathMockPublicAnnotation, { + plugins: [{ + visitor: { + Package(node) { + assert.equal(JTKind.PACKAGE, node.kind); + assert.equal('com.caoccao.jaspiler.trees.JTPackageDecl', node.className); + assert.equal('JTPackageDecl', node.classSimpleName); + assert.equal('package com.caoccao.jaspiler.mock;', node.toString()); + const compilationUnit = node.parentTree; + assert.equal('com.caoccao.jaspiler.trees.JTCompilationUnit', compilationUnit.className); + assert.equal('JTCompilationUnit', compilationUnit.classSimpleName); + assert.isNotNull(compilationUnit); + const packageDecl = jaspiler.newPackageDecl(); + assert.equal('com.caoccao.jaspiler.trees.JTPackageDecl', packageDecl.className); + assert.equal('JTPackageDecl', packageDecl.classSimpleName); + packageDecl.packageName = jaspiler.createFieldAccess('abc', 'def', 'ghi'); + compilationUnit.package = packageDecl; + }, + }, + }], + }); + assert.include(result.code, 'package abc.def.ghi;'); +} + +function testReplacePackageName() { + const result = jaspiler.transformSync(pathMockPublicAnnotation, { + plugins: [{ + visitor: { + Package(node) { + assert.isTrue(node.isActionNoChange()); + node.packageName = jaspiler.createFieldAccess('abc', 'def', 'ghi'); + assert.isTrue(node.isActionChange()); + }, + }, + }], + }); + assert.include(result.code, 'package abc.def.ghi;'); +} + +// Imports + +function testImports() { + const result = jaspiler.transformSync(pathMockPublicAnnotation, { + plugins: [{ + visitor: { + CompilationUnit(node) { + assert.equal(JTKind.COMPILATION_UNIT, node.kind); + assert.equal(pathMockPublicAnnotation, node.sourceFile, 'The source file should match'); + const imports = node.imports; + assert.equal(2, imports.length); + imports.push(imports.shift()); + const newImport = jaspiler.newImport(); + newImport.qualifiedIdentifier = jaspiler.createFieldAccess('abc', 'def', 'ghi'); + newImport.staticImport = true; + imports.push(newImport); + node.imports = imports; + }, + }, + }], + }); + assert.include( + result.code, + 'import java.lang.annotation.Inherited;\n' + + 'import java.lang.annotation.Documented;\n' + + 'import static abc.def.ghi;\n'); +} + +// Class + +function testClass() { + const simpleNames = [] + const result = jaspiler.transformSync(pathMockAllInOnePublicClass, { + plugins: [{ + visitor: { + Class(node) { + assert.equal('com.caoccao.jaspiler.trees.JTClassDecl', node.className); + const modifiers = node.modifiers; + assert.equal('com.caoccao.jaspiler.trees.JTModifiers', modifiers.className); + const simpleName = node.simpleName.value; + simpleNames.push(simpleName); + if ('MockAnnotation' == simpleName) { + assert.equal(JTKind.ANNOTATION_TYPE, node.kind); + const annotations = modifiers.annotations; + assert.equal(4, annotations.length); + annotations.push(annotations.shift()); + assert.equal('@Inherited', annotations[0].toString()); + assert.equal('com.caoccao.jaspiler.trees.JTIdent', annotations[0].annotationType.className); + assert.equal('Inherited', annotations[0].annotationType.name.value); + assert.equal(0, annotations[0].arguments.length); + assert.equal('Retention', annotations[1].annotationType.name.value); + assert.equal(1, annotations[1].arguments.length); + annotations[0].annotationType = jaspiler.createIdent('NotInherited'); + const args = annotations[1].arguments; + args.push(jaspiler.createFieldAccess('aaa', 'bbb')); + annotations[1].arguments = args; + modifiers.annotations = annotations; + assert.equal(0, node.typeParameters.length); + assert.isNull(node.extendsClause); + assert.equal(0, node.implementsClauses.length); + assert.equal(0, node.permitsClauses.length); + assert.equal(2, node.members.length); + assert.equal('String[] names() default {"A", "B"};', node.members[0].toString()); + } else if ('MockAllInOnePublicClass' == simpleName) { + assert.equal(JTKind.CLASS, node.kind); + assert.isNotNull(node.extendsClause); + assert.equal('Object', node.extendsClause.toString()); + assert.equal(2, node.implementsClauses.length); + assert.equal('Serializable', node.implementsClauses[0].toString()); + assert.equal(1, node.permitsClauses.length); + assert.equal('MockChild', node.permitsClauses[0].toString()); + assert.equal(8, node.members.length); + assert.equal('private String a;', node.members[1].toString()); + } else if ('MockChild' == simpleName) { + node.simpleName = jaspiler.createName('NewMockChild'); + } else if ('MockChild1' == simpleName) { + node.simpleName = jaspiler.createName('NewMockChild1'); + } + }, + }, + }], + }); + assert.equal('MockAnnotation,MockAllInOnePublicClass,,MockChild,MockChild1', simpleNames.join(',')); + assert.include(result.code, '@NotInherited\n' + + '@Retention(RetentionPolicy.RUNTIME, aaa.bbb)\n' + + '@Target(ElementType.ANNOTATION_TYPE)\n' + + '@Documented\n'); + assert.include(result.code, 'final class NewMockChild extends MockAllInOnePublicClass {'); +} + +// Identifier + +function testIdentifier() { + const values = []; + const result = jaspiler.transformSync(pathMockPublicAnnotation, { + plugins: [{ + visitor: { + Identifier(node) { + const value = node.name.value; + values.push(value); + if (value == 'Inherited') { + node.name = jaspiler.createName('NotInherited'); + } + }, + }, + }], + }); + assert.equal('com,java,java,Documented,Inherited,String,String', values.join(',')); + assert.include(result.code, '@NotInherited'); +} + +// Import + +function testImport() { + const values = []; + const result = jaspiler.transformSync(pathMockPublicAnnotation, { + plugins: [{ + visitor: { + Import(node) { + assert.isFalse(node.staticImport); + values.push(node.qualifiedIdentifier.toString()); + node.staticImport = true; + }, + }, + }], + }); + assert.equal(2, values.length); + assert.equal('java.lang.annotation.Documented', values[0]); + assert.equal('java.lang.annotation.Inherited', values[1]); + assert.include( + result.code, + 'import static java.lang.annotation.Documented;\n' + + 'import static java.lang.annotation.Inherited;\n'); +} + +// Variable +function testVariable() { + const result = jaspiler.transformSync(pathMockAllInOnePublicClass, { + plugins: [{ + visitor: { + Variable(node) { + const value = node.name.value; + if ('x' == value) { + node.name = jaspiler.createName('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'); + } else if ('y' == value) { + node.name = jaspiler.createName('yy'); + } else if ('a' == value) { + node.name = jaspiler.createName('aa'); + } else if ('c' == value) { + node.name = jaspiler.createName('cc'); + } + }, + }, + }], + }); + assert.include(result.code, '\n private String aa;\n'); + assert.include(result.code, '\n @SuppressWarnings("unchecked")\n'); + assert.include( + result.code, + '\n @SuppressWarnings("unchecked")\n' + + ' public final void Test(T xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, @Deprecated int yy)\n' + + ' throws IOException, NoClassDefFoundError {\n'); + assert.include(result.code, '\n int cc = 5;\n'); +} + +// Method + +function testMethod() { + const methodNames = []; + const result = jaspiler.transformSync(pathMockAllInOnePublicClass, { + plugins: [{ + visitor: { + Method(node) { + assert.equal('com.caoccao.jaspiler.trees.JTMethodDecl', node.className); + const methodName = node.name.value; + methodNames.push(methodName); + if (methodName == 'names') { + const modifiers = node.modifiers; + assert.isEmpty(modifiers.toString()); + assert.isEmpty(modifiers.annotations); + assert.isEmpty(modifiers.flags); + assert.isEmpty(node.parameters); + assert.isNull(node.receiverParameter); + assert.isEmpty(node.returnType); + assert.isEmpty(node.throwExpressions); + assert.isEmpty(node.typeParameters); + assert.equal('com.caoccao.jaspiler.trees.JTNewArray', node.defaultValue.className); + assert.equal('{"A", "B"}', node.defaultValue.toString()); + node.defaultValue = jaspiler.createFieldAccess('ABC'); + } else if (methodName == 'value') { + assert.equal('com.caoccao.jaspiler.trees.JTLiteral', node.defaultValue.className); + assert.equal(JTKind.STRING_LITERAL, node.defaultValue.kind); + } else if (methodName == 'Test') { + assert.equal(1, node.modifiers.annotations.length); + assert.equal(2, node.modifiers.flags.length); + assert.equal(1, node.typeParameters.length); + assert.equal('T', node.typeParameters[0].toString()); + assert.equal('void', node.returnType.toString()); + assert.equal(2, node.throwExpressions.length); + assert.equal(2, node.parameters.length); + } + }, + }, + }], + }); + assert.equal('names,value,Test,add,close', methodNames.join(',')); + assert.include(result.code, '\n String[] names() default ABC;\n'); +} + +// Block +function testBlock() { + const values = []; + jaspiler.transformSync(pathMockAllInOnePublicClass, { + plugins: [{ + visitor: { + Block(node) { + const value = node.toString(); + if (value.includes('System.out.println("static block");')) { + values.push(value); + assert.equal(1, node.statements.length); + assert.isTrue(node.static); + } else if (value.includes('put("a", 1);')) { + values.push(value); + assert.equal(2, node.statements.length); + assert.isFalse(node.static); + } + }, + }, + }], + }); + assert.equal(2, values.length); +} + +// Other + +function testOther() { + let count = 0; + jaspiler.transformSync(pathMockForScan, { + plugins: [{ + visitor: { + Other(node) { + count++; + }, + }, + }], + }); + assert.equal(0, count, 'There should not be other nodes'); +} + +// Scan + +function testScan() { + const classSimpleNameSet = new Set(); + jaspiler.transformSync(pathMockForScan, { + plugins: [{ + visitor: { + Scan(node) { + if (node) { + classSimpleNameSet.add(node.classSimpleName); + } + }, + }, + }], + }); + const expectedClassSimpleNameSet = new Set([ + 'JTCompilationUnit', 'JTPackageDecl', 'JTFieldAccess', 'JTIdent', 'JTImport', + 'JTClassDecl', 'JTModifiers', 'JTMethodDecl', 'JTArrayType', 'JTNewArray', + 'JTPrimitiveType', 'JTBlock', 'JTAnnotation', 'JTLiteral', 'JTVariableDecl', + 'JTExpressionStatement', 'JTForLoop', 'JTBinary', 'JTUnary', 'JTReturn', + 'JTNewClass', 'JTIf', 'JTAssign', + 'JTSwitch', 'JTCase', 'JTBreak', + 'JTMethodInvocation', 'JTWhileLoop', 'JTDoWhileLoop', 'JTParens']); + const unexpectedClassSimpleNames = + [...classSimpleNameSet].filter(name => !expectedClassSimpleNameSet.has(name)); + assert.equal(0, unexpectedClassSimpleNames.length, + 'Unexpected [\'' + unexpectedClassSimpleNames.join('\',\'') + '\']'); +} + +// AST +testAstForFile(); +testAstForString(); +// Contract.Ignore +testContractIgnoreCompilationUnit(); +testContractIgnoreClass(); +testContractIgnoreMethod(); +testContractIgnoreProperty(); +testContractChangeMethod(); +// Package +testIgnorePackage(); +testReplacePackage(); +testReplacePackageName(); +// Imports +testImports(); +// Class +testClass(); +// Identifier +testIdentifier(); +// Import +testImport(); +// Variable +testVariable(); +// Method +testMethod(); +// Block +testBlock(); +// Other +testOther(); +// Scan +testScan(); diff --git a/scripts/node/tutorials/01_quick_start.js b/scripts/node/tutorials/01_quick_start.js index f19e1d9..3aff0c4 100644 --- a/scripts/node/tutorials/01_quick_start.js +++ b/scripts/node/tutorials/01_quick_start.js @@ -1,34 +1,34 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// Tutorial 01: Quick Start - -const result = jaspiler.transformSync( - `package com.test; - public class A { - } - `, - { - plugins: [{ - visitor: { - Class(node) { - node.simpleName = jaspiler.createName('B'); - }, - }, - }], - sourceType: 'string', - }); -console.info(result.code); +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Tutorial 01: Quick Start + +const result = jaspiler.transformSync( + `package com.test; + public class A { + } + `, + { + plugins: [{ + visitor: { + Class(node) { + node.simpleName = jaspiler.createName('B'); + }, + }, + }], + sourceType: 'string', + }); +console.info(result.code); diff --git a/scripts/node/tutorials/02_play_with_types.js b/scripts/node/tutorials/02_play_with_types.js index 17c0ea6..64bb8dc 100644 --- a/scripts/node/tutorials/02_play_with_types.js +++ b/scripts/node/tutorials/02_play_with_types.js @@ -1,54 +1,54 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// Tutorial 02: Play with Types - -/// - -const { JTKind } = require('../jaspiler/jaspiler'); - -const result = jaspiler.transformSync( - `package com.test; - public class A {} - public interface B {} - public record C() {} - public class D {} - `, - { - plugins: [{ - visitor: { - Class(node) { - const simpleName = node.simpleName.value; - switch (simpleName) { - case 'A': - node.kind = JTKind.INTERFACE; - break; - case 'B': - node.kind = JTKind.CLASS; - break; - case 'C': - node.kind = JTKind.ENUM; - break; - case 'D': - node.kind = JTKind.RECORD; - break; - } - }, - }, - }], - sourceType: 'string', - }); -console.info(result.code); +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Tutorial 02: Play with Types + +/// + +const { JTKind } = require('../jaspiler/jaspiler'); + +const result = jaspiler.transformSync( + `package com.test; + public class A {} + public interface B {} + public record C() {} + public class D {} + `, + { + plugins: [{ + visitor: { + Class(node) { + const simpleName = node.simpleName.value; + switch (simpleName) { + case 'A': + node.kind = JTKind.INTERFACE; + break; + case 'B': + node.kind = JTKind.CLASS; + break; + case 'C': + node.kind = JTKind.ENUM; + break; + case 'D': + node.kind = JTKind.RECORD; + break; + } + }, + }, + }], + sourceType: 'string', + }); +console.info(result.code); diff --git a/scripts/node/tutorials/03_builtin_annotations.js b/scripts/node/tutorials/03_builtin_annotations.js index fee4d35..a118018 100644 --- a/scripts/node/tutorials/03_builtin_annotations.js +++ b/scripts/node/tutorials/03_builtin_annotations.js @@ -1,65 +1,65 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// Tutorial 03: Built-in Annotations - -/// - -const { PluginContractIgnore, PluginContractChangeMethod } = require('../jaspiler/jaspiler'); - -const result = jaspiler.transformSync( - `package com.test; - - public class A { - @JaspilerContract.Ignore - private int a; // This property is ignored. - - @JaspilerContract.Ignore(condition = "x == 1") - private int b; // This property is ignored. - - @JaspilerContract.Ignore(condition = "x == 2") - private int c; // This property is not ignored. - - @JaspilerContract.Ignore - public void d() { - // This method is ignored. - } - - @JaspilerContract.Change(instruction = "options = { type: 'clear' }") - public void e(String str) { - System.out.println(str); // This method is cleared. - } - - @JaspilerContract.Change(condition = "x == 1", instruction = "options = { type: 'clear' }") - public int f(int x, int y) { - return x + y; // This method is cleared. - } - - @JaspilerContract.Change(condition = "x == 2", instruction = "options = { type: 'clear' }") - public int g(int x, int y) { - return x + y; // This method is not cleared. - } - } - - @JaspilerContract.Ignore - interface B {} // This interface is ignored. - `, - { - context: { x: 1, options: {} }, - plugins: [PluginContractIgnore, PluginContractChangeMethod], - sourceType: 'string', - }); -console.info(result.code); +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Tutorial 03: Built-in Annotations + +/// + +const { PluginContractIgnore, PluginContractChangeMethod } = require('../jaspiler/jaspiler'); + +const result = jaspiler.transformSync( + `package com.test; + + public class A { + @JaspilerContract.Ignore + private int a; // This property is ignored. + + @JaspilerContract.Ignore(condition = "x == 1") + private int b; // This property is ignored. + + @JaspilerContract.Ignore(condition = "x == 2") + private int c; // This property is not ignored. + + @JaspilerContract.Ignore + public void d() { + // This method is ignored. + } + + @JaspilerContract.Change(instruction = "options = { type: 'clear' }") + public void e(String str) { + System.out.println(str); // This method is cleared. + } + + @JaspilerContract.Change(condition = "x == 1", instruction = "options = { type: 'clear' }") + public int f(int x, int y) { + return x + y; // This method is cleared. + } + + @JaspilerContract.Change(condition = "x == 2", instruction = "options = { type: 'clear' }") + public int g(int x, int y) { + return x + y; // This method is not cleared. + } + } + + @JaspilerContract.Ignore + interface B {} // This interface is ignored. + `, + { + context: { x: 1, options: {} }, + plugins: [PluginContractIgnore, PluginContractChangeMethod], + sourceType: 'string', + }); +console.info(result.code); diff --git a/scripts/node/tutorials/04_parse_argv.js b/scripts/node/tutorials/04_parse_argv.js index cb84b0d..d7d8b39 100644 --- a/scripts/node/tutorials/04_parse_argv.js +++ b/scripts/node/tutorials/04_parse_argv.js @@ -1,44 +1,44 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// Tutorial 04: Parse argv - -/// - -process.argv = [process.argv[0], ...jaspiler.argv]; -process.chdir('../') -const yargs = require('yargs'); - -const argv = yargs - .option('input', { - alias: 'i', - type: 'string', - describe: 'the input', - demandOption: true, - }) - .option('output', { - alias: 'o', - type: 'string', - describe: 'the output', - demandOption: true, - }) - .version('1.0.0') - .help() - .argv; - -console.info(); -console.info(` Input: ${argv.input}`); +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Tutorial 04: Parse argv + +/// + +process.argv = [process.argv[0], ...jaspiler.argv]; +process.chdir('../') +const yargs = require('yargs'); + +const argv = yargs + .option('input', { + alias: 'i', + type: 'string', + describe: 'the input', + demandOption: true, + }) + .option('output', { + alias: 'o', + type: 'string', + describe: 'the output', + demandOption: true, + }) + .version('1.0.0') + .help() + .argv; + +console.info(); +console.info(` Input: ${argv.input}`); console.info(`Output: ${argv.output}`); \ No newline at end of file diff --git a/settings.gradle.kts b/settings.gradle.kts index 88c5688..aa6586d 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1,19 +1,19 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import org.gradle.internal.os.OperatingSystem - -rootProject.name = if (OperatingSystem.current().isMacOsX) "Jaspiler-macos" else "Jaspiler" +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.gradle.internal.os.OperatingSystem + +rootProject.name = if (OperatingSystem.current().isMacOsX) "Jaspiler-macos" else "Jaspiler" diff --git a/src/main/java/com/caoccao/jaspiler/JaspilerCompiler.java b/src/main/java/com/caoccao/jaspiler/JaspilerCompiler.java index 3c3a9e6..a31f262 100644 --- a/src/main/java/com/caoccao/jaspiler/JaspilerCompiler.java +++ b/src/main/java/com/caoccao/jaspiler/JaspilerCompiler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/JaspilerContract.java b/src/main/java/com/caoccao/jaspiler/JaspilerContract.java index a614aef..6114fda 100644 --- a/src/main/java/com/caoccao/jaspiler/JaspilerContract.java +++ b/src/main/java/com/caoccao/jaspiler/JaspilerContract.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/JaspilerMain.java b/src/main/java/com/caoccao/jaspiler/JaspilerMain.java index 75c08b1..a391233 100644 --- a/src/main/java/com/caoccao/jaspiler/JaspilerMain.java +++ b/src/main/java/com/caoccao/jaspiler/JaspilerMain.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/contexts/BaseJaspilerContext.java b/src/main/java/com/caoccao/jaspiler/contexts/BaseJaspilerContext.java index 90a711a..9c7dbfd 100644 --- a/src/main/java/com/caoccao/jaspiler/contexts/BaseJaspilerContext.java +++ b/src/main/java/com/caoccao/jaspiler/contexts/BaseJaspilerContext.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/contexts/JaspilerDocContext.java b/src/main/java/com/caoccao/jaspiler/contexts/JaspilerDocContext.java index 8f879c6..d397ed6 100644 --- a/src/main/java/com/caoccao/jaspiler/contexts/JaspilerDocContext.java +++ b/src/main/java/com/caoccao/jaspiler/contexts/JaspilerDocContext.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/contexts/JaspilerParseContext.java b/src/main/java/com/caoccao/jaspiler/contexts/JaspilerParseContext.java index bea5286..2102213 100644 --- a/src/main/java/com/caoccao/jaspiler/contexts/JaspilerParseContext.java +++ b/src/main/java/com/caoccao/jaspiler/contexts/JaspilerParseContext.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/contexts/JaspilerTransformContext.java b/src/main/java/com/caoccao/jaspiler/contexts/JaspilerTransformContext.java index b2fb32d..b0853cf 100644 --- a/src/main/java/com/caoccao/jaspiler/contexts/JaspilerTransformContext.java +++ b/src/main/java/com/caoccao/jaspiler/contexts/JaspilerTransformContext.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/contexts/package-info.java b/src/main/java/com/caoccao/jaspiler/contexts/package-info.java index 5172b99..23334ac 100644 --- a/src/main/java/com/caoccao/jaspiler/contexts/package-info.java +++ b/src/main/java/com/caoccao/jaspiler/contexts/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/enums/JaspilerExitCode.java b/src/main/java/com/caoccao/jaspiler/enums/JaspilerExitCode.java index 1a1ed52..8b64341 100644 --- a/src/main/java/com/caoccao/jaspiler/enums/JaspilerExitCode.java +++ b/src/main/java/com/caoccao/jaspiler/enums/JaspilerExitCode.java @@ -1,43 +1,43 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.enums; - -public enum JaspilerExitCode { - UnknownError(1, "The is an unknown error: {}"), - OptionsInvalid(2, "The options is invalid."), - ScriptAbsent(101, "The script is absent."), - ScriptNotFound(102, "The script [{}] is not found."), - ScriptEmpty(103, "The script [{}] is empty."), - EngineUnknownError(201, "The Node.js engine met an unknown error: {}"), - NoError(0, "There is no error."); - - private final int exitCode; - private final String messageFormat; - - JaspilerExitCode(int exitCode, String messageFormat) { - this.exitCode = exitCode; - this.messageFormat = messageFormat; - } - - public int getExitCode() { - return exitCode; - } - - public String getMessageFormat() { - return messageFormat; - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.enums; + +public enum JaspilerExitCode { + UnknownError(1, "The is an unknown error: {}"), + OptionsInvalid(2, "The options is invalid."), + ScriptAbsent(101, "The script is absent."), + ScriptNotFound(102, "The script [{}] is not found."), + ScriptEmpty(103, "The script [{}] is empty."), + EngineUnknownError(201, "The Node.js engine met an unknown error: {}"), + NoError(0, "There is no error."); + + private final int exitCode; + private final String messageFormat; + + JaspilerExitCode(int exitCode, String messageFormat) { + this.exitCode = exitCode; + this.messageFormat = messageFormat; + } + + public int getExitCode() { + return exitCode; + } + + public String getMessageFormat() { + return messageFormat; + } +} diff --git a/src/main/java/com/caoccao/jaspiler/enums/JavaKeyword.java b/src/main/java/com/caoccao/jaspiler/enums/JavaKeyword.java index ba243e1..627194c 100644 --- a/src/main/java/com/caoccao/jaspiler/enums/JavaKeyword.java +++ b/src/main/java/com/caoccao/jaspiler/enums/JavaKeyword.java @@ -1,103 +1,103 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.enums; - -public enum JavaKeyword { - ABSTRACT("abstract"), - ASSERT("assert"), - BOOLEAN("boolean"), - BREAK("break"), - BYTE("byte"), - CASE("case"), - CATCH("catch"), - CHAR("char"), - CLASS("class"), - CONST("const"), - CONTINUE("continue"), - DEFAULT("default"), - DO("do"), - DOUBLE("double"), - ELSE("else"), - ENUM("enum"), - EXPORTS("exports"), - EXTENDS("extends"), - FINAL("final"), - FINALLY("finally"), - FLOAT("float"), - FOR("for"), - GOTO("goto"), - IF("if"), - IMPLEMENTS("implements"), - IMPORT("import"), - INSTANCEOF("instanceOf"), - INT("int"), - INTERFACE("interface"), - LONG("long"), - MODULE("module"), - NATIve("native"), - NEW("new"), - NON("non"), - OPEN("open"), - OPENS("opens"), - PACKAGE("package"), - PERMITS("permits"), - PRIVATE("private"), - PROTECTED("protected"), - PROVIDES("provides"), - PUBLic("public"), - RECORD("record"), - REQUIRES("requires"), - RETURN("return"), - SEALED("sealed"), - SHORT("short"), - STATIC("static"), - STRICTFP("strictfp"), - SUPER("super"), - SWITCH("switch"), - SYNCHRONIZED("synchronized"), - THIS("this"), - THROW("throw"), - THROWS("throws"), - TRANSIENT("transient"), - TRY("try"), - UNDERSCORE("_"), - USES("uses"), - VAR("var"), - VOID("void"), - VOLATILE("volatile"), - WHILE("while"), - YIELD("yield"); - - private final String value; - - JavaKeyword(String value) { - this.value = value; - } - - public int getLength() { - return value.length(); - } - - public String getValue() { - return value; - } - - @Override - public String toString() { - return value; - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.enums; + +public enum JavaKeyword { + ABSTRACT("abstract"), + ASSERT("assert"), + BOOLEAN("boolean"), + BREAK("break"), + BYTE("byte"), + CASE("case"), + CATCH("catch"), + CHAR("char"), + CLASS("class"), + CONST("const"), + CONTINUE("continue"), + DEFAULT("default"), + DO("do"), + DOUBLE("double"), + ELSE("else"), + ENUM("enum"), + EXPORTS("exports"), + EXTENDS("extends"), + FINAL("final"), + FINALLY("finally"), + FLOAT("float"), + FOR("for"), + GOTO("goto"), + IF("if"), + IMPLEMENTS("implements"), + IMPORT("import"), + INSTANCEOF("instanceOf"), + INT("int"), + INTERFACE("interface"), + LONG("long"), + MODULE("module"), + NATIve("native"), + NEW("new"), + NON("non"), + OPEN("open"), + OPENS("opens"), + PACKAGE("package"), + PERMITS("permits"), + PRIVATE("private"), + PROTECTED("protected"), + PROVIDES("provides"), + PUBLic("public"), + RECORD("record"), + REQUIRES("requires"), + RETURN("return"), + SEALED("sealed"), + SHORT("short"), + STATIC("static"), + STRICTFP("strictfp"), + SUPER("super"), + SWITCH("switch"), + SYNCHRONIZED("synchronized"), + THIS("this"), + THROW("throw"), + THROWS("throws"), + TRANSIENT("transient"), + TRY("try"), + UNDERSCORE("_"), + USES("uses"), + VAR("var"), + VOID("void"), + VOLATILE("volatile"), + WHILE("while"), + YIELD("yield"); + + private final String value; + + JavaKeyword(String value) { + this.value = value; + } + + public int getLength() { + return value.length(); + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return value; + } +} diff --git a/src/main/java/com/caoccao/jaspiler/exceptions/JaspilerArgumentException.java b/src/main/java/com/caoccao/jaspiler/exceptions/JaspilerArgumentException.java index 1a7d0df..4f3e072 100644 --- a/src/main/java/com/caoccao/jaspiler/exceptions/JaspilerArgumentException.java +++ b/src/main/java/com/caoccao/jaspiler/exceptions/JaspilerArgumentException.java @@ -1,27 +1,27 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.exceptions; - -public class JaspilerArgumentException extends JaspilerCheckedException { - public JaspilerArgumentException(String message) { - super(message); - } - - public JaspilerArgumentException(String message, Throwable cause) { - super(message, cause); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.exceptions; + +public class JaspilerArgumentException extends JaspilerCheckedException { + public JaspilerArgumentException(String message) { + super(message); + } + + public JaspilerArgumentException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/exceptions/JaspilerCheckedException.java b/src/main/java/com/caoccao/jaspiler/exceptions/JaspilerCheckedException.java index dd391fb..3e62361 100644 --- a/src/main/java/com/caoccao/jaspiler/exceptions/JaspilerCheckedException.java +++ b/src/main/java/com/caoccao/jaspiler/exceptions/JaspilerCheckedException.java @@ -1,27 +1,27 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.exceptions; - -public abstract class JaspilerCheckedException extends Exception { - public JaspilerCheckedException(String message) { - super(message); - } - - public JaspilerCheckedException(String message, Throwable cause) { - super(message, cause); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.exceptions; + +public abstract class JaspilerCheckedException extends Exception { + public JaspilerCheckedException(String message) { + super(message); + } + + public JaspilerCheckedException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/exceptions/JaspilerExecutionException.java b/src/main/java/com/caoccao/jaspiler/exceptions/JaspilerExecutionException.java index 0033bdc..f25bc76 100644 --- a/src/main/java/com/caoccao/jaspiler/exceptions/JaspilerExecutionException.java +++ b/src/main/java/com/caoccao/jaspiler/exceptions/JaspilerExecutionException.java @@ -1,27 +1,27 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.exceptions; - -public class JaspilerExecutionException extends JaspilerCheckedException { - public JaspilerExecutionException(String message) { - super(message); - } - - public JaspilerExecutionException(String message, Throwable cause) { - super(message, cause); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.exceptions; + +public class JaspilerExecutionException extends JaspilerCheckedException { + public JaspilerExecutionException(String message) { + super(message); + } + + public JaspilerExecutionException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/exceptions/JaspilerNotImplementedException.java b/src/main/java/com/caoccao/jaspiler/exceptions/JaspilerNotImplementedException.java index 9ec7b6c..0005bc2 100644 --- a/src/main/java/com/caoccao/jaspiler/exceptions/JaspilerNotImplementedException.java +++ b/src/main/java/com/caoccao/jaspiler/exceptions/JaspilerNotImplementedException.java @@ -1,31 +1,31 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.exceptions; - -public class JaspilerNotImplementedException extends JaspilerUncheckedException { - public JaspilerNotImplementedException() { - super(); - } - - public JaspilerNotImplementedException(String message) { - super(message); - } - - public JaspilerNotImplementedException(String message, Throwable cause) { - super(message, cause); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.exceptions; + +public class JaspilerNotImplementedException extends JaspilerUncheckedException { + public JaspilerNotImplementedException() { + super(); + } + + public JaspilerNotImplementedException(String message) { + super(message); + } + + public JaspilerNotImplementedException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/exceptions/JaspilerNotSupportedException.java b/src/main/java/com/caoccao/jaspiler/exceptions/JaspilerNotSupportedException.java index 73f2c71..2a6fdb3 100644 --- a/src/main/java/com/caoccao/jaspiler/exceptions/JaspilerNotSupportedException.java +++ b/src/main/java/com/caoccao/jaspiler/exceptions/JaspilerNotSupportedException.java @@ -1,31 +1,31 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.exceptions; - -public class JaspilerNotSupportedException extends JaspilerUncheckedException { - public JaspilerNotSupportedException() { - super(); - } - - public JaspilerNotSupportedException(String message) { - super(message); - } - - public JaspilerNotSupportedException(String message, Throwable cause) { - super(message, cause); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.exceptions; + +public class JaspilerNotSupportedException extends JaspilerUncheckedException { + public JaspilerNotSupportedException() { + super(); + } + + public JaspilerNotSupportedException(String message) { + super(message); + } + + public JaspilerNotSupportedException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/exceptions/JaspilerParseException.java b/src/main/java/com/caoccao/jaspiler/exceptions/JaspilerParseException.java index f71e1ce..34d630e 100644 --- a/src/main/java/com/caoccao/jaspiler/exceptions/JaspilerParseException.java +++ b/src/main/java/com/caoccao/jaspiler/exceptions/JaspilerParseException.java @@ -1,27 +1,27 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.exceptions; - -public class JaspilerParseException extends JaspilerCheckedException { - public JaspilerParseException(String message) { - super(message); - } - - public JaspilerParseException(String message, Throwable cause) { - super(message, cause); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.exceptions; + +public class JaspilerParseException extends JaspilerCheckedException { + public JaspilerParseException(String message) { + super(message); + } + + public JaspilerParseException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/exceptions/JaspilerUncheckedException.java b/src/main/java/com/caoccao/jaspiler/exceptions/JaspilerUncheckedException.java index 3de4338..8477ada 100644 --- a/src/main/java/com/caoccao/jaspiler/exceptions/JaspilerUncheckedException.java +++ b/src/main/java/com/caoccao/jaspiler/exceptions/JaspilerUncheckedException.java @@ -1,31 +1,31 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.exceptions; - -public abstract class JaspilerUncheckedException extends RuntimeException { - public JaspilerUncheckedException() { - super(); - } - - public JaspilerUncheckedException(String message) { - super(message); - } - - public JaspilerUncheckedException(String message, Throwable cause) { - super(message, cause); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.exceptions; + +public abstract class JaspilerUncheckedException extends RuntimeException { + public JaspilerUncheckedException() { + super(); + } + + public JaspilerUncheckedException(String message) { + super(message); + } + + public JaspilerUncheckedException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/exceptions/package-info.java b/src/main/java/com/caoccao/jaspiler/exceptions/package-info.java index bee941d..38ce7eb 100644 --- a/src/main/java/com/caoccao/jaspiler/exceptions/package-info.java +++ b/src/main/java/com/caoccao/jaspiler/exceptions/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/package-info.java b/src/main/java/com/caoccao/jaspiler/package-info.java index 07c4d33..ffdbf21 100644 --- a/src/main/java/com/caoccao/jaspiler/package-info.java +++ b/src/main/java/com/caoccao/jaspiler/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/styles/BaseStyleWriter.java b/src/main/java/com/caoccao/jaspiler/styles/BaseStyleWriter.java index 27eaed4..2195a14 100644 --- a/src/main/java/com/caoccao/jaspiler/styles/BaseStyleWriter.java +++ b/src/main/java/com/caoccao/jaspiler/styles/BaseStyleWriter.java @@ -1,267 +1,267 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.styles; - -import com.caoccao.jaspiler.enums.JavaKeyword; -import com.caoccao.jaspiler.trees.IJTTree; -import org.apache.commons.lang3.StringUtils; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -@SuppressWarnings("unchecked") -public abstract class BaseStyleWriter> - implements IStyleWriter, Appendable, CharSequence { - protected final List lines; - protected final StyleOptions options; - protected int depth; - protected int lengthOfLines; - protected StringBuilder stringBuilder; - - public BaseStyleWriter(StyleOptions options) { - depth = 0; - lines = new ArrayList<>(); - lengthOfLines = 0; - this.options = options; - stringBuilder = new StringBuilder(); - } - - @Override - public StyleWriter append(CharSequence csq) { - stringBuilder.append(csq); - return (StyleWriter) this; - } - - @Override - public StyleWriter append(CharSequence csq, int start, int end) { - stringBuilder.append(csq, start, end); - return (StyleWriter) this; - } - - @Override - public StyleWriter append(boolean b) { - stringBuilder.append(b); - return (StyleWriter) this; - } - - @Override - public StyleWriter append(char c) { - stringBuilder.append(c); - return (StyleWriter) this; - } - - @Override - public StyleWriter append(double d) { - stringBuilder.append(d); - return (StyleWriter) this; - } - - @Override - public StyleWriter append(float f) { - stringBuilder.append(f); - return (StyleWriter) this; - } - - @Override - public StyleWriter append(int i) { - stringBuilder.append(i); - return (StyleWriter) this; - } - - @Override - public StyleWriter append(long l) { - stringBuilder.append(l); - return (StyleWriter) this; - } - - @Override - public StyleWriter append(short s) { - stringBuilder.append(s); - return (StyleWriter) this; - } - - @Override - public StyleWriter append(Object object) { - stringBuilder.append(object); - return (StyleWriter) this; - } - - @Override - public StyleWriter append(char[] str) { - stringBuilder.append(str); - return (StyleWriter) this; - } - - @Override - public StyleWriter append(IJTTree jtTree) { - jtTree.serialize(this); - return (StyleWriter) this; - } - - @Override - public StyleWriter appendAt() { - return append(AT); - } - - @Override - public StyleWriter appendComma() { - return append(COMMA); - } - - protected StyleWriter appendContinuationIndent() { - return append(StringUtils.repeat(SPACE, options.getContinuationIndentSize())); - } - - @Override - public StyleWriter appendDot() { - return append(DOT); - } - - @Override - public StyleWriter appendEqual() { - return append(EQUAL); - } - - @Override - public StyleWriter appendIndent(int depth) { - if (depth > 0 && options.getIndentSize() > 0) { - stringBuilder.append(StringUtils.repeat(SPACE, depth * options.getIndentSize())); - } - return (StyleWriter) this; - } - - @Override - public StyleWriter appendKeyword(JavaKeyword javaKeyword) { - return appendSpaceIfNeeded().append(Objects.requireNonNull(javaKeyword).getValue()); - } - - @Override - public StyleWriter appendLeftArrow() { - return append(LEFT_ARROW); - } - - protected StyleWriter appendLeftCurlyBracket() { - return append(LEFT_CURLY_BRACKET); - } - - @Override - public StyleWriter appendLeftParenthesis() { - return append(LEFT_PARENTHESIS); - } - - @Override - public StyleWriter appendLineSeparator() { - String line = stringBuilder.toString(); - lines.add(line); - lengthOfLines += line.length(); - stringBuilder = new StringBuilder(); - return (StyleWriter) this; - } - - protected StyleWriter appendLineSeparator(int count) { - for (int i = 0; i < count; i++) { - appendLineSeparator(); - } - return (StyleWriter) this; - } - - @Override - public StyleWriter appendRightArrow() { - return append(RIGHT_ARROW); - } - - protected StyleWriter appendRightCurlyBracket() { - return append(RIGHT_CURLY_BRACKET); - } - - @Override - public StyleWriter appendRightParenthesis() { - return append(RIGHT_PARENTHESIS); - } - - @Override - public StyleWriter appendSemiColon() { - return append(SEMI_COLON); - } - - @Override - public StyleWriter appendSpace() { - return append(SPACE); - } - - @Override - public StyleWriter appendSpaceIfNeeded() { - if (!endsWithWhitespace()) { - appendSpace(); - } - return (StyleWriter) this; - } - - @Override - public char charAt(int index) { - return stringBuilder.charAt(index); - } - - @Override - public int decreaseDepth() { - return depth > 0 ? --depth : depth; - } - - @Override - public boolean endsWithWhitespace() { - if (stringBuilder.isEmpty()) { - return true; - } - return switch (stringBuilder.charAt(stringBuilder.length() - 1)) { - case ' ', '(', '\t', '\r', '\n' -> true; - default -> false; - }; - } - - @Override - public int getDepth() { - return depth; - } - - @Override - public StyleOptions getOptions() { - return options; - } - - @Override - public int increaseDepth() { - return ++depth; - } - - @Override - public int length() { - return lengthOfLines + stringBuilder.length(); - } - - @Override - public CharSequence subSequence(int start, int end) { - return stringBuilder.subSequence(start, end); - } - - @Override - public String toString() { - var totalLines = new ArrayList<>(lines); - totalLines.add(stringBuilder.toString()); - return String.join(LINE_SEPARATOR, totalLines); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.styles; + +import com.caoccao.jaspiler.enums.JavaKeyword; +import com.caoccao.jaspiler.trees.IJTTree; +import org.apache.commons.lang3.StringUtils; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +@SuppressWarnings("unchecked") +public abstract class BaseStyleWriter> + implements IStyleWriter, Appendable, CharSequence { + protected final List lines; + protected final StyleOptions options; + protected int depth; + protected int lengthOfLines; + protected StringBuilder stringBuilder; + + public BaseStyleWriter(StyleOptions options) { + depth = 0; + lines = new ArrayList<>(); + lengthOfLines = 0; + this.options = options; + stringBuilder = new StringBuilder(); + } + + @Override + public StyleWriter append(CharSequence csq) { + stringBuilder.append(csq); + return (StyleWriter) this; + } + + @Override + public StyleWriter append(CharSequence csq, int start, int end) { + stringBuilder.append(csq, start, end); + return (StyleWriter) this; + } + + @Override + public StyleWriter append(boolean b) { + stringBuilder.append(b); + return (StyleWriter) this; + } + + @Override + public StyleWriter append(char c) { + stringBuilder.append(c); + return (StyleWriter) this; + } + + @Override + public StyleWriter append(double d) { + stringBuilder.append(d); + return (StyleWriter) this; + } + + @Override + public StyleWriter append(float f) { + stringBuilder.append(f); + return (StyleWriter) this; + } + + @Override + public StyleWriter append(int i) { + stringBuilder.append(i); + return (StyleWriter) this; + } + + @Override + public StyleWriter append(long l) { + stringBuilder.append(l); + return (StyleWriter) this; + } + + @Override + public StyleWriter append(short s) { + stringBuilder.append(s); + return (StyleWriter) this; + } + + @Override + public StyleWriter append(Object object) { + stringBuilder.append(object); + return (StyleWriter) this; + } + + @Override + public StyleWriter append(char[] str) { + stringBuilder.append(str); + return (StyleWriter) this; + } + + @Override + public StyleWriter append(IJTTree jtTree) { + jtTree.serialize(this); + return (StyleWriter) this; + } + + @Override + public StyleWriter appendAt() { + return append(AT); + } + + @Override + public StyleWriter appendComma() { + return append(COMMA); + } + + protected StyleWriter appendContinuationIndent() { + return append(StringUtils.repeat(SPACE, options.getContinuationIndentSize())); + } + + @Override + public StyleWriter appendDot() { + return append(DOT); + } + + @Override + public StyleWriter appendEqual() { + return append(EQUAL); + } + + @Override + public StyleWriter appendIndent(int depth) { + if (depth > 0 && options.getIndentSize() > 0) { + stringBuilder.append(StringUtils.repeat(SPACE, depth * options.getIndentSize())); + } + return (StyleWriter) this; + } + + @Override + public StyleWriter appendKeyword(JavaKeyword javaKeyword) { + return appendSpaceIfNeeded().append(Objects.requireNonNull(javaKeyword).getValue()); + } + + @Override + public StyleWriter appendLeftArrow() { + return append(LEFT_ARROW); + } + + protected StyleWriter appendLeftCurlyBracket() { + return append(LEFT_CURLY_BRACKET); + } + + @Override + public StyleWriter appendLeftParenthesis() { + return append(LEFT_PARENTHESIS); + } + + @Override + public StyleWriter appendLineSeparator() { + String line = stringBuilder.toString(); + lines.add(line); + lengthOfLines += line.length(); + stringBuilder = new StringBuilder(); + return (StyleWriter) this; + } + + protected StyleWriter appendLineSeparator(int count) { + for (int i = 0; i < count; i++) { + appendLineSeparator(); + } + return (StyleWriter) this; + } + + @Override + public StyleWriter appendRightArrow() { + return append(RIGHT_ARROW); + } + + protected StyleWriter appendRightCurlyBracket() { + return append(RIGHT_CURLY_BRACKET); + } + + @Override + public StyleWriter appendRightParenthesis() { + return append(RIGHT_PARENTHESIS); + } + + @Override + public StyleWriter appendSemiColon() { + return append(SEMI_COLON); + } + + @Override + public StyleWriter appendSpace() { + return append(SPACE); + } + + @Override + public StyleWriter appendSpaceIfNeeded() { + if (!endsWithWhitespace()) { + appendSpace(); + } + return (StyleWriter) this; + } + + @Override + public char charAt(int index) { + return stringBuilder.charAt(index); + } + + @Override + public int decreaseDepth() { + return depth > 0 ? --depth : depth; + } + + @Override + public boolean endsWithWhitespace() { + if (stringBuilder.isEmpty()) { + return true; + } + return switch (stringBuilder.charAt(stringBuilder.length() - 1)) { + case ' ', '(', '\t', '\r', '\n' -> true; + default -> false; + }; + } + + @Override + public int getDepth() { + return depth; + } + + @Override + public StyleOptions getOptions() { + return options; + } + + @Override + public int increaseDepth() { + return ++depth; + } + + @Override + public int length() { + return lengthOfLines + stringBuilder.length(); + } + + @Override + public CharSequence subSequence(int start, int end) { + return stringBuilder.subSequence(start, end); + } + + @Override + public String toString() { + var totalLines = new ArrayList<>(lines); + totalLines.add(stringBuilder.toString()); + return String.join(LINE_SEPARATOR, totalLines); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/styles/IStyleWriter.java b/src/main/java/com/caoccao/jaspiler/styles/IStyleWriter.java index d5f5c0e..022b59f 100644 --- a/src/main/java/com/caoccao/jaspiler/styles/IStyleWriter.java +++ b/src/main/java/com/caoccao/jaspiler/styles/IStyleWriter.java @@ -1,118 +1,118 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.styles; - -import com.caoccao.jaspiler.enums.JavaKeyword; -import com.caoccao.jaspiler.trees.IJTTree; - -public interface IStyleWriter> { - String AT = "@"; - String COMMA = ","; - String COMMA_ = ", "; - String DOT = "."; - String EMPTY = ""; - String EQUAL = "="; - String LEFT_ARROW = "<"; - String LEFT_CURLY_BRACKET = "{"; - String LEFT_PARENTHESIS = "("; - String LINE_SEPARATOR = "\n"; - String QUOTE = "\""; - String RIGHT_ARROW = ">"; - String RIGHT_CURLY_BRACKET = "}"; - String RIGHT_PARENTHESIS = ")"; - String SEMI_COLON = ";"; - String SINGLE_QUOTE = "'"; - String SPACE = " "; - - StyleWriter append(boolean b); - - StyleWriter append(double d); - - StyleWriter append(float f); - - StyleWriter append(int i); - - StyleWriter append(long l); - - StyleWriter append(short s); - - StyleWriter append(Object object); - - StyleWriter append(IJTTree jtTree); - - StyleWriter append(char[] str); - - StyleWriter appendAt(); - - StyleWriter appendBlockClose(); - - StyleWriter appendBlockOpen(); - - StyleWriter appendClassClose(); - - StyleWriter appendClassOpen(); - - StyleWriter appendComma(); - - StyleWriter appendDot(); - - StyleWriter appendEqual(); - - StyleWriter appendIndent(); - - StyleWriter appendIndent(int depth); - - StyleWriter appendJavaCharacter(char c); - - StyleWriter appendJavaCharacter(String str); - - StyleWriter appendJavaString(String str); - - StyleWriter appendKeyword(JavaKeyword javaKeyword); - - StyleWriter appendLeftArrow(); - - StyleWriter appendLeftParenthesis(); - - StyleWriter appendLineSeparator(); - - StyleWriter appendQuote(); - - StyleWriter appendRightArrow(); - - StyleWriter appendRightParenthesis(); - - StyleWriter appendSemiColon(); - - StyleWriter appendSingleQuote(); - - StyleWriter appendSpace(); - - StyleWriter appendSpaceIfNeeded(); - - StyleWriter appendTypeSeparator(); - - int decreaseDepth(); - - boolean endsWithWhitespace(); - - int getDepth(); - - StyleOptions getOptions(); - - int increaseDepth(); -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.styles; + +import com.caoccao.jaspiler.enums.JavaKeyword; +import com.caoccao.jaspiler.trees.IJTTree; + +public interface IStyleWriter> { + String AT = "@"; + String COMMA = ","; + String COMMA_ = ", "; + String DOT = "."; + String EMPTY = ""; + String EQUAL = "="; + String LEFT_ARROW = "<"; + String LEFT_CURLY_BRACKET = "{"; + String LEFT_PARENTHESIS = "("; + String LINE_SEPARATOR = "\n"; + String QUOTE = "\""; + String RIGHT_ARROW = ">"; + String RIGHT_CURLY_BRACKET = "}"; + String RIGHT_PARENTHESIS = ")"; + String SEMI_COLON = ";"; + String SINGLE_QUOTE = "'"; + String SPACE = " "; + + StyleWriter append(boolean b); + + StyleWriter append(double d); + + StyleWriter append(float f); + + StyleWriter append(int i); + + StyleWriter append(long l); + + StyleWriter append(short s); + + StyleWriter append(Object object); + + StyleWriter append(IJTTree jtTree); + + StyleWriter append(char[] str); + + StyleWriter appendAt(); + + StyleWriter appendBlockClose(); + + StyleWriter appendBlockOpen(); + + StyleWriter appendClassClose(); + + StyleWriter appendClassOpen(); + + StyleWriter appendComma(); + + StyleWriter appendDot(); + + StyleWriter appendEqual(); + + StyleWriter appendIndent(); + + StyleWriter appendIndent(int depth); + + StyleWriter appendJavaCharacter(char c); + + StyleWriter appendJavaCharacter(String str); + + StyleWriter appendJavaString(String str); + + StyleWriter appendKeyword(JavaKeyword javaKeyword); + + StyleWriter appendLeftArrow(); + + StyleWriter appendLeftParenthesis(); + + StyleWriter appendLineSeparator(); + + StyleWriter appendQuote(); + + StyleWriter appendRightArrow(); + + StyleWriter appendRightParenthesis(); + + StyleWriter appendSemiColon(); + + StyleWriter appendSingleQuote(); + + StyleWriter appendSpace(); + + StyleWriter appendSpaceIfNeeded(); + + StyleWriter appendTypeSeparator(); + + int decreaseDepth(); + + boolean endsWithWhitespace(); + + int getDepth(); + + StyleOptions getOptions(); + + int increaseDepth(); +} diff --git a/src/main/java/com/caoccao/jaspiler/styles/StandardStyleWriter.java b/src/main/java/com/caoccao/jaspiler/styles/StandardStyleWriter.java index f01a18e..fce67d5 100644 --- a/src/main/java/com/caoccao/jaspiler/styles/StandardStyleWriter.java +++ b/src/main/java/com/caoccao/jaspiler/styles/StandardStyleWriter.java @@ -1,93 +1,93 @@ -/* - * Copyright (c) 2023-2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.styles; - -import com.caoccao.jaspiler.enums.JavaKeyword; -import org.apache.commons.text.StringEscapeUtils; - -public class StandardStyleWriter extends BaseStyleWriter { - - public StandardStyleWriter(StyleOptions options) { - super(options); - } - - @Override - public StandardStyleWriter appendBlockClose() { - return appendRightCurlyBracket(); - } - - @Override - public StandardStyleWriter appendBlockOpen() { - return appendLeftCurlyBracket().appendLineSeparator(); - } - - @Override - public StandardStyleWriter appendClassClose() { - return appendIndent(getDepth()).appendRightCurlyBracket(); - } - - @Override - public StandardStyleWriter appendClassOpen() { - return appendLeftCurlyBracket().appendLineSeparator(); - } - - @Override - public StandardStyleWriter appendIndent() { - return appendIndent(getDepth()); - } - - @Override - public StandardStyleWriter appendJavaCharacter(char c) { - return appendSingleQuote().append(c).appendSingleQuote(); - } - - @Override - public StandardStyleWriter appendJavaCharacter(String str) { - return appendSingleQuote().append(str).appendSingleQuote(); - } - - @Override - public StandardStyleWriter appendJavaString(String str) { - if (str == null) { - return append((String) null); - } - return appendQuote().append(StringEscapeUtils.escapeJava(str)).appendQuote(); - } - - @Override - public StandardStyleWriter appendKeyword(JavaKeyword javaKeyword) { - if (stringBuilder.length() + javaKeyword.getLength() >= options.getWordWrapColumn()) { - appendLineSeparator().appendIndent(getDepth()).appendContinuationIndent(); - } - return super.appendKeyword(javaKeyword); - } - - @Override - public StandardStyleWriter appendQuote() { - return append(QUOTE); - } - - @Override - public StandardStyleWriter appendSingleQuote() { - return append(SINGLE_QUOTE); - } - - @Override - public StandardStyleWriter appendTypeSeparator() { - return appendLineSeparator(2); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.styles; + +import com.caoccao.jaspiler.enums.JavaKeyword; +import org.apache.commons.text.StringEscapeUtils; + +public class StandardStyleWriter extends BaseStyleWriter { + + public StandardStyleWriter(StyleOptions options) { + super(options); + } + + @Override + public StandardStyleWriter appendBlockClose() { + return appendRightCurlyBracket(); + } + + @Override + public StandardStyleWriter appendBlockOpen() { + return appendLeftCurlyBracket().appendLineSeparator(); + } + + @Override + public StandardStyleWriter appendClassClose() { + return appendIndent(getDepth()).appendRightCurlyBracket(); + } + + @Override + public StandardStyleWriter appendClassOpen() { + return appendLeftCurlyBracket().appendLineSeparator(); + } + + @Override + public StandardStyleWriter appendIndent() { + return appendIndent(getDepth()); + } + + @Override + public StandardStyleWriter appendJavaCharacter(char c) { + return appendSingleQuote().append(c).appendSingleQuote(); + } + + @Override + public StandardStyleWriter appendJavaCharacter(String str) { + return appendSingleQuote().append(str).appendSingleQuote(); + } + + @Override + public StandardStyleWriter appendJavaString(String str) { + if (str == null) { + return append((String) null); + } + return appendQuote().append(StringEscapeUtils.escapeJava(str)).appendQuote(); + } + + @Override + public StandardStyleWriter appendKeyword(JavaKeyword javaKeyword) { + if (stringBuilder.length() + javaKeyword.getLength() >= options.getWordWrapColumn()) { + appendLineSeparator().appendIndent(getDepth()).appendContinuationIndent(); + } + return super.appendKeyword(javaKeyword); + } + + @Override + public StandardStyleWriter appendQuote() { + return append(QUOTE); + } + + @Override + public StandardStyleWriter appendSingleQuote() { + return append(SINGLE_QUOTE); + } + + @Override + public StandardStyleWriter appendTypeSeparator() { + return appendLineSeparator(2); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/styles/StyleOptions.java b/src/main/java/com/caoccao/jaspiler/styles/StyleOptions.java index 3347746..39ea17f 100644 --- a/src/main/java/com/caoccao/jaspiler/styles/StyleOptions.java +++ b/src/main/java/com/caoccao/jaspiler/styles/StyleOptions.java @@ -1,92 +1,92 @@ -/* - * Copyright (c) 2023-2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.styles; - -public final class StyleOptions { - public static final StyleOptions Default = new StyleOptions().seal(); - private static final int DEFAULT_CONTINUATION_INDENT_SIZE = 8; - private static final int DEFAULT_INDENT_SIZE = 4; - private static final int DEFAULT_WORD_WRAP_COLUMN = 120; - private static final int MAX_INDENT_SIZE = 100; - private static final int MIN_INDENT_SIZE = 0; - private static final int MIN_WORD_WRAP_COLUMN = 60; - private int continuationIndentSize; - private int indentSize; - private boolean preserveCopyrights; - private boolean sealed; - private int wordWrapColumn; - - public StyleOptions() { - setContinuationIndentSize(DEFAULT_CONTINUATION_INDENT_SIZE); - setIndentSize(DEFAULT_INDENT_SIZE); - setPreserveCopyrights(true); - setWordWrapColumn(DEFAULT_WORD_WRAP_COLUMN); - } - - public int getContinuationIndentSize() { - return continuationIndentSize; - } - - public int getIndentSize() { - return indentSize; - } - - public int getWordWrapColumn() { - return wordWrapColumn; - } - - public boolean isPreserveCopyrights() { - return preserveCopyrights; - } - - public boolean isSealed() { - return sealed; - } - - public StyleOptions seal() { - sealed = true; - return this; - } - - public StyleOptions setContinuationIndentSize(int continuationIndentSize) { - if (!sealed) { - this.continuationIndentSize = Math.min(Math.max(continuationIndentSize, MIN_INDENT_SIZE), MAX_INDENT_SIZE); - } - return this; - } - - public StyleOptions setIndentSize(int indentSize) { - if (!sealed) { - this.indentSize = Math.min(Math.max(indentSize, MIN_INDENT_SIZE), MAX_INDENT_SIZE); - } - return this; - } - - public StyleOptions setPreserveCopyrights(boolean preserveCopyrights) { - if (!sealed) { - this.preserveCopyrights = preserveCopyrights; - } - return this; - } - - public StyleOptions setWordWrapColumn(int wordWrapColumn) { - if (!sealed) { - this.wordWrapColumn = Math.max(wordWrapColumn, MIN_WORD_WRAP_COLUMN); - } - return this; - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.styles; + +public final class StyleOptions { + public static final StyleOptions Default = new StyleOptions().seal(); + private static final int DEFAULT_CONTINUATION_INDENT_SIZE = 8; + private static final int DEFAULT_INDENT_SIZE = 4; + private static final int DEFAULT_WORD_WRAP_COLUMN = 120; + private static final int MAX_INDENT_SIZE = 100; + private static final int MIN_INDENT_SIZE = 0; + private static final int MIN_WORD_WRAP_COLUMN = 60; + private int continuationIndentSize; + private int indentSize; + private boolean preserveCopyrights; + private boolean sealed; + private int wordWrapColumn; + + public StyleOptions() { + setContinuationIndentSize(DEFAULT_CONTINUATION_INDENT_SIZE); + setIndentSize(DEFAULT_INDENT_SIZE); + setPreserveCopyrights(true); + setWordWrapColumn(DEFAULT_WORD_WRAP_COLUMN); + } + + public int getContinuationIndentSize() { + return continuationIndentSize; + } + + public int getIndentSize() { + return indentSize; + } + + public int getWordWrapColumn() { + return wordWrapColumn; + } + + public boolean isPreserveCopyrights() { + return preserveCopyrights; + } + + public boolean isSealed() { + return sealed; + } + + public StyleOptions seal() { + sealed = true; + return this; + } + + public StyleOptions setContinuationIndentSize(int continuationIndentSize) { + if (!sealed) { + this.continuationIndentSize = Math.min(Math.max(continuationIndentSize, MIN_INDENT_SIZE), MAX_INDENT_SIZE); + } + return this; + } + + public StyleOptions setIndentSize(int indentSize) { + if (!sealed) { + this.indentSize = Math.min(Math.max(indentSize, MIN_INDENT_SIZE), MAX_INDENT_SIZE); + } + return this; + } + + public StyleOptions setPreserveCopyrights(boolean preserveCopyrights) { + if (!sealed) { + this.preserveCopyrights = preserveCopyrights; + } + return this; + } + + public StyleOptions setWordWrapColumn(int wordWrapColumn) { + if (!sealed) { + this.wordWrapColumn = Math.max(wordWrapColumn, MIN_WORD_WRAP_COLUMN); + } + return this; + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/IJTAnnotatable.java b/src/main/java/com/caoccao/jaspiler/trees/IJTAnnotatable.java index 3e887da..93e2611 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/IJTAnnotatable.java +++ b/src/main/java/com/caoccao/jaspiler/trees/IJTAnnotatable.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/IJTTree.java b/src/main/java/com/caoccao/jaspiler/trees/IJTTree.java index 074a79a..53ef2bb 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/IJTTree.java +++ b/src/main/java/com/caoccao/jaspiler/trees/IJTTree.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTAnnotatedType.java b/src/main/java/com/caoccao/jaspiler/trees/JTAnnotatedType.java index 8ed008e..a8ed230 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTAnnotatedType.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTAnnotatedType.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTAnnotation.java b/src/main/java/com/caoccao/jaspiler/trees/JTAnnotation.java index 439f16e..cb044ce 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTAnnotation.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTAnnotation.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTArrayAccess.java b/src/main/java/com/caoccao/jaspiler/trees/JTArrayAccess.java index c0c0fc1..b267494 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTArrayAccess.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTArrayAccess.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTArrayType.java b/src/main/java/com/caoccao/jaspiler/trees/JTArrayType.java index 06926c7..30ee276 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTArrayType.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTArrayType.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTAssert.java b/src/main/java/com/caoccao/jaspiler/trees/JTAssert.java index 9d98465..1676df2 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTAssert.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTAssert.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTAssign.java b/src/main/java/com/caoccao/jaspiler/trees/JTAssign.java index 8abe894..4565b57 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTAssign.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTAssign.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTAssignOp.java b/src/main/java/com/caoccao/jaspiler/trees/JTAssignOp.java index 2070474..db7e402 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTAssignOp.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTAssignOp.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTBinary.java b/src/main/java/com/caoccao/jaspiler/trees/JTBinary.java index a60b5c6..4f0b83e 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTBinary.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTBinary.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTBindingPattern.java b/src/main/java/com/caoccao/jaspiler/trees/JTBindingPattern.java index fef74ce..8ae3862 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTBindingPattern.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTBindingPattern.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTBlock.java b/src/main/java/com/caoccao/jaspiler/trees/JTBlock.java index d8208d7..c421ac8 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTBlock.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTBlock.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTBreak.java b/src/main/java/com/caoccao/jaspiler/trees/JTBreak.java index e55d9ce..79f3a35 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTBreak.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTBreak.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTCase.java b/src/main/java/com/caoccao/jaspiler/trees/JTCase.java index 078576e..b37a52f 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTCase.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTCase.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTCaseLabel.java b/src/main/java/com/caoccao/jaspiler/trees/JTCaseLabel.java index c9086ae..ad12434 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTCaseLabel.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTCaseLabel.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTCatch.java b/src/main/java/com/caoccao/jaspiler/trees/JTCatch.java index fa38363..37863b4 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTCatch.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTCatch.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTCharacter.java b/src/main/java/com/caoccao/jaspiler/trees/JTCharacter.java index 02f5e00..4d01edf 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTCharacter.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTCharacter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTClassDecl.java b/src/main/java/com/caoccao/jaspiler/trees/JTClassDecl.java index ef70769..fcdff89 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTClassDecl.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTClassDecl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTCompilationUnit.java b/src/main/java/com/caoccao/jaspiler/trees/JTCompilationUnit.java index 6e27e77..fa71446 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTCompilationUnit.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTCompilationUnit.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTConditional.java b/src/main/java/com/caoccao/jaspiler/trees/JTConditional.java index 323eec7..70dcf78 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTConditional.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTConditional.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTContinue.java b/src/main/java/com/caoccao/jaspiler/trees/JTContinue.java index 8087884..360e5aa 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTContinue.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTContinue.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTDefaultCaseLabel.java b/src/main/java/com/caoccao/jaspiler/trees/JTDefaultCaseLabel.java index 2c03d15..744cdde 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTDefaultCaseLabel.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTDefaultCaseLabel.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTDirective.java b/src/main/java/com/caoccao/jaspiler/trees/JTDirective.java index 33cab78..20bf296 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTDirective.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTDirective.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTDoWhileLoop.java b/src/main/java/com/caoccao/jaspiler/trees/JTDoWhileLoop.java index 6edd955..0fd1d59 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTDoWhileLoop.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTDoWhileLoop.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTEnhancedForLoop.java b/src/main/java/com/caoccao/jaspiler/trees/JTEnhancedForLoop.java index 08bd9f5..1d9d40c 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTEnhancedForLoop.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTEnhancedForLoop.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTErroneous.java b/src/main/java/com/caoccao/jaspiler/trees/JTErroneous.java index 2c31483..0e48eb7 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTErroneous.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTErroneous.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTExports.java b/src/main/java/com/caoccao/jaspiler/trees/JTExports.java index 97a32a0..d81eff7 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTExports.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTExports.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTExpression.java b/src/main/java/com/caoccao/jaspiler/trees/JTExpression.java index 119e82c..8c13d09 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTExpression.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTExpression.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTExpressionStatement.java b/src/main/java/com/caoccao/jaspiler/trees/JTExpressionStatement.java index 6999772..1ac2e12 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTExpressionStatement.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTExpressionStatement.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTFieldAccess.java b/src/main/java/com/caoccao/jaspiler/trees/JTFieldAccess.java index 24fa61e..a4c58c8 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTFieldAccess.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTFieldAccess.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTFlags.java b/src/main/java/com/caoccao/jaspiler/trees/JTFlags.java index d58712e..1b6d457 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTFlags.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTFlags.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTFloat.java b/src/main/java/com/caoccao/jaspiler/trees/JTFloat.java index e6ee6e6..0f73203 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTFloat.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTFloat.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTForLoop.java b/src/main/java/com/caoccao/jaspiler/trees/JTForLoop.java index 97e6993..3cc6ba7 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTForLoop.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTForLoop.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTFunctionalExpression.java b/src/main/java/com/caoccao/jaspiler/trees/JTFunctionalExpression.java index 388d735..fd3895c 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTFunctionalExpression.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTFunctionalExpression.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTGuardedPattern.java b/src/main/java/com/caoccao/jaspiler/trees/JTGuardedPattern.java index dc6aece..28b59cb 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTGuardedPattern.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTGuardedPattern.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTIdent.java b/src/main/java/com/caoccao/jaspiler/trees/JTIdent.java index 69acae4..02433a2 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTIdent.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTIdent.java @@ -1,109 +1,109 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.jaspiler.styles.IStyleWriter; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.sun.source.tree.IdentifierTree; -import com.sun.source.tree.TreeVisitor; - -import java.util.Map; -import java.util.Objects; - -public final class JTIdent - extends JTExpression - implements IdentifierTree { - private static final String PROPERTY_NAME = "name"; - private JTName name; - - public JTIdent() { - this(null, null); - setActionChange(); - } - - JTIdent(IdentifierTree originalTree, JTTree parentTree) { - super(originalTree, parentTree); - name = null; - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitIdentifier(this, data); - } - - @Override - JTIdent analyze() { - super.analyze(); - name = JTTreeFactory.createName(getOriginalTree().getName()); - return this; - } - - @Override - public Kind getKind() { - return Kind.IDENTIFIER; - } - - @Override - public JTName getName() { - return name; - } - - @Override - public boolean isActionChange() { - return getAction().isChange(); - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_NAME, propertyName -> v8Runtime.toV8Value(getName())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_NAME, (propertyName, propertyValue) -> replaceName(this::setName, propertyValue)); - } - return stringSetterMap; - } - - @Override - public boolean serialize(IStyleWriter writer) { - if (isActionChange()) { - if (name != null) { - writer.append(name); - } - return true; - } - return super.serialize(writer); - } - - public JTIdent setName(JTName name) { - if (this.name == name) { - return this; - } - this.name = Objects.requireNonNull(name); - return setActionChange(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.jaspiler.styles.IStyleWriter; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.sun.source.tree.IdentifierTree; +import com.sun.source.tree.TreeVisitor; + +import java.util.Map; +import java.util.Objects; + +public final class JTIdent + extends JTExpression + implements IdentifierTree { + private static final String PROPERTY_NAME = "name"; + private JTName name; + + public JTIdent() { + this(null, null); + setActionChange(); + } + + JTIdent(IdentifierTree originalTree, JTTree parentTree) { + super(originalTree, parentTree); + name = null; + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitIdentifier(this, data); + } + + @Override + JTIdent analyze() { + super.analyze(); + name = JTTreeFactory.createName(getOriginalTree().getName()); + return this; + } + + @Override + public Kind getKind() { + return Kind.IDENTIFIER; + } + + @Override + public JTName getName() { + return name; + } + + @Override + public boolean isActionChange() { + return getAction().isChange(); + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_NAME, propertyName -> v8Runtime.toV8Value(getName())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_NAME, (propertyName, propertyValue) -> replaceName(this::setName, propertyValue)); + } + return stringSetterMap; + } + + @Override + public boolean serialize(IStyleWriter writer) { + if (isActionChange()) { + if (name != null) { + writer.append(name); + } + return true; + } + return super.serialize(writer); + } + + public JTIdent setName(JTName name) { + if (this.name == name) { + return this; + } + this.name = Objects.requireNonNull(name); + return setActionChange(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTIf.java b/src/main/java/com/caoccao/jaspiler/trees/JTIf.java index fef5c98..b333a12 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTIf.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTIf.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTImport.java b/src/main/java/com/caoccao/jaspiler/trees/JTImport.java index a935cbf..975123c 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTImport.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTImport.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTInstanceOf.java b/src/main/java/com/caoccao/jaspiler/trees/JTInstanceOf.java index 40611aa..1b3f823 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTInstanceOf.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTInstanceOf.java @@ -1,129 +1,129 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.sun.source.tree.InstanceOfTree; -import com.sun.source.tree.TreeVisitor; - -import java.util.List; -import java.util.Map; -import java.util.Optional; - -public final class JTInstanceOf - extends JTExpression - implements InstanceOfTree { - private static final String PROPERTY_EXPRESSION = "expression"; - private static final String PROPERTY_PATTERN = "pattern"; - private JTExpression expression; - private JTTree pattern; - - public JTInstanceOf() { - this(null, null); - setActionChange(); - } - - JTInstanceOf(InstanceOfTree instanceOfTree, JTTree parentTree) { - super(instanceOfTree, parentTree); - expression = null; - pattern = null; - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitInstanceOf(this, data); - } - - @Override - JTInstanceOf analyze() { - super.analyze(); - expression = JTTreeFactory.create(getOriginalTree().getExpression(), this); - pattern = JTTreeFactory.create(getOriginalTree().getPattern(), this); - return this; - } - - @Override - List> getAllNodes() { - return super.getAllNodes(); - } - - @Override - public JTExpression getExpression() { - return expression; - } - - @Override - public Kind getKind() { - return Kind.INSTANCE_OF; - } - - @Override - public JTPattern getPattern() { - return pattern instanceof JTPattern jtPattern ? jtPattern : null; - } - - @Override - public JTTree getType() { - if (pattern instanceof JTPattern) { - if (pattern instanceof JTBindingPattern bindingPattern) { - return bindingPattern.getVariable().getType(); - } else { - return null; - } - } - return pattern; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_EXPRESSION, propertyName -> v8Runtime.toV8Value(getExpression())); - registerStringGetter(PROPERTY_PATTERN, propertyName -> v8Runtime.toV8Value(getPattern())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_EXPRESSION, (propertyName, propertyValue) -> replaceExpression(this::setExpression, propertyValue)); - registerStringSetter(PROPERTY_PATTERN, (propertyName, propertyValue) -> replaceTree(this::setPattern, propertyValue)); - } - return stringSetterMap; - } - - public JTInstanceOf setExpression(JTExpression expression) { - if (this.expression == expression) { - return this; - } - this.expression = Optional.ofNullable(expression).map(o -> o.setParentTree(this)).orElse(null); - return setActionChange(); - } - - public JTInstanceOf setPattern(JTTree pattern) { - if (this.pattern == pattern) { - return this; - } - this.pattern = Optional.ofNullable(pattern).map(o -> o.setParentTree(this)).orElse(null); - return setActionChange(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.sun.source.tree.InstanceOfTree; +import com.sun.source.tree.TreeVisitor; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +public final class JTInstanceOf + extends JTExpression + implements InstanceOfTree { + private static final String PROPERTY_EXPRESSION = "expression"; + private static final String PROPERTY_PATTERN = "pattern"; + private JTExpression expression; + private JTTree pattern; + + public JTInstanceOf() { + this(null, null); + setActionChange(); + } + + JTInstanceOf(InstanceOfTree instanceOfTree, JTTree parentTree) { + super(instanceOfTree, parentTree); + expression = null; + pattern = null; + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitInstanceOf(this, data); + } + + @Override + JTInstanceOf analyze() { + super.analyze(); + expression = JTTreeFactory.create(getOriginalTree().getExpression(), this); + pattern = JTTreeFactory.create(getOriginalTree().getPattern(), this); + return this; + } + + @Override + List> getAllNodes() { + return super.getAllNodes(); + } + + @Override + public JTExpression getExpression() { + return expression; + } + + @Override + public Kind getKind() { + return Kind.INSTANCE_OF; + } + + @Override + public JTPattern getPattern() { + return pattern instanceof JTPattern jtPattern ? jtPattern : null; + } + + @Override + public JTTree getType() { + if (pattern instanceof JTPattern) { + if (pattern instanceof JTBindingPattern bindingPattern) { + return bindingPattern.getVariable().getType(); + } else { + return null; + } + } + return pattern; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_EXPRESSION, propertyName -> v8Runtime.toV8Value(getExpression())); + registerStringGetter(PROPERTY_PATTERN, propertyName -> v8Runtime.toV8Value(getPattern())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_EXPRESSION, (propertyName, propertyValue) -> replaceExpression(this::setExpression, propertyValue)); + registerStringSetter(PROPERTY_PATTERN, (propertyName, propertyValue) -> replaceTree(this::setPattern, propertyValue)); + } + return stringSetterMap; + } + + public JTInstanceOf setExpression(JTExpression expression) { + if (this.expression == expression) { + return this; + } + this.expression = Optional.ofNullable(expression).map(o -> o.setParentTree(this)).orElse(null); + return setActionChange(); + } + + public JTInstanceOf setPattern(JTTree pattern) { + if (this.pattern == pattern) { + return this; + } + this.pattern = Optional.ofNullable(pattern).map(o -> o.setParentTree(this)).orElse(null); + return setActionChange(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTLabeledStatement.java b/src/main/java/com/caoccao/jaspiler/trees/JTLabeledStatement.java index ab109ac..e17d1aa 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTLabeledStatement.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTLabeledStatement.java @@ -1,121 +1,121 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.sun.source.tree.LabeledStatementTree; -import com.sun.source.tree.TreeVisitor; - -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -public final class JTLabeledStatement - extends JTStatement - implements LabeledStatementTree { - private static final String PROPERTY_LABEL = "label"; - private static final String PROPERTY_STATEMENT = "statement"; - private JTName label; - private JTStatement statement; - - public JTLabeledStatement() { - this(null, null); - setActionChange(); - } - - JTLabeledStatement(LabeledStatementTree labeledStatementTree, JTTree parentTree) { - super(labeledStatementTree, parentTree); - label = null; - statement = null; - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitLabeledStatement(this, data); - } - - @Override - JTLabeledStatement analyze() { - super.analyze(); - label = JTTreeFactory.createName(getOriginalTree().getLabel()); - statement = JTTreeFactory.create(getOriginalTree().getStatement(), this); - return this; - } - - @Override - List> getAllNodes() { - var nodes = super.getAllNodes(); - Optional.ofNullable(statement).ifPresent(nodes::add); - nodes.forEach(node -> node.setParentTree(this)); - return nodes; - } - - @Override - public Kind getKind() { - return Kind.LABELED_STATEMENT; - } - - @Override - public JTName getLabel() { - return label; - } - - @Override - public JTStatement getStatement() { - return statement; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_LABEL, propertyName -> v8Runtime.toV8Value(getLabel())); - registerStringGetter(PROPERTY_STATEMENT, propertyName -> v8Runtime.toV8Value(getStatement())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_LABEL, (propertyName, propertyValue) -> replaceName(this::setLabel, propertyValue)); - registerStringSetter(PROPERTY_STATEMENT, (propertyName, propertyValue) -> replaceStatement(this::setStatement, propertyValue)); - } - return stringSetterMap; - } - - public JTLabeledStatement setLabel(JTName label) { - if (this.label == label) { - return this; - } - this.label = Objects.requireNonNull(label); - return setActionChange(); - } - - public JTLabeledStatement setStatement(JTStatement statement) { - if (this.statement == statement) { - return this; - } - this.statement = Objects.requireNonNull(statement).setParentTree(this); - return setActionChange(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.sun.source.tree.LabeledStatementTree; +import com.sun.source.tree.TreeVisitor; + +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +public final class JTLabeledStatement + extends JTStatement + implements LabeledStatementTree { + private static final String PROPERTY_LABEL = "label"; + private static final String PROPERTY_STATEMENT = "statement"; + private JTName label; + private JTStatement statement; + + public JTLabeledStatement() { + this(null, null); + setActionChange(); + } + + JTLabeledStatement(LabeledStatementTree labeledStatementTree, JTTree parentTree) { + super(labeledStatementTree, parentTree); + label = null; + statement = null; + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitLabeledStatement(this, data); + } + + @Override + JTLabeledStatement analyze() { + super.analyze(); + label = JTTreeFactory.createName(getOriginalTree().getLabel()); + statement = JTTreeFactory.create(getOriginalTree().getStatement(), this); + return this; + } + + @Override + List> getAllNodes() { + var nodes = super.getAllNodes(); + Optional.ofNullable(statement).ifPresent(nodes::add); + nodes.forEach(node -> node.setParentTree(this)); + return nodes; + } + + @Override + public Kind getKind() { + return Kind.LABELED_STATEMENT; + } + + @Override + public JTName getLabel() { + return label; + } + + @Override + public JTStatement getStatement() { + return statement; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_LABEL, propertyName -> v8Runtime.toV8Value(getLabel())); + registerStringGetter(PROPERTY_STATEMENT, propertyName -> v8Runtime.toV8Value(getStatement())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_LABEL, (propertyName, propertyValue) -> replaceName(this::setLabel, propertyValue)); + registerStringSetter(PROPERTY_STATEMENT, (propertyName, propertyValue) -> replaceStatement(this::setStatement, propertyValue)); + } + return stringSetterMap; + } + + public JTLabeledStatement setLabel(JTName label) { + if (this.label == label) { + return this; + } + this.label = Objects.requireNonNull(label); + return setActionChange(); + } + + public JTLabeledStatement setStatement(JTStatement statement) { + if (this.statement == statement) { + return this; + } + this.statement = Objects.requireNonNull(statement).setParentTree(this); + return setActionChange(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTLambda.java b/src/main/java/com/caoccao/jaspiler/trees/JTLambda.java index d198dce..14f671a 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTLambda.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTLambda.java @@ -1,140 +1,140 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.caoccao.javet.values.primitive.V8ValueString; -import com.sun.source.tree.LambdaExpressionTree; -import com.sun.source.tree.TreeVisitor; - -import java.util.*; - -public final class JTLambda - extends JTFunctionalExpression - implements LambdaExpressionTree { - private static final String PROPERTY_BODY = "body"; - private static final String PROPERTY_BODY_KIND = "bodyKind"; - private static final String PROPERTY_PARAMETERS = "parameters"; - private final List parameters; - private JTTree body; - private BodyKind bodyKind; - - public JTLambda() { - this(null, null); - setActionChange(); - } - - JTLambda(LambdaExpressionTree lambdaExpressionTree, JTTree parentTree) { - super(lambdaExpressionTree, parentTree); - body = null; - bodyKind = null; - parameters = new ArrayList<>(); - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitLambdaExpression(this, data); - } - - @Override - JTLambda analyze() { - super.analyze(); - JTTreeFactory.createAndAdd( - getOriginalTree().getParameters(), this, JTVariableDecl::new, parameters::add); - body = JTTreeFactory.create(getOriginalTree().getBody(), this); - bodyKind = getOriginalTree().getBodyKind(); - return this; - } - - @Override - List> getAllNodes() { - var nodes = super.getAllNodes(); - parameters.stream().filter(Objects::nonNull).forEach(nodes::add); - Optional.ofNullable(body).ifPresent(nodes::add); - nodes.forEach(node -> node.setParentTree(this)); - return nodes; - } - - @Override - public JTTree getBody() { - return body; - } - - @Override - public BodyKind getBodyKind() { - return bodyKind; - } - - @Override - public Kind getKind() { - return Kind.LAMBDA_EXPRESSION; - } - - @Override - public List getParameters() { - return parameters; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_BODY, propertyName -> v8Runtime.toV8Value(getBody())); - registerStringGetter(PROPERTY_BODY_KIND, propertyName -> v8Runtime.createV8ValueString(getBodyKind().name())); - registerStringGetter(PROPERTY_PARAMETERS, propertyName -> v8Runtime.toV8Value(getParameters())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_BODY, (propertyName, propertyValue) -> replaceLambda(this::setBody, propertyValue)); - registerStringSetter(PROPERTY_BODY_KIND, (propertyName, propertyValue) -> setBodyKind(propertyValue)); - registerStringSetter(PROPERTY_PARAMETERS, (propertyName, propertyValue) -> replaceVariableDecls(parameters, propertyValue)); - } - return stringSetterMap; - } - - public JTLambda setBody(JTTree body) { - if (this.body == body) { - return this; - } - this.body = Objects.requireNonNull(body).setParentTree(this); - return setActionChange(); - } - - private boolean setBodyKind(V8Value v8Value) { - if (v8Value instanceof V8ValueString v8ValueString) { - setBodyKind(BodyKind.valueOf(v8ValueString.getValue())); - return true; - } - return false; - } - - public JTLambda setBodyKind(BodyKind bodyKind) { - if (this.bodyKind == bodyKind) { - return this; - } - this.bodyKind = Objects.requireNonNull(bodyKind); - return setActionChange(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.caoccao.javet.values.primitive.V8ValueString; +import com.sun.source.tree.LambdaExpressionTree; +import com.sun.source.tree.TreeVisitor; + +import java.util.*; + +public final class JTLambda + extends JTFunctionalExpression + implements LambdaExpressionTree { + private static final String PROPERTY_BODY = "body"; + private static final String PROPERTY_BODY_KIND = "bodyKind"; + private static final String PROPERTY_PARAMETERS = "parameters"; + private final List parameters; + private JTTree body; + private BodyKind bodyKind; + + public JTLambda() { + this(null, null); + setActionChange(); + } + + JTLambda(LambdaExpressionTree lambdaExpressionTree, JTTree parentTree) { + super(lambdaExpressionTree, parentTree); + body = null; + bodyKind = null; + parameters = new ArrayList<>(); + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitLambdaExpression(this, data); + } + + @Override + JTLambda analyze() { + super.analyze(); + JTTreeFactory.createAndAdd( + getOriginalTree().getParameters(), this, JTVariableDecl::new, parameters::add); + body = JTTreeFactory.create(getOriginalTree().getBody(), this); + bodyKind = getOriginalTree().getBodyKind(); + return this; + } + + @Override + List> getAllNodes() { + var nodes = super.getAllNodes(); + parameters.stream().filter(Objects::nonNull).forEach(nodes::add); + Optional.ofNullable(body).ifPresent(nodes::add); + nodes.forEach(node -> node.setParentTree(this)); + return nodes; + } + + @Override + public JTTree getBody() { + return body; + } + + @Override + public BodyKind getBodyKind() { + return bodyKind; + } + + @Override + public Kind getKind() { + return Kind.LAMBDA_EXPRESSION; + } + + @Override + public List getParameters() { + return parameters; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_BODY, propertyName -> v8Runtime.toV8Value(getBody())); + registerStringGetter(PROPERTY_BODY_KIND, propertyName -> v8Runtime.createV8ValueString(getBodyKind().name())); + registerStringGetter(PROPERTY_PARAMETERS, propertyName -> v8Runtime.toV8Value(getParameters())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_BODY, (propertyName, propertyValue) -> replaceLambda(this::setBody, propertyValue)); + registerStringSetter(PROPERTY_BODY_KIND, (propertyName, propertyValue) -> setBodyKind(propertyValue)); + registerStringSetter(PROPERTY_PARAMETERS, (propertyName, propertyValue) -> replaceVariableDecls(parameters, propertyValue)); + } + return stringSetterMap; + } + + public JTLambda setBody(JTTree body) { + if (this.body == body) { + return this; + } + this.body = Objects.requireNonNull(body).setParentTree(this); + return setActionChange(); + } + + private boolean setBodyKind(V8Value v8Value) { + if (v8Value instanceof V8ValueString v8ValueString) { + setBodyKind(BodyKind.valueOf(v8ValueString.getValue())); + return true; + } + return false; + } + + public JTLambda setBodyKind(BodyKind bodyKind) { + if (this.bodyKind == bodyKind) { + return this; + } + this.bodyKind = Objects.requireNonNull(bodyKind); + return setActionChange(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTLiteral.java b/src/main/java/com/caoccao/jaspiler/trees/JTLiteral.java index eaa758e..346ec4e 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTLiteral.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTLiteral.java @@ -1,222 +1,222 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.jaspiler.styles.IStyleWriter; -import com.caoccao.javet.exceptions.JavetException; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.caoccao.javet.values.primitive.*; -import com.caoccao.javet.values.reference.V8ValueObject; -import com.sun.source.tree.LiteralTree; -import com.sun.source.tree.TreeVisitor; - -import java.util.Map; - -public final class JTLiteral - extends JTExpression - implements LiteralTree { - private static final String DEFAULT_BOOLEAN = "false"; - private static final String DEFAULT_CHAR = "\\0"; - private static final String DEFAULT_DOUBLE = "0D"; - private static final String DEFAULT_FLOAT = "0F"; - private static final String DEFAULT_INT = "0"; - private static final String DEFAULT_LONG = "0L"; - private static final String PROPERTY_VALUE = "value"; - private Kind kind; - private Object value; - - public JTLiteral() { - this(null, null); - setActionChange(); - } - - JTLiteral(LiteralTree literalTree, JTTree parentTree) { - super(literalTree, parentTree); - kind = Kind.NULL_LITERAL; - value = null; - } - - private static Kind parseKind(Object value) { - if (value instanceof Integer) { - return Kind.INT_LITERAL; - } - if (value instanceof Long) { - return Kind.LONG_LITERAL; - } - if (value instanceof Float) { - return Kind.FLOAT_LITERAL; - } - if (value instanceof Double) { - return Kind.DOUBLE_LITERAL; - } - if (value instanceof Boolean) { - return Kind.BOOLEAN_LITERAL; - } - if (value instanceof Character) { - return Kind.CHAR_LITERAL; - } - if (value instanceof String) { - return Kind.STRING_LITERAL; - } - if (value == null) { - return Kind.NULL_LITERAL; - } - throw new AssertionError(value + " is not supported."); - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitLiteral(this, data); - } - - @Override - JTLiteral analyze() { - super.analyze(); - kind = getOriginalTree().getKind(); - value = getOriginalTree().getValue(); - return this; - } - - @Override - public Kind getKind() { - return kind; - } - - private V8Value getV8Value() throws JavetException { - if (value instanceof Integer valueInteger) { - return v8Runtime.createV8ValueInteger(valueInteger); - } - if (value instanceof Long valueLong) { - return v8Runtime.createV8ValueLong(valueLong); - } - if (value instanceof Float valueFloat) { - return v8Runtime.toV8Value(new JTFloat(valueFloat)); - } - if (value instanceof Double valueDouble) { - return v8Runtime.createV8ValueDouble(valueDouble); - } - if (value instanceof Boolean valueBoolean) { - return v8Runtime.createV8ValueBoolean(valueBoolean); - } - if (value instanceof Character valueCharacter) { - return v8Runtime.toV8Value(new JTCharacter(valueCharacter)); - } - if (value instanceof String valueString) { - return v8Runtime.toV8Value(valueString); - } - return v8Runtime.createV8ValueNull(); - } - - @Override - public Object getValue() { - return value; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_VALUE, propertyName -> getV8Value()); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_VALUE, (propertyName, propertyValue) -> setValue(propertyValue)); - registerStringSetter(PROPERTY_KIND, (propertyName, propertyValue) -> replaceKind(this::setKind, propertyValue)); - } - return stringSetterMap; - } - - @Override - public boolean serialize(IStyleWriter writer) { - if (isActionChange()) { - switch (kind) { - case BOOLEAN_LITERAL -> writer.append(value == null ? DEFAULT_BOOLEAN : String.valueOf(value)); - case CHAR_LITERAL -> { - String charString = DEFAULT_CHAR; - if (value instanceof Character character) { - charString = character.toString(); - } else if (value != null) { - charString = String.valueOf(value); - } - writer.appendJavaCharacter(charString); - } - case DOUBLE_LITERAL -> writer.append(value == null ? DEFAULT_DOUBLE : String.valueOf(value)); - case FLOAT_LITERAL -> writer.append(value == null ? DEFAULT_FLOAT : String.valueOf(value)); - case INT_LITERAL -> writer.append(value == null ? DEFAULT_INT : String.valueOf(value)); - case LONG_LITERAL -> writer.append(value == null ? DEFAULT_LONG : String.valueOf(value)); - case NULL_LITERAL -> writer.append((String) null); - case STRING_LITERAL -> { - if (value == null) { - writer.append((String) null); - } else { - writer.appendJavaString(String.valueOf(value)); - } - } - } - return true; - } - return super.serialize(writer); - } - - public JTLiteral setKind(Kind kind) { - switch (kind) { - case INT_LITERAL, LONG_LITERAL, FLOAT_LITERAL, DOUBLE_LITERAL, BOOLEAN_LITERAL, - CHAR_LITERAL, STRING_LITERAL, NULL_LITERAL -> this.kind = kind; - default -> this.kind = Kind.NULL_LITERAL; - } - return setActionChange(); - } - - private boolean setValue(V8Value v8Value) throws JavetException { - Object valueObject = null; - if (v8Value instanceof V8ValueInteger v8ValueInteger) { - valueObject = v8ValueInteger.getValue(); - } else if (v8Value instanceof V8ValueLong v8ValueLong) { - valueObject = v8ValueLong.getValue(); - } else if (v8Value instanceof V8ValueDouble v8ValueDouble) { - valueObject = v8ValueDouble.getValue(); - } else if (v8Value instanceof V8ValueBoolean v8ValueBoolean) { - valueObject = v8ValueBoolean.getValue(); - } else if (v8Value instanceof V8ValueString v8ValueString) { - valueObject = v8ValueString.getValue(); - } else if (v8Value instanceof V8ValueObject v8ValueObject) { - valueObject = v8Runtime.toObject(v8ValueObject); - if (!(valueObject instanceof Float || valueObject instanceof Character)) { - valueObject = null; - } - } - setValue(valueObject); - return true; - } - - public JTLiteral setValue(Object value) { - if (this.value == value) { - return this; - } - this.value = value; - kind = parseKind(this.value); - return setActionChange(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.jaspiler.styles.IStyleWriter; +import com.caoccao.javet.exceptions.JavetException; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.caoccao.javet.values.primitive.*; +import com.caoccao.javet.values.reference.V8ValueObject; +import com.sun.source.tree.LiteralTree; +import com.sun.source.tree.TreeVisitor; + +import java.util.Map; + +public final class JTLiteral + extends JTExpression + implements LiteralTree { + private static final String DEFAULT_BOOLEAN = "false"; + private static final String DEFAULT_CHAR = "\\0"; + private static final String DEFAULT_DOUBLE = "0D"; + private static final String DEFAULT_FLOAT = "0F"; + private static final String DEFAULT_INT = "0"; + private static final String DEFAULT_LONG = "0L"; + private static final String PROPERTY_VALUE = "value"; + private Kind kind; + private Object value; + + public JTLiteral() { + this(null, null); + setActionChange(); + } + + JTLiteral(LiteralTree literalTree, JTTree parentTree) { + super(literalTree, parentTree); + kind = Kind.NULL_LITERAL; + value = null; + } + + private static Kind parseKind(Object value) { + if (value instanceof Integer) { + return Kind.INT_LITERAL; + } + if (value instanceof Long) { + return Kind.LONG_LITERAL; + } + if (value instanceof Float) { + return Kind.FLOAT_LITERAL; + } + if (value instanceof Double) { + return Kind.DOUBLE_LITERAL; + } + if (value instanceof Boolean) { + return Kind.BOOLEAN_LITERAL; + } + if (value instanceof Character) { + return Kind.CHAR_LITERAL; + } + if (value instanceof String) { + return Kind.STRING_LITERAL; + } + if (value == null) { + return Kind.NULL_LITERAL; + } + throw new AssertionError(value + " is not supported."); + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitLiteral(this, data); + } + + @Override + JTLiteral analyze() { + super.analyze(); + kind = getOriginalTree().getKind(); + value = getOriginalTree().getValue(); + return this; + } + + @Override + public Kind getKind() { + return kind; + } + + private V8Value getV8Value() throws JavetException { + if (value instanceof Integer valueInteger) { + return v8Runtime.createV8ValueInteger(valueInteger); + } + if (value instanceof Long valueLong) { + return v8Runtime.createV8ValueLong(valueLong); + } + if (value instanceof Float valueFloat) { + return v8Runtime.toV8Value(new JTFloat(valueFloat)); + } + if (value instanceof Double valueDouble) { + return v8Runtime.createV8ValueDouble(valueDouble); + } + if (value instanceof Boolean valueBoolean) { + return v8Runtime.createV8ValueBoolean(valueBoolean); + } + if (value instanceof Character valueCharacter) { + return v8Runtime.toV8Value(new JTCharacter(valueCharacter)); + } + if (value instanceof String valueString) { + return v8Runtime.toV8Value(valueString); + } + return v8Runtime.createV8ValueNull(); + } + + @Override + public Object getValue() { + return value; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_VALUE, propertyName -> getV8Value()); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_VALUE, (propertyName, propertyValue) -> setValue(propertyValue)); + registerStringSetter(PROPERTY_KIND, (propertyName, propertyValue) -> replaceKind(this::setKind, propertyValue)); + } + return stringSetterMap; + } + + @Override + public boolean serialize(IStyleWriter writer) { + if (isActionChange()) { + switch (kind) { + case BOOLEAN_LITERAL -> writer.append(value == null ? DEFAULT_BOOLEAN : String.valueOf(value)); + case CHAR_LITERAL -> { + String charString = DEFAULT_CHAR; + if (value instanceof Character character) { + charString = character.toString(); + } else if (value != null) { + charString = String.valueOf(value); + } + writer.appendJavaCharacter(charString); + } + case DOUBLE_LITERAL -> writer.append(value == null ? DEFAULT_DOUBLE : String.valueOf(value)); + case FLOAT_LITERAL -> writer.append(value == null ? DEFAULT_FLOAT : String.valueOf(value)); + case INT_LITERAL -> writer.append(value == null ? DEFAULT_INT : String.valueOf(value)); + case LONG_LITERAL -> writer.append(value == null ? DEFAULT_LONG : String.valueOf(value)); + case NULL_LITERAL -> writer.append((String) null); + case STRING_LITERAL -> { + if (value == null) { + writer.append((String) null); + } else { + writer.appendJavaString(String.valueOf(value)); + } + } + } + return true; + } + return super.serialize(writer); + } + + public JTLiteral setKind(Kind kind) { + switch (kind) { + case INT_LITERAL, LONG_LITERAL, FLOAT_LITERAL, DOUBLE_LITERAL, BOOLEAN_LITERAL, + CHAR_LITERAL, STRING_LITERAL, NULL_LITERAL -> this.kind = kind; + default -> this.kind = Kind.NULL_LITERAL; + } + return setActionChange(); + } + + private boolean setValue(V8Value v8Value) throws JavetException { + Object valueObject = null; + if (v8Value instanceof V8ValueInteger v8ValueInteger) { + valueObject = v8ValueInteger.getValue(); + } else if (v8Value instanceof V8ValueLong v8ValueLong) { + valueObject = v8ValueLong.getValue(); + } else if (v8Value instanceof V8ValueDouble v8ValueDouble) { + valueObject = v8ValueDouble.getValue(); + } else if (v8Value instanceof V8ValueBoolean v8ValueBoolean) { + valueObject = v8ValueBoolean.getValue(); + } else if (v8Value instanceof V8ValueString v8ValueString) { + valueObject = v8ValueString.getValue(); + } else if (v8Value instanceof V8ValueObject v8ValueObject) { + valueObject = v8Runtime.toObject(v8ValueObject); + if (!(valueObject instanceof Float || valueObject instanceof Character)) { + valueObject = null; + } + } + setValue(valueObject); + return true; + } + + public JTLiteral setValue(Object value) { + if (this.value == value) { + return this; + } + this.value = value; + kind = parseKind(this.value); + return setActionChange(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTMemberReference.java b/src/main/java/com/caoccao/jaspiler/trees/JTMemberReference.java index 539542c..2210309 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTMemberReference.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTMemberReference.java @@ -1,159 +1,159 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.caoccao.javet.values.primitive.V8ValueString; -import com.sun.source.tree.MemberReferenceTree; -import com.sun.source.tree.TreeVisitor; - -import java.util.*; - -public final class JTMemberReference - extends JTFunctionalExpression - implements MemberReferenceTree { - private static final String PROPERTY_MODE = "mode"; - private static final String PROPERTY_NAME = "name"; - private static final String PROPERTY_QUALIFIED_EXPRESSION = "qualifiedExpression"; - private static final String PROPERTY_TYPE_ARGUMENTS = "typeArguments"; - private final List> typeArguments; - private ReferenceMode mode; - private JTName name; - private JTExpression qualifiedExpression; - - public JTMemberReference() { - this(null, null); - setActionChange(); - } - - JTMemberReference(MemberReferenceTree memberReferenceTree, JTTree parentTree) { - super(memberReferenceTree, parentTree); - mode = null; - name = null; - qualifiedExpression = null; - typeArguments = new ArrayList<>(); - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitMemberReference(this, data); - } - - @Override - JTMemberReference analyze() { - super.analyze(); - qualifiedExpression = JTTreeFactory.create(getOriginalTree().getQualifierExpression(), this); - JTTreeFactory.createAndAdd( - getOriginalTree().getTypeArguments(), this, (JTExpression o) -> typeArguments.add(o)); - mode = getOriginalTree().getMode(); - name = JTTreeFactory.createName(getOriginalTree().getName()); - return this; - } - - @Override - List> getAllNodes() { - var nodes = super.getAllNodes(); - Optional.ofNullable(qualifiedExpression).ifPresent(nodes::add); - typeArguments.stream().filter(Objects::nonNull).forEach(nodes::add); - nodes.forEach(node -> node.setParentTree(this)); - return nodes; - } - - @Override - public Kind getKind() { - return Kind.MEMBER_REFERENCE; - } - - @Override - public ReferenceMode getMode() { - return mode; - } - - @Override - public JTName getName() { - return name; - } - - @Override - public JTExpression getQualifierExpression() { - return qualifiedExpression; - } - - @Override - public List> getTypeArguments() { - return typeArguments; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_MODE, propertyName -> v8Runtime.createV8ValueString(getMode().name())); - registerStringGetter(PROPERTY_NAME, propertyName -> v8Runtime.toV8Value(getName())); - registerStringGetter(PROPERTY_QUALIFIED_EXPRESSION, propertyName -> v8Runtime.toV8Value(getQualifierExpression())); - registerStringGetter(PROPERTY_TYPE_ARGUMENTS, propertyName -> v8Runtime.toV8Value(getTypeArguments())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_MODE, (propertyName, propertyValue) -> setMode(propertyValue)); - registerStringSetter(PROPERTY_NAME, (propertyName, propertyValue) -> replaceName(this::setName, propertyValue)); - registerStringSetter(PROPERTY_QUALIFIED_EXPRESSION, (propertyName, propertyValue) -> replaceExpression(this::setQualifiedExpression, propertyValue)); - registerStringSetter(PROPERTY_TYPE_ARGUMENTS, (propertyName, propertyValue) -> replaceExpressions(typeArguments, propertyValue)); - } - return stringSetterMap; - } - - private boolean setMode(V8Value v8Value) { - if (v8Value instanceof V8ValueString v8ValueString) { - setMode(ReferenceMode.valueOf(v8ValueString.getValue())); - return true; - } - return false; - } - - public JTMemberReference setMode(ReferenceMode mode) { - if (this.mode == mode) { - return this; - } - this.mode = Objects.requireNonNull(mode); - return setActionChange(); - } - - public JTMemberReference setName(JTName name) { - if (this.name == name) { - return this; - } - this.name = Objects.requireNonNull(name); - return setActionChange(); - } - - public JTMemberReference setQualifiedExpression(JTExpression qualifiedExpression) { - if (this.qualifiedExpression == qualifiedExpression) { - return this; - } - this.qualifiedExpression = Objects.requireNonNull(qualifiedExpression).setParentTree(this); - return setActionChange(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.caoccao.javet.values.primitive.V8ValueString; +import com.sun.source.tree.MemberReferenceTree; +import com.sun.source.tree.TreeVisitor; + +import java.util.*; + +public final class JTMemberReference + extends JTFunctionalExpression + implements MemberReferenceTree { + private static final String PROPERTY_MODE = "mode"; + private static final String PROPERTY_NAME = "name"; + private static final String PROPERTY_QUALIFIED_EXPRESSION = "qualifiedExpression"; + private static final String PROPERTY_TYPE_ARGUMENTS = "typeArguments"; + private final List> typeArguments; + private ReferenceMode mode; + private JTName name; + private JTExpression qualifiedExpression; + + public JTMemberReference() { + this(null, null); + setActionChange(); + } + + JTMemberReference(MemberReferenceTree memberReferenceTree, JTTree parentTree) { + super(memberReferenceTree, parentTree); + mode = null; + name = null; + qualifiedExpression = null; + typeArguments = new ArrayList<>(); + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitMemberReference(this, data); + } + + @Override + JTMemberReference analyze() { + super.analyze(); + qualifiedExpression = JTTreeFactory.create(getOriginalTree().getQualifierExpression(), this); + JTTreeFactory.createAndAdd( + getOriginalTree().getTypeArguments(), this, (JTExpression o) -> typeArguments.add(o)); + mode = getOriginalTree().getMode(); + name = JTTreeFactory.createName(getOriginalTree().getName()); + return this; + } + + @Override + List> getAllNodes() { + var nodes = super.getAllNodes(); + Optional.ofNullable(qualifiedExpression).ifPresent(nodes::add); + typeArguments.stream().filter(Objects::nonNull).forEach(nodes::add); + nodes.forEach(node -> node.setParentTree(this)); + return nodes; + } + + @Override + public Kind getKind() { + return Kind.MEMBER_REFERENCE; + } + + @Override + public ReferenceMode getMode() { + return mode; + } + + @Override + public JTName getName() { + return name; + } + + @Override + public JTExpression getQualifierExpression() { + return qualifiedExpression; + } + + @Override + public List> getTypeArguments() { + return typeArguments; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_MODE, propertyName -> v8Runtime.createV8ValueString(getMode().name())); + registerStringGetter(PROPERTY_NAME, propertyName -> v8Runtime.toV8Value(getName())); + registerStringGetter(PROPERTY_QUALIFIED_EXPRESSION, propertyName -> v8Runtime.toV8Value(getQualifierExpression())); + registerStringGetter(PROPERTY_TYPE_ARGUMENTS, propertyName -> v8Runtime.toV8Value(getTypeArguments())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_MODE, (propertyName, propertyValue) -> setMode(propertyValue)); + registerStringSetter(PROPERTY_NAME, (propertyName, propertyValue) -> replaceName(this::setName, propertyValue)); + registerStringSetter(PROPERTY_QUALIFIED_EXPRESSION, (propertyName, propertyValue) -> replaceExpression(this::setQualifiedExpression, propertyValue)); + registerStringSetter(PROPERTY_TYPE_ARGUMENTS, (propertyName, propertyValue) -> replaceExpressions(typeArguments, propertyValue)); + } + return stringSetterMap; + } + + private boolean setMode(V8Value v8Value) { + if (v8Value instanceof V8ValueString v8ValueString) { + setMode(ReferenceMode.valueOf(v8ValueString.getValue())); + return true; + } + return false; + } + + public JTMemberReference setMode(ReferenceMode mode) { + if (this.mode == mode) { + return this; + } + this.mode = Objects.requireNonNull(mode); + return setActionChange(); + } + + public JTMemberReference setName(JTName name) { + if (this.name == name) { + return this; + } + this.name = Objects.requireNonNull(name); + return setActionChange(); + } + + public JTMemberReference setQualifiedExpression(JTExpression qualifiedExpression) { + if (this.qualifiedExpression == qualifiedExpression) { + return this; + } + this.qualifiedExpression = Objects.requireNonNull(qualifiedExpression).setParentTree(this); + return setActionChange(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTMethodDecl.java b/src/main/java/com/caoccao/jaspiler/trees/JTMethodDecl.java index eb2346a..86a22d3 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTMethodDecl.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTMethodDecl.java @@ -1,283 +1,283 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.enums.JavaKeyword; -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.jaspiler.styles.IStyleWriter; -import com.caoccao.jaspiler.utils.ForEachUtils; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.sun.source.tree.MethodTree; -import com.sun.source.tree.TreeVisitor; - -import java.util.*; - -public final class JTMethodDecl - extends JTTree - implements MethodTree { - private static final String PROPERTY_BODY = "body"; - private static final String PROPERTY_DEFAULT_VALUE = "defaultValue"; - private static final String PROPERTY_MODIFIERS = "modifiers"; - private static final String PROPERTY_NAME = "name"; - private static final String PROPERTY_PARAMETERS = "parameters"; - private static final String PROPERTY_RECEIVER_PARAMETER = "receiverParameter"; - private static final String PROPERTY_RETURN_TYPE = "returnType"; - private static final String PROPERTY_THROW_EXPRESSIONS = "throwExpressions"; - private static final String PROPERTY_TYPE_PARAMETERS = "typeParameters"; - private final List parameters; - private final List> throwExpressions; - private final List typeParameters; - private JTBlock body; - private JTExpression defaultValue; - private JTModifiers modifiers; - private JTName name; - private JTVariableDecl receiverParameter; - private JTExpression returnType; - - public JTMethodDecl() { - this(null, null); - setActionChange(); - } - - JTMethodDecl(MethodTree methodTree, JTTree parentTree) { - super(methodTree, parentTree); - body = null; - defaultValue = null; - modifiers = null; - name = null; - parameters = new ArrayList<>(); - receiverParameter = null; - returnType = null; - throwExpressions = new ArrayList<>(); - typeParameters = new ArrayList<>(); - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitMethod(this, data); - } - - @Override - JTMethodDecl analyze() { - super.analyze(); - modifiers = JTTreeFactory.create( - getOriginalTree().getModifiers(), this, JTModifiers::new); - returnType = JTTreeFactory.create(getOriginalTree().getReturnType(), this); - JTTreeFactory.createAndAdd( - getOriginalTree().getTypeParameters(), this, JTTypeParameter::new, typeParameters::add); - JTTreeFactory.createAndAdd( - getOriginalTree().getParameters(), this, JTVariableDecl::new, parameters::add); - receiverParameter = JTTreeFactory.create( - getOriginalTree().getReceiverParameter(), this, JTVariableDecl::new); - JTTreeFactory.createAndAdd( - getOriginalTree().getThrows(), this, (JTExpression o) -> throwExpressions.add(o)); - body = JTTreeFactory.create( - getOriginalTree().getBody(), this, JTBlock::new); - defaultValue = JTTreeFactory.create(getOriginalTree().getDefaultValue(), this); - name = JTTreeFactory.createName(getOriginalTree().getName()); - return this; - } - - @Override - List> getAllNodes() { - var nodes = super.getAllNodes(); - Optional.ofNullable(modifiers).ifPresent(nodes::add); - Optional.ofNullable(returnType).ifPresent(nodes::add); - typeParameters.stream().filter(Objects::nonNull).forEach(nodes::add); - parameters.stream().filter(Objects::nonNull).forEach(nodes::add); - Optional.ofNullable(receiverParameter).ifPresent(nodes::add); - throwExpressions.stream().filter(Objects::nonNull).forEach(nodes::add); - Optional.ofNullable(body).ifPresent(nodes::add); - Optional.ofNullable(defaultValue).ifPresent(nodes::add); - nodes.forEach(node -> node.setParentTree(this)); - return nodes; - } - - @Override - public JTBlock getBody() { - return body; - } - - @Override - public JTExpression getDefaultValue() { - return defaultValue; - } - - @Override - public Kind getKind() { - return Kind.METHOD; - } - - @Override - public JTModifiers getModifiers() { - return modifiers; - } - - @Override - public JTName getName() { - return name; - } - - @Override - public List getParameters() { - return parameters; - } - - @Override - public JTVariableDecl getReceiverParameter() { - return receiverParameter; - } - - @Override - public JTExpression getReturnType() { - return returnType; - } - - @Override - public List> getThrows() { - return throwExpressions; - } - - @Override - public List getTypeParameters() { - return typeParameters; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_BODY, propertyName -> v8Runtime.toV8Value(getBody())); - registerStringGetter(PROPERTY_DEFAULT_VALUE, propertyName -> v8Runtime.toV8Value(getDefaultValue())); - registerStringGetter(PROPERTY_MODIFIERS, propertyName -> v8Runtime.toV8Value(getModifiers())); - registerStringGetter(PROPERTY_NAME, propertyName -> v8Runtime.toV8Value(getName())); - registerStringGetter(PROPERTY_PARAMETERS, propertyName -> v8Runtime.toV8Value(getParameters())); - registerStringGetter(PROPERTY_RECEIVER_PARAMETER, propertyName -> v8Runtime.toV8Value(getReceiverParameter())); - registerStringGetter(PROPERTY_RETURN_TYPE, propertyName -> v8Runtime.toV8Value(getReturnType())); - registerStringGetter(PROPERTY_THROW_EXPRESSIONS, propertyName -> v8Runtime.toV8Value(getThrows())); - registerStringGetter(PROPERTY_TYPE_PARAMETERS, propertyName -> v8Runtime.toV8Value(getTypeParameters())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_BODY, (propertyName, propertyValue) -> replaceBlock(this::setBody, propertyValue)); - registerStringSetter(PROPERTY_DEFAULT_VALUE, (propertyName, propertyValue) -> replaceExpression(this::setDefaultValue, propertyValue)); - registerStringSetter(PROPERTY_MODIFIERS, (propertyName, propertyValue) -> replaceModifiers(this::setModifiers, propertyValue)); - registerStringSetter(PROPERTY_NAME, (propertyName, propertyValue) -> replaceName(this::setName, propertyValue)); - registerStringSetter(PROPERTY_PARAMETERS, (propertyName, propertyValue) -> replaceVariableDecls(parameters, propertyValue)); - registerStringSetter(PROPERTY_RECEIVER_PARAMETER, (propertyName, propertyValue) -> replaceVariableDecl(this::setReceiverParameter, propertyValue)); - registerStringSetter(PROPERTY_RETURN_TYPE, (propertyName, propertyValue) -> replaceExpression(this::setReturnType, propertyValue)); - registerStringSetter(PROPERTY_THROW_EXPRESSIONS, (propertyName, propertyValue) -> replaceExpressions(throwExpressions, propertyValue)); - registerStringSetter(PROPERTY_TYPE_PARAMETERS, (propertyName, propertyValue) -> replaceTypeParameters(typeParameters, propertyValue)); - } - return stringSetterMap; - } - - @Override - public boolean serialize(IStyleWriter writer) { - if (isActionChange()) { - Optional.ofNullable(modifiers).ifPresent(writer::append); - ForEachUtils.forEach( - typeParameters.stream().filter(Objects::nonNull).filter(tree -> !tree.isActionIgnore()).toList(), - writer::append, - tree -> writer.appendComma().appendSpace(), - trees -> writer.appendSpaceIfNeeded().appendLeftArrow(), - trees -> writer.appendRightArrow()); - Optional.of(returnType) - .filter(tree -> !tree.isActionIgnore()) - .ifPresent(tree -> writer.appendSpaceIfNeeded().append(tree)); - writer.appendSpaceIfNeeded().append(name).appendLeftParenthesis(); - ForEachUtils.forEach( - parameters.stream().filter(Objects::nonNull).filter(tree -> !tree.isActionIgnore()).toList(), - writer::append, - tree -> writer.appendComma().appendSpace()); - writer.appendRightParenthesis(); - Optional.ofNullable(receiverParameter) - .filter(tree -> !tree.isActionIgnore()) - .ifPresent(tree -> writer.appendSpace().append(tree)); - ForEachUtils.forEach( - throwExpressions.stream().filter(Objects::nonNull).filter(tree -> !tree.isActionIgnore()).toList(), - writer::append, - tree -> writer.appendComma().appendSpace(), - trees -> writer.appendKeyword(JavaKeyword.THROWS).appendSpace()); - Optional.ofNullable(defaultValue) - .filter(tree -> !tree.isActionIgnore()) - .ifPresent(tree -> writer.appendKeyword(JavaKeyword.DEFAULT).appendSpace().append(tree)); - if (body != null && !body.isActionIgnore()) { - writer.appendSpaceIfNeeded().append(body); - } else { - writer.appendSemiColon(); - } - return true; - } - return super.serialize(writer); - } - - public JTMethodDecl setBody(JTBlock body) { - if (this.body == body) { - return this; - } - this.body = Objects.requireNonNull(body).setParentTree(this); - return setActionChange(); - } - - public JTMethodDecl setDefaultValue(JTExpression defaultValue) { - if (this.defaultValue == defaultValue) { - return this; - } - this.defaultValue = Optional.ofNullable(defaultValue).map(o -> o.setParentTree(this)).orElse(null); - return setActionChange(); - } - - public JTMethodDecl setModifiers(JTModifiers modifiers) { - if (this.modifiers == modifiers) { - return this; - } - this.modifiers = Objects.requireNonNull(modifiers).setParentTree(this); - return setActionChange(); - } - - public JTMethodDecl setName(JTName name) { - if (this.name == name) { - return this; - } - this.name = Objects.requireNonNull(name); - return setActionChange(); - } - - public JTMethodDecl setReceiverParameter(JTVariableDecl receiverParameter) { - if (this.receiverParameter == receiverParameter) { - return this; - } - this.receiverParameter = Optional.ofNullable(receiverParameter).map(o -> o.setParentTree(this)).orElse(null); - return setActionChange(); - } - - public JTMethodDecl setReturnType(JTExpression returnType) { - if (this.returnType == returnType) { - return this; - } - this.returnType = Objects.requireNonNull(returnType).setParentTree(this); - return setActionChange(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.enums.JavaKeyword; +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.jaspiler.styles.IStyleWriter; +import com.caoccao.jaspiler.utils.ForEachUtils; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.sun.source.tree.MethodTree; +import com.sun.source.tree.TreeVisitor; + +import java.util.*; + +public final class JTMethodDecl + extends JTTree + implements MethodTree { + private static final String PROPERTY_BODY = "body"; + private static final String PROPERTY_DEFAULT_VALUE = "defaultValue"; + private static final String PROPERTY_MODIFIERS = "modifiers"; + private static final String PROPERTY_NAME = "name"; + private static final String PROPERTY_PARAMETERS = "parameters"; + private static final String PROPERTY_RECEIVER_PARAMETER = "receiverParameter"; + private static final String PROPERTY_RETURN_TYPE = "returnType"; + private static final String PROPERTY_THROW_EXPRESSIONS = "throwExpressions"; + private static final String PROPERTY_TYPE_PARAMETERS = "typeParameters"; + private final List parameters; + private final List> throwExpressions; + private final List typeParameters; + private JTBlock body; + private JTExpression defaultValue; + private JTModifiers modifiers; + private JTName name; + private JTVariableDecl receiverParameter; + private JTExpression returnType; + + public JTMethodDecl() { + this(null, null); + setActionChange(); + } + + JTMethodDecl(MethodTree methodTree, JTTree parentTree) { + super(methodTree, parentTree); + body = null; + defaultValue = null; + modifiers = null; + name = null; + parameters = new ArrayList<>(); + receiverParameter = null; + returnType = null; + throwExpressions = new ArrayList<>(); + typeParameters = new ArrayList<>(); + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitMethod(this, data); + } + + @Override + JTMethodDecl analyze() { + super.analyze(); + modifiers = JTTreeFactory.create( + getOriginalTree().getModifiers(), this, JTModifiers::new); + returnType = JTTreeFactory.create(getOriginalTree().getReturnType(), this); + JTTreeFactory.createAndAdd( + getOriginalTree().getTypeParameters(), this, JTTypeParameter::new, typeParameters::add); + JTTreeFactory.createAndAdd( + getOriginalTree().getParameters(), this, JTVariableDecl::new, parameters::add); + receiverParameter = JTTreeFactory.create( + getOriginalTree().getReceiverParameter(), this, JTVariableDecl::new); + JTTreeFactory.createAndAdd( + getOriginalTree().getThrows(), this, (JTExpression o) -> throwExpressions.add(o)); + body = JTTreeFactory.create( + getOriginalTree().getBody(), this, JTBlock::new); + defaultValue = JTTreeFactory.create(getOriginalTree().getDefaultValue(), this); + name = JTTreeFactory.createName(getOriginalTree().getName()); + return this; + } + + @Override + List> getAllNodes() { + var nodes = super.getAllNodes(); + Optional.ofNullable(modifiers).ifPresent(nodes::add); + Optional.ofNullable(returnType).ifPresent(nodes::add); + typeParameters.stream().filter(Objects::nonNull).forEach(nodes::add); + parameters.stream().filter(Objects::nonNull).forEach(nodes::add); + Optional.ofNullable(receiverParameter).ifPresent(nodes::add); + throwExpressions.stream().filter(Objects::nonNull).forEach(nodes::add); + Optional.ofNullable(body).ifPresent(nodes::add); + Optional.ofNullable(defaultValue).ifPresent(nodes::add); + nodes.forEach(node -> node.setParentTree(this)); + return nodes; + } + + @Override + public JTBlock getBody() { + return body; + } + + @Override + public JTExpression getDefaultValue() { + return defaultValue; + } + + @Override + public Kind getKind() { + return Kind.METHOD; + } + + @Override + public JTModifiers getModifiers() { + return modifiers; + } + + @Override + public JTName getName() { + return name; + } + + @Override + public List getParameters() { + return parameters; + } + + @Override + public JTVariableDecl getReceiverParameter() { + return receiverParameter; + } + + @Override + public JTExpression getReturnType() { + return returnType; + } + + @Override + public List> getThrows() { + return throwExpressions; + } + + @Override + public List getTypeParameters() { + return typeParameters; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_BODY, propertyName -> v8Runtime.toV8Value(getBody())); + registerStringGetter(PROPERTY_DEFAULT_VALUE, propertyName -> v8Runtime.toV8Value(getDefaultValue())); + registerStringGetter(PROPERTY_MODIFIERS, propertyName -> v8Runtime.toV8Value(getModifiers())); + registerStringGetter(PROPERTY_NAME, propertyName -> v8Runtime.toV8Value(getName())); + registerStringGetter(PROPERTY_PARAMETERS, propertyName -> v8Runtime.toV8Value(getParameters())); + registerStringGetter(PROPERTY_RECEIVER_PARAMETER, propertyName -> v8Runtime.toV8Value(getReceiverParameter())); + registerStringGetter(PROPERTY_RETURN_TYPE, propertyName -> v8Runtime.toV8Value(getReturnType())); + registerStringGetter(PROPERTY_THROW_EXPRESSIONS, propertyName -> v8Runtime.toV8Value(getThrows())); + registerStringGetter(PROPERTY_TYPE_PARAMETERS, propertyName -> v8Runtime.toV8Value(getTypeParameters())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_BODY, (propertyName, propertyValue) -> replaceBlock(this::setBody, propertyValue)); + registerStringSetter(PROPERTY_DEFAULT_VALUE, (propertyName, propertyValue) -> replaceExpression(this::setDefaultValue, propertyValue)); + registerStringSetter(PROPERTY_MODIFIERS, (propertyName, propertyValue) -> replaceModifiers(this::setModifiers, propertyValue)); + registerStringSetter(PROPERTY_NAME, (propertyName, propertyValue) -> replaceName(this::setName, propertyValue)); + registerStringSetter(PROPERTY_PARAMETERS, (propertyName, propertyValue) -> replaceVariableDecls(parameters, propertyValue)); + registerStringSetter(PROPERTY_RECEIVER_PARAMETER, (propertyName, propertyValue) -> replaceVariableDecl(this::setReceiverParameter, propertyValue)); + registerStringSetter(PROPERTY_RETURN_TYPE, (propertyName, propertyValue) -> replaceExpression(this::setReturnType, propertyValue)); + registerStringSetter(PROPERTY_THROW_EXPRESSIONS, (propertyName, propertyValue) -> replaceExpressions(throwExpressions, propertyValue)); + registerStringSetter(PROPERTY_TYPE_PARAMETERS, (propertyName, propertyValue) -> replaceTypeParameters(typeParameters, propertyValue)); + } + return stringSetterMap; + } + + @Override + public boolean serialize(IStyleWriter writer) { + if (isActionChange()) { + Optional.ofNullable(modifiers).ifPresent(writer::append); + ForEachUtils.forEach( + typeParameters.stream().filter(Objects::nonNull).filter(tree -> !tree.isActionIgnore()).toList(), + writer::append, + tree -> writer.appendComma().appendSpace(), + trees -> writer.appendSpaceIfNeeded().appendLeftArrow(), + trees -> writer.appendRightArrow()); + Optional.of(returnType) + .filter(tree -> !tree.isActionIgnore()) + .ifPresent(tree -> writer.appendSpaceIfNeeded().append(tree)); + writer.appendSpaceIfNeeded().append(name).appendLeftParenthesis(); + ForEachUtils.forEach( + parameters.stream().filter(Objects::nonNull).filter(tree -> !tree.isActionIgnore()).toList(), + writer::append, + tree -> writer.appendComma().appendSpace()); + writer.appendRightParenthesis(); + Optional.ofNullable(receiverParameter) + .filter(tree -> !tree.isActionIgnore()) + .ifPresent(tree -> writer.appendSpace().append(tree)); + ForEachUtils.forEach( + throwExpressions.stream().filter(Objects::nonNull).filter(tree -> !tree.isActionIgnore()).toList(), + writer::append, + tree -> writer.appendComma().appendSpace(), + trees -> writer.appendKeyword(JavaKeyword.THROWS).appendSpace()); + Optional.ofNullable(defaultValue) + .filter(tree -> !tree.isActionIgnore()) + .ifPresent(tree -> writer.appendKeyword(JavaKeyword.DEFAULT).appendSpace().append(tree)); + if (body != null && !body.isActionIgnore()) { + writer.appendSpaceIfNeeded().append(body); + } else { + writer.appendSemiColon(); + } + return true; + } + return super.serialize(writer); + } + + public JTMethodDecl setBody(JTBlock body) { + if (this.body == body) { + return this; + } + this.body = Objects.requireNonNull(body).setParentTree(this); + return setActionChange(); + } + + public JTMethodDecl setDefaultValue(JTExpression defaultValue) { + if (this.defaultValue == defaultValue) { + return this; + } + this.defaultValue = Optional.ofNullable(defaultValue).map(o -> o.setParentTree(this)).orElse(null); + return setActionChange(); + } + + public JTMethodDecl setModifiers(JTModifiers modifiers) { + if (this.modifiers == modifiers) { + return this; + } + this.modifiers = Objects.requireNonNull(modifiers).setParentTree(this); + return setActionChange(); + } + + public JTMethodDecl setName(JTName name) { + if (this.name == name) { + return this; + } + this.name = Objects.requireNonNull(name); + return setActionChange(); + } + + public JTMethodDecl setReceiverParameter(JTVariableDecl receiverParameter) { + if (this.receiverParameter == receiverParameter) { + return this; + } + this.receiverParameter = Optional.ofNullable(receiverParameter).map(o -> o.setParentTree(this)).orElse(null); + return setActionChange(); + } + + public JTMethodDecl setReturnType(JTExpression returnType) { + if (this.returnType == returnType) { + return this; + } + this.returnType = Objects.requireNonNull(returnType).setParentTree(this); + return setActionChange(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTMethodInvocation.java b/src/main/java/com/caoccao/jaspiler/trees/JTMethodInvocation.java index cfc5bc7..977e958 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTMethodInvocation.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTMethodInvocation.java @@ -1,125 +1,125 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.sun.source.tree.MethodInvocationTree; -import com.sun.source.tree.TreeVisitor; - -import java.util.*; - -public final class JTMethodInvocation - extends JTPolyExpression - implements MethodInvocationTree { - private static final String PROPERTY_ARGUMENTS = "arguments"; - private static final String PROPERTY_METHOD_SELECT = "methodSelect"; - private static final String PROPERTY_TYPE_ARGUMENTS = "typeArguments"; - private final List> arguments; - private final List> typeArguments; - private JTExpression methodSelect; - - public JTMethodInvocation() { - this(null, null); - setActionChange(); - } - - JTMethodInvocation(MethodInvocationTree methodInvocationTree, JTTree parentTree) { - super(methodInvocationTree, parentTree); - arguments = new ArrayList<>(); - methodSelect = null; - typeArguments = new ArrayList<>(); - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitMethodInvocation(this, data); - } - - @Override - JTMethodInvocation analyze() { - super.analyze(); - JTTreeFactory.createAndAdd( - getOriginalTree().getTypeArguments(), this, (JTExpression o) -> typeArguments.add(o)); - methodSelect = JTTreeFactory.create(getOriginalTree().getMethodSelect(), this); - JTTreeFactory.createAndAdd( - getOriginalTree().getArguments(), this, (JTExpression o) -> arguments.add(o)); - return this; - } - - @Override - List> getAllNodes() { - var nodes = super.getAllNodes(); - typeArguments.stream().filter(Objects::nonNull).forEach(nodes::add); - Optional.ofNullable(methodSelect).ifPresent(nodes::add); - arguments.stream().filter(Objects::nonNull).forEach(nodes::add); - nodes.forEach(node -> node.setParentTree(this)); - return nodes; - } - - @Override - public List> getArguments() { - return arguments; - } - - @Override - public Kind getKind() { - return Kind.METHOD_INVOCATION; - } - - @Override - public JTExpression getMethodSelect() { - return methodSelect; - } - - @Override - public List> getTypeArguments() { - return typeArguments; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_ARGUMENTS, propertyName -> v8Runtime.toV8Value(getArguments())); - registerStringGetter(PROPERTY_METHOD_SELECT, propertyName -> v8Runtime.toV8Value(getMethodSelect())); - registerStringGetter(PROPERTY_TYPE_ARGUMENTS, propertyName -> v8Runtime.toV8Value(getTypeArguments())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_ARGUMENTS, (propertyName, propertyValue) -> replaceExpressions(arguments, propertyValue)); - registerStringSetter(PROPERTY_METHOD_SELECT, (propertyName, propertyValue) -> replaceExpression(this::setMethodSelect, propertyValue)); - registerStringSetter(PROPERTY_TYPE_ARGUMENTS, (propertyName, propertyValue) -> replaceExpressions(typeArguments, propertyValue)); - } - return stringSetterMap; - } - - public JTMethodInvocation setMethodSelect(JTExpression methodSelect) { - if (this.methodSelect == methodSelect) { - return this; - } - this.methodSelect = Objects.requireNonNull(methodSelect).setParentTree(this); - return setActionChange(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.sun.source.tree.MethodInvocationTree; +import com.sun.source.tree.TreeVisitor; + +import java.util.*; + +public final class JTMethodInvocation + extends JTPolyExpression + implements MethodInvocationTree { + private static final String PROPERTY_ARGUMENTS = "arguments"; + private static final String PROPERTY_METHOD_SELECT = "methodSelect"; + private static final String PROPERTY_TYPE_ARGUMENTS = "typeArguments"; + private final List> arguments; + private final List> typeArguments; + private JTExpression methodSelect; + + public JTMethodInvocation() { + this(null, null); + setActionChange(); + } + + JTMethodInvocation(MethodInvocationTree methodInvocationTree, JTTree parentTree) { + super(methodInvocationTree, parentTree); + arguments = new ArrayList<>(); + methodSelect = null; + typeArguments = new ArrayList<>(); + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitMethodInvocation(this, data); + } + + @Override + JTMethodInvocation analyze() { + super.analyze(); + JTTreeFactory.createAndAdd( + getOriginalTree().getTypeArguments(), this, (JTExpression o) -> typeArguments.add(o)); + methodSelect = JTTreeFactory.create(getOriginalTree().getMethodSelect(), this); + JTTreeFactory.createAndAdd( + getOriginalTree().getArguments(), this, (JTExpression o) -> arguments.add(o)); + return this; + } + + @Override + List> getAllNodes() { + var nodes = super.getAllNodes(); + typeArguments.stream().filter(Objects::nonNull).forEach(nodes::add); + Optional.ofNullable(methodSelect).ifPresent(nodes::add); + arguments.stream().filter(Objects::nonNull).forEach(nodes::add); + nodes.forEach(node -> node.setParentTree(this)); + return nodes; + } + + @Override + public List> getArguments() { + return arguments; + } + + @Override + public Kind getKind() { + return Kind.METHOD_INVOCATION; + } + + @Override + public JTExpression getMethodSelect() { + return methodSelect; + } + + @Override + public List> getTypeArguments() { + return typeArguments; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_ARGUMENTS, propertyName -> v8Runtime.toV8Value(getArguments())); + registerStringGetter(PROPERTY_METHOD_SELECT, propertyName -> v8Runtime.toV8Value(getMethodSelect())); + registerStringGetter(PROPERTY_TYPE_ARGUMENTS, propertyName -> v8Runtime.toV8Value(getTypeArguments())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_ARGUMENTS, (propertyName, propertyValue) -> replaceExpressions(arguments, propertyValue)); + registerStringSetter(PROPERTY_METHOD_SELECT, (propertyName, propertyValue) -> replaceExpression(this::setMethodSelect, propertyValue)); + registerStringSetter(PROPERTY_TYPE_ARGUMENTS, (propertyName, propertyValue) -> replaceExpressions(typeArguments, propertyValue)); + } + return stringSetterMap; + } + + public JTMethodInvocation setMethodSelect(JTExpression methodSelect) { + if (this.methodSelect == methodSelect) { + return this; + } + this.methodSelect = Objects.requireNonNull(methodSelect).setParentTree(this); + return setActionChange(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTModifiers.java b/src/main/java/com/caoccao/jaspiler/trees/JTModifiers.java index 56c1b39..5577981 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTModifiers.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTModifiers.java @@ -1,158 +1,158 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.jaspiler.styles.IStyleWriter; -import com.caoccao.jaspiler.utils.ForEachUtils; -import com.caoccao.javet.exceptions.JavetException; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.caoccao.javet.values.primitive.V8ValueString; -import com.caoccao.javet.values.reference.V8ValueArray; -import com.sun.source.tree.ModifiersTree; -import com.sun.source.tree.TreeVisitor; - -import javax.lang.model.element.Modifier; -import java.util.*; - -public final class JTModifiers - extends JTTree - implements ModifiersTree, IJTAnnotatable { - private static final List ABSTRACT_OR_DEFAULT_OR_STATIC_MODIFIERS = List.of( - Modifier.ABSTRACT, Modifier.DEFAULT, Modifier.STATIC); - private static final List OTHER_MODIFIERS = List.of( - Modifier.FINAL, Modifier.TRANSIENT, Modifier.VOLATILE, - Modifier.SYNCHRONIZED, Modifier.NATIVE, Modifier.STRICTFP); - private static final String PROPERTY_FLAGS = "flags"; - private static final List SCOPE_MODIFIERS = List.of( - Modifier.PUBLIC, Modifier.PROTECTED, Modifier.PRIVATE); - private static final List SEALED_OR_NON_SEALED_MODIFIERS = List.of( - Modifier.SEALED, Modifier.NON_SEALED); - private final List annotations; - private final Set flags; - - public JTModifiers() { - this(null, null); - setActionChange(); - } - - JTModifiers(ModifiersTree modifiersTree, JTTree parentTree) { - super(modifiersTree, parentTree); - annotations = new ArrayList<>(); - flags = new HashSet<>(); - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitModifiers(this, data); - } - - @Override - JTModifiers analyze() { - super.analyze(); - JTTreeFactory.createAndAdd( - getOriginalTree().getAnnotations(), this, JTAnnotation::new, annotations::add); - flags.clear(); - flags.addAll(getOriginalTree().getFlags()); - return this; - } - - @Override - List> getAllNodes() { - var nodes = super.getAllNodes(); - annotations.stream().filter(Objects::nonNull).forEach(nodes::add); - nodes.forEach(node -> node.setParentTree(this)); - return nodes; - } - - @Override - public List getAnnotations() { - return annotations; - } - - @Override - public Set getFlags() { - return flags; - } - - @Override - public Kind getKind() { - return Kind.MODIFIERS; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_ANNOTATIONS, propertyName -> v8Runtime.toV8Value(getAnnotations())); - registerStringGetter(PROPERTY_FLAGS, propertyName -> v8Runtime.toV8Value(getFlags().stream() - .map(Modifier::toString) - .toList())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_ANNOTATIONS, (propertyName, propertyValue) -> replaceAnnotations(annotations, propertyValue)); - registerStringSetter(PROPERTY_FLAGS, (propertyName, propertyValue) -> setFlags(propertyValue)); - } - return stringSetterMap; - } - - @Override - public boolean serialize(IStyleWriter writer) { - if (isActionChange()) { - int annotationDepth = writer.getDepth() - 1; - ForEachUtils.forEach( - annotations.stream().filter(Objects::nonNull).filter(tree -> !tree.isActionIgnore()).toList(), - tree -> writer.appendIndent(annotationDepth).append(tree).appendLineSeparator()); - List modifiers = new ArrayList<>(); - SCOPE_MODIFIERS.stream().filter(flags::contains).findFirst().ifPresent(modifiers::add); - ABSTRACT_OR_DEFAULT_OR_STATIC_MODIFIERS.stream().filter(flags::contains).findFirst().ifPresent(modifiers::add); - SEALED_OR_NON_SEALED_MODIFIERS.stream().filter(flags::contains).findFirst().ifPresent(modifiers::add); - OTHER_MODIFIERS.stream().filter(flags::contains).forEach(modifiers::add); - ForEachUtils.forEach( - modifiers, - writer::append, - tree -> writer.appendSpace(), - trees -> writer.appendSpaceIfNeeded()); - return true; - } - return super.serialize(writer); - } - - private boolean setFlags(V8Value v8Value) throws JavetException { - if (v8Value instanceof V8ValueArray v8ValueArray) { - flags.clear(); - v8ValueArray.forEach(v8ValueItem -> { - if (v8ValueItem instanceof V8ValueString v8ValueString) { - try { - flags.add(Modifier.valueOf(v8ValueString.getValue())); - } catch (Throwable ignored) { - } - } - }); - return true; - } - return false; - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.jaspiler.styles.IStyleWriter; +import com.caoccao.jaspiler.utils.ForEachUtils; +import com.caoccao.javet.exceptions.JavetException; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.caoccao.javet.values.primitive.V8ValueString; +import com.caoccao.javet.values.reference.V8ValueArray; +import com.sun.source.tree.ModifiersTree; +import com.sun.source.tree.TreeVisitor; + +import javax.lang.model.element.Modifier; +import java.util.*; + +public final class JTModifiers + extends JTTree + implements ModifiersTree, IJTAnnotatable { + private static final List ABSTRACT_OR_DEFAULT_OR_STATIC_MODIFIERS = List.of( + Modifier.ABSTRACT, Modifier.DEFAULT, Modifier.STATIC); + private static final List OTHER_MODIFIERS = List.of( + Modifier.FINAL, Modifier.TRANSIENT, Modifier.VOLATILE, + Modifier.SYNCHRONIZED, Modifier.NATIVE, Modifier.STRICTFP); + private static final String PROPERTY_FLAGS = "flags"; + private static final List SCOPE_MODIFIERS = List.of( + Modifier.PUBLIC, Modifier.PROTECTED, Modifier.PRIVATE); + private static final List SEALED_OR_NON_SEALED_MODIFIERS = List.of( + Modifier.SEALED, Modifier.NON_SEALED); + private final List annotations; + private final Set flags; + + public JTModifiers() { + this(null, null); + setActionChange(); + } + + JTModifiers(ModifiersTree modifiersTree, JTTree parentTree) { + super(modifiersTree, parentTree); + annotations = new ArrayList<>(); + flags = new HashSet<>(); + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitModifiers(this, data); + } + + @Override + JTModifiers analyze() { + super.analyze(); + JTTreeFactory.createAndAdd( + getOriginalTree().getAnnotations(), this, JTAnnotation::new, annotations::add); + flags.clear(); + flags.addAll(getOriginalTree().getFlags()); + return this; + } + + @Override + List> getAllNodes() { + var nodes = super.getAllNodes(); + annotations.stream().filter(Objects::nonNull).forEach(nodes::add); + nodes.forEach(node -> node.setParentTree(this)); + return nodes; + } + + @Override + public List getAnnotations() { + return annotations; + } + + @Override + public Set getFlags() { + return flags; + } + + @Override + public Kind getKind() { + return Kind.MODIFIERS; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_ANNOTATIONS, propertyName -> v8Runtime.toV8Value(getAnnotations())); + registerStringGetter(PROPERTY_FLAGS, propertyName -> v8Runtime.toV8Value(getFlags().stream() + .map(Modifier::toString) + .toList())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_ANNOTATIONS, (propertyName, propertyValue) -> replaceAnnotations(annotations, propertyValue)); + registerStringSetter(PROPERTY_FLAGS, (propertyName, propertyValue) -> setFlags(propertyValue)); + } + return stringSetterMap; + } + + @Override + public boolean serialize(IStyleWriter writer) { + if (isActionChange()) { + int annotationDepth = writer.getDepth() - 1; + ForEachUtils.forEach( + annotations.stream().filter(Objects::nonNull).filter(tree -> !tree.isActionIgnore()).toList(), + tree -> writer.appendIndent(annotationDepth).append(tree).appendLineSeparator()); + List modifiers = new ArrayList<>(); + SCOPE_MODIFIERS.stream().filter(flags::contains).findFirst().ifPresent(modifiers::add); + ABSTRACT_OR_DEFAULT_OR_STATIC_MODIFIERS.stream().filter(flags::contains).findFirst().ifPresent(modifiers::add); + SEALED_OR_NON_SEALED_MODIFIERS.stream().filter(flags::contains).findFirst().ifPresent(modifiers::add); + OTHER_MODIFIERS.stream().filter(flags::contains).forEach(modifiers::add); + ForEachUtils.forEach( + modifiers, + writer::append, + tree -> writer.appendSpace(), + trees -> writer.appendSpaceIfNeeded()); + return true; + } + return super.serialize(writer); + } + + private boolean setFlags(V8Value v8Value) throws JavetException { + if (v8Value instanceof V8ValueArray v8ValueArray) { + flags.clear(); + v8ValueArray.forEach(v8ValueItem -> { + if (v8ValueItem instanceof V8ValueString v8ValueString) { + try { + flags.add(Modifier.valueOf(v8ValueString.getValue())); + } catch (Throwable ignored) { + } + } + }); + return true; + } + return false; + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTModuleDecl.java b/src/main/java/com/caoccao/jaspiler/trees/JTModuleDecl.java index 573ae1b..98828fe 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTModuleDecl.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTModuleDecl.java @@ -1,146 +1,146 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.sun.source.tree.ModuleTree; -import com.sun.source.tree.TreeVisitor; - -import java.util.*; - -/** - * The type Module Declaration. - *

- * module a.b.c { - * exports a.b.c; - * opens a.b.c; - * requires x.y.z; - * } - */ -public final class JTModuleDecl - extends JTTree - implements ModuleTree, IJTAnnotatable { - private static final String PROPERTY_DIRECTIVES = "directives"; - private static final String PROPERTY_NAME = "name"; - private final List annotations; - private final List> directives; - private ModuleKind moduleType; - private JTExpression name; - - public JTModuleDecl() { - this(null, null); - setActionChange(); - } - - JTModuleDecl(ModuleTree moduleTree, JTTree parentTree) { - super(moduleTree, parentTree); - annotations = new ArrayList<>(); - directives = new ArrayList<>(); - moduleType = null; - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitModule(this, data); - } - - @Override - JTModuleDecl analyze() { - super.analyze(); - JTTreeFactory.createAndAdd( - getOriginalTree().getAnnotations(), this, JTAnnotation::new, annotations::add); - name = JTTreeFactory.create(getOriginalTree().getName(), this); - JTTreeFactory.createAndAdd( - getOriginalTree().getDirectives(), this, (JTDirective o) -> directives.add(o)); - return this; - } - - @Override - List> getAllNodes() { - var nodes = super.getAllNodes(); - annotations.stream().filter(Objects::nonNull).forEach(nodes::add); - Optional.ofNullable(name).ifPresent(nodes::add); - nodes.forEach(node -> node.setParentTree(this)); - return nodes; - } - - @Override - public List getAnnotations() { - return annotations; - } - - @Override - public List> getDirectives() { - return directives; - } - - @Override - public Kind getKind() { - return Kind.MODULE; - } - - @Override - public ModuleKind getModuleType() { - return moduleType; - } - - @Override - public JTExpression getName() { - return name; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_ANNOTATIONS, propertyName -> v8Runtime.toV8Value(getAnnotations())); - registerStringGetter(PROPERTY_DIRECTIVES, propertyName -> v8Runtime.toV8Value(getDirectives())); - registerStringGetter(PROPERTY_NAME, propertyName -> v8Runtime.toV8Value(getName())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_ANNOTATIONS, (propertyName, propertyValue) -> replaceAnnotations(annotations, propertyValue)); - registerStringSetter(PROPERTY_DIRECTIVES, (propertyName, propertyValue) -> replaceDirectives(directives, propertyValue)); - registerStringSetter(PROPERTY_NAME, (propertyName, propertyValue) -> replaceExpression(this::setName, propertyValue)); - } - return stringSetterMap; - } - - public JTModuleDecl setModuleType(ModuleKind moduleType) { - if (this.moduleType == moduleType) { - return this; - } - this.moduleType = Objects.requireNonNull(moduleType); - return setActionChange(); - } - - public JTModuleDecl setName(JTExpression name) { - if (this.name == name) { - return this; - } - this.name = Objects.requireNonNull(name).setParentTree(this); - return setActionChange(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.sun.source.tree.ModuleTree; +import com.sun.source.tree.TreeVisitor; + +import java.util.*; + +/** + * The type Module Declaration. + *

+ * module a.b.c { + * exports a.b.c; + * opens a.b.c; + * requires x.y.z; + * } + */ +public final class JTModuleDecl + extends JTTree + implements ModuleTree, IJTAnnotatable { + private static final String PROPERTY_DIRECTIVES = "directives"; + private static final String PROPERTY_NAME = "name"; + private final List annotations; + private final List> directives; + private ModuleKind moduleType; + private JTExpression name; + + public JTModuleDecl() { + this(null, null); + setActionChange(); + } + + JTModuleDecl(ModuleTree moduleTree, JTTree parentTree) { + super(moduleTree, parentTree); + annotations = new ArrayList<>(); + directives = new ArrayList<>(); + moduleType = null; + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitModule(this, data); + } + + @Override + JTModuleDecl analyze() { + super.analyze(); + JTTreeFactory.createAndAdd( + getOriginalTree().getAnnotations(), this, JTAnnotation::new, annotations::add); + name = JTTreeFactory.create(getOriginalTree().getName(), this); + JTTreeFactory.createAndAdd( + getOriginalTree().getDirectives(), this, (JTDirective o) -> directives.add(o)); + return this; + } + + @Override + List> getAllNodes() { + var nodes = super.getAllNodes(); + annotations.stream().filter(Objects::nonNull).forEach(nodes::add); + Optional.ofNullable(name).ifPresent(nodes::add); + nodes.forEach(node -> node.setParentTree(this)); + return nodes; + } + + @Override + public List getAnnotations() { + return annotations; + } + + @Override + public List> getDirectives() { + return directives; + } + + @Override + public Kind getKind() { + return Kind.MODULE; + } + + @Override + public ModuleKind getModuleType() { + return moduleType; + } + + @Override + public JTExpression getName() { + return name; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_ANNOTATIONS, propertyName -> v8Runtime.toV8Value(getAnnotations())); + registerStringGetter(PROPERTY_DIRECTIVES, propertyName -> v8Runtime.toV8Value(getDirectives())); + registerStringGetter(PROPERTY_NAME, propertyName -> v8Runtime.toV8Value(getName())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_ANNOTATIONS, (propertyName, propertyValue) -> replaceAnnotations(annotations, propertyValue)); + registerStringSetter(PROPERTY_DIRECTIVES, (propertyName, propertyValue) -> replaceDirectives(directives, propertyValue)); + registerStringSetter(PROPERTY_NAME, (propertyName, propertyValue) -> replaceExpression(this::setName, propertyValue)); + } + return stringSetterMap; + } + + public JTModuleDecl setModuleType(ModuleKind moduleType) { + if (this.moduleType == moduleType) { + return this; + } + this.moduleType = Objects.requireNonNull(moduleType); + return setActionChange(); + } + + public JTModuleDecl setName(JTExpression name) { + if (this.name == name) { + return this; + } + this.name = Objects.requireNonNull(name).setParentTree(this); + return setActionChange(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTName.java b/src/main/java/com/caoccao/jaspiler/trees/JTName.java index cfea1ee..3a48740 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTName.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTName.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTNewArray.java b/src/main/java/com/caoccao/jaspiler/trees/JTNewArray.java index 0a2eaa9..f3971d9 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTNewArray.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTNewArray.java @@ -1,173 +1,173 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.javet.exceptions.JavetException; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.sun.source.tree.NewArrayTree; -import com.sun.source.tree.TreeVisitor; - -import java.util.*; - -public final class JTNewArray - extends JTExpression - implements NewArrayTree, IJTAnnotatable { - private static final String PROPERTY_DIMENSIONS = "dimensions"; - private static final String PROPERTY_DIM_ANNOTATIONS = "dimAnnotations"; - private static final String PROPERTY_INITIALIZERS = "initializers"; - private static final String PROPERTY_TYPE = "type"; - private final List annotations; - private final List> dimAnnotations; - private final List> dimensions; - private final List> initializers; - private JTExpression type; - - public JTNewArray() { - this(null, null); - setActionChange(); - } - - JTNewArray(NewArrayTree newArrayTree, JTTree parentTree) { - super(newArrayTree, parentTree); - annotations = new ArrayList<>(); - dimAnnotations = new ArrayList<>(); - dimensions = new ArrayList<>(); - initializers = new ArrayList<>(); - type = null; - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitNewArray(this, data); - } - - @Override - JTNewArray analyze() { - super.analyze(); - type = JTTreeFactory.create(getOriginalTree().getType(), this); - JTTreeFactory.createAndAdd( - getOriginalTree().getDimensions(), this, (JTExpression o) -> dimensions.add(o)); - JTTreeFactory.createAndAdd( - getOriginalTree().getInitializers(), this, (JTExpression o) -> initializers.add(o)); - JTTreeFactory.createAndAdd( - getOriginalTree().getAnnotations(), this, JTAnnotation::new, annotations::add); - for (var originalDimAnnotation : getOriginalTree().getDimAnnotations()) { - List dimAnnotation = new ArrayList<>(); - dimAnnotations.add(dimAnnotation); - JTTreeFactory.createAndAdd( - originalDimAnnotation, this, JTAnnotation::new, dimAnnotation::add); - } - return this; - } - - @Override - List> getAllNodes() { - var nodes = super.getAllNodes(); - Optional.ofNullable(type).ifPresent(nodes::add); - dimensions.stream().filter(Objects::nonNull).forEach(nodes::add); - initializers.stream().filter(Objects::nonNull).forEach(nodes::add); - annotations.stream().filter(Objects::nonNull).forEach(nodes::add); - dimAnnotations.stream().filter(Objects::nonNull).flatMap(Collection::stream).forEach(nodes::add); - nodes.forEach(node -> node.setParentTree(this)); - return nodes; - } - - @Override - public List getAnnotations() { - return annotations; - } - - @Override - public List> getDimAnnotations() { - return dimAnnotations; - } - - @Override - public List> getDimensions() { - return dimensions; - } - - @Override - public List> getInitializers() { - return initializers; - } - - @Override - public Kind getKind() { - return Kind.NEW_ARRAY; - } - - @Override - public JTExpression getType() { - return type; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_ANNOTATIONS, propertyName -> v8Runtime.toV8Value(getAnnotations())); - registerStringGetter(PROPERTY_DIM_ANNOTATIONS, propertyName -> v8Runtime.toV8Value(getDimAnnotations())); - registerStringGetter(PROPERTY_DIMENSIONS, propertyName -> v8Runtime.toV8Value(getDimensions())); - registerStringGetter(PROPERTY_INITIALIZERS, propertyName -> v8Runtime.toV8Value(getInitializers())); - registerStringGetter(PROPERTY_TYPE, propertyName -> v8Runtime.toV8Value(getType())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_ANNOTATIONS, (propertyName, propertyValue) -> replaceAnnotations(annotations, propertyValue)); - registerStringSetter(PROPERTY_DIM_ANNOTATIONS, (propertyName, propertyValue) -> setDimAnnotations(propertyValue)); - registerStringSetter(PROPERTY_DIMENSIONS, (propertyName, propertyValue) -> replaceExpressions(dimensions, propertyValue)); - registerStringSetter(PROPERTY_INITIALIZERS, (propertyName, propertyValue) -> replaceExpressions(initializers, propertyValue)); - registerStringSetter(PROPERTY_TYPE, (propertyName, propertyValue) -> replaceExpression(this::setType, propertyValue)); - } - return stringSetterMap; - } - - private boolean setDimAnnotations(V8Value v8Value) throws JavetException { - if (v8Runtime.toObject(v8Value) instanceof List list) { - dimAnnotations.clear(); - list.stream() - .filter(item -> item instanceof List) - .map(item -> (List) item) - .map(trees -> trees.stream() - .filter(tree -> tree instanceof JTAnnotation) - .map(tree -> ((JTAnnotation) tree).setParentTree(this)) - .toList()) - .forEach(dimAnnotations::add); - setActionChange(); - return true; - } - return false; - - } - - public JTNewArray setType(JTExpression type) { - if (this.type == type) { - return this; - } - this.type = Objects.requireNonNull(type).setParentTree(this); - return setActionChange(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.javet.exceptions.JavetException; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.sun.source.tree.NewArrayTree; +import com.sun.source.tree.TreeVisitor; + +import java.util.*; + +public final class JTNewArray + extends JTExpression + implements NewArrayTree, IJTAnnotatable { + private static final String PROPERTY_DIMENSIONS = "dimensions"; + private static final String PROPERTY_DIM_ANNOTATIONS = "dimAnnotations"; + private static final String PROPERTY_INITIALIZERS = "initializers"; + private static final String PROPERTY_TYPE = "type"; + private final List annotations; + private final List> dimAnnotations; + private final List> dimensions; + private final List> initializers; + private JTExpression type; + + public JTNewArray() { + this(null, null); + setActionChange(); + } + + JTNewArray(NewArrayTree newArrayTree, JTTree parentTree) { + super(newArrayTree, parentTree); + annotations = new ArrayList<>(); + dimAnnotations = new ArrayList<>(); + dimensions = new ArrayList<>(); + initializers = new ArrayList<>(); + type = null; + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitNewArray(this, data); + } + + @Override + JTNewArray analyze() { + super.analyze(); + type = JTTreeFactory.create(getOriginalTree().getType(), this); + JTTreeFactory.createAndAdd( + getOriginalTree().getDimensions(), this, (JTExpression o) -> dimensions.add(o)); + JTTreeFactory.createAndAdd( + getOriginalTree().getInitializers(), this, (JTExpression o) -> initializers.add(o)); + JTTreeFactory.createAndAdd( + getOriginalTree().getAnnotations(), this, JTAnnotation::new, annotations::add); + for (var originalDimAnnotation : getOriginalTree().getDimAnnotations()) { + List dimAnnotation = new ArrayList<>(); + dimAnnotations.add(dimAnnotation); + JTTreeFactory.createAndAdd( + originalDimAnnotation, this, JTAnnotation::new, dimAnnotation::add); + } + return this; + } + + @Override + List> getAllNodes() { + var nodes = super.getAllNodes(); + Optional.ofNullable(type).ifPresent(nodes::add); + dimensions.stream().filter(Objects::nonNull).forEach(nodes::add); + initializers.stream().filter(Objects::nonNull).forEach(nodes::add); + annotations.stream().filter(Objects::nonNull).forEach(nodes::add); + dimAnnotations.stream().filter(Objects::nonNull).flatMap(Collection::stream).forEach(nodes::add); + nodes.forEach(node -> node.setParentTree(this)); + return nodes; + } + + @Override + public List getAnnotations() { + return annotations; + } + + @Override + public List> getDimAnnotations() { + return dimAnnotations; + } + + @Override + public List> getDimensions() { + return dimensions; + } + + @Override + public List> getInitializers() { + return initializers; + } + + @Override + public Kind getKind() { + return Kind.NEW_ARRAY; + } + + @Override + public JTExpression getType() { + return type; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_ANNOTATIONS, propertyName -> v8Runtime.toV8Value(getAnnotations())); + registerStringGetter(PROPERTY_DIM_ANNOTATIONS, propertyName -> v8Runtime.toV8Value(getDimAnnotations())); + registerStringGetter(PROPERTY_DIMENSIONS, propertyName -> v8Runtime.toV8Value(getDimensions())); + registerStringGetter(PROPERTY_INITIALIZERS, propertyName -> v8Runtime.toV8Value(getInitializers())); + registerStringGetter(PROPERTY_TYPE, propertyName -> v8Runtime.toV8Value(getType())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_ANNOTATIONS, (propertyName, propertyValue) -> replaceAnnotations(annotations, propertyValue)); + registerStringSetter(PROPERTY_DIM_ANNOTATIONS, (propertyName, propertyValue) -> setDimAnnotations(propertyValue)); + registerStringSetter(PROPERTY_DIMENSIONS, (propertyName, propertyValue) -> replaceExpressions(dimensions, propertyValue)); + registerStringSetter(PROPERTY_INITIALIZERS, (propertyName, propertyValue) -> replaceExpressions(initializers, propertyValue)); + registerStringSetter(PROPERTY_TYPE, (propertyName, propertyValue) -> replaceExpression(this::setType, propertyValue)); + } + return stringSetterMap; + } + + private boolean setDimAnnotations(V8Value v8Value) throws JavetException { + if (v8Runtime.toObject(v8Value) instanceof List list) { + dimAnnotations.clear(); + list.stream() + .filter(item -> item instanceof List) + .map(item -> (List) item) + .map(trees -> trees.stream() + .filter(tree -> tree instanceof JTAnnotation) + .map(tree -> ((JTAnnotation) tree).setParentTree(this)) + .toList()) + .forEach(dimAnnotations::add); + setActionChange(); + return true; + } + return false; + + } + + public JTNewArray setType(JTExpression type) { + if (this.type == type) { + return this; + } + this.type = Objects.requireNonNull(type).setParentTree(this); + return setActionChange(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTNewClass.java b/src/main/java/com/caoccao/jaspiler/trees/JTNewClass.java index df71ce5..e724a40 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTNewClass.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTNewClass.java @@ -1,165 +1,165 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.sun.source.tree.NewClassTree; -import com.sun.source.tree.TreeVisitor; - -import java.util.*; - -public final class JTNewClass - extends JTPolyExpression - implements NewClassTree { - private static final String PROPERTY_ARGUMENTS = "arguments"; - private static final String PROPERTY_CLASS_BODY = "classBody"; - private static final String PROPERTY_ENCLOSING_EXPRESSION = "enclosingExpression"; - private static final String PROPERTY_IDENTIFIER = "identifier"; - private static final String PROPERTY_TYPE_ARGUMENTS = "typeArguments"; - private final List> arguments; - private final List> typeArguments; - private JTClassDecl classBody; - private JTExpression enclosingExpression; - private JTExpression identifier; - - public JTNewClass() { - this(null, null); - setActionChange(); - } - - JTNewClass(NewClassTree newClassTree, JTTree parentTree) { - super(newClassTree, parentTree); - arguments = new ArrayList<>(); - classBody = null; - enclosingExpression = null; - identifier = null; - typeArguments = new ArrayList<>(); - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitNewClass(this, data); - } - - @Override - JTNewClass analyze() { - super.analyze(); - enclosingExpression = JTTreeFactory.create(getOriginalTree().getEnclosingExpression(), this); - identifier = JTTreeFactory.create(getOriginalTree().getIdentifier(), this); - JTTreeFactory.createAndAdd( - getOriginalTree().getTypeArguments(), this, (JTExpression o) -> typeArguments.add(o)); - JTTreeFactory.createAndAdd( - getOriginalTree().getArguments(), this, (JTExpression o) -> arguments.add(o)); - classBody = JTTreeFactory.create(getOriginalTree().getClassBody(), this, JTClassDecl::new); - return this; - } - - @Override - List> getAllNodes() { - var nodes = super.getAllNodes(); - Optional.ofNullable(enclosingExpression).ifPresent(nodes::add); - Optional.ofNullable(identifier).ifPresent(nodes::add); - typeArguments.stream().filter(Objects::nonNull).forEach(nodes::add); - arguments.stream().filter(Objects::nonNull).forEach(nodes::add); - Optional.ofNullable(classBody).ifPresent(nodes::add); - nodes.forEach(node -> node.setParentTree(this)); - return nodes; - } - - @Override - public List> getArguments() { - return arguments; - } - - @Override - public JTClassDecl getClassBody() { - return classBody; - } - - @Override - public JTExpression getEnclosingExpression() { - return enclosingExpression; - } - - @Override - public JTExpression getIdentifier() { - return identifier; - } - - @Override - public Kind getKind() { - return Kind.NEW_CLASS; - } - - @Override - public List> getTypeArguments() { - return typeArguments; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_ARGUMENTS, propertyName -> v8Runtime.toV8Value(getArguments())); - registerStringGetter(PROPERTY_CLASS_BODY, propertyName -> v8Runtime.toV8Value(getClassBody())); - registerStringGetter(PROPERTY_ENCLOSING_EXPRESSION, propertyName -> v8Runtime.toV8Value(getEnclosingExpression())); - registerStringGetter(PROPERTY_IDENTIFIER, propertyName -> v8Runtime.toV8Value(getIdentifier())); - registerStringGetter(PROPERTY_TYPE_ARGUMENTS, propertyName -> v8Runtime.toV8Value(getTypeArguments())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_ARGUMENTS, (propertyName, propertyValue) -> replaceExpressions(arguments, propertyValue)); - registerStringSetter(PROPERTY_CLASS_BODY, (propertyName, propertyValue) -> replaceClassDecl(this::setClassBody, propertyValue)); - registerStringSetter(PROPERTY_ENCLOSING_EXPRESSION, (propertyName, propertyValue) -> replaceExpression(this::setEnclosingExpression, propertyValue)); - registerStringSetter(PROPERTY_IDENTIFIER, (propertyName, propertyValue) -> replaceExpression(this::setIdentifier, propertyValue)); - registerStringSetter(PROPERTY_TYPE_ARGUMENTS, (propertyName, propertyValue) -> replaceExpressions(typeArguments, propertyValue)); - } - return stringSetterMap; - } - - public JTNewClass setClassBody(JTClassDecl classBody) { - if (this.classBody == classBody) { - return this; - } - this.classBody = Optional.ofNullable(classBody).map(o -> o.setParentTree(this)).orElse(null); - return setActionChange(); - } - - public JTNewClass setEnclosingExpression(JTExpression enclosingExpression) { - if (this.enclosingExpression == enclosingExpression) { - return this; - } - this.enclosingExpression = Optional.ofNullable(enclosingExpression).map(o -> o.setParentTree(this)).orElse(null); - return setActionChange(); - } - - public JTNewClass setIdentifier(JTExpression identifier) { - if (this.identifier == identifier) { - return this; - } - this.identifier = Objects.requireNonNull(identifier).setParentTree(this); - return setActionChange(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.sun.source.tree.NewClassTree; +import com.sun.source.tree.TreeVisitor; + +import java.util.*; + +public final class JTNewClass + extends JTPolyExpression + implements NewClassTree { + private static final String PROPERTY_ARGUMENTS = "arguments"; + private static final String PROPERTY_CLASS_BODY = "classBody"; + private static final String PROPERTY_ENCLOSING_EXPRESSION = "enclosingExpression"; + private static final String PROPERTY_IDENTIFIER = "identifier"; + private static final String PROPERTY_TYPE_ARGUMENTS = "typeArguments"; + private final List> arguments; + private final List> typeArguments; + private JTClassDecl classBody; + private JTExpression enclosingExpression; + private JTExpression identifier; + + public JTNewClass() { + this(null, null); + setActionChange(); + } + + JTNewClass(NewClassTree newClassTree, JTTree parentTree) { + super(newClassTree, parentTree); + arguments = new ArrayList<>(); + classBody = null; + enclosingExpression = null; + identifier = null; + typeArguments = new ArrayList<>(); + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitNewClass(this, data); + } + + @Override + JTNewClass analyze() { + super.analyze(); + enclosingExpression = JTTreeFactory.create(getOriginalTree().getEnclosingExpression(), this); + identifier = JTTreeFactory.create(getOriginalTree().getIdentifier(), this); + JTTreeFactory.createAndAdd( + getOriginalTree().getTypeArguments(), this, (JTExpression o) -> typeArguments.add(o)); + JTTreeFactory.createAndAdd( + getOriginalTree().getArguments(), this, (JTExpression o) -> arguments.add(o)); + classBody = JTTreeFactory.create(getOriginalTree().getClassBody(), this, JTClassDecl::new); + return this; + } + + @Override + List> getAllNodes() { + var nodes = super.getAllNodes(); + Optional.ofNullable(enclosingExpression).ifPresent(nodes::add); + Optional.ofNullable(identifier).ifPresent(nodes::add); + typeArguments.stream().filter(Objects::nonNull).forEach(nodes::add); + arguments.stream().filter(Objects::nonNull).forEach(nodes::add); + Optional.ofNullable(classBody).ifPresent(nodes::add); + nodes.forEach(node -> node.setParentTree(this)); + return nodes; + } + + @Override + public List> getArguments() { + return arguments; + } + + @Override + public JTClassDecl getClassBody() { + return classBody; + } + + @Override + public JTExpression getEnclosingExpression() { + return enclosingExpression; + } + + @Override + public JTExpression getIdentifier() { + return identifier; + } + + @Override + public Kind getKind() { + return Kind.NEW_CLASS; + } + + @Override + public List> getTypeArguments() { + return typeArguments; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_ARGUMENTS, propertyName -> v8Runtime.toV8Value(getArguments())); + registerStringGetter(PROPERTY_CLASS_BODY, propertyName -> v8Runtime.toV8Value(getClassBody())); + registerStringGetter(PROPERTY_ENCLOSING_EXPRESSION, propertyName -> v8Runtime.toV8Value(getEnclosingExpression())); + registerStringGetter(PROPERTY_IDENTIFIER, propertyName -> v8Runtime.toV8Value(getIdentifier())); + registerStringGetter(PROPERTY_TYPE_ARGUMENTS, propertyName -> v8Runtime.toV8Value(getTypeArguments())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_ARGUMENTS, (propertyName, propertyValue) -> replaceExpressions(arguments, propertyValue)); + registerStringSetter(PROPERTY_CLASS_BODY, (propertyName, propertyValue) -> replaceClassDecl(this::setClassBody, propertyValue)); + registerStringSetter(PROPERTY_ENCLOSING_EXPRESSION, (propertyName, propertyValue) -> replaceExpression(this::setEnclosingExpression, propertyValue)); + registerStringSetter(PROPERTY_IDENTIFIER, (propertyName, propertyValue) -> replaceExpression(this::setIdentifier, propertyValue)); + registerStringSetter(PROPERTY_TYPE_ARGUMENTS, (propertyName, propertyValue) -> replaceExpressions(typeArguments, propertyValue)); + } + return stringSetterMap; + } + + public JTNewClass setClassBody(JTClassDecl classBody) { + if (this.classBody == classBody) { + return this; + } + this.classBody = Optional.ofNullable(classBody).map(o -> o.setParentTree(this)).orElse(null); + return setActionChange(); + } + + public JTNewClass setEnclosingExpression(JTExpression enclosingExpression) { + if (this.enclosingExpression == enclosingExpression) { + return this; + } + this.enclosingExpression = Optional.ofNullable(enclosingExpression).map(o -> o.setParentTree(this)).orElse(null); + return setActionChange(); + } + + public JTNewClass setIdentifier(JTExpression identifier) { + if (this.identifier == identifier) { + return this; + } + this.identifier = Objects.requireNonNull(identifier).setParentTree(this); + return setActionChange(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTOpens.java b/src/main/java/com/caoccao/jaspiler/trees/JTOpens.java index c1850df..cb30500 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTOpens.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTOpens.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTOperatorExpression.java b/src/main/java/com/caoccao/jaspiler/trees/JTOperatorExpression.java index 88b1243..411057e 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTOperatorExpression.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTOperatorExpression.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTPackageDecl.java b/src/main/java/com/caoccao/jaspiler/trees/JTPackageDecl.java index c4f0963..c58322d 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTPackageDecl.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTPackageDecl.java @@ -1,134 +1,134 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.enums.JavaKeyword; -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.jaspiler.styles.IStyleWriter; -import com.caoccao.jaspiler.utils.ForEachUtils; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.sun.source.tree.PackageTree; -import com.sun.source.tree.TreeVisitor; - -import java.util.*; - -/** - * The type Jt package tree. - * It references com.sun.tools.javac.tree.JCTree.JCPackageDecl. - */ -public final class JTPackageDecl - extends JTTree - implements PackageTree, IJTAnnotatable { - private static final String PROPERTY_PACKAGE_NAME = "packageName"; - private final List annotations; - private JTExpression packageName; - - public JTPackageDecl() { - this(null, null); - setActionChange(); - } - - JTPackageDecl(PackageTree originalTree, JTTree parentTree) { - super(originalTree, parentTree); - annotations = new ArrayList<>(); - packageName = null; - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitPackage(this, data); - } - - @Override - JTPackageDecl analyze() { - super.analyze(); - packageName = JTTreeFactory.create(getOriginalTree().getPackageName(), this); - JTTreeFactory.createAndAdd( - getOriginalTree().getAnnotations(), this, JTAnnotation::new, annotations::add); - return this; - } - - @Override - List> getAllNodes() { - var nodes = super.getAllNodes(); - annotations.stream().filter(Objects::nonNull).forEach(nodes::add); - Optional.ofNullable(packageName).ifPresent(nodes::add); - nodes.forEach(node -> node.setParentTree(this)); - return nodes; - } - - @Override - public List getAnnotations() { - return annotations; - } - - @Override - public Kind getKind() { - return Kind.PACKAGE; - } - - @Override - public JTExpression getPackageName() { - return packageName; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_ANNOTATIONS, propertyName -> v8Runtime.toV8Value(getAnnotations())); - registerStringGetter(PROPERTY_PACKAGE_NAME, propertyName -> v8Runtime.toV8Value(getPackageName())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_ANNOTATIONS, (propertyName, propertyValue) -> replaceAnnotations(annotations, propertyValue)); - registerStringSetter(PROPERTY_PACKAGE_NAME, (propertyName, propertyValue) -> replaceExpression(this::setPackageName, propertyValue)); - } - return stringSetterMap; - } - - @Override - public boolean serialize(IStyleWriter writer) { - if (isActionChange()) { - ForEachUtils.forEach( - annotations.stream().filter(Objects::nonNull).filter(tree -> !tree.isActionIgnore()).toList(), - writer::append, - tree -> writer.appendLineSeparator(), - null, - trees -> writer.appendLineSeparator()); - Optional.ofNullable(packageName) - .ifPresent(tree -> writer.appendKeyword(JavaKeyword.PACKAGE).appendSpace().append(tree).appendSemiColon()); - return true; - } - return super.serialize(writer); - } - - public JTPackageDecl setPackageName(JTExpression packageName) { - if (this.packageName == packageName) { - return this; - } - this.packageName = Objects.requireNonNull(packageName).setParentTree(this); - return setActionChange(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.enums.JavaKeyword; +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.jaspiler.styles.IStyleWriter; +import com.caoccao.jaspiler.utils.ForEachUtils; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.sun.source.tree.PackageTree; +import com.sun.source.tree.TreeVisitor; + +import java.util.*; + +/** + * The type Jt package tree. + * It references com.sun.tools.javac.tree.JCTree.JCPackageDecl. + */ +public final class JTPackageDecl + extends JTTree + implements PackageTree, IJTAnnotatable { + private static final String PROPERTY_PACKAGE_NAME = "packageName"; + private final List annotations; + private JTExpression packageName; + + public JTPackageDecl() { + this(null, null); + setActionChange(); + } + + JTPackageDecl(PackageTree originalTree, JTTree parentTree) { + super(originalTree, parentTree); + annotations = new ArrayList<>(); + packageName = null; + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitPackage(this, data); + } + + @Override + JTPackageDecl analyze() { + super.analyze(); + packageName = JTTreeFactory.create(getOriginalTree().getPackageName(), this); + JTTreeFactory.createAndAdd( + getOriginalTree().getAnnotations(), this, JTAnnotation::new, annotations::add); + return this; + } + + @Override + List> getAllNodes() { + var nodes = super.getAllNodes(); + annotations.stream().filter(Objects::nonNull).forEach(nodes::add); + Optional.ofNullable(packageName).ifPresent(nodes::add); + nodes.forEach(node -> node.setParentTree(this)); + return nodes; + } + + @Override + public List getAnnotations() { + return annotations; + } + + @Override + public Kind getKind() { + return Kind.PACKAGE; + } + + @Override + public JTExpression getPackageName() { + return packageName; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_ANNOTATIONS, propertyName -> v8Runtime.toV8Value(getAnnotations())); + registerStringGetter(PROPERTY_PACKAGE_NAME, propertyName -> v8Runtime.toV8Value(getPackageName())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_ANNOTATIONS, (propertyName, propertyValue) -> replaceAnnotations(annotations, propertyValue)); + registerStringSetter(PROPERTY_PACKAGE_NAME, (propertyName, propertyValue) -> replaceExpression(this::setPackageName, propertyValue)); + } + return stringSetterMap; + } + + @Override + public boolean serialize(IStyleWriter writer) { + if (isActionChange()) { + ForEachUtils.forEach( + annotations.stream().filter(Objects::nonNull).filter(tree -> !tree.isActionIgnore()).toList(), + writer::append, + tree -> writer.appendLineSeparator(), + null, + trees -> writer.appendLineSeparator()); + Optional.ofNullable(packageName) + .ifPresent(tree -> writer.appendKeyword(JavaKeyword.PACKAGE).appendSpace().append(tree).appendSemiColon()); + return true; + } + return super.serialize(writer); + } + + public JTPackageDecl setPackageName(JTExpression packageName) { + if (this.packageName == packageName) { + return this; + } + this.packageName = Objects.requireNonNull(packageName).setParentTree(this); + return setActionChange(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTParens.java b/src/main/java/com/caoccao/jaspiler/trees/JTParens.java index 33e1d6a..0f50404 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTParens.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTParens.java @@ -1,102 +1,102 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.sun.source.tree.ParenthesizedTree; -import com.sun.source.tree.TreeVisitor; - -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -public final class JTParens - extends JTExpression - implements ParenthesizedTree { - private static final String PROPERTY_EXPRESSION = "expression"; - private JTExpression expression; - - public JTParens() { - this(null, null); - setActionChange(); - } - - JTParens(ParenthesizedTree parenthesizedTree, JTTree parentTree) { - super(parenthesizedTree, parentTree); - expression = null; - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitParenthesized(this, data); - } - - @Override - JTParens analyze() { - super.analyze(); - expression = JTTreeFactory.create(getOriginalTree().getExpression(), this); - return this; - } - - @Override - List> getAllNodes() { - var nodes = super.getAllNodes(); - Optional.ofNullable(expression).ifPresent(nodes::add); - nodes.forEach(node -> node.setParentTree(this)); - return nodes; - } - - @Override - public JTExpression getExpression() { - return expression; - } - - @Override - public Kind getKind() { - return Kind.PARENTHESIZED; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_EXPRESSION, propertyName -> v8Runtime.toV8Value(getExpression())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_EXPRESSION, (propertyName, propertyValue) -> replaceExpression(this::setExpression, propertyValue)); - } - return stringSetterMap; - } - - public JTParens setExpression(JTExpression expression) { - if (this.expression == expression) { - return this; - } - this.expression = Objects.requireNonNull(expression).setParentTree(this); - return setActionChange(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.sun.source.tree.ParenthesizedTree; +import com.sun.source.tree.TreeVisitor; + +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +public final class JTParens + extends JTExpression + implements ParenthesizedTree { + private static final String PROPERTY_EXPRESSION = "expression"; + private JTExpression expression; + + public JTParens() { + this(null, null); + setActionChange(); + } + + JTParens(ParenthesizedTree parenthesizedTree, JTTree parentTree) { + super(parenthesizedTree, parentTree); + expression = null; + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitParenthesized(this, data); + } + + @Override + JTParens analyze() { + super.analyze(); + expression = JTTreeFactory.create(getOriginalTree().getExpression(), this); + return this; + } + + @Override + List> getAllNodes() { + var nodes = super.getAllNodes(); + Optional.ofNullable(expression).ifPresent(nodes::add); + nodes.forEach(node -> node.setParentTree(this)); + return nodes; + } + + @Override + public JTExpression getExpression() { + return expression; + } + + @Override + public Kind getKind() { + return Kind.PARENTHESIZED; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_EXPRESSION, propertyName -> v8Runtime.toV8Value(getExpression())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_EXPRESSION, (propertyName, propertyValue) -> replaceExpression(this::setExpression, propertyValue)); + } + return stringSetterMap; + } + + public JTParens setExpression(JTExpression expression) { + if (this.expression == expression) { + return this; + } + this.expression = Objects.requireNonNull(expression).setParentTree(this); + return setActionChange(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTParenthesizedPattern.java b/src/main/java/com/caoccao/jaspiler/trees/JTParenthesizedPattern.java index b503275..226aea1 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTParenthesizedPattern.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTParenthesizedPattern.java @@ -1,103 +1,103 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.sun.source.tree.ParenthesizedPatternTree; -import com.sun.source.tree.TreeVisitor; - -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -@SuppressWarnings("preview") -public final class JTParenthesizedPattern - extends JTPattern - implements ParenthesizedPatternTree { - private static final String PROPERTY_PATTERN = "pattern"; - private JTPattern pattern; - - public JTParenthesizedPattern() { - this(null, null); - setActionChange(); - } - - JTParenthesizedPattern(ParenthesizedPatternTree parenthesizedPatternTree, JTTree parentTree) { - super(parenthesizedPatternTree, parentTree); - pattern = null; - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitParenthesizedPattern(this, data); - } - - @Override - JTParenthesizedPattern analyze() { - super.analyze(); - pattern = JTTreeFactory.create(getOriginalTree().getPattern(), this); - return this; - } - - @Override - List> getAllNodes() { - var nodes = super.getAllNodes(); - Optional.ofNullable(pattern).ifPresent(nodes::add); - nodes.forEach(node -> node.setParentTree(this)); - return nodes; - } - - @Override - public Kind getKind() { - return Kind.PARENTHESIZED_PATTERN; - } - - @Override - public JTPattern getPattern() { - return pattern; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_PATTERN, propertyName -> v8Runtime.toV8Value(getPattern())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_PATTERN, (propertyName, propertyValue) -> replacePattern(this::setPattern, propertyValue)); - } - return stringSetterMap; - } - - public JTParenthesizedPattern setPattern(JTPattern pattern) { - if (this.pattern == pattern) { - return this; - } - this.pattern = Objects.requireNonNull(pattern).setParentTree(this); - return setActionChange(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.sun.source.tree.ParenthesizedPatternTree; +import com.sun.source.tree.TreeVisitor; + +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@SuppressWarnings("preview") +public final class JTParenthesizedPattern + extends JTPattern + implements ParenthesizedPatternTree { + private static final String PROPERTY_PATTERN = "pattern"; + private JTPattern pattern; + + public JTParenthesizedPattern() { + this(null, null); + setActionChange(); + } + + JTParenthesizedPattern(ParenthesizedPatternTree parenthesizedPatternTree, JTTree parentTree) { + super(parenthesizedPatternTree, parentTree); + pattern = null; + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitParenthesizedPattern(this, data); + } + + @Override + JTParenthesizedPattern analyze() { + super.analyze(); + pattern = JTTreeFactory.create(getOriginalTree().getPattern(), this); + return this; + } + + @Override + List> getAllNodes() { + var nodes = super.getAllNodes(); + Optional.ofNullable(pattern).ifPresent(nodes::add); + nodes.forEach(node -> node.setParentTree(this)); + return nodes; + } + + @Override + public Kind getKind() { + return Kind.PARENTHESIZED_PATTERN; + } + + @Override + public JTPattern getPattern() { + return pattern; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_PATTERN, propertyName -> v8Runtime.toV8Value(getPattern())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_PATTERN, (propertyName, propertyValue) -> replacePattern(this::setPattern, propertyValue)); + } + return stringSetterMap; + } + + public JTParenthesizedPattern setPattern(JTPattern pattern) { + if (this.pattern == pattern) { + return this; + } + this.pattern = Objects.requireNonNull(pattern).setParentTree(this); + return setActionChange(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTPattern.java b/src/main/java/com/caoccao/jaspiler/trees/JTPattern.java index 2043aaa..d32531b 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTPattern.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTPattern.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTPolyExpression.java b/src/main/java/com/caoccao/jaspiler/trees/JTPolyExpression.java index bd1ea84..b680ac2 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTPolyExpression.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTPolyExpression.java @@ -1,52 +1,52 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.sun.source.tree.Tree; - -import java.util.Objects; - -@SuppressWarnings("unchecked") -public abstract class JTPolyExpression< - OriginalTree extends Tree, - NewTree extends JTExpression> - extends JTExpression { - protected JTPolyKind polyKind; - - JTPolyExpression(OriginalTree originalTree, JTTree parentTree) { - super(originalTree, parentTree); - polyKind = JTPolyKind.STANDALONE; - } - - @Override - public boolean isPoly() { - return polyKind == JTPolyKind.POLY; - } - - @Override - public boolean isStandalone() { - return polyKind == JTPolyKind.STANDALONE; - } - - public NewTree setPolyKind(JTPolyKind polyKind) { - if (this.polyKind == polyKind) { - return (NewTree) this; - } - this.polyKind = Objects.requireNonNull(polyKind); - return setActionChange(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.sun.source.tree.Tree; + +import java.util.Objects; + +@SuppressWarnings("unchecked") +public abstract class JTPolyExpression< + OriginalTree extends Tree, + NewTree extends JTExpression> + extends JTExpression { + protected JTPolyKind polyKind; + + JTPolyExpression(OriginalTree originalTree, JTTree parentTree) { + super(originalTree, parentTree); + polyKind = JTPolyKind.STANDALONE; + } + + @Override + public boolean isPoly() { + return polyKind == JTPolyKind.POLY; + } + + @Override + public boolean isStandalone() { + return polyKind == JTPolyKind.STANDALONE; + } + + public NewTree setPolyKind(JTPolyKind polyKind) { + if (this.polyKind == polyKind) { + return (NewTree) this; + } + this.polyKind = Objects.requireNonNull(polyKind); + return setActionChange(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTPolyKind.java b/src/main/java/com/caoccao/jaspiler/trees/JTPolyKind.java index a413a80..db7ed27 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTPolyKind.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTPolyKind.java @@ -1,28 +1,28 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -public enum JTPolyKind { - /** - * true poly expression - */ - POLY, - /** - * poly expression to be treated as a standalone expression - */ - STANDALONE, -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +public enum JTPolyKind { + /** + * true poly expression + */ + POLY, + /** + * poly expression to be treated as a standalone expression + */ + STANDALONE, +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTPosition.java b/src/main/java/com/caoccao/jaspiler/trees/JTPosition.java index 33e8499..caed12b 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTPosition.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTPosition.java @@ -1,82 +1,82 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.styles.StandardStyleWriter; -import com.sun.source.doctree.DocCommentTree; -import com.sun.source.doctree.DocTree; -import com.sun.source.tree.CompilationUnitTree; -import com.sun.source.tree.Tree; -import com.sun.source.util.DocSourcePositions; -import com.sun.source.util.SourcePositions; - -public record JTPosition( - long startPosition, - long endPosition, - long lineNumber, - long columnNumber) { - public static final JTPosition Invalid = new JTPosition(-1, -1, -1, -1); - - public static JTPosition from( - DocSourcePositions docSourcePositions, - CompilationUnitTree compilationUnitTree, - DocCommentTree docCommentTree, - DocTree docTree) { - long startPosition = docSourcePositions.getStartPosition(compilationUnitTree, docCommentTree, docTree); - long endPosition = docSourcePositions.getEndPosition(compilationUnitTree, docCommentTree, docTree); - long lineNumber = -1; - long columnNumber = -1; - if (startPosition >= 0) { - lineNumber = compilationUnitTree.getLineMap().getLineNumber(startPosition); - columnNumber = compilationUnitTree.getLineMap().getColumnNumber(startPosition); - } - return new JTPosition(startPosition, endPosition, lineNumber, columnNumber); - } - - public static JTPosition from( - SourcePositions sourcePositions, - CompilationUnitTree compilationUnitTree, - Tree tree) { - long startPosition = sourcePositions.getStartPosition(compilationUnitTree, tree); - long endPosition = sourcePositions.getEndPosition(compilationUnitTree, tree); - long lineNumber = -1; - long columnNumber = -1; - if (startPosition >= 0) { - lineNumber = compilationUnitTree.getLineMap().getLineNumber(startPosition); - columnNumber = compilationUnitTree.getLineMap().getColumnNumber(startPosition); - } - return new JTPosition(startPosition, endPosition, lineNumber, columnNumber); - } - - public boolean isValid() { - return !(startPosition < 0 || endPosition < 0 || lineNumber < 0 || columnNumber < 0); - } - - public long length() { - return endPosition - startPosition; - } - - @Override - public String toString() { - final var stringBuilder = new StringBuilder(); - stringBuilder.append("S: ").append(startPosition).append(", "); - stringBuilder.append("E: ").append(endPosition).append(", "); - stringBuilder.append("L: ").append(lineNumber).append(", "); - stringBuilder.append("C: ").append(columnNumber); - return stringBuilder.toString(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.styles.StandardStyleWriter; +import com.sun.source.doctree.DocCommentTree; +import com.sun.source.doctree.DocTree; +import com.sun.source.tree.CompilationUnitTree; +import com.sun.source.tree.Tree; +import com.sun.source.util.DocSourcePositions; +import com.sun.source.util.SourcePositions; + +public record JTPosition( + long startPosition, + long endPosition, + long lineNumber, + long columnNumber) { + public static final JTPosition Invalid = new JTPosition(-1, -1, -1, -1); + + public static JTPosition from( + DocSourcePositions docSourcePositions, + CompilationUnitTree compilationUnitTree, + DocCommentTree docCommentTree, + DocTree docTree) { + long startPosition = docSourcePositions.getStartPosition(compilationUnitTree, docCommentTree, docTree); + long endPosition = docSourcePositions.getEndPosition(compilationUnitTree, docCommentTree, docTree); + long lineNumber = -1; + long columnNumber = -1; + if (startPosition >= 0) { + lineNumber = compilationUnitTree.getLineMap().getLineNumber(startPosition); + columnNumber = compilationUnitTree.getLineMap().getColumnNumber(startPosition); + } + return new JTPosition(startPosition, endPosition, lineNumber, columnNumber); + } + + public static JTPosition from( + SourcePositions sourcePositions, + CompilationUnitTree compilationUnitTree, + Tree tree) { + long startPosition = sourcePositions.getStartPosition(compilationUnitTree, tree); + long endPosition = sourcePositions.getEndPosition(compilationUnitTree, tree); + long lineNumber = -1; + long columnNumber = -1; + if (startPosition >= 0) { + lineNumber = compilationUnitTree.getLineMap().getLineNumber(startPosition); + columnNumber = compilationUnitTree.getLineMap().getColumnNumber(startPosition); + } + return new JTPosition(startPosition, endPosition, lineNumber, columnNumber); + } + + public boolean isValid() { + return !(startPosition < 0 || endPosition < 0 || lineNumber < 0 || columnNumber < 0); + } + + public long length() { + return endPosition - startPosition; + } + + @Override + public String toString() { + final var stringBuilder = new StringBuilder(); + stringBuilder.append("S: ").append(startPosition).append(", "); + stringBuilder.append("E: ").append(endPosition).append(", "); + stringBuilder.append("L: ").append(lineNumber).append(", "); + stringBuilder.append("C: ").append(columnNumber); + return stringBuilder.toString(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTPrimitiveType.java b/src/main/java/com/caoccao/jaspiler/trees/JTPrimitiveType.java index 92b56d0..b50717d 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTPrimitiveType.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTPrimitiveType.java @@ -1,108 +1,108 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.jaspiler.exceptions.JaspilerNotSupportedException; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.caoccao.javet.values.primitive.V8ValueString; -import com.sun.source.tree.PrimitiveTypeTree; -import com.sun.source.tree.TreeVisitor; - -import javax.lang.model.type.TypeKind; -import java.util.Map; -import java.util.Objects; - -public final class JTPrimitiveType - extends JTExpression - implements PrimitiveTypeTree { - private static final String PROPERTY_PRIMITIVE_TYPE_KIND = "primitiveTypeKind"; - private TypeKind primitiveTypeKind; - - public JTPrimitiveType() { - this(null, null); - setActionChange(); - } - - JTPrimitiveType(PrimitiveTypeTree primitiveTypeTree, JTTree parentTree) { - super(primitiveTypeTree, parentTree); - primitiveTypeKind = null; - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitPrimitiveType(this, data); - } - - @Override - JTPrimitiveType analyze() { - super.analyze(); - primitiveTypeKind = getOriginalTree().getPrimitiveTypeKind(); - return this; - } - - @Override - public Kind getKind() { - return Kind.PRIMITIVE_TYPE; - } - - @Override - public TypeKind getPrimitiveTypeKind() { - return primitiveTypeKind; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_PRIMITIVE_TYPE_KIND, propertyName -> v8Runtime.createV8ValueString(getPrimitiveTypeKind().name())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_PRIMITIVE_TYPE_KIND, (propertyName, propertyValue) -> setPrimitiveTypeKind(propertyValue)); - } - return stringSetterMap; - } - - private boolean setPrimitiveTypeKind(V8Value v8Value) { - if (v8Value instanceof V8ValueString v8ValueString) { - setPrimitiveTypeKind(TypeKind.valueOf(v8ValueString.getValue())); - return true; - } - return false; - } - - public JTPrimitiveType setPrimitiveTypeKind(TypeKind primitiveTypeKind) { - if (this.primitiveTypeKind == primitiveTypeKind) { - return this; - } - switch (Objects.requireNonNull(primitiveTypeKind)) { - case BOOLEAN, BYTE, SHORT, INT, LONG, CHAR, FLOAT, DOUBLE, VOID -> { - this.primitiveTypeKind = primitiveTypeKind; - return setActionChange(); - } - default -> throw new JaspilerNotSupportedException(primitiveTypeKind.name() + " is not supported."); - } - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.jaspiler.exceptions.JaspilerNotSupportedException; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.caoccao.javet.values.primitive.V8ValueString; +import com.sun.source.tree.PrimitiveTypeTree; +import com.sun.source.tree.TreeVisitor; + +import javax.lang.model.type.TypeKind; +import java.util.Map; +import java.util.Objects; + +public final class JTPrimitiveType + extends JTExpression + implements PrimitiveTypeTree { + private static final String PROPERTY_PRIMITIVE_TYPE_KIND = "primitiveTypeKind"; + private TypeKind primitiveTypeKind; + + public JTPrimitiveType() { + this(null, null); + setActionChange(); + } + + JTPrimitiveType(PrimitiveTypeTree primitiveTypeTree, JTTree parentTree) { + super(primitiveTypeTree, parentTree); + primitiveTypeKind = null; + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitPrimitiveType(this, data); + } + + @Override + JTPrimitiveType analyze() { + super.analyze(); + primitiveTypeKind = getOriginalTree().getPrimitiveTypeKind(); + return this; + } + + @Override + public Kind getKind() { + return Kind.PRIMITIVE_TYPE; + } + + @Override + public TypeKind getPrimitiveTypeKind() { + return primitiveTypeKind; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_PRIMITIVE_TYPE_KIND, propertyName -> v8Runtime.createV8ValueString(getPrimitiveTypeKind().name())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_PRIMITIVE_TYPE_KIND, (propertyName, propertyValue) -> setPrimitiveTypeKind(propertyValue)); + } + return stringSetterMap; + } + + private boolean setPrimitiveTypeKind(V8Value v8Value) { + if (v8Value instanceof V8ValueString v8ValueString) { + setPrimitiveTypeKind(TypeKind.valueOf(v8ValueString.getValue())); + return true; + } + return false; + } + + public JTPrimitiveType setPrimitiveTypeKind(TypeKind primitiveTypeKind) { + if (this.primitiveTypeKind == primitiveTypeKind) { + return this; + } + switch (Objects.requireNonNull(primitiveTypeKind)) { + case BOOLEAN, BYTE, SHORT, INT, LONG, CHAR, FLOAT, DOUBLE, VOID -> { + this.primitiveTypeKind = primitiveTypeKind; + return setActionChange(); + } + default -> throw new JaspilerNotSupportedException(primitiveTypeKind.name() + " is not supported."); + } + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTProvides.java b/src/main/java/com/caoccao/jaspiler/trees/JTProvides.java index 1751727..129f2e9 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTProvides.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTProvides.java @@ -1,112 +1,112 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.sun.source.tree.ProvidesTree; -import com.sun.source.tree.TreeVisitor; - -import java.util.*; - -public final class JTProvides - extends JTDirective - implements ProvidesTree { - private static final String PROPERTY_IMPLEMENTATION_NAMES = "implementationNames"; - private static final String PROPERTY_SERVICE_NAME = "serviceName"; - private final List> implementationNames; - private JTExpression serviceName; - - public JTProvides() { - this(null, null); - setActionChange(); - } - - JTProvides(ProvidesTree providesTree, JTTree parentTree) { - super(providesTree, parentTree); - implementationNames = new ArrayList<>(); - serviceName = null; - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitProvides(this, data); - } - - @Override - JTProvides analyze() { - super.analyze(); - serviceName = JTTreeFactory.create(getOriginalTree().getServiceName(), this); - JTTreeFactory.createAndAdd( - getOriginalTree().getImplementationNames(), this, (JTExpression o) -> implementationNames.add(o)); - return this; - } - - @Override - List> getAllNodes() { - var nodes = super.getAllNodes(); - Optional.ofNullable(serviceName).ifPresent(nodes::add); - implementationNames.stream().filter(Objects::nonNull).forEach(nodes::add); - nodes.forEach(node -> node.setParentTree(this)); - return nodes; - } - - @Override - public List> getImplementationNames() { - return implementationNames; - } - - @Override - public Kind getKind() { - return Kind.PROVIDES; - } - - @Override - public JTExpression getServiceName() { - return serviceName; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_IMPLEMENTATION_NAMES, propertyName -> v8Runtime.toV8Value(getImplementationNames())); - registerStringGetter(PROPERTY_SERVICE_NAME, propertyName -> v8Runtime.toV8Value(getServiceName())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_IMPLEMENTATION_NAMES, (propertyName, propertyValue) -> replaceExpressions(implementationNames, propertyValue)); - registerStringSetter(PROPERTY_SERVICE_NAME, (propertyName, propertyValue) -> replaceExpression(this::setServiceName, propertyValue)); - } - return stringSetterMap; - } - - public JTProvides setServiceName(JTExpression serviceName) { - if (this.serviceName == serviceName) { - return this; - } - this.serviceName = Objects.requireNonNull(serviceName).setParentTree(this); - return setActionChange(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.sun.source.tree.ProvidesTree; +import com.sun.source.tree.TreeVisitor; + +import java.util.*; + +public final class JTProvides + extends JTDirective + implements ProvidesTree { + private static final String PROPERTY_IMPLEMENTATION_NAMES = "implementationNames"; + private static final String PROPERTY_SERVICE_NAME = "serviceName"; + private final List> implementationNames; + private JTExpression serviceName; + + public JTProvides() { + this(null, null); + setActionChange(); + } + + JTProvides(ProvidesTree providesTree, JTTree parentTree) { + super(providesTree, parentTree); + implementationNames = new ArrayList<>(); + serviceName = null; + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitProvides(this, data); + } + + @Override + JTProvides analyze() { + super.analyze(); + serviceName = JTTreeFactory.create(getOriginalTree().getServiceName(), this); + JTTreeFactory.createAndAdd( + getOriginalTree().getImplementationNames(), this, (JTExpression o) -> implementationNames.add(o)); + return this; + } + + @Override + List> getAllNodes() { + var nodes = super.getAllNodes(); + Optional.ofNullable(serviceName).ifPresent(nodes::add); + implementationNames.stream().filter(Objects::nonNull).forEach(nodes::add); + nodes.forEach(node -> node.setParentTree(this)); + return nodes; + } + + @Override + public List> getImplementationNames() { + return implementationNames; + } + + @Override + public Kind getKind() { + return Kind.PROVIDES; + } + + @Override + public JTExpression getServiceName() { + return serviceName; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_IMPLEMENTATION_NAMES, propertyName -> v8Runtime.toV8Value(getImplementationNames())); + registerStringGetter(PROPERTY_SERVICE_NAME, propertyName -> v8Runtime.toV8Value(getServiceName())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_IMPLEMENTATION_NAMES, (propertyName, propertyValue) -> replaceExpressions(implementationNames, propertyValue)); + registerStringSetter(PROPERTY_SERVICE_NAME, (propertyName, propertyValue) -> replaceExpression(this::setServiceName, propertyValue)); + } + return stringSetterMap; + } + + public JTProvides setServiceName(JTExpression serviceName) { + if (this.serviceName == serviceName) { + return this; + } + this.serviceName = Objects.requireNonNull(serviceName).setParentTree(this); + return setActionChange(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTRequires.java b/src/main/java/com/caoccao/jaspiler/trees/JTRequires.java index e232eb8..818959d 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTRequires.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTRequires.java @@ -1,140 +1,140 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.sun.source.tree.RequiresTree; -import com.sun.source.tree.TreeVisitor; - -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -public final class JTRequires - extends JTDirective - implements RequiresTree { - private static final String PROPERTY_MODULE_NAME = "moduleName"; - private static final String PROPERTY_STATIC = "static"; - private static final String PROPERTY_TRANSITIVE = "transitive"; - private JTExpression moduleName; - private boolean staticPhase; - private boolean transitive; - - public JTRequires() { - this(null, null); - setActionChange(); - } - - JTRequires(RequiresTree requiresTree, JTTree parentTree) { - super(requiresTree, parentTree); - moduleName = null; - staticPhase = false; - transitive = false; - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitRequires(this, data); - } - - @Override - JTRequires analyze() { - super.analyze(); - moduleName = JTTreeFactory.create(getOriginalTree().getModuleName(), this); - staticPhase = getOriginalTree().isStatic(); - transitive = getOriginalTree().isTransitive(); - return this; - } - - @Override - List> getAllNodes() { - var nodes = super.getAllNodes(); - Optional.ofNullable(moduleName).ifPresent(nodes::add); - nodes.forEach(node -> node.setParentTree(this)); - return nodes; - } - - @Override - public Kind getKind() { - return Kind.REQUIRES; - } - - @Override - public JTExpression getModuleName() { - return moduleName; - } - - @Override - public boolean isStatic() { - return staticPhase; - } - - @Override - public boolean isTransitive() { - return transitive; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_MODULE_NAME, propertyName -> v8Runtime.toV8Value(getModuleName())); - registerStringGetter(PROPERTY_STATIC, propertyName -> v8Runtime.createV8ValueBoolean(isStatic())); - registerStringGetter(PROPERTY_TRANSITIVE, propertyName -> v8Runtime.createV8ValueBoolean(isTransitive())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_MODULE_NAME, (propertyName, propertyValue) -> replaceExpression(this::setModuleName, propertyValue)); - registerStringSetter(PROPERTY_STATIC, (propertyName, propertyValue) -> replaceBoolean(this::setStaticPhase, propertyValue)); - registerStringSetter(PROPERTY_TRANSITIVE, (propertyName, propertyValue) -> replaceBoolean(this::setTransitive, propertyValue)); - } - return stringSetterMap; - } - - public JTRequires setModuleName(JTExpression moduleName) { - if (this.moduleName == moduleName) { - return this; - } - this.moduleName = Objects.requireNonNull(moduleName).setParentTree(this); - return setActionChange(); - } - - public JTRequires setStaticPhase(boolean staticPhase) { - if (this.staticPhase == staticPhase) { - return this; - } - this.staticPhase = staticPhase; - return setActionChange(); - } - - public JTRequires setTransitive(boolean transitive) { - if (this.transitive == transitive) { - return this; - } - this.transitive = transitive; - return setActionChange(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.sun.source.tree.RequiresTree; +import com.sun.source.tree.TreeVisitor; + +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +public final class JTRequires + extends JTDirective + implements RequiresTree { + private static final String PROPERTY_MODULE_NAME = "moduleName"; + private static final String PROPERTY_STATIC = "static"; + private static final String PROPERTY_TRANSITIVE = "transitive"; + private JTExpression moduleName; + private boolean staticPhase; + private boolean transitive; + + public JTRequires() { + this(null, null); + setActionChange(); + } + + JTRequires(RequiresTree requiresTree, JTTree parentTree) { + super(requiresTree, parentTree); + moduleName = null; + staticPhase = false; + transitive = false; + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitRequires(this, data); + } + + @Override + JTRequires analyze() { + super.analyze(); + moduleName = JTTreeFactory.create(getOriginalTree().getModuleName(), this); + staticPhase = getOriginalTree().isStatic(); + transitive = getOriginalTree().isTransitive(); + return this; + } + + @Override + List> getAllNodes() { + var nodes = super.getAllNodes(); + Optional.ofNullable(moduleName).ifPresent(nodes::add); + nodes.forEach(node -> node.setParentTree(this)); + return nodes; + } + + @Override + public Kind getKind() { + return Kind.REQUIRES; + } + + @Override + public JTExpression getModuleName() { + return moduleName; + } + + @Override + public boolean isStatic() { + return staticPhase; + } + + @Override + public boolean isTransitive() { + return transitive; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_MODULE_NAME, propertyName -> v8Runtime.toV8Value(getModuleName())); + registerStringGetter(PROPERTY_STATIC, propertyName -> v8Runtime.createV8ValueBoolean(isStatic())); + registerStringGetter(PROPERTY_TRANSITIVE, propertyName -> v8Runtime.createV8ValueBoolean(isTransitive())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_MODULE_NAME, (propertyName, propertyValue) -> replaceExpression(this::setModuleName, propertyValue)); + registerStringSetter(PROPERTY_STATIC, (propertyName, propertyValue) -> replaceBoolean(this::setStaticPhase, propertyValue)); + registerStringSetter(PROPERTY_TRANSITIVE, (propertyName, propertyValue) -> replaceBoolean(this::setTransitive, propertyValue)); + } + return stringSetterMap; + } + + public JTRequires setModuleName(JTExpression moduleName) { + if (this.moduleName == moduleName) { + return this; + } + this.moduleName = Objects.requireNonNull(moduleName).setParentTree(this); + return setActionChange(); + } + + public JTRequires setStaticPhase(boolean staticPhase) { + if (this.staticPhase == staticPhase) { + return this; + } + this.staticPhase = staticPhase; + return setActionChange(); + } + + public JTRequires setTransitive(boolean transitive) { + if (this.transitive == transitive) { + return this; + } + this.transitive = transitive; + return setActionChange(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTReturn.java b/src/main/java/com/caoccao/jaspiler/trees/JTReturn.java index 85d1cff..afc6c6b 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTReturn.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTReturn.java @@ -1,115 +1,115 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.enums.JavaKeyword; -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.jaspiler.styles.IStyleWriter; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.sun.source.tree.ReturnTree; -import com.sun.source.tree.TreeVisitor; - -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -public final class JTReturn - extends JTStatement - implements ReturnTree { - private static final String PROPERTY_EXPRESSION = "expression"; - private JTExpression expression; - - public JTReturn() { - this(null, null); - setActionChange(); - } - - JTReturn(ReturnTree returnTree, JTTree parentTree) { - super(returnTree, parentTree); - expression = null; - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitReturn(this, data); - } - - @Override - JTReturn analyze() { - super.analyze(); - expression = JTTreeFactory.create(getOriginalTree().getExpression(), this); - return this; - } - - @Override - List> getAllNodes() { - var nodes = super.getAllNodes(); - Optional.ofNullable(expression).ifPresent(nodes::add); - nodes.forEach(node -> node.setParentTree(this)); - return nodes; - } - - @Override - public JTExpression getExpression() { - return expression; - } - - @Override - public Kind getKind() { - return Kind.RETURN; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_EXPRESSION, propertyName -> v8Runtime.toV8Value(getExpression())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_EXPRESSION, (propertyName, propertyValue) -> replaceExpression(this::setExpression, propertyValue)); - } - return stringSetterMap; - } - - @Override - public boolean serialize(IStyleWriter writer) { - if (isActionChange()) { - writer.appendKeyword(JavaKeyword.RETURN); - Optional.ofNullable(expression).ifPresent(tree -> writer.appendSpace().append(tree)); - writer.appendSemiColon(); - return true; - } - return super.serialize(writer); - } - - public JTReturn setExpression(JTExpression expression) { - if (this.expression == expression) { - return this; - } - this.expression = Objects.requireNonNull(expression).setParentTree(this); - return setActionChange(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.enums.JavaKeyword; +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.jaspiler.styles.IStyleWriter; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.sun.source.tree.ReturnTree; +import com.sun.source.tree.TreeVisitor; + +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +public final class JTReturn + extends JTStatement + implements ReturnTree { + private static final String PROPERTY_EXPRESSION = "expression"; + private JTExpression expression; + + public JTReturn() { + this(null, null); + setActionChange(); + } + + JTReturn(ReturnTree returnTree, JTTree parentTree) { + super(returnTree, parentTree); + expression = null; + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitReturn(this, data); + } + + @Override + JTReturn analyze() { + super.analyze(); + expression = JTTreeFactory.create(getOriginalTree().getExpression(), this); + return this; + } + + @Override + List> getAllNodes() { + var nodes = super.getAllNodes(); + Optional.ofNullable(expression).ifPresent(nodes::add); + nodes.forEach(node -> node.setParentTree(this)); + return nodes; + } + + @Override + public JTExpression getExpression() { + return expression; + } + + @Override + public Kind getKind() { + return Kind.RETURN; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_EXPRESSION, propertyName -> v8Runtime.toV8Value(getExpression())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_EXPRESSION, (propertyName, propertyValue) -> replaceExpression(this::setExpression, propertyValue)); + } + return stringSetterMap; + } + + @Override + public boolean serialize(IStyleWriter writer) { + if (isActionChange()) { + writer.appendKeyword(JavaKeyword.RETURN); + Optional.ofNullable(expression).ifPresent(tree -> writer.appendSpace().append(tree)); + writer.appendSemiColon(); + return true; + } + return super.serialize(writer); + } + + public JTReturn setExpression(JTExpression expression) { + if (this.expression == expression) { + return this; + } + this.expression = Objects.requireNonNull(expression).setParentTree(this); + return setActionChange(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTSkip.java b/src/main/java/com/caoccao/jaspiler/trees/JTSkip.java index f4feb0b..2c649de 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTSkip.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTSkip.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTStatement.java b/src/main/java/com/caoccao/jaspiler/trees/JTStatement.java index ffb3624..993101b 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTStatement.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTStatement.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTSwitch.java b/src/main/java/com/caoccao/jaspiler/trees/JTSwitch.java index 8fd083d..ba6f0f8 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTSwitch.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTSwitch.java @@ -1,112 +1,112 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.sun.source.tree.SwitchTree; -import com.sun.source.tree.TreeVisitor; - -import java.util.*; - -public final class JTSwitch - extends JTStatement - implements SwitchTree { - private static final String PROPERTY_CASES = "cases"; - private static final String PROPERTY_EXPRESSION = "expression"; - private final List cases; - private JTExpression expression; - - public JTSwitch() { - this(null, null); - setActionChange(); - } - - JTSwitch(SwitchTree switchTree, JTTree parentTree) { - super(switchTree, parentTree); - cases = new ArrayList<>(); - expression = null; - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitSwitch(this, data); - } - - @Override - JTSwitch analyze() { - super.analyze(); - expression = JTTreeFactory.create(getOriginalTree().getExpression(), this); - JTTreeFactory.createAndAdd( - getOriginalTree().getCases(), this, JTCase::new, cases::add); - return this; - } - - @Override - List> getAllNodes() { - var nodes = super.getAllNodes(); - Optional.ofNullable(expression).ifPresent(nodes::add); - cases.stream().filter(Objects::nonNull).forEach(nodes::add); - nodes.forEach(node -> node.setParentTree(this)); - return nodes; - } - - @Override - public List getCases() { - return cases; - } - - @Override - public JTExpression getExpression() { - return expression; - } - - @Override - public Kind getKind() { - return Kind.SWITCH; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_CASES, propertyName -> v8Runtime.toV8Value(getCases())); - registerStringGetter(PROPERTY_EXPRESSION, propertyName -> v8Runtime.toV8Value(getExpression())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_CASES, (propertyName, propertyValue) -> replaceCases(cases, propertyValue)); - registerStringSetter(PROPERTY_EXPRESSION, (propertyName, propertyValue) -> replaceExpression(this::setExpression, propertyValue)); - } - return stringSetterMap; - } - - public JTSwitch setExpression(JTExpression expression) { - if (this.expression == expression) { - return this; - } - this.expression = Optional.ofNullable(expression).map(o -> o.setParentTree(this)).orElse(null); - return setActionChange(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.sun.source.tree.SwitchTree; +import com.sun.source.tree.TreeVisitor; + +import java.util.*; + +public final class JTSwitch + extends JTStatement + implements SwitchTree { + private static final String PROPERTY_CASES = "cases"; + private static final String PROPERTY_EXPRESSION = "expression"; + private final List cases; + private JTExpression expression; + + public JTSwitch() { + this(null, null); + setActionChange(); + } + + JTSwitch(SwitchTree switchTree, JTTree parentTree) { + super(switchTree, parentTree); + cases = new ArrayList<>(); + expression = null; + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitSwitch(this, data); + } + + @Override + JTSwitch analyze() { + super.analyze(); + expression = JTTreeFactory.create(getOriginalTree().getExpression(), this); + JTTreeFactory.createAndAdd( + getOriginalTree().getCases(), this, JTCase::new, cases::add); + return this; + } + + @Override + List> getAllNodes() { + var nodes = super.getAllNodes(); + Optional.ofNullable(expression).ifPresent(nodes::add); + cases.stream().filter(Objects::nonNull).forEach(nodes::add); + nodes.forEach(node -> node.setParentTree(this)); + return nodes; + } + + @Override + public List getCases() { + return cases; + } + + @Override + public JTExpression getExpression() { + return expression; + } + + @Override + public Kind getKind() { + return Kind.SWITCH; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_CASES, propertyName -> v8Runtime.toV8Value(getCases())); + registerStringGetter(PROPERTY_EXPRESSION, propertyName -> v8Runtime.toV8Value(getExpression())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_CASES, (propertyName, propertyValue) -> replaceCases(cases, propertyValue)); + registerStringSetter(PROPERTY_EXPRESSION, (propertyName, propertyValue) -> replaceExpression(this::setExpression, propertyValue)); + } + return stringSetterMap; + } + + public JTSwitch setExpression(JTExpression expression) { + if (this.expression == expression) { + return this; + } + this.expression = Optional.ofNullable(expression).map(o -> o.setParentTree(this)).orElse(null); + return setActionChange(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTSwitchExpression.java b/src/main/java/com/caoccao/jaspiler/trees/JTSwitchExpression.java index 2a699f8..9206573 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTSwitchExpression.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTSwitchExpression.java @@ -1,120 +1,120 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.sun.source.tree.SwitchExpressionTree; -import com.sun.source.tree.TreeVisitor; - -import java.util.*; - -/** - * The type Jt switch expression. - *

- * switch () { - * case "" -> yield ...; - * default "" -> yield ...; - * } - */ -public final class JTSwitchExpression - extends JTPolyExpression - implements SwitchExpressionTree { - private static final String PROPERTY_CASES = "cases"; - private static final String PROPERTY_EXPRESSION = "expression"; - private final List cases; - private JTExpression expression; - - public JTSwitchExpression() { - this(null, null); - setActionChange(); - } - - JTSwitchExpression(SwitchExpressionTree switchExpressionTree, JTTree parentTree) { - super(switchExpressionTree, parentTree); - cases = new ArrayList<>(); - expression = null; - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitSwitchExpression(this, data); - } - - @Override - JTSwitchExpression analyze() { - super.analyze(); - expression = JTTreeFactory.create(getOriginalTree().getExpression(), this); - JTTreeFactory.createAndAdd( - getOriginalTree().getCases(), this, JTCase::new, cases::add); - return this; - } - - @Override - List> getAllNodes() { - var nodes = super.getAllNodes(); - Optional.ofNullable(expression).ifPresent(nodes::add); - cases.stream().filter(Objects::nonNull).forEach(nodes::add); - nodes.forEach(node -> node.setParentTree(this)); - return nodes; - } - - @Override - public List getCases() { - return cases; - } - - @Override - public JTExpression getExpression() { - return expression; - } - - @Override - public Kind getKind() { - return Kind.SWITCH_EXPRESSION; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_CASES, propertyName -> v8Runtime.toV8Value(getCases())); - registerStringGetter(PROPERTY_EXPRESSION, propertyName -> v8Runtime.toV8Value(getExpression())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_CASES, (propertyName, propertyValue) -> replaceCases(cases, propertyValue)); - registerStringSetter(PROPERTY_EXPRESSION, (propertyName, propertyValue) -> replaceExpression(this::setExpression, propertyValue)); - } - return stringSetterMap; - } - - public JTSwitchExpression setExpression(JTExpression expression) { - if (this.expression == expression) { - return this; - } - this.expression = Objects.requireNonNull(expression).setParentTree(this); - return setActionChange(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.sun.source.tree.SwitchExpressionTree; +import com.sun.source.tree.TreeVisitor; + +import java.util.*; + +/** + * The type Jt switch expression. + *

+ * switch () { + * case "" -> yield ...; + * default "" -> yield ...; + * } + */ +public final class JTSwitchExpression + extends JTPolyExpression + implements SwitchExpressionTree { + private static final String PROPERTY_CASES = "cases"; + private static final String PROPERTY_EXPRESSION = "expression"; + private final List cases; + private JTExpression expression; + + public JTSwitchExpression() { + this(null, null); + setActionChange(); + } + + JTSwitchExpression(SwitchExpressionTree switchExpressionTree, JTTree parentTree) { + super(switchExpressionTree, parentTree); + cases = new ArrayList<>(); + expression = null; + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitSwitchExpression(this, data); + } + + @Override + JTSwitchExpression analyze() { + super.analyze(); + expression = JTTreeFactory.create(getOriginalTree().getExpression(), this); + JTTreeFactory.createAndAdd( + getOriginalTree().getCases(), this, JTCase::new, cases::add); + return this; + } + + @Override + List> getAllNodes() { + var nodes = super.getAllNodes(); + Optional.ofNullable(expression).ifPresent(nodes::add); + cases.stream().filter(Objects::nonNull).forEach(nodes::add); + nodes.forEach(node -> node.setParentTree(this)); + return nodes; + } + + @Override + public List getCases() { + return cases; + } + + @Override + public JTExpression getExpression() { + return expression; + } + + @Override + public Kind getKind() { + return Kind.SWITCH_EXPRESSION; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_CASES, propertyName -> v8Runtime.toV8Value(getCases())); + registerStringGetter(PROPERTY_EXPRESSION, propertyName -> v8Runtime.toV8Value(getExpression())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_CASES, (propertyName, propertyValue) -> replaceCases(cases, propertyValue)); + registerStringSetter(PROPERTY_EXPRESSION, (propertyName, propertyValue) -> replaceExpression(this::setExpression, propertyValue)); + } + return stringSetterMap; + } + + public JTSwitchExpression setExpression(JTExpression expression) { + if (this.expression == expression) { + return this; + } + this.expression = Objects.requireNonNull(expression).setParentTree(this); + return setActionChange(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTSynchronized.java b/src/main/java/com/caoccao/jaspiler/trees/JTSynchronized.java index b86518d..205ddbf 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTSynchronized.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTSynchronized.java @@ -1,122 +1,122 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.sun.source.tree.SynchronizedTree; -import com.sun.source.tree.TreeVisitor; - -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -public final class JTSynchronized - extends JTStatement - implements SynchronizedTree { - private static final String PROPERTY_BLOCK = "block"; - private static final String PROPERTY_EXPRESSION = "expression"; - private JTBlock block; - private JTExpression expression; - - public JTSynchronized() { - this(null, null); - setActionChange(); - } - - JTSynchronized(SynchronizedTree synchronizedTree, JTTree parentTree) { - super(synchronizedTree, parentTree); - block = null; - expression = null; - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitSynchronized(this, data); - } - - @Override - JTSynchronized analyze() { - super.analyze(); - expression = JTTreeFactory.create(getOriginalTree().getExpression(), this); - block = JTTreeFactory.create(getOriginalTree().getBlock(), this, JTBlock::new); - return this; - } - - @Override - List> getAllNodes() { - var nodes = super.getAllNodes(); - Optional.ofNullable(expression).ifPresent(nodes::add); - Optional.ofNullable(block).ifPresent(nodes::add); - nodes.forEach(node -> node.setParentTree(this)); - return nodes; - } - - @Override - public JTBlock getBlock() { - return block; - } - - @Override - public JTExpression getExpression() { - return expression; - } - - @Override - public Kind getKind() { - return Kind.SYNCHRONIZED; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_BLOCK, propertyName -> v8Runtime.toV8Value(getBlock())); - registerStringGetter(PROPERTY_EXPRESSION, propertyName -> v8Runtime.toV8Value(getExpression())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_BLOCK, (propertyName, propertyValue) -> replaceBlock(this::setBlock, propertyValue)); - registerStringSetter(PROPERTY_EXPRESSION, (propertyName, propertyValue) -> replaceExpression(this::setExpression, propertyValue)); - } - return stringSetterMap; - } - - public JTSynchronized setBlock(JTBlock block) { - if (this.block == block) { - return this; - } - this.block = Objects.requireNonNull(block).setParentTree(this); - return setActionChange(); - } - - public JTSynchronized setExpression(JTExpression expression) { - if (this.expression == expression) { - return this; - } - this.expression = Objects.requireNonNull(expression).setParentTree(this); - return setActionChange(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.sun.source.tree.SynchronizedTree; +import com.sun.source.tree.TreeVisitor; + +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +public final class JTSynchronized + extends JTStatement + implements SynchronizedTree { + private static final String PROPERTY_BLOCK = "block"; + private static final String PROPERTY_EXPRESSION = "expression"; + private JTBlock block; + private JTExpression expression; + + public JTSynchronized() { + this(null, null); + setActionChange(); + } + + JTSynchronized(SynchronizedTree synchronizedTree, JTTree parentTree) { + super(synchronizedTree, parentTree); + block = null; + expression = null; + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitSynchronized(this, data); + } + + @Override + JTSynchronized analyze() { + super.analyze(); + expression = JTTreeFactory.create(getOriginalTree().getExpression(), this); + block = JTTreeFactory.create(getOriginalTree().getBlock(), this, JTBlock::new); + return this; + } + + @Override + List> getAllNodes() { + var nodes = super.getAllNodes(); + Optional.ofNullable(expression).ifPresent(nodes::add); + Optional.ofNullable(block).ifPresent(nodes::add); + nodes.forEach(node -> node.setParentTree(this)); + return nodes; + } + + @Override + public JTBlock getBlock() { + return block; + } + + @Override + public JTExpression getExpression() { + return expression; + } + + @Override + public Kind getKind() { + return Kind.SYNCHRONIZED; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_BLOCK, propertyName -> v8Runtime.toV8Value(getBlock())); + registerStringGetter(PROPERTY_EXPRESSION, propertyName -> v8Runtime.toV8Value(getExpression())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_BLOCK, (propertyName, propertyValue) -> replaceBlock(this::setBlock, propertyValue)); + registerStringSetter(PROPERTY_EXPRESSION, (propertyName, propertyValue) -> replaceExpression(this::setExpression, propertyValue)); + } + return stringSetterMap; + } + + public JTSynchronized setBlock(JTBlock block) { + if (this.block == block) { + return this; + } + this.block = Objects.requireNonNull(block).setParentTree(this); + return setActionChange(); + } + + public JTSynchronized setExpression(JTExpression expression) { + if (this.expression == expression) { + return this; + } + this.expression = Objects.requireNonNull(expression).setParentTree(this); + return setActionChange(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTThrow.java b/src/main/java/com/caoccao/jaspiler/trees/JTThrow.java index 5b200b1..8b97534 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTThrow.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTThrow.java @@ -1,102 +1,102 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.sun.source.tree.ThrowTree; -import com.sun.source.tree.TreeVisitor; - -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -public final class JTThrow - extends JTStatement - implements ThrowTree { - private static final String PROPERTY_EXPRESSION = "expression"; - private JTExpression expression; - - public JTThrow() { - this(null, null); - setActionChange(); - } - - JTThrow(ThrowTree throwTree, JTTree parentTree) { - super(throwTree, parentTree); - expression = null; - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitThrow(this, data); - } - - @Override - JTThrow analyze() { - super.analyze(); - expression = JTTreeFactory.create(getOriginalTree().getExpression(), this); - return this; - } - - @Override - List> getAllNodes() { - var nodes = super.getAllNodes(); - Optional.ofNullable(expression).ifPresent(nodes::add); - nodes.forEach(node -> node.setParentTree(this)); - return nodes; - } - - @Override - public JTExpression getExpression() { - return expression; - } - - @Override - public Kind getKind() { - return Kind.THROW; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_EXPRESSION, propertyName -> v8Runtime.toV8Value(getExpression())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_EXPRESSION, (propertyName, propertyValue) -> replaceExpression(this::setExpression, propertyValue)); - } - return stringSetterMap; - } - - public JTThrow setExpression(JTExpression expression) { - if (this.expression == expression) { - return this; - } - this.expression = Objects.requireNonNull(expression).setParentTree(this); - return setActionChange(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.sun.source.tree.ThrowTree; +import com.sun.source.tree.TreeVisitor; + +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +public final class JTThrow + extends JTStatement + implements ThrowTree { + private static final String PROPERTY_EXPRESSION = "expression"; + private JTExpression expression; + + public JTThrow() { + this(null, null); + setActionChange(); + } + + JTThrow(ThrowTree throwTree, JTTree parentTree) { + super(throwTree, parentTree); + expression = null; + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitThrow(this, data); + } + + @Override + JTThrow analyze() { + super.analyze(); + expression = JTTreeFactory.create(getOriginalTree().getExpression(), this); + return this; + } + + @Override + List> getAllNodes() { + var nodes = super.getAllNodes(); + Optional.ofNullable(expression).ifPresent(nodes::add); + nodes.forEach(node -> node.setParentTree(this)); + return nodes; + } + + @Override + public JTExpression getExpression() { + return expression; + } + + @Override + public Kind getKind() { + return Kind.THROW; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_EXPRESSION, propertyName -> v8Runtime.toV8Value(getExpression())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_EXPRESSION, (propertyName, propertyValue) -> replaceExpression(this::setExpression, propertyValue)); + } + return stringSetterMap; + } + + public JTThrow setExpression(JTExpression expression) { + if (this.expression == expression) { + return this; + } + this.expression = Objects.requireNonNull(expression).setParentTree(this); + return setActionChange(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTTree.java b/src/main/java/com/caoccao/jaspiler/trees/JTTree.java index 88110e0..624b4f1 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTTree.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTTree.java @@ -1,502 +1,502 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.JaspilerContract; -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.jaspiler.exceptions.JaspilerNotImplementedException; -import com.caoccao.jaspiler.styles.IStyleWriter; -import com.caoccao.jaspiler.styles.StandardStyleWriter; -import com.caoccao.jaspiler.styles.StyleOptions; -import com.caoccao.jaspiler.utils.BaseLoggingObject; -import com.caoccao.javet.exceptions.JavetException; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.interop.V8Runtime; -import com.caoccao.javet.values.V8Value; -import com.caoccao.javet.values.primitive.V8ValueBoolean; -import com.caoccao.javet.values.primitive.V8ValueString; -import com.caoccao.javet.values.reference.V8ValueSymbol; -import com.caoccao.javet.values.reference.builtin.V8ValueBuiltInSymbol; -import com.sun.source.tree.Tree; - -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.Function; - -@SuppressWarnings("unchecked") -public abstract class JTTree< - OriginalTree extends Tree, - NewTree extends JTTree> - extends BaseLoggingObject - implements IJTTree { - protected static final String FUNCTION_IS_ACTION_CHANGE = "isActionChange"; - protected static final String FUNCTION_IS_ACTION_IGNORE = "isActionIgnore"; - protected static final String FUNCTION_IS_ACTION_NO_CHANGE = "isActionNoChange"; - protected static final String FUNCTION_SET_ACTION_CHANGE = "setActionChange"; - protected static final String FUNCTION_SET_ACTION_IGNORE = "setActionIgnore"; - protected static final String FUNCTION_SET_ACTION_NO_CHANGE = "setActionNoChange"; - protected static final String FUNCTION_TO_STRING = "toString"; - protected static final long INVALID_POSITION = -1L; - protected static final String PROPERTY_CLASS_NAME = "className"; - protected static final String PROPERTY_CLASS_SIMPLE_NAME = "classSimpleName"; - protected static final String PROPERTY_KIND = "kind"; - protected static final String PROPERTY_PARENT_TREE = "parentTree"; - protected JaspilerContract.Action action; - protected JTPosition originalPosition; - protected OriginalTree originalTree; - protected JTTree parentTree; - protected Map> stringGetterMap; - protected Map> stringSetterMap; - protected Map> symbolGetterMap; - protected V8Runtime v8Runtime; - - JTTree(OriginalTree originalTree, JTTree parentTree) { - super(); - originalPosition = JTPosition.Invalid; - this.originalTree = originalTree; - this.parentTree = parentTree; - setAction(JaspilerContract.Action.NoChange); - stringGetterMap = null; - stringSetterMap = null; - symbolGetterMap = null; - setV8Runtime(null); - } - - NewTree analyze() { - originalPosition = getCompilationUnit().getOriginalPosition(getOriginalTree()); - return (NewTree) this; - } - - @Override - public JaspilerContract.Action getAction() { - return action; - } - - List> getAllNodes() { - return new ArrayList<>(); - } - - protected long getOptionalEndPosition(long position) { - return getOriginalPosition().isValid() ? getOriginalPosition().endPosition() : position; - } - - public String getOriginalCode() { - return getCompilationUnit().getOriginalCode(); - } - - @Override - public JTPosition getOriginalPosition() { - return originalPosition; - } - - @Override - public OriginalTree getOriginalTree() { - return originalTree; - } - - @Override - public JTTree getParentTree() { - return parentTree; - } - - @Override - public V8Runtime getV8Runtime() { - return v8Runtime; - } - - @Override - public boolean isActionChange() { - if (isActionIgnore()) { - return false; - } - if (getAction().isChange()) { - return true; - } - return getAllNodes().stream() - .anyMatch(jtTree -> jtTree.isActionChange() || jtTree.isActionIgnore()); - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - stringGetterMap = new HashMap<>(); - registerStringGetterFunction(FUNCTION_IS_ACTION_CHANGE, property -> v8Runtime.createV8ValueBoolean(isActionChange())); - registerStringGetterFunction(FUNCTION_IS_ACTION_IGNORE, property -> v8Runtime.createV8ValueBoolean(isActionIgnore())); - registerStringGetterFunction(FUNCTION_IS_ACTION_NO_CHANGE, property -> v8Runtime.createV8ValueBoolean(isActionNoChange())); - registerStringGetterFunction(FUNCTION_SET_ACTION_CHANGE, property -> { - setActionChange(); - return v8Runtime.createV8ValueBoolean(true); - }); - registerStringGetterFunction(FUNCTION_SET_ACTION_IGNORE, property -> { - setActionIgnore(); - return v8Runtime.createV8ValueBoolean(true); - }); - registerStringGetterFunction(FUNCTION_SET_ACTION_NO_CHANGE, property -> { - setActionNoChange(); - return v8Runtime.createV8ValueBoolean(true); - }); - registerStringGetterFunction(FUNCTION_TO_STRING, property -> v8Runtime.createV8ValueString(toString())); - registerStringGetter(PROPERTY_CLASS_NAME, property -> v8Runtime.createV8ValueString(getClass().getName())); - registerStringGetter(PROPERTY_CLASS_SIMPLE_NAME, property -> v8Runtime.createV8ValueString(getClass().getSimpleName())); - registerStringGetter(PROPERTY_KIND, property -> v8Runtime.createV8ValueString(getKind().name())); - registerStringGetter(PROPERTY_PARENT_TREE, property -> v8Runtime.toV8Value(getParentTree())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - stringSetterMap = new HashMap<>(); - } - return stringSetterMap; - } - - @Override - public Map> proxyGetSymbolGetterMap() { - if (symbolGetterMap == null) { - symbolGetterMap = new HashMap<>(); - registerSymbolGetterFunction(V8ValueBuiltInSymbol.SYMBOL_PROPERTY_TO_PRIMITIVE, description -> v8Runtime.createV8ValueString(toString())); - } - return symbolGetterMap; - } - - protected boolean replaceAnnotations(List list, V8Value v8Value) throws JavetException { - if (v8Runtime.toObject(v8Value) instanceof List trees) { - list.clear(); - trees.stream() - .filter(tree -> tree instanceof JTAnnotation) - .map(tree -> ((JTAnnotation) tree).setParentTree(this)) - .forEach(list::add); - setActionChange(); - return true; - } - return false; - } - - protected boolean replaceBlock(Function setter, V8Value v8Value) throws JavetException { - if (v8Runtime.toObject(v8Value) instanceof JTBlock tree) { - setter.apply(tree); - return true; - } - return false; - } - - protected boolean replaceBoolean(Function setter, V8Value v8Value) { - if (v8Value instanceof V8ValueBoolean v8ValueBoolean) { - setter.apply(v8ValueBoolean.getValue()); - return true; - } - return false; - } - - protected boolean replaceCaseLabels(List> list, V8Value v8Value) throws JavetException { - if (v8Runtime.toObject(v8Value) instanceof List trees) { - list.clear(); - trees.stream() - .filter(tree -> tree instanceof JTCaseLabel) - .map(tree -> ((JTCaseLabel) tree).setParentTree(this)) - .forEach(list::add); - setActionChange(); - return true; - } - return false; - } - - protected boolean replaceCases(List list, V8Value v8Value) throws JavetException { - if (v8Runtime.toObject(v8Value) instanceof List trees) { - list.clear(); - trees.stream() - .filter(tree -> tree instanceof JTCase) - .map(tree -> ((JTCase) tree).setParentTree(this)) - .forEach(list::add); - setActionChange(); - return true; - } - return false; - } - - protected boolean replaceCatches(List list, V8Value v8Value) throws JavetException { - if (v8Runtime.toObject(v8Value) instanceof List trees) { - list.clear(); - trees.stream() - .filter(tree -> tree instanceof JTCatch) - .map(tree -> ((JTCatch) tree).setParentTree(this)) - .forEach(list::add); - setActionChange(); - return true; - } - return false; - } - - protected boolean replaceClassDecl(Function setter, V8Value v8Value) throws JavetException { - if (v8Runtime.toObject(v8Value) instanceof JTClassDecl tree) { - setter.apply(tree); - return true; - } - return false; - } - - protected boolean replaceDirectives(List> list, V8Value v8Value) throws JavetException { - if (v8Runtime.toObject(v8Value) instanceof List trees) { - list.clear(); - trees.stream() - .filter(tree -> tree instanceof JTDirective) - .map(tree -> ((JTDirective) tree).setParentTree(this)) - .forEach(list::add); - setActionChange(); - return true; - } - return false; - } - - protected boolean replaceExpression(Function, NewTree> setter, V8Value v8Value) throws JavetException { - if (v8Runtime.toObject(v8Value) instanceof JTExpression tree) { - setter.apply(tree); - return true; - } - return false; - } - - protected boolean replaceExpressionStatements(List list, V8Value v8Value) throws JavetException { - if (v8Runtime.toObject(v8Value) instanceof List trees) { - list.clear(); - trees.stream() - .filter(tree -> tree instanceof JTExpressionStatement) - .map(tree -> ((JTExpressionStatement) tree).setParentTree(this)) - .forEach(list::add); - setActionChange(); - return true; - } - return false; - } - - protected boolean replaceExpressions(List> list, V8Value v8Value) throws JavetException { - if (v8Runtime.toObject(v8Value) instanceof List trees) { - list.clear(); - trees.stream() - .filter(tree -> tree instanceof JTExpression) - .map(tree -> ((JTExpression) tree).setParentTree(this)) - .forEach(list::add); - setActionChange(); - return true; - } - return false; - } - - protected boolean replaceImports(List list, V8Value v8Value) throws JavetException { - if (v8Runtime.toObject(v8Value) instanceof List trees) { - list.clear(); - trees.stream() - .filter(tree -> tree instanceof JTImport) - .map(tree -> ((JTImport) tree).setParentTree(this)) - .forEach(list::add); - setActionChange(); - return true; - } - return false; - } - - protected boolean replaceKind(Function setter, V8Value v8Value) { - if (v8Value instanceof V8ValueString v8ValueString) { - setter.apply(Kind.valueOf(v8ValueString.getValue())); - return true; - } - return false; - } - - protected boolean replaceLambda(Function setter, V8Value v8Value) throws JavetException { - if (v8Runtime.toObject(v8Value) instanceof JTLambda tree) { - setter.apply(tree); - return true; - } - return false; - } - - protected boolean replaceModifiers(Function setter, V8Value v8Value) throws JavetException { - if (v8Runtime.toObject(v8Value) instanceof JTModifiers tree) { - setter.apply(tree); - return true; - } - return false; - } - - protected boolean replaceModuleDecl(Function setter, V8Value v8Value) throws JavetException { - if (v8Runtime.toObject(v8Value) instanceof JTModuleDecl tree) { - setter.apply(tree); - return true; - } - return false; - } - - protected boolean replaceName(Function setter, V8Value v8Value) throws JavetException { - if (v8Runtime.toObject(v8Value) instanceof JTName tree) { - setter.apply(tree); - return true; - } - return false; - } - - protected boolean replacePackageDecl(Function setter, V8Value v8Value) throws JavetException { - if (v8Runtime.toObject(v8Value) instanceof JTPackageDecl tree) { - setter.apply(tree); - return true; - } - return false; - } - - protected boolean replacePattern(Function, NewTree> setter, V8Value v8Value) throws JavetException { - if (v8Runtime.toObject(v8Value) instanceof JTPattern tree) { - setter.apply(tree); - return true; - } - return false; - } - - protected boolean replaceStatement(Function, NewTree> setter, V8Value v8Value) throws JavetException { - if (v8Runtime.toObject(v8Value) instanceof JTStatement tree) { - setter.apply(tree); - return true; - } - return false; - } - - protected boolean replaceStatements(List> list, V8Value v8Value) throws JavetException { - if (v8Runtime.toObject(v8Value) instanceof List trees) { - list.clear(); - trees.stream() - .filter(tree -> tree instanceof JTStatement) - .map(tree -> ((JTStatement) tree).setParentTree(this)) - .forEach(list::add); - setActionChange(); - return true; - } - return false; - } - - protected boolean replaceString(Function setter, V8Value v8Value) { - if (v8Value instanceof V8ValueString v8ValueString) { - setter.apply(v8ValueString.getValue()); - return true; - } - return false; - } - - protected boolean replaceTree(Function, NewTree> setter, V8Value v8Value) throws JavetException { - if (v8Runtime.toObject(v8Value) instanceof JTTree tree) { - setter.apply(tree); - return true; - } - return false; - } - - protected boolean replaceTrees(List> list, V8Value v8Value) throws JavetException { - if (v8Runtime.toObject(v8Value) instanceof List trees) { - list.clear(); - trees.stream() - .filter(tree -> tree instanceof JTTree) - .map(tree -> ((JTTree) tree).setParentTree(this)) - .forEach(list::add); - setActionChange(); - return true; - } - return false; - } - - protected boolean replaceTypeParameters(List list, V8Value v8Value) throws JavetException { - if (v8Runtime.toObject(v8Value) instanceof List trees) { - list.clear(); - trees.stream() - .filter(tree -> tree instanceof JTTypeParameter) - .map(tree -> ((JTTypeParameter) tree).setParentTree(this)) - .forEach(list::add); - setActionChange(); - return true; - } - return false; - } - - protected boolean replaceVariableDecl(Function setter, V8Value v8Value) throws JavetException { - if (v8Runtime.toObject(v8Value) instanceof JTVariableDecl tree) { - setter.apply(tree); - return true; - } - return false; - } - - protected boolean replaceVariableDecls(List list, V8Value v8Value) throws JavetException { - if (v8Runtime.toObject(v8Value) instanceof List trees) { - list.clear(); - trees.stream() - .filter(tree -> tree instanceof JTVariableDecl) - .map(tree -> ((JTVariableDecl) tree).setParentTree(this)) - .forEach(list::add); - setActionChange(); - return true; - } - return false; - } - - @Override - public boolean serialize(IStyleWriter writer) { - if (isActionIgnore()) { - return false; - } - if (isActionChange()) { - throw new JaspilerNotImplementedException( - MessageFormat.format( - "{0} serialize() has not been implemented yet. You may either file an issue, or submit a pull request.", - getClass().getSimpleName())); - } - if (!getOriginalPosition().isValid()) { - return false; - } - writer.append(getOriginalCode().substring( - (int) getOriginalPosition().startPosition(), - (int) getOriginalPosition().endPosition())); - return true; - } - - public NewTree setAction(JaspilerContract.Action action) { - this.action = action; - return (NewTree) this; - } - - NewTree setParentTree(JTTree parentTree) { - if (this.parentTree != parentTree) { - this.parentTree = parentTree; - return setActionChange(); - } - return (NewTree) this; - } - - @Override - public void setV8Runtime(V8Runtime v8Runtime) { - this.v8Runtime = v8Runtime; - } - - @Override - public String toString() { - var writer = new StandardStyleWriter(StyleOptions.Default); - serialize(writer); - return writer.toString(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.JaspilerContract; +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.jaspiler.exceptions.JaspilerNotImplementedException; +import com.caoccao.jaspiler.styles.IStyleWriter; +import com.caoccao.jaspiler.styles.StandardStyleWriter; +import com.caoccao.jaspiler.styles.StyleOptions; +import com.caoccao.jaspiler.utils.BaseLoggingObject; +import com.caoccao.javet.exceptions.JavetException; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.interop.V8Runtime; +import com.caoccao.javet.values.V8Value; +import com.caoccao.javet.values.primitive.V8ValueBoolean; +import com.caoccao.javet.values.primitive.V8ValueString; +import com.caoccao.javet.values.reference.V8ValueSymbol; +import com.caoccao.javet.values.reference.builtin.V8ValueBuiltInSymbol; +import com.sun.source.tree.Tree; + +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; + +@SuppressWarnings("unchecked") +public abstract class JTTree< + OriginalTree extends Tree, + NewTree extends JTTree> + extends BaseLoggingObject + implements IJTTree { + protected static final String FUNCTION_IS_ACTION_CHANGE = "isActionChange"; + protected static final String FUNCTION_IS_ACTION_IGNORE = "isActionIgnore"; + protected static final String FUNCTION_IS_ACTION_NO_CHANGE = "isActionNoChange"; + protected static final String FUNCTION_SET_ACTION_CHANGE = "setActionChange"; + protected static final String FUNCTION_SET_ACTION_IGNORE = "setActionIgnore"; + protected static final String FUNCTION_SET_ACTION_NO_CHANGE = "setActionNoChange"; + protected static final String FUNCTION_TO_STRING = "toString"; + protected static final long INVALID_POSITION = -1L; + protected static final String PROPERTY_CLASS_NAME = "className"; + protected static final String PROPERTY_CLASS_SIMPLE_NAME = "classSimpleName"; + protected static final String PROPERTY_KIND = "kind"; + protected static final String PROPERTY_PARENT_TREE = "parentTree"; + protected JaspilerContract.Action action; + protected JTPosition originalPosition; + protected OriginalTree originalTree; + protected JTTree parentTree; + protected Map> stringGetterMap; + protected Map> stringSetterMap; + protected Map> symbolGetterMap; + protected V8Runtime v8Runtime; + + JTTree(OriginalTree originalTree, JTTree parentTree) { + super(); + originalPosition = JTPosition.Invalid; + this.originalTree = originalTree; + this.parentTree = parentTree; + setAction(JaspilerContract.Action.NoChange); + stringGetterMap = null; + stringSetterMap = null; + symbolGetterMap = null; + setV8Runtime(null); + } + + NewTree analyze() { + originalPosition = getCompilationUnit().getOriginalPosition(getOriginalTree()); + return (NewTree) this; + } + + @Override + public JaspilerContract.Action getAction() { + return action; + } + + List> getAllNodes() { + return new ArrayList<>(); + } + + protected long getOptionalEndPosition(long position) { + return getOriginalPosition().isValid() ? getOriginalPosition().endPosition() : position; + } + + public String getOriginalCode() { + return getCompilationUnit().getOriginalCode(); + } + + @Override + public JTPosition getOriginalPosition() { + return originalPosition; + } + + @Override + public OriginalTree getOriginalTree() { + return originalTree; + } + + @Override + public JTTree getParentTree() { + return parentTree; + } + + @Override + public V8Runtime getV8Runtime() { + return v8Runtime; + } + + @Override + public boolean isActionChange() { + if (isActionIgnore()) { + return false; + } + if (getAction().isChange()) { + return true; + } + return getAllNodes().stream() + .anyMatch(jtTree -> jtTree.isActionChange() || jtTree.isActionIgnore()); + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + stringGetterMap = new HashMap<>(); + registerStringGetterFunction(FUNCTION_IS_ACTION_CHANGE, property -> v8Runtime.createV8ValueBoolean(isActionChange())); + registerStringGetterFunction(FUNCTION_IS_ACTION_IGNORE, property -> v8Runtime.createV8ValueBoolean(isActionIgnore())); + registerStringGetterFunction(FUNCTION_IS_ACTION_NO_CHANGE, property -> v8Runtime.createV8ValueBoolean(isActionNoChange())); + registerStringGetterFunction(FUNCTION_SET_ACTION_CHANGE, property -> { + setActionChange(); + return v8Runtime.createV8ValueBoolean(true); + }); + registerStringGetterFunction(FUNCTION_SET_ACTION_IGNORE, property -> { + setActionIgnore(); + return v8Runtime.createV8ValueBoolean(true); + }); + registerStringGetterFunction(FUNCTION_SET_ACTION_NO_CHANGE, property -> { + setActionNoChange(); + return v8Runtime.createV8ValueBoolean(true); + }); + registerStringGetterFunction(FUNCTION_TO_STRING, property -> v8Runtime.createV8ValueString(toString())); + registerStringGetter(PROPERTY_CLASS_NAME, property -> v8Runtime.createV8ValueString(getClass().getName())); + registerStringGetter(PROPERTY_CLASS_SIMPLE_NAME, property -> v8Runtime.createV8ValueString(getClass().getSimpleName())); + registerStringGetter(PROPERTY_KIND, property -> v8Runtime.createV8ValueString(getKind().name())); + registerStringGetter(PROPERTY_PARENT_TREE, property -> v8Runtime.toV8Value(getParentTree())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + stringSetterMap = new HashMap<>(); + } + return stringSetterMap; + } + + @Override + public Map> proxyGetSymbolGetterMap() { + if (symbolGetterMap == null) { + symbolGetterMap = new HashMap<>(); + registerSymbolGetterFunction(V8ValueBuiltInSymbol.SYMBOL_PROPERTY_TO_PRIMITIVE, description -> v8Runtime.createV8ValueString(toString())); + } + return symbolGetterMap; + } + + protected boolean replaceAnnotations(List list, V8Value v8Value) throws JavetException { + if (v8Runtime.toObject(v8Value) instanceof List trees) { + list.clear(); + trees.stream() + .filter(tree -> tree instanceof JTAnnotation) + .map(tree -> ((JTAnnotation) tree).setParentTree(this)) + .forEach(list::add); + setActionChange(); + return true; + } + return false; + } + + protected boolean replaceBlock(Function setter, V8Value v8Value) throws JavetException { + if (v8Runtime.toObject(v8Value) instanceof JTBlock tree) { + setter.apply(tree); + return true; + } + return false; + } + + protected boolean replaceBoolean(Function setter, V8Value v8Value) { + if (v8Value instanceof V8ValueBoolean v8ValueBoolean) { + setter.apply(v8ValueBoolean.getValue()); + return true; + } + return false; + } + + protected boolean replaceCaseLabels(List> list, V8Value v8Value) throws JavetException { + if (v8Runtime.toObject(v8Value) instanceof List trees) { + list.clear(); + trees.stream() + .filter(tree -> tree instanceof JTCaseLabel) + .map(tree -> ((JTCaseLabel) tree).setParentTree(this)) + .forEach(list::add); + setActionChange(); + return true; + } + return false; + } + + protected boolean replaceCases(List list, V8Value v8Value) throws JavetException { + if (v8Runtime.toObject(v8Value) instanceof List trees) { + list.clear(); + trees.stream() + .filter(tree -> tree instanceof JTCase) + .map(tree -> ((JTCase) tree).setParentTree(this)) + .forEach(list::add); + setActionChange(); + return true; + } + return false; + } + + protected boolean replaceCatches(List list, V8Value v8Value) throws JavetException { + if (v8Runtime.toObject(v8Value) instanceof List trees) { + list.clear(); + trees.stream() + .filter(tree -> tree instanceof JTCatch) + .map(tree -> ((JTCatch) tree).setParentTree(this)) + .forEach(list::add); + setActionChange(); + return true; + } + return false; + } + + protected boolean replaceClassDecl(Function setter, V8Value v8Value) throws JavetException { + if (v8Runtime.toObject(v8Value) instanceof JTClassDecl tree) { + setter.apply(tree); + return true; + } + return false; + } + + protected boolean replaceDirectives(List> list, V8Value v8Value) throws JavetException { + if (v8Runtime.toObject(v8Value) instanceof List trees) { + list.clear(); + trees.stream() + .filter(tree -> tree instanceof JTDirective) + .map(tree -> ((JTDirective) tree).setParentTree(this)) + .forEach(list::add); + setActionChange(); + return true; + } + return false; + } + + protected boolean replaceExpression(Function, NewTree> setter, V8Value v8Value) throws JavetException { + if (v8Runtime.toObject(v8Value) instanceof JTExpression tree) { + setter.apply(tree); + return true; + } + return false; + } + + protected boolean replaceExpressionStatements(List list, V8Value v8Value) throws JavetException { + if (v8Runtime.toObject(v8Value) instanceof List trees) { + list.clear(); + trees.stream() + .filter(tree -> tree instanceof JTExpressionStatement) + .map(tree -> ((JTExpressionStatement) tree).setParentTree(this)) + .forEach(list::add); + setActionChange(); + return true; + } + return false; + } + + protected boolean replaceExpressions(List> list, V8Value v8Value) throws JavetException { + if (v8Runtime.toObject(v8Value) instanceof List trees) { + list.clear(); + trees.stream() + .filter(tree -> tree instanceof JTExpression) + .map(tree -> ((JTExpression) tree).setParentTree(this)) + .forEach(list::add); + setActionChange(); + return true; + } + return false; + } + + protected boolean replaceImports(List list, V8Value v8Value) throws JavetException { + if (v8Runtime.toObject(v8Value) instanceof List trees) { + list.clear(); + trees.stream() + .filter(tree -> tree instanceof JTImport) + .map(tree -> ((JTImport) tree).setParentTree(this)) + .forEach(list::add); + setActionChange(); + return true; + } + return false; + } + + protected boolean replaceKind(Function setter, V8Value v8Value) { + if (v8Value instanceof V8ValueString v8ValueString) { + setter.apply(Kind.valueOf(v8ValueString.getValue())); + return true; + } + return false; + } + + protected boolean replaceLambda(Function setter, V8Value v8Value) throws JavetException { + if (v8Runtime.toObject(v8Value) instanceof JTLambda tree) { + setter.apply(tree); + return true; + } + return false; + } + + protected boolean replaceModifiers(Function setter, V8Value v8Value) throws JavetException { + if (v8Runtime.toObject(v8Value) instanceof JTModifiers tree) { + setter.apply(tree); + return true; + } + return false; + } + + protected boolean replaceModuleDecl(Function setter, V8Value v8Value) throws JavetException { + if (v8Runtime.toObject(v8Value) instanceof JTModuleDecl tree) { + setter.apply(tree); + return true; + } + return false; + } + + protected boolean replaceName(Function setter, V8Value v8Value) throws JavetException { + if (v8Runtime.toObject(v8Value) instanceof JTName tree) { + setter.apply(tree); + return true; + } + return false; + } + + protected boolean replacePackageDecl(Function setter, V8Value v8Value) throws JavetException { + if (v8Runtime.toObject(v8Value) instanceof JTPackageDecl tree) { + setter.apply(tree); + return true; + } + return false; + } + + protected boolean replacePattern(Function, NewTree> setter, V8Value v8Value) throws JavetException { + if (v8Runtime.toObject(v8Value) instanceof JTPattern tree) { + setter.apply(tree); + return true; + } + return false; + } + + protected boolean replaceStatement(Function, NewTree> setter, V8Value v8Value) throws JavetException { + if (v8Runtime.toObject(v8Value) instanceof JTStatement tree) { + setter.apply(tree); + return true; + } + return false; + } + + protected boolean replaceStatements(List> list, V8Value v8Value) throws JavetException { + if (v8Runtime.toObject(v8Value) instanceof List trees) { + list.clear(); + trees.stream() + .filter(tree -> tree instanceof JTStatement) + .map(tree -> ((JTStatement) tree).setParentTree(this)) + .forEach(list::add); + setActionChange(); + return true; + } + return false; + } + + protected boolean replaceString(Function setter, V8Value v8Value) { + if (v8Value instanceof V8ValueString v8ValueString) { + setter.apply(v8ValueString.getValue()); + return true; + } + return false; + } + + protected boolean replaceTree(Function, NewTree> setter, V8Value v8Value) throws JavetException { + if (v8Runtime.toObject(v8Value) instanceof JTTree tree) { + setter.apply(tree); + return true; + } + return false; + } + + protected boolean replaceTrees(List> list, V8Value v8Value) throws JavetException { + if (v8Runtime.toObject(v8Value) instanceof List trees) { + list.clear(); + trees.stream() + .filter(tree -> tree instanceof JTTree) + .map(tree -> ((JTTree) tree).setParentTree(this)) + .forEach(list::add); + setActionChange(); + return true; + } + return false; + } + + protected boolean replaceTypeParameters(List list, V8Value v8Value) throws JavetException { + if (v8Runtime.toObject(v8Value) instanceof List trees) { + list.clear(); + trees.stream() + .filter(tree -> tree instanceof JTTypeParameter) + .map(tree -> ((JTTypeParameter) tree).setParentTree(this)) + .forEach(list::add); + setActionChange(); + return true; + } + return false; + } + + protected boolean replaceVariableDecl(Function setter, V8Value v8Value) throws JavetException { + if (v8Runtime.toObject(v8Value) instanceof JTVariableDecl tree) { + setter.apply(tree); + return true; + } + return false; + } + + protected boolean replaceVariableDecls(List list, V8Value v8Value) throws JavetException { + if (v8Runtime.toObject(v8Value) instanceof List trees) { + list.clear(); + trees.stream() + .filter(tree -> tree instanceof JTVariableDecl) + .map(tree -> ((JTVariableDecl) tree).setParentTree(this)) + .forEach(list::add); + setActionChange(); + return true; + } + return false; + } + + @Override + public boolean serialize(IStyleWriter writer) { + if (isActionIgnore()) { + return false; + } + if (isActionChange()) { + throw new JaspilerNotImplementedException( + MessageFormat.format( + "{0} serialize() has not been implemented yet. You may either file an issue, or submit a pull request.", + getClass().getSimpleName())); + } + if (!getOriginalPosition().isValid()) { + return false; + } + writer.append(getOriginalCode().substring( + (int) getOriginalPosition().startPosition(), + (int) getOriginalPosition().endPosition())); + return true; + } + + public NewTree setAction(JaspilerContract.Action action) { + this.action = action; + return (NewTree) this; + } + + NewTree setParentTree(JTTree parentTree) { + if (this.parentTree != parentTree) { + this.parentTree = parentTree; + return setActionChange(); + } + return (NewTree) this; + } + + @Override + public void setV8Runtime(V8Runtime v8Runtime) { + this.v8Runtime = v8Runtime; + } + + @Override + public String toString() { + var writer = new StandardStyleWriter(StyleOptions.Default); + serialize(writer); + return writer.toString(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTTreeFactory.java b/src/main/java/com/caoccao/jaspiler/trees/JTTreeFactory.java index 5bc2c98..483526e 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTTreeFactory.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTTreeFactory.java @@ -1,233 +1,233 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.sun.source.tree.*; -import org.apache.commons.collections4.CollectionUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.lang.model.element.Name; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.function.BiFunction; -import java.util.function.Consumer; - -@SuppressWarnings({"unchecked", "preview"}) -public final class JTTreeFactory { - private static final Logger logger = LoggerFactory.getLogger(JTTreeFactory.class); - - private JTTreeFactory() { - } - - public static > R create( - T tree, - JTTree parentTree, - BiFunction, R> constructor) { - return Optional.ofNullable(tree) - .map(o -> constructor.apply(o, parentTree)) - .map(o -> (R) o.analyze()) - .orElse(null); - } - - public static > R create( - T tree, - JTTree parentTree) { - Objects.requireNonNull(parentTree); - R r = null; - if (tree != null) { - if (logger.isTraceEnabled()) { - String text = tree.toString(); - if (text.length() > 40) { - text = text.substring(0, 40) + " ..."; - } - text = text.replace("\n", "\\n").replace("\r", "\\r"); - logger.trace("Parsing [{}] [{}].", tree.getKind().name(), text); - } - try { - switch (tree.getKind()) { - case AND, CONDITIONAL_AND, CONDITIONAL_OR, DIVIDE, EQUAL_TO, - GREATER_THAN, GREATER_THAN_EQUAL, LEFT_SHIFT, LESS_THAN, LESS_THAN_EQUAL, - MINUS, MULTIPLY, NOT_EQUAL_TO, OR, PLUS, - REMAINDER, RIGHT_SHIFT, UNSIGNED_RIGHT_SHIFT, XOR -> - r = (R) create((BinaryTree) tree, parentTree, JTBinary::new); - case AND_ASSIGNMENT, DIVIDE_ASSIGNMENT, LEFT_SHIFT_ASSIGNMENT, MINUS_ASSIGNMENT, MULTIPLY_ASSIGNMENT, - OR_ASSIGNMENT, PLUS_ASSIGNMENT, REMAINDER_ASSIGNMENT, RIGHT_SHIFT_ASSIGNMENT, UNSIGNED_RIGHT_SHIFT_ASSIGNMENT, - XOR_ASSIGNMENT -> - r = (R) create((CompoundAssignmentTree) tree, parentTree, JTAssignOp::new); - case ANNOTATED_TYPE -> r = (R) create((AnnotatedTypeTree) tree, parentTree, JTAnnotatedType::new); - case ANNOTATION -> r = (R) create((AnnotationTree) tree, parentTree, JTAnnotation::new); - case ANNOTATION_TYPE, CLASS, ENUM, INTERFACE, RECORD -> - r = (R) create((ClassTree) tree, parentTree, JTClassDecl::new); - case ARRAY_ACCESS -> r = (R) create((ArrayAccessTree) tree, parentTree, JTArrayAccess::new); - case ARRAY_TYPE -> r = (R) create((ArrayTypeTree) tree, parentTree, JTArrayType::new); - case ASSERT -> r = (R) create((AssertTree) tree, parentTree, JTAssert::new); - case ASSIGNMENT -> r = (R) create((AssignmentTree) tree, parentTree, JTAssign::new); - case BINDING_PATTERN -> - r = (R) create((BindingPatternTree) tree, parentTree, JTBindingPattern::new); - case BITWISE_COMPLEMENT, LOGICAL_COMPLEMENT, POSTFIX_DECREMENT, POSTFIX_INCREMENT, PREFIX_DECREMENT, - PREFIX_INCREMENT, UNARY_MINUS, UNARY_PLUS -> - r = (R) create((UnaryTree) tree, parentTree, JTUnary::new); - case BLOCK -> r = (R) create((BlockTree) tree, parentTree, JTBlock::new); - case BREAK -> r = (R) create((BreakTree) tree, parentTree, JTBreak::new); - case CASE -> r = (R) create((CaseTree) tree, parentTree, JTCase::new); - case CATCH -> r = (R) create((CatchTree) tree, parentTree, JTCatch::new); - case CONDITIONAL_EXPRESSION -> - r = (R) create((ConditionalExpressionTree) tree, parentTree, JTConditional::new); - case CONTINUE -> r = (R) create((ContinueTree) tree, parentTree, JTContinue::new); - case DEFAULT_CASE_LABEL -> - r = (R) create((DefaultCaseLabelTree) tree, parentTree, JTDefaultCaseLabel::new); - case DO_WHILE_LOOP -> r = (R) create((DoWhileLoopTree) tree, parentTree, JTDoWhileLoop::new); - case EMPTY_STATEMENT -> r = (R) create((EmptyStatementTree) tree, parentTree, JTSkip::new); - case ENHANCED_FOR_LOOP -> - r = (R) create((EnhancedForLoopTree) tree, parentTree, JTEnhancedForLoop::new); - case ERRONEOUS -> r = (R) create((ErroneousTree) tree, parentTree, JTErroneous::new); - case EXPORTS -> r = (R) create((ExportsTree) tree, parentTree, JTExports::new); - case EXPRESSION_STATEMENT -> - r = (R) create((ExpressionStatementTree) tree, parentTree, JTExpressionStatement::new); - case EXTENDS_WILDCARD, SUPER_WILDCARD, UNBOUNDED_WILDCARD -> - r = (R) create((WildcardTree) tree, parentTree, JTWildcard::new); - case FOR_LOOP -> r = (R) create((ForLoopTree) tree, parentTree, JTForLoop::new); - case GUARDED_PATTERN -> - r = (R) create((GuardedPatternTree) tree, parentTree, JTGuardedPattern::new); - case IDENTIFIER -> r = (R) create((IdentifierTree) tree, parentTree, JTIdent::new); - case IF -> r = (R) create((IfTree) tree, parentTree, JTIf::new); - case IMPORT -> r = (R) create((ImportTree) tree, parentTree, JTImport::new); - case INSTANCE_OF -> r = (R) create((InstanceOfTree) tree, parentTree, JTInstanceOf::new); - case INT_LITERAL, LONG_LITERAL, FLOAT_LITERAL, DOUBLE_LITERAL, - BOOLEAN_LITERAL, CHAR_LITERAL, STRING_LITERAL, NULL_LITERAL -> - r = (R) create((LiteralTree) tree, parentTree, JTLiteral::new); - case INTERSECTION_TYPE -> - r = (R) create((IntersectionTypeTree) tree, parentTree, JTTypeIntersection::new); - case LABELED_STATEMENT -> - r = (R) create((LabeledStatementTree) tree, parentTree, JTLabeledStatement::new); - case LAMBDA_EXPRESSION -> r = (R) create((LambdaExpressionTree) tree, parentTree, JTLambda::new); - case MEMBER_REFERENCE -> - r = (R) create((MemberReferenceTree) tree, parentTree, JTMemberReference::new); - case MEMBER_SELECT -> r = (R) create((MemberSelectTree) tree, parentTree, JTFieldAccess::new); - case METHOD -> r = (R) create((MethodTree) tree, parentTree, JTMethodDecl::new); - case METHOD_INVOCATION -> - r = (R) create((MethodInvocationTree) tree, parentTree, JTMethodInvocation::new); - case MODIFIERS -> r = (R) create((ModifiersTree) tree, parentTree, JTModifiers::new); - case NEW_ARRAY -> r = (R) create((NewArrayTree) tree, parentTree, JTNewArray::new); - case NEW_CLASS -> r = (R) create((NewClassTree) tree, parentTree, JTNewClass::new); - case OPENS -> r = (R) create((OpensTree) tree, parentTree, JTOpens::new); - case PARAMETERIZED_TYPE -> - r = (R) create((ParameterizedTypeTree) tree, parentTree, JTTypeApply::new); - case PARENTHESIZED -> r = (R) create((ParenthesizedTree) tree, parentTree, JTParens::new); - case PARENTHESIZED_PATTERN -> - r = (R) create((ParenthesizedPatternTree) tree, parentTree, JTParenthesizedPattern::new); - case PRIMITIVE_TYPE -> r = (R) create((PrimitiveTypeTree) tree, parentTree, JTPrimitiveType::new); - case PROVIDES -> r = (R) create((ProvidesTree) tree, parentTree, JTProvides::new); - case RETURN -> r = (R) create((ReturnTree) tree, parentTree, JTReturn::new); - case REQUIRES -> r = (R) create((RequiresTree) tree, parentTree, JTRequires::new); - case SWITCH -> r = (R) create((SwitchTree) tree, parentTree, JTSwitch::new); - case SWITCH_EXPRESSION -> - r = (R) create((SwitchExpressionTree) tree, parentTree, JTSwitchExpression::new); - case SYNCHRONIZED -> r = (R) create((SynchronizedTree) tree, parentTree, JTSynchronized::new); - case THROW -> r = (R) create((ThrowTree) tree, parentTree, JTThrow::new); - case TRY -> r = (R) create((TryTree) tree, parentTree, JTTry::new); - case TYPE_CAST -> r = (R) create((TypeCastTree) tree, parentTree, JTTypeCast::new); - case UNION_TYPE -> r = (R) create((UnionTypeTree) tree, parentTree, JTTypeUnion::new); - case USES -> r = (R) create((UsesTree) tree, parentTree, JTUses::new); - case VARIABLE -> r = (R) create((VariableTree) tree, parentTree, JTVariableDecl::new); - case WHILE_LOOP -> r = (R) create((WhileLoopTree) tree, parentTree, JTWhileLoop::new); - case YIELD -> r = (R) create((YieldTree) tree, parentTree, JTYield::new); - default -> { - parentTree.getCompilationUnit().incrementUnsupportedTreeCount(); - logger.warn( - "Type {} and kind {} is not supported in [{}].\n{}", - tree.getClass().getName(), - tree.getKind().name(), - parentTree.getCompilationUnit().getSourceFile().getName(), - tree); - } - } - } catch (Throwable t) { - logger.error( - "Failed to create [{}] for [{}].", - tree.getKind().name(), - parentTree.getCompilationUnit().getSourceFile().getName()); - throw t; - } - } - return r; - } - - public static > void createAndAdd( - List trees, - JTTree parentTree, - BiFunction, R> constructor, - Consumer consumer) { - if (CollectionUtils.isNotEmpty(trees)) { - trees.stream() - .filter(Objects::nonNull) - .map(o -> constructor.apply(o, parentTree)) - .filter(Objects::nonNull) - .map(o -> (R) o.analyze()) - .forEach(consumer); - } - } - - public static > void createAndAdd( - List trees, - JTTree parentTree, - Consumer consumer) { - createAndAddWithoutAnalyze(trees, parentTree, JTTreeFactory::create, consumer); - } - - public static > void createAndAddWithoutAnalyze( - List trees, - JTTree parentTree, - BiFunction, R> constructor, - Consumer consumer) { - if (CollectionUtils.isNotEmpty(trees)) { - trees.stream() - .filter(Objects::nonNull) - .map(o -> constructor.apply(o, parentTree)) - .filter(Objects::nonNull) - .forEach(consumer); - } - } - - public static JTFieldAccess createFieldAccess(String... strings) { - assert strings.length > 0 : "String array must not be empty."; - var jtFieldAccess = new JTFieldAccess(); - jtFieldAccess.setIdentifier(new JTName(strings[strings.length - 1])); - if (strings.length > 1) { - jtFieldAccess.setExpression(createFieldAccess(Arrays.copyOfRange(strings, 0, strings.length - 1))); - } - return jtFieldAccess; - } - - public static JTIdent createIdent(String name) { - return new JTIdent().setName(new JTName(name)); - } - - public static JTLiteral createLiteral(Object value) { - return new JTLiteral().setValue(value); - } - - public static JTName createName(Name name) { - return Optional.ofNullable(name) - .map(Object::toString) - .map(JTName::new) - .orElse(null); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.sun.source.tree.*; +import org.apache.commons.collections4.CollectionUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.lang.model.element.Name; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.function.BiFunction; +import java.util.function.Consumer; + +@SuppressWarnings({"unchecked", "preview"}) +public final class JTTreeFactory { + private static final Logger logger = LoggerFactory.getLogger(JTTreeFactory.class); + + private JTTreeFactory() { + } + + public static > R create( + T tree, + JTTree parentTree, + BiFunction, R> constructor) { + return Optional.ofNullable(tree) + .map(o -> constructor.apply(o, parentTree)) + .map(o -> (R) o.analyze()) + .orElse(null); + } + + public static > R create( + T tree, + JTTree parentTree) { + Objects.requireNonNull(parentTree); + R r = null; + if (tree != null) { + if (logger.isTraceEnabled()) { + String text = tree.toString(); + if (text.length() > 40) { + text = text.substring(0, 40) + " ..."; + } + text = text.replace("\n", "\\n").replace("\r", "\\r"); + logger.trace("Parsing [{}] [{}].", tree.getKind().name(), text); + } + try { + switch (tree.getKind()) { + case AND, CONDITIONAL_AND, CONDITIONAL_OR, DIVIDE, EQUAL_TO, + GREATER_THAN, GREATER_THAN_EQUAL, LEFT_SHIFT, LESS_THAN, LESS_THAN_EQUAL, + MINUS, MULTIPLY, NOT_EQUAL_TO, OR, PLUS, + REMAINDER, RIGHT_SHIFT, UNSIGNED_RIGHT_SHIFT, XOR -> + r = (R) create((BinaryTree) tree, parentTree, JTBinary::new); + case AND_ASSIGNMENT, DIVIDE_ASSIGNMENT, LEFT_SHIFT_ASSIGNMENT, MINUS_ASSIGNMENT, MULTIPLY_ASSIGNMENT, + OR_ASSIGNMENT, PLUS_ASSIGNMENT, REMAINDER_ASSIGNMENT, RIGHT_SHIFT_ASSIGNMENT, UNSIGNED_RIGHT_SHIFT_ASSIGNMENT, + XOR_ASSIGNMENT -> + r = (R) create((CompoundAssignmentTree) tree, parentTree, JTAssignOp::new); + case ANNOTATED_TYPE -> r = (R) create((AnnotatedTypeTree) tree, parentTree, JTAnnotatedType::new); + case ANNOTATION -> r = (R) create((AnnotationTree) tree, parentTree, JTAnnotation::new); + case ANNOTATION_TYPE, CLASS, ENUM, INTERFACE, RECORD -> + r = (R) create((ClassTree) tree, parentTree, JTClassDecl::new); + case ARRAY_ACCESS -> r = (R) create((ArrayAccessTree) tree, parentTree, JTArrayAccess::new); + case ARRAY_TYPE -> r = (R) create((ArrayTypeTree) tree, parentTree, JTArrayType::new); + case ASSERT -> r = (R) create((AssertTree) tree, parentTree, JTAssert::new); + case ASSIGNMENT -> r = (R) create((AssignmentTree) tree, parentTree, JTAssign::new); + case BINDING_PATTERN -> + r = (R) create((BindingPatternTree) tree, parentTree, JTBindingPattern::new); + case BITWISE_COMPLEMENT, LOGICAL_COMPLEMENT, POSTFIX_DECREMENT, POSTFIX_INCREMENT, PREFIX_DECREMENT, + PREFIX_INCREMENT, UNARY_MINUS, UNARY_PLUS -> + r = (R) create((UnaryTree) tree, parentTree, JTUnary::new); + case BLOCK -> r = (R) create((BlockTree) tree, parentTree, JTBlock::new); + case BREAK -> r = (R) create((BreakTree) tree, parentTree, JTBreak::new); + case CASE -> r = (R) create((CaseTree) tree, parentTree, JTCase::new); + case CATCH -> r = (R) create((CatchTree) tree, parentTree, JTCatch::new); + case CONDITIONAL_EXPRESSION -> + r = (R) create((ConditionalExpressionTree) tree, parentTree, JTConditional::new); + case CONTINUE -> r = (R) create((ContinueTree) tree, parentTree, JTContinue::new); + case DEFAULT_CASE_LABEL -> + r = (R) create((DefaultCaseLabelTree) tree, parentTree, JTDefaultCaseLabel::new); + case DO_WHILE_LOOP -> r = (R) create((DoWhileLoopTree) tree, parentTree, JTDoWhileLoop::new); + case EMPTY_STATEMENT -> r = (R) create((EmptyStatementTree) tree, parentTree, JTSkip::new); + case ENHANCED_FOR_LOOP -> + r = (R) create((EnhancedForLoopTree) tree, parentTree, JTEnhancedForLoop::new); + case ERRONEOUS -> r = (R) create((ErroneousTree) tree, parentTree, JTErroneous::new); + case EXPORTS -> r = (R) create((ExportsTree) tree, parentTree, JTExports::new); + case EXPRESSION_STATEMENT -> + r = (R) create((ExpressionStatementTree) tree, parentTree, JTExpressionStatement::new); + case EXTENDS_WILDCARD, SUPER_WILDCARD, UNBOUNDED_WILDCARD -> + r = (R) create((WildcardTree) tree, parentTree, JTWildcard::new); + case FOR_LOOP -> r = (R) create((ForLoopTree) tree, parentTree, JTForLoop::new); + case GUARDED_PATTERN -> + r = (R) create((GuardedPatternTree) tree, parentTree, JTGuardedPattern::new); + case IDENTIFIER -> r = (R) create((IdentifierTree) tree, parentTree, JTIdent::new); + case IF -> r = (R) create((IfTree) tree, parentTree, JTIf::new); + case IMPORT -> r = (R) create((ImportTree) tree, parentTree, JTImport::new); + case INSTANCE_OF -> r = (R) create((InstanceOfTree) tree, parentTree, JTInstanceOf::new); + case INT_LITERAL, LONG_LITERAL, FLOAT_LITERAL, DOUBLE_LITERAL, + BOOLEAN_LITERAL, CHAR_LITERAL, STRING_LITERAL, NULL_LITERAL -> + r = (R) create((LiteralTree) tree, parentTree, JTLiteral::new); + case INTERSECTION_TYPE -> + r = (R) create((IntersectionTypeTree) tree, parentTree, JTTypeIntersection::new); + case LABELED_STATEMENT -> + r = (R) create((LabeledStatementTree) tree, parentTree, JTLabeledStatement::new); + case LAMBDA_EXPRESSION -> r = (R) create((LambdaExpressionTree) tree, parentTree, JTLambda::new); + case MEMBER_REFERENCE -> + r = (R) create((MemberReferenceTree) tree, parentTree, JTMemberReference::new); + case MEMBER_SELECT -> r = (R) create((MemberSelectTree) tree, parentTree, JTFieldAccess::new); + case METHOD -> r = (R) create((MethodTree) tree, parentTree, JTMethodDecl::new); + case METHOD_INVOCATION -> + r = (R) create((MethodInvocationTree) tree, parentTree, JTMethodInvocation::new); + case MODIFIERS -> r = (R) create((ModifiersTree) tree, parentTree, JTModifiers::new); + case NEW_ARRAY -> r = (R) create((NewArrayTree) tree, parentTree, JTNewArray::new); + case NEW_CLASS -> r = (R) create((NewClassTree) tree, parentTree, JTNewClass::new); + case OPENS -> r = (R) create((OpensTree) tree, parentTree, JTOpens::new); + case PARAMETERIZED_TYPE -> + r = (R) create((ParameterizedTypeTree) tree, parentTree, JTTypeApply::new); + case PARENTHESIZED -> r = (R) create((ParenthesizedTree) tree, parentTree, JTParens::new); + case PARENTHESIZED_PATTERN -> + r = (R) create((ParenthesizedPatternTree) tree, parentTree, JTParenthesizedPattern::new); + case PRIMITIVE_TYPE -> r = (R) create((PrimitiveTypeTree) tree, parentTree, JTPrimitiveType::new); + case PROVIDES -> r = (R) create((ProvidesTree) tree, parentTree, JTProvides::new); + case RETURN -> r = (R) create((ReturnTree) tree, parentTree, JTReturn::new); + case REQUIRES -> r = (R) create((RequiresTree) tree, parentTree, JTRequires::new); + case SWITCH -> r = (R) create((SwitchTree) tree, parentTree, JTSwitch::new); + case SWITCH_EXPRESSION -> + r = (R) create((SwitchExpressionTree) tree, parentTree, JTSwitchExpression::new); + case SYNCHRONIZED -> r = (R) create((SynchronizedTree) tree, parentTree, JTSynchronized::new); + case THROW -> r = (R) create((ThrowTree) tree, parentTree, JTThrow::new); + case TRY -> r = (R) create((TryTree) tree, parentTree, JTTry::new); + case TYPE_CAST -> r = (R) create((TypeCastTree) tree, parentTree, JTTypeCast::new); + case UNION_TYPE -> r = (R) create((UnionTypeTree) tree, parentTree, JTTypeUnion::new); + case USES -> r = (R) create((UsesTree) tree, parentTree, JTUses::new); + case VARIABLE -> r = (R) create((VariableTree) tree, parentTree, JTVariableDecl::new); + case WHILE_LOOP -> r = (R) create((WhileLoopTree) tree, parentTree, JTWhileLoop::new); + case YIELD -> r = (R) create((YieldTree) tree, parentTree, JTYield::new); + default -> { + parentTree.getCompilationUnit().incrementUnsupportedTreeCount(); + logger.warn( + "Type {} and kind {} is not supported in [{}].\n{}", + tree.getClass().getName(), + tree.getKind().name(), + parentTree.getCompilationUnit().getSourceFile().getName(), + tree); + } + } + } catch (Throwable t) { + logger.error( + "Failed to create [{}] for [{}].", + tree.getKind().name(), + parentTree.getCompilationUnit().getSourceFile().getName()); + throw t; + } + } + return r; + } + + public static > void createAndAdd( + List trees, + JTTree parentTree, + BiFunction, R> constructor, + Consumer consumer) { + if (CollectionUtils.isNotEmpty(trees)) { + trees.stream() + .filter(Objects::nonNull) + .map(o -> constructor.apply(o, parentTree)) + .filter(Objects::nonNull) + .map(o -> (R) o.analyze()) + .forEach(consumer); + } + } + + public static > void createAndAdd( + List trees, + JTTree parentTree, + Consumer consumer) { + createAndAddWithoutAnalyze(trees, parentTree, JTTreeFactory::create, consumer); + } + + public static > void createAndAddWithoutAnalyze( + List trees, + JTTree parentTree, + BiFunction, R> constructor, + Consumer consumer) { + if (CollectionUtils.isNotEmpty(trees)) { + trees.stream() + .filter(Objects::nonNull) + .map(o -> constructor.apply(o, parentTree)) + .filter(Objects::nonNull) + .forEach(consumer); + } + } + + public static JTFieldAccess createFieldAccess(String... strings) { + assert strings.length > 0 : "String array must not be empty."; + var jtFieldAccess = new JTFieldAccess(); + jtFieldAccess.setIdentifier(new JTName(strings[strings.length - 1])); + if (strings.length > 1) { + jtFieldAccess.setExpression(createFieldAccess(Arrays.copyOfRange(strings, 0, strings.length - 1))); + } + return jtFieldAccess; + } + + public static JTIdent createIdent(String name) { + return new JTIdent().setName(new JTName(name)); + } + + public static JTLiteral createLiteral(Object value) { + return new JTLiteral().setValue(value); + } + + public static JTName createName(Name name) { + return Optional.ofNullable(name) + .map(Object::toString) + .map(JTName::new) + .orElse(null); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTTry.java b/src/main/java/com/caoccao/jaspiler/trees/JTTry.java index c9485a3..65d0293 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTTry.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTTry.java @@ -1,146 +1,146 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.sun.source.tree.TreeVisitor; -import com.sun.source.tree.TryTree; - -import java.util.*; - -public final class JTTry - extends JTStatement - implements TryTree { - private static final String PROPERTY_BLOCK = "block"; - private static final String PROPERTY_CATCHES = "catches"; - private static final String PROPERTY_FINALLY_BLOCK = "finallyBlock"; - private static final String PROPERTY_RESOURCES = "resources"; - private final List catches; - private final List> resources; - private JTBlock block; - private JTBlock finallyBlock; - - public JTTry() { - this(null, null); - setActionChange(); - } - - JTTry(TryTree tryTree, JTTree parentTree) { - super(tryTree, parentTree); - block = null; - catches = new ArrayList<>(); - finallyBlock = null; - resources = new ArrayList<>(); - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitTry(this, data); - } - - @Override - JTTry analyze() { - super.analyze(); - JTTreeFactory.createAndAdd(getOriginalTree().getResources(), this, resources::add); - block = JTTreeFactory.create( - getOriginalTree().getBlock(), this, JTBlock::new); - JTTreeFactory.createAndAdd( - getOriginalTree().getCatches(), this, JTCatch::new, catches::add); - finallyBlock = JTTreeFactory.create( - getOriginalTree().getFinallyBlock(), this, JTBlock::new); - return this; - } - - @Override - List> getAllNodes() { - var nodes = super.getAllNodes(); - resources.stream().filter(Objects::nonNull).forEach(nodes::add); - Optional.ofNullable(block).ifPresent(nodes::add); - catches.stream().filter(Objects::nonNull).forEach(nodes::add); - Optional.ofNullable(finallyBlock).ifPresent(nodes::add); - nodes.forEach(node -> node.setParentTree(this)); - return nodes; - } - - @Override - public JTBlock getBlock() { - return block; - } - - @Override - public List getCatches() { - return catches; - } - - @Override - public JTBlock getFinallyBlock() { - return finallyBlock; - } - - @Override - public Kind getKind() { - return Kind.TRY; - } - - @Override - public List> getResources() { - return resources; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_BLOCK, propertyName -> v8Runtime.toV8Value(getBlock())); - registerStringGetter(PROPERTY_CATCHES, propertyName -> v8Runtime.toV8Value(getCatches())); - registerStringGetter(PROPERTY_FINALLY_BLOCK, propertyName -> v8Runtime.toV8Value(getFinallyBlock())); - registerStringGetter(PROPERTY_RESOURCES, propertyName -> v8Runtime.toV8Value(getResources())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_BLOCK, (propertyName, propertyValue) -> replaceBlock(this::setBlock, propertyValue)); - registerStringSetter(PROPERTY_CATCHES, (propertyName, propertyValue) -> replaceCatches(catches, propertyValue)); - registerStringSetter(PROPERTY_FINALLY_BLOCK, (propertyName, propertyValue) -> replaceBlock(this::setFinallyBlock, propertyValue)); - registerStringSetter(PROPERTY_RESOURCES, (propertyName, propertyValue) -> replaceTrees(resources, propertyValue)); - } - return stringSetterMap; - } - - public JTTry setBlock(JTBlock block) { - if (this.block == block) { - return this; - } - this.block = Objects.requireNonNull(block).setParentTree(this); - return setActionChange(); - } - - public JTTry setFinallyBlock(JTBlock finallyBlock) { - if (this.finallyBlock == finallyBlock) { - return this; - } - this.finallyBlock = Optional.ofNullable(finallyBlock).map(o -> o.setParentTree(this)).orElse(null); - return setActionChange(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.sun.source.tree.TreeVisitor; +import com.sun.source.tree.TryTree; + +import java.util.*; + +public final class JTTry + extends JTStatement + implements TryTree { + private static final String PROPERTY_BLOCK = "block"; + private static final String PROPERTY_CATCHES = "catches"; + private static final String PROPERTY_FINALLY_BLOCK = "finallyBlock"; + private static final String PROPERTY_RESOURCES = "resources"; + private final List catches; + private final List> resources; + private JTBlock block; + private JTBlock finallyBlock; + + public JTTry() { + this(null, null); + setActionChange(); + } + + JTTry(TryTree tryTree, JTTree parentTree) { + super(tryTree, parentTree); + block = null; + catches = new ArrayList<>(); + finallyBlock = null; + resources = new ArrayList<>(); + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitTry(this, data); + } + + @Override + JTTry analyze() { + super.analyze(); + JTTreeFactory.createAndAdd(getOriginalTree().getResources(), this, resources::add); + block = JTTreeFactory.create( + getOriginalTree().getBlock(), this, JTBlock::new); + JTTreeFactory.createAndAdd( + getOriginalTree().getCatches(), this, JTCatch::new, catches::add); + finallyBlock = JTTreeFactory.create( + getOriginalTree().getFinallyBlock(), this, JTBlock::new); + return this; + } + + @Override + List> getAllNodes() { + var nodes = super.getAllNodes(); + resources.stream().filter(Objects::nonNull).forEach(nodes::add); + Optional.ofNullable(block).ifPresent(nodes::add); + catches.stream().filter(Objects::nonNull).forEach(nodes::add); + Optional.ofNullable(finallyBlock).ifPresent(nodes::add); + nodes.forEach(node -> node.setParentTree(this)); + return nodes; + } + + @Override + public JTBlock getBlock() { + return block; + } + + @Override + public List getCatches() { + return catches; + } + + @Override + public JTBlock getFinallyBlock() { + return finallyBlock; + } + + @Override + public Kind getKind() { + return Kind.TRY; + } + + @Override + public List> getResources() { + return resources; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_BLOCK, propertyName -> v8Runtime.toV8Value(getBlock())); + registerStringGetter(PROPERTY_CATCHES, propertyName -> v8Runtime.toV8Value(getCatches())); + registerStringGetter(PROPERTY_FINALLY_BLOCK, propertyName -> v8Runtime.toV8Value(getFinallyBlock())); + registerStringGetter(PROPERTY_RESOURCES, propertyName -> v8Runtime.toV8Value(getResources())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_BLOCK, (propertyName, propertyValue) -> replaceBlock(this::setBlock, propertyValue)); + registerStringSetter(PROPERTY_CATCHES, (propertyName, propertyValue) -> replaceCatches(catches, propertyValue)); + registerStringSetter(PROPERTY_FINALLY_BLOCK, (propertyName, propertyValue) -> replaceBlock(this::setFinallyBlock, propertyValue)); + registerStringSetter(PROPERTY_RESOURCES, (propertyName, propertyValue) -> replaceTrees(resources, propertyValue)); + } + return stringSetterMap; + } + + public JTTry setBlock(JTBlock block) { + if (this.block == block) { + return this; + } + this.block = Objects.requireNonNull(block).setParentTree(this); + return setActionChange(); + } + + public JTTry setFinallyBlock(JTBlock finallyBlock) { + if (this.finallyBlock == finallyBlock) { + return this; + } + this.finallyBlock = Optional.ofNullable(finallyBlock).map(o -> o.setParentTree(this)).orElse(null); + return setActionChange(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTTypeApply.java b/src/main/java/com/caoccao/jaspiler/trees/JTTypeApply.java index 0ce649a..2c5a42a 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTTypeApply.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTTypeApply.java @@ -1,113 +1,113 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.sun.source.tree.ParameterizedTypeTree; -import com.sun.source.tree.Tree; -import com.sun.source.tree.TreeVisitor; - -import java.util.*; - -public final class JTTypeApply - extends JTExpression - implements ParameterizedTypeTree { - private static final String PROPERTY_TYPE = "type"; - private static final String PROPERTY_TYPE_ARGUMENTS = "typeArguments"; - private final List> typeArguments; - private JTExpression type; - - public JTTypeApply() { - this(null, null); - setActionChange(); - } - - JTTypeApply(ParameterizedTypeTree parameterizedTypeTree, JTTree parentTree) { - super(parameterizedTypeTree, parentTree); - typeArguments = new ArrayList<>(); - type = null; - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitParameterizedType(this, data); - } - - @Override - JTTypeApply analyze() { - super.analyze(); - type = JTTreeFactory.create(getOriginalTree().getType(), this); - JTTreeFactory.createAndAdd( - getOriginalTree().getTypeArguments(), this, (JTExpression o) -> typeArguments.add(o)); - return this; - } - - @Override - List> getAllNodes() { - var nodes = super.getAllNodes(); - Optional.ofNullable(type).ifPresent(nodes::add); - typeArguments.stream().filter(Objects::nonNull).forEach(nodes::add); - nodes.forEach(node -> node.setParentTree(this)); - return nodes; - } - - @Override - public Kind getKind() { - return Kind.PARAMETERIZED_TYPE; - } - - @Override - public Tree getType() { - return type; - } - - @Override - public List> getTypeArguments() { - return typeArguments; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_TYPE, propertyName -> v8Runtime.toV8Value(getType())); - registerStringGetter(PROPERTY_TYPE_ARGUMENTS, propertyName -> v8Runtime.toV8Value(getTypeArguments())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_TYPE, (propertyName, propertyValue) -> replaceExpression(this::setType, propertyValue)); - registerStringSetter(PROPERTY_TYPE_ARGUMENTS, (propertyName, propertyValue) -> replaceExpressions(typeArguments, propertyValue)); - } - return stringSetterMap; - } - - public JTTypeApply setType(JTExpression type) { - if (this.type == type) { - return this; - } - this.type = Objects.requireNonNull(type).setParentTree(this); - return setActionChange(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.sun.source.tree.ParameterizedTypeTree; +import com.sun.source.tree.Tree; +import com.sun.source.tree.TreeVisitor; + +import java.util.*; + +public final class JTTypeApply + extends JTExpression + implements ParameterizedTypeTree { + private static final String PROPERTY_TYPE = "type"; + private static final String PROPERTY_TYPE_ARGUMENTS = "typeArguments"; + private final List> typeArguments; + private JTExpression type; + + public JTTypeApply() { + this(null, null); + setActionChange(); + } + + JTTypeApply(ParameterizedTypeTree parameterizedTypeTree, JTTree parentTree) { + super(parameterizedTypeTree, parentTree); + typeArguments = new ArrayList<>(); + type = null; + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitParameterizedType(this, data); + } + + @Override + JTTypeApply analyze() { + super.analyze(); + type = JTTreeFactory.create(getOriginalTree().getType(), this); + JTTreeFactory.createAndAdd( + getOriginalTree().getTypeArguments(), this, (JTExpression o) -> typeArguments.add(o)); + return this; + } + + @Override + List> getAllNodes() { + var nodes = super.getAllNodes(); + Optional.ofNullable(type).ifPresent(nodes::add); + typeArguments.stream().filter(Objects::nonNull).forEach(nodes::add); + nodes.forEach(node -> node.setParentTree(this)); + return nodes; + } + + @Override + public Kind getKind() { + return Kind.PARAMETERIZED_TYPE; + } + + @Override + public Tree getType() { + return type; + } + + @Override + public List> getTypeArguments() { + return typeArguments; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_TYPE, propertyName -> v8Runtime.toV8Value(getType())); + registerStringGetter(PROPERTY_TYPE_ARGUMENTS, propertyName -> v8Runtime.toV8Value(getTypeArguments())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_TYPE, (propertyName, propertyValue) -> replaceExpression(this::setType, propertyValue)); + registerStringSetter(PROPERTY_TYPE_ARGUMENTS, (propertyName, propertyValue) -> replaceExpressions(typeArguments, propertyValue)); + } + return stringSetterMap; + } + + public JTTypeApply setType(JTExpression type) { + if (this.type == type) { + return this; + } + this.type = Objects.requireNonNull(type).setParentTree(this); + return setActionChange(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTTypeCast.java b/src/main/java/com/caoccao/jaspiler/trees/JTTypeCast.java index c4fddea..59b7492 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTTypeCast.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTTypeCast.java @@ -1,122 +1,122 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.sun.source.tree.TreeVisitor; -import com.sun.source.tree.TypeCastTree; - -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -public final class JTTypeCast - extends JTExpression - implements TypeCastTree { - private static final String PROPERTY_EXPRESSION = "expression"; - private static final String PROPERTY_TYPE = "type"; - private JTExpression expression; - private JTTree type; - - public JTTypeCast() { - this(null, null); - setActionChange(); - } - - JTTypeCast(TypeCastTree typeCastTree, JTTree parentTree) { - super(typeCastTree, parentTree); - expression = null; - type = null; - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitTypeCast(this, data); - } - - @Override - JTTypeCast analyze() { - super.analyze(); - type = JTTreeFactory.create(getOriginalTree().getType(), this); - expression = JTTreeFactory.create(getOriginalTree().getExpression(), this); - return this; - } - - @Override - List> getAllNodes() { - var nodes = super.getAllNodes(); - Optional.ofNullable(type).ifPresent(nodes::add); - Optional.ofNullable(expression).ifPresent(nodes::add); - nodes.forEach(node -> node.setParentTree(this)); - return nodes; - } - - @Override - public JTExpression getExpression() { - return expression; - } - - @Override - public Kind getKind() { - return Kind.TYPE_CAST; - } - - @Override - public JTTree getType() { - return type; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_EXPRESSION, propertyName -> v8Runtime.toV8Value(getExpression())); - registerStringGetter(PROPERTY_TYPE, propertyName -> v8Runtime.toV8Value(getType())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_EXPRESSION, (propertyName, propertyValue) -> replaceExpression(this::setExpression, propertyValue)); - registerStringSetter(PROPERTY_TYPE, (propertyName, propertyValue) -> replaceTree(this::setType, propertyValue)); - } - return stringSetterMap; - } - - public JTTypeCast setExpression(JTExpression expression) { - if (this.expression == expression) { - return this; - } - this.expression = Objects.requireNonNull(expression).setParentTree(this); - return setActionChange(); - } - - public JTTypeCast setType(JTTree type) { - if (this.type == type) { - return this; - } - this.type = Objects.requireNonNull(type).setParentTree(this); - return setActionChange(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.sun.source.tree.TreeVisitor; +import com.sun.source.tree.TypeCastTree; + +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +public final class JTTypeCast + extends JTExpression + implements TypeCastTree { + private static final String PROPERTY_EXPRESSION = "expression"; + private static final String PROPERTY_TYPE = "type"; + private JTExpression expression; + private JTTree type; + + public JTTypeCast() { + this(null, null); + setActionChange(); + } + + JTTypeCast(TypeCastTree typeCastTree, JTTree parentTree) { + super(typeCastTree, parentTree); + expression = null; + type = null; + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitTypeCast(this, data); + } + + @Override + JTTypeCast analyze() { + super.analyze(); + type = JTTreeFactory.create(getOriginalTree().getType(), this); + expression = JTTreeFactory.create(getOriginalTree().getExpression(), this); + return this; + } + + @Override + List> getAllNodes() { + var nodes = super.getAllNodes(); + Optional.ofNullable(type).ifPresent(nodes::add); + Optional.ofNullable(expression).ifPresent(nodes::add); + nodes.forEach(node -> node.setParentTree(this)); + return nodes; + } + + @Override + public JTExpression getExpression() { + return expression; + } + + @Override + public Kind getKind() { + return Kind.TYPE_CAST; + } + + @Override + public JTTree getType() { + return type; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_EXPRESSION, propertyName -> v8Runtime.toV8Value(getExpression())); + registerStringGetter(PROPERTY_TYPE, propertyName -> v8Runtime.toV8Value(getType())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_EXPRESSION, (propertyName, propertyValue) -> replaceExpression(this::setExpression, propertyValue)); + registerStringSetter(PROPERTY_TYPE, (propertyName, propertyValue) -> replaceTree(this::setType, propertyValue)); + } + return stringSetterMap; + } + + public JTTypeCast setExpression(JTExpression expression) { + if (this.expression == expression) { + return this; + } + this.expression = Objects.requireNonNull(expression).setParentTree(this); + return setActionChange(); + } + + public JTTypeCast setType(JTTree type) { + if (this.type == type) { + return this; + } + this.type = Objects.requireNonNull(type).setParentTree(this); + return setActionChange(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTTypeIntersection.java b/src/main/java/com/caoccao/jaspiler/trees/JTTypeIntersection.java index 578d772..ffcc79b 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTTypeIntersection.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTTypeIntersection.java @@ -1,95 +1,95 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.sun.source.tree.IntersectionTypeTree; -import com.sun.source.tree.TreeVisitor; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -public final class JTTypeIntersection - extends JTExpression - implements IntersectionTypeTree { - private static final String PROPERTY_BOUNDS = "bounds"; - private final List> bounds; - - public JTTypeIntersection() { - this(null, null); - setActionChange(); - } - - JTTypeIntersection(IntersectionTypeTree intersectionTypeTree, JTTree parentTree) { - super(intersectionTypeTree, parentTree); - bounds = new ArrayList<>(); - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitIntersectionType(this, data); - } - - @Override - JTTypeIntersection analyze() { - super.analyze(); - JTTreeFactory.createAndAdd( - getOriginalTree().getBounds(), this, (JTExpression o) -> bounds.add(o)); - return this; - } - - @Override - List> getAllNodes() { - var nodes = super.getAllNodes(); - bounds.stream().filter(Objects::nonNull).forEach(nodes::add); - nodes.forEach(node -> node.setParentTree(this)); - return nodes; - } - - @Override - public List> getBounds() { - return bounds; - } - - @Override - public Kind getKind() { - return Kind.INTERSECTION_TYPE; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_BOUNDS, propertyName -> v8Runtime.toV8Value(getBounds())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_BOUNDS, (propertyName, propertyValue) -> replaceExpressions(bounds, propertyValue)); - } - return stringSetterMap; - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.sun.source.tree.IntersectionTypeTree; +import com.sun.source.tree.TreeVisitor; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +public final class JTTypeIntersection + extends JTExpression + implements IntersectionTypeTree { + private static final String PROPERTY_BOUNDS = "bounds"; + private final List> bounds; + + public JTTypeIntersection() { + this(null, null); + setActionChange(); + } + + JTTypeIntersection(IntersectionTypeTree intersectionTypeTree, JTTree parentTree) { + super(intersectionTypeTree, parentTree); + bounds = new ArrayList<>(); + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitIntersectionType(this, data); + } + + @Override + JTTypeIntersection analyze() { + super.analyze(); + JTTreeFactory.createAndAdd( + getOriginalTree().getBounds(), this, (JTExpression o) -> bounds.add(o)); + return this; + } + + @Override + List> getAllNodes() { + var nodes = super.getAllNodes(); + bounds.stream().filter(Objects::nonNull).forEach(nodes::add); + nodes.forEach(node -> node.setParentTree(this)); + return nodes; + } + + @Override + public List> getBounds() { + return bounds; + } + + @Override + public Kind getKind() { + return Kind.INTERSECTION_TYPE; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_BOUNDS, propertyName -> v8Runtime.toV8Value(getBounds())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_BOUNDS, (propertyName, propertyValue) -> replaceExpressions(bounds, propertyValue)); + } + return stringSetterMap; + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTTypeParameter.java b/src/main/java/com/caoccao/jaspiler/trees/JTTypeParameter.java index 21e6ffd..e081b1c 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTTypeParameter.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTTypeParameter.java @@ -1,126 +1,126 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.sun.source.tree.TreeVisitor; -import com.sun.source.tree.TypeParameterTree; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -public final class JTTypeParameter - extends JTTree - implements TypeParameterTree, IJTAnnotatable { - private static final String PROPERTY_BOUNDS = "bounds"; - private static final String PROPERTY_NAME = "name"; - private final List annotations; - private final List> bounds; - private JTName name; - - public JTTypeParameter() { - this(null, null); - setActionChange(); - } - - JTTypeParameter(TypeParameterTree typeParameterTree, JTTree parentTree) { - super(typeParameterTree, parentTree); - annotations = new ArrayList<>(); - bounds = new ArrayList<>(); - name = null; - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitTypeParameter(this, data); - } - - @Override - JTTypeParameter analyze() { - super.analyze(); - JTTreeFactory.createAndAdd( - getOriginalTree().getAnnotations(), this, JTAnnotation::new, annotations::add); - name = JTTreeFactory.createName(getOriginalTree().getName()); - JTTreeFactory.createAndAdd( - getOriginalTree().getBounds(), this, (JTExpression o) -> bounds.add(o)); - return this; - } - - @Override - List> getAllNodes() { - var nodes = super.getAllNodes(); - annotations.stream().filter(Objects::nonNull).forEach(nodes::add); - bounds.stream().filter(Objects::nonNull).forEach(nodes::add); - nodes.forEach(node -> node.setParentTree(this)); - return nodes; - } - - @Override - public List getAnnotations() { - return annotations; - } - - @Override - public List> getBounds() { - return bounds; - } - - @Override - public Kind getKind() { - return Kind.TYPE_PARAMETER; - } - - @Override - public JTName getName() { - return name; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_ANNOTATIONS, propertyName -> v8Runtime.toV8Value(getAnnotations())); - registerStringGetter(PROPERTY_BOUNDS, propertyName -> v8Runtime.toV8Value(getBounds())); - registerStringGetter(PROPERTY_NAME, propertyName -> v8Runtime.toV8Value(getName())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_ANNOTATIONS, (propertyName, propertyValue) -> replaceAnnotations(annotations, propertyValue)); - registerStringSetter(PROPERTY_BOUNDS, (propertyName, propertyValue) -> replaceExpressions(bounds, propertyValue)); - registerStringSetter(PROPERTY_NAME, (propertyName, propertyValue) -> replaceName(this::setName, propertyValue)); - } - return stringSetterMap; - } - - public JTTypeParameter setName(JTName name) { - if (this.name == name) { - return this; - } - this.name = Objects.requireNonNull(name); - return setActionChange(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.sun.source.tree.TreeVisitor; +import com.sun.source.tree.TypeParameterTree; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +public final class JTTypeParameter + extends JTTree + implements TypeParameterTree, IJTAnnotatable { + private static final String PROPERTY_BOUNDS = "bounds"; + private static final String PROPERTY_NAME = "name"; + private final List annotations; + private final List> bounds; + private JTName name; + + public JTTypeParameter() { + this(null, null); + setActionChange(); + } + + JTTypeParameter(TypeParameterTree typeParameterTree, JTTree parentTree) { + super(typeParameterTree, parentTree); + annotations = new ArrayList<>(); + bounds = new ArrayList<>(); + name = null; + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitTypeParameter(this, data); + } + + @Override + JTTypeParameter analyze() { + super.analyze(); + JTTreeFactory.createAndAdd( + getOriginalTree().getAnnotations(), this, JTAnnotation::new, annotations::add); + name = JTTreeFactory.createName(getOriginalTree().getName()); + JTTreeFactory.createAndAdd( + getOriginalTree().getBounds(), this, (JTExpression o) -> bounds.add(o)); + return this; + } + + @Override + List> getAllNodes() { + var nodes = super.getAllNodes(); + annotations.stream().filter(Objects::nonNull).forEach(nodes::add); + bounds.stream().filter(Objects::nonNull).forEach(nodes::add); + nodes.forEach(node -> node.setParentTree(this)); + return nodes; + } + + @Override + public List getAnnotations() { + return annotations; + } + + @Override + public List> getBounds() { + return bounds; + } + + @Override + public Kind getKind() { + return Kind.TYPE_PARAMETER; + } + + @Override + public JTName getName() { + return name; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_ANNOTATIONS, propertyName -> v8Runtime.toV8Value(getAnnotations())); + registerStringGetter(PROPERTY_BOUNDS, propertyName -> v8Runtime.toV8Value(getBounds())); + registerStringGetter(PROPERTY_NAME, propertyName -> v8Runtime.toV8Value(getName())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_ANNOTATIONS, (propertyName, propertyValue) -> replaceAnnotations(annotations, propertyValue)); + registerStringSetter(PROPERTY_BOUNDS, (propertyName, propertyValue) -> replaceExpressions(bounds, propertyValue)); + registerStringSetter(PROPERTY_NAME, (propertyName, propertyValue) -> replaceName(this::setName, propertyValue)); + } + return stringSetterMap; + } + + public JTTypeParameter setName(JTName name) { + if (this.name == name) { + return this; + } + this.name = Objects.requireNonNull(name); + return setActionChange(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTTypeUnion.java b/src/main/java/com/caoccao/jaspiler/trees/JTTypeUnion.java index fe4b340..7165308 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTTypeUnion.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTTypeUnion.java @@ -1,95 +1,95 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.sun.source.tree.TreeVisitor; -import com.sun.source.tree.UnionTypeTree; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -public final class JTTypeUnion - extends JTExpression - implements UnionTypeTree { - private static final String PROPERTY_TYPE_ALTERNATIVES = "typeAlternatives"; - private final List> typeAlternatives; - - public JTTypeUnion() { - this(null, null); - setActionChange(); - } - - JTTypeUnion(UnionTypeTree unionTypeTree, JTTree parentTree) { - super(unionTypeTree, parentTree); - typeAlternatives = new ArrayList<>(); - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitUnionType(this, data); - } - - @Override - JTTypeUnion analyze() { - super.analyze(); - JTTreeFactory.createAndAdd( - getOriginalTree().getTypeAlternatives(), this, (JTExpression o) -> typeAlternatives.add(o)); - return this; - } - - @Override - List> getAllNodes() { - var nodes = super.getAllNodes(); - typeAlternatives.stream().filter(Objects::nonNull).forEach(nodes::add); - nodes.forEach(node -> node.setParentTree(this)); - return nodes; - } - - @Override - public Kind getKind() { - return Kind.UNION_TYPE; - } - - @Override - public List> getTypeAlternatives() { - return typeAlternatives; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_TYPE_ALTERNATIVES, propertyName -> v8Runtime.toV8Value(getTypeAlternatives())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_TYPE_ALTERNATIVES, (propertyName, propertyValue) -> replaceExpressions(typeAlternatives, propertyValue)); - } - return stringSetterMap; - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.sun.source.tree.TreeVisitor; +import com.sun.source.tree.UnionTypeTree; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +public final class JTTypeUnion + extends JTExpression + implements UnionTypeTree { + private static final String PROPERTY_TYPE_ALTERNATIVES = "typeAlternatives"; + private final List> typeAlternatives; + + public JTTypeUnion() { + this(null, null); + setActionChange(); + } + + JTTypeUnion(UnionTypeTree unionTypeTree, JTTree parentTree) { + super(unionTypeTree, parentTree); + typeAlternatives = new ArrayList<>(); + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitUnionType(this, data); + } + + @Override + JTTypeUnion analyze() { + super.analyze(); + JTTreeFactory.createAndAdd( + getOriginalTree().getTypeAlternatives(), this, (JTExpression o) -> typeAlternatives.add(o)); + return this; + } + + @Override + List> getAllNodes() { + var nodes = super.getAllNodes(); + typeAlternatives.stream().filter(Objects::nonNull).forEach(nodes::add); + nodes.forEach(node -> node.setParentTree(this)); + return nodes; + } + + @Override + public Kind getKind() { + return Kind.UNION_TYPE; + } + + @Override + public List> getTypeAlternatives() { + return typeAlternatives; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_TYPE_ALTERNATIVES, propertyName -> v8Runtime.toV8Value(getTypeAlternatives())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_TYPE_ALTERNATIVES, (propertyName, propertyValue) -> replaceExpressions(typeAlternatives, propertyValue)); + } + return stringSetterMap; + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTUnary.java b/src/main/java/com/caoccao/jaspiler/trees/JTUnary.java index 40874ad..e5f1901 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTUnary.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTUnary.java @@ -1,120 +1,120 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.jaspiler.exceptions.JaspilerNotSupportedException; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.sun.source.tree.TreeVisitor; -import com.sun.source.tree.UnaryTree; - -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -public final class JTUnary - extends JTOperatorExpression - implements UnaryTree { - private static final String PROPERTY_EXPRESSION = "expression"; - private static final String PROPERTY_KIND = "kind"; - private JTExpression expression; - private Kind kind; - - public JTUnary() { - this(null, null); - setActionChange(); - } - - JTUnary(UnaryTree unaryTree, JTTree parentTree) { - super(unaryTree, parentTree); - expression = null; - kind = null; - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitUnary(this, data); - } - - @Override - JTUnary analyze() { - super.analyze(); - expression = JTTreeFactory.create(getOriginalTree().getExpression(), this); - kind = getOriginalTree().getKind(); - return this; - } - - @Override - List> getAllNodes() { - var nodes = super.getAllNodes(); - Optional.ofNullable(expression).ifPresent(nodes::add); - nodes.forEach(node -> node.setParentTree(this)); - return nodes; - } - - @Override - public JTExpression getExpression() { - return expression; - } - - @Override - public Kind getKind() { - return kind; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_EXPRESSION, propertyName -> v8Runtime.toV8Value(getExpression())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_EXPRESSION, (propertyName, propertyValue) -> replaceExpression(this::setExpression, propertyValue)); - registerStringSetter(PROPERTY_KIND, (propertyName, propertyValue) -> replaceKind(this::setKind, propertyValue)); - } - return stringSetterMap; - } - - public JTUnary setExpression(JTExpression expression) { - if (this.expression == expression) { - return this; - } - this.expression = Objects.requireNonNull(expression).setParentTree(this); - return setActionChange(); - } - - public JTUnary setKind(Kind kind) { - if (this.kind == kind) { - return this; - } - switch (Objects.requireNonNull(kind)) { - case BITWISE_COMPLEMENT, LOGICAL_COMPLEMENT, POSTFIX_DECREMENT, POSTFIX_INCREMENT, PREFIX_DECREMENT, - PREFIX_INCREMENT, UNARY_MINUS, UNARY_PLUS -> this.kind = kind; - default -> throw new JaspilerNotSupportedException(kind.name() + " is not supported."); - } - return setActionChange(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.jaspiler.exceptions.JaspilerNotSupportedException; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.sun.source.tree.TreeVisitor; +import com.sun.source.tree.UnaryTree; + +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +public final class JTUnary + extends JTOperatorExpression + implements UnaryTree { + private static final String PROPERTY_EXPRESSION = "expression"; + private static final String PROPERTY_KIND = "kind"; + private JTExpression expression; + private Kind kind; + + public JTUnary() { + this(null, null); + setActionChange(); + } + + JTUnary(UnaryTree unaryTree, JTTree parentTree) { + super(unaryTree, parentTree); + expression = null; + kind = null; + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitUnary(this, data); + } + + @Override + JTUnary analyze() { + super.analyze(); + expression = JTTreeFactory.create(getOriginalTree().getExpression(), this); + kind = getOriginalTree().getKind(); + return this; + } + + @Override + List> getAllNodes() { + var nodes = super.getAllNodes(); + Optional.ofNullable(expression).ifPresent(nodes::add); + nodes.forEach(node -> node.setParentTree(this)); + return nodes; + } + + @Override + public JTExpression getExpression() { + return expression; + } + + @Override + public Kind getKind() { + return kind; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_EXPRESSION, propertyName -> v8Runtime.toV8Value(getExpression())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_EXPRESSION, (propertyName, propertyValue) -> replaceExpression(this::setExpression, propertyValue)); + registerStringSetter(PROPERTY_KIND, (propertyName, propertyValue) -> replaceKind(this::setKind, propertyValue)); + } + return stringSetterMap; + } + + public JTUnary setExpression(JTExpression expression) { + if (this.expression == expression) { + return this; + } + this.expression = Objects.requireNonNull(expression).setParentTree(this); + return setActionChange(); + } + + public JTUnary setKind(Kind kind) { + if (this.kind == kind) { + return this; + } + switch (Objects.requireNonNull(kind)) { + case BITWISE_COMPLEMENT, LOGICAL_COMPLEMENT, POSTFIX_DECREMENT, POSTFIX_INCREMENT, PREFIX_DECREMENT, + PREFIX_INCREMENT, UNARY_MINUS, UNARY_PLUS -> this.kind = kind; + default -> throw new JaspilerNotSupportedException(kind.name() + " is not supported."); + } + return setActionChange(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTUses.java b/src/main/java/com/caoccao/jaspiler/trees/JTUses.java index a60b4eb..da232f8 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTUses.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTUses.java @@ -1,102 +1,102 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.sun.source.tree.TreeVisitor; -import com.sun.source.tree.UsesTree; - -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -public final class JTUses - extends JTDirective - implements UsesTree { - private static final String PROPERTY_SERVICE_NAME = "serviceName"; - private JTExpression serviceName; - - public JTUses() { - this(null, null); - setActionChange(); - } - - JTUses(UsesTree usesTree, JTTree parentTree) { - super(usesTree, parentTree); - serviceName = null; - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitUses(this, data); - } - - @Override - JTUses analyze() { - super.analyze(); - serviceName = JTTreeFactory.create(getOriginalTree().getServiceName(), this); - return this; - } - - @Override - List> getAllNodes() { - var nodes = super.getAllNodes(); - Optional.ofNullable(serviceName).ifPresent(nodes::add); - nodes.forEach(node -> node.setParentTree(this)); - return nodes; - } - - @Override - public Kind getKind() { - return Kind.USES; - } - - @Override - public JTExpression getServiceName() { - return serviceName; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_SERVICE_NAME, propertyName -> v8Runtime.toV8Value(getServiceName())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_SERVICE_NAME, (propertyName, propertyValue) -> replaceExpression(this::setServiceName, propertyValue)); - } - return stringSetterMap; - } - - public JTUses setServiceName(JTExpression serviceName) { - if (this.serviceName == serviceName) { - return this; - } - this.serviceName = Objects.requireNonNull(serviceName).setParentTree(this); - return setActionChange(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.sun.source.tree.TreeVisitor; +import com.sun.source.tree.UsesTree; + +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +public final class JTUses + extends JTDirective + implements UsesTree { + private static final String PROPERTY_SERVICE_NAME = "serviceName"; + private JTExpression serviceName; + + public JTUses() { + this(null, null); + setActionChange(); + } + + JTUses(UsesTree usesTree, JTTree parentTree) { + super(usesTree, parentTree); + serviceName = null; + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitUses(this, data); + } + + @Override + JTUses analyze() { + super.analyze(); + serviceName = JTTreeFactory.create(getOriginalTree().getServiceName(), this); + return this; + } + + @Override + List> getAllNodes() { + var nodes = super.getAllNodes(); + Optional.ofNullable(serviceName).ifPresent(nodes::add); + nodes.forEach(node -> node.setParentTree(this)); + return nodes; + } + + @Override + public Kind getKind() { + return Kind.USES; + } + + @Override + public JTExpression getServiceName() { + return serviceName; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_SERVICE_NAME, propertyName -> v8Runtime.toV8Value(getServiceName())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_SERVICE_NAME, (propertyName, propertyValue) -> replaceExpression(this::setServiceName, propertyValue)); + } + return stringSetterMap; + } + + public JTUses setServiceName(JTExpression serviceName) { + if (this.serviceName == serviceName) { + return this; + } + this.serviceName = Objects.requireNonNull(serviceName).setParentTree(this); + return setActionChange(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTVariableDecl.java b/src/main/java/com/caoccao/jaspiler/trees/JTVariableDecl.java index 9b0f03e..e61150d 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTVariableDecl.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTVariableDecl.java @@ -1,208 +1,208 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.jaspiler.styles.IStyleWriter; -import com.caoccao.javet.exceptions.JavetException; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.sun.source.tree.TreeVisitor; -import com.sun.source.tree.VariableTree; - -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -public final class JTVariableDecl - extends JTStatement - implements VariableTree { - private static final String PROPERTY_INITIALIZER = "initializer"; - private static final String PROPERTY_MODIFIERS = "modifiers"; - private static final String PROPERTY_NAME = "name"; - private static final String PROPERTY_NAME_EXPRESSION = "nameExpression"; - private static final String PROPERTY_TYPE = "type"; - private JTExpression initializer; - private JTModifiers modifiers; - private JTName name; - private JTExpression nameExpression; - private JTExpression type; - - public JTVariableDecl() { - this(null, null); - setActionChange(); - } - - JTVariableDecl(VariableTree variableTree, JTTree parentTree) { - super(variableTree, parentTree); - initializer = null; - modifiers = null; - name = null; - nameExpression = null; - type = null; - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitVariable(this, data); - } - - @Override - JTVariableDecl analyze() { - super.analyze(); - modifiers = JTTreeFactory.create( - getOriginalTree().getModifiers(), this, JTModifiers::new); - type = JTTreeFactory.create(getOriginalTree().getType(), this); - nameExpression = JTTreeFactory.create(getOriginalTree().getNameExpression(), this); - initializer = JTTreeFactory.create(getOriginalTree().getInitializer(), this); - name = JTTreeFactory.createName(getOriginalTree().getName()); - return this; - } - - @Override - List> getAllNodes() { - var nodes = super.getAllNodes(); - Optional.ofNullable(modifiers).ifPresent(nodes::add); - Optional.ofNullable(type).ifPresent(nodes::add); - Optional.ofNullable(nameExpression).ifPresent(nodes::add); - Optional.ofNullable(initializer).ifPresent(nodes::add); - return nodes; - } - - @Override - public JTExpression getInitializer() { - return initializer; - } - - @Override - public Kind getKind() { - return Kind.VARIABLE; - } - - @Override - public JTModifiers getModifiers() { - return modifiers; - } - - @Override - public JTName getName() { - return name; - } - - @Override - public JTExpression getNameExpression() { - return nameExpression; - } - - @Override - public JTExpression getType() { - return type; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_INITIALIZER, propertyName -> v8Runtime.toV8Value(getInitializer())); - registerStringGetter(PROPERTY_MODIFIERS, propertyName -> v8Runtime.toV8Value(getModifiers())); - registerStringGetter(PROPERTY_NAME, propertyName -> v8Runtime.toV8Value(getName())); - registerStringGetter(PROPERTY_NAME_EXPRESSION, propertyName -> v8Runtime.toV8Value(getNameExpression())); - registerStringGetter(PROPERTY_TYPE, propertyName -> v8Runtime.toV8Value(getType())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_INITIALIZER, (propertyName, propertyValue) -> replaceExpression(this::setInitializer, propertyValue)); - registerStringSetter(PROPERTY_MODIFIERS, (propertyName, propertyValue) -> replaceModifiers(this::setModifiers, propertyValue)); - registerStringSetter(PROPERTY_NAME, (propertyName, propertyValue) -> replaceName(this::setName, propertyValue)); - registerStringSetter(PROPERTY_NAME_EXPRESSION, (propertyName, propertyValue) -> replaceExpression(this::setNameExpression, propertyValue)); - registerStringSetter(PROPERTY_TYPE, (propertyName, propertyValue) -> replaceExpression(this::setType, propertyValue)); - } - return stringSetterMap; - } - - @Override - public boolean serialize(IStyleWriter writer) { - if (isActionChange()) { - Optional.ofNullable(modifiers).ifPresent(writer::append); - Optional.ofNullable(type).ifPresent(tree -> writer.appendSpaceIfNeeded().append(tree)); - Optional.ofNullable(nameExpression).ifPresent(tree -> writer.appendSpaceIfNeeded().append(tree)); - Optional.ofNullable(name).ifPresent(tree -> writer.appendSpaceIfNeeded().append(tree)); - Optional.ofNullable(initializer).ifPresent( - tree -> writer.appendSpaceIfNeeded().appendEqual().appendSpace().append(tree)); - if (getParentTree() instanceof JTClassDecl || getParentTree() instanceof JTBlock) { - writer.appendSemiColon(); - } - return true; - } - return super.serialize(writer); - } - - private boolean setInitialValue(V8Value v8Value) throws JavetException { - if (v8Runtime.toObject(v8Value) instanceof JTExpression tree) { - setNameExpression(tree); - return true; - } - return false; - } - - public JTVariableDecl setInitializer(JTExpression initializer) { - if (this.initializer == initializer) { - return this; - } - this.initializer = Optional.ofNullable(initializer).map(o -> o.setParentTree(this)).orElse(null); - return setActionChange(); - } - - public JTVariableDecl setModifiers(JTModifiers modifiers) { - if (this.modifiers == modifiers) { - return this; - } - this.modifiers = Objects.requireNonNull(modifiers).setParentTree(this); - return setActionChange(); - } - - public JTVariableDecl setName(JTName name) { - if (this.name == name) { - return this; - } - this.name = Objects.requireNonNull(name); - return setActionChange(); - } - - public JTVariableDecl setNameExpression(JTExpression nameExpression) { - if (this.nameExpression == nameExpression) { - return this; - } - this.nameExpression = Objects.requireNonNull(nameExpression).setParentTree(this); - return this; - } - - public JTVariableDecl setType(JTExpression type) { - if (this.type == type) { - return this; - } - this.type = Optional.ofNullable(type).map(o -> o.setParentTree(this)).orElse(null); - return setActionChange(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.jaspiler.styles.IStyleWriter; +import com.caoccao.javet.exceptions.JavetException; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.sun.source.tree.TreeVisitor; +import com.sun.source.tree.VariableTree; + +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +public final class JTVariableDecl + extends JTStatement + implements VariableTree { + private static final String PROPERTY_INITIALIZER = "initializer"; + private static final String PROPERTY_MODIFIERS = "modifiers"; + private static final String PROPERTY_NAME = "name"; + private static final String PROPERTY_NAME_EXPRESSION = "nameExpression"; + private static final String PROPERTY_TYPE = "type"; + private JTExpression initializer; + private JTModifiers modifiers; + private JTName name; + private JTExpression nameExpression; + private JTExpression type; + + public JTVariableDecl() { + this(null, null); + setActionChange(); + } + + JTVariableDecl(VariableTree variableTree, JTTree parentTree) { + super(variableTree, parentTree); + initializer = null; + modifiers = null; + name = null; + nameExpression = null; + type = null; + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitVariable(this, data); + } + + @Override + JTVariableDecl analyze() { + super.analyze(); + modifiers = JTTreeFactory.create( + getOriginalTree().getModifiers(), this, JTModifiers::new); + type = JTTreeFactory.create(getOriginalTree().getType(), this); + nameExpression = JTTreeFactory.create(getOriginalTree().getNameExpression(), this); + initializer = JTTreeFactory.create(getOriginalTree().getInitializer(), this); + name = JTTreeFactory.createName(getOriginalTree().getName()); + return this; + } + + @Override + List> getAllNodes() { + var nodes = super.getAllNodes(); + Optional.ofNullable(modifiers).ifPresent(nodes::add); + Optional.ofNullable(type).ifPresent(nodes::add); + Optional.ofNullable(nameExpression).ifPresent(nodes::add); + Optional.ofNullable(initializer).ifPresent(nodes::add); + return nodes; + } + + @Override + public JTExpression getInitializer() { + return initializer; + } + + @Override + public Kind getKind() { + return Kind.VARIABLE; + } + + @Override + public JTModifiers getModifiers() { + return modifiers; + } + + @Override + public JTName getName() { + return name; + } + + @Override + public JTExpression getNameExpression() { + return nameExpression; + } + + @Override + public JTExpression getType() { + return type; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_INITIALIZER, propertyName -> v8Runtime.toV8Value(getInitializer())); + registerStringGetter(PROPERTY_MODIFIERS, propertyName -> v8Runtime.toV8Value(getModifiers())); + registerStringGetter(PROPERTY_NAME, propertyName -> v8Runtime.toV8Value(getName())); + registerStringGetter(PROPERTY_NAME_EXPRESSION, propertyName -> v8Runtime.toV8Value(getNameExpression())); + registerStringGetter(PROPERTY_TYPE, propertyName -> v8Runtime.toV8Value(getType())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_INITIALIZER, (propertyName, propertyValue) -> replaceExpression(this::setInitializer, propertyValue)); + registerStringSetter(PROPERTY_MODIFIERS, (propertyName, propertyValue) -> replaceModifiers(this::setModifiers, propertyValue)); + registerStringSetter(PROPERTY_NAME, (propertyName, propertyValue) -> replaceName(this::setName, propertyValue)); + registerStringSetter(PROPERTY_NAME_EXPRESSION, (propertyName, propertyValue) -> replaceExpression(this::setNameExpression, propertyValue)); + registerStringSetter(PROPERTY_TYPE, (propertyName, propertyValue) -> replaceExpression(this::setType, propertyValue)); + } + return stringSetterMap; + } + + @Override + public boolean serialize(IStyleWriter writer) { + if (isActionChange()) { + Optional.ofNullable(modifiers).ifPresent(writer::append); + Optional.ofNullable(type).ifPresent(tree -> writer.appendSpaceIfNeeded().append(tree)); + Optional.ofNullable(nameExpression).ifPresent(tree -> writer.appendSpaceIfNeeded().append(tree)); + Optional.ofNullable(name).ifPresent(tree -> writer.appendSpaceIfNeeded().append(tree)); + Optional.ofNullable(initializer).ifPresent( + tree -> writer.appendSpaceIfNeeded().appendEqual().appendSpace().append(tree)); + if (getParentTree() instanceof JTClassDecl || getParentTree() instanceof JTBlock) { + writer.appendSemiColon(); + } + return true; + } + return super.serialize(writer); + } + + private boolean setInitialValue(V8Value v8Value) throws JavetException { + if (v8Runtime.toObject(v8Value) instanceof JTExpression tree) { + setNameExpression(tree); + return true; + } + return false; + } + + public JTVariableDecl setInitializer(JTExpression initializer) { + if (this.initializer == initializer) { + return this; + } + this.initializer = Optional.ofNullable(initializer).map(o -> o.setParentTree(this)).orElse(null); + return setActionChange(); + } + + public JTVariableDecl setModifiers(JTModifiers modifiers) { + if (this.modifiers == modifiers) { + return this; + } + this.modifiers = Objects.requireNonNull(modifiers).setParentTree(this); + return setActionChange(); + } + + public JTVariableDecl setName(JTName name) { + if (this.name == name) { + return this; + } + this.name = Objects.requireNonNull(name); + return setActionChange(); + } + + public JTVariableDecl setNameExpression(JTExpression nameExpression) { + if (this.nameExpression == nameExpression) { + return this; + } + this.nameExpression = Objects.requireNonNull(nameExpression).setParentTree(this); + return this; + } + + public JTVariableDecl setType(JTExpression type) { + if (this.type == type) { + return this; + } + this.type = Optional.ofNullable(type).map(o -> o.setParentTree(this)).orElse(null); + return setActionChange(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTWhileLoop.java b/src/main/java/com/caoccao/jaspiler/trees/JTWhileLoop.java index 33e621e..2cacb75 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTWhileLoop.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTWhileLoop.java @@ -1,122 +1,122 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.sun.source.tree.TreeVisitor; -import com.sun.source.tree.WhileLoopTree; - -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -public final class JTWhileLoop - extends JTStatement - implements WhileLoopTree { - private static final String PROPERTY_CONDITION = "condition"; - private static final String PROPERTY_STATEMENT = "statement"; - private JTExpression condition; - private JTStatement statement; - - public JTWhileLoop() { - this(null, null); - setActionChange(); - } - - JTWhileLoop(WhileLoopTree whileLoopTree, JTTree parentTree) { - super(whileLoopTree, parentTree); - condition = null; - statement = null; - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitWhileLoop(this, data); - } - - @Override - JTWhileLoop analyze() { - super.analyze(); - condition = JTTreeFactory.create(getOriginalTree().getCondition(), this); - statement = JTTreeFactory.create(getOriginalTree().getStatement(), this); - return this; - } - - @Override - List> getAllNodes() { - var nodes = super.getAllNodes(); - Optional.ofNullable(condition).ifPresent(nodes::add); - Optional.ofNullable(statement).ifPresent(nodes::add); - nodes.forEach(node -> node.setParentTree(this)); - return nodes; - } - - @Override - public JTExpression getCondition() { - return condition; - } - - @Override - public Kind getKind() { - return Kind.WHILE_LOOP; - } - - @Override - public JTStatement getStatement() { - return statement; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_CONDITION, propertyName -> v8Runtime.toV8Value(getCondition())); - registerStringGetter(PROPERTY_STATEMENT, propertyName -> v8Runtime.toV8Value(getStatement())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_CONDITION, (propertyName, propertyValue) -> replaceExpression(this::setCondition, propertyValue)); - registerStringSetter(PROPERTY_STATEMENT, (propertyName, propertyValue) -> replaceStatement(this::setStatement, propertyValue)); - } - return stringSetterMap; - } - - public JTWhileLoop setCondition(JTExpression condition) { - if (this.condition == condition) { - return this; - } - this.condition = Objects.requireNonNull(condition).setParentTree(this); - return setActionChange(); - } - - public JTWhileLoop setStatement(JTStatement statement) { - if (this.statement == statement) { - return this; - } - this.statement = Objects.requireNonNull(statement).setParentTree(this); - return setActionChange(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.sun.source.tree.TreeVisitor; +import com.sun.source.tree.WhileLoopTree; + +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +public final class JTWhileLoop + extends JTStatement + implements WhileLoopTree { + private static final String PROPERTY_CONDITION = "condition"; + private static final String PROPERTY_STATEMENT = "statement"; + private JTExpression condition; + private JTStatement statement; + + public JTWhileLoop() { + this(null, null); + setActionChange(); + } + + JTWhileLoop(WhileLoopTree whileLoopTree, JTTree parentTree) { + super(whileLoopTree, parentTree); + condition = null; + statement = null; + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitWhileLoop(this, data); + } + + @Override + JTWhileLoop analyze() { + super.analyze(); + condition = JTTreeFactory.create(getOriginalTree().getCondition(), this); + statement = JTTreeFactory.create(getOriginalTree().getStatement(), this); + return this; + } + + @Override + List> getAllNodes() { + var nodes = super.getAllNodes(); + Optional.ofNullable(condition).ifPresent(nodes::add); + Optional.ofNullable(statement).ifPresent(nodes::add); + nodes.forEach(node -> node.setParentTree(this)); + return nodes; + } + + @Override + public JTExpression getCondition() { + return condition; + } + + @Override + public Kind getKind() { + return Kind.WHILE_LOOP; + } + + @Override + public JTStatement getStatement() { + return statement; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_CONDITION, propertyName -> v8Runtime.toV8Value(getCondition())); + registerStringGetter(PROPERTY_STATEMENT, propertyName -> v8Runtime.toV8Value(getStatement())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_CONDITION, (propertyName, propertyValue) -> replaceExpression(this::setCondition, propertyValue)); + registerStringSetter(PROPERTY_STATEMENT, (propertyName, propertyValue) -> replaceStatement(this::setStatement, propertyValue)); + } + return stringSetterMap; + } + + public JTWhileLoop setCondition(JTExpression condition) { + if (this.condition == condition) { + return this; + } + this.condition = Objects.requireNonNull(condition).setParentTree(this); + return setActionChange(); + } + + public JTWhileLoop setStatement(JTStatement statement) { + if (this.statement == statement) { + return this; + } + this.statement = Objects.requireNonNull(statement).setParentTree(this); + return setActionChange(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTWildcard.java b/src/main/java/com/caoccao/jaspiler/trees/JTWildcard.java index 8a822bf..ca6051a 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTWildcard.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTWildcard.java @@ -1,119 +1,119 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.jaspiler.exceptions.JaspilerNotSupportedException; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.sun.source.tree.TreeVisitor; -import com.sun.source.tree.WildcardTree; - -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -public final class JTWildcard - extends JTExpression - implements WildcardTree { - private static final String PROPERTY_BOUND = "bound"; - private static final String PROPERTY_KIND = "kind"; - private JTTree bound; - private Kind kind; - - public JTWildcard() { - this(null, null); - setActionChange(); - } - - JTWildcard(WildcardTree wildcardTree, JTTree parentTree) { - super(wildcardTree, parentTree); - bound = null; - kind = null; - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitWildcard(this, data); - } - - @Override - JTWildcard analyze() { - super.analyze(); - bound = JTTreeFactory.create(getOriginalTree().getBound(), this); - kind = getOriginalTree().getKind(); - return this; - } - - @Override - List> getAllNodes() { - var nodes = super.getAllNodes(); - Optional.ofNullable(bound).ifPresent(nodes::add); - nodes.forEach(node -> node.setParentTree(this)); - return nodes; - } - - @Override - public JTTree getBound() { - return bound; - } - - @Override - public Kind getKind() { - return kind; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_BOUND, propertyName -> v8Runtime.toV8Value(getBound())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_BOUND, (propertyName, propertyValue) -> replaceTree(this::setBound, propertyValue)); - registerStringSetter(PROPERTY_KIND, (propertyName, propertyValue) -> replaceKind(this::setKind, propertyValue)); - } - return stringSetterMap; - } - - public JTWildcard setBound(JTTree bound) { - if (this.bound == bound) { - return this; - } - this.bound = Objects.requireNonNull(bound).setParentTree(this); - return setActionChange(); - } - - public JTWildcard setKind(Kind kind) { - if (this.kind == kind) { - return this; - } - switch (Objects.requireNonNull(kind)) { - case EXTENDS_WILDCARD, SUPER_WILDCARD, UNBOUNDED_WILDCARD -> this.kind = kind; - default -> throw new JaspilerNotSupportedException(kind.name() + " is not supported."); - } - return setActionChange(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.jaspiler.exceptions.JaspilerNotSupportedException; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.sun.source.tree.TreeVisitor; +import com.sun.source.tree.WildcardTree; + +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +public final class JTWildcard + extends JTExpression + implements WildcardTree { + private static final String PROPERTY_BOUND = "bound"; + private static final String PROPERTY_KIND = "kind"; + private JTTree bound; + private Kind kind; + + public JTWildcard() { + this(null, null); + setActionChange(); + } + + JTWildcard(WildcardTree wildcardTree, JTTree parentTree) { + super(wildcardTree, parentTree); + bound = null; + kind = null; + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitWildcard(this, data); + } + + @Override + JTWildcard analyze() { + super.analyze(); + bound = JTTreeFactory.create(getOriginalTree().getBound(), this); + kind = getOriginalTree().getKind(); + return this; + } + + @Override + List> getAllNodes() { + var nodes = super.getAllNodes(); + Optional.ofNullable(bound).ifPresent(nodes::add); + nodes.forEach(node -> node.setParentTree(this)); + return nodes; + } + + @Override + public JTTree getBound() { + return bound; + } + + @Override + public Kind getKind() { + return kind; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_BOUND, propertyName -> v8Runtime.toV8Value(getBound())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_BOUND, (propertyName, propertyValue) -> replaceTree(this::setBound, propertyValue)); + registerStringSetter(PROPERTY_KIND, (propertyName, propertyValue) -> replaceKind(this::setKind, propertyValue)); + } + return stringSetterMap; + } + + public JTWildcard setBound(JTTree bound) { + if (this.bound == bound) { + return this; + } + this.bound = Objects.requireNonNull(bound).setParentTree(this); + return setActionChange(); + } + + public JTWildcard setKind(Kind kind) { + if (this.kind == kind) { + return this; + } + switch (Objects.requireNonNull(kind)) { + case EXTENDS_WILDCARD, SUPER_WILDCARD, UNBOUNDED_WILDCARD -> this.kind = kind; + default -> throw new JaspilerNotSupportedException(kind.name() + " is not supported."); + } + return setActionChange(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/JTYield.java b/src/main/java/com/caoccao/jaspiler/trees/JTYield.java index 4b169be..2b6d79c 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/JTYield.java +++ b/src/main/java/com/caoccao/jaspiler/trees/JTYield.java @@ -1,102 +1,102 @@ -/* - * Copyright (c) 2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.trees; - -import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; -import com.caoccao.javet.interfaces.IJavetBiFunction; -import com.caoccao.javet.interfaces.IJavetUniFunction; -import com.caoccao.javet.values.V8Value; -import com.sun.source.tree.TreeVisitor; -import com.sun.source.tree.YieldTree; - -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -public final class JTYield - extends JTStatement - implements YieldTree { - private static final String PROPERTY_VALUE = "value"; - private JTExpression value; - - public JTYield() { - this(null, null); - setActionChange(); - } - - JTYield(YieldTree yieldTree, JTTree parentTree) { - super(yieldTree, parentTree); - value = null; - } - - @Override - public R accept(TreeVisitor visitor, D data) { - return visitor.visitYield(this, data); - } - - @Override - JTYield analyze() { - super.analyze(); - value = JTTreeFactory.create(getOriginalTree().getValue(), this); - return this; - } - - @Override - List> getAllNodes() { - var nodes = super.getAllNodes(); - Optional.ofNullable(value).ifPresent(nodes::add); - nodes.forEach(node -> node.setParentTree(this)); - return nodes; - } - - @Override - public Kind getKind() { - return Kind.YIELD; - } - - @Override - public JTExpression getValue() { - return value; - } - - @Override - public Map> proxyGetStringGetterMap() { - if (stringGetterMap == null) { - super.proxyGetStringGetterMap(); - registerStringGetter(PROPERTY_VALUE, propertyName -> v8Runtime.toV8Value(getValue())); - } - return stringGetterMap; - } - - @Override - public Map> proxyGetStringSetterMap() { - if (stringSetterMap == null) { - super.proxyGetStringSetterMap(); - registerStringSetter(PROPERTY_VALUE, (propertyName, propertyValue) -> replaceExpression(this::setValue, propertyValue)); - } - return stringSetterMap; - } - - public JTYield setValue(JTExpression value) { - if (this.value == value) { - return this; - } - this.value = Objects.requireNonNull(value).setParentTree(this); - return setActionChange(); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.trees; + +import com.caoccao.jaspiler.exceptions.JaspilerCheckedException; +import com.caoccao.javet.interfaces.IJavetBiFunction; +import com.caoccao.javet.interfaces.IJavetUniFunction; +import com.caoccao.javet.values.V8Value; +import com.sun.source.tree.TreeVisitor; +import com.sun.source.tree.YieldTree; + +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +public final class JTYield + extends JTStatement + implements YieldTree { + private static final String PROPERTY_VALUE = "value"; + private JTExpression value; + + public JTYield() { + this(null, null); + setActionChange(); + } + + JTYield(YieldTree yieldTree, JTTree parentTree) { + super(yieldTree, parentTree); + value = null; + } + + @Override + public R accept(TreeVisitor visitor, D data) { + return visitor.visitYield(this, data); + } + + @Override + JTYield analyze() { + super.analyze(); + value = JTTreeFactory.create(getOriginalTree().getValue(), this); + return this; + } + + @Override + List> getAllNodes() { + var nodes = super.getAllNodes(); + Optional.ofNullable(value).ifPresent(nodes::add); + nodes.forEach(node -> node.setParentTree(this)); + return nodes; + } + + @Override + public Kind getKind() { + return Kind.YIELD; + } + + @Override + public JTExpression getValue() { + return value; + } + + @Override + public Map> proxyGetStringGetterMap() { + if (stringGetterMap == null) { + super.proxyGetStringGetterMap(); + registerStringGetter(PROPERTY_VALUE, propertyName -> v8Runtime.toV8Value(getValue())); + } + return stringGetterMap; + } + + @Override + public Map> proxyGetStringSetterMap() { + if (stringSetterMap == null) { + super.proxyGetStringSetterMap(); + registerStringSetter(PROPERTY_VALUE, (propertyName, propertyValue) -> replaceExpression(this::setValue, propertyValue)); + } + return stringSetterMap; + } + + public JTYield setValue(JTExpression value) { + if (this.value == value) { + return this; + } + this.value = Objects.requireNonNull(value).setParentTree(this); + return setActionChange(); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/trees/package-info.java b/src/main/java/com/caoccao/jaspiler/trees/package-info.java index 30f1cd2..c1f7067 100644 --- a/src/main/java/com/caoccao/jaspiler/trees/package-info.java +++ b/src/main/java/com/caoccao/jaspiler/trees/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/utils/BaseLoggingObject.java b/src/main/java/com/caoccao/jaspiler/utils/BaseLoggingObject.java index 6ccb9e7..4654d7f 100644 --- a/src/main/java/com/caoccao/jaspiler/utils/BaseLoggingObject.java +++ b/src/main/java/com/caoccao/jaspiler/utils/BaseLoggingObject.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/utils/ForEachUtils.java b/src/main/java/com/caoccao/jaspiler/utils/ForEachUtils.java index 9817440..05de830 100644 --- a/src/main/java/com/caoccao/jaspiler/utils/ForEachUtils.java +++ b/src/main/java/com/caoccao/jaspiler/utils/ForEachUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/utils/JavaFileStringObject.java b/src/main/java/com/caoccao/jaspiler/utils/JavaFileStringObject.java index e843281..3bb5c48 100644 --- a/src/main/java/com/caoccao/jaspiler/utils/JavaFileStringObject.java +++ b/src/main/java/com/caoccao/jaspiler/utils/JavaFileStringObject.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/utils/JsonUtils.java b/src/main/java/com/caoccao/jaspiler/utils/JsonUtils.java index 1b9fa57..876d4dc 100644 --- a/src/main/java/com/caoccao/jaspiler/utils/JsonUtils.java +++ b/src/main/java/com/caoccao/jaspiler/utils/JsonUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/utils/SystemUtils.java b/src/main/java/com/caoccao/jaspiler/utils/SystemUtils.java index f0c9f13..0c8df0f 100644 --- a/src/main/java/com/caoccao/jaspiler/utils/SystemUtils.java +++ b/src/main/java/com/caoccao/jaspiler/utils/SystemUtils.java @@ -1,36 +1,36 @@ -/* - * Copyright (c) 2023-2023. caoccao.com Sam Cao - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.caoccao.jaspiler.utils; - -import java.nio.file.Path; - -public final class SystemUtils { - public static final Path INITIAL_WORKING_DIRECTORY = getWorkingDirectory(); - public static final String SYSTEM_PROPERTY_JAVA_IO_TMPDIR = "java.io.tmpdir"; - public static final String SYSTEM_PROPERTY_USER_DIR = "user.dir"; - - private SystemUtils() { - } - - public static Path getSystemTmpPath() { - return Path.of(System.getProperty(SYSTEM_PROPERTY_JAVA_IO_TMPDIR)); - } - - public static Path getWorkingDirectory() { - return Path.of(System.getProperty(SYSTEM_PROPERTY_USER_DIR)); - } -} +/* + * Copyright (c) 2023-2024. caoccao.com Sam Cao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.caoccao.jaspiler.utils; + +import java.nio.file.Path; + +public final class SystemUtils { + public static final Path INITIAL_WORKING_DIRECTORY = getWorkingDirectory(); + public static final String SYSTEM_PROPERTY_JAVA_IO_TMPDIR = "java.io.tmpdir"; + public static final String SYSTEM_PROPERTY_USER_DIR = "user.dir"; + + private SystemUtils() { + } + + public static Path getSystemTmpPath() { + return Path.of(System.getProperty(SYSTEM_PROPERTY_JAVA_IO_TMPDIR)); + } + + public static Path getWorkingDirectory() { + return Path.of(System.getProperty(SYSTEM_PROPERTY_USER_DIR)); + } +} diff --git a/src/main/java/com/caoccao/jaspiler/utils/package-info.java b/src/main/java/com/caoccao/jaspiler/utils/package-info.java index 8026e99..ffa43e6 100644 --- a/src/main/java/com/caoccao/jaspiler/utils/package-info.java +++ b/src/main/java/com/caoccao/jaspiler/utils/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/v8/V8Jaspiler.java b/src/main/java/com/caoccao/jaspiler/v8/V8Jaspiler.java index 103b6c4..3a3cae7 100644 --- a/src/main/java/com/caoccao/jaspiler/v8/V8Jaspiler.java +++ b/src/main/java/com/caoccao/jaspiler/v8/V8Jaspiler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/v8/V8JaspilerDocScanner.java b/src/main/java/com/caoccao/jaspiler/v8/V8JaspilerDocScanner.java index eb89bd2..717fa58 100644 --- a/src/main/java/com/caoccao/jaspiler/v8/V8JaspilerDocScanner.java +++ b/src/main/java/com/caoccao/jaspiler/v8/V8JaspilerDocScanner.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/v8/V8JaspilerOptions.java b/src/main/java/com/caoccao/jaspiler/v8/V8JaspilerOptions.java index 61d2c23..ba201e4 100644 --- a/src/main/java/com/caoccao/jaspiler/v8/V8JaspilerOptions.java +++ b/src/main/java/com/caoccao/jaspiler/v8/V8JaspilerOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/v8/V8JaspilerTransformScanner.java b/src/main/java/com/caoccao/jaspiler/v8/V8JaspilerTransformScanner.java index 96a2f7c..3c9c4d9 100644 --- a/src/main/java/com/caoccao/jaspiler/v8/V8JaspilerTransformScanner.java +++ b/src/main/java/com/caoccao/jaspiler/v8/V8JaspilerTransformScanner.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/v8/V8PatchedFileExecutor.java b/src/main/java/com/caoccao/jaspiler/v8/V8PatchedFileExecutor.java index f0a2601..b90f09d 100644 --- a/src/main/java/com/caoccao/jaspiler/v8/V8PatchedFileExecutor.java +++ b/src/main/java/com/caoccao/jaspiler/v8/V8PatchedFileExecutor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/visiters/BaseJaspilerDocScanner.java b/src/main/java/com/caoccao/jaspiler/visiters/BaseJaspilerDocScanner.java index 7ab906b..4ae9604 100644 --- a/src/main/java/com/caoccao/jaspiler/visiters/BaseJaspilerDocScanner.java +++ b/src/main/java/com/caoccao/jaspiler/visiters/BaseJaspilerDocScanner.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/visiters/BaseJaspilerParseScanner.java b/src/main/java/com/caoccao/jaspiler/visiters/BaseJaspilerParseScanner.java index 8236dde..d6967a2 100644 --- a/src/main/java/com/caoccao/jaspiler/visiters/BaseJaspilerParseScanner.java +++ b/src/main/java/com/caoccao/jaspiler/visiters/BaseJaspilerParseScanner.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/visiters/BaseJaspilerTransformScanner.java b/src/main/java/com/caoccao/jaspiler/visiters/BaseJaspilerTransformScanner.java index ee1d1b6..366d0ea 100644 --- a/src/main/java/com/caoccao/jaspiler/visiters/BaseJaspilerTransformScanner.java +++ b/src/main/java/com/caoccao/jaspiler/visiters/BaseJaspilerTransformScanner.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/caoccao/jaspiler/visiters/package-info.java b/src/main/java/com/caoccao/jaspiler/visiters/package-info.java index 9791047..362d09b 100644 --- a/src/main/java/com/caoccao/jaspiler/visiters/package-info.java +++ b/src/main/java/com/caoccao/jaspiler/visiters/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/resources/log4j.properties b/src/main/resources/log4j.properties index cba51ab..c5a7769 100644 --- a/src/main/resources/log4j.properties +++ b/src/main/resources/log4j.properties @@ -1,3 +1,19 @@ +# +# Copyright (c) 2024. caoccao.com Sam Cao +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + # Root logger option log4j.rootLogger=INFO, stdout diff --git a/src/test/java/com/caoccao/jaspiler/BaseTestSuite.java b/src/test/java/com/caoccao/jaspiler/BaseTestSuite.java index 93cc4a1..86a6549 100644 --- a/src/test/java/com/caoccao/jaspiler/BaseTestSuite.java +++ b/src/test/java/com/caoccao/jaspiler/BaseTestSuite.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/java/com/caoccao/jaspiler/TestJaspilerCompiler.java b/src/test/java/com/caoccao/jaspiler/TestJaspilerCompiler.java index 7819dbf..3551aee 100644 --- a/src/test/java/com/caoccao/jaspiler/TestJaspilerCompiler.java +++ b/src/test/java/com/caoccao/jaspiler/TestJaspilerCompiler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/java/com/caoccao/jaspiler/TestJaspilerContract.java b/src/test/java/com/caoccao/jaspiler/TestJaspilerContract.java index bc3e58e..9678990 100644 --- a/src/test/java/com/caoccao/jaspiler/TestJaspilerContract.java +++ b/src/test/java/com/caoccao/jaspiler/TestJaspilerContract.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/java/com/caoccao/jaspiler/TestJaspilerMain.java b/src/test/java/com/caoccao/jaspiler/TestJaspilerMain.java index e0866e2..0e8be05 100644 --- a/src/test/java/com/caoccao/jaspiler/TestJaspilerMain.java +++ b/src/test/java/com/caoccao/jaspiler/TestJaspilerMain.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/java/com/caoccao/jaspiler/mock/MockAllInOnePublicClass.java b/src/test/java/com/caoccao/jaspiler/mock/MockAllInOnePublicClass.java index 7553caf..544346b 100644 --- a/src/test/java/com/caoccao/jaspiler/mock/MockAllInOnePublicClass.java +++ b/src/test/java/com/caoccao/jaspiler/mock/MockAllInOnePublicClass.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/java/com/caoccao/jaspiler/mock/MockForScan.java b/src/test/java/com/caoccao/jaspiler/mock/MockForScan.java index c8d334e..0438013 100644 --- a/src/test/java/com/caoccao/jaspiler/mock/MockForScan.java +++ b/src/test/java/com/caoccao/jaspiler/mock/MockForScan.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/java/com/caoccao/jaspiler/mock/MockIgnorePublicClass.java b/src/test/java/com/caoccao/jaspiler/mock/MockIgnorePublicClass.java index a78325e..cadf32a 100644 --- a/src/test/java/com/caoccao/jaspiler/mock/MockIgnorePublicClass.java +++ b/src/test/java/com/caoccao/jaspiler/mock/MockIgnorePublicClass.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/java/com/caoccao/jaspiler/mock/MockPublicAnnotation.java b/src/test/java/com/caoccao/jaspiler/mock/MockPublicAnnotation.java index 7e1c14e..4f9cd55 100644 --- a/src/test/java/com/caoccao/jaspiler/mock/MockPublicAnnotation.java +++ b/src/test/java/com/caoccao/jaspiler/mock/MockPublicAnnotation.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/java/com/caoccao/jaspiler/trees/TestJTAnnotation.java b/src/test/java/com/caoccao/jaspiler/trees/TestJTAnnotation.java index 49b21bc..4c57cec 100644 --- a/src/test/java/com/caoccao/jaspiler/trees/TestJTAnnotation.java +++ b/src/test/java/com/caoccao/jaspiler/trees/TestJTAnnotation.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/java/com/caoccao/jaspiler/trees/TestJTClassDecl.java b/src/test/java/com/caoccao/jaspiler/trees/TestJTClassDecl.java index 4b059c3..1455bbc 100644 --- a/src/test/java/com/caoccao/jaspiler/trees/TestJTClassDecl.java +++ b/src/test/java/com/caoccao/jaspiler/trees/TestJTClassDecl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/java/com/caoccao/jaspiler/trees/TestJTCompilationUnit.java b/src/test/java/com/caoccao/jaspiler/trees/TestJTCompilationUnit.java index 8e233ff..0231f85 100644 --- a/src/test/java/com/caoccao/jaspiler/trees/TestJTCompilationUnit.java +++ b/src/test/java/com/caoccao/jaspiler/trees/TestJTCompilationUnit.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/java/com/caoccao/jaspiler/trees/TestJTImport.java b/src/test/java/com/caoccao/jaspiler/trees/TestJTImport.java index d6d5724..5d06df9 100644 --- a/src/test/java/com/caoccao/jaspiler/trees/TestJTImport.java +++ b/src/test/java/com/caoccao/jaspiler/trees/TestJTImport.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/java/com/caoccao/jaspiler/trees/TestJTMethodDecl.java b/src/test/java/com/caoccao/jaspiler/trees/TestJTMethodDecl.java index eb0e9c4..8f9b4ec 100644 --- a/src/test/java/com/caoccao/jaspiler/trees/TestJTMethodDecl.java +++ b/src/test/java/com/caoccao/jaspiler/trees/TestJTMethodDecl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,6 +61,6 @@ public TestTransformScanner visitMethod(MethodTree node, JaspilerTransformContex " }\n", "String[] mockNames() default {\"A\", \"B\"};", "String mockValue() default \"value\";"); - texts.forEach(text -> assertTrue(code.contains(text))); + texts.forEach(text -> assertTrue(code.contains(text), text + " is not founded.")); } } diff --git a/src/test/java/com/caoccao/jaspiler/trees/TestJTPackageDecl.java b/src/test/java/com/caoccao/jaspiler/trees/TestJTPackageDecl.java index 70f792f..5f474f1 100644 --- a/src/test/java/com/caoccao/jaspiler/trees/TestJTPackageDecl.java +++ b/src/test/java/com/caoccao/jaspiler/trees/TestJTPackageDecl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/java/com/caoccao/jaspiler/trees/TestJTVariableDecl.java b/src/test/java/com/caoccao/jaspiler/trees/TestJTVariableDecl.java index 1b92517..be27c92 100644 --- a/src/test/java/com/caoccao/jaspiler/trees/TestJTVariableDecl.java +++ b/src/test/java/com/caoccao/jaspiler/trees/TestJTVariableDecl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/java/com/caoccao/jaspiler/utils/MockUtils.java b/src/test/java/com/caoccao/jaspiler/utils/MockUtils.java index 084c0c5..5efab57 100644 --- a/src/test/java/com/caoccao/jaspiler/utils/MockUtils.java +++ b/src/test/java/com/caoccao/jaspiler/utils/MockUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/java/com/caoccao/jaspiler/visiters/DummyDocScanner.java b/src/test/java/com/caoccao/jaspiler/visiters/DummyDocScanner.java index 9cdb411..ab4f66a 100644 --- a/src/test/java/com/caoccao/jaspiler/visiters/DummyDocScanner.java +++ b/src/test/java/com/caoccao/jaspiler/visiters/DummyDocScanner.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/java/com/caoccao/jaspiler/visiters/DummyTransformScanner.java b/src/test/java/com/caoccao/jaspiler/visiters/DummyTransformScanner.java index 9494370..2db3290 100644 --- a/src/test/java/com/caoccao/jaspiler/visiters/DummyTransformScanner.java +++ b/src/test/java/com/caoccao/jaspiler/visiters/DummyTransformScanner.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2023. caoccao.com Sam Cao + * Copyright (c) 2023-2024. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/resources/log4j.properties b/src/test/resources/log4j.properties index 8d8432d..8a72d74 100644 --- a/src/test/resources/log4j.properties +++ b/src/test/resources/log4j.properties @@ -1,3 +1,19 @@ +# +# Copyright (c) 2024. caoccao.com Sam Cao +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + # Root logger option log4j.rootLogger=DEBUG, stdout