From b447e558429bc8809f738e27f4af8a5d6b7b62bf Mon Sep 17 00:00:00 2001 From: Yauheni Khnykin Date: Wed, 27 Dec 2023 20:35:16 +0100 Subject: [PATCH] Applies new klint format Signed-off-by: Yauheni Khnykin --- .../gluecodium/gradle/GluecodiumPlugin.kt | 184 ++--- .../gluecodium/gradle/GluecodiumRunner.kt | 7 +- .../here/gluecodium/gradle/GluecodiumTask.kt | 11 +- .../java/com/here/gluecodium/Gluecodium.kt | 57 +- .../com/here/gluecodium/GluecodiumOptions.kt | 2 +- .../com/here/gluecodium/cache/FileOutput.kt | 46 +- .../com/here/gluecodium/cache/FileRemove.kt | 8 +- .../gluecodium/cache/SplitSourceSetCache.kt | 98 +-- .../com/here/gluecodium/cli/OptionReader.kt | 226 +++--- .../cbridge/CBridgeCppNameResolver.kt | 3 +- .../generator/cbridge/CBridgeFileNames.kt | 6 +- .../generator/cbridge/CBridgeGenerator.kt | 159 +++-- .../cbridge/CBridgeGeneratorPredicates.kt | 65 +- .../cbridge/CBridgeHeaderIncludeResolver.kt | 3 +- .../cbridge/CBridgeImplIncludeResolver.kt | 37 +- .../generator/cbridge/CBridgeNameResolver.kt | 23 +- .../generator/cbridge/CBridgeNameRules.kt | 4 +- .../generator/common/CamelCaseNameResolver.kt | 1 - .../generator/common/CommentsProcessor.kt | 60 +- .../common/CommonGeneratorPredicates.kt | 40 +- .../generator/common/GeneratedFile.kt | 5 +- .../gluecodium/generator/common/Generator.kt | 24 +- .../generator/common/GeneratorOptions.kt | 38 +- .../common/GenericImportsCollector.kt | 30 +- .../common/GenericIncludesCollector.kt | 19 +- .../gluecodium/generator/common/Include.kt | 14 +- .../generator/common/NameResolver.kt | 15 +- .../generator/common/NameRuleSet.kt | 3 +- .../generator/common/NameRuleSetLoader.kt | 50 +- .../gluecodium/generator/common/NameRules.kt | 9 +- .../common/OptimizedListsCollector.kt | 6 +- .../common/PlatformSignatureResolver.kt | 3 +- .../common/ReferenceMapBasedResolver.kt | 19 +- .../templates/CopyrightHeaderResolver.kt | 13 +- .../common/templates/JoinPartialHelper.kt | 15 +- .../common/templates/NameResolverHelper.kt | 13 +- .../common/templates/NiceSwitchHelper.kt | 7 +- .../common/templates/PrefixHelper.kt | 8 +- .../common/templates/PrefixPartialHelper.kt | 5 +- .../common/templates/SetJoinHelper.kt | 1 - .../common/templates/TemplateEngine.kt | 71 +- .../cpp/CppForwardDeclarationGroup.kt | 2 +- .../cpp/CppForwardDeclarationsCollector.kt | 5 +- .../generator/cpp/CppFullNameResolver.kt | 4 +- .../gluecodium/generator/cpp/CppGenerator.kt | 195 +++--- .../generator/cpp/CppGeneratorPredicates.kt | 188 ++--- .../cpp/CppHeaderIncludesCollector.kt | 25 +- .../generator/cpp/CppImplIncludesCollector.kt | 14 +- .../generator/cpp/CppImportsCollector.kt | 25 +- .../generator/cpp/CppIncludeResolver.kt | 24 +- .../generator/cpp/CppIncludesCache.kt | 11 +- .../gluecodium/generator/cpp/CppNameCache.kt | 41 +- .../generator/cpp/CppNameResolver.kt | 250 ++++--- .../gluecodium/generator/cpp/CppNameRules.kt | 3 +- .../generator/cpp/CppSignatureResolver.kt | 3 +- .../cpp/CppSkipAttributesValidator.kt | 3 +- .../generator/cpp/DoxygenCommentsProcessor.kt | 7 +- .../generator/cpp/TopologicalSort.kt | 38 +- .../generator/dart/DartAsyncHelpers.kt | 85 ++- .../generator/dart/DartCommentsProcessor.kt | 7 +- .../dart/DartDeclarationImportResolver.kt | 21 +- .../generator/dart/DartGenerator.kt | 505 +++++++------- .../generator/dart/DartGeneratorPredicates.kt | 73 +- .../gluecodium/generator/dart/DartImport.kt | 3 +- .../generator/dart/DartImportResolver.kt | 30 +- .../generator/dart/DartImportResolverBase.kt | 29 +- .../generator/dart/DartImportsCollector.kt | 8 +- .../generator/dart/DartNameResolver.kt | 146 ++-- .../generator/dart/DartOverloadsValidator.kt | 27 +- .../generator/dart/DartVisibilityResolver.kt | 8 +- .../generator/dart/FfiApiTypeNameResolver.kt | 1 - .../generator/dart/FfiDartTypeNameResolver.kt | 1 - .../generator/ffi/FfiCppIncludeResolver.kt | 89 ++- .../generator/ffi/FfiCppNameResolver.kt | 18 +- .../ffi/FfiCppParameterTypeNameResolver.kt | 15 +- .../ffi/FfiCppReturnTypeNameResolver.kt | 3 +- .../generator/ffi/FfiNameResolver.kt | 65 +- .../generator/java/JavaDocProcessor.kt | 27 +- .../generator/java/JavaEmptyValueResolver.kt | 1 - .../generator/java/JavaGenerator.kt | 191 +++--- .../generator/java/JavaGeneratorPredicates.kt | 87 +-- .../gluecodium/generator/java/JavaImport.kt | 1 - .../generator/java/JavaImportCollector.kt | 38 +- .../generator/java/JavaImportResolver.kt | 60 +- .../generator/java/JavaNameResolver.kt | 67 +- .../generator/java/JavaNameRules.kt | 18 +- .../generator/java/JavaSignatureResolver.kt | 8 +- .../generator/java/JavaValueResolver.kt | 64 +- .../generator/java/JavaVisibilityResolver.kt | 1 - .../generator/jni/JniFileNameRules.kt | 1 - .../generator/jni/JniGeneratorPredicates.kt | 102 +-- .../generator/jni/JniIncludeCollector.kt | 18 +- .../generator/jni/JniIncludeResolver.kt | 3 +- .../generator/jni/JniMangledNameResolver.kt | 7 +- .../generator/jni/JniNameResolver.kt | 20 +- .../gluecodium/generator/jni/JniTemplates.kt | 301 ++++---- .../jni/JniTypeSignatureNameResolver.kt | 1 - .../generator/swift/SwiftCommentsProcessor.kt | 14 +- .../generator/swift/SwiftFieldsValidator.kt | 1 - .../generator/swift/SwiftGenerator.kt | 171 ++--- .../swift/SwiftGeneratorPredicates.kt | 158 +++-- .../generator/swift/SwiftImportsResolver.kt | 1 - .../swift/SwiftMangledNameResolver.kt | 1 - .../generator/swift/SwiftNameResolver.kt | 64 +- .../generator/swift/SwiftNameRules.kt | 9 +- .../generator/swift/SwiftSignatureResolver.kt | 3 +- .../swift/SwiftVisibilityResolver.kt | 13 +- .../swift/SwiftWeakAttributeValidator.kt | 12 +- .../validator/LimeAsyncValidator.kt | 34 +- .../validator/LimeConstantRefsValidator.kt | 6 +- .../validator/LimeExternalTypesValidator.kt | 11 +- .../LimeFieldConstructorsValidator.kt | 21 +- .../validator/LimeFunctionsValidator.kt | 14 +- .../validator/LimeGenericTypesValidator.kt | 21 +- .../validator/LimeInheritanceValidator.kt | 5 +- .../validator/LimeOptimizedListsValidator.kt | 21 +- .../validator/LimeOverloadsValidator.kt | 28 +- .../validator/LimePropertiesValidator.kt | 10 +- .../LimeSerializableStructsValidator.kt | 10 +- .../gluecodium/validator/LimeSkipValidator.kt | 21 +- .../validator/LimeStructsValidator.kt | 5 +- .../validator/LimeTypeRefTargetValidator.kt | 10 +- .../validator/LimeTypeRefsValidator.kt | 22 +- .../validator/LimeValuesValidator.kt | 62 +- .../gluecodium/GluecodiumIntegrationTest.kt | 34 +- .../java/com/here/gluecodium/SmokeTest.kt | 51 +- .../cache/SplitSourceSetCacheTest.kt | 1 - .../here/gluecodium/cli/OptionReaderTest.kt | 13 +- .../generator/common/NameHelperTest.kt | 144 ++-- .../templates/NameResolverHelperTest.kt | 95 +-- .../cpp/CppSkipAttributesValidatorTest.kt | 40 +- .../generator/cpp/TopologicalSortTest.kt | 179 ++--- .../cpp/TopologicalSortTestHelper.kt | 28 +- ...OverloadsValidatorFieldConstructorsTest.kt | 1 - .../dart/DartOverloadsValidatorTest.kt | 52 +- .../swift/SwiftFieldsValidatorTest.kt | 36 +- .../swift/SwiftWeakAttributeValidatorTest.kt | 92 +-- .../here/gluecodium/output/FileOutputTest.kt | 11 +- .../gluecodium/test/NiceErrorCollector.kt | 11 +- .../validator/LimeAsyncValidatorTest.kt | 14 +- .../LimeConstantRefsValidatorTest.kt | 65 +- .../LimeExternalTypesValidatorTest.kt | 55 +- .../LimeFieldConstructorsValidatorTest.kt | 42 +- .../LimeFunctionsValidatorRefsTest.kt | 1 - .../LimeFunctionsValidatorThrowsTest.kt | 1 - .../LimeGenericTypesValidatorTest.kt | 52 +- .../LimeInheritanceValidatorClassTest.kt | 46 +- .../LimeInheritanceValidatorInterfaceTest.kt | 28 +- .../LimeOptimizedListsValidatorTest.kt | 116 ++-- ...OverloadsValidatorFieldConstructorsTest.kt | 19 +- .../validator/LimeOverloadsValidatorTest.kt | 89 +-- .../validator/LimePropertiesValidatorTest.kt | 124 ++-- .../LimeSerializableStructsValidatorTest.kt | 1 - .../validator/LimeSkipValidatorTest.kt | 67 +- .../LimeStructsValidatorStrictTest.kt | 62 +- .../validator/LimeStructsValidatorTest.kt | 1 - .../LimeTypeRefTargetValidatorTest.kt | 1 - .../validator/LimeTypeRefsValidatorTest.kt | 64 +- .../validator/LimeValuesValidatorTest.kt | 127 ++-- .../gluecodium/loader/AntlrLimeConverter.kt | 93 +-- .../loader/AntlrLimeModelBuilder.kt | 648 +++++++++--------- .../loader/AntlrLimeModelBuilderBase.kt | 3 +- .../loader/AntlrLimeReferenceResolver.kt | 8 +- .../gluecodium/loader/AntlrLimedocBuilder.kt | 28 +- .../here/gluecodium/loader/AntlrTypeMapper.kt | 54 +- .../loader/LimeBasedLimeModelLoader.kt | 38 +- .../loader/LimeStructuredComment.kt | 8 +- .../loader/ThrowingErrorListener.kt | 2 +- .../validator/LimeImportsValidator.kt | 13 +- .../loader/AntlrLimeModelBuilderTest.kt | 2 + .../loader/LimeBasedLimeModelLoaderTest.kt | 8 +- .../gluecodium/common/CaseInsensitiveMap.kt | 57 +- .../gluecodium/common/CaseInsensitiveSet.kt | 1 - .../common/ContextBasedModelBuilder.kt | 6 +- .../com/here/gluecodium/common/LimeLogger.kt | 36 +- .../here/gluecodium/common/LimeModelFilter.kt | 42 +- .../common/LimeModelSkipPredicates.kt | 13 +- .../gluecodium/common/LimeTypeRefsVisitor.kt | 17 +- .../gluecodium/common/LimeValuesVisitor.kt | 5 +- .../here/gluecodium/common/StringHelper.kt | 5 +- .../model/lime/LimeAmbiguityResolver.kt | 7 +- .../model/lime/LimeAmbiguousConstantRef.kt | 6 +- .../model/lime/LimeAmbiguousTypeRef.kt | 3 +- .../model/lime/LimeAttributeType.kt | 5 +- .../model/lime/LimeAttributeValueType.kt | 3 +- .../gluecodium/model/lime/LimeAttributes.kt | 50 +- .../gluecodium/model/lime/LimeBasicType.kt | 5 +- .../gluecodium/model/lime/LimeBasicTypeRef.kt | 2 +- .../here/gluecodium/model/lime/LimeClass.kt | 36 +- .../here/gluecodium/model/lime/LimeComment.kt | 18 +- .../gluecodium/model/lime/LimeConstant.kt | 2 +- .../gluecodium/model/lime/LimeContainer.kt | 3 +- .../lime/LimeContainerWithInheritance.kt | 42 +- .../model/lime/LimeDirectTypeRef.kt | 2 +- .../gluecodium/model/lime/LimeEnumeration.kt | 3 +- .../gluecodium/model/lime/LimeEnumerator.kt | 2 +- .../gluecodium/model/lime/LimeException.kt | 2 +- .../model/lime/LimeExternalDescriptor.kt | 11 +- .../here/gluecodium/model/lime/LimeField.kt | 2 +- .../model/lime/LimeFieldConstructor.kt | 21 +- .../gluecodium/model/lime/LimeFunction.kt | 2 +- .../gluecodium/model/lime/LimeInterface.kt | 36 +- .../here/gluecodium/model/lime/LimeLambda.kt | 18 +- .../model/lime/LimeLambdaParameter.kt | 6 +- .../gluecodium/model/lime/LimeLazyFieldRef.kt | 6 +- .../gluecodium/model/lime/LimeLazyTypeRef.kt | 9 +- .../here/gluecodium/model/lime/LimeModel.kt | 2 +- .../gluecodium/model/lime/LimeModelLoader.kt | 5 +- .../gluecodium/model/lime/LimeNamedElement.kt | 3 +- .../gluecodium/model/lime/LimeParameter.kt | 2 +- .../here/gluecodium/model/lime/LimePath.kt | 14 +- .../model/lime/LimePositionalEnumeratorRef.kt | 6 +- .../model/lime/LimePositionalTypeRef.kt | 8 +- .../gluecodium/model/lime/LimeProperty.kt | 2 +- .../model/lime/LimeReferenceResolver.kt | 8 +- .../gluecodium/model/lime/LimeReturnType.kt | 7 +- .../model/lime/LimeSignatureResolver.kt | 18 +- .../here/gluecodium/model/lime/LimeStruct.kt | 30 +- .../gluecodium/model/lime/LimeThrownType.kt | 2 +- .../here/gluecodium/model/lime/LimeType.kt | 2 +- .../gluecodium/model/lime/LimeTypeAlias.kt | 2 +- .../gluecodium/model/lime/LimeTypeHelper.kt | 36 +- .../gluecodium/model/lime/LimeTypedElement.kt | 2 +- .../here/gluecodium/model/lime/LimeValue.kt | 6 +- .../common/ContextBasedModelBuilderTest.kt | 2 - .../here/gluecodium/common/LimeLoggerTest.kt | 1 - .../model/lime/LimeAmbiguityResolverTest.kt | 2 +- .../com/here/gluecodium/test/AssertHelpers.kt | 5 +- 228 files changed, 4553 insertions(+), 3908 deletions(-) diff --git a/gluecodium-gradle/src/main/java/com/here/gluecodium/gradle/GluecodiumPlugin.kt b/gluecodium-gradle/src/main/java/com/here/gluecodium/gradle/GluecodiumPlugin.kt index c0c4db27b7..e50d4e4c79 100644 --- a/gluecodium-gradle/src/main/java/com/here/gluecodium/gradle/GluecodiumPlugin.kt +++ b/gluecodium-gradle/src/main/java/com/here/gluecodium/gradle/GluecodiumPlugin.kt @@ -35,104 +35,116 @@ import org.gradle.api.plugins.JavaPluginConvention import java.io.File import javax.inject.Inject -class GluecodiumPlugin @Inject constructor(private val objectFactory: ObjectFactory) : Plugin { - - override fun apply(project: Project) { - val gluecodiumExtension = - project.extensions.create(GLUECODIUM_EXTENSION_NAME, GluecodiumExtension::class.java) - - val javaGenerator: String - if (project.pluginManager.hasPlugin("com.android.base")) { - javaGenerator = "android" - applyAndroid(project, gluecodiumExtension) - } else { - javaGenerator = "java" - applyJava(project, gluecodiumExtension) - } +class GluecodiumPlugin + @Inject + constructor(private val objectFactory: ObjectFactory) : Plugin { + override fun apply(project: Project) { + val gluecodiumExtension = + project.extensions.create(GLUECODIUM_EXTENSION_NAME, GluecodiumExtension::class.java) + + val javaGenerator: String + if (project.pluginManager.hasPlugin("com.android.base")) { + javaGenerator = "android" + applyAndroid(project, gluecodiumExtension) + } else { + javaGenerator = "java" + applyJava(project, gluecodiumExtension) + } - project.tasks.register(GLUECODIUM_TASK_NAME, GluecodiumTask::class.java) { - it.description = "Processes Gluecodium IDL files" - it.javaGenerator = javaGenerator - propagateExtensionProperties(it, gluecodiumExtension) + project.tasks.register(GLUECODIUM_TASK_NAME, GluecodiumTask::class.java) { + it.description = "Processes Gluecodium IDL files" + it.javaGenerator = javaGenerator + propagateExtensionProperties(it, gluecodiumExtension) + } } - } - private fun applyAndroid(project: Project, gluecodiumExtension: GluecodiumExtension) { - val androidExtension = project.extensions.getByName("android") as BaseExtension + private fun applyAndroid( + project: Project, + gluecodiumExtension: GluecodiumExtension, + ) { + val androidExtension = project.extensions.getByName("android") as BaseExtension - val sourceSets = androidExtension.sourceSets - sourceSets.forEach { it.java.srcDir(gluecodiumExtension.outputDirectory) } - setDefaultGluecodiumSources(project, gluecodiumExtension, sourceSets.map { it.name }) + val sourceSets = androidExtension.sourceSets + sourceSets.forEach { it.java.srcDir(gluecodiumExtension.outputDirectory) } + setDefaultGluecodiumSources(project, gluecodiumExtension, sourceSets.map { it.name }) - project.afterEvaluate { injectGluecodiumTask(androidExtension) } - } - - private fun applyJava(project: Project, gluecodiumExtension: GluecodiumExtension) { - project.pluginManager.apply(JavaPlugin::class.java) - - val sourceSets = project.convention.getPlugin(JavaPluginConvention::class.java) - .sourceSets - .filterIsInstance() - sourceSets.forEach { it.java.srcDir(gluecodiumExtension.outputDirectory) } - setDefaultGluecodiumSources(project, gluecodiumExtension, sourceSets.map { it.name }) + project.afterEvaluate { injectGluecodiumTask(androidExtension) } + } - sourceSets.forEach { sourceSet -> - project.tasks.named(sourceSet.compileJavaTaskName) { compileTask -> - compileTask.dependsOn(GLUECODIUM_TASK_NAME) + private fun applyJava( + project: Project, + gluecodiumExtension: GluecodiumExtension, + ) { + project.pluginManager.apply(JavaPlugin::class.java) + + val sourceSets = + project.convention.getPlugin(JavaPluginConvention::class.java) + .sourceSets + .filterIsInstance() + sourceSets.forEach { it.java.srcDir(gluecodiumExtension.outputDirectory) } + setDefaultGluecodiumSources(project, gluecodiumExtension, sourceSets.map { it.name }) + + sourceSets.forEach { sourceSet -> + project.tasks.named(sourceSet.compileJavaTaskName) { compileTask -> + compileTask.dependsOn(GLUECODIUM_TASK_NAME) + } } } - } - - private fun setDefaultGluecodiumSources( - project: Project, - gluecodiumExtension: GluecodiumExtension, - sourceSetNames: List - ) { - val defaultSources = sourceSetNames.map { "${project.rootDir}/src/$it/$GLUECODIUM_DIR_NAME" } - gluecodiumExtension.source.convention(project.files(defaultSources).asFileTree) - gluecodiumExtension.outputDirectory.convention( - File("${project.buildDir}/generated-src/$GLUECODIUM_DIR_NAME") - ) - } - private fun propagateExtensionProperties(task: GluecodiumTask, gluecodiumExtension: GluecodiumExtension) { - task.source(gluecodiumExtension.source) - task.outputDirectory.set(gluecodiumExtension.outputDirectory) - task.commonOutputDirectory.set(gluecodiumExtension.commonOutputDirectory) - task.auxiliarySource.set(gluecodiumExtension.auxiliarySource) - task.copyrightHeaderFile.set(gluecodiumExtension.copyrightHeaderFile) - task.javaPackage.set(gluecodiumExtension.javaPackage) - task.javaInternalPackage.set(gluecodiumExtension.javaInternalPackage) - task.javaNameRules.set(gluecodiumExtension.javaNameRules) - task.javaNonNullAnnotation.set(gluecodiumExtension.javaNonNullAnnotation) - task.javaNullableAnnotation.set(gluecodiumExtension.javaNullableAnnotation) - task.cppNamespace.set(gluecodiumExtension.cppNamespace) - task.cppInternalNamespace.set(gluecodiumExtension.cppInternalNamespace) - task.cppExportMacroName.set(gluecodiumExtension.cppExportMacroName) - task.cppNameRules.set(gluecodiumExtension.cppNameRules) - } + private fun setDefaultGluecodiumSources( + project: Project, + gluecodiumExtension: GluecodiumExtension, + sourceSetNames: List, + ) { + val defaultSources = sourceSetNames.map { "${project.rootDir}/src/$it/$GLUECODIUM_DIR_NAME" } + gluecodiumExtension.source.convention(project.files(defaultSources).asFileTree) + gluecodiumExtension.outputDirectory.convention( + File("${project.buildDir}/generated-src/$GLUECODIUM_DIR_NAME"), + ) + } - private fun injectGluecodiumTask(androidExtension: BaseExtension) { - val variants = when (androidExtension) { - is AppExtension -> androidExtension.applicationVariants - is LibraryExtension -> androidExtension.libraryVariants - else -> emptyList() + private fun propagateExtensionProperties( + task: GluecodiumTask, + gluecodiumExtension: GluecodiumExtension, + ) { + task.source(gluecodiumExtension.source) + task.outputDirectory.set(gluecodiumExtension.outputDirectory) + task.commonOutputDirectory.set(gluecodiumExtension.commonOutputDirectory) + task.auxiliarySource.set(gluecodiumExtension.auxiliarySource) + task.copyrightHeaderFile.set(gluecodiumExtension.copyrightHeaderFile) + task.javaPackage.set(gluecodiumExtension.javaPackage) + task.javaInternalPackage.set(gluecodiumExtension.javaInternalPackage) + task.javaNameRules.set(gluecodiumExtension.javaNameRules) + task.javaNonNullAnnotation.set(gluecodiumExtension.javaNonNullAnnotation) + task.javaNullableAnnotation.set(gluecodiumExtension.javaNullableAnnotation) + task.cppNamespace.set(gluecodiumExtension.cppNamespace) + task.cppInternalNamespace.set(gluecodiumExtension.cppInternalNamespace) + task.cppExportMacroName.set(gluecodiumExtension.cppExportMacroName) + task.cppNameRules.set(gluecodiumExtension.cppNameRules) } - val testVariants = - variants.filterIsInstance().mapNotNull { it.testVariant } - - val allVariants = variants + testVariants - for (variant in allVariants) { - val taskProviders = variant.externalNativeBuildProviders + variant.javaCompileProvider - for (taskProvider in taskProviders) { - taskProvider.configure { it.dependsOn(GLUECODIUM_TASK_NAME) } + + private fun injectGluecodiumTask(androidExtension: BaseExtension) { + val variants = + when (androidExtension) { + is AppExtension -> androidExtension.applicationVariants + is LibraryExtension -> androidExtension.libraryVariants + else -> emptyList() + } + val testVariants = + variants.filterIsInstance().mapNotNull { it.testVariant } + + val allVariants = variants + testVariants + for (variant in allVariants) { + val taskProviders = variant.externalNativeBuildProviders + variant.javaCompileProvider + for (taskProvider in taskProviders) { + taskProvider.configure { it.dependsOn(GLUECODIUM_TASK_NAME) } + } } } - } - companion object { - private const val GLUECODIUM_DIR_NAME = "gluecodium" - private const val GLUECODIUM_EXTENSION_NAME = "gluecodium" - private const val GLUECODIUM_TASK_NAME = "generateGluecodiumSources" + companion object { + private const val GLUECODIUM_DIR_NAME = "gluecodium" + private const val GLUECODIUM_EXTENSION_NAME = "gluecodium" + private const val GLUECODIUM_TASK_NAME = "generateGluecodiumSources" + } } -} diff --git a/gluecodium-gradle/src/main/java/com/here/gluecodium/gradle/GluecodiumRunner.kt b/gluecodium-gradle/src/main/java/com/here/gluecodium/gradle/GluecodiumRunner.kt index 161d199ba1..161bb40328 100644 --- a/gluecodium-gradle/src/main/java/com/here/gluecodium/gradle/GluecodiumRunner.kt +++ b/gluecodium-gradle/src/main/java/com/here/gluecodium/gradle/GluecodiumRunner.kt @@ -33,9 +33,12 @@ internal class GluecodiumRunner( private val gluecodiumFactory: (GluecodiumOptions, GeneratorOptions) -> Gluecodium = { gluecodiumOptions: GluecodiumOptions, generatorOptions: GeneratorOptions -> Gluecodium(gluecodiumOptions, generatorOptions) - } + }, ) { - fun run(gluecodiumOptions: GluecodiumOptions, generatorOptions: GeneratorOptions) { + fun run( + gluecodiumOptions: GluecodiumOptions, + generatorOptions: GeneratorOptions, + ) { val executionResult = gluecodiumFactory(gluecodiumOptions, generatorOptions).execute() if (!executionResult) { throw GradleException("Gluecodium code generation failed. See log for details.") diff --git a/gluecodium-gradle/src/main/java/com/here/gluecodium/gradle/GluecodiumTask.kt b/gluecodium-gradle/src/main/java/com/here/gluecodium/gradle/GluecodiumTask.kt index 1c00c9f34a..3072f287a1 100644 --- a/gluecodium-gradle/src/main/java/com/here/gluecodium/gradle/GluecodiumTask.kt +++ b/gluecodium-gradle/src/main/java/com/here/gluecodium/gradle/GluecodiumTask.kt @@ -158,13 +158,18 @@ open class GluecodiumTask : SourceTask() { logProperty("cppNamespace", cppNamespace) logProperty("cppInternalNamespace", cppInternalNamespace) logProperty( - "cppExportMacroName", cppExportMacroName, - DEFAULT_VALUE_STRING + " " + GeneratorOptions.DEFAULT_CPP_EXPORT_MACRO_NAME + "cppExportMacroName", + cppExportMacroName, + DEFAULT_VALUE_STRING + " " + GeneratorOptions.DEFAULT_CPP_EXPORT_MACRO_NAME, ) logProperty("cppNameRules", cppNameRules, DEFAULT_VALUE_STRING) } - private fun logProperty(optionName: String, property: Property<*>, defaultValue: String = "") { + private fun logProperty( + optionName: String, + property: Property<*>, + defaultValue: String = "", + ) { logger.debug(GLUECODIUM_OPTIONS_FORMAT, optionName, property.orNull ?: defaultValue) } diff --git a/gluecodium/src/main/java/com/here/gluecodium/Gluecodium.kt b/gluecodium/src/main/java/com/here/gluecodium/Gluecodium.kt index 23acd225d3..7f9f63b2b4 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/Gluecodium.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/Gluecodium.kt @@ -60,18 +60,19 @@ import kotlin.system.exitProcess class Gluecodium( private val gluecodiumOptions: GluecodiumOptions, private val generatorOptions: GeneratorOptions, - private val modelLoader: LimeModelLoader = LimeModelLoader.getLoaders().first() + private val modelLoader: LimeModelLoader = LimeModelLoader.getLoaders().first(), ) { - internal val cache = SplitSourceSetCache( - gluecodiumOptions.outputDir, - gluecodiumOptions.commonOutputDir, - gluecodiumOptions.isEnableCaching - ) + internal val cache = + SplitSourceSetCache( + gluecodiumOptions.outputDir, + gluecodiumOptions.commonOutputDir, + gluecodiumOptions.isEnableCaching, + ) init { try { LogManager.getLogManager().readConfiguration( - Gluecodium::class.java.classLoader.getResourceAsStream("logging.properties") + Gluecodium::class.java.classLoader.getResourceAsStream("logging.properties"), ) } catch (e: IOException) { e.printStackTrace() @@ -115,7 +116,7 @@ class Gluecodium( internal fun executeGenerator( generatorName: String, limeModel: LimeModel, - fileNamesCache: MutableMap + fileNamesCache: MutableMap, ): Boolean { LOGGER.fine("Using generator '$generatorName'") val generator = Generator.initializeGenerator(generatorName, generatorOptions) @@ -125,12 +126,13 @@ class Gluecodium( } LOGGER.fine("Initialized generator '$generatorName'") - val outputFiles = try { - generator.generate(limeModel) - } catch (e: LimeModelLoaderException) { - LOGGER.severe(e.message) - return false - } + val outputFiles = + try { + generator.generate(limeModel) + } catch (e: LimeModelLoaderException) { + LOGGER.severe(e.message) + return false + } val outputSuccessful = output(generatorName, outputFiles) val processedWithoutCollisions = checkForFileNameCollisions(fileNamesCache, outputFiles, generatorName) @@ -149,7 +151,10 @@ class Gluecodium( return generators } - internal fun output(generatorName: String, files: List): Boolean { + internal fun output( + generatorName: String, + files: List, + ): Boolean { val filesToBeWritten = cache.updateCache(generatorName, files) val mainFiles = filesToBeWritten.filter { it.sourceSet == GeneratedFile.SourceSet.MAIN } val commonFiles = filesToBeWritten.filter { it.sourceSet == GeneratedFile.SourceSet.COMMON } @@ -163,8 +168,9 @@ class Gluecodium( LimeModelFilter.filter(limeModel) { LimeModelSkipPredicates.shouldRetainElement(it, generatorOptions.tags) } val limeLogger = LimeLogger(LOGGER, filteredModel.fileNameMap) val typeRefsValidationResult = LimeTypeRefsValidator(limeLogger).validate(filteredModel) - val validators = getIndependentValidators(limeLogger) + - if (typeRefsValidationResult) getTypeRefDependentValidators(limeLogger) else emptyList() + val validators = + getIndependentValidators(limeLogger) + + if (typeRefsValidationResult) getTypeRefDependentValidators(limeLogger) else emptyList() val validationResults = validators.map { it.invoke(filteredModel) } return typeRefsValidationResult && !validationResults.contains(false) } @@ -179,7 +185,7 @@ class Gluecodium( { LimeFunctionsValidator(limeLogger).validate(it) }, { LimeOptimizedListsValidator(limeLogger).validate(it) }, { LimeFieldConstructorsValidator(limeLogger).validate(it) }, - { LimeValuesValidator(limeLogger).validate(it) } + { LimeValuesValidator(limeLogger).validate(it) }, ) private fun getIndependentValidators(limeLogger: LimeLogger) = @@ -189,7 +195,7 @@ class Gluecodium( { LimePropertiesValidator(limeLogger).validate(it) }, { LimeFunctionsValidator(limeLogger).validate(it) }, { LimeSkipValidator(limeLogger).validate(it) }, - { LimeAsyncValidator(limeLogger).validate(it) } + { LimeAsyncValidator(limeLogger).validate(it) }, ) companion object { @@ -210,7 +216,7 @@ class Gluecodium( private fun checkForFileNameCollisions( fileNamesCache: MutableMap, files: List, - generatorName: String + generatorName: String, ): Boolean { var succeeded = true for (file in files) { @@ -222,8 +228,10 @@ class Gluecodium( LOGGER.severe( String.format( "Generator '%s' is overwriting file %s created already by '%s' ", - generatorName, path, previousEntry - ) + generatorName, + path, + previousEntry, + ), ) succeeded = false } @@ -231,7 +239,10 @@ class Gluecodium( return succeeded } - private fun saveToDirectory(outputDir: String, files: List): Boolean { + private fun saveToDirectory( + outputDir: String, + files: List, + ): Boolean { try { FileOutput(File(outputDir)).output(files) } catch (ignored: IOException) { diff --git a/gluecodium/src/main/java/com/here/gluecodium/GluecodiumOptions.kt b/gluecodium/src/main/java/com/here/gluecodium/GluecodiumOptions.kt index 85bb5d584a..5a90862670 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/GluecodiumOptions.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/GluecodiumOptions.kt @@ -27,5 +27,5 @@ data class GluecodiumOptions( var generators: Set = setOf(), var isValidatingOnly: Boolean = false, var isEnableCaching: Boolean = false, - var isStrictMode: Boolean = false + var isStrictMode: Boolean = false, ) diff --git a/gluecodium/src/main/java/com/here/gluecodium/cache/FileOutput.kt b/gluecodium/src/main/java/com/here/gluecodium/cache/FileOutput.kt index 4606b7c4e9..e793f2af52 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/cache/FileOutput.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/cache/FileOutput.kt @@ -30,33 +30,35 @@ import java.nio.file.Paths import java.util.logging.Logger /** Write the generated files to disk. */ -internal class FileOutput @Throws(IOException::class) constructor(private val rootPath: File) { - init { - if (!rootPath.exists() && !rootPath.mkdir()) { - throw FileNotFoundException(rootPath.path + " (Can't create output directory)") +internal class FileOutput + @Throws(IOException::class) + constructor(private val rootPath: File) { + init { + if (!rootPath.exists() && !rootPath.mkdir()) { + throw FileNotFoundException(rootPath.path + " (Can't create output directory)") + } } - } - @Throws(IOException::class) - fun output(files: List) = files.forEach { output(it) } + @Throws(IOException::class) + fun output(files: List) = files.forEach { output(it) } - @Throws(IOException::class) - fun output(file: GeneratedFile) { - val targetFile = File(rootPath, file.targetFile.path) - LOGGER.fine("Writing $targetFile") + @Throws(IOException::class) + fun output(file: GeneratedFile) { + val targetFile = File(rootPath, file.targetFile.path) + LOGGER.fine("Writing $targetFile") - val path = Paths.get(targetFile.parent) - if (Files.notExists(path)) { - Files.createDirectories(path) - } + val path = Paths.get(targetFile.parent) + if (Files.notExists(path)) { + Files.createDirectories(path) + } - BufferedWriter(FileWriter(targetFile)).apply { - write(file.content) - close() + BufferedWriter(FileWriter(targetFile)).apply { + write(file.content) + close() + } } - } - companion object { - private val LOGGER = Logger.getLogger(FileOutput::class.java.name) + companion object { + private val LOGGER = Logger.getLogger(FileOutput::class.java.name) + } } -} diff --git a/gluecodium/src/main/java/com/here/gluecodium/cache/FileRemove.kt b/gluecodium/src/main/java/com/here/gluecodium/cache/FileRemove.kt index 3648cd3011..3f552111b4 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/cache/FileRemove.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/cache/FileRemove.kt @@ -27,20 +27,20 @@ import java.nio.file.Path import java.util.logging.Logger internal class FileRemove(private val rootDir: File?) { - @Throws(FileNotFoundException::class) fun removeFiles(absolutePaths: List?): Boolean { if (rootDir?.exists() == false || rootDir?.isDirectory == false) { throw FileNotFoundException( - "Accessing root directory '" + rootDir.path + "' failed" + "Accessing root directory '" + rootDir.path + "' failed", ) } absolutePaths?.forEach { try { // only remove regular files located below root dir - if (Files.isRegularFile(it) && it.toFile().canonicalPath - .startsWith(rootDir?.canonicalPath + File.separator) + if (Files.isRegularFile(it) && + it.toFile().canonicalPath + .startsWith(rootDir?.canonicalPath + File.separator) ) { Files.delete(it) } diff --git a/gluecodium/src/main/java/com/here/gluecodium/cache/SplitSourceSetCache.kt b/gluecodium/src/main/java/com/here/gluecodium/cache/SplitSourceSetCache.kt index af38ea7e77..74775643c9 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/cache/SplitSourceSetCache.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/cache/SplitSourceSetCache.kt @@ -31,12 +31,14 @@ import java.io.File class SplitSourceSetCache( private val outputDir: String, private val commonOutputDir: String, - private val isEnableCaching: Boolean + private val isEnableCaching: Boolean, ) { // Cache for the main source set, can be null if main directory is nested inside common private var mainCacheStrategy: CachingStrategy? = null + // Cache for common code, can be null if common code resides inside main directory private var commonCacheStrategy: CachingStrategy? = null + // Subdirectory of the nested source set in case it is nested private var prefix: String = "" @@ -62,19 +64,21 @@ class SplitSourceSetCache( } private fun initMain() { - mainCacheStrategy = CachingStrategyCreator.initializeCaching( - isEnableCaching, - outputDir, - Generator.allGeneratorShortNames - ) + mainCacheStrategy = + CachingStrategyCreator.initializeCaching( + isEnableCaching, + outputDir, + Generator.allGeneratorShortNames, + ) } private fun initCommon() { - commonCacheStrategy = CachingStrategyCreator.initializeCaching( - isEnableCaching, - commonOutputDir, - Generator.allGeneratorShortNames - ) + commonCacheStrategy = + CachingStrategyCreator.initializeCaching( + isEnableCaching, + commonOutputDir, + Generator.allGeneratorShortNames, + ) } fun write(executionSucceeded: Boolean): Boolean { @@ -82,46 +86,58 @@ class SplitSourceSetCache( return commonCacheStrategy?.write(executionSucceeded) ?: true && success } - fun updateCache(generatorName: String, files: List) = - when { - mainCacheStrategy == null -> unprefix( + fun updateCache( + generatorName: String, + files: List, + ) = when { + mainCacheStrategy == null -> + unprefix( commonCacheStrategy?.updateCache( generatorName, - prefix(files, MAIN) + prefix(files, MAIN), ), - MAIN + MAIN, ) - commonCacheStrategy == null -> unprefix( + commonCacheStrategy == null -> + unprefix( mainCacheStrategy?.updateCache( generatorName, - prefix(files, COMMON) + prefix(files, COMMON), ), - COMMON + COMMON, ) - else -> { - val mainFiles = files.filter { it.sourceSet == MAIN } - val commonFiles = files.filter { it.sourceSet == COMMON } - ( - commonCacheStrategy?.updateCache(generatorName, commonFiles) - ?: emptyList() - ) + ( - mainCacheStrategy?.updateCache(generatorName, mainFiles) - ?: emptyList() - ) - } - } ?: emptyList() + else -> { + val mainFiles = files.filter { it.sourceSet == MAIN } + val commonFiles = files.filter { it.sourceSet == COMMON } + ( + commonCacheStrategy?.updateCache(generatorName, commonFiles) + ?: emptyList() + ) + ( + mainCacheStrategy?.updateCache(generatorName, mainFiles) + ?: emptyList() + ) + } + } ?: emptyList() - private fun prefix(files: List, sourceSet: GeneratedFile.SourceSet) = - files.map { - if (it.sourceSet == sourceSet) - GeneratedFile(it.content, prefix + it.targetFile, it.sourceSet) - else it + private fun prefix( + files: List, + sourceSet: GeneratedFile.SourceSet, + ) = files.map { + if (it.sourceSet == sourceSet) { + GeneratedFile(it.content, prefix + it.targetFile, it.sourceSet) + } else { + it } + } - private fun unprefix(files: List?, sourceSet: GeneratedFile.SourceSet) = - files?.map { - if (it.sourceSet == sourceSet) - GeneratedFile(it.content, it.targetFile.path.removePrefix(prefix), it.sourceSet) - else it + private fun unprefix( + files: List?, + sourceSet: GeneratedFile.SourceSet, + ) = files?.map { + if (it.sourceSet == sourceSet) { + GeneratedFile(it.content, it.targetFile.path.removePrefix(prefix), it.sourceSet) + } else { + it } + } } diff --git a/gluecodium/src/main/java/com/here/gluecodium/cli/OptionReader.kt b/gluecodium/src/main/java/com/here/gluecodium/cli/OptionReader.kt index 6b4eab3966..328b48f00a 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/cli/OptionReader.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/cli/OptionReader.kt @@ -39,110 +39,112 @@ import java.io.File import java.nio.file.Paths object OptionReader { - private val options: Options = Options().run { - addOption("input", true, "The path or the file to use for generation") - addOption("output", true, "Generated files output directory") - addOption( - "commonoutput", - "common-output-dir", - true, - "Common generated files output directory, defaults to be the same as output" - ) - addOption("options", true, "Options file to load options from") - addOption("auxinput", true, "Auxiliary IDL sources that are loaded but not generated from") - addOption("javapackage", true, "Java package name") - addOption( - "javanonnullannotation", - true, - "Java @NonNull annotation full name including package" - ) - addOption( - "javanullableannotation", - true, - "Java @Nullable annotation full name including package" - ) - addOption( - "intpackage", - "java-internal-package", - true, - "Java package name to append to 'javapackage' for internal types." - ) - addOption("help", false, "Shows this help and exits.") - addOption("version", false, "Prints version info and exits.") - addOption( - "validate", - "validate-only", - false, - "Perform validation of input files without generating any code." - ) - addOption( - "cache", - "enable-caching", - false, - "enable caching of output files, only available if output destination is set" - ) - addOption( - Option( - "generators", + private val options: Options = + Options().run { + addOption("input", true, "The path or the file to use for generation") + addOption("output", true, "Generated files output directory") + addOption( + "commonoutput", + "common-output-dir", true, - "List of generators to use, separated by comma. If empty, all available generators are used. Available generators: " + - Generator.allGeneratorShortNames.joinToString(", ") + "\n" - ).apply { - valueSeparator = ',' - setOptionalArg(true) - args = Option.UNLIMITED_VALUES - } - ) - addOption( - "copyright", - "copyright-header", - true, - "Specify the path for the file containing the copyright header that will be appended to all the generated files." - ) - addOption( - "intnamespace", - "cpp-internal-namespace", - true, - "C++ namespace for internal (non-API) headers. Multiple namespace levels may be separated with '.'." - ) - addOption("cppnamespace", true, "C++ namespace for public (API) headers.") - addOption("cppexport", true, "C++ export macro name for explicit symbols exporting.") - addOption("cppexportcommon", true, "C++ export macro name for exporting explicit symbols from `common` dir.") - addOption("internalprefix", true, "Name prefix for internal conversion functions in Swift.") - addOption("libraryname", true, "Name of the generated library for some generators (e.g. Dart).") - addOption("dartlookuperrormessage", true, "Custom error message for when Dart FFI function lookup fails.") - addOption( - "werror", - "warning-as-error", - true, - "Treat the specified validation warning type as an error. Possible values: " + - listOf( - GeneratorOptions.WARNING_DOC_LINKS, - GeneratorOptions.WARNING_DEPRECATED_ATTRIBUTES, - GeneratorOptions.WARNING_DART_OVERLOADS - ).joinToString() - ) - addOption( - "swiftexpose", - "swift-expose-internals", - false, - "Expose `internal` Swift generated code as `public` for reuse across several frameworks." - ) - addOption("strict", "strict-mode", false, "Use 'strict' validation rules for `struct` declarations.") - addOption("tag", true, "Add a custom tag for @Skip attributes.") - addOption("cppnamerules", true, "C++ name rules property file.") - addOption("javanamerules", true, "Java name rules property file.") - addOption("swiftnamerules", true, "Swift name rules property file.") - addOption("dartnamerules", true, "Dart name rules property file.") - } + "Common generated files output directory, defaults to be the same as output", + ) + addOption("options", true, "Options file to load options from") + addOption("auxinput", true, "Auxiliary IDL sources that are loaded but not generated from") + addOption("javapackage", true, "Java package name") + addOption( + "javanonnullannotation", + true, + "Java @NonNull annotation full name including package", + ) + addOption( + "javanullableannotation", + true, + "Java @Nullable annotation full name including package", + ) + addOption( + "intpackage", + "java-internal-package", + true, + "Java package name to append to 'javapackage' for internal types.", + ) + addOption("help", false, "Shows this help and exits.") + addOption("version", false, "Prints version info and exits.") + addOption( + "validate", + "validate-only", + false, + "Perform validation of input files without generating any code.", + ) + addOption( + "cache", + "enable-caching", + false, + "enable caching of output files, only available if output destination is set", + ) + addOption( + Option( + "generators", + true, + "List of generators to use, separated by comma. If empty, all available generators are used. Available generators: " + + Generator.allGeneratorShortNames.joinToString(", ") + "\n", + ).apply { + valueSeparator = ',' + setOptionalArg(true) + args = Option.UNLIMITED_VALUES + }, + ) + addOption( + "copyright", + "copyright-header", + true, + "Specify the path for the file containing the copyright header that will be appended to all the generated files.", + ) + addOption( + "intnamespace", + "cpp-internal-namespace", + true, + "C++ namespace for internal (non-API) headers. Multiple namespace levels may be separated with '.'.", + ) + addOption("cppnamespace", true, "C++ namespace for public (API) headers.") + addOption("cppexport", true, "C++ export macro name for explicit symbols exporting.") + addOption("cppexportcommon", true, "C++ export macro name for exporting explicit symbols from `common` dir.") + addOption("internalprefix", true, "Name prefix for internal conversion functions in Swift.") + addOption("libraryname", true, "Name of the generated library for some generators (e.g. Dart).") + addOption("dartlookuperrormessage", true, "Custom error message for when Dart FFI function lookup fails.") + addOption( + "werror", + "warning-as-error", + true, + "Treat the specified validation warning type as an error. Possible values: " + + listOf( + GeneratorOptions.WARNING_DOC_LINKS, + GeneratorOptions.WARNING_DEPRECATED_ATTRIBUTES, + GeneratorOptions.WARNING_DART_OVERLOADS, + ).joinToString(), + ) + addOption( + "swiftexpose", + "swift-expose-internals", + false, + "Expose `internal` Swift generated code as `public` for reuse across several frameworks.", + ) + addOption("strict", "strict-mode", false, "Use 'strict' validation rules for `struct` declarations.") + addOption("tag", true, "Add a custom tag for @Skip attributes.") + addOption("cppnamerules", true, "C++ name rules property file.") + addOption("javanamerules", true, "Java name rules property file.") + addOption("swiftnamerules", true, "Swift name rules property file.") + addOption("dartnamerules", true, "Dart name rules property file.") + } @Throws(OptionReaderException::class) fun read(args: Array): Pair? { - val cmd = try { - DefaultParser().parse(this.options, args) - } catch (e: ParseException) { - throw OptionReaderException(e) - } + val cmd = + try { + DefaultParser().parse(this.options, args) + } catch (e: ParseException) { + throw OptionReaderException(e) + } if (cmd.hasOption("help")) { printUsage() @@ -152,21 +154,24 @@ object OptionReader { return null } - val optionsConfig = when { - cmd.hasOption("options") -> readConfigFile(cmd.getOptionValue("options")) - else -> null - } + val optionsConfig = + when { + cmd.hasOption("options") -> readConfigFile(cmd.getOptionValue("options")) + else -> null + } + fun getStringListValue(key: String) = cmd.getOptionValues(key)?.toList() ?: optionsConfig?.getOrNull(Key(key, listType(stringType))) + fun getStringValue(key: String) = cmd.getOptionValues(key)?.also { if (it.size > 1) { throw OptionReaderException("multiple values for option: $key") } }?.get(0) ?: optionsConfig?.getOrNull(Key(key, stringType)) - fun getFlagValue(key: String) = - cmd.hasOption(key) || optionsConfig?.getOrNull(Key(key, booleanType)) == true + + fun getFlagValue(key: String) = cmd.hasOption(key) || optionsConfig?.getOrNull(Key(key, booleanType)) == true val gluecodiumOptions = GluecodiumOptions() @@ -228,9 +233,10 @@ object OptionReader { } @Throws(OptionReaderException::class) - fun readConfigFile(configFilePath: String?, defaultConfig: Configuration) = - configFilePath?.let { readConfigFile(it) overriding defaultConfig } ?: defaultConfig + fun readConfigFile( + configFilePath: String?, + defaultConfig: Configuration, + ) = configFilePath?.let { readConfigFile(it) overriding defaultConfig } ?: defaultConfig - fun parseAnnotation(argument: String?) = - argument?.split('.')?.let { Pair(it.last(), it.dropLast(1)) } + fun parseAnnotation(argument: String?) = argument?.split('.')?.let { Pair(it.last(), it.dropLast(1)) } } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/cbridge/CBridgeCppNameResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/cbridge/CBridgeCppNameResolver.kt index d6a01825e4..df5b439a8c 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/cbridge/CBridgeCppNameResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/cbridge/CBridgeCppNameResolver.kt @@ -36,9 +36,8 @@ import com.here.gluecodium.model.lime.LimeTypeRef internal class CBridgeCppNameResolver( limeReferenceMap: Map, private val cppFullNameResolver: CppFullNameResolver, - private val cppShortNameResolver: CppNameResolver + private val cppShortNameResolver: CppNameResolver, ) : ReferenceMapBasedResolver(limeReferenceMap), NameResolver { - override fun resolveName(element: Any): String = when (element) { is LimeTypeRef, is LimeBasicType, is LimeGenericType -> cppShortNameResolver.resolveName(element) diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/cbridge/CBridgeFileNames.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/cbridge/CBridgeFileNames.kt index 9428c23de9..97b4bb4130 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/cbridge/CBridgeFileNames.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/cbridge/CBridgeFileNames.kt @@ -22,9 +22,7 @@ package com.here.gluecodium.generator.cbridge import com.here.gluecodium.model.lime.LimeNamedElement internal class CBridgeFileNames(private val rootNamespace: List) { - fun getHeaderFilePath(limeElement: LimeNamedElement) = - CBridgeNameRules.createPath(limeElement, rootNamespace, "include", ".h") + fun getHeaderFilePath(limeElement: LimeNamedElement) = CBridgeNameRules.createPath(limeElement, rootNamespace, "include", ".h") - fun getImplFilePath(limeElement: LimeNamedElement) = - CBridgeNameRules.createPath(limeElement, rootNamespace, "src", ".cpp") + fun getImplFilePath(limeElement: LimeNamedElement) = CBridgeNameRules.createPath(limeElement, rootNamespace, "src", ".cpp") } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/cbridge/CBridgeGenerator.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/cbridge/CBridgeGenerator.kt index ac97c2bf9a..ed58faa32a 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/cbridge/CBridgeGenerator.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/cbridge/CBridgeGenerator.kt @@ -63,7 +63,7 @@ internal class CBridgeGenerator( private val internalNamespace: List, cppNameRules: CppNameRules, private val nameResolver: CBridgeNameResolver, - activeTags: Set + activeTags: Set, ) { val cppNameResolver = CppNameResolver(limeReferenceMap, internalNamespace, nameCache, forceFollowThrough = true) private val cppRefNameResolver = @@ -85,16 +85,17 @@ internal class CBridgeGenerator( }, collectTypeRefImports = true, collectOwnImports = true, - parentTypeFilter = { it is LimeInterface } + parentTypeFilter = { it is LimeInterface }, ) val genericTypesCollector = GenericTypesCollector(nameResolver) fun generate(rootElement: LimeNamedElement): List { - val optimizedLists = when (rootElement) { - is LimeContainer -> OptimizedListsCollector().getAllOptimizedLists(rootElement) - else -> emptyMap() - } + val optimizedLists = + when (rootElement) { + is LimeContainer -> OptimizedListsCollector().getAllOptimizedLists(rootElement) + else -> emptyMap() + } val templateData = mutableMapOf("model" to rootElement, "internalNamespace" to internalNamespace) val nameResolvers = mapOf("" to nameResolver, "C++" to cppRefNameResolver) @@ -103,12 +104,13 @@ internal class CBridgeGenerator( val selfInclude = Include.createInternalInclude(headerFilePath) templateData["includes"] = headerIncludeCollector.collectImports(rootElement).distinct().sorted() - selfInclude templateData["contentTemplate"] = (selectHeaderTemplate(rootElement) ?: return emptyList()) - val headerFileContent = TemplateEngine.render( - "cbridge/CBridgeHeader", - templateData, - nameResolvers, - generatorPredicates.predicates - ) + val headerFileContent = + TemplateEngine.render( + "cbridge/CBridgeHeader", + templateData, + nameResolvers, + generatorPredicates.predicates, + ) val headerFile = GeneratedFile(headerFileContent, headerFilePath) templateData["contentTemplate"] = selectImplTemplate(rootElement) ?: return listOf(headerFile) @@ -119,7 +121,7 @@ internal class CBridgeGenerator( "cbridge/CBridgeImplementation", templateData, nameResolvers, - generatorPredicates.predicates + generatorPredicates.predicates, ) val implFile = GeneratedFile(implFileContent, fileNames.getImplFilePath(rootElement)) @@ -131,32 +133,35 @@ internal class CBridgeGenerator( val allTypes = limeModel.flatMap { LimeTypeHelper.getAllTypes(it) } val allParentTypes = LimeTypeHelper.getAllParentTypes(allTypes) val genericTypes = genericTypesCollector.getAllGenericTypes(allTypes + allParentTypes) - val templateData = mutableMapOf( - "lists" to genericTypes.filterIsInstance(), - "maps" to genericTypes.filterIsInstance(), - "sets" to genericTypes.filterIsInstance(), - "internalNamespace" to internalNamespace - ) + val templateData = + mutableMapOf( + "lists" to genericTypes.filterIsInstance(), + "maps" to genericTypes.filterIsInstance(), + "sets" to genericTypes.filterIsInstance(), + "internalNamespace" to internalNamespace, + ) val nameResolvers = mapOf("" to nameResolver, "C++" to cppRefNameResolver) - val headerIncludes = genericTypes.flatMap { headerIncludeCollector.collectImports(it) } + - listOfNotNull( - CBridgeHeaderIncludeResolver.INT_INCLUDE.takeIf { genericTypes.any { it is LimeList } }, - CBridgeHeaderIncludeResolver.BOOL_INCLUDE.takeIf { genericTypes.any { it !is LimeList } } - ) + val headerIncludes = + genericTypes.flatMap { headerIncludeCollector.collectImports(it) } + + listOfNotNull( + CBridgeHeaderIncludeResolver.INT_INCLUDE.takeIf { genericTypes.any { it is LimeList } }, + CBridgeHeaderIncludeResolver.BOOL_INCLUDE.takeIf { genericTypes.any { it !is LimeList } }, + ) templateData["includes"] = headerIncludes.distinct().sorted() val headerFileContent = TemplateEngine.render( "cbridge/CBridgeCollectionsHeader", templateData, nameResolvers, - generatorPredicates.predicates + generatorPredicates.predicates, ) val headerFile = GeneratedFile(headerFileContent, CBRIDGE_COLLECTIONS_HEADER) - val implIncludes = genericTypes.flatMap { implIncludeCollector.collectImports(it) } + - CBridgeImplIncludeResolver.BASE_HANDLE_IMPL_INCLUDE + - CppLibraryIncludes.OPTIONAL + val implIncludes = + genericTypes.flatMap { implIncludeCollector.collectImports(it) } + + CBridgeImplIncludeResolver.BASE_HANDLE_IMPL_INCLUDE + + CppLibraryIncludes.OPTIONAL templateData["includes"] = listOf(Include.createInternalInclude(CBRIDGE_COLLECTIONS_HEADER)) + implIncludes.distinct().sorted() val implFileContent = @@ -164,14 +169,17 @@ internal class CBridgeGenerator( "cbridge/CBridgeCollectionsImpl", templateData, nameResolvers, - generatorPredicates.predicates + generatorPredicates.predicates, ) val implFile = GeneratedFile(implFileContent, CBRIDGE_COLLECTIONS_IMPL) return listOf(headerFile, implFile) } - private fun generateOptimizedListFiles(limeElement: LimeElement?, lists: List?): List { + private fun generateOptimizedListFiles( + limeElement: LimeElement?, + lists: List?, + ): List { if (limeElement !is LimeNamedElement || lists.isNullOrEmpty()) return emptyList() val containerData = mutableMapOf("container" to limeElement, "internalNamespace" to internalNamespace) @@ -181,7 +189,7 @@ internal class CBridgeGenerator( private fun generateOptimizedListFile( limeList: LimeList, container: LimeNamedElement, - containerData: MutableMap + containerData: MutableMap, ): List { val elementType = limeList.elementType.type.actualType val infix = "_${elementType.name}LazyList" @@ -191,25 +199,27 @@ internal class CBridgeGenerator( containerData["elementType"] = limeList.elementType val nameResolvers = mapOf("" to nameResolver, "C++" to cppRefNameResolver) - val headerFile = GeneratedFile( - TemplateEngine.render( - "cbridge/LazyListHeader", - containerData, - nameResolvers, - generatorPredicates.predicates - ), - headerFileName - ) + val headerFile = + GeneratedFile( + TemplateEngine.render( + "cbridge/LazyListHeader", + containerData, + nameResolvers, + generatorPredicates.predicates, + ), + headerFileName, + ) val implIncludes = implIncludeCollector.collectImports(elementType) + Include.createInternalInclude(headerFileName) containerData["includes"] = implIncludes.distinct().sorted() val implFileName = CBridgeNameRules.createPath(container, rootNamespace, "src", ".cpp", infix) - val implFile = GeneratedFile( - TemplateEngine.render("cbridge/LazyListImpl", containerData, nameResolvers, generatorPredicates.predicates), - implFileName - ) + val implFile = + GeneratedFile( + TemplateEngine.render("cbridge/LazyListImpl", containerData, nameResolvers, generatorPredicates.predicates), + implFileName, + ) return listOf(headerFile, implFile) } @@ -218,45 +228,52 @@ internal class CBridgeGenerator( listOf( generateHelperContent("BaseHandleImpl", BASE_HANDLE_IMPL_FILE), generateHelperContent( - "StringHandle", Paths.get(CBRIDGE_PUBLIC, SRC_DIR, "StringHandle.cpp").toString() + "StringHandle", + Paths.get(CBRIDGE_PUBLIC, SRC_DIR, "StringHandle.cpp").toString(), ), generateHelperContent( "ByteArrayHandle", - Paths.get(CBRIDGE_PUBLIC, SRC_DIR, "ByteArrayHandle.cpp").toString() + Paths.get(CBRIDGE_PUBLIC, SRC_DIR, "ByteArrayHandle.cpp").toString(), ), generateHelperContent( "LocaleHandle", - Paths.get(CBRIDGE_PUBLIC, SRC_DIR, "LocaleHandle.cpp").toString() + Paths.get(CBRIDGE_PUBLIC, SRC_DIR, "LocaleHandle.cpp").toString(), ), generateHelperContent( "BuiltinHandle", - Paths.get(CBRIDGE_PUBLIC, SRC_DIR, "BuiltinHandle.cpp").toString() + Paths.get(CBRIDGE_PUBLIC, SRC_DIR, "BuiltinHandle.cpp").toString(), ), generateHelperContent( "TypeInitRepository", - Paths.get(CBRIDGE_INTERNAL, INCLUDE_DIR, "TypeInitRepository.h").toString() + Paths.get(CBRIDGE_INTERNAL, INCLUDE_DIR, "TypeInitRepository.h").toString(), ), generateHelperContent( "TypeInitRepositoryImpl", - Paths.get(CBRIDGE_PUBLIC, SRC_DIR, "TypeInitRepository.cpp").toString() + Paths.get(CBRIDGE_PUBLIC, SRC_DIR, "TypeInitRepository.cpp").toString(), ), generateHelperContent( "WrapperCacheHeader", Paths.get( - CBRIDGE_INTERNAL, INCLUDE_DIR, "WrapperCache.h" - ).toString() + CBRIDGE_INTERNAL, + INCLUDE_DIR, + "WrapperCache.h", + ).toString(), ), generateHelperContent( "WrapperCacheImpl", - Paths.get(CBRIDGE_PUBLIC, SRC_DIR, "WrapperCache.cpp").toString() - ) + Paths.get(CBRIDGE_PUBLIC, SRC_DIR, "WrapperCache.cpp").toString(), + ), ) - private fun generateHelperContent(template: String, path: String): GeneratedFile { - val content = TemplateEngine.render( - "cbridge/common/$template", - mapOf("internalNamespace" to internalNamespace) - ) + private fun generateHelperContent( + template: String, + path: String, + ): GeneratedFile { + val content = + TemplateEngine.render( + "cbridge/common/$template", + mapOf("internalNamespace" to internalNamespace), + ) return GeneratedFile(content, path, GeneratedFile.SourceSet.COMMON) } @@ -279,16 +296,20 @@ internal class CBridgeGenerator( class GenericTypesCollector(private val nameResolver: NameResolver) : LimeTypeRefsVisitor>() { - - override fun visitTypeRef(parentElement: LimeNamedElement, limeTypeRef: LimeTypeRef?): List { + override fun visitTypeRef( + parentElement: LimeNamedElement, + limeTypeRef: LimeTypeRef?, + ): List { val limeType = limeTypeRef?.type?.actualType as? LimeGenericType ?: return emptyList() - return listOf(limeType) + when (limeType) { - is LimeList -> visitTypeRef(parentElement, limeType.elementType) - is LimeSet -> visitTypeRef(parentElement, limeType.elementType) - is LimeMap -> visitTypeRef(parentElement, limeType.keyType) + - visitTypeRef(parentElement, limeType.valueType) - else -> emptyList() - } + return listOf(limeType) + + when (limeType) { + is LimeList -> visitTypeRef(parentElement, limeType.elementType) + is LimeSet -> visitTypeRef(parentElement, limeType.elementType) + is LimeMap -> + visitTypeRef(parentElement, limeType.keyType) + + visitTypeRef(parentElement, limeType.valueType) + else -> emptyList() + } } fun getAllGenericTypes(allTypes: List) = @@ -319,7 +340,7 @@ internal class CBridgeGenerator( Generator.copyCommonFile(Paths.get(CBRIDGE_PUBLIC, INCLUDE_DIR, "BuiltinHandle.h").toString(), ""), Generator.copyCommonFile(Paths.get(CBRIDGE_PUBLIC, INCLUDE_DIR, "ByteArrayHandle.h").toString(), ""), Generator.copyCommonFile(Paths.get(CBRIDGE_PUBLIC, INCLUDE_DIR, "LocaleHandle.h").toString(), ""), - Generator.copyCommonFile(PROXY_CACHE_FILENAME, "") + Generator.copyCommonFile(PROXY_CACHE_FILENAME, ""), ) } } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/cbridge/CBridgeGeneratorPredicates.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/cbridge/CBridgeGeneratorPredicates.kt index c438e987ad..51e273fddf 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/cbridge/CBridgeGeneratorPredicates.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/cbridge/CBridgeGeneratorPredicates.kt @@ -38,38 +38,41 @@ import com.here.gluecodium.model.lime.LimeTypeRef internal class CBridgeGeneratorPredicates( cppNameResolver: CppNameResolver, private val limeReferenceMap: Map, - private val activeTags: Set + private val activeTags: Set, ) { - val predicates = mapOf( - "hasCppGetter" to { limeField: Any -> - limeField is LimeField && cppNameResolver.resolveGetterName(limeField) != null - }, - "hasCppSetter" to { limeField: Any -> - limeField is LimeField && cppNameResolver.resolveSetterName(limeField) != null - }, - "hasImmutableFields" to { CommonGeneratorPredicates.hasImmutableFields(it) }, - "hasTypeRepository" to { CommonGeneratorPredicates.hasTypeRepository(it) }, - "isNonNullableEnum" to { limeTypeRef: Any -> - limeTypeRef is LimeTypeRef && !limeTypeRef.isNullable && limeTypeRef.type.actualType is LimeEnumeration - }, - "isComplexType" to fun(limeTypeRef: Any): Boolean { - if (limeTypeRef !is LimeTypeRef) return false - val limeType = limeTypeRef.type.actualType - return when { - limeTypeRef.isNullable -> true - limeType is LimeEnumeration -> false - limeType is LimeBasicType -> - !(limeType.typeId.isNumericType || limeType.typeId == BOOLEAN || limeType.typeId == VOID) - else -> true - } - }, - "needsRefSuffix" to { limeTypeRef: Any -> - limeTypeRef is LimeTypeRef && CppNameResolver.needsRefSuffix(limeTypeRef) - }, - "shouldRetain" to { limeElement: Any -> - limeElement is LimeNamedElement && shouldRetain(limeElement) - } - ) + val predicates = + mapOf( + "hasCppGetter" to { limeField: Any -> + limeField is LimeField && cppNameResolver.resolveGetterName(limeField) != null + }, + "hasCppSetter" to { limeField: Any -> + limeField is LimeField && cppNameResolver.resolveSetterName(limeField) != null + }, + "hasImmutableFields" to { CommonGeneratorPredicates.hasImmutableFields(it) }, + "hasTypeRepository" to { CommonGeneratorPredicates.hasTypeRepository(it) }, + "isNonNullableEnum" to { limeTypeRef: Any -> + limeTypeRef is LimeTypeRef && !limeTypeRef.isNullable && limeTypeRef.type.actualType is LimeEnumeration + }, + "isComplexType" to + + fun(limeTypeRef: Any): Boolean { + if (limeTypeRef !is LimeTypeRef) return false + val limeType = limeTypeRef.type.actualType + return when { + limeTypeRef.isNullable -> true + limeType is LimeEnumeration -> false + limeType is LimeBasicType -> + !(limeType.typeId.isNumericType || limeType.typeId == BOOLEAN || limeType.typeId == VOID) + else -> true + } + }, + "needsRefSuffix" to { limeTypeRef: Any -> + limeTypeRef is LimeTypeRef && CppNameResolver.needsRefSuffix(limeTypeRef) + }, + "shouldRetain" to { limeElement: Any -> + limeElement is LimeNamedElement && shouldRetain(limeElement) + }, + ) fun shouldRetain(limeElement: LimeNamedElement) = LimeModelSkipPredicates.shouldRetainCheckParent(limeElement, activeTags, SWIFT, limeReferenceMap) diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/cbridge/CBridgeHeaderIncludeResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/cbridge/CBridgeHeaderIncludeResolver.kt index 6d9783ff70..8c197f87fe 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/cbridge/CBridgeHeaderIncludeResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/cbridge/CBridgeHeaderIncludeResolver.kt @@ -39,9 +39,8 @@ import com.here.gluecodium.model.lime.LimeTypeRef import com.here.gluecodium.model.lime.LimeTypedElement internal class CBridgeHeaderIncludeResolver( - limeReferenceMap: Map + limeReferenceMap: Map, ) : ReferenceMapBasedResolver(limeReferenceMap), ImportsResolver { - override fun resolveElementImports(limeElement: LimeElement) = when (limeElement) { is LimeConstant -> emptyList() diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/cbridge/CBridgeImplIncludeResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/cbridge/CBridgeImplIncludeResolver.kt index f6a7294252..74a46fa04c 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/cbridge/CBridgeImplIncludeResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/cbridge/CBridgeImplIncludeResolver.kt @@ -46,7 +46,6 @@ import java.io.File internal class CBridgeImplIncludeResolver(private val cppIncludeResolver: CppIncludeResolver) : ImportsResolver { - override fun resolveElementImports(limeElement: LimeElement) = when (limeElement) { is LimeConstant -> emptyList() @@ -65,12 +64,13 @@ internal class CBridgeImplIncludeResolver(private val cppIncludeResolver: CppInc private fun resolveClassInterfaceIncludes(limeContainer: LimeContainerWithInheritance): List { val containerIncludes = resolveContainerIncludes(limeContainer) - val ownIncludes = listOfNotNull( - TYPE_INIT_REPOSITORY_INCLUDE, - WRAPPER_CACHE_INCLUDE, - CACHED_PROXY_BASE_INCLUDE.takeIf { limeContainer is LimeInterface }, - cppIncludeResolver.typeRepositoryInclude.takeIf { CommonGeneratorPredicates.hasTypeRepository(limeContainer) } - ) + val ownIncludes = + listOfNotNull( + TYPE_INIT_REPOSITORY_INCLUDE, + WRAPPER_CACHE_INCLUDE, + CACHED_PROXY_BASE_INCLUDE.takeIf { limeContainer is LimeInterface }, + cppIncludeResolver.typeRepositoryInclude.takeIf { CommonGeneratorPredicates.hasTypeRepository(limeContainer) }, + ) val parentIncludes = resolveParentIncludes(limeContainer) return containerIncludes + ownIncludes + parentIncludes } @@ -80,8 +80,7 @@ internal class CBridgeImplIncludeResolver(private val cppIncludeResolver: CppInc return limeInterface.parents.flatMap { cppIncludeResolver.resolveElementImports(it.type.actualType) } } - private fun resolveStructIncludes(limeStruct: LimeStruct) = - resolveContainerIncludes(limeStruct) + listOf(CppLibraryIncludes.OPTIONAL) + private fun resolveStructIncludes(limeStruct: LimeStruct) = resolveContainerIncludes(limeStruct) + listOf(CppLibraryIncludes.OPTIONAL) private fun resolveContainerIncludes(limeContainer: LimeContainer) = cppIncludeResolver.resolveElementImports(limeContainer) + @@ -107,18 +106,20 @@ internal class CBridgeImplIncludeResolver(private val cppIncludeResolver: CppInc when (limeType) { is LimeList -> cppIncludeResolver.resolveElementImports(limeType) + resolveTypeRefIncludes(limeType.elementType) is LimeSet -> cppIncludeResolver.resolveElementImports(limeType) + resolveTypeRefIncludes(limeType.elementType) - is LimeMap -> cppIncludeResolver.resolveElementImports(limeType) + resolveTypeRefIncludes(limeType.keyType) + - resolveTypeRefIncludes(limeType.valueType) + is LimeMap -> + cppIncludeResolver.resolveElementImports(limeType) + resolveTypeRefIncludes(limeType.keyType) + + resolveTypeRefIncludes(limeType.valueType) else -> emptyList() } - private fun resolveLambdaIncludes(limeLambda: LimeLambda) = cppIncludeResolver.resolveElementImports(limeLambda) + - listOf( - CppLibraryIncludes.NEW, - BASE_HANDLE_IMPL_INCLUDE, - CACHED_PROXY_BASE_INCLUDE, - CppLibraryIncludes.OPTIONAL - ) + private fun resolveLambdaIncludes(limeLambda: LimeLambda) = + cppIncludeResolver.resolveElementImports(limeLambda) + + listOf( + CppLibraryIncludes.NEW, + BASE_HANDLE_IMPL_INCLUDE, + CACHED_PROXY_BASE_INCLUDE, + CppLibraryIncludes.OPTIONAL, + ) companion object { val BASE_HANDLE_IMPL_INCLUDE = Include.createInternalInclude(createInternalHeaderPath("BaseHandleImpl.h")) diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/cbridge/CBridgeNameResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/cbridge/CBridgeNameResolver.kt index 914df031b5..da844f31b2 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/cbridge/CBridgeNameResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/cbridge/CBridgeNameResolver.kt @@ -47,9 +47,8 @@ internal class CBridgeNameResolver( limeReferenceMap: Map, private val swiftNameRules: SwiftNameRules, private val internalPrefix: String, - private val signatureResolver: PlatformSignatureResolver + private val signatureResolver: PlatformSignatureResolver, ) : ReferenceMapBasedResolver(limeReferenceMap), NameResolver { - override fun resolveName(element: Any): String = when (element) { is LimeGenericType -> resolveGenericTypeName(element) @@ -76,10 +75,11 @@ internal class CBridgeNameResolver( private fun resolveFunctionName(limeFunction: LimeFunction): String { val parentElement = getParentElement(limeFunction) - val functionName = when (parentElement) { - is LimeLambda -> "call" - else -> CBridgeNameRules.mangleName(swiftNameRules.getName(limeFunction)) - } + val functionName = + when (parentElement) { + is LimeLambda -> "call" + else -> CBridgeNameRules.mangleName(swiftNameRules.getName(limeFunction)) + } return (resolveNestedNames(parentElement) + functionName + getOverloadSuffix(limeFunction)).joinToString("_") } @@ -144,11 +144,12 @@ internal class CBridgeNameResolver( val limeType = limeTypeRef.type if (limeType is LimeTypeAlias) return resolveElementTypeName(limeType.typeRef) - val prefix = when { - limeTypeRef.isNullable -> "nullable_" - limeType is LimeBasicType -> "_" - else -> "" - } + val prefix = + when { + limeTypeRef.isNullable -> "nullable_" + limeType is LimeBasicType -> "_" + else -> "" + } val cppType = limeTypeRef.attributes.get(LimeAttributeType.CPP, LimeAttributeValueType.TYPE, String::class.java) val suffix = cppType?.let { "_" + mangleSignature(it) } ?: "" return prefix + resolveName(limeType) + suffix diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/cbridge/CBridgeNameRules.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/cbridge/CBridgeNameRules.kt index d6f125122b..6ebdb9ff54 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/cbridge/CBridgeNameRules.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/cbridge/CBridgeNameRules.kt @@ -41,11 +41,11 @@ internal object CBridgeNameRules { rootNamespace: List, subfolder: String, suffix: String, - infix: String = "" + infix: String = "", ): String { val fileName = "cbridge_" + getName(limeElement) + infix + suffix return ( listOf(CBRIDGE_PUBLIC, subfolder) + rootNamespace + limeElement.path.head + fileName - ).joinToString(File.separator) + ).joinToString(File.separator) } } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/common/CamelCaseNameResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/common/CamelCaseNameResolver.kt index 48dccc2cb6..1548e2d289 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/common/CamelCaseNameResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/common/CamelCaseNameResolver.kt @@ -20,7 +20,6 @@ package com.here.gluecodium.generator.common internal class CamelCaseNameResolver(private val mainResolver: NameResolver, upper: Boolean = false) : NameResolver { - val camelCase = if (upper) NameHelper::toUpperCamelCase else NameHelper::toLowerCamelCase override fun resolveName(element: Any) = camelCase(mainResolver.resolveName(element)) diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/common/CommentsProcessor.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/common/CommentsProcessor.kt index ce790b9d02..defb7567ef 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/common/CommentsProcessor.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/common/CommentsProcessor.kt @@ -37,7 +37,7 @@ import com.vladsch.flexmark.util.sequence.CharSubSequence abstract class CommentsProcessor( private val renderer: IRender, private val werror: Boolean, - parserOptions: DataHolder = DataSet() + parserOptions: DataHolder = DataSet(), ) { val hasError get() = werror && hasErrorFlag @@ -45,42 +45,48 @@ abstract class CommentsProcessor( private val parser = Parser.builder(parserOptions).build() private val logFunction: LimeLogger.(String, String) -> Unit = - if (werror) { elementName: String, message: String -> - this.error(elementName, message) - } else { elementName: String, message: String -> - this.warning(elementName, message) + if (werror) { + { elementName: String, message: String -> + this.error(elementName, message) + } + } else { + { elementName: String, message: String -> + this.warning(elementName, message) + } } fun process( limeFullName: String, comment: String, limeToLanguage: Map, - logger: LimeLogger? + logger: LimeLogger?, ): String { val document = parser.parse(comment.trim()) val path = limeFullName.split(".") - val linkRefHandler = VisitHandler(LinkRef::class.java) { - if (it.isDefined) return@VisitHandler + val linkRefHandler = + VisitHandler(LinkRef::class.java) { + if (it.isDefined) return@VisitHandler - val rawReference = it.reference.toString() - val normalizedReference = normalizeReference(rawReference) - for (i in path.size downTo 0) { - val child = (path.take(i) + normalizedReference).joinToString(".") - val element = limeToLanguage[child] - if (element != null) { - processLink(it, element, child) - return@VisitHandler + val rawReference = it.reference.toString() + val normalizedReference = normalizeReference(rawReference) + for (i in path.size downTo 0) { + val child = (path.take(i) + normalizedReference).joinToString(".") + val element = limeToLanguage[child] + if (element != null) { + processLink(it, element, child) + return@VisitHandler + } } + logger?.logFunction(limeFullName, "Failed to resolve documentation reference [$rawReference]") + hasErrorFlag = true } - logger?.logFunction(limeFullName, "Failed to resolve documentation reference [$rawReference]") - hasErrorFlag = true - } - val codeBlockHandler = VisitHandler(Code::class.java) { - if (it.text.toString() == STANDART_NULL_REFERENCE) { - it.text = CharSubSequence.of(nullReference) + val codeBlockHandler = + VisitHandler(Code::class.java) { + if (it.text.toString() == STANDART_NULL_REFERENCE) { + it.text = CharSubSequence.of(nullReference) + } } - } val autoLinkHandler = VisitHandler(AutoLink::class.java) { processAutoLink(it) } NodeVisitor(linkRefHandler, codeBlockHandler, autoLinkHandler).visit(document) @@ -101,8 +107,14 @@ abstract class CommentsProcessor( return name + "(" + signature.split(",").joinToString(",") { it.split('.').last() } } - abstract fun processLink(linkNode: LinkRef, linkReference: String, limeFullName: String) + abstract fun processLink( + linkNode: LinkRef, + linkReference: String, + limeFullName: String, + ) + open fun processAutoLink(linkNode: AutoLink) {} + open fun postRenderDocument(renderedDocument: String): String = renderedDocument open val nullReference = STANDART_NULL_REFERENCE diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/common/CommonGeneratorPredicates.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/common/CommonGeneratorPredicates.kt index a627b1663d..0ef868e583 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/common/CommonGeneratorPredicates.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/common/CommonGeneratorPredicates.kt @@ -40,26 +40,31 @@ import com.here.gluecodium.model.lime.LimeTypeAlias * Predicates used by `ifPredicate`/`unlessPredicate` template helpers in several generators. */ internal object CommonGeneratorPredicates { - fun hasAnyComment(limeElement: Any, platformTag: String) = - when (limeElement) { - is LimeFunction -> limeElement.run { + fun hasAnyComment( + limeElement: Any, + platformTag: String, + ) = when (limeElement) { + is LimeFunction -> + limeElement.run { comment.getFor(platformTag).isNotBlank() || comment.isExcluded || returnType.comment.getFor(platformTag).isNotBlank() || (thrownType?.comment?.getFor(platformTag)?.isEmpty() == false) || attributes.have(LimeAttributeType.DEPRECATED) || parameters.any { it.comment.getFor(platformTag).isNotBlank() } } - is LimeFieldConstructor -> limeElement.run { + is LimeFieldConstructor -> + limeElement.run { comment.getFor(platformTag).isNotBlank() || comment.isExcluded || attributes.have(LimeAttributeType.DEPRECATED) || struct.constructorComment.getFor(platformTag).isNotBlank() } - is LimeNamedElement -> limeElement.run { + is LimeNamedElement -> + limeElement.run { comment.getFor(platformTag).isNotBlank() || comment.isExcluded || attributes.have(LimeAttributeType.DEPRECATED) } - else -> false - } + else -> false + } fun hasImmutableFields(limeStruct: Any) = when { @@ -90,7 +95,7 @@ internal object CommonGeneratorPredicates { fun needsImportsForSkippedField( limeElement: LimeNamedElement, platformAttribute: LimeAttributeType, - referenceMap: Map + referenceMap: Map, ): Boolean { if (limeElement !is LimeField) return false if (!limeElement.attributes.have(platformAttribute, LimeAttributeValueType.SKIP)) return false @@ -99,16 +104,21 @@ internal object CommonGeneratorPredicates { return hasImmutableFields(limeStruct) } - fun isInternal(limeElement: LimeNamedElement, platformAttribute: LimeAttributeType) = - when { - limeElement.attributes.have(platformAttribute, LimeAttributeValueType.PUBLIC) -> false - limeElement.attributes.have(platformAttribute, LimeAttributeValueType.INTERNAL) -> true - else -> limeElement.attributes.have(LimeAttributeType.INTERNAL) - } + fun isInternal( + limeElement: LimeNamedElement, + platformAttribute: LimeAttributeType, + ) = when { + limeElement.attributes.have(platformAttribute, LimeAttributeValueType.PUBLIC) -> false + limeElement.attributes.have(platformAttribute, LimeAttributeValueType.INTERNAL) -> true + else -> limeElement.attributes.have(LimeAttributeType.INTERNAL) + } private fun getAllFieldTypes(limeType: LimeType) = getAllFieldTypesRec(getLeafType(limeType), mutableSetOf()) - private fun getAllFieldTypesRec(leafType: LimeType, visitedTypes: MutableSet): List { + private fun getAllFieldTypesRec( + leafType: LimeType, + visitedTypes: MutableSet, + ): List { if (leafType !is LimeStruct) return listOf(leafType) visitedTypes += leafType diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/common/GeneratedFile.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/common/GeneratedFile.kt index 67e1d4d970..d5926f7508 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/common/GeneratedFile.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/common/GeneratedFile.kt @@ -24,11 +24,12 @@ import java.io.File data class GeneratedFile( val content: String, private val targetFilename: String, - val sourceSet: SourceSet = SourceSet.MAIN + val sourceSet: SourceSet = SourceSet.MAIN, ) { enum class SourceSet { COMMON, - MAIN + MAIN, } + val targetFile: File = File(targetFilename) } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/common/Generator.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/common/Generator.kt index e8c0429c01..bf6ae62aec 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/common/Generator.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/common/Generator.kt @@ -27,7 +27,6 @@ import java.util.ServiceLoader /** The base interface for all the generators. */ interface Generator { - /** Short name of the generator. */ val shortName: String @@ -43,24 +42,31 @@ interface Generator { fun generate(limeModel: LimeModel): List companion object { - private val allGenerators = ServiceLoader.load(Generator::class.java).iterator().asSequence() - .sortedBy { it.shortName }.associateByTo(LinkedHashMap()) { it.shortName } + private val allGenerators = + ServiceLoader.load(Generator::class.java).iterator().asSequence() + .sortedBy { it.shortName }.associateByTo(LinkedHashMap()) { it.shortName } val allGeneratorShortNames get() = allGenerators.keys - fun initializeGenerator(shortName: String, options: GeneratorOptions) = - allGenerators[shortName]?.also { it.initialize(options) } + fun initializeGenerator( + shortName: String, + options: GeneratorOptions, + ) = allGenerators[shortName]?.also { it.initialize(options) } - fun copyCommonFile(fileName: String, targetDir: String): GeneratedFile { - val stream = Generator::class.java.classLoader.getResourceAsStream(fileName) - ?: throw GluecodiumExecutionException(String.format("Failed loading resource %s.", fileName)) + fun copyCommonFile( + fileName: String, + targetDir: String, + ): GeneratedFile { + val stream = + Generator::class.java.classLoader.getResourceAsStream(fileName) + ?: throw GluecodiumExecutionException(String.format("Failed loading resource %s.", fileName)) return try { GeneratedFile( stream.bufferedReader().use { it.readText() }, if (targetDir.isNotEmpty()) targetDir + File.separator + fileName else fileName, - GeneratedFile.SourceSet.COMMON + GeneratedFile.SourceSet.COMMON, ) } catch (e: IOException) { throw GluecodiumExecutionException("Copying resource file failed with error:", e) diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/common/GeneratorOptions.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/common/GeneratorOptions.kt index 56661d08ee..2e58d4e405 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/common/GeneratorOptions.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/common/GeneratorOptions.kt @@ -39,23 +39,27 @@ data class GeneratorOptions( var dartLookupErrorMessage: String = "Failed to resolve an FFI function. Perhaps `LibraryContext.init()` was not called.", var swiftExposeInternals: Boolean = false, - var cppNameRules: Configuration = ConfigurationProperties.fromResource( - Gluecodium::class.java, - "/namerules/cpp.properties" - ), - var javaNameRules: Configuration = ConfigurationProperties.fromResource( - Gluecodium::class.java, - "/namerules/java.properties" - ), - var swiftNameRules: Configuration = ConfigurationProperties.fromResource( - Gluecodium::class.java, - "/namerules/swift.properties" - ), - var dartNameRules: Configuration = ConfigurationProperties.fromResource( - Gluecodium::class.java, - "/namerules/dart.properties" - ), - var tags: Set = emptySet() + var cppNameRules: Configuration = + ConfigurationProperties.fromResource( + Gluecodium::class.java, + "/namerules/cpp.properties", + ), + var javaNameRules: Configuration = + ConfigurationProperties.fromResource( + Gluecodium::class.java, + "/namerules/java.properties", + ), + var swiftNameRules: Configuration = + ConfigurationProperties.fromResource( + Gluecodium::class.java, + "/namerules/swift.properties", + ), + var dartNameRules: Configuration = + ConfigurationProperties.fromResource( + Gluecodium::class.java, + "/namerules/dart.properties", + ), + var tags: Set = emptySet(), ) { companion object { const val WARNING_DOC_LINKS = "DocLinks" diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/common/GenericImportsCollector.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/common/GenericImportsCollector.kt index eefbeb7c5e..fbf98ab5c5 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/common/GenericImportsCollector.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/common/GenericImportsCollector.kt @@ -39,14 +39,16 @@ internal open class GenericImportsCollector( private val parentTypeFilter: (LimeContainerWithInheritance) -> Boolean = { false }, private val collectTypeAliasImports: Boolean = false, private val collectFunctionErrorType: Boolean = true, - private val collectValueImports: Boolean = false + private val collectValueImports: Boolean = false, ) : ImportsCollector { - override fun collectImports(limeElement: LimeNamedElement): List { val allTypes = LimeTypeHelper.getAllTypes(limeElement) val typeRefImports = - if (collectTypeRefImports) collectTypeRefs(allTypes).flatMap { importsResolver.resolveElementImports(it) } - else emptyList() + if (collectTypeRefImports) { + collectTypeRefs(allTypes).flatMap { importsResolver.resolveElementImports(it) } + } else { + emptyList() + } val ownImports = if (collectOwnImports) allTypes.flatMap { importsResolver.resolveElementImports(it) } else emptyList() val parentImports = @@ -55,21 +57,25 @@ internal open class GenericImportsCollector( .flatMap { collectParentTypeRefs(it) } .flatMap { importsResolver.resolveElementImports(it) } val typeAliasImports = - if (collectTypeAliasImports) + if (collectTypeAliasImports) { allTypes.filterIsInstance().flatMap { importsResolver.resolveElementImports(it.typeRef) } - else emptyList() - val constantImports = allTypes.filterIsInstance().flatMap { it.constants } - .flatMap { importsResolver.resolveElementImports(it) } + } else { + emptyList() + } + val constantImports = + allTypes.filterIsInstance().flatMap { it.constants } + .flatMap { importsResolver.resolveElementImports(it) } val valueImports = - if (collectValueImports) + if (collectValueImports) { LimeTypeHelper.getAllValues(limeElement).flatMap { importsResolver.resolveElementImports(it) } - else emptyList() + } else { + emptyList() + } return typeRefImports + ownImports + parentImports + typeAliasImports + constantImports + valueImports } - private fun shouldRetain(limeElement: LimeNamedElement) = - retainPredicate == null || retainPredicate.invoke(limeElement) + private fun shouldRetain(limeElement: LimeNamedElement) = retainPredicate == null || retainPredicate.invoke(limeElement) private fun collectTypeRefs(allTypes: List): List { val containers = allTypes.filterIsInstance() diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/common/GenericIncludesCollector.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/common/GenericIncludesCollector.kt index d52e88d9be..f588dec081 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/common/GenericIncludesCollector.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/common/GenericIncludesCollector.kt @@ -25,18 +25,19 @@ import com.here.gluecodium.model.lime.LimeNamedElement internal class GenericIncludesCollector( includesResolver: ImportsResolver, - retainPredicate: ((LimeNamedElement) -> Boolean) + retainPredicate: ((LimeNamedElement) -> Boolean), ) : GenericImportsCollector( - includesResolver, - retainPredicate = retainPredicate, - collectTypeRefImports = true, - collectOwnImports = true, - parentTypeFilter = { it is LimeClass } -) { + includesResolver, + retainPredicate = retainPredicate, + collectTypeRefImports = true, + collectOwnImports = true, + parentTypeFilter = { it is LimeClass }, + ) { override fun collectParentTypeRefs(limeContainer: LimeContainerWithInheritance) = when (limeContainer) { - is LimeClass -> limeContainer.interfaceInheritedFunctions.flatMap { collectTypeRefs(it) } + - limeContainer.interfaceInheritedProperties.map { it.typeRef } + is LimeClass -> + limeContainer.interfaceInheritedFunctions.flatMap { collectTypeRefs(it) } + + limeContainer.interfaceInheritedProperties.map { it.typeRef } else -> emptyList() } } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/common/Include.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/common/Include.kt index b126d77800..72aee217f6 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/common/Include.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/common/Include.kt @@ -21,16 +21,18 @@ package com.here.gluecodium.generator.common data class Include( val fileName: String, - val isSystem: Boolean + val isSystem: Boolean, ) : Comparable { - override fun compareTo(other: Include) = when { - isSystem && !other.isSystem -> 1 - !isSystem && other.isSystem -> -1 - else -> fileName.compareTo(other.fileName) - } + override fun compareTo(other: Include) = + when { + isSystem && !other.isSystem -> 1 + !isSystem && other.isSystem -> -1 + else -> fileName.compareTo(other.fileName) + } companion object { fun createInternalInclude(fileName: String) = Include(fileName, false) + fun createSystemInclude(fileName: String) = Include(fileName, true) } } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/common/NameResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/common/NameResolver.kt index 1df7359256..ba8fb41da2 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/common/NameResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/common/NameResolver.kt @@ -21,7 +21,16 @@ package com.here.gluecodium.generator.common interface NameResolver { fun resolveName(element: Any): String - fun resolveGetterName(element: Any): String? { throw IllegalArgumentException() } - fun resolveSetterName(element: Any): String? { throw IllegalArgumentException() } - fun resolveReferenceName(element: Any): String? { throw IllegalArgumentException() } + + fun resolveGetterName(element: Any): String? { + throw IllegalArgumentException() + } + + fun resolveSetterName(element: Any): String? { + throw IllegalArgumentException() + } + + fun resolveReferenceName(element: Any): String? { + throw IllegalArgumentException() + } } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/common/NameRuleSet.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/common/NameRuleSet.kt index 1dadce73c1..585d1daccd 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/common/NameRuleSet.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/common/NameRuleSet.kt @@ -30,10 +30,9 @@ class NameRuleSet( val getSetterName: (name: String) -> String = { illegal(it) }, val getGetterName: (name: String, Boolean) -> String = ignore2 { illegal(it) }, val getErrorName: (name: String) -> String = { illegal(it) }, - val joinInfix: String? = null + val joinInfix: String? = null, ) { companion object { - @Suppress("UNUSED_PARAMETER") fun illegal(name: String): String { throw IllegalArgumentException() diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/common/NameRuleSetLoader.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/common/NameRuleSetLoader.kt index 58d41e63cc..2838c954ae 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/common/NameRuleSetLoader.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/common/NameRuleSetLoader.kt @@ -28,26 +28,27 @@ import com.natpryce.konfig.stringType import java.util.Locale private object NameRuleSetLoader { - fun getNameRuleSet(config: Configuration) = NameRuleSet( - getFieldName = getNameRule(config, NameTypes.Field), - getParameterName = getNameRule(config, NameTypes.Parameter), - getConstantName = getNameRule(config, NameTypes.Constant), - getEnumeratorName = getNameRule(config, NameTypes.Enumerator), - getMethodName = getNameRule(config, NameTypes.Method), - getTypeName = getNameRule(config, NameTypes.Type), - getPropertyName = getNameRuleBooleanPrefix(config, NameTypes.Property), - getSetterName = getNameRule(config, NameTypes.Setter), - getGetterName = getNameRuleBooleanPrefix(config, NameTypes.Getter), - getErrorName = getNameRule(config, NameTypes.Error), - joinInfix = getInfix(config, NameTypes.Join) - ) + fun getNameRuleSet(config: Configuration) = + NameRuleSet( + getFieldName = getNameRule(config, NameTypes.Field), + getParameterName = getNameRule(config, NameTypes.Parameter), + getConstantName = getNameRule(config, NameTypes.Constant), + getEnumeratorName = getNameRule(config, NameTypes.Enumerator), + getMethodName = getNameRule(config, NameTypes.Method), + getTypeName = getNameRule(config, NameTypes.Type), + getPropertyName = getNameRuleBooleanPrefix(config, NameTypes.Property), + getSetterName = getNameRule(config, NameTypes.Setter), + getGetterName = getNameRuleBooleanPrefix(config, NameTypes.Getter), + getErrorName = getNameRule(config, NameTypes.Error), + joinInfix = getInfix(config, NameTypes.Join), + ) @Suppress("EnumEntryName", "unused") enum class NameFormat(val apply: (String) -> String, val joinApply: (List) -> String) { UPPER_SNAKE_CASE({ NameHelper.toUpperSnakeCase(it) }, { NameHelper.joinToUpperSnakeCase(it) }), lower_snake_case({ NameHelper.toLowerSnakeCase(it) }, { NameHelper.joinToLowerSnakeCase(it) }), UpperCamelCase({ NameHelper.toUpperCamelCase(it) }, { NameHelper.joinToUpperCamelCase(it) }), - lowerCamelCase({ NameHelper.toLowerCamelCase(it) }, { NameHelper.joinToLowerCamelCase(it) }) + lowerCamelCase({ NameHelper.toLowerCamelCase(it) }, { NameHelper.joinToLowerCamelCase(it) }), } enum class NameTypes { @@ -61,10 +62,13 @@ private object NameRuleSetLoader { Setter, Getter, Error, - Join + Join, } - private fun getNameRuleBooleanPrefix(config: Configuration, nameType: NameTypes): (String, Boolean) -> String { + private fun getNameRuleBooleanPrefix( + config: Configuration, + nameType: NameTypes, + ): (String, Boolean) -> String { val key = nameType.toString().lowercase(Locale.getDefault()) val formattingKey = Key(key, enumType()) val prefixKey = Key("$key.prefix", stringType) @@ -88,7 +92,10 @@ private object NameRuleSetLoader { } } - private fun getNameRule(config: Configuration, nameType: NameTypes): (String) -> String { + private fun getNameRule( + config: Configuration, + nameType: NameTypes, + ): (String) -> String { val key = nameType.toString().lowercase(Locale.getDefault()) val formattingKey = Key(key, enumType()) val prefixKey = Key("$key.prefix", stringType) @@ -103,11 +110,16 @@ private object NameRuleSetLoader { val suffix = config.getOrNull(suffixKey) val formatting = config[formattingKey] return { formatting.joinApply(listOf(prefix, it, suffix)) } - } else return config[formattingKey].apply + } else { + return config[formattingKey].apply + } } @Suppress("SameParameterValue") - private fun getInfix(config: Configuration, nameType: NameTypes): String? { + private fun getInfix( + config: Configuration, + nameType: NameTypes, + ): String? { val key = nameType.toString().lowercase(Locale.getDefault()) val infixKey = Key("$key.infix", stringType) return config.getOrNull(infixKey) diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/common/NameRules.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/common/NameRules.kt index e41e556f29..ebef0d3e2f 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/common/NameRules.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/common/NameRules.kt @@ -50,17 +50,18 @@ open class NameRules(val ruleSet: NameRuleSet) { open fun getPropertyName(limeProperty: LimeProperty): String { val type = limeProperty.typeRef.type.actualType return ruleSet.getPropertyName( - limeProperty.name, type is LimeBasicType && type.typeId == LimeBasicType.TypeId.BOOLEAN + limeProperty.name, + type is LimeBasicType && type.typeId == LimeBasicType.TypeId.BOOLEAN, ) } open fun getGetterName(limeElement: LimeTypedElement): String { val type = limeElement.typeRef.type.actualType return ruleSet.getGetterName( - limeElement.name, type is LimeBasicType && type.typeId == LimeBasicType.TypeId.BOOLEAN + limeElement.name, + type is LimeBasicType && type.typeId == LimeBasicType.TypeId.BOOLEAN, ) } - open fun getSetterName(limeElement: LimeTypedElement) = - ruleSet.getSetterName(limeElement.name) + open fun getSetterName(limeElement: LimeTypedElement) = ruleSet.getSetterName(limeElement.name) } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/common/OptimizedListsCollector.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/common/OptimizedListsCollector.kt index 6f2ee47e28..22f1be649f 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/common/OptimizedListsCollector.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/common/OptimizedListsCollector.kt @@ -27,8 +27,10 @@ import com.here.gluecodium.model.lime.LimeType import com.here.gluecodium.model.lime.LimeTypeRef internal class OptimizedListsCollector : LimeTypeRefsVisitor>() { - - override fun visitTypeRef(parentElement: LimeNamedElement, limeTypeRef: LimeTypeRef?): Map { + override fun visitTypeRef( + parentElement: LimeNamedElement, + limeTypeRef: LimeTypeRef?, + ): Map { val limeType = limeTypeRef?.type?.actualType return when { limeType !is LimeList -> emptyMap() diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/common/PlatformSignatureResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/common/PlatformSignatureResolver.kt index e8449cf9a9..948631f527 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/common/PlatformSignatureResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/common/PlatformSignatureResolver.kt @@ -33,9 +33,8 @@ internal open class PlatformSignatureResolver( limeReferenceMap: Map, private val platformAttributeType: LimeAttributeType, protected val nameRules: NameRules, - private val activeTags: Set + private val activeTags: Set, ) : LimeSignatureResolver(limeReferenceMap) { - override fun getOwnFunctions(limeContainer: LimeContainer) = super.getOwnFunctions(limeContainer) .filter { LimeModelSkipPredicates.shouldRetainElement(it, activeTags, platformAttributeType) } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/common/ReferenceMapBasedResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/common/ReferenceMapBasedResolver.kt index 88b65e8acc..1d8c9da122 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/common/ReferenceMapBasedResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/common/ReferenceMapBasedResolver.kt @@ -26,20 +26,23 @@ import com.here.gluecodium.model.lime.LimeParameter import com.here.gluecodium.model.lime.LimePath internal abstract class ReferenceMapBasedResolver(protected val limeReferenceMap: Map) { - protected fun getParentElement(limeElement: LimeNamedElement): LimeNamedElement = getParentElement(limeElement.path, limeElement is LimeParameter) - protected fun getParentElement(limePath: LimePath, withSuffix: Boolean = false): LimeNamedElement { - val parentPath = when { - withSuffix -> limePath.parent.withSuffix(limePath.disambiguator) - else -> limePath.parent - } + protected fun getParentElement( + limePath: LimePath, + withSuffix: Boolean = false, + ): LimeNamedElement { + val parentPath = + when { + withSuffix -> limePath.parent.withSuffix(limePath.disambiguator) + else -> limePath.parent + } return ( limeReferenceMap[parentPath.toString()] as? LimeNamedElement ?: throw GluecodiumExecutionException( - "Failed to resolve parent for element $limePath" + "Failed to resolve parent for element $limePath", ) - ) + ) } } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/common/templates/CopyrightHeaderResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/common/templates/CopyrightHeaderResolver.kt index 959517eb7f..63064a75ca 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/common/templates/CopyrightHeaderResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/common/templates/CopyrightHeaderResolver.kt @@ -31,11 +31,14 @@ import org.trimou.engine.resolver.Resolver internal class CopyrightHeaderResolver : AbstractResolver(Resolver.DEFAULT_PRIORITY) { var copyrightHeaderContent: String? = null - override fun resolve(contextObject: Any?, name: String, context: ResolutionContext) = - when (TAG_COPYRIGHT_HEADER) { - name -> copyrightHeaderContent - else -> null - } + override fun resolve( + contextObject: Any?, + name: String, + context: ResolutionContext, + ) = when (TAG_COPYRIGHT_HEADER) { + name -> copyrightHeaderContent + else -> null + } companion object { const val TAG_COPYRIGHT_HEADER = "copyrightHeader" diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/common/templates/JoinPartialHelper.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/common/templates/JoinPartialHelper.kt index 2d3b3116b6..0797cb31dc 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/common/templates/JoinPartialHelper.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/common/templates/JoinPartialHelper.kt @@ -52,10 +52,13 @@ internal class JoinPartialHelper : BasicHelper() { } } - private fun applyPartial(options: Options, partialName: String, dataObject: Any) = - options.apply { - push(dataObject) - partial(partialName) - pop() - } + private fun applyPartial( + options: Options, + partialName: String, + dataObject: Any, + ) = options.apply { + push(dataObject) + partial(partialName) + pop() + } } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/common/templates/NameResolverHelper.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/common/templates/NameResolverHelper.kt index 6c57c56c30..5e2174afc3 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/common/templates/NameResolverHelper.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/common/templates/NameResolverHelper.kt @@ -70,12 +70,13 @@ internal class NameResolverHelper : BasicHelper() { } val resolver = nameResolvers[key] ?: return - val name = when (subKey?.lowercase(Locale.getDefault())) { - "getter" -> resolver.resolveGetterName(element) - "setter" -> resolver.resolveSetterName(element) - "ref" -> resolver.resolveReferenceName(element) - else -> resolver.resolveName(element) - } ?: return + val name = + when (subKey?.lowercase(Locale.getDefault())) { + "getter" -> resolver.resolveGetterName(element) + "setter" -> resolver.resolveSetterName(element) + "ref" -> resolver.resolveReferenceName(element) + else -> resolver.resolveName(element) + } ?: return if (isSection(options)) { options.push(name) diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/common/templates/NiceSwitchHelper.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/common/templates/NiceSwitchHelper.kt index 5bd4716e40..53e7b2425f 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/common/templates/NiceSwitchHelper.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/common/templates/NiceSwitchHelper.kt @@ -54,13 +54,16 @@ internal class NiceSwitchHelper : SwitchHelper() { "Invalid content detected {}. " + "This helper should only contain case, default and comment sections. " + "Other types of segments are always rendered.", - info + info, ) } } } - private fun isValid(info: MustacheTagInfo, validNames: Set): Boolean { + private fun isValid( + info: MustacheTagInfo, + validNames: Set, + ): Boolean { // Accept "comment" sections as valid if (info.type == MustacheTagType.COMMENT) { return true diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/common/templates/PrefixHelper.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/common/templates/PrefixHelper.kt index 7c35813e2f..381a936d4f 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/common/templates/PrefixHelper.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/common/templates/PrefixHelper.kt @@ -45,7 +45,7 @@ internal open class PrefixHelper : BasicHelper() { } else { (prefix + it).trimEnd() } - } + }, ) } @@ -53,6 +53,8 @@ internal open class PrefixHelper : BasicHelper() { return ImmutableSet.of("skipFirstLine") } - protected open operator fun getValue(options: Options, dataObject: Any?) = - dataObject?.toString() ?: "" + protected open operator fun getValue( + options: Options, + dataObject: Any?, + ) = dataObject?.toString() ?: "" } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/common/templates/PrefixPartialHelper.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/common/templates/PrefixPartialHelper.kt index e1648ca262..bfc7478ce6 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/common/templates/PrefixPartialHelper.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/common/templates/PrefixPartialHelper.kt @@ -28,7 +28,10 @@ import org.trimou.handlebars.Options * Example: {{prefixPartial "common/CopyrightNotice" "// "}} */ internal class PrefixPartialHelper : PrefixHelper() { - override fun getValue(options: Options, dataObject: Any?): String { + override fun getValue( + options: Options, + dataObject: Any?, + ): String { val builder = StringBuilder() options.partial(dataObject.toString(), builder) return builder.toString() diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/common/templates/SetJoinHelper.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/common/templates/SetJoinHelper.kt index 94e2899cc1..30e4089126 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/common/templates/SetJoinHelper.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/common/templates/SetJoinHelper.kt @@ -30,7 +30,6 @@ import org.trimou.handlebars.SetHelper * Example: {{#setJoin "parentName" parentName name delimiter="::"}}...{{/setJoin}} */ class SetJoinHelper : BasicSectionHelper() { - override fun execute(options: Options) { val delimiter = convertValue(options.hash[DELIMITER]) val key = convertValue(options.parameters.first()) diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/common/templates/TemplateEngine.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/common/templates/TemplateEngine.kt index f2a622dba8..4a5da74c1e 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/common/templates/TemplateEngine.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/common/templates/TemplateEngine.kt @@ -39,39 +39,40 @@ object TemplateEngine { private val sortHelper = SortHelper() init { - engine = MustacheEngineBuilder.newBuilder() - .addTemplateLocator(ClassPathTemplateLocator(1, "templates", "mustache")) - .setProperty("org.trimou.engine.config.skipValueEscaping", true) - .setKeySplitter(BracketDotKeySplitter()) - .registerHelper("prefix", PrefixHelper()) - .registerHelper("prefixPartial", PrefixPartialHelper()) - .registerHelper("joinPartial", JoinPartialHelper()) - .registerHelper("instanceOf", InstanceOfHelper(true)) - .registerHelper("notInstanceOf", InstanceOfHelper(false)) - .registerHelper("capitalize", CapitalizeHelper()) - .registerHelper("escape", EscapeHelper()) - .registerHelper("switch", NiceSwitchHelper()) - .registerHelper("case", SwitchHelper.CaseHelper(true)) - .registerHelper("default", SwitchHelper.DefaultHelper()) - .registerHelper("setJoin", SetJoinHelper()) - .registerHelper("resolveName", nameResolverHelper) - .registerHelper("ifPredicate", ifPredicateHelper) - .registerHelper("unlessPredicate", unlessPredicateHelper) - .registerHelper("sort", sortHelper) - .registerHelper("filter", FilterHelper(ifPredicateHelper.predicates)) - .registerHelpers( - HelpersBuilder.empty() - .addEval(EvalHelper.BracketDotNotation()) - .addIsEqual() - .addIsNotEqual() - .addInclude() - .addJoin() - .addNumExpr() - .addSet() - .build() - ) - .addResolver(copyrightHeaderResolver) - .build() + engine = + MustacheEngineBuilder.newBuilder() + .addTemplateLocator(ClassPathTemplateLocator(1, "templates", "mustache")) + .setProperty("org.trimou.engine.config.skipValueEscaping", true) + .setKeySplitter(BracketDotKeySplitter()) + .registerHelper("prefix", PrefixHelper()) + .registerHelper("prefixPartial", PrefixPartialHelper()) + .registerHelper("joinPartial", JoinPartialHelper()) + .registerHelper("instanceOf", InstanceOfHelper(true)) + .registerHelper("notInstanceOf", InstanceOfHelper(false)) + .registerHelper("capitalize", CapitalizeHelper()) + .registerHelper("escape", EscapeHelper()) + .registerHelper("switch", NiceSwitchHelper()) + .registerHelper("case", SwitchHelper.CaseHelper(true)) + .registerHelper("default", SwitchHelper.DefaultHelper()) + .registerHelper("setJoin", SetJoinHelper()) + .registerHelper("resolveName", nameResolverHelper) + .registerHelper("ifPredicate", ifPredicateHelper) + .registerHelper("unlessPredicate", unlessPredicateHelper) + .registerHelper("sort", sortHelper) + .registerHelper("filter", FilterHelper(ifPredicateHelper.predicates)) + .registerHelpers( + HelpersBuilder.empty() + .addEval(EvalHelper.BracketDotNotation()) + .addIsEqual() + .addIsNotEqual() + .addInclude() + .addJoin() + .addNumExpr() + .addSet() + .build(), + ) + .addResolver(copyrightHeaderResolver) + .build() } fun initCopyrightHeaderContents(contents: String?) { @@ -85,8 +86,8 @@ object TemplateEngine { templateName: String, data: Any, nameResolvers: Map = emptyMap(), - predicates: Map Boolean> = emptyMap(), - sorters: Map)-> List> = emptyMap() + predicates: Map Boolean> = emptyMap(), + sorters: Map) -> List> = emptyMap(), ): String { nameResolverHelper.nameResolvers += nameResolvers ifPredicateHelper.predicates += predicates diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppForwardDeclarationGroup.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppForwardDeclarationGroup.kt index b326b2d582..e90d0cc709 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppForwardDeclarationGroup.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppForwardDeclarationGroup.kt @@ -22,5 +22,5 @@ package com.here.gluecodium.generator.cpp internal class CppForwardDeclarationGroup( val namespace: String, @Suppress("unused") val types: List, - @Suppress("unused") val subGroups: List + @Suppress("unused") val subGroups: List, ) diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppForwardDeclarationsCollector.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppForwardDeclarationsCollector.kt index 9c1c0bcee2..d173747bd9 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppForwardDeclarationsCollector.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppForwardDeclarationsCollector.kt @@ -25,7 +25,6 @@ import com.here.gluecodium.model.lime.LimeTypeHelper internal class CppForwardDeclarationsCollector(private val nameResolver: CppNameResolver) : CppImportsCollector() { - override fun collectImports(limeElement: LimeNamedElement): List { val allTypeRefs = collectTypeRefs(LimeTypeHelper.getAllTypes(limeElement)) val forwardDeclaredTypes = @@ -37,13 +36,13 @@ internal class CppForwardDeclarationsCollector(private val nameResolver: CppName name: String, paths: List, level: Int, - nameResolver: NameResolver + nameResolver: NameResolver, ): CppForwardDeclarationGroup = CppForwardDeclarationGroup( name, paths.filter { level == it.path.head.size }.map { nameResolver.resolveName(it) }, paths.filter { level < it.path.head.size } .groupBy { it.path.head[level] } - .map { createForwardDeclarationGroup(it.key, it.value, level + 1, nameResolver) } + .map { createForwardDeclarationGroup(it.key, it.value, level + 1, nameResolver) }, ) } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppFullNameResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppFullNameResolver.kt index ce5b42823d..d4721fe5ca 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppFullNameResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppFullNameResolver.kt @@ -29,7 +29,6 @@ import com.here.gluecodium.model.lime.LimeTypeRef * Auxiliary name resolver for the C++ generator. Resolves fully qualified names only. */ internal class CppFullNameResolver(private val nameCache: CppNameCache) : NameResolver { - override fun resolveName(element: Any): String = when (element) { is LimeReturnType -> resolveElementName(element.typeRef.type) @@ -39,6 +38,5 @@ internal class CppFullNameResolver(private val nameCache: CppNameCache) : NameRe throw GluecodiumExecutionException("Unsupported element type ${element.javaClass.name}") } - private fun resolveElementName(limeElement: LimeNamedElement) = - nameCache.getFullyQualifiedName(limeElement) + private fun resolveElementName(limeElement: LimeNamedElement) = nameCache.getFullyQualifiedName(limeElement) } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppGenerator.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppGenerator.kt index 8abe5cc80f..76aa9e2505 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppGenerator.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppGenerator.kt @@ -56,7 +56,6 @@ import java.util.logging.Logger * templates to it and returns the list of generated files. */ internal class CppGenerator : Generator { - private lateinit var nameRules: CppNameRules private lateinit var rootNamespace: List private lateinit var internalNamespace: List @@ -75,12 +74,13 @@ internal class CppGenerator : Generator { commentsProcessor = DoxygenCommentsProcessor(options.werror.contains(GeneratorOptions.WARNING_DOC_LINKS)) exportName = options.cppExport exportCommonName = options.cppExportCommon ?: options.cppExport - exportInclude = Include.createInternalInclude( - Paths.get( - internalNamespace.joinToString(File.separator), - getExportFileName(exportName) + ".h" - ).toString() - ) + exportInclude = + Include.createInternalInclude( + Paths.get( + internalNamespace.joinToString(File.separator), + getExportFileName(exportName) + ".h", + ).toString(), + ) activeTags = options.tags } @@ -104,33 +104,36 @@ internal class CppGenerator : Generator { val includeResolver = CppIncludeResolver(filteredModel.referenceMap, nameRules, internalNamespace) val cachingNameResolver = CppNameCache(rootNamespace, filteredModel.referenceMap, nameRules) - val nameResolver = CppNameResolver( - filteredModel.referenceMap, - internalNamespace, - cachingNameResolver, - limeLogger, - commentsProcessor - ) + val nameResolver = + CppNameResolver( + filteredModel.referenceMap, + internalNamespace, + cachingNameResolver, + limeLogger, + commentsProcessor, + ) val fullNameResolver = CppFullNameResolver(cachingNameResolver) - val allErrorEnums = filteredModel.topElements - .flatMap { LimeTypeHelper.getAllTypes(it) } - .asSequence() - .filterIsInstance() - .map { it.errorType.type } - .filterIsInstance() - .filter { it.external?.cpp == null } - .map { it.fullName } - .toSet() + val allErrorEnums = + filteredModel.topElements + .flatMap { LimeTypeHelper.getAllTypes(it) } + .asSequence() + .filterIsInstance() + .map { it.errorType.type } + .filterIsInstance() + .filter { it.external?.cpp == null } + .map { it.fullName } + .toSet() val predicates = CppGeneratorPredicates(filteredModel.referenceMap).predicates - val generatedFiles = filteredModel.topElements.flatMap { - val fileName = nameRules.getOutputFilePath(it) - generateCode(it, fileName, includeResolver, nameResolver, fullNameResolver, signatureResolver, allErrorEnums, predicates) - } + COMMON_HEADERS.map { generateHelperFile(it, "include", ".h") } + - COMMON_IMPLS.map { generateHelperFile(it, "src", ".cpp") } + - generateExportHelperFile(exportCommonName, "Common", GeneratedFile.SourceSet.COMMON) + - generateExportHelperFile(exportName, "", GeneratedFile.SourceSet.MAIN) + val generatedFiles = + filteredModel.topElements.flatMap { + val fileName = nameRules.getOutputFilePath(it) + generateCode(it, fileName, includeResolver, nameResolver, fullNameResolver, signatureResolver, allErrorEnums, predicates) + } + COMMON_HEADERS.map { generateHelperFile(it, "include", ".h") } + + COMMON_IMPLS.map { generateHelperFile(it, "src", ".cpp") } + + generateExportHelperFile(exportCommonName, "Common", GeneratedFile.SourceSet.COMMON) + + generateExportHelperFile(exportName, "", GeneratedFile.SourceSet.MAIN) if (commentsProcessor.hasError) { throw GluecodiumExecutionException("Validation errors found, see log for details.") @@ -147,33 +150,34 @@ internal class CppGenerator : Generator { fullNameResolver: CppFullNameResolver, signatureResolver: CppSignatureResolver, allErrorEnums: Set, - predicates: Map Boolean> + predicates: Map Boolean>, ): List { - val allTypes = LimeTypeHelper.getAllTypes(rootElement) val errorEnums = allTypes.filter { allErrorEnums.contains(it.fullName) }.toSet() val limeElements = listOf(rootElement) // TODO val hasConstants = limeElements.any { it is LimeConstant } val needsHeader = hasConstants || limeElements.any { it !is LimeException && it.external?.cpp == null } - val needsImplementation = hasConstants || errorEnums.isNotEmpty() || - limeElements.any { it is LimeContainer } || limeElements.any { it is LimeEnumeration } + val needsImplementation = + hasConstants || errorEnums.isNotEmpty() || + limeElements.any { it is LimeContainer } || limeElements.any { it is LimeEnumeration } if (!needsHeader && !needsImplementation) { return emptyList() } val equatableTypes = allTypes.filter { it.external?.cpp == null && it.attributes.have(EQUATABLE) } val forwardDeclarations = CppForwardDeclarationsCollector(nameResolver).collectImports(rootElement) - val templateData = mutableMapOf( - "internalNamespace" to internalNamespace, - "namespace" to rootNamespace + rootElement.path.head, - "rootNamespace" to rootNamespace, - "exportName" to exportName, - "model" to rootElement, - "equatables" to equatableTypes, - "errorEnums" to errorEnums, - "forwardDeclarations" to forwardDeclarations - ) + val templateData = + mutableMapOf( + "internalNamespace" to internalNamespace, + "namespace" to rootNamespace + rootElement.path.head, + "rootNamespace" to rootNamespace, + "exportName" to exportName, + "model" to rootElement, + "equatables" to equatableTypes, + "errorEnums" to errorEnums, + "forwardDeclarations" to forwardDeclarations, + ) val nameResolvers = mapOf("" to nameResolver, "FQN" to fullNameResolver, "C++" to nameResolver) val result = mutableListOf() @@ -185,22 +189,27 @@ internal class CppGenerator : Generator { } if (needsImplementation) { val implIncludesCollector = CppImplIncludesCollector(includeResolver, allErrorEnums) - val implementationIncludes = implIncludesCollector.collectImports(rootElement) + - createSelfInclude(rootElement, needsHeader, fileName) + val implementationIncludes = + implIncludesCollector.collectImports(rootElement) + + createSelfInclude(rootElement, needsHeader, fileName) result += generateImplementation(rootElement, nameResolvers, implementationIncludes, templateData, fileName, predicates) } return result } - private fun collectFunctionUsings(rootElement: LimeNamedElement, signatureResolver: CppSignatureResolver) = - LimeTypeHelper.getAllTypes(rootElement) - .filterIsInstance() - .filter { it.parents.isNotEmpty() } - .associateBy({ it.fullName }, { getFunctionUsing(it, signatureResolver) }) + private fun collectFunctionUsings( + rootElement: LimeNamedElement, + signatureResolver: CppSignatureResolver, + ) = LimeTypeHelper.getAllTypes(rootElement) + .filterIsInstance() + .filter { it.parents.isNotEmpty() } + .associateBy({ it.fullName }, { getFunctionUsing(it, signatureResolver) }) - private fun getFunctionUsing(limeContainer: LimeContainerWithInheritance, signatureResolver: CppSignatureResolver) = - limeContainer.functions.mapNotNull { signatureResolver.getInheritedOverloads(it).firstOrNull() } + private fun getFunctionUsing( + limeContainer: LimeContainerWithInheritance, + signatureResolver: CppSignatureResolver, + ) = limeContainer.functions.mapNotNull { signatureResolver.getInheritedOverloads(it).firstOrNull() } private fun generateImplementation( rootElement: LimeNamedElement, @@ -208,12 +217,14 @@ internal class CppGenerator : Generator { implementationIncludes: List, generalData: Map, fileName: String, - predicates: Map Boolean> + predicates: Map Boolean>, ): GeneratedFile { - val templateData = generalData + mapOf( - "includes" to implementationIncludes.distinct().sorted(), - "contentTemplate" to selectTemplate(rootElement) + "Impl" - ) + val templateData = + generalData + + mapOf( + "includes" to implementationIncludes.distinct().sorted(), + "contentTemplate" to selectTemplate(rootElement) + "Impl", + ) val implementationContent = TemplateEngine.render("cpp/CppImplementation", templateData, nameResolvers, predicates) val absolutePath = Paths.get(GENERATOR_NAME, "src", fileName) @@ -226,26 +237,32 @@ internal class CppGenerator : Generator { fileName: String, generalData: Map, headerIncludes: List, - predicates: Map Boolean> + predicates: Map Boolean>, ): GeneratedFile { val absolutePath = Paths.get(GENERATOR_NAME, "include", fileName) val headerFileName = "$absolutePath.h" val sortedIncludes = headerIncludes.distinct().sorted().filterNot { headerFileName.endsWith(it.fileName) } - val templateData = generalData + - mapOf("includes" to sortedIncludes, "contentTemplate" to selectTemplate(rootElement)) + val templateData = + generalData + + mapOf("includes" to sortedIncludes, "contentTemplate" to selectTemplate(rootElement)) val headerContent = TemplateEngine.render("cpp/CppHeader", templateData, nameResolvers, predicates, sorters) return GeneratedFile(headerContent, headerFileName) } - private fun generateHelperFile(fileName: String, subDir: String, suffix: String): GeneratedFile { - val templateData = mapOf( - "internalNamespace" to internalNamespace, - "exportName" to exportCommonName, - "exportFileName" to getExportFileName(exportCommonName, "Common") - ) + private fun generateHelperFile( + fileName: String, + subDir: String, + suffix: String, + ): GeneratedFile { + val templateData = + mapOf( + "internalNamespace" to internalNamespace, + "exportName" to exportCommonName, + "exportFileName" to getExportFileName(exportCommonName, "Common"), + ) val content = TemplateEngine.render("cpp/common/$fileName", templateData) val namePrefix = Paths.get(GENERATOR_NAME, subDir, internalNamespace.joinToString("/"), fileName).toString() @@ -255,7 +272,7 @@ internal class CppGenerator : Generator { private fun generateExportHelperFile( exportName: String, infix: String, - sourceSet: GeneratedFile.SourceSet + sourceSet: GeneratedFile.SourceSet, ): GeneratedFile { val templateData = mapOf("internalNamespace" to internalNamespace, "exportName" to exportName) val content = TemplateEngine.render("cpp/common/Export", templateData) @@ -265,8 +282,10 @@ internal class CppGenerator : Generator { return GeneratedFile(content, "$namePrefix.h", sourceSet) } - private fun getExportFileName(exportName: String, infix: String = "") = - "Export" + infix + NameHelper.toUpperCamelCase(exportName) + private fun getExportFileName( + exportName: String, + infix: String = "", + ) = "Export" + infix + NameHelper.toUpperCamelCase(exportName) private fun selectTemplate(limeElement: LimeNamedElement) = when (limeElement) { @@ -282,7 +301,7 @@ internal class CppGenerator : Generator { private fun createSelfInclude( rootElement: LimeNamedElement, needsHeader: Boolean, - fileName: String + fileName: String, ): List { if (needsHeader) return listOf(Include.createInternalInclude("$fileName.h")) val externalInclude = rootElement.external?.cpp?.get(LimeExternalDescriptor.INCLUDE_NAME) ?: return emptyList() @@ -293,23 +312,25 @@ internal class CppGenerator : Generator { private const val GENERATOR_NAME = "cpp" private val logger = Logger.getLogger(CppGenerator::class.java.name) - private val COMMON_HEADERS = listOf( - "DurationHash", - "Hash", - "Locale", - "Return", - "TimePointHash", - "TypeRepository", - "UnorderedMapHash", - "UnorderedSetHash", - "VectorHash" - ) + private val COMMON_HEADERS = + listOf( + "DurationHash", + "Hash", + "Locale", + "Return", + "TimePointHash", + "TypeRepository", + "UnorderedMapHash", + "UnorderedSetHash", + "VectorHash", + ) private val COMMON_IMPLS = listOf("LocaleImpl", "TypeRepositoryImpl") - private val sorters = mapOf( - "" to { elements: List -> - TopologicalSort(elements.filterIsInstance()).sort() - } - ) + private val sorters = + mapOf( + "" to { elements: List -> + TopologicalSort(elements.filterIsInstance()).sort() + }, + ) } } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppGeneratorPredicates.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppGeneratorPredicates.kt index de0822c18e..62d6de02bb 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppGeneratorPredicates.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppGeneratorPredicates.kt @@ -36,103 +36,117 @@ import com.here.gluecodium.model.lime.LimeTypeRef * List of predicates used by `ifPredicate`/`unlessPredicate` template helpers in C++ generator. */ internal class CppGeneratorPredicates(private val referenceMap: Map) { - val predicates = mapOf( - "needsRefSuffix" to { limeTypeRef: Any -> - limeTypeRef is LimeTypeRef && CppNameResolver.needsRefSuffix(limeTypeRef) - }, - "needsNotNullComment" to { limeTypeRef: Any -> - limeTypeRef is LimeTypeRef && needsNotNullComment(limeTypeRef) - }, - "hasAnyComment" to { limeElement: Any -> - when (limeElement) { - is LimeFunction -> limeElement.run { - comment.getFor("Cpp").isNotBlank() || comment.isExcluded || - returnType.comment.getFor("Cpp").isNotBlank() || - needsNotNullComment(returnType.typeRef) || - (thrownType?.comment?.getFor("Cpp")?.isBlank() == false) || - attributes.have(LimeAttributeType.DEPRECATED) || - parameters.any { it.comment.getFor("Cpp").isNotBlank() || needsNotNullComment(it.typeRef) } + val predicates = + mapOf( + "needsRefSuffix" to { limeTypeRef: Any -> + limeTypeRef is LimeTypeRef && CppNameResolver.needsRefSuffix(limeTypeRef) + }, + "needsNotNullComment" to { limeTypeRef: Any -> + limeTypeRef is LimeTypeRef && needsNotNullComment(limeTypeRef) + }, + "hasAnyComment" to { limeElement: Any -> + when (limeElement) { + is LimeFunction -> + limeElement.run { + comment.getFor("Cpp").isNotBlank() || comment.isExcluded || + returnType.comment.getFor("Cpp").isNotBlank() || + needsNotNullComment(returnType.typeRef) || + (thrownType?.comment?.getFor("Cpp")?.isBlank() == false) || + attributes.have(LimeAttributeType.DEPRECATED) || + parameters.any { it.comment.getFor("Cpp").isNotBlank() || needsNotNullComment(it.typeRef) } + } + else -> CommonGeneratorPredicates.hasAnyComment(limeElement, "Cpp") } - else -> CommonGeneratorPredicates.hasAnyComment(limeElement, "Cpp") - } - }, - "hasDefaultConstructor" to { limeStruct: Any -> - when { - limeStruct !is LimeStruct -> false - limeStruct.fieldConstructors.map { it.fields.size }.contains(0) -> false - limeStruct.uninitializedFields.isEmpty() -> true - limeStruct.uninitializedFields - .flatMap { getAllFieldTypes(it.typeRef.type) } - .any { it.attributes.have(LimeAttributeType.IMMUTABLE) } -> false - !limeStruct.attributes.have(LimeAttributeType.IMMUTABLE) -> true - else -> false - } - }, - "hasPartialDefaults" to { limeStruct: Any -> - when { - limeStruct !is LimeStruct -> false - limeStruct.uninitializedFields.isEmpty() -> false - limeStruct.fieldConstructors.isNotEmpty() -> false - else -> limeStruct.uninitializedFields.size < limeStruct.fields.size - } - }, - "needsAllFieldsConstructor" to { limeStruct: Any -> - when { - limeStruct !is LimeStruct -> false - limeStruct.fieldConstructors.isEmpty() -> true - CommonGeneratorPredicates.hasImmutableFields(limeStruct) -> limeStruct.allFieldsConstructor == null - else -> false - } - }, - "needsPointerValueEqual" to fun(limeField: Any): Boolean { - if (limeField !is LimeField) return false - val limeType = limeField.typeRef.type.actualType - return when { - limeType is LimeContainerWithInheritance && - limeType.attributes.have(LimeAttributeType.EQUATABLE) -> true - !limeField.typeRef.isNullable -> false - else -> true - } - }, - "needsRawPointerEqual" to fun(limeField: Any): Boolean { - if (limeField !is LimeField) return false - val limeType = limeField.typeRef.type.actualType - return when { - !limeField.typeRef.isNullable -> false - limeType !is LimeContainerWithInheritance -> false - limeType.attributes.have(LimeAttributeType.EQUATABLE) -> false - else -> true - } - }, - "isUsedInAnotherInnerClasses" to fun(limeField: Any): Boolean { - if (limeField !is LimeContainer || !limeField.path.hasParent) return false - val parent = referenceMap[limeField.path.parent.toAmbiguousString()] - if (parent !is LimeContainerWithInheritance) return false + }, + "hasDefaultConstructor" to { limeStruct: Any -> + when { + limeStruct !is LimeStruct -> false + limeStruct.fieldConstructors.map { it.fields.size }.contains(0) -> false + limeStruct.uninitializedFields.isEmpty() -> true + limeStruct.uninitializedFields + .flatMap { getAllFieldTypes(it.typeRef.type) } + .any { it.attributes.have(LimeAttributeType.IMMUTABLE) } -> false + !limeStruct.attributes.have(LimeAttributeType.IMMUTABLE) -> true + else -> false + } + }, + "hasPartialDefaults" to { limeStruct: Any -> + when { + limeStruct !is LimeStruct -> false + limeStruct.uninitializedFields.isEmpty() -> false + limeStruct.fieldConstructors.isNotEmpty() -> false + else -> limeStruct.uninitializedFields.size < limeStruct.fields.size + } + }, + "needsAllFieldsConstructor" to { limeStruct: Any -> + when { + limeStruct !is LimeStruct -> false + limeStruct.fieldConstructors.isEmpty() -> true + CommonGeneratorPredicates.hasImmutableFields(limeStruct) -> limeStruct.allFieldsConstructor == null + else -> false + } + }, + "needsPointerValueEqual" to - return (parent.interfaces + parent.classes) - .filter { it != limeField } - .map { InnerClassForwardDeclarationCollection.collectImports(it) } - .any { it.contains(limeField.fullName) } - }, - "needsInnerForwardDeclarations" to fun(limeField: Any): Boolean { - if (limeField !is LimeContainer) return false + fun(limeField: Any): Boolean { + if (limeField !is LimeField) return false + val limeType = limeField.typeRef.type.actualType + return when { + limeType is LimeContainerWithInheritance && + limeType.attributes.have(LimeAttributeType.EQUATABLE) -> true + !limeField.typeRef.isNullable -> false + else -> true + } + }, + "needsRawPointerEqual" to - val containers = limeField.interfaces + limeField.classes - val typesUsedInTheClass = containers - .associateWith { InnerClassForwardDeclarationCollection.collectImports(it) } + fun(limeField: Any): Boolean { + if (limeField !is LimeField) return false + val limeType = limeField.typeRef.type.actualType + return when { + !limeField.typeRef.isNullable -> false + limeType !is LimeContainerWithInheritance -> false + limeType.attributes.have(LimeAttributeType.EQUATABLE) -> false + else -> true + } + }, + "isUsedInAnotherInnerClasses" to - return containers.any { container -> - typesUsedInTheClass.filterKeys { it != container }.values.flatten().contains(container.fullName) - } - } - ) + fun(limeField: Any): Boolean { + if (limeField !is LimeContainer || !limeField.path.hasParent) return false + val parent = referenceMap[limeField.path.parent.toAmbiguousString()] + if (parent !is LimeContainerWithInheritance) return false + + return (parent.interfaces + parent.classes) + .filter { it != limeField } + .map { InnerClassForwardDeclarationCollection.collectImports(it) } + .any { it.contains(limeField.fullName) } + }, + "needsInnerForwardDeclarations" to + + fun(limeField: Any): Boolean { + if (limeField !is LimeContainer) return false + + val containers = limeField.interfaces + limeField.classes + val typesUsedInTheClass = + containers + .associateWith { InnerClassForwardDeclarationCollection.collectImports(it) } + + return containers.any { container -> + typesUsedInTheClass.filterKeys { it != container }.values.flatten().contains(container.fullName) + } + }, + ) private fun needsNotNullComment(limeTypeRef: LimeTypeRef) = !limeTypeRef.isNullable && limeTypeRef.type.actualType is LimeContainerWithInheritance private fun getAllFieldTypes(limeType: LimeType) = getAllFieldTypesRec(limeType.actualType, mutableSetOf()) - private fun getAllFieldTypesRec(leafType: LimeType, visitedTypes: MutableSet): List { + private fun getAllFieldTypesRec( + leafType: LimeType, + visitedTypes: MutableSet, + ): List { if (leafType !is LimeStruct) return listOf(leafType) visitedTypes += leafType diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppHeaderIncludesCollector.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppHeaderIncludesCollector.kt index 43eb957b30..4c7e0811af 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppHeaderIncludesCollector.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppHeaderIncludesCollector.kt @@ -31,17 +31,17 @@ import com.here.gluecodium.model.lime.LimeTypeHelper internal class CppHeaderIncludesCollector( private val includesResolver: CppIncludeResolver, - private val allErrorEnums: Set + private val allErrorEnums: Set, ) : CppImportsCollector() { - override fun collectImports(limeElement: LimeNamedElement): List { val allTypes = LimeTypeHelper.getAllTypes(limeElement) val errorEnums = allTypes.filter { allErrorEnums.contains(it.fullName) }.toSet() - val typeRegisteredClasses = allTypes.filterIsInstance() - .filter { - it.external?.cpp == null && it.parents.isEmpty() && (it is LimeInterface || it.isOpen) - } + val typeRegisteredClasses = + allTypes.filterIsInstance() + .filter { + it.external?.cpp == null && it.parents.isEmpty() && (it is LimeInterface || it.isOpen) + } val allTypeRefs = collectTypeRefs(allTypes) val forwardDeclaredTypes = collectForwardDeclaredTypes(limeElement, allTypeRefs) @@ -62,13 +62,14 @@ internal class CppHeaderIncludesCollector( limeElement: LimeNamedElement, equatableTypes: List, errorEnums: Set, - typeRegisteredClasses: List + typeRegisteredClasses: List, ): List { - val parentIncludes = when (limeElement) { - is LimeContainerWithInheritance -> - limeElement.parents.flatMap { includesResolver.resolveElementImports(it.type) } - else -> emptyList() - } + val parentIncludes = + when (limeElement) { + is LimeContainerWithInheritance -> + limeElement.parents.flatMap { includesResolver.resolveElementImports(it.type) } + else -> emptyList() + } val additionalIncludes = parentIncludes.toMutableList() if (limeElement is LimeEnumeration) { additionalIncludes += CppLibraryIncludes.INT_TYPES diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppImplIncludesCollector.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppImplIncludesCollector.kt index 201040f71b..c83286f7fe 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppImplIncludesCollector.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppImplIncludesCollector.kt @@ -28,17 +28,17 @@ import com.here.gluecodium.model.lime.LimeTypeHelper internal class CppImplIncludesCollector( private val includesResolver: CppIncludeResolver, - private val allErrorEnums: Set + private val allErrorEnums: Set, ) : CppImportsCollector() { - override fun collectImports(limeElement: LimeNamedElement): List { val allTypes = LimeTypeHelper.getAllTypes(limeElement) - val result = collectTypeRefs(allTypes).map { it.type } - .filterIsInstance() - .filter { !it.path.hasParent && it.external?.cpp == null } - .flatMap { includesResolver.resolveElementImports(it) } - .toMutableList() + val result = + collectTypeRefs(allTypes).map { it.type } + .filterIsInstance() + .filter { !it.path.hasParent && it.external?.cpp == null } + .flatMap { includesResolver.resolveElementImports(it) } + .toMutableList() val externalContainers = allTypes.filter { it is LimeContainer && it.external?.cpp != null } if (externalContainers.isNotEmpty()) { diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppImportsCollector.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppImportsCollector.kt index eda5ef041f..b3e11bde0c 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppImportsCollector.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppImportsCollector.kt @@ -36,10 +36,9 @@ import com.here.gluecodium.model.lime.LimeTypeAlias import com.here.gluecodium.model.lime.LimeTypeRef internal abstract class CppImportsCollector : ImportsCollector { - protected fun collectForwardDeclaredTypes( limeElement: LimeNamedElement, - allTypeRefs: List + allTypeRefs: List, ): List { val parentPaths = if (limeElement is LimeContainerWithInheritance) limeElement.parents.map { it.type.path } else emptyList() @@ -52,13 +51,14 @@ internal abstract class CppImportsCollector : ImportsCollector { protected fun collectTypeRefs(allTypes: List): List { val containers = allTypes.filterIsInstance() val classes = containers.filterIsInstance() - val typeRefs = containers.flatMap { it.constants }.map { it.typeRef } + - containers.filterIsInstance().flatMap { it.fields }.map { it.typeRef } + - containers.flatMap { it.functions }.flatMap { collectTypeRefs(it) } + - classes.flatMap { it.properties }.map { it.typeRef } + - allTypes.filterIsInstance().map { it.typeRef } + - allTypes.filterIsInstance().flatMap { collectTypeRefs(it.asFunction()) } + - allTypes.filterIsInstance().map { it.errorType } + val typeRefs = + containers.flatMap { it.constants }.map { it.typeRef } + + containers.filterIsInstance().flatMap { it.fields }.map { it.typeRef } + + containers.flatMap { it.functions }.flatMap { collectTypeRefs(it) } + + classes.flatMap { it.properties }.map { it.typeRef } + + allTypes.filterIsInstance().map { it.typeRef } + + allTypes.filterIsInstance().flatMap { collectTypeRefs(it.asFunction()) } + + allTypes.filterIsInstance().map { it.errorType } return typeRefs + typeRefs.flatMap { collectTypeRefs(it) } } @@ -67,15 +67,16 @@ internal abstract class CppImportsCollector : ImportsCollector { limeFunction.parameters.map { it.typeRef } + limeFunction.returnType.typeRef + listOfNotNull( - limeFunction.exception?.errorType?.takeIf { it.type.actualType !is LimeEnumeration } + limeFunction.exception?.errorType?.takeIf { it.type.actualType !is LimeEnumeration }, ) private fun collectTypeRefs(limeTypeRef: LimeTypeRef): List = when (val limeType = limeTypeRef.type) { is LimeList -> collectTypeRefs(limeType.elementType) + limeType.elementType is LimeSet -> collectTypeRefs(limeType.elementType) + limeType.elementType - is LimeMap -> collectTypeRefs(limeType.keyType) + collectTypeRefs(limeType.valueType) + - limeType.keyType + limeType.valueType + is LimeMap -> + collectTypeRefs(limeType.keyType) + collectTypeRefs(limeType.valueType) + + limeType.keyType + limeType.valueType else -> emptyList() } } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppIncludeResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppIncludeResolver.kt index c2e258d91b..828057af32 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppIncludeResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppIncludeResolver.kt @@ -47,7 +47,7 @@ import com.here.gluecodium.model.lime.LimeValue internal class CppIncludeResolver( limeReferenceMap: Map, nameRules: CppNameRules, - internalNamespace: List + internalNamespace: List, ) : ImportsResolver { private val cppIncludesCache = CppIncludesCache(limeReferenceMap, nameRules, internalNamespace) @@ -70,8 +70,9 @@ internal class CppIncludeResolver( is LimeGenericType -> resolveGenericTypeIncludes(limeElement) is LimeFunction -> resolveFunctionIncludes(limeElement) is LimeLambda -> cppIncludesCache.resolveIncludes(limeElement) + CppLibraryIncludes.FUNCTIONAL - is LimeNamedElement -> cppIncludesCache.resolveIncludes(limeElement) + - listOfNotNull(CppLibraryIncludes.STRING_VIEW.takeIf { limeElement.attributes.have(CPP, TO_STRING) }) + is LimeNamedElement -> + cppIncludesCache.resolveIncludes(limeElement) + + listOfNotNull(CppLibraryIncludes.STRING_VIEW.takeIf { limeElement.attributes.have(CPP, TO_STRING) }) else -> emptyList() } @@ -82,8 +83,9 @@ internal class CppIncludeResolver( private fun resolveExceptionIncludes(limeFunction: LimeFunction): List { val payloadType = limeFunction.exception?.errorType?.type?.actualType ?: return emptyList() return when (payloadType) { - is LimeEnumeration -> listOf(CppLibraryIncludes.SYSTEM_ERROR) + - if (limeFunction.attributes.have(ASYNC)) cppIncludesCache.resolveIncludes(payloadType) else emptyList() + is LimeEnumeration -> + listOf(CppLibraryIncludes.SYSTEM_ERROR) + + if (limeFunction.attributes.have(ASYNC)) cppIncludesCache.resolveIncludes(payloadType) else emptyList() is LimeBasicType -> listOf(returnInclude) else -> cppIncludesCache.resolveIncludes(payloadType) + returnInclude } + listOfNotNull(returnInclude.takeIf { !limeFunction.returnType.isVoid }) @@ -95,8 +97,9 @@ internal class CppIncludeResolver( is LimeValue.KeyValuePair -> resolveValueIncludes(limeValue.key) + resolveValueIncludes(limeValue.value) is LimeValue.InitializerList -> limeValue.values.flatMap { resolveValueIncludes(it) } - is LimeValue.StructInitializer -> resolveTypeRefIncludes(limeValue.typeRef) + - limeValue.values.flatMap { resolveValueIncludes(it) } + is LimeValue.StructInitializer -> + resolveTypeRefIncludes(limeValue.typeRef) + + limeValue.values.flatMap { resolveValueIncludes(it) } is LimeValue.Constant -> cppIncludesCache.resolveIncludes(limeValue.valueRef.element) else -> emptyList() } @@ -129,9 +132,10 @@ internal class CppIncludeResolver( is LimeSet -> limeType.elementType.let { resolveElementImports(it) + resolveHashIncludes(it) } + CppLibraryIncludes.SET + unorderedSetHashInclude - is LimeMap -> resolveElementImports(limeType.valueType) + - limeType.keyType.let { resolveElementImports(it) + resolveHashIncludes(it) } + - CppLibraryIncludes.MAP + unorderedMapHashInclude + is LimeMap -> + resolveElementImports(limeType.valueType) + + limeType.keyType.let { resolveElementImports(it) + resolveHashIncludes(it) } + + CppLibraryIncludes.MAP + unorderedMapHashInclude else -> emptyList() } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppIncludesCache.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppIncludesCache.kt index f6982acacc..27cb7ee204 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppIncludesCache.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppIncludesCache.kt @@ -28,7 +28,7 @@ import java.io.File internal class CppIncludesCache( private val limeReferenceMap: Map, private val nameRules: CppNameRules, - private val internalNamespace: List + private val internalNamespace: List, ) { private val resolvedIncludes = mutableMapOf>() @@ -43,11 +43,12 @@ internal class CppIncludesCache( when { externalType != null -> externalType.split(',').map { Include.createInternalInclude(it.trim()) } - !limeNamedElement.path.hasParent -> listOf( - Include.createInternalInclude( - nameRules.getOutputFilePath(limeNamedElement) + ".h" + !limeNamedElement.path.hasParent -> + listOf( + Include.createInternalInclude( + nameRules.getOutputFilePath(limeNamedElement) + ".h", + ), ) - ) else -> { val parentElementKey = limeNamedElement.path.parent.toString() resolveIncludes(limeReferenceMap[parentElementKey] as LimeNamedElement) diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppNameCache.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppNameCache.kt index a9393d1d14..8affcda25a 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppNameCache.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppNameCache.kt @@ -33,7 +33,7 @@ import java.util.HashMap internal class CppNameCache( rootNamespace: List, private val limeReferenceMap: Map, - val nameRules: CppNameRules + val nameRules: CppNameRules, ) { private val rootNamespace: String = rootNamespace.joinToString("::") private val namesCache = HashMap() @@ -41,7 +41,7 @@ internal class CppNameCache( private class NamesCacheEntry( val isExternal: Boolean, val shortName: String, - val fullName: String + val fullName: String, ) fun getName(limeElement: LimeNamedElement) = getCachedEntry(limeElement).shortName @@ -58,20 +58,15 @@ internal class CppNameCache( ?: limeProperty.setter?.attributes?.get(CPP, NAME) ?: nameRules.getSetterName(limeProperty) - fun getGetterName(limeField: LimeField) = - limeField.external?.cpp?.get(GETTER_NAME_NAME) ?: nameRules.getGetterName(limeField) + fun getGetterName(limeField: LimeField) = limeField.external?.cpp?.get(GETTER_NAME_NAME) ?: nameRules.getGetterName(limeField) - fun getSetterName(limeField: LimeField) = - limeField.external?.cpp?.get(SETTER_NAME_NAME) ?: nameRules.getSetterName(limeField) + fun getSetterName(limeField: LimeField) = limeField.external?.cpp?.get(SETTER_NAME_NAME) ?: nameRules.getSetterName(limeField) - fun getFullyQualifiedGetterName(limeProperty: LimeProperty) = - getParentFullName(limeProperty) + "::" + getGetterName(limeProperty) + fun getFullyQualifiedGetterName(limeProperty: LimeProperty) = getParentFullName(limeProperty) + "::" + getGetterName(limeProperty) - fun getFullyQualifiedSetterName(limeProperty: LimeProperty) = - getParentFullName(limeProperty) + "::" + getSetterName(limeProperty) + fun getFullyQualifiedSetterName(limeProperty: LimeProperty) = getParentFullName(limeProperty) + "::" + getSetterName(limeProperty) - private fun getCachedEntry(limeElement: LimeNamedElement) = - namesCache.getOrPut(limeElement.fullName) { resolveNames(limeElement) } + private fun getCachedEntry(limeElement: LimeNamedElement) = namesCache.getOrPut(limeElement.fullName) { resolveNames(limeElement) } private fun getParentFullName(limeElement: LimeNamedElement): String { val parentPath = limeElement.path.parent.toString() @@ -98,16 +93,18 @@ internal class CppNameCache( val externalName = limeElement.external?.cpp?.get(NAME_NAME) val platformName = limeElement.attributes.get(CPP, NAME) - val name = when { - externalName != null -> externalName - platformName != null -> platformName - isExternal -> limeElement.name - else -> nameRules.getName(limeElement) - } - val fullName = when { - externalName != null -> externalName - else -> "$parentFullName::$name" - } + val name = + when { + externalName != null -> externalName + platformName != null -> platformName + isExternal -> limeElement.name + else -> nameRules.getName(limeElement) + } + val fullName = + when { + externalName != null -> externalName + else -> "$parentFullName::$name" + } return NamesCacheEntry(isExternal, name, fullName) } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppNameResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppNameResolver.kt index eaee2f5ab1..e7a2af9118 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppNameResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppNameResolver.kt @@ -67,9 +67,8 @@ internal class CppNameResolver( private val limeLogger: LimeLogger? = null, private val commentsProcessor: CommentsProcessor? = null, private val forceFullNames: Boolean = false, - private val forceFollowThrough: Boolean = false + private val forceFollowThrough: Boolean = false, ) : ReferenceMapBasedResolver(limeReferenceMap), NameResolver { - private val hashTypeName = (listOf("") + internalNamespace + "hash").joinToString("::") private val localeTypeName = (listOf("") + internalNamespace + "Locale").joinToString("::") @@ -91,13 +90,14 @@ internal class CppNameResolver( override fun resolveGetterName(element: Any) = when (element) { is LimeProperty -> nameCache.getGetterName(element) - is LimeField -> when { - element.external?.cpp?.get(GETTER_NAME_NAME) != null -> - nameCache.getGetterName(element) - getParentElement(element).attributes.have(CPP, ACCESSORS) -> - nameCache.getGetterName(element) - else -> null - } + is LimeField -> + when { + element.external?.cpp?.get(GETTER_NAME_NAME) != null -> + nameCache.getGetterName(element) + getParentElement(element).attributes.have(CPP, ACCESSORS) -> + nameCache.getGetterName(element) + else -> null + } else -> throw GluecodiumExecutionException("Unsupported element type ${element.javaClass.name}") } @@ -105,13 +105,14 @@ internal class CppNameResolver( override fun resolveSetterName(element: Any) = when (element) { is LimeProperty -> nameCache.getSetterName(element) - is LimeField -> when { - element.external?.cpp?.get(SETTER_NAME_NAME) != null -> - nameCache.getSetterName(element) - getParentElement(element).attributes.have(CPP, ACCESSORS) -> - nameCache.getSetterName(element) - else -> null - } + is LimeField -> + when { + element.external?.cpp?.get(SETTER_NAME_NAME) != null -> + nameCache.getSetterName(element) + getParentElement(element).attributes.have(CPP, ACCESSORS) -> + nameCache.getSetterName(element) + else -> null + } else -> throw GluecodiumExecutionException("Unsupported element type ${element.javaClass.name}") } @@ -125,42 +126,49 @@ internal class CppNameResolver( } } - private fun resolveTypeName(limeType: LimeType, isFullName: Boolean, attributes: LimeAttributes? = null): String = + private fun resolveTypeName( + limeType: LimeType, + isFullName: Boolean, + attributes: LimeAttributes? = null, + ): String = when { forceFollowThrough && limeType is LimeTypeAlias -> resolveTypeName(limeType.typeRef.type, isFullName, limeType.typeRef.attributes) limeType is LimeBasicType -> resolveBasicType(limeType.typeId, attributes) limeType is LimeGenericType -> resolveGenericType(limeType, attributes) limeType is LimeException -> "::std::error_code" - isFullName -> when (limeType.actualType) { - is LimeContainerWithInheritance -> - "::std::shared_ptr< ${nameCache.getFullyQualifiedName(limeType)} >" - else -> nameCache.getFullyQualifiedName(limeType) - } + isFullName -> + when (limeType.actualType) { + is LimeContainerWithInheritance -> + "::std::shared_ptr< ${nameCache.getFullyQualifiedName(limeType)} >" + else -> nameCache.getFullyQualifiedName(limeType) + } forceFullNames -> nameCache.getFullyQualifiedName(limeType) else -> nameCache.getName(limeType) } - private fun resolveBasicType(typeId: TypeId, attributes: LimeAttributes? = null) = - when (typeId) { - TypeId.VOID -> "void" - TypeId.INT8 -> "int8_t" - TypeId.UINT8 -> "uint8_t" - TypeId.INT16 -> "int16_t" - TypeId.UINT16 -> "uint16_t" - TypeId.INT32 -> "int32_t" - TypeId.UINT32 -> "uint32_t" - TypeId.INT64 -> "int64_t" - TypeId.UINT64 -> "uint64_t" - TypeId.BOOLEAN -> "bool" - TypeId.FLOAT -> "float" - TypeId.DOUBLE -> "double" - TypeId.STRING -> attributes?.get(CPP, TYPE) ?: "::std::string" - TypeId.BLOB -> "::std::shared_ptr< ::std::vector< uint8_t > >" - TypeId.DATE -> attributes?.get(CPP, TYPE) ?: "::std::chrono::system_clock::time_point" - TypeId.DURATION -> attributes?.get(CPP, TYPE) ?: "::std::chrono::seconds" - TypeId.LOCALE -> localeTypeName - } + private fun resolveBasicType( + typeId: TypeId, + attributes: LimeAttributes? = null, + ) = when (typeId) { + TypeId.VOID -> "void" + TypeId.INT8 -> "int8_t" + TypeId.UINT8 -> "uint8_t" + TypeId.INT16 -> "int16_t" + TypeId.UINT16 -> "uint16_t" + TypeId.INT32 -> "int32_t" + TypeId.UINT32 -> "uint32_t" + TypeId.INT64 -> "int64_t" + TypeId.UINT64 -> "uint64_t" + TypeId.BOOLEAN -> "bool" + TypeId.FLOAT -> "float" + TypeId.DOUBLE -> "double" + TypeId.STRING -> attributes?.get(CPP, TYPE) ?: "::std::string" + TypeId.BLOB -> "::std::shared_ptr< ::std::vector< uint8_t > >" + TypeId.DATE -> attributes?.get(CPP, TYPE) ?: "::std::chrono::system_clock::time_point" + TypeId.DURATION -> attributes?.get(CPP, TYPE) ?: "::std::chrono::seconds" + TypeId.LOCALE -> localeTypeName + } private fun resolveValue(limeValue: LimeValue): String = when (limeValue) { @@ -211,58 +219,65 @@ internal class CppNameResolver( private fun resolveDurationValue(limeValue: LimeValue.Duration): String { val typeName = resolveBasicType(TypeId.DURATION, limeValue.typeRef.attributes) - val factoryMethod = when (limeValue.timeUnit) { - TimeUnit.DAY, TimeUnit.HOUR -> "::std::chrono::hours" - TimeUnit.MINUTE -> "::std::chrono::minutes" - TimeUnit.SECOND -> "::std::chrono::seconds" - TimeUnit.MILLISECOND -> "::std::chrono::milliseconds" - TimeUnit.MICROSECOND -> "::std::chrono::microseconds" - TimeUnit.NANOSECOND -> "::std::chrono::nanoseconds" - } - val multiplierSuffix = when (limeValue.timeUnit) { - TimeUnit.DAY -> " * 24" - else -> "" - } + val factoryMethod = + when (limeValue.timeUnit) { + TimeUnit.DAY, TimeUnit.HOUR -> "::std::chrono::hours" + TimeUnit.MINUTE -> "::std::chrono::minutes" + TimeUnit.SECOND -> "::std::chrono::seconds" + TimeUnit.MILLISECOND -> "::std::chrono::milliseconds" + TimeUnit.MICROSECOND -> "::std::chrono::microseconds" + TimeUnit.NANOSECOND -> "::std::chrono::nanoseconds" + } + val multiplierSuffix = + when (limeValue.timeUnit) { + TimeUnit.DAY -> " * 24" + else -> "" + } return "::std::chrono::duration_cast<$typeName>($factoryMethod(${limeValue.value}$multiplierSuffix))" } - private fun resolveGenericType(limeType: LimeGenericType, attributes: LimeAttributes? = null) = - when (limeType) { - is LimeList -> { - val elementType = limeType.elementType - val elementName = when { + private fun resolveGenericType( + limeType: LimeGenericType, + attributes: LimeAttributes? = null, + ) = when (limeType) { + is LimeList -> { + val elementType = limeType.elementType + val elementName = + when { (attributes?.have(OPTIMIZED) == true) && elementType.type.actualType !is LimeContainerWithInheritance -> "::std::shared_ptr< ${resolveName(elementType)} >" else -> resolveName(elementType) } - "::std::vector< $elementName >" - } - is LimeMap -> { - val keyName = resolveName(limeType.keyType) - val valueName = resolveName(limeType.valueType) - val hashInfix = resolveHashInfix(limeType.keyType, keyName) - "::std::unordered_map< $keyName, $valueName$hashInfix >" - } - is LimeSet -> { - val elementName = resolveName(limeType.elementType) - val hashInfix = resolveHashInfix(limeType.elementType, elementName) - "::std::unordered_set< $elementName$hashInfix >" - } - else -> throw GluecodiumExecutionException( - "Unsupported element type ${limeType.javaClass.name}" - ) + "::std::vector< $elementName >" + } + is LimeMap -> { + val keyName = resolveName(limeType.keyType) + val valueName = resolveName(limeType.valueType) + val hashInfix = resolveHashInfix(limeType.keyType, keyName) + "::std::unordered_map< $keyName, $valueName$hashInfix >" + } + is LimeSet -> { + val elementName = resolveName(limeType.elementType) + val hashInfix = resolveHashInfix(limeType.elementType, elementName) + "::std::unordered_set< $elementName$hashInfix >" } + else -> throw GluecodiumExecutionException( + "Unsupported element type ${limeType.javaClass.name}", + ) + } - private fun resolveHashInfix(limeTypeRef: LimeTypeRef, resolvedName: String) = - if (CppLibraryIncludes.hasStdHash(limeTypeRef)) "" else ", $hashTypeName< $resolvedName >" + private fun resolveHashInfix( + limeTypeRef: LimeTypeRef, + resolvedName: String, + ) = if (CppLibraryIncludes.hasStdHash(limeTypeRef)) "" else ", $hashTypeName< $resolvedName >" private fun resolveComment(limeComment: LimeComment) = commentsProcessor?.process( limeComment.path.toString(), limeComment.getFor("Cpp"), limeToCppNames, - limeLogger + limeLogger, ) ?: "" private fun getFullyQualifiedReference(limeElement: LimeNamedElement) = @@ -276,40 +291,48 @@ internal class CppNameResolver( } private fun buildPathMap(): Map { - val result = limeReferenceMap.values - .filterIsInstance() - .filterNot { it is LimeProperty || it is LimeException || it is LimeBasicType || it is LimeParameter } - .associateBy({ it.path.toAmbiguousString() }, { getFullyQualifiedReference(it) }) - .toMutableMap() + val result = + limeReferenceMap.values + .filterIsInstance() + .filterNot { it is LimeProperty || it is LimeException || it is LimeBasicType || it is LimeParameter } + .associateBy({ it.path.toAmbiguousString() }, { getFullyQualifiedReference(it) }) + .toMutableMap() - result += limeReferenceMap.values.filterIsInstance() - .associateBy({ it.path.toAmbiguousString() }, { resolveName(it.errorType) }) - result += limeReferenceMap.values.filterIsInstance() - .associateBy({ it.fullName }, { resolveName(it) }) + result += + limeReferenceMap.values.filterIsInstance() + .associateBy({ it.path.toAmbiguousString() }, { resolveName(it.errorType) }) + result += + limeReferenceMap.values.filterIsInstance() + .associateBy({ it.fullName }, { resolveName(it) }) val functions = limeReferenceMap.values.filterIsInstance() result += functions.associateBy({ it.path.toAmbiguousString() }, { getFullyQualifiedReference(it) }) - result += functions.associateBy( - { function -> - function.path.toAmbiguousString() + function.parameters - .joinToString(prefix = "(", postfix = ")", separator = ",") { it.typeRef.toString() } - }, - { getFullyQualifiedReference(it) } - ) + result += + functions.associateBy( + { function -> + function.path.toAmbiguousString() + + function.parameters + .joinToString(prefix = "(", postfix = ")", separator = ",") { it.typeRef.toString() } + }, + { getFullyQualifiedReference(it) }, + ) val properties = limeReferenceMap.values.filterIsInstance() - result += properties.associateBy( - { it.path.toAmbiguousString() }, - { nameCache.getFullyQualifiedGetterName(it) } - ) - result += properties.associateBy( - { it.path.toAmbiguousString() + ".get" }, - { nameCache.getFullyQualifiedGetterName(it) } - ) - result += properties.filter { it.setter != null }.associateBy( - { it.path.toAmbiguousString() + ".set" }, - { nameCache.getFullyQualifiedSetterName(it) } - ) + result += + properties.associateBy( + { it.path.toAmbiguousString() }, + { nameCache.getFullyQualifiedGetterName(it) }, + ) + result += + properties.associateBy( + { it.path.toAmbiguousString() + ".get" }, + { nameCache.getFullyQualifiedGetterName(it) }, + ) + result += + properties.filter { it.setter != null }.associateBy( + { it.path.toAmbiguousString() + ".set" }, + { nameCache.getFullyQualifiedSetterName(it) }, + ) return result } @@ -320,13 +343,14 @@ internal class CppNameResolver( fun needsRefSuffix(limeTypeRef: LimeTypeRef): Boolean { if (limeTypeRef.isNullable) return true return when (val actualType = limeTypeRef.type.actualType) { - is LimeBasicType -> when (actualType.typeId) { - TypeId.STRING -> !limeTypeRef.attributes.have(CPP, TYPE) - TypeId.BLOB -> true - TypeId.DATE -> true - TypeId.LOCALE -> true - else -> false - } + is LimeBasicType -> + when (actualType.typeId) { + TypeId.STRING -> !limeTypeRef.attributes.have(CPP, TYPE) + TypeId.BLOB -> true + TypeId.DATE -> true + TypeId.LOCALE -> true + else -> false + } is LimeEnumeration -> false else -> true } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppNameRules.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppNameRules.kt index f488676937..3e16d51baa 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppNameRules.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppNameRules.kt @@ -28,9 +28,8 @@ import java.io.File internal class CppNameRules( private val rootNamespace: List, - nameRuleSet: NameRuleSet + nameRuleSet: NameRuleSet, ) : NameRules(nameRuleSet) { - fun getOutputFilePath(limeElement: LimeNamedElement): String { val fileName = limeElement.attributes.get(CPP, NAME) ?: ruleSet.getTypeName(limeElement.path.container) diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppSignatureResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppSignatureResolver.kt index 46ca523ef9..045b53635f 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppSignatureResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppSignatureResolver.kt @@ -30,9 +30,8 @@ import com.here.gluecodium.model.lime.LimeTypeRef internal class CppSignatureResolver( limeReferenceMap: Map, - nameRules: CppNameRules + nameRules: CppNameRules, ) : PlatformSignatureResolver(limeReferenceMap, CPP, nameRules, emptySet()) { - override fun getNullableSuffix(limeTypeRef: LimeTypeRef) = when { !limeTypeRef.isNullable -> "" diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppSkipAttributesValidator.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppSkipAttributesValidator.kt index 8a399e64e7..cfc47de36f 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppSkipAttributesValidator.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/CppSkipAttributesValidator.kt @@ -31,7 +31,6 @@ import com.here.gluecodium.model.lime.LimeNamedElement * Validate that `@Cpp(Skip)` attribute is only used on field constructors of structs. */ internal class CppSkipAttributesValidator(private val logger: LimeLogger) { - fun validate(limeModel: LimeModel): Boolean { val allElements = limeModel.referenceMap.values val validationResults = allElements.filterIsInstance().map { validateElement(it) } @@ -45,7 +44,7 @@ internal class CppSkipAttributesValidator(private val logger: LimeLogger) { limeElement.attributes.have(LimeAttributeType.CPP, LimeAttributeValueType.SKIP) -> { logger.error( limeElement, - "`@Cpp(Skip)` attribute can only be used on a field constructor or a constant" + "`@Cpp(Skip)` attribute can only be used on a field constructor or a constant", ) false } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/DoxygenCommentsProcessor.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/DoxygenCommentsProcessor.kt index 9892206f62..dc3f88f260 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/DoxygenCommentsProcessor.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/DoxygenCommentsProcessor.kt @@ -25,8 +25,11 @@ import com.vladsch.flexmark.formatter.Formatter import com.vladsch.flexmark.util.sequence.CharSubSequence internal class DoxygenCommentsProcessor(werror: Boolean) : CommentsProcessor(Formatter.builder().build(), werror) { - - override fun processLink(linkNode: LinkRef, linkReference: String, limeFullName: String) { + override fun processLink( + linkNode: LinkRef, + linkReference: String, + limeFullName: String, + ) { linkNode.reference = CharSubSequence.of(linkReference) // Doxygen documentation claims that \link classname Alternative title \endlink is the // correct way to have a link with alternative title, however it only works for a small diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/TopologicalSort.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/TopologicalSort.kt index c1b494b691..2955d9b472 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/TopologicalSort.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/cpp/TopologicalSort.kt @@ -30,7 +30,6 @@ import com.here.gluecodium.model.lime.LimeTypeRef import com.here.gluecodium.model.lime.LimeTypedElement internal class TopologicalSort(private val elements: List) { - private val fullNames = elements.map { it.fullName }.toSet() /** @@ -39,18 +38,20 @@ internal class TopologicalSort(private val elements: List) { * to structs so the most-basic structs are defined first to avoid compilation errors on C++. */ fun sort(): List { - val dependencies = elements.associateBy( - { it.fullName }, - { getElementDependencies(it).toMutableSet() } - ) + val dependencies = + elements.associateBy( + { it.fullName }, + { getElementDependencies(it).toMutableSet() }, + ) val sortedElements = mutableListOf() while (sortedElements.size < elements.size) { // Find the first element with no dependency needed which is not in the sorted elements. - val nextElement = elements.firstOrNull { - val dependencySet = dependencies[it.fullName] - dependencySet != null && dependencySet.isEmpty() && !sortedElements.contains(it) - } ?: throw GluecodiumExecutionException("Cycle detected in C++ elements dependencies.") + val nextElement = + elements.firstOrNull { + val dependencySet = dependencies[it.fullName] + dependencySet != null && dependencySet.isEmpty() && !sortedElements.contains(it) + } ?: throw GluecodiumExecutionException("Cycle detected in C++ elements dependencies.") sortedElements.add(nextElement) @@ -72,16 +73,19 @@ internal class TopologicalSort(private val elements: List) { private fun getElementDependencies(limeElement: LimeNamedElement): Set = when (limeElement) { is LimeTypedElement -> getTypeRefDependencies(limeElement.typeRef) - is LimeStruct -> (limeElement.fields + limeElement.functions + limeElement.constants) - .flatMap { getElementDependencies(it) } + is LimeStruct -> + (limeElement.fields + limeElement.functions + limeElement.constants) + .flatMap { getElementDependencies(it) } is LimeTypeAlias -> getTypeRefDependencies(limeElement.typeRef) - is LimeFunction -> ( - limeElement.parameters.map { it.typeRef } + - listOfNotNull(limeElement.returnType.typeRef, limeElement.exception?.errorType) + is LimeFunction -> + ( + limeElement.parameters.map { it.typeRef } + + listOfNotNull(limeElement.returnType.typeRef, limeElement.exception?.errorType) ) - .flatMap { getTypeRefDependencies(it) } - is LimeLambda -> (limeElement.parameters.map { it.typeRef } + limeElement.returnType.typeRef) - .flatMap { getTypeRefDependencies(it) } + .flatMap { getTypeRefDependencies(it) } + is LimeLambda -> + (limeElement.parameters.map { it.typeRef } + limeElement.returnType.typeRef) + .flatMap { getTypeRefDependencies(it) } else -> emptyList() }.toSet() - limeElement.fullName } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartAsyncHelpers.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartAsyncHelpers.kt index 1d2abb63f6..3f4fd84579 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartAsyncHelpers.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartAsyncHelpers.kt @@ -38,7 +38,7 @@ internal object DartAsyncHelpers { class AsyncHelpersGroup( val pathKey: String, val lambdas: List, - val helpers: Map + val helpers: Map, ) private const val FIRST_PARAMETER_NAME = "p0" @@ -46,14 +46,16 @@ internal object DartAsyncHelpers { private const val ERROR_LAMBDA = "__errorLambda" private const val ASYNC_FUNCTION = "__async" - fun createAsyncHelpers(rootElement: LimeNamedElement, dartNameResolver: DartNameResolver) = - LimeTypeHelper.getAllTypes(rootElement) - .filterIsInstance() - .map { createAsyncHelpersGroup(it, dartNameResolver) } + fun createAsyncHelpers( + rootElement: LimeNamedElement, + dartNameResolver: DartNameResolver, + ) = LimeTypeHelper.getAllTypes(rootElement) + .filterIsInstance() + .map { createAsyncHelpersGroup(it, dartNameResolver) } private fun createAsyncHelpersGroup( limeContainer: LimeContainer, - dartNameResolver: DartNameResolver + dartNameResolver: DartNameResolver, ): AsyncHelpersGroup { val lambdas = mutableListOf() val helpers = mutableMapOf() @@ -62,45 +64,54 @@ internal object DartAsyncHelpers { for (limeFunction in asyncFunctions) { val functionName = dartNameResolver.resolveName(limeFunction) val resultLambda = createResultLambda(limeFunction, functionName).also { lambdas += it } - val errorLambda = limeFunction.exception - ?.let { createErrorLambda(limeFunction, it, functionName) } - ?.also { lambdas += it } + val errorLambda = + limeFunction.exception + ?.let { createErrorLambda(limeFunction, it, functionName) } + ?.also { lambdas += it } helpers[limeFunction.fullName] = createAsyncHelper(limeFunction, functionName, resultLambda, errorLambda) } return AsyncHelpersGroup(limeContainer.fullName, lambdas, helpers) } - private fun createResultLambda(limeFunction: LimeFunction, functionName: String): LimeLambda { + private fun createResultLambda( + limeFunction: LimeFunction, + functionName: String, + ): LimeLambda { val path = limeFunction.path.parent.child(limeFunction.name + RESULT_LAMBDA, limeFunction.path.disambiguator) return LimeLambda( path, attributes = LimeAttributes.Builder().addAttribute(DART, NAME, functionName + RESULT_LAMBDA).build(), - parameters = when { - limeFunction.returnType.isVoid -> emptyList() - else -> listOf( - LimeLambdaParameter( - limeFunction.returnType.typeRef, path.child(FIRST_PARAMETER_NAME) - ) - ) - } + parameters = + when { + limeFunction.returnType.isVoid -> emptyList() + else -> + listOf( + LimeLambdaParameter( + limeFunction.returnType.typeRef, + path.child(FIRST_PARAMETER_NAME), + ), + ) + }, ) } private fun createErrorLambda( limeFunction: LimeFunction, limeException: LimeException, - functionName: String + functionName: String, ): LimeLambda { val path = limeFunction.path.parent.child(limeFunction.name + ERROR_LAMBDA, limeFunction.path.disambiguator) return LimeLambda( path, attributes = LimeAttributes.Builder().addAttribute(DART, NAME, functionName + ERROR_LAMBDA).build(), - parameters = listOf( - LimeLambdaParameter( - limeException.errorType, path.child(FIRST_PARAMETER_NAME) - ) - ) + parameters = + listOf( + LimeLambdaParameter( + limeException.errorType, + path.child(FIRST_PARAMETER_NAME), + ), + ), ) } @@ -108,21 +119,23 @@ internal object DartAsyncHelpers { limeFunction: LimeFunction, functionName: String, resultLambda: LimeLambda, - errorLambda: LimeLambda? + errorLambda: LimeLambda?, ): LimeFunction { val path = limeFunction.path.withSuffix(limeFunction.path.disambiguator + "async") - val resultLambdaParameter = LimeParameter( - path = path.child("_resultLambda"), - typeRef = LimeDirectTypeRef(resultLambda), - attributes = LimeAttributes.Builder().addAttribute(DART, NAME, "_resultLambda").build(), - ) - val errorLambdaParameter = errorLambda?.let { + val resultLambdaParameter = LimeParameter( - path = path.child("_errorLambda"), - typeRef = LimeDirectTypeRef(errorLambda), - attributes = LimeAttributes.Builder().addAttribute(DART, NAME, "_errorLambda").build(), + path = path.child("_resultLambda"), + typeRef = LimeDirectTypeRef(resultLambda), + attributes = LimeAttributes.Builder().addAttribute(DART, NAME, "_resultLambda").build(), ) - } + val errorLambdaParameter = + errorLambda?.let { + LimeParameter( + path = path.child("_errorLambda"), + typeRef = LimeDirectTypeRef(errorLambda), + attributes = LimeAttributes.Builder().addAttribute(DART, NAME, "_errorLambda").build(), + ) + } val attributes = LimeAttributes.Builder().addAttribute(DART, NAME, "_$functionName$ASYNC_FUNCTION") limeFunction.attributes.get(CPP, NAME)?.let { attributes.addAttribute(CPP, NAME, it) } @@ -130,7 +143,7 @@ internal object DartAsyncHelpers { path = path, attributes = attributes.build(), parameters = listOfNotNull(resultLambdaParameter, errorLambdaParameter) + limeFunction.parameters, - isStatic = limeFunction.isStatic + isStatic = limeFunction.isStatic, ) } } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartCommentsProcessor.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartCommentsProcessor.kt index 7aeabbe571..52debf0676 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartCommentsProcessor.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartCommentsProcessor.kt @@ -25,8 +25,11 @@ import com.vladsch.flexmark.formatter.Formatter import com.vladsch.flexmark.util.sequence.CharSubSequence internal class DartCommentsProcessor(werror: Boolean) : CommentsProcessor(Formatter.builder().build(), werror) { - - override fun processLink(linkNode: LinkRef, linkReference: String, limeFullName: String) { + override fun processLink( + linkNode: LinkRef, + linkReference: String, + limeFullName: String, + ) { linkNode.reference = CharSubSequence.of(linkReference) linkNode.referenceOpeningMarker = CharSubSequence.of("[") linkNode.referenceClosingMarker = CharSubSequence.of("]") diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartDeclarationImportResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartDeclarationImportResolver.kt index cc40126b3c..393453da18 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartDeclarationImportResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartDeclarationImportResolver.kt @@ -39,9 +39,8 @@ internal class DartDeclarationImportResolver( limeReferenceMap: Map, nameResolver: DartNameResolver, srcPath: String, - private val descendantInterfaces: Map> + private val descendantInterfaces: Map>, ) : DartImportResolverBase(limeReferenceMap, nameResolver, srcPath) { - private val builtInTypesConversionImport = DartImport("$srcPath/${"builtin_types"}__conversion") private val typeRepositoryImport = DartImport("$srcPath/_type_repository", "__lib") private val tokenCacheImport = DartImport("$srcPath/_token_cache", "__lib") @@ -63,10 +62,11 @@ internal class DartDeclarationImportResolver( limeElement is LimeInterface -> resolveInterfaceImports(limeElement) limeElement is LimeClass -> resolveClassImports(limeElement) else -> emptyList() - } + listOfNotNull( - resolveExternalImport(limeElement, IMPORT_PATH_NAME, useAlias = true), - resolveExternalImport(limeElement, CONVERTER_IMPORT_NAME, useAlias = false) - ) + listOf(ffiSystemImport, libraryContextImport) + } + + listOfNotNull( + resolveExternalImport(limeElement, IMPORT_PATH_NAME, useAlias = true), + resolveExternalImport(limeElement, CONVERTER_IMPORT_NAME, useAlias = false), + ) + listOf(ffiSystemImport, libraryContextImport) } private fun resolveStructImports(limeStruct: LimeStruct): List { @@ -100,10 +100,11 @@ internal class DartDeclarationImportResolver( } private fun resolveClassImports(limeClass: LimeClass): List { - val result = when { - limeClass.parents.isNotEmpty() || limeClass.isOpen -> classInterfaceImports - else -> listOf(tokenCacheImport, nativeBaseImport) - }.toMutableList() + val result = + when { + limeClass.parents.isNotEmpty() || limeClass.isOpen -> classInterfaceImports + else -> listOf(tokenCacheImport, nativeBaseImport) + }.toMutableList() if (hasStaticFunctions(limeClass)) { result += listOf(metaPackageImport) } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartGenerator.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartGenerator.kt index 4ab22db5c0..6c3531bb56 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartGenerator.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartGenerator.kt @@ -78,7 +78,6 @@ import com.here.gluecodium.model.lime.LimeTypeRef import java.util.logging.Logger internal class DartGenerator : Generator { - private lateinit var libraryName: String private lateinit var lookupErrorMessage: String private lateinit var nameRules: NameRules @@ -108,96 +107,107 @@ internal class DartGenerator : Generator { override fun generate(limeModel: LimeModel): List { val limeLogger = LimeLogger(logger, limeModel.fileNameMap) - val ffiFilteredModel = LimeModelFilter.filter(limeModel) { - LimeModelSkipPredicates.shouldRetainElement(it, activeTags, DART, retainFunctionsAndFields = true) - } + val ffiFilteredModel = + LimeModelFilter.filter(limeModel) { + LimeModelSkipPredicates.shouldRetainElement(it, activeTags, DART, retainFunctionsAndFields = true) + } val visibilityResolver = VisibilityResolver(limeModel.referenceMap) - val dartFilteredModel = LimeModelFilter.filter(limeModel) { - !visibilityResolver.isSkippedByVisibility(it) && - LimeModelSkipPredicates.shouldRetainElement(it, activeTags, DART, retainFunctionsAndFields = false) - } + val dartFilteredModel = + LimeModelFilter.filter(limeModel) { + !visibilityResolver.isSkippedByVisibility(it) && + LimeModelSkipPredicates.shouldRetainElement(it, activeTags, DART, retainFunctionsAndFields = false) + } val ffiReferenceMap = ffiFilteredModel.referenceMap.toMutableMap() val dartNameResolver = DartNameResolver(ffiReferenceMap, nameRules, limeLogger, commentsProcessor) val ffiNameResolver = FfiNameResolver(ffiReferenceMap, nameRules, internalPrefix) - val validationResult = DartOverloadsValidator(dartNameResolver, limeLogger, overloadsWerror) - .validate(dartFilteredModel.referenceMap.values) + val validationResult = + DartOverloadsValidator(dartNameResolver, limeLogger, overloadsWerror) + .validate(dartFilteredModel.referenceMap.values) if (!validationResult) { throw GluecodiumExecutionException("Validation errors found, see log for details.") } - val dartResolvers = mapOf( - "" to dartNameResolver, - "Ffi" to CamelCaseNameResolver(ffiNameResolver), - "FfiSnakeCase" to ffiNameResolver, - "FfiApiTypes" to FfiApiTypeNameResolver(), - "FfiDartTypes" to FfiDartTypeNameResolver(), - "visibility" to DartVisibilityResolver(dartFilteredModel.referenceMap) - ) + val dartResolvers = + mapOf( + "" to dartNameResolver, + "Ffi" to CamelCaseNameResolver(ffiNameResolver), + "FfiSnakeCase" to ffiNameResolver, + "FfiApiTypes" to FfiApiTypeNameResolver(), + "FfiDartTypes" to FfiDartTypeNameResolver(), + "visibility" to DartVisibilityResolver(dartFilteredModel.referenceMap), + ) val ffiCppNameResolver = FfiCppNameResolver(ffiReferenceMap, cppNameRules, rootNamespace, internalNamespace) - val ffiResolvers = mapOf( - "" to ffiNameResolver, - "C++" to ffiCppNameResolver, - "C++ parameter" to FfiCppParameterTypeNameResolver(ffiCppNameResolver), - "C++ return type" to FfiCppReturnTypeNameResolver(internalNamespace, ffiCppNameResolver) - ) + val ffiResolvers = + mapOf( + "" to ffiNameResolver, + "C++" to ffiCppNameResolver, + "C++ parameter" to FfiCppParameterTypeNameResolver(ffiCppNameResolver), + "C++ return type" to FfiCppReturnTypeNameResolver(internalNamespace, ffiCppNameResolver), + ) val descendantInterfaces = LimeTypeHelper.collectDescendantInterfaces(dartFilteredModel.topElements) val importResolver = DartImportResolver(dartFilteredModel.referenceMap, dartNameResolver, "$libraryName/$SRC_DIR_SUFFIX") - val declarationImportResolver = DartDeclarationImportResolver( - dartFilteredModel.referenceMap, - dartNameResolver, - "$libraryName/$SRC_DIR_SUFFIX", - descendantInterfaces - ) + val declarationImportResolver = + DartDeclarationImportResolver( + dartFilteredModel.referenceMap, + dartNameResolver, + "$libraryName/$SRC_DIR_SUFFIX", + descendantInterfaces, + ) val importsCollector = DartImportsCollector(importResolver) val declarationImportsCollector = GenericImportsCollector(declarationImportResolver, collectOwnImports = true) val generatorPredicates = DartGeneratorPredicates(dartFilteredModel.referenceMap, activeTags, dartNameResolver) val predicatesMap = generatorPredicates.predicates val includeResolver = FfiCppIncludeResolver(ffiReferenceMap, cppNameRules, internalNamespace) - val includeCollector = GenericIncludesCollector( - includeResolver, - retainPredicate = { - generatorPredicates.shouldRetain(it) || - CommonGeneratorPredicates.needsImportsForSkippedField(it, DART, ffiReferenceMap) - } - ) + val includeCollector = + GenericIncludesCollector( + includeResolver, + retainPredicate = { + generatorPredicates.shouldRetain(it) || + CommonGeneratorPredicates.needsImportsForSkippedField(it, DART, ffiReferenceMap) + }, + ) val exportsCollector = mutableMapOf, MutableList>() val typeRepositoriesCollector = mutableListOf() - val genericTypes = TypeRefsCollector.getAllTypeRefs(dartFilteredModel) - .map { it.type } - .filterIsInstance() - .distinctBy { ffiNameResolver.resolveName(it) } - .sortedBy { ffiNameResolver.resolveName(it) } - - val asyncHelpers = dartFilteredModel.topElements - .flatMap { DartAsyncHelpers.createAsyncHelpers(it, dartNameResolver) } - .associateBy { it.pathKey } + val genericTypes = + TypeRefsCollector.getAllTypeRefs(dartFilteredModel) + .map { it.type } + .filterIsInstance() + .distinctBy { ffiNameResolver.resolveName(it) } + .sortedBy { ffiNameResolver.resolveName(it) } + + val asyncHelpers = + dartFilteredModel.topElements + .flatMap { DartAsyncHelpers.createAsyncHelpers(it, dartNameResolver) } + .associateBy { it.pathKey } injectAsyncHelpers(ffiReferenceMap, asyncHelpers) - val generatedFiles = dartFilteredModel.topElements.flatMap { - listOfNotNull( - generateDart( - it, dartResolvers, dartNameResolver, listOf(importsCollector, declarationImportsCollector), - exportsCollector, typeRepositoriesCollector, predicatesMap, descendantInterfaces, - asyncHelpers[it.fullName] + val generatedFiles = + dartFilteredModel.topElements.flatMap { + listOfNotNull( + generateDart( + it, dartResolvers, dartNameResolver, listOf(importsCollector, declarationImportsCollector), + exportsCollector, typeRepositoriesCollector, predicatesMap, descendantInterfaces, + asyncHelpers[it.fullName], + ), ) - ) - } + ffiFilteredModel.topElements.flatMap { - generateFfi( - it, ffiResolvers, includeResolver, includeCollector, ffiReferenceMap, activeTags, - asyncHelpers[it.fullName] - ) - } + - generateDartGenericTypesConversion(genericTypes, importResolver, dartResolvers, predicatesMap) + - generateFfiGenericTypesConversion(genericTypes, ffiResolvers, includeResolver) + - generateDartCommonFiles(exportsCollector, typeRepositoriesCollector, dartResolvers, importResolver) + - generateFfiCommonFiles(ffiResolvers) + } + + ffiFilteredModel.topElements.flatMap { + generateFfi( + it, ffiResolvers, includeResolver, includeCollector, ffiReferenceMap, activeTags, + asyncHelpers[it.fullName], + ) + } + + generateDartGenericTypesConversion(genericTypes, importResolver, dartResolvers, predicatesMap) + + generateFfiGenericTypesConversion(genericTypes, ffiResolvers, includeResolver) + + generateDartCommonFiles(exportsCollector, typeRepositoriesCollector, dartResolvers, importResolver) + + generateFfiCommonFiles(ffiResolvers) if (commentsProcessor.hasError) { throw GluecodiumExecutionException("Validation errors found, see log for details.") @@ -215,7 +225,7 @@ internal class DartGenerator : Generator { typeRepositoriesCollector: MutableList, predicates: Map Boolean>, descendantInterfaces: Map>, - asyncHelpers: DartAsyncHelpers.AsyncHelpersGroup? + asyncHelpers: DartAsyncHelpers.AsyncHelpersGroup?, ): GeneratedFile? { val contentTemplateName = selectTemplate(rootElement) ?: return null @@ -229,9 +239,10 @@ internal class DartGenerator : Generator { val allSymbols = nonExternalTypes.filterNot { CommonGeneratorPredicates.isInternal(it, DART) } if (allSymbols.isNotEmpty()) { val allNames = allSymbols.map { dartNameResolver.resolveName(it) } - val testNames = allSymbols - .filter { CommonGeneratorPredicates.hasStaticFunctions(it) } - .map { dartNameResolver.resolveName(it) + "\$Impl" } + val testNames = + allSymbols + .filter { CommonGeneratorPredicates.hasStaticFunctions(it) } + .map { dartNameResolver.resolveName(it) + "\$Impl" } exportsCollector .getOrPut(rootElement.path.head) { mutableListOf() } .add(DartExport(relativePath, (allNames + testNames).sorted())) @@ -240,20 +251,21 @@ internal class DartGenerator : Generator { val optimizedLists = OptimizedListsCollector().getAllOptimizedLists(rootElement) val imports = importCollectors.flatMap { it.collectImports(rootElement) } - val content = TemplateEngine.render( - "dart/DartFile", - mapOf( - "imports" to imports.distinct().sorted().filterNot { it.filePath.endsWith(filePath) }, - "model" to rootElement, - "contentTemplate" to contentTemplateName, - "libraryName" to libraryName, - "optimizedLists" to optimizedLists, - "descendantInterfaces" to descendantInterfaces, - "asyncHelpers" to asyncHelpers - ), - nameResolvers, - predicates - ) + val content = + TemplateEngine.render( + "dart/DartFile", + mapOf( + "imports" to imports.distinct().sorted().filterNot { it.filePath.endsWith(filePath) }, + "model" to rootElement, + "contentTemplate" to contentTemplateName, + "libraryName" to libraryName, + "optimizedLists" to optimizedLists, + "descendantInterfaces" to descendantInterfaces, + "asyncHelpers" to asyncHelpers, + ), + nameResolvers, + predicates, + ) return GeneratedFile(content, "$LIB_DIR/$relativePath") } @@ -269,7 +281,7 @@ internal class DartGenerator : Generator { includeCollector: ImportsCollector, limeReferenceMap: Map, activeTags: Set, - asyncHelpers: DartAsyncHelpers.AsyncHelpersGroup? + asyncHelpers: DartAsyncHelpers.AsyncHelpersGroup?, ): List { val limeType = rootElement as? LimeType if (limeType == null || limeType is LimeException) return emptyList() @@ -283,20 +295,21 @@ internal class DartGenerator : Generator { val packagePath = rootElement.path.head.joinToString(separator = "_") val fileName = "ffi_${packagePath}_${nameRules.getName(rootElement)}" - val data = mapOf( - "model" to rootElement, - "libraryName" to libraryName, - "classes" to classes, - "enums" to enums, - "interfaces" to interfaces, - "lambdas" to lambdas, - "typeRepositories" to getTypeRepositories(types), - "structs" to structs, - "internalNamespace" to internalNamespace, - "headerName" to fileName, - "includes" to includeCollector.collectImports(limeType).distinct().sorted(), - "asyncHelpers" to asyncHelpers - ) + val data = + mapOf( + "model" to rootElement, + "libraryName" to libraryName, + "classes" to classes, + "enums" to enums, + "interfaces" to interfaces, + "lambdas" to lambdas, + "typeRepositories" to getTypeRepositories(types), + "structs" to structs, + "internalNamespace" to internalNamespace, + "headerName" to fileName, + "includes" to includeCollector.collectImports(limeType).distinct().sorted(), + "asyncHelpers" to asyncHelpers, + ) val predicates = DartGeneratorPredicates(limeReferenceMap, activeTags).predicates val headerContent = TemplateEngine.render("ffi/FfiHeader", data, nameResolvers, predicates) val implContent = TemplateEngine.render("ffi/FfiImplementation", data, nameResolvers, predicates) @@ -305,10 +318,11 @@ internal class DartGenerator : Generator { return listOf( GeneratedFile(headerContent, "$FFI_DIR/$fileName.h"), - GeneratedFile(implContent, "$FFI_DIR/$fileName.cpp") - ) + optimizedLists.keys.flatMap { - generateOptimizedListFiles(limeReferenceMap[it], optimizedLists[it], fileName, nameResolvers, includeResolver, predicates) - } + GeneratedFile(implContent, "$FFI_DIR/$fileName.cpp"), + ) + + optimizedLists.keys.flatMap { + generateOptimizedListFiles(limeReferenceMap[it], optimizedLists[it], fileName, nameResolvers, includeResolver, predicates) + } } private fun generateOptimizedListFiles( @@ -317,15 +331,16 @@ internal class DartGenerator : Generator { fileNamePrefix: String, nameResolvers: Map, includeResolver: ImportsResolver, - predicates: Map Boolean> + predicates: Map Boolean>, ): List { if (limeElement !is LimeNamedElement || lists.isNullOrEmpty()) return emptyList() - val containerData = mutableMapOf( - "container" to limeElement, - "internalNamespace" to internalNamespace, - "libraryName" to libraryName - ) + val containerData = + mutableMapOf( + "container" to limeElement, + "internalNamespace" to internalNamespace, + "libraryName" to libraryName, + ) return lists.flatMap { generateOptimizedListFile(it, fileNamePrefix, containerData, nameResolvers, includeResolver, predicates) } @@ -337,25 +352,27 @@ internal class DartGenerator : Generator { containerData: MutableMap, nameResolvers: Map, includeResolver: ImportsResolver, - predicates: Map Boolean> + predicates: Map Boolean>, ): List { val fileName = "${containerFileName}_${limeList.elementType.type.actualType.name}LazyList" containerData["listType"] = LimeDirectTypeRef(limeList, attributes = optimizedAttributes) containerData["elementType"] = limeList.elementType - val headerFile = GeneratedFile( - TemplateEngine.render("ffi/FfiLazyListHeader", containerData, nameResolvers, predicates), - "$FFI_DIR/$fileName.h" - ) + val headerFile = + GeneratedFile( + TemplateEngine.render("ffi/FfiLazyListHeader", containerData, nameResolvers, predicates), + "$FFI_DIR/$fileName.h", + ) val implIncludes = includeResolver.resolveElementImports(limeList.elementType) + Include.createInternalInclude("$fileName.h") containerData["includes"] = implIncludes.distinct().sorted() - val implFile = GeneratedFile( - TemplateEngine.render("ffi/FfiLazyListImpl", containerData, nameResolvers, predicates), - "$FFI_DIR/$fileName.cpp" - ) + val implFile = + GeneratedFile( + TemplateEngine.render("ffi/FfiLazyListImpl", containerData, nameResolvers, predicates), + "$FFI_DIR/$fileName.cpp", + ) return listOf(headerFile, implFile) } @@ -364,134 +381,141 @@ internal class DartGenerator : Generator { exports: Map, List>, typeRepositories: List, nameResolvers: Map, - importResolver: DartImportResolver + importResolver: DartImportResolver, ): List { - val exportFiles = exports.map { - GeneratedFile( - TemplateEngine.render("dart/DartExports", mapOf("files" to it.value.sorted()), nameResolvers), - "$LIB_DIR/${it.key.joinToString(".")}.dart" + val exportFiles = + exports.map { + GeneratedFile( + TemplateEngine.render("dart/DartExports", mapOf("files" to it.value.sorted()), nameResolvers), + "$LIB_DIR/${it.key.joinToString(".")}.dart", + ) + } + val templateData = + mapOf( + "libraryName" to libraryName, + "lookupErrorMessage" to lookupErrorMessage, + "builtInTypes" to TypeId.values().subtract(customNullableTypes), + "typeRepositories" to typeRepositories.sortedBy { it.fullName }, + "imports" to + typeRepositories.flatMap { importResolver.resolveElementImports(it) }.distinct().sorted(), ) - } - val templateData = mapOf( - "libraryName" to libraryName, - "lookupErrorMessage" to lookupErrorMessage, - "builtInTypes" to TypeId.values().subtract(customNullableTypes), - "typeRepositories" to typeRepositories.sortedBy { it.fullName }, - "imports" to - typeRepositories.flatMap { importResolver.resolveElementImports(it) }.distinct().sorted() - ) - return exportFiles + listOf( - GeneratedFile( - TemplateEngine.render("dart/DartLibraryContextExport", templateData, nameResolvers), - "$LIB_DIR/${libraryName}_context.dart", - COMMON - ), - GeneratedFile( - TemplateEngine.render("dart/DartLibraryContext", templateData, nameResolvers), - "$LIB_DIR/$SRC_DIR_SUFFIX/_library_context.dart", - COMMON - ), - GeneratedFile( - TemplateEngine.render("dart/DartLazyList", templateData, nameResolvers), - "$LIB_DIR/$SRC_DIR_SUFFIX/_lazy_list.dart", - COMMON - ), - GeneratedFile( - TemplateEngine.render("dart/DartNativeBase", templateData, nameResolvers), - "$LIB_DIR/$SRC_DIR_SUFFIX/_native_base.dart", - COMMON - ), - GeneratedFile( - TemplateEngine.render("dart/DartPubspec", templateData, nameResolvers), - "$ROOT_DIR/pubspec.yaml", - COMMON - ), - GeneratedFile( - TemplateEngine.render("dart/DartBuiltInTypesConversion", templateData, nameResolvers), - "$LIB_DIR/$SRC_DIR_SUFFIX/builtin_types__conversion.dart", - COMMON - ), - GeneratedFile( - TemplateEngine.render("dart/DartTypeRepository", templateData, nameResolvers), - "$LIB_DIR/$SRC_DIR_SUFFIX/_type_repository.dart", - COMMON - ), - GeneratedFile( - TemplateEngine.render("dart/DartTokenCache", templateData, nameResolvers), - "$LIB_DIR/$SRC_DIR_SUFFIX/_token_cache.dart", - COMMON + return exportFiles + + listOf( + GeneratedFile( + TemplateEngine.render("dart/DartLibraryContextExport", templateData, nameResolvers), + "$LIB_DIR/${libraryName}_context.dart", + COMMON, + ), + GeneratedFile( + TemplateEngine.render("dart/DartLibraryContext", templateData, nameResolvers), + "$LIB_DIR/$SRC_DIR_SUFFIX/_library_context.dart", + COMMON, + ), + GeneratedFile( + TemplateEngine.render("dart/DartLazyList", templateData, nameResolvers), + "$LIB_DIR/$SRC_DIR_SUFFIX/_lazy_list.dart", + COMMON, + ), + GeneratedFile( + TemplateEngine.render("dart/DartNativeBase", templateData, nameResolvers), + "$LIB_DIR/$SRC_DIR_SUFFIX/_native_base.dart", + COMMON, + ), + GeneratedFile( + TemplateEngine.render("dart/DartPubspec", templateData, nameResolvers), + "$ROOT_DIR/pubspec.yaml", + COMMON, + ), + GeneratedFile( + TemplateEngine.render("dart/DartBuiltInTypesConversion", templateData, nameResolvers), + "$LIB_DIR/$SRC_DIR_SUFFIX/builtin_types__conversion.dart", + COMMON, + ), + GeneratedFile( + TemplateEngine.render("dart/DartTypeRepository", templateData, nameResolvers), + "$LIB_DIR/$SRC_DIR_SUFFIX/_type_repository.dart", + COMMON, + ), + GeneratedFile( + TemplateEngine.render("dart/DartTokenCache", templateData, nameResolvers), + "$LIB_DIR/$SRC_DIR_SUFFIX/_token_cache.dart", + COMMON, + ), ) - ) } private fun generateFfiCommonFiles(nameResolvers: Map): List { - val headerOnly = listOf("ConversionBase", "Export", "OpaqueHandle") - val headerAndImpl = listOf( - "BlobHandle", - "CallbacksQueue", - "CallbacksHandle", - "DartDLInit", - "InstanceCache", - "IsolateContext", - "FinalizerData", - "LocaleHandle", - "NullableHandles", - "ProxyCache", - "StringHandle" - ) - val data = mapOf( - "libraryName" to libraryName, - "opaqueHandleType" to OPAQUE_HANDLE_TYPE, - "internalNamespace" to internalNamespace, - "builtInTypes" to TypeId.values().subtract(customNullableTypes) - ) + val headerAndImpl = + listOf( + "BlobHandle", + "CallbacksQueue", + "CallbacksHandle", + "DartDLInit", + "InstanceCache", + "IsolateContext", + "FinalizerData", + "LocaleHandle", + "NullableHandles", + "ProxyCache", + "StringHandle", + ) + val data = + mapOf( + "libraryName" to libraryName, + "opaqueHandleType" to OPAQUE_HANDLE_TYPE, + "internalNamespace" to internalNamespace, + "builtInTypes" to TypeId.values().subtract(customNullableTypes), + ) return headerOnly.map { GeneratedFile( TemplateEngine.render("ffi/Ffi$it", data, nameResolvers), "$FFI_DIR/$it.h", - COMMON + COMMON, ) - } + headerAndImpl.flatMap { - listOf( - GeneratedFile( - TemplateEngine.render("ffi/Ffi${it}Header", data, nameResolvers), - "$FFI_DIR/$it.h", - COMMON - ), - GeneratedFile( - TemplateEngine.render("ffi/Ffi${it}Impl", data, nameResolvers), - "$FFI_DIR/$it.cpp", - COMMON + } + + headerAndImpl.flatMap { + listOf( + GeneratedFile( + TemplateEngine.render("ffi/Ffi${it}Header", data, nameResolvers), + "$FFI_DIR/$it.h", + COMMON, + ), + GeneratedFile( + TemplateEngine.render("ffi/Ffi${it}Impl", data, nameResolvers), + "$FFI_DIR/$it.cpp", + COMMON, + ), ) - ) - } + } } private fun generateDartGenericTypesConversion( genericTypes: List, importResolver: DartImportResolver, nameResolvers: Map, - predicates: Map Boolean> + predicates: Map Boolean>, ): GeneratedFile { - val elementTypeRefs = genericTypes.filterIsInstance().map { it.elementType } + - genericTypes.filterIsInstance().map { it.elementType } + - genericTypes.filterIsInstance().flatMap { listOf(it.keyType, it.valueType) } + val elementTypeRefs = + genericTypes.filterIsInstance().map { it.elementType } + + genericTypes.filterIsInstance().map { it.elementType } + + genericTypes.filterIsInstance().flatMap { listOf(it.keyType, it.valueType) } val imports = (genericTypes + elementTypeRefs).flatMap { importResolver.resolveElementImports(it) } val fileName = "$SRC_DIR_SUFFIX/generic_types__conversion" - val content = TemplateEngine.render( - "dart/DartGenericTypesConversion", - mapOf( - "libraryName" to libraryName, - "internalPrefix" to internalPrefix, - "imports" to imports.distinct().sorted().filterNot { it.filePath.endsWith(fileName) }, - "genericTypes" to genericTypes - ), - nameResolvers, - predicates - ) + val content = + TemplateEngine.render( + "dart/DartGenericTypesConversion", + mapOf( + "libraryName" to libraryName, + "internalPrefix" to internalPrefix, + "imports" to imports.distinct().sorted().filterNot { it.filePath.endsWith(fileName) }, + "genericTypes" to genericTypes, + ), + nameResolvers, + predicates, + ) return GeneratedFile(content, "$LIB_DIR/$fileName.dart") } @@ -499,25 +523,26 @@ internal class DartGenerator : Generator { private fun generateFfiGenericTypesConversion( genericTypes: List, nameResolvers: Map, - includeResolver: FfiCppIncludeResolver + includeResolver: FfiCppIncludeResolver, ): List { val includes = genericTypes.flatMap { includeResolver.resolveElementImports(it) } val fileName = "GenericTypesConversion" - val data = mapOf( - "libraryName" to libraryName, - "internalPrefix" to internalPrefix, - "genericTypes" to genericTypes, - "internalNamespace" to internalNamespace, - "headerName" to fileName, - "includes" to includes.distinct().sorted() - ) + val data = + mapOf( + "libraryName" to libraryName, + "internalPrefix" to internalPrefix, + "genericTypes" to genericTypes, + "internalNamespace" to internalNamespace, + "headerName" to fileName, + "includes" to includes.distinct().sorted(), + ) val headerContent = TemplateEngine.render("ffi/FfiGenericTypesHeader", data, nameResolvers) val implContent = TemplateEngine.render("ffi/FfiGenericTypesImpl", data, nameResolvers) return listOf( GeneratedFile(headerContent, "$FFI_DIR/$fileName.h"), - GeneratedFile(implContent, "$FFI_DIR/$fileName.cpp") + GeneratedFile(implContent, "$FFI_DIR/$fileName.cpp"), ) } @@ -532,13 +557,13 @@ internal class DartGenerator : Generator { is LimeTypeAlias -> null else -> throw GluecodiumExecutionException( "Unsupported top-level element: " + - limeElement::class.java.name + limeElement::class.java.name, ) } private fun injectAsyncHelpers( referenceMap: MutableMap, - asyncHelpers: Map + asyncHelpers: Map, ) { val lambdas = asyncHelpers.values.map { it.lambdas }.flatten() referenceMap += lambdas.associateBy { it.fullName } @@ -552,15 +577,17 @@ internal class DartGenerator : Generator { private object TypeRefsCollector : LimeTypeRefsVisitor>() { override fun visitTypeRef( parentElement: LimeNamedElement, - limeTypeRef: LimeTypeRef? + limeTypeRef: LimeTypeRef?, ): List = - listOfNotNull(limeTypeRef) + when (val limeType = limeTypeRef?.type?.actualType) { - is LimeList -> visitTypeRef(parentElement, limeType.elementType) - is LimeSet -> visitTypeRef(parentElement, limeType.elementType) - is LimeMap -> visitTypeRef(parentElement, limeType.keyType) + - visitTypeRef(parentElement, limeType.valueType) - else -> emptyList() - } + listOfNotNull(limeTypeRef) + + when (val limeType = limeTypeRef?.type?.actualType) { + is LimeList -> visitTypeRef(parentElement, limeType.elementType) + is LimeSet -> visitTypeRef(parentElement, limeType.elementType) + is LimeMap -> + visitTypeRef(parentElement, limeType.keyType) + + visitTypeRef(parentElement, limeType.valueType) + else -> emptyList() + } fun getAllTypeRefs(limeModel: LimeModel): List { val allElements = limeModel.referenceMap.values.filterIsInstance() diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartGeneratorPredicates.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartGeneratorPredicates.kt index 3e79ca5be2..d1d7628377 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartGeneratorPredicates.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartGeneratorPredicates.kt @@ -37,43 +37,44 @@ import com.here.gluecodium.model.lime.LimeType internal class DartGeneratorPredicates( private val limeReferenceMap: Map, private val activeTags: Set, - dartNameResolver: DartNameResolver? = null + dartNameResolver: DartNameResolver? = null, ) { - val predicates = mapOf( - "allFieldsCtorIsPublic" to { limeStruct: Any -> - limeStruct is LimeStruct && allFieldsCtorIsPublic(limeStruct) - }, - "hasAnyComment" to { CommonGeneratorPredicates.hasAnyComment(it, "Dart") }, - "hasImmutableFields" to { CommonGeneratorPredicates.hasImmutableFields(it) }, - "hasSingleConstructor" to { limeContainer: Any -> - when (limeContainer) { - !is LimeContainer -> false - is LimeStruct -> limeContainer.constructors.size + limeContainer.fieldConstructors.size == 1 - else -> limeContainer.constructors.size == 1 - } - }, - "hasStaticFunctions" to { CommonGeneratorPredicates.hasStaticFunctions(it) }, - "needsAliasPrefix" to { limeType: Any -> - when { - limeType !is LimeType -> false - dartNameResolver == null -> false - else -> dartNameResolver.typesWithDuplicateNames.contains(limeType.fullName) - } - }, - "needsNoDoc" to { limeElement: Any -> - when { - limeElement !is LimeNamedElement -> false - CommonGeneratorPredicates.isInternal(limeElement, DART) -> true - else -> limeElement.comment.isExcluded - } - }, - "skipDeclaration" to { limeType: Any -> - limeType is LimeType && skipDeclaration(limeType) - }, - "shouldRetain" to { limeElement: Any -> - limeElement is LimeNamedElement && shouldRetain(limeElement) - } - ) + val predicates = + mapOf( + "allFieldsCtorIsPublic" to { limeStruct: Any -> + limeStruct is LimeStruct && allFieldsCtorIsPublic(limeStruct) + }, + "hasAnyComment" to { CommonGeneratorPredicates.hasAnyComment(it, "Dart") }, + "hasImmutableFields" to { CommonGeneratorPredicates.hasImmutableFields(it) }, + "hasSingleConstructor" to { limeContainer: Any -> + when (limeContainer) { + !is LimeContainer -> false + is LimeStruct -> limeContainer.constructors.size + limeContainer.fieldConstructors.size == 1 + else -> limeContainer.constructors.size == 1 + } + }, + "hasStaticFunctions" to { CommonGeneratorPredicates.hasStaticFunctions(it) }, + "needsAliasPrefix" to { limeType: Any -> + when { + limeType !is LimeType -> false + dartNameResolver == null -> false + else -> dartNameResolver.typesWithDuplicateNames.contains(limeType.fullName) + } + }, + "needsNoDoc" to { limeElement: Any -> + when { + limeElement !is LimeNamedElement -> false + CommonGeneratorPredicates.isInternal(limeElement, DART) -> true + else -> limeElement.comment.isExcluded + } + }, + "skipDeclaration" to { limeType: Any -> + limeType is LimeType && skipDeclaration(limeType) + }, + "shouldRetain" to { limeElement: Any -> + limeElement is LimeNamedElement && shouldRetain(limeElement) + }, + ) fun shouldRetain(limeElement: LimeNamedElement) = LimeModelSkipPredicates.shouldRetainCheckParent(limeElement, activeTags, DART, limeReferenceMap) diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartImport.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartImport.kt index 61f41897c0..467671eb4e 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartImport.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartImport.kt @@ -22,9 +22,8 @@ package com.here.gluecodium.generator.dart data class DartImport( val filePath: String, val asAlias: String? = null, - val importType: ImportType = ImportType.PACKAGE + val importType: ImportType = ImportType.PACKAGE, ) : Comparable { - // According to Dart style guide, system imports should precede package imports. enum class ImportType { SYSTEM, diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartImportResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartImportResolver.kt index 8adf89acf8..5760dd0c3e 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartImportResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartImportResolver.kt @@ -38,7 +38,7 @@ import com.here.gluecodium.model.lime.LimeValue internal class DartImportResolver( limeReferenceMap: Map, nameResolver: DartNameResolver, - private val srcPath: String + private val srcPath: String, ) : DartImportResolverBase(limeReferenceMap, nameResolver, srcPath) { private val builtInTypesConversionImport = createConversionImport("builtin_types") private val lazyListImport = DartImport("$srcPath/_lazy_list", "__lib") @@ -46,8 +46,9 @@ internal class DartImportResolver( override fun resolveElementImports(limeElement: LimeElement): List = when (limeElement) { is LimeTypeAlias -> emptyList() - is LimeTypeRef -> resolveTypeImports(limeElement.type) + resolveConversionImports(limeElement) + - listOfNotNull(lazyListImport.takeIf { limeElement.attributes.have(LimeAttributeType.OPTIMIZED) }) + is LimeTypeRef -> + resolveTypeImports(limeElement.type) + resolveConversionImports(limeElement) + + listOfNotNull(lazyListImport.takeIf { limeElement.attributes.have(LimeAttributeType.OPTIMIZED) }) is LimeType -> resolveTypeImports(limeElement) + resolveConversionImports(limeElement) is LimeConstant -> resolveTypeImports(limeElement.typeRef.type) is LimeValue -> resolveValueImports(limeElement) @@ -55,7 +56,10 @@ internal class DartImportResolver( else -> emptyList() } - private fun resolveTypeImports(limeType: LimeType, skipHelpers: Boolean = false): List { + private fun resolveTypeImports( + limeType: LimeType, + skipHelpers: Boolean = false, + ): List { val actualType = limeType.actualType when (actualType) { is LimeBasicType -> return resolveBasicTypeImports(actualType) @@ -73,17 +77,22 @@ internal class DartImportResolver( private fun resolveConversionImports(limeType: LimeType): List = when (val actualType = limeType.actualType) { is LimeBasicType -> - if (actualType.typeId.isNumericType || actualType.typeId == LimeBasicType.TypeId.VOID) emptyList() - else listOf(builtInTypesConversionImport) + if (actualType.typeId.isNumericType || actualType.typeId == LimeBasicType.TypeId.VOID) { + emptyList() + } else { + listOf(builtInTypesConversionImport) + } is LimeGenericType -> listOf(createConversionImport("generic_types")) else -> emptyList() } private fun resolveConversionImports(limeTypeRef: LimeTypeRef): List = resolveConversionImports(limeTypeRef.type) + - if (limeTypeRef.isNullable && limeTypeRef.type.actualType is LimeBasicType) + if (limeTypeRef.isNullable && limeTypeRef.type.actualType is LimeBasicType) { listOf(builtInTypesConversionImport) - else emptyList() + } else { + emptyList() + } private fun resolveBasicTypeImports(limeType: LimeBasicType) = when (limeType.typeId) { @@ -97,8 +106,9 @@ internal class DartImportResolver( when (limeType) { is LimeList -> resolveTypeImports(limeType.elementType.type, skipHelpers = true) is LimeSet -> resolveTypeImports(limeType.elementType.type, skipHelpers = true) - is LimeMap -> resolveTypeImports(limeType.keyType.type, skipHelpers = true) + - resolveTypeImports(limeType.valueType.type, skipHelpers = true) + is LimeMap -> + resolveTypeImports(limeType.keyType.type, skipHelpers = true) + + resolveTypeImports(limeType.valueType.type, skipHelpers = true) else -> emptyList() } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartImportResolverBase.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartImportResolverBase.kt index 4ee121e4fc..1396c1a362 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartImportResolverBase.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartImportResolverBase.kt @@ -29,13 +29,12 @@ import com.here.gluecodium.model.lime.LimeType internal abstract class DartImportResolverBase( limeReferenceMap: Map, private val nameResolver: DartNameResolver, - private val srcPath: String + private val srcPath: String, ) : ReferenceMapBasedResolver(limeReferenceMap), ImportsResolver { - protected fun resolveExternalImport( limeElement: LimeElement, key: String, - useAlias: Boolean + useAlias: Boolean, ): DartImport? { val importPath = (limeElement as? LimeNamedElement)?.external?.dart?.get(key) ?: return null val components = importPath.split(':') @@ -43,23 +42,25 @@ internal abstract class DartImportResolverBase( return when (components.first()) { "dart" -> DartImport(components.last(), importType = ImportType.SYSTEM, asAlias = alias) "package" -> DartImport(components.last().removeSuffix(".dart"), asAlias = alias) - else -> DartImport( - components.last().removeSuffix(".dart"), - importType = ImportType.RELATIVE, - asAlias = alias - ) + else -> + DartImport( + components.last().removeSuffix(".dart"), + importType = ImportType.RELATIVE, + asAlias = alias, + ) } } protected fun createImport(limeElement: LimeNamedElement): DartImport { val filePath = limeElement.path.head.joinToString("/") val fileName = nameResolver.resolveFileName(getTopElement(limeElement)) - val alias = when { - limeElement !is LimeType -> null - nameResolver.typesWithDuplicateNames.contains(limeElement.fullName) -> - limeElement.path.head.joinToString("_") - else -> null - } + val alias = + when { + limeElement !is LimeType -> null + nameResolver.typesWithDuplicateNames.contains(limeElement.fullName) -> + limeElement.path.head.joinToString("_") + else -> null + } return DartImport("$srcPath/$filePath/$fileName", asAlias = alias) } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartImportsCollector.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartImportsCollector.kt index a7bc45488b..8e8dc5ce66 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartImportsCollector.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartImportsCollector.kt @@ -29,13 +29,13 @@ internal class DartImportsCollector(importsResolver: ImportsResolver importsResolver, collectTypeRefImports = true, collectValueImports = true, - parentTypeFilter = { true } + parentTypeFilter = { true }, ) { - override fun collectParentTypeRefs(limeContainer: LimeContainerWithInheritance) = when (limeContainer) { - is LimeClass -> limeContainer.interfaceInheritedFunctions.flatMap { collectTypeRefs(it) } + - limeContainer.interfaceInheritedProperties.map { it.typeRef } + limeContainer.parents + is LimeClass -> + limeContainer.interfaceInheritedFunctions.flatMap { collectTypeRefs(it) } + + limeContainer.interfaceInheritedProperties.map { it.typeRef } + limeContainer.parents else -> super.collectParentTypeRefs(limeContainer) } } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartNameResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartNameResolver.kt index 2c8980aa72..b8ebcab584 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartNameResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartNameResolver.kt @@ -59,9 +59,8 @@ internal class DartNameResolver( limeReferenceMap: Map, private val nameRules: NameRules, private val limeLogger: LimeLogger, - private val commentsProcessor: CommentsProcessor + private val commentsProcessor: CommentsProcessor, ) : ReferenceMapBasedResolver(limeReferenceMap), NameResolver { - private val joinInfix = nameRules.ruleSet.joinInfix ?: "" private val duplicateNames: Set private val limeToDartNames: Map @@ -104,7 +103,8 @@ internal class DartNameResolver( when (typeId) { TypeId.VOID -> "void" TypeId.INT8, TypeId.UINT8, TypeId.INT16, TypeId.UINT16, - TypeId.INT32, TypeId.UINT32, TypeId.INT64, TypeId.UINT64 -> "int" + TypeId.INT32, TypeId.UINT32, TypeId.INT64, TypeId.UINT64, + -> "int" TypeId.BOOLEAN -> "bool" TypeId.FLOAT, TypeId.DOUBLE -> "double" TypeId.STRING -> "String" @@ -119,11 +119,12 @@ internal class DartNameResolver( is LimeValue.Literal -> resolveLiteralValue(limeValue) is LimeValue.Constant -> resolveConstantValue(limeValue) is LimeValue.Special -> { - val specialName = when (limeValue.value) { - LimeValue.Special.ValueId.NAN -> "nan" - LimeValue.Special.ValueId.INFINITY -> "infinity" - LimeValue.Special.ValueId.NEGATIVE_INFINITY -> "negativeInfinity" - } + val specialName = + when (limeValue.value) { + LimeValue.Special.ValueId.NAN -> "nan" + LimeValue.Special.ValueId.INFINITY -> "infinity" + LimeValue.Special.ValueId.NEGATIVE_INFINITY -> "negativeInfinity" + } "double.$specialName" } is LimeValue.Null -> "null" @@ -135,17 +136,18 @@ internal class DartNameResolver( } val useDefaultsConstructor = actualType.fields.isNotEmpty() && limeValue.values.isEmpty() val noFieldsConstructor = actualType.noFieldsConstructor - val constructorName = when { - !useDefaultsConstructor -> "" - noFieldsConstructor == null -> - if (DartGeneratorPredicates.allFieldsCtorIsPublic(actualType)) ".withDefaults" else "" - noFieldsConstructor.attributes.have(DART, DEFAULT) -> "" - else -> resolveName(noFieldsConstructor).let { if (it.isEmpty()) "" else ".$it" } - } + val constructorName = + when { + !useDefaultsConstructor -> "" + noFieldsConstructor == null -> + if (DartGeneratorPredicates.allFieldsCtorIsPublic(actualType)) ".withDefaults" else "" + noFieldsConstructor.attributes.have(DART, DEFAULT) -> "" + else -> resolveName(noFieldsConstructor).let { if (it.isEmpty()) "" else ".$it" } + } limeValue.values.joinToString( prefix = "${resolveTypeRefName(limeValue.typeRef, ignoreNullability = true)}$constructorName(", postfix = ")", - separator = ", " + separator = ", ", ) { resolveValue(it) } } is LimeValue.KeyValuePair -> "${resolveValue(limeValue.key)}: ${resolveValue(limeValue.value)}" @@ -170,10 +172,11 @@ internal class DartNameResolver( private fun resolveConstantValue(limeValue: LimeValue.Constant): String { val limeElement = limeValue.valueRef.element - val typeRef = when (limeElement) { - is LimeEnumerator -> limeValue.typeRef - else -> LimeDirectTypeRef(getParentElement(limeElement) as LimeType) - } + val typeRef = + when (limeElement) { + is LimeEnumerator -> limeValue.typeRef + else -> LimeDirectTypeRef(getParentElement(limeElement) as LimeType) + } return "${resolveName(typeRef)}.${resolveName(limeElement)}" } @@ -188,19 +191,21 @@ internal class DartNameResolver( } private fun resolveDurationValue(limeValue: LimeValue.Duration): String { - val parameterName: String = when (limeValue.timeUnit) { - TimeUnit.DAY -> "days" - TimeUnit.HOUR -> "hours" - TimeUnit.MINUTE -> "minutes" - TimeUnit.SECOND -> "seconds" - TimeUnit.MILLISECOND -> "milliseconds" - TimeUnit.MICROSECOND, TimeUnit.NANOSECOND -> "microseconds" - } - val valueLiteral = when (limeValue.timeUnit) { - // Convert to microseconds during generation to have a compile-time constant in Dart. - TimeUnit.NANOSECOND -> (limeValue.value.toDouble() / 1000.0).toInt().toString() - else -> limeValue.value - } + val parameterName: String = + when (limeValue.timeUnit) { + TimeUnit.DAY -> "days" + TimeUnit.HOUR -> "hours" + TimeUnit.MINUTE -> "minutes" + TimeUnit.SECOND -> "seconds" + TimeUnit.MILLISECOND -> "milliseconds" + TimeUnit.MICROSECOND, TimeUnit.NANOSECOND -> "microseconds" + } + val valueLiteral = + when (limeValue.timeUnit) { + // Convert to microseconds during generation to have a compile-time constant in Dart. + TimeUnit.NANOSECOND -> (limeValue.value.toDouble() / 1000.0).toInt().toString() + else -> limeValue.value + } return "const Duration($parameterName: $valueLiteral)" } @@ -211,7 +216,7 @@ internal class DartNameResolver( "Map<${resolveName(limeType.keyType)}, ${resolveName(limeType.valueType)}>" is LimeSet -> "Set<${resolveName(limeType.elementType)}>" else -> throw GluecodiumExecutionException( - "Unsupported element type ${limeType.javaClass.name}" + "Unsupported element type ${limeType.javaClass.name}", ) } @@ -240,9 +245,13 @@ internal class DartNameResolver( return commentsProcessor.process(commentedElement.fullName, commentText, limeToDartNames, limeLogger) } - private fun isNeededToSeparateFirstLine(limeElement: LimeNamedElement?, limeComment: LimeComment): Boolean { - val isParameterComment = limeElement is LimeLambda && - limeElement.parameters.any { it.comment === limeComment } + private fun isNeededToSeparateFirstLine( + limeElement: LimeNamedElement?, + limeComment: LimeComment, + ): Boolean { + val isParameterComment = + limeElement is LimeLambda && + limeElement.parameters.any { it.comment === limeComment } if (isParameterComment) { return false @@ -267,55 +276,62 @@ internal class DartNameResolver( return resolveName(limeElement) } val parentElement = getParentElement(limeElement) - val ownName = when { - limeElement is LimeFunction && limeElement.isConstructor && !limeElement.attributes.have(DART, NAME) -> - "${resolveName(parentElement)}()" - else -> resolveName(limeElement) - } + val ownName = + when { + limeElement is LimeFunction && limeElement.isConstructor && !limeElement.attributes.have(DART, NAME) -> + "${resolveName(parentElement)}()" + else -> resolveName(limeElement) + } return "${resolveFullName(parentElement)}.$ownName" } private fun resolveTypeRefName( limeTypeRef: LimeTypeRef, ignoreDuplicates: Boolean = false, - ignoreNullability: Boolean = false + ignoreNullability: Boolean = false, ): String { val typeName = resolveName(limeTypeRef.type) val importPath = limeTypeRef.type.actualType.external?.dart?.get(IMPORT_PATH_NAME) - val alias = when { - importPath != null -> computeAlias(importPath) - ignoreDuplicates -> null - duplicateNames.contains(typeName) -> limeTypeRef.type.actualType.path.head.joinToString("_") - else -> null - } + val alias = + when { + importPath != null -> computeAlias(importPath) + ignoreDuplicates -> null + duplicateNames.contains(typeName) -> limeTypeRef.type.actualType.path.head.joinToString("_") + else -> null + } val suffix = if (limeTypeRef.isNullable && !ignoreNullability) "?" else "" return listOfNotNull(alias, typeName).joinToString(".") + suffix } private fun buildPathMap(): Map { - val result = limeReferenceMap.values - .filterIsInstance() - .filterNot { it is LimeParameter } - .associateBy({ it.path.toAmbiguousString() }, { resolveFullName(it) }) - .toMutableMap() + val result = + limeReferenceMap.values + .filterIsInstance() + .filterNot { it is LimeParameter } + .associateBy({ it.path.toAmbiguousString() }, { resolveFullName(it) }) + .toMutableMap() - result += limeReferenceMap.values.filterIsInstance() - .associateBy({ it.fullName }, { resolveFullName(it) }) + result += + limeReferenceMap.values.filterIsInstance() + .associateBy({ it.fullName }, { resolveFullName(it) }) val functions = limeReferenceMap.values.filterIsInstance() result += functions.associateBy({ it.path.toAmbiguousString() }, { resolveFullName(it) }) - result += functions.associateBy( - { function -> - function.path.toAmbiguousString() + function.parameters - .joinToString(prefix = "(", postfix = ")", separator = ",") { it.typeRef.toString() } - }, - { resolveFullName(it) } - ) + result += + functions.associateBy( + { function -> + function.path.toAmbiguousString() + + function.parameters + .joinToString(prefix = "(", postfix = ")", separator = ",") { it.typeRef.toString() } + }, + { resolveFullName(it) }, + ) val properties = limeReferenceMap.values.filterIsInstance() result += properties.associateBy({ it.path.toAmbiguousString() + ".get" }, { resolveFullName(it) }) - result += properties.filter { it.setter != null } - .associateBy({ it.path.toAmbiguousString() + ".set" }, { resolveFullName(it) }) + result += + properties.filter { it.setter != null } + .associateBy({ it.path.toAmbiguousString() + ".set" }, { resolveFullName(it) }) return result } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartOverloadsValidator.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartOverloadsValidator.kt index 0d2751a497..35e8d77736 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartOverloadsValidator.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartOverloadsValidator.kt @@ -34,7 +34,7 @@ import com.here.gluecodium.model.lime.LimeStruct internal class DartOverloadsValidator( private val nameResolver: DartNameResolver, private val logger: LimeLogger, - private val werror: Boolean + private val werror: Boolean, ) { private val logFunction: LimeLogger.(LimeNamedElement, String) -> Unit = if (werror) LimeLogger::error else LimeLogger::warning @@ -46,19 +46,21 @@ internal class DartOverloadsValidator( } private fun validateContainer(limeContainer: LimeContainer): Boolean { - val allFunctions = limeContainer.functions + - ((limeContainer as? LimeContainerWithInheritance)?.inheritedFunctions ?: emptyList()) + val allFunctions = + limeContainer.functions + + ((limeContainer as? LimeContainerWithInheritance)?.inheritedFunctions ?: emptyList()) val constructors = allFunctions.filter { it.isConstructor } - val overloadedFunctions = (allFunctions - constructors.toSet()) - .groupBy { nameResolver.resolveName(it) } - .filter { it.value.size > 1 } + val overloadedFunctions = + (allFunctions - constructors.toSet()) + .groupBy { nameResolver.resolveName(it) } + .filter { it.value.size > 1 } overloadedFunctions.forEach { entry -> val pathsString = entry.value.map { it.path.toString() }.sorted().joinToString() logger.logFunction( entry.value.first(), "there is more than one function with '${entry.key}' name: $pathsString. " + - "Dart language does not support function overloading." + "Dart language does not support function overloading.", ) } @@ -67,11 +69,12 @@ internal class DartOverloadsValidator( (constructors + fieldConstructors).groupBy { getConstructorName(it) }.filter { it.value.size > 1 } overloadedConstructors.forEach { entry -> val pathsString = entry.value.map { it.path.toString() }.sorted().joinToString() - val warningText = if (entry.key.isEmpty()) { - "there is more than one default constructor: $pathsString. " - } else { - "there is more than one constructor with '${entry.key}' name: $pathsString. " - } + "Dart language does not support constructor overloading." + val warningText = + if (entry.key.isEmpty()) { + "there is more than one default constructor: $pathsString. " + } else { + "there is more than one constructor with '${entry.key}' name: $pathsString. " + } + "Dart language does not support constructor overloading." logger.logFunction(entry.value.first(), warningText) } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartVisibilityResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartVisibilityResolver.kt index eda1add77a..f59819d08d 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartVisibilityResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/dart/DartVisibilityResolver.kt @@ -30,14 +30,14 @@ import com.here.gluecodium.model.lime.LimeType internal class DartVisibilityResolver(limeReferenceMap: Map) : ReferenceMapBasedResolver(limeReferenceMap), NameResolver { - override fun resolveName(element: Any): String = when (element) { // Dart has no type nesting, so all types are "outside" and have to check for an internal outer type. is LimeType -> { - val isInternal = generateSequence(element) { - limeReferenceMap[it.path.parent.toString()] as? LimeType - }.any { CommonGeneratorPredicates.isInternal(it, DART) } + val isInternal = + generateSequence(element) { + limeReferenceMap[it.path.parent.toString()] as? LimeType + }.any { CommonGeneratorPredicates.isInternal(it, DART) } getVisibilityPrefix(isInternal) } is LimeNamedElement -> getVisibilityPrefix(CommonGeneratorPredicates.isInternal(element, DART)) diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/dart/FfiApiTypeNameResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/dart/FfiApiTypeNameResolver.kt index 6ea18d23c1..25b7b9da4d 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/dart/FfiApiTypeNameResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/dart/FfiApiTypeNameResolver.kt @@ -28,7 +28,6 @@ import com.here.gluecodium.model.lime.LimeType import com.here.gluecodium.model.lime.LimeTypeRef internal class FfiApiTypeNameResolver : NameResolver { - override fun resolveName(element: Any): String = when (element) { is TypeId -> getBasicTypeName(element) diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/dart/FfiDartTypeNameResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/dart/FfiDartTypeNameResolver.kt index ce84d09adc..7101c5ebf0 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/dart/FfiDartTypeNameResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/dart/FfiDartTypeNameResolver.kt @@ -28,7 +28,6 @@ import com.here.gluecodium.model.lime.LimeType import com.here.gluecodium.model.lime.LimeTypeRef internal class FfiDartTypeNameResolver : NameResolver { - override fun resolveName(element: Any): String = when (element) { is TypeId -> getBasicTypeName(element) diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/ffi/FfiCppIncludeResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/ffi/FfiCppIncludeResolver.kt index 3d88515e06..eed026538c 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/ffi/FfiCppIncludeResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/ffi/FfiCppIncludeResolver.kt @@ -47,7 +47,7 @@ import com.here.gluecodium.model.lime.LimeTypeRef internal class FfiCppIncludeResolver( limeReferenceMap: Map, nameRules: CppNameRules, - internalNamespace: List + internalNamespace: List, ) : ImportsResolver { private val cppIncludesCache = CppIncludesCache(limeReferenceMap, nameRules, internalNamespace) @@ -55,8 +55,9 @@ internal class FfiCppIncludeResolver( when (limeElement) { is LimeTypeRef -> getTypeRefIncludes(limeElement) is LimeException, is LimeTypeAlias, is LimeConstant -> emptyList() - is LimeInterface -> getTypeIncludes(limeElement) + getThrownTypeIncludes(limeElement) + - getContainerIncludes(limeElement) + proxyIncludes + is LimeInterface -> + getTypeIncludes(limeElement) + getThrownTypeIncludes(limeElement) + + getContainerIncludes(limeElement) + proxyIncludes is LimeContainer -> getTypeIncludes(limeElement) + getContainerIncludes(limeElement) is LimeLambda -> getTypeIncludes(limeElement) + proxyIncludes + isolateContextInclude is LimeType -> getTypeIncludes(limeElement) @@ -73,25 +74,33 @@ internal class FfiCppIncludeResolver( when (limeType) { is LimeException -> emptyList() is LimeBasicType -> getBasicTypeIncludes(limeType) - is LimeList -> getTypeRefIncludes(limeType.elementType) + listOf( - CppLibraryIncludes.VECTOR, - cppIncludesCache.createInternalNamespaceInclude("VectorHash.h") - ) - is LimeSet -> getTypeRefIncludes(limeType.elementType) + listOf( - CppLibraryIncludes.SET, - cppIncludesCache.createInternalNamespaceInclude("UnorderedSetHash.h") - ) - is LimeMap -> getTypeRefIncludes(limeType.keyType) + - getTypeRefIncludes(limeType.valueType) + listOf( - CppLibraryIncludes.MAP, - cppIncludesCache.createInternalNamespaceInclude("UnorderedMapHash.h") - ) - is LimeLambda -> cppIncludesCache.resolveIncludes(limeType) + - getTypeRefIncludes(limeType.returnType.typeRef) + - limeType.parameters.flatMap { getTypeRefIncludes(it.typeRef) } + - CppLibraryIncludes.FUNCTIONAL - is LimeContainerWithInheritance -> cppIncludesCache.resolveIncludes(limeType) + - CppLibraryIncludes.MEMORY + is LimeList -> + getTypeRefIncludes(limeType.elementType) + + listOf( + CppLibraryIncludes.VECTOR, + cppIncludesCache.createInternalNamespaceInclude("VectorHash.h"), + ) + is LimeSet -> + getTypeRefIncludes(limeType.elementType) + + listOf( + CppLibraryIncludes.SET, + cppIncludesCache.createInternalNamespaceInclude("UnorderedSetHash.h"), + ) + is LimeMap -> + getTypeRefIncludes(limeType.keyType) + + getTypeRefIncludes(limeType.valueType) + + listOf( + CppLibraryIncludes.MAP, + cppIncludesCache.createInternalNamespaceInclude("UnorderedMapHash.h"), + ) + is LimeLambda -> + cppIncludesCache.resolveIncludes(limeType) + + getTypeRefIncludes(limeType.returnType.typeRef) + + limeType.parameters.flatMap { getTypeRefIncludes(it.typeRef) } + + CppLibraryIncludes.FUNCTIONAL + is LimeContainerWithInheritance -> + cppIncludesCache.resolveIncludes(limeType) + + CppLibraryIncludes.MEMORY else -> cppIncludesCache.resolveIncludes(limeType) } @@ -101,22 +110,25 @@ internal class FfiCppIncludeResolver( TypeId.VOID, TypeId.FLOAT, TypeId.DOUBLE -> emptyList() TypeId.STRING -> listOf(CppLibraryIncludes.STRING) TypeId.BLOB -> listOf(CppLibraryIncludes.MEMORY, CppLibraryIncludes.VECTOR, CppLibraryIncludes.INT_TYPES) - TypeId.DATE -> listOf( - CppLibraryIncludes.CHRONO, - cppIncludesCache.createInternalNamespaceInclude("TimePointHash.h") - ) - TypeId.DURATION -> listOf( - CppLibraryIncludes.CHRONO, - cppIncludesCache.createInternalNamespaceInclude("DurationHash.h") - ) + TypeId.DATE -> + listOf( + CppLibraryIncludes.CHRONO, + cppIncludesCache.createInternalNamespaceInclude("TimePointHash.h"), + ) + TypeId.DURATION -> + listOf( + CppLibraryIncludes.CHRONO, + cppIncludesCache.createInternalNamespaceInclude("DurationHash.h"), + ) TypeId.LOCALE -> listOf(cppIncludesCache.createInternalNamespaceInclude("Locale.h")) else -> listOf(CppLibraryIncludes.INT_TYPES) } private fun getThrownTypeIncludes(limeInterface: LimeInterface): List { - val exceptionEnums = limeInterface.functions - .mapNotNull { it.exception?.errorType?.type?.actualType } - .filterIsInstance() + val exceptionEnums = + limeInterface.functions + .mapNotNull { it.exception?.errorType?.type?.actualType } + .filterIsInstance() return when { exceptionEnums.isNotEmpty() -> listOf(CppLibraryIncludes.SYSTEM_ERROR) else -> emptyList() @@ -126,16 +138,17 @@ internal class FfiCppIncludeResolver( private fun getContainerIncludes(limeContainer: LimeContainer): List = listOfNotNull( isolateContextInclude.takeIf { limeContainer.functions.isNotEmpty() || limeContainer.properties.isNotEmpty() }, - cppIncludesCache.typeRepositoryInclude.takeIf { CommonGeneratorPredicates.hasTypeRepository(limeContainer) } + cppIncludesCache.typeRepositoryInclude.takeIf { CommonGeneratorPredicates.hasTypeRepository(limeContainer) }, ) companion object { private val BOOL_INCLUDE = Include.createSystemInclude("stdbool.h") private val isolateContextInclude = Include.createInternalInclude("IsolateContext.h") - private val proxyIncludes = listOf( - Include.createInternalInclude("CallbacksQueue.h"), - Include.createInternalInclude("ProxyCache.h") - ) + private val proxyIncludes = + listOf( + Include.createInternalInclude("CallbacksQueue.h"), + Include.createInternalInclude("ProxyCache.h"), + ) } } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/ffi/FfiCppNameResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/ffi/FfiCppNameResolver.kt index 80d4a4b7f5..d0db08429b 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/ffi/FfiCppNameResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/ffi/FfiCppNameResolver.kt @@ -35,17 +35,17 @@ internal class FfiCppNameResolver( limeReferenceMap: Map, nameRules: CppNameRules, rootNamespace: List, - internalNamespace: List + internalNamespace: List, ) : ReferenceMapBasedResolver(limeReferenceMap), NameResolver { - private val cppNameCache = CppNameCache(rootNamespace, limeReferenceMap, nameRules) - private val cppNameResolver = CppNameResolver( - limeReferenceMap, - internalNamespace, - cppNameCache, - forceFullNames = true, - forceFollowThrough = true - ) + private val cppNameResolver = + CppNameResolver( + limeReferenceMap, + internalNamespace, + cppNameCache, + forceFullNames = true, + forceFollowThrough = true, + ) override fun resolveName(element: Any): String = when (element) { diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/ffi/FfiCppParameterTypeNameResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/ffi/FfiCppParameterTypeNameResolver.kt index 20c201f2e7..b2b2f1400f 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/ffi/FfiCppParameterTypeNameResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/ffi/FfiCppParameterTypeNameResolver.kt @@ -27,11 +27,9 @@ import com.here.gluecodium.model.lime.LimeType import com.here.gluecodium.model.lime.LimeTypeRef internal class FfiCppParameterTypeNameResolver( - private val ffiCppNameResolver: FfiCppNameResolver + private val ffiCppNameResolver: FfiCppNameResolver, ) : NameResolver { - - override fun resolveName(element: Any): String = - ffiCppNameResolver.resolveName(element) + resolveSuffix(element) + override fun resolveName(element: Any): String = ffiCppNameResolver.resolveName(element) + resolveSuffix(element) private fun resolveSuffix(element: Any) = when (element) { @@ -44,10 +42,11 @@ internal class FfiCppParameterTypeNameResolver( private fun resolveTypeSuffix(limeType: LimeType) = when (val actualType = limeType.actualType) { is LimeEnumeration -> "" - is LimeBasicType -> when (actualType.typeId) { - TypeId.STRING, TypeId.BLOB, TypeId.DATE -> REFERENCE_SUFFIX - else -> "" - } + is LimeBasicType -> + when (actualType.typeId) { + TypeId.STRING, TypeId.BLOB, TypeId.DATE -> REFERENCE_SUFFIX + else -> "" + } else -> REFERENCE_SUFFIX } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/ffi/FfiCppReturnTypeNameResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/ffi/FfiCppReturnTypeNameResolver.kt index 2085a8d85c..d6f1c77d6e 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/ffi/FfiCppReturnTypeNameResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/ffi/FfiCppReturnTypeNameResolver.kt @@ -26,9 +26,8 @@ import com.here.gluecodium.model.lime.LimeFunction internal class FfiCppReturnTypeNameResolver( private val internalNamespace: List, - private val ffiCppNameResolver: FfiCppNameResolver + private val ffiCppNameResolver: FfiCppNameResolver, ) : NameResolver { - override fun resolveName(element: Any): String = when (element) { is LimeFunction -> resolveReturnTypeName(element) diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/ffi/FfiNameResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/ffi/FfiNameResolver.kt index 86a41c2e8b..b213ce5bf0 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/ffi/FfiNameResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/ffi/FfiNameResolver.kt @@ -44,9 +44,8 @@ import com.here.gluecodium.model.lime.LimeTypeRef internal class FfiNameResolver( limeReferenceMap: Map, private val nameRules: NameRules, - private val internalPrefix: String + private val internalPrefix: String, ) : ReferenceMapBasedResolver(limeReferenceMap), NameResolver { - private val signatureResolver = FfiSignatureResolver(limeReferenceMap, this) override fun resolveName(element: Any): String = @@ -100,13 +99,14 @@ internal class FfiNameResolver( } private fun getGenericTypeName(limeType: LimeType) = - internalPrefix + when (val actualType = limeType.actualType) { - is LimeList -> getListName(actualType.elementType) - is LimeSet -> getSetName(actualType.elementType) - is LimeMap -> getMapName(actualType.keyType, actualType.valueType) - else -> - throw GluecodiumExecutionException("Unsupported element type ${actualType.javaClass.name}") - } + internalPrefix + + when (val actualType = limeType.actualType) { + is LimeList -> getListName(actualType.elementType) + is LimeSet -> getSetName(actualType.elementType) + is LimeMap -> getMapName(actualType.keyType, actualType.valueType) + else -> + throw GluecodiumExecutionException("Unsupported element type ${actualType.javaClass.name}") + } private fun getBasicTypeName(typeId: TypeId) = when (typeId) { @@ -126,28 +126,29 @@ internal class FfiNameResolver( TypeId.STRING, TypeId.BLOB, TypeId.LOCALE -> OPAQUE_HANDLE_TYPE } - private fun getListName(elementType: LimeTypeRef) = - "ListOf_${getNestedTypeRefName(elementType)}" + private fun getListName(elementType: LimeTypeRef) = "ListOf_${getNestedTypeRefName(elementType)}" - private fun getSetName(elementType: LimeTypeRef) = - "SetOf_${getNestedTypeRefName(elementType)}" + private fun getSetName(elementType: LimeTypeRef) = "SetOf_${getNestedTypeRefName(elementType)}" - private fun getMapName(keyType: LimeTypeRef, valueType: LimeTypeRef) = - "MapOf_${getNestedTypeRefName(keyType)}_to_${getNestedTypeRefName(valueType)}" + private fun getMapName( + keyType: LimeTypeRef, + valueType: LimeTypeRef, + ) = "MapOf_${getNestedTypeRefName(keyType)}_to_${getNestedTypeRefName(valueType)}" private fun getMangledFullName(limeElement: LimeNamedElement): String { - val prefix = when { - limeElement.path.hasParent -> { - val parentElement = - limeReferenceMap[limeElement.path.parent.toString()] as? LimeNamedElement - ?: throw GluecodiumExecutionException( - "Failed to resolve parent for element ${limeElement.fullName}" - ) - getMangledFullName(parentElement) + val prefix = + when { + limeElement.path.hasParent -> { + val parentElement = + limeReferenceMap[limeElement.path.parent.toString()] as? LimeNamedElement + ?: throw GluecodiumExecutionException( + "Failed to resolve parent for element ${limeElement.fullName}", + ) + getMangledFullName(parentElement) + } + limeElement.path.head.isEmpty() -> null + else -> limeElement.path.head.joinToString("_") } - limeElement.path.head.isEmpty() -> null - else -> limeElement.path.head.joinToString("_") - } val mangledName = mangleName(nameRules.getName(limeElement)) val fullName = listOfNotNull(prefix, mangledName).joinToString("_") @@ -174,18 +175,18 @@ internal class FfiNameResolver( private class FfiSignatureResolver( limeReferenceMap: Map, - private val nameResolver: FfiNameResolver + private val nameResolver: FfiNameResolver, ) : LimeSignatureResolver(limeReferenceMap) { - - override fun getFunctionName(limeFunction: LimeFunction) = - nameResolver.nameRules.getName(limeFunction) + override fun getFunctionName(limeFunction: LimeFunction) = nameResolver.nameRules.getName(limeFunction) override fun getArrayName(elementType: LimeTypeRef) = nameResolver.getListName(elementType) override fun getSetName(elementType: LimeTypeRef) = nameResolver.getSetName(elementType) - override fun getMapName(keyType: LimeTypeRef, valueType: LimeTypeRef) = - nameResolver.getMapName(keyType, valueType) + override fun getMapName( + keyType: LimeTypeRef, + valueType: LimeTypeRef, + ) = nameResolver.getMapName(keyType, valueType) } companion object { diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaDocProcessor.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaDocProcessor.kt index 0e2e7c17eb..a4fdc6d0f7 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaDocProcessor.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaDocProcessor.kt @@ -35,15 +35,19 @@ import com.vladsch.flexmark.util.sequence.CharSubSequence */ internal class JavaDocProcessor(werror: Boolean, private val referenceMap: Map) : CommentsProcessor(HtmlRenderer.builder(flexmarkOptions).build(), werror, flexmarkOptions) { - - override fun processLink(linkNode: LinkRef, linkReference: String, limeFullName: String) { + override fun processLink( + linkNode: LinkRef, + linkReference: String, + limeFullName: String, + ) { val limeElement = referenceMap[fullNameToPathKey(limeFullName)] - linkNode.chars = if (limeElement is LimeParameter) { - val shortReference = linkReference.split("#").last() - CharSubSequence.of("{@code $shortReference}") - } else { - CharSubSequence.of("{@link $linkReference}") - } + linkNode.chars = + if (limeElement is LimeParameter) { + val shortReference = linkReference.split("#").last() + CharSubSequence.of("{@code $shortReference}") + } else { + CharSubSequence.of("{@link $linkReference}") + } linkNode.firstChild?.unlink() } @@ -62,8 +66,9 @@ internal class JavaDocProcessor(werror: Boolean, private val referenceMap: Map resolveEmptyValue(element) diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaGenerator.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaGenerator.kt index 2f9ee0ea6c..125d057a50 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaGenerator.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaGenerator.kt @@ -53,7 +53,6 @@ import java.util.logging.Logger * Combines Java and JNI templates to generate Java code and bindings to C++ layer for Java. */ internal class JavaGenerator : Generator { - private lateinit var internalPackage: List private lateinit var internalNamespace: List private lateinit var rootNamespace: List @@ -84,10 +83,12 @@ internal class JavaGenerator : Generator { override fun generate(limeModel: LimeModel): List { val cachingNameResolver = CppNameCache(rootNamespace, limeModel.referenceMap, cppNameRules) - val jniFilteredModel = LimeModelFilter - .filter(limeModel) { LimeModelSkipPredicates.shouldRetainElement(it, activeTags, JAVA, retainFunctionsAndFields = true) } - val javaFilteredModel = LimeModelFilter - .filter(limeModel) { LimeModelSkipPredicates.shouldRetainElement(it, activeTags, JAVA, retainFunctionsAndFields = false) } + val jniFilteredModel = + LimeModelFilter + .filter(limeModel) { LimeModelSkipPredicates.shouldRetainElement(it, activeTags, JAVA, retainFunctionsAndFields = true) } + val javaFilteredModel = + LimeModelFilter + .filter(limeModel) { LimeModelSkipPredicates.shouldRetainElement(it, activeTags, JAVA, retainFunctionsAndFields = false) } val limeLogger = LimeLogger(logger, limeModel.fileNameMap) val signatureResolver = JavaSignatureResolver(limeModel.referenceMap, javaNameRules, activeTags) @@ -99,62 +100,71 @@ internal class JavaGenerator : Generator { val commentsProcessor = JavaDocProcessor(werror.contains(GeneratorOptions.WARNING_DOC_LINKS), javaFilteredModel.referenceMap) - val nameResolver = JavaNameResolver( - limeReferenceMap = limeModel.referenceMap, - basePackages = basePackages, - javaNameRules = javaNameRules, - limeLogger = limeLogger, - commentsProcessor = commentsProcessor, - signatureResolver = signatureResolver - ) - val importResolver = JavaImportResolver( - limeReferenceMap = limeModel.referenceMap, - nameResolver = nameResolver, - internalPackages = internalPackageList, - nonNullAnnotation = nonNullAnnotation, - nullableAnnotation = nullableAnnotation - ) - val importCollector = JavaImportCollector(importResolver) { - LimeModelSkipPredicates.shouldRetainCheckParent(it, activeTags, JAVA, limeModel.referenceMap) - } - val resultFiles = javaFilteredModel.topElements - .flatMap { generateJavaFiles(it, nameResolver, importResolver, importCollector) } - .toMutableList() + val nameResolver = + JavaNameResolver( + limeReferenceMap = limeModel.referenceMap, + basePackages = basePackages, + javaNameRules = javaNameRules, + limeLogger = limeLogger, + commentsProcessor = commentsProcessor, + signatureResolver = signatureResolver, + ) + val importResolver = + JavaImportResolver( + limeReferenceMap = limeModel.referenceMap, + nameResolver = nameResolver, + internalPackages = internalPackageList, + nonNullAnnotation = nonNullAnnotation, + nullableAnnotation = nullableAnnotation, + ) + val importCollector = + JavaImportCollector(importResolver) { + LimeModelSkipPredicates.shouldRetainCheckParent(it, activeTags, JAVA, limeModel.referenceMap) + } + val resultFiles = + javaFilteredModel.topElements + .flatMap { generateJavaFiles(it, nameResolver, importResolver, importCollector) } + .toMutableList() val nativeBasePath = (listOf(GENERATOR_NAME) + internalPackageList).joinToString("/") - resultFiles += GeneratedFile( - TemplateEngine.render("java/NativeBase", internalPackageList), - "$nativeBasePath/NativeBase.java", - GeneratedFile.SourceSet.COMMON - ) - resultFiles += GeneratedFile( - TemplateEngine.render("java/AbstractNativeList", internalPackageList), - "$nativeBasePath/AbstractNativeList.java", - GeneratedFile.SourceSet.COMMON - ) - resultFiles += GeneratedFile( - TemplateEngine.render("java/HashMapBuilder", internalPackageList), - "$nativeBasePath/HashMapBuilder.java", - GeneratedFile.SourceSet.COMMON - ) - resultFiles += GeneratedFile( - TemplateEngine.render("java/Duration", internalPackageList), - "$nativeBasePath/time/Duration.java", - GeneratedFile.SourceSet.COMMON - ) + resultFiles += + GeneratedFile( + TemplateEngine.render("java/NativeBase", internalPackageList), + "$nativeBasePath/NativeBase.java", + GeneratedFile.SourceSet.COMMON, + ) + resultFiles += + GeneratedFile( + TemplateEngine.render("java/AbstractNativeList", internalPackageList), + "$nativeBasePath/AbstractNativeList.java", + GeneratedFile.SourceSet.COMMON, + ) + resultFiles += + GeneratedFile( + TemplateEngine.render("java/HashMapBuilder", internalPackageList), + "$nativeBasePath/HashMapBuilder.java", + GeneratedFile.SourceSet.COMMON, + ) + resultFiles += + GeneratedFile( + TemplateEngine.render("java/Duration", internalPackageList), + "$nativeBasePath/time/Duration.java", + GeneratedFile.SourceSet.COMMON, + ) val descendantInterfaces = LimeTypeHelper.collectDescendantInterfaces(jniFilteredModel.topElements) - val jniTemplates = JniTemplates( - limeReferenceMap = jniFilteredModel.referenceMap, - javaNameRules = javaNameRules, - basePackages = basePackages, - internalPackages = internalPackage, - internalNamespace = internalNamespace, - cppNameRules = cppNameRules, - nameCache = cachingNameResolver, - activeTags = activeTags, - descendantInterfaces = descendantInterfaces - ) + val jniTemplates = + JniTemplates( + limeReferenceMap = jniFilteredModel.referenceMap, + javaNameRules = javaNameRules, + basePackages = basePackages, + internalPackages = internalPackage, + internalNamespace = internalNamespace, + cppNameRules = cppNameRules, + nameCache = cachingNameResolver, + activeTags = activeTags, + descendantInterfaces = descendantInterfaces, + ) for (fileName in UTILS_FILES) { resultFiles += jniTemplates.generateConversionUtilsHeaderFile(fileName) resultFiles += jniTemplates.generateConversionUtilsImplementationFile(fileName) @@ -178,7 +188,7 @@ internal class JavaGenerator : Generator { limeElement: LimeNamedElement, nameResolver: JavaNameResolver, importResolver: JavaImportResolver, - importCollector: JavaImportCollector + importCollector: JavaImportCollector, ): List { if (limeElement.external?.java?.get(NAME_NAME) != null && limeElement.external?.java?.get(CONVERTER_NAME) == null @@ -191,21 +201,23 @@ internal class JavaGenerator : Generator { val imports = importCollector.collectImports(limeElement).filterNot { it.packageNames == packages } val optimizedLists = OptimizedListsCollector().getAllOptimizedLists(limeElement) - val templateData = mutableMapOf( - "model" to limeElement, - "contentTemplate" to contentTemplateName, - "package" to packages, - "imports" to imports.distinct().sorted(), - "nonNullAnnotation" to nonNullAnnotation, - "nullableAnnotation" to nullableAnnotation, - "optimizedLists" to optimizedLists - ) + val templateData = + mutableMapOf( + "model" to limeElement, + "contentTemplate" to contentTemplateName, + "package" to packages, + "imports" to imports.distinct().sorted(), + "nonNullAnnotation" to nonNullAnnotation, + "nullableAnnotation" to nullableAnnotation, + "optimizedLists" to optimizedLists, + ) - val nameResolvers = mapOf( - "" to nameResolver, - "empty" to JavaEmptyValueResolver(nameResolver), - "visibility" to JavaVisibilityResolver() - ) + val nameResolvers = + mapOf( + "" to nameResolver, + "empty" to JavaEmptyValueResolver(nameResolver), + "visibility" to JavaVisibilityResolver(), + ) val mainContent = TemplateEngine.render("java/JavaFile", templateData, nameResolvers, JavaGeneratorPredicates.predicates) val name = nameResolver.resolveName(limeElement) @@ -216,10 +228,11 @@ internal class JavaGenerator : Generator { return listOf(mainFile) } - val implImports = when (limeElement) { - is LimeInterface -> importCollector.collectImplImports(limeElement, imports) - else -> imports - } + importResolver.nativeBaseImport + val implImports = + when (limeElement) { + is LimeInterface -> importCollector.collectImplImports(limeElement, imports) + else -> imports + } + importResolver.nativeBaseImport templateData["imports"] = implImports.distinct().sorted() templateData["contentTemplate"] = "java/JavaImplClass" @@ -248,21 +261,21 @@ internal class JavaGenerator : Generator { private val logger = Logger.getLogger(JavaGenerator::class.java.name) - private val UTILS_FILES = listOf( - "CppProxyBase", - "FieldAccessMethods", - "JniBase", - "JniCallbackErrorChecking", - "JniCppConversionUtils", - "BoxingConversionUtils", - "JniClassCache", - "JniWrapperCache", - "JniCallJavaMethod" - ) + private val UTILS_FILES = + listOf( + "CppProxyBase", + "FieldAccessMethods", + "JniBase", + "JniCallbackErrorChecking", + "JniCppConversionUtils", + "BoxingConversionUtils", + "JniClassCache", + "JniWrapperCache", + "JniCallJavaMethod", + ) private val UTILS_FILES_HEADER_ONLY = listOf("ArrayConversionUtils", "JniExceptionThrower", "JniReference", "JniTemplateMetainfo") - private fun annotationFromOption(option: Pair>?) = - option?.let { JavaImport(option.second, option.first) } + private fun annotationFromOption(option: Pair>?) = option?.let { JavaImport(option.second, option.first) } } } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaGeneratorPredicates.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaGeneratorPredicates.kt index 587741ad69..ba6a60660e 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaGeneratorPredicates.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaGeneratorPredicates.kt @@ -33,47 +33,48 @@ import com.here.gluecodium.model.lime.LimeTypeRef * List of predicates used by `ifPredicate`/`unlessPredicate` template helpers in Java generator. */ internal object JavaGeneratorPredicates { - val predicates = mapOf( - "hasAnyComment" to { CommonGeneratorPredicates.hasAnyComment(it, "Java") }, - "hasInternalAllArgsConstructor" to { limeStruct: Any -> - limeStruct is LimeStruct && limeStruct.fields.any { CommonGeneratorPredicates.isInternal(it, JAVA) } - }, - "hasInternalFreeArgsConstructor" to { limeStruct: Any -> - limeStruct is LimeStruct && - limeStruct.uninitializedFields.any { CommonGeneratorPredicates.isInternal(it, JAVA) } - }, - "hasOwnEqualsAndHashCode" to { limeTypeRef -> - when { - limeTypeRef !is LimeTypeRef -> false - limeTypeRef.isNullable -> true - JavaImportResolver.needsNonNullAnnotation(limeTypeRef.type.actualType) -> true - else -> false - } - }, - "hasStaticFunctions" to { limeInterface -> - when { - limeInterface !is LimeInterface -> false - limeInterface.functions.any { it.isStatic } -> true - limeInterface.properties.any { it.isStatic } -> true - else -> false - } - }, - "needsAllFieldsConstructor" to { limeStruct: Any -> - when { - limeStruct !is LimeStruct -> false - limeStruct.external?.java?.get(LimeExternalDescriptor.CONVERTER_NAME) != null -> true - limeStruct.attributes.have(JAVA, LimeAttributeValueType.POSITIONAL_DEFAULTS) -> false - limeStruct.attributes.have(LimeAttributeType.IMMUTABLE) -> limeStruct.allFieldsConstructor == null - limeStruct.fieldConstructors.isEmpty() -> limeStruct.initializedFields.isEmpty() - else -> false - } - }, - "needsDisposer" to { limeClass: Any -> - limeClass is LimeClass && limeClass.parentClass == null - }, - "needsNonNullAnnotation" to { limeTypeRef -> - limeTypeRef is LimeTypeRef && !limeTypeRef.isNullable && - JavaImportResolver.needsNonNullAnnotation(limeTypeRef.type.actualType) - } - ) + val predicates = + mapOf( + "hasAnyComment" to { CommonGeneratorPredicates.hasAnyComment(it, "Java") }, + "hasInternalAllArgsConstructor" to { limeStruct: Any -> + limeStruct is LimeStruct && limeStruct.fields.any { CommonGeneratorPredicates.isInternal(it, JAVA) } + }, + "hasInternalFreeArgsConstructor" to { limeStruct: Any -> + limeStruct is LimeStruct && + limeStruct.uninitializedFields.any { CommonGeneratorPredicates.isInternal(it, JAVA) } + }, + "hasOwnEqualsAndHashCode" to { limeTypeRef -> + when { + limeTypeRef !is LimeTypeRef -> false + limeTypeRef.isNullable -> true + JavaImportResolver.needsNonNullAnnotation(limeTypeRef.type.actualType) -> true + else -> false + } + }, + "hasStaticFunctions" to { limeInterface -> + when { + limeInterface !is LimeInterface -> false + limeInterface.functions.any { it.isStatic } -> true + limeInterface.properties.any { it.isStatic } -> true + else -> false + } + }, + "needsAllFieldsConstructor" to { limeStruct: Any -> + when { + limeStruct !is LimeStruct -> false + limeStruct.external?.java?.get(LimeExternalDescriptor.CONVERTER_NAME) != null -> true + limeStruct.attributes.have(JAVA, LimeAttributeValueType.POSITIONAL_DEFAULTS) -> false + limeStruct.attributes.have(LimeAttributeType.IMMUTABLE) -> limeStruct.allFieldsConstructor == null + limeStruct.fieldConstructors.isEmpty() -> limeStruct.initializedFields.isEmpty() + else -> false + } + }, + "needsDisposer" to { limeClass: Any -> + limeClass is LimeClass && limeClass.parentClass == null + }, + "needsNonNullAnnotation" to { limeTypeRef -> + limeTypeRef is LimeTypeRef && !limeTypeRef.isNullable && + JavaImportResolver.needsNonNullAnnotation(limeTypeRef.type.actualType) + }, + ) } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaImport.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaImport.kt index 171d299f3e..e95e21546c 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaImport.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaImport.kt @@ -22,7 +22,6 @@ package com.here.gluecodium.generator.java import kotlin.math.min internal data class JavaImport(val packageNames: List, val className: String) : Comparable { - override fun compareTo(other: JavaImport): Int { val minimumNameCount = min(packageNames.size, other.packageNames.size) for (i in 0 until minimumNameCount) { diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaImportCollector.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaImportCollector.kt index 89e6cdf14f..48cb1e4407 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaImportCollector.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaImportCollector.kt @@ -33,27 +33,30 @@ import com.here.gluecodium.model.lime.LimeStruct internal class JavaImportCollector( private val importsResolver: JavaImportResolver, - private val retainPredicate: (LimeNamedElement) -> Boolean + private val retainPredicate: (LimeNamedElement) -> Boolean, ) : ImportsCollector { - override fun collectImports(limeElement: LimeNamedElement): List { if (!retainPredicate(limeElement)) return emptyList() - val nestedImports = when (limeElement) { - is LimeStruct -> - collectContainerImports(limeElement) + limeElement.fields.flatMap { collectImports(it) } - is LimeContainer -> collectContainerImports(limeElement) - is LimeFunction -> collectFunctionImports(limeElement) - is LimeLambda -> collectFunctionImports(limeElement.asFunction()) - is LimeConstant -> importsResolver.resolveElementImports(limeElement.value) - is LimeField -> - limeElement.defaultValue?.let { importsResolver.resolveElementImports(it) } ?: emptyList() - else -> emptyList() - } + val nestedImports = + when (limeElement) { + is LimeStruct -> + collectContainerImports(limeElement) + limeElement.fields.flatMap { collectImports(it) } + is LimeContainer -> collectContainerImports(limeElement) + is LimeFunction -> collectFunctionImports(limeElement) + is LimeLambda -> collectFunctionImports(limeElement.asFunction()) + is LimeConstant -> importsResolver.resolveElementImports(limeElement.value) + is LimeField -> + limeElement.defaultValue?.let { importsResolver.resolveElementImports(it) } ?: emptyList() + else -> emptyList() + } return importsResolver.resolveElementImports(limeElement) + nestedImports } - fun collectImplImports(limeInterface: LimeInterface, defImports: List): List { + fun collectImplImports( + limeInterface: LimeInterface, + defImports: List, + ): List { if (limeInterface.parents.isEmpty()) return defImports val parentImports = limeInterface.parents.mapNotNull { importsResolver.createTopElementImport(it.type.actualType) } @@ -62,9 +65,10 @@ internal class JavaImportCollector( } private fun collectContainerImports(limeContainer: LimeContainer): List { - val nestedElements = limeContainer.functions + limeContainer.properties + limeContainer.structs + - limeContainer.classes + limeContainer.interfaces + limeContainer.exceptions + limeContainer.lambdas + - limeContainer.constants + val nestedElements = + limeContainer.functions + limeContainer.properties + limeContainer.structs + + limeContainer.classes + limeContainer.interfaces + limeContainer.exceptions + limeContainer.lambdas + + limeContainer.constants val inheritedElements = when { limeContainer !is LimeContainerWithInheritance -> emptyList() diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaImportResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaImportResolver.kt index fe7f07ad3b..b7c75b69eb 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaImportResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaImportResolver.kt @@ -50,7 +50,7 @@ internal class JavaImportResolver( private val nameResolver: JavaNameResolver, internalPackages: List, private val nonNullAnnotation: JavaImport?, - private val nullableAnnotation: JavaImport? + private val nullableAnnotation: JavaImport?, ) : ImportsResolver { val nativeBaseImport = JavaImport(internalPackages, "NativeBase") private val abstractNativeListImport = JavaImport(internalPackages, "AbstractNativeList") @@ -86,8 +86,9 @@ internal class JavaImportResolver( private fun resolveStructImports(limeStruct: LimeStruct) = when { - limeStruct.attributes.have(SERIALIZABLE) -> listOf(parcelImport, parcelableImport) + - limeStruct.fields.mapNotNull { resolveSerializationImport(it.typeRef.type.actualType) } + limeStruct.attributes.have(SERIALIZABLE) -> + listOf(parcelImport, parcelableImport) + + limeStruct.fields.mapNotNull { resolveSerializationImport(it.typeRef.type.actualType) } else -> emptyList() } @@ -115,40 +116,49 @@ internal class JavaImportResolver( val hasValues = limeInitializerList.values.isNotEmpty() return when (limeType) { is LimeList -> listOfNotNull(arrayListImport, arraysImport.takeIf { hasValues }) - is LimeSet -> listOfNotNull(arraysImport.takeIf { hasValues }) + - if (limeType.elementType.type.actualType is LimeEnumeration) enumSetImport else hashSetImport + is LimeSet -> + listOfNotNull(arraysImport.takeIf { hasValues }) + + if (limeType.elementType.type.actualType is LimeEnumeration) enumSetImport else hashSetImport is LimeMap -> listOfNotNull(hashMapImport, hashMapBuilderImport.takeIf { hasValues }) else -> emptyList() } } - private fun resolveTypeRefImports(limeTypeRef: LimeTypeRef?, ignoreNullability: Boolean = false): List { + private fun resolveTypeRefImports( + limeTypeRef: LimeTypeRef?, + ignoreNullability: Boolean = false, + ): List { val limeType = limeTypeRef?.type?.actualType ?: return emptyList() - val imports = when { - limeType.external?.java != null -> emptyList() // External types are referred by FQN, so no import needed. - limeType is LimeBasicType -> listOfNotNull(resolveBasicTypeImport(limeType.typeId)) - limeType is LimeList -> resolveTypeRefImports(limeType.elementType, ignoreNullability = true) + listImport + - if (limeTypeRef.attributes.have(OPTIMIZED)) listOf(abstractNativeListImport) else emptyList() - limeType is LimeSet -> resolveTypeRefImports(limeType.elementType, ignoreNullability = true) + setImport - limeType is LimeMap -> resolveTypeRefImports(limeType.keyType, ignoreNullability = true) + - resolveTypeRefImports(limeType.valueType, ignoreNullability = true) + mapImport - else -> listOfNotNull(createTopElementImport(limeType)) - } - val nullabilityImport = when { - ignoreNullability -> null - limeTypeRef.isNullable -> nullableAnnotation - needsNonNullAnnotation(limeType) -> nonNullAnnotation - else -> null - } + val imports = + when { + limeType.external?.java != null -> emptyList() // External types are referred by FQN, so no import needed. + limeType is LimeBasicType -> listOfNotNull(resolveBasicTypeImport(limeType.typeId)) + limeType is LimeList -> + resolveTypeRefImports(limeType.elementType, ignoreNullability = true) + listImport + + if (limeTypeRef.attributes.have(OPTIMIZED)) listOf(abstractNativeListImport) else emptyList() + limeType is LimeSet -> resolveTypeRefImports(limeType.elementType, ignoreNullability = true) + setImport + limeType is LimeMap -> + resolveTypeRefImports(limeType.keyType, ignoreNullability = true) + + resolveTypeRefImports(limeType.valueType, ignoreNullability = true) + mapImport + else -> listOfNotNull(createTopElementImport(limeType)) + } + val nullabilityImport = + when { + ignoreNullability -> null + limeTypeRef.isNullable -> nullableAnnotation + needsNonNullAnnotation(limeType) -> nonNullAnnotation + else -> null + } return imports + listOfNotNull(nullabilityImport) } fun createTopElementImport(limeType: LimeType): JavaImport? { if (nameResolver.typesWithDuplicateNames.contains(limeType.fullName)) return null - val topElement = generateSequence(limeType) { - limeReferenceMap[it.path.parent.toString()] as? LimeType - }.last() + val topElement = + generateSequence(limeType) { + limeReferenceMap[it.path.parent.toString()] as? LimeType + }.last() return JavaImport(nameResolver.resolvePackageNames(topElement), nameResolver.resolveName(topElement)) } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaNameResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaNameResolver.kt index 7b6720e6a1..8e48beeb29 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaNameResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaNameResolver.kt @@ -54,9 +54,8 @@ internal class JavaNameResolver( private val javaNameRules: JavaNameRules, private val limeLogger: LimeLogger, private val commentsProcessor: CommentsProcessor, - private val signatureResolver: JavaSignatureResolver + private val signatureResolver: JavaSignatureResolver, ) : ReferenceMapBasedResolver(limeReferenceMap), NameResolver { - private val valueResolver = JavaValueResolver(this) private val duplicateNames: Set private val limeToJavaNames: Map @@ -103,10 +102,15 @@ internal class JavaNameResolver( return commentsProcessor.process(commentedElement.fullName, commentText, limeToJavaNames, limeLogger) } - private fun resolveAccessorName(element: Any, rule: JavaNameRules.(LimeTypedElement) -> String) = - (element as? LimeTypedElement)?.let { javaNameRules.rule(it) } + private fun resolveAccessorName( + element: Any, + rule: JavaNameRules.(LimeTypedElement) -> String, + ) = (element as? LimeTypedElement)?.let { javaNameRules.rule(it) } - internal fun resolveTypeRef(limeTypeRef: LimeTypeRef, needsBoxing: Boolean = false): String { + internal fun resolveTypeRef( + limeTypeRef: LimeTypeRef, + needsBoxing: Boolean = false, + ): String { val limeType = limeTypeRef.type.actualType val externalName = limeType.external?.java?.get(NAME_NAME) return when { @@ -114,8 +118,11 @@ internal class JavaNameResolver( limeType is LimeGenericType -> resolveGenericTypeRef(limeType) limeType !is LimeBasicType -> { val nestedName = resolveNestedNames(limeType).joinToString(".") - if (duplicateNames.contains(nestedName)) (resolvePackageNames(limeType) + nestedName).joinToString(".") - else nestedName + if (duplicateNames.contains(nestedName)) { + (resolvePackageNames(limeType) + nestedName).joinToString(".") + } else { + nestedName + } } needsBoxing || limeTypeRef.isNullable -> resolveBoxedBasicType(limeType.typeId) else -> resolveBasicType(limeType.typeId) @@ -195,22 +202,25 @@ internal class JavaNameResolver( } private fun buildPathMap(): Map { - val result = limeReferenceMap.values - .filterIsInstance() - .filterNot { it is LimeProperty || it is LimeFunction || it is LimeTypeAlias || it is LimeParameter } - .associateBy({ it.path.toAmbiguousString() }, { resolveFullName(it) }) - .toMutableMap() + val result = + limeReferenceMap.values + .filterIsInstance() + .filterNot { it is LimeProperty || it is LimeFunction || it is LimeTypeAlias || it is LimeParameter } + .associateBy({ it.path.toAmbiguousString() }, { resolveFullName(it) }) + .toMutableMap() - result += limeReferenceMap.values.filterIsInstance() - .associateBy({ it.fullName }, { resolveFullName(it) }) + result += + limeReferenceMap.values.filterIsInstance() + .associateBy({ it.fullName }, { resolveFullName(it) }) limeReferenceMap.values.filterIsInstance().forEach { val ambiguousKey = it.path.toAmbiguousString() - val fullSignatureKey = ambiguousKey + - it.parameters.joinToString(prefix = "(", postfix = ")", separator = ",") { - parameter -> - parameter.typeRef.toString() - } + val fullSignatureKey = + ambiguousKey + + it.parameters.joinToString(prefix = "(", postfix = ")", separator = ",") { + parameter -> + parameter.typeRef.toString() + } val fullName = resolveFullName(it) + getSignatureSuffix(it) result[it.fullName] = fullName @@ -233,7 +243,10 @@ internal class JavaNameResolver( return result } - fun resolveFullName(limeElement: LimeNamedElement, forceDelimiter: String? = null): String { + fun resolveFullName( + limeElement: LimeNamedElement, + forceDelimiter: String? = null, + ): String { val elementName = resolveName(limeElement) if (!limeElement.path.hasParent) { @@ -243,18 +256,18 @@ internal class JavaNameResolver( val parentElement = getParentElement(limeElement) val prefix = resolveFullName(parentElement) - val delimiter = when { - forceDelimiter != null -> forceDelimiter - limeElement is LimeType -> "." - else -> "#" - } + val delimiter = + when { + forceDelimiter != null -> forceDelimiter + limeElement is LimeType -> "." + else -> "#" + } val ownName = if (limeElement is LimeFunction && limeElement.isConstructor) resolveName(parentElement) else elementName return prefix + delimiter + ownName } - fun resolvePackageNames(limeElement: LimeNamedElement) = - (basePackages + limeElement.path.head).map { normalizePackageName(it) } + fun resolvePackageNames(limeElement: LimeNamedElement) = (basePackages + limeElement.path.head).map { normalizePackageName(it) } private fun getSignatureSuffix(limeFunction: LimeFunction) = when { diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaNameRules.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaNameRules.kt index 74bf3d6107..0fabc74d38 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaNameRules.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaNameRules.kt @@ -30,8 +30,7 @@ import com.here.gluecodium.model.lime.LimeProperty import com.here.gluecodium.model.lime.LimeTypedElement internal class JavaNameRules(nameRuleSet: NameRuleSet) : NameRules(nameRuleSet) { - override fun getName(limeElement: LimeElement) = - getPlatformName(limeElement as? LimeNamedElement) ?: super.getName(limeElement) + override fun getName(limeElement: LimeElement) = getPlatformName(limeElement as? LimeNamedElement) ?: super.getName(limeElement) override fun getGetterName(limeElement: LimeTypedElement) = (limeElement as? LimeProperty)?.let { getPlatformName(it.getter) } @@ -41,17 +40,16 @@ internal class JavaNameRules(nameRuleSet: NameRuleSet) : NameRules(nameRuleSet) (limeElement as? LimeProperty)?.let { getPlatformName(it.setter) } ?: super.getSetterName(limeElement) - fun getName(limeLambdaParameter: LimeLambdaParameter, index: Int) = - limeLambdaParameter.attributes.get(JAVA, NAME) ?: "p$index" + fun getName( + limeLambdaParameter: LimeLambdaParameter, + index: Int, + ) = limeLambdaParameter.attributes.get(JAVA, NAME) ?: "p$index" - private fun getPlatformName(limeElement: LimeNamedElement?) = - limeElement?.attributes?.get(JAVA, NAME) + private fun getPlatformName(limeElement: LimeNamedElement?) = limeElement?.attributes?.get(JAVA, NAME) companion object { - fun getPackageFromImportString(importString: String) = - importString.split('.').takeWhile { it.first().isLowerCase() } + fun getPackageFromImportString(importString: String) = importString.split('.').takeWhile { it.first().isLowerCase() } - fun getClassNamesFromImportString(importString: String) = - importString.split('.').dropWhile { it.first().isLowerCase() } + fun getClassNamesFromImportString(importString: String) = importString.split('.').dropWhile { it.first().isLowerCase() } } } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaSignatureResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaSignatureResolver.kt index 1acfdbb0ae..e502c1b555 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaSignatureResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaSignatureResolver.kt @@ -27,12 +27,14 @@ import com.here.gluecodium.model.lime.LimeTypeRef internal class JavaSignatureResolver( limeReferenceMap: Map, nameRules: JavaNameRules, - activeTags: Set + activeTags: Set, ) : PlatformSignatureResolver(limeReferenceMap, LimeAttributeType.JAVA, nameRules, activeTags) { - override fun getArrayName(elementType: LimeTypeRef) = TYPE_ERASED_ARRAY - override fun getMapName(keyType: LimeTypeRef, valueType: LimeTypeRef) = TYPE_ERASED_MAP + override fun getMapName( + keyType: LimeTypeRef, + valueType: LimeTypeRef, + ) = TYPE_ERASED_MAP override fun getSetName(elementType: LimeTypeRef) = TYPE_ERASED_SET diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaValueResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaValueResolver.kt index 622c6a9f9b..e1bfa078d4 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaValueResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaValueResolver.kt @@ -33,7 +33,6 @@ import com.here.gluecodium.model.lime.LimeValue import com.here.gluecodium.model.lime.LimeValue.Duration.TimeUnit internal class JavaValueResolver(private val nameResolver: JavaNameResolver) { - fun resolveValue(limeValue: LimeValue): String = when (limeValue) { is LimeValue.Literal -> mapLiteralValue(limeValue) @@ -102,15 +101,16 @@ internal class JavaValueResolver(private val nameResolver: JavaNameResolver) { "new HashSet<>($valuesAsList)" } } - is LimeMap -> when { - limeValue.values.isEmpty() -> "new HashMap<>()" - else -> { - val keyType = nameResolver.resolveTypeRef(limeType.keyType, needsBoxing = true) - val valueType = nameResolver.resolveTypeRef(limeType.valueType, needsBoxing = true) - val values = limeValue.values.joinToString(".") { resolveValue(it) } - "new HashMapBuilder<$keyType, $valueType>().$values.build()" + is LimeMap -> + when { + limeValue.values.isEmpty() -> "new HashMap<>()" + else -> { + val keyType = nameResolver.resolveTypeRef(limeType.keyType, needsBoxing = true) + val valueType = nameResolver.resolveTypeRef(limeType.valueType, needsBoxing = true) + val values = limeValue.values.joinToString(".") { resolveValue(it) } + "new HashMapBuilder<$keyType, $valueType>().$values.build()" + } } - } else -> throw GluecodiumExecutionException("Unsupported type ${limeType.javaClass.name} for initializer list") } } @@ -125,31 +125,35 @@ internal class JavaValueResolver(private val nameResolver: JavaNameResolver) { } private fun mapSpecialValue(limeValue: LimeValue.Special): String { - val prefix = when ((limeValue.typeRef.type as LimeBasicType).typeId) { - TypeId.FLOAT -> "Float" - else -> "Double" - } - val value = when (limeValue.value) { - LimeValue.Special.ValueId.NAN -> "NaN" - LimeValue.Special.ValueId.INFINITY -> "POSITIVE_INFINITY" - LimeValue.Special.ValueId.NEGATIVE_INFINITY -> "NEGATIVE_INFINITY" - } + val prefix = + when ((limeValue.typeRef.type as LimeBasicType).typeId) { + TypeId.FLOAT -> "Float" + else -> "Double" + } + val value = + when (limeValue.value) { + LimeValue.Special.ValueId.NAN -> "NaN" + LimeValue.Special.ValueId.INFINITY -> "POSITIVE_INFINITY" + LimeValue.Special.ValueId.NEGATIVE_INFINITY -> "NEGATIVE_INFINITY" + } return "$prefix.$value" } private fun mapDurationValue(limeValue: LimeValue.Duration): String { - val factoryMethod = when (limeValue.timeUnit) { - TimeUnit.DAY -> "ofDays" - TimeUnit.HOUR -> "ofHours" - TimeUnit.MINUTE -> "ofMinutes" - TimeUnit.SECOND -> "ofSeconds" - TimeUnit.MILLISECOND -> "ofMillis" - TimeUnit.MICROSECOND, TimeUnit.NANOSECOND -> "ofNanos" - } - val valueSuffix = when (limeValue.timeUnit) { - TimeUnit.MICROSECOND -> "000L" - else -> "L" - } + val factoryMethod = + when (limeValue.timeUnit) { + TimeUnit.DAY -> "ofDays" + TimeUnit.HOUR -> "ofHours" + TimeUnit.MINUTE -> "ofMinutes" + TimeUnit.SECOND -> "ofSeconds" + TimeUnit.MILLISECOND -> "ofMillis" + TimeUnit.MICROSECOND, TimeUnit.NANOSECOND -> "ofNanos" + } + val valueSuffix = + when (limeValue.timeUnit) { + TimeUnit.MICROSECOND -> "000L" + else -> "L" + } return "Duration.$factoryMethod(${limeValue.value}$valueSuffix)" } } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaVisibilityResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaVisibilityResolver.kt index 1708980e6c..c3058dc497 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaVisibilityResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/java/JavaVisibilityResolver.kt @@ -26,7 +26,6 @@ import com.here.gluecodium.model.lime.LimeAttributeType.JAVA import com.here.gluecodium.model.lime.LimeNamedElement internal class JavaVisibilityResolver : NameResolver { - override fun resolveName(element: Any): String = when (element) { is LimeNamedElement -> if (CommonGeneratorPredicates.isInternal(element, JAVA)) "" else "public " diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/jni/JniFileNameRules.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/jni/JniFileNameRules.kt index b4cf240106..1d374cbf3c 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/jni/JniFileNameRules.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/jni/JniFileNameRules.kt @@ -27,7 +27,6 @@ import com.here.gluecodium.model.lime.LimeNamedElement import java.io.File internal class JniFileNameRules(generatorName: String, private val nameResolver: JniNameResolver) { - private val jniPathPrefix = generatorName + File.separator + "jni" + File.separator fun getHeaderFilePath(fileName: String) = "$jniPathPrefix$fileName.h" diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/jni/JniGeneratorPredicates.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/jni/JniGeneratorPredicates.kt index 24d9925f5d..7b07730c61 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/jni/JniGeneratorPredicates.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/jni/JniGeneratorPredicates.kt @@ -54,60 +54,65 @@ internal class JniGeneratorPredicates( javaNameRules: JavaNameRules, cppNameRules: CppNameRules, cppNameResolver: CppNameResolver, - private val activeTags: Set + private val activeTags: Set, ) { private val javaSignatureResolver = JavaSignatureResolver(limeReferenceMap, javaNameRules, activeTags) private val cppSignatureResolver = CppSignatureResolver(limeReferenceMap, cppNameRules) private val overloadedLambdas = collectOverloadedLambdas() - val predicates = mapOf( - "hasConstructors" to { limeContainer: Any -> - limeContainer is LimeContainer && limeContainer.functions.any { it.isConstructor } - }, - "hasCppGetter" to { limeField: Any -> - limeField is LimeField && cppNameResolver.resolveGetterName(limeField) != null - }, - "hasCppSetter" to { limeField: Any -> - limeField is LimeField && cppNameResolver.resolveSetterName(limeField) != null - }, - "hasImmutableFields" to { CommonGeneratorPredicates.hasImmutableFields(it) }, - "hasOverloadedLambda" to { limeType: Any -> - when (limeType) { - is LimeLambda -> isOverloadedLambda(limeType) - is LimeList -> isOverloadedLambda(limeType.elementType.type.actualType) - is LimeMap -> isOverloadedLambda(limeType.valueType.type.actualType) - else -> false - } - }, - "hasTypeRepository" to { CommonGeneratorPredicates.hasTypeRepository(it) }, - "isJniPrimitive" to fun(limeTypeRef: Any): Boolean { - if (limeTypeRef !is LimeTypeRef || limeTypeRef.isNullable) return false + val predicates = + mapOf( + "hasConstructors" to { limeContainer: Any -> + limeContainer is LimeContainer && limeContainer.functions.any { it.isConstructor } + }, + "hasCppGetter" to { limeField: Any -> + limeField is LimeField && cppNameResolver.resolveGetterName(limeField) != null + }, + "hasCppSetter" to { limeField: Any -> + limeField is LimeField && cppNameResolver.resolveSetterName(limeField) != null + }, + "hasImmutableFields" to { CommonGeneratorPredicates.hasImmutableFields(it) }, + "hasOverloadedLambda" to { limeType: Any -> + when (limeType) { + is LimeLambda -> isOverloadedLambda(limeType) + is LimeList -> isOverloadedLambda(limeType.elementType.type.actualType) + is LimeMap -> isOverloadedLambda(limeType.valueType.type.actualType) + else -> false + } + }, + "hasTypeRepository" to { CommonGeneratorPredicates.hasTypeRepository(it) }, + "isJniPrimitive" to - val limeType = limeTypeRef.type.actualType - if (limeType !is LimeBasicType) return false + fun(limeTypeRef: Any): Boolean { + if (limeTypeRef !is LimeTypeRef || limeTypeRef.isNullable) return false - val typeId = limeType.typeId - return typeId.isNumericType || typeId == VOID || typeId == BOOLEAN - }, - "isOverloaded" to { limeFunction: Any -> - limeFunction is LimeFunction && javaSignatureResolver.isOverloadedInBindings(limeFunction) - }, - "needsOrdinalConversion" to fun(limeEnumeration: Any): Boolean { - if (limeEnumeration !is LimeEnumeration) return false - val descriptor = limeEnumeration.external?.java ?: return false - return !descriptor.containsKey(CONVERTER_NAME) - }, - "needsRefSuffix" to { limeTypeRef: Any -> - limeTypeRef is LimeTypeRef && CppNameResolver.needsRefSuffix(limeTypeRef) - }, - "returnsOpaqueHandle" to { limeFunction: Any -> - limeFunction is LimeFunction && limeFunction.isConstructor && - limeFunction.returnType.typeRef.type is LimeClass - }, - "shouldRetain" to { limeElement: Any -> - limeElement is LimeNamedElement && shouldRetain(limeElement) - } - ) + val limeType = limeTypeRef.type.actualType + if (limeType !is LimeBasicType) return false + + val typeId = limeType.typeId + return typeId.isNumericType || typeId == VOID || typeId == BOOLEAN + }, + "isOverloaded" to { limeFunction: Any -> + limeFunction is LimeFunction && javaSignatureResolver.isOverloadedInBindings(limeFunction) + }, + "needsOrdinalConversion" to + + fun(limeEnumeration: Any): Boolean { + if (limeEnumeration !is LimeEnumeration) return false + val descriptor = limeEnumeration.external?.java ?: return false + return !descriptor.containsKey(CONVERTER_NAME) + }, + "needsRefSuffix" to { limeTypeRef: Any -> + limeTypeRef is LimeTypeRef && CppNameResolver.needsRefSuffix(limeTypeRef) + }, + "returnsOpaqueHandle" to { limeFunction: Any -> + limeFunction is LimeFunction && limeFunction.isConstructor && + limeFunction.returnType.typeRef.type is LimeClass + }, + "shouldRetain" to { limeElement: Any -> + limeElement is LimeNamedElement && shouldRetain(limeElement) + }, + ) fun shouldRetain(limeElement: LimeNamedElement) = LimeModelSkipPredicates.shouldRetainCheckParent(limeElement, activeTags, JAVA, limeReferenceMap) @@ -120,8 +125,7 @@ internal class JniGeneratorPredicates( return (overloadedLambdas + attributeLambdas).map { it.path.toString() }.toSet() } - private fun isOverloadedLambda(limeType: LimeType) = - limeType is LimeLambda && overloadedLambdas.contains(limeType.path.toString()) + private fun isOverloadedLambda(limeType: LimeType) = limeType is LimeLambda && overloadedLambdas.contains(limeType.path.toString()) companion object { fun hasThrowingFunctions(limeElement: LimeNamedElement) = diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/jni/JniIncludeCollector.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/jni/JniIncludeCollector.kt index fa774bd937..3d7f9cafa5 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/jni/JniIncludeCollector.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/jni/JniIncludeCollector.kt @@ -31,14 +31,14 @@ import com.here.gluecodium.model.lime.LimeStruct internal class JniIncludeCollector( private val includeResolver: JniIncludeResolver, - private val retainPredicate: (LimeNamedElement) -> Boolean + private val retainPredicate: (LimeNamedElement) -> Boolean, ) : ImportsCollector { - override fun collectImports(limeElement: LimeNamedElement) = when (limeElement) { is LimeLambda -> collectImplIncludes(limeElement) - is LimeContainerWithInheritance -> collectImplIncludes(limeElement) + - collectImplIncludes(limeElement.inheritedFunctions, limeElement.inheritedProperties) + is LimeContainerWithInheritance -> + collectImplIncludes(limeElement) + + collectImplIncludes(limeElement.inheritedFunctions, limeElement.inheritedProperties) is LimeContainer -> collectImplIncludes(limeElement) else -> emptyList() } @@ -47,9 +47,13 @@ internal class JniIncludeCollector( limeFunction.parameters.map { it.typeRef } + limeFunction.returnType.typeRef + listOfNotNull(limeFunction.exception?.errorType) - private fun collectImplIncludes(functions: List, properties: List): List { - val allFunctions = functions + - properties.filter(retainPredicate).flatMap { listOfNotNull(it.getter, it.setter) } + private fun collectImplIncludes( + functions: List, + properties: List, + ): List { + val allFunctions = + functions + + properties.filter(retainPredicate).flatMap { listOfNotNull(it.getter, it.setter) } return allFunctions.filter(retainPredicate) .flatMap { collectFunctionTypes(it) } .flatMap { includeResolver.resolveElementImports(it) } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/jni/JniIncludeResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/jni/JniIncludeResolver.kt index cb4c4340bf..0b9358a593 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/jni/JniIncludeResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/jni/JniIncludeResolver.kt @@ -37,9 +37,8 @@ import com.here.gluecodium.model.lime.LimeTypedElement internal class JniIncludeResolver( private val fileNameRules: JniFileNameRules, - private val descendantInterfaces: Map> + private val descendantInterfaces: Map>, ) : ImportsResolver { - override fun resolveElementImports(limeElement: LimeElement): List = when (limeElement) { is LimeTypeRef -> resolveElementImports(limeElement.type.actualType) diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/jni/JniMangledNameResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/jni/JniMangledNameResolver.kt index 7af1cc8f08..d1ec4df640 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/jni/JniMangledNameResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/jni/JniMangledNameResolver.kt @@ -26,18 +26,15 @@ import com.here.gluecodium.model.lime.LimeType import com.here.gluecodium.model.lime.LimeTypeRef internal class JniMangledNameResolver(private val baseNameResolver: JniNameResolver) : NameResolver { - override fun resolveName(element: Any) = when (element) { is LimeElement -> mangleName(baseNameResolver.resolveName(element)) else -> mangleName(element.toString()) } - override fun resolveGetterName(element: Any) = - baseNameResolver.resolveGetterName(element)?.let { mangleName(it) } + override fun resolveGetterName(element: Any) = baseNameResolver.resolveGetterName(element)?.let { mangleName(it) } - override fun resolveSetterName(element: Any) = - baseNameResolver.resolveSetterName(element)?.let { mangleName(it) } + override fun resolveSetterName(element: Any) = baseNameResolver.resolveSetterName(element)?.let { mangleName(it) } // Narrow usage: // * for intermediate types for "external" types with converters diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/jni/JniNameResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/jni/JniNameResolver.kt index aa9b79ed4b..63a50b04ac 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/jni/JniNameResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/jni/JniNameResolver.kt @@ -47,9 +47,8 @@ import com.here.gluecodium.model.lime.LimeTypedElement internal class JniNameResolver( limeReferenceMap: Map, private val basePackages: List, - private val javaNameRules: JavaNameRules + private val javaNameRules: JavaNameRules, ) : ReferenceMapBasedResolver(limeReferenceMap), NameResolver { - override fun resolveName(element: Any): String = when (element) { is String -> createJavaTypePath(element) @@ -79,7 +78,10 @@ internal class JniNameResolver( else -> createJavaTypePath(basePackages + element.path.head, resolveNestedNames(element)) } - private fun resolveAccessorName(element: Any, rule: JavaNameRules.(LimeTypedElement) -> String): String? { + private fun resolveAccessorName( + element: Any, + rule: JavaNameRules.(LimeTypedElement) -> String, + ): String? { val limeTypedElement = element as? LimeTypedElement ?: return null return javaNameRules.rule(limeTypedElement) + if (limeTypedElement.attributes.have(CACHED)) "_private" else "" @@ -100,17 +102,21 @@ internal class JniNameResolver( is LimeList -> "java/util/List" is LimeSet -> "java/util/Set" is LimeMap -> "java/util/Map" - else -> limeType.external?.java?.get(LimeExternalDescriptor.NAME_NAME)?.let { createJavaTypePath(it) } - ?: createJavaTypePath(basePackages + actualType.path.head, resolveNestedNames(actualType)) + else -> + limeType.external?.java?.get(LimeExternalDescriptor.NAME_NAME)?.let { createJavaTypePath(it) } + ?: createJavaTypePath(basePackages + actualType.path.head, resolveNestedNames(actualType)) } private fun createJavaTypePath(importString: String) = createJavaTypePath( JavaNameRules.getPackageFromImportString(importString), - JavaNameRules.getClassNamesFromImportString(importString) + JavaNameRules.getClassNamesFromImportString(importString), ) - private fun createJavaTypePath(packageNames: List, classNames: List): String { + private fun createJavaTypePath( + packageNames: List, + classNames: List, + ): String { val fixedPackageNames = packageNames.map { it.replace("_", "") } return (fixedPackageNames + classNames.joinToString("$")).joinToString("/") } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/jni/JniTemplates.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/jni/JniTemplates.kt index 80f8c28ac1..42c3873a7b 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/jni/JniTemplates.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/jni/JniTemplates.kt @@ -55,19 +55,20 @@ internal class JniTemplates( cppNameRules: CppNameRules, nameCache: CppNameCache, activeTags: Set, - private val descendantInterfaces: Map> + private val descendantInterfaces: Map>, ) { private val jniNameResolver = JniNameResolver(limeReferenceMap, basePackages, javaNameRules) private val cppNameResolver = CppNameResolver(limeReferenceMap, internalNamespace, nameCache) private val fileNameRules = JniFileNameRules(JavaGenerator.GENERATOR_NAME, jniNameResolver) private val fullInternalPackages = basePackages + internalPackages - private val nameResolvers = mapOf( - "" to jniNameResolver, - "signature" to JniTypeSignatureNameResolver(jniNameResolver, fullInternalPackages), - "mangled" to JniMangledNameResolver(jniNameResolver), - "C++" to cppNameResolver, - "C++ FQN" to CppFullNameResolver(nameCache) - ) + private val nameResolvers = + mapOf( + "" to jniNameResolver, + "signature" to JniTypeSignatureNameResolver(jniNameResolver, fullInternalPackages), + "mangled" to JniMangledNameResolver(jniNameResolver), + "C++" to cppNameResolver, + "C++ FQN" to CppFullNameResolver(nameCache), + ) private val generatorPredicates = JniGeneratorPredicates(limeReferenceMap, javaNameRules, nameCache.nameRules, cppNameResolver, activeTags) @@ -76,10 +77,11 @@ internal class JniTemplates( private val jniIncludeCollector = JniIncludeCollector(jniIncludeResolver) { generatorPredicates.shouldRetain(it) } fun generateFiles(limeElement: LimeNamedElement): List { - val optimizedLists = when (limeElement) { - is LimeContainer -> OptimizedListsCollector().getAllOptimizedLists(limeElement) - else -> emptyMap() - } + val optimizedLists = + when (limeElement) { + is LimeContainer -> OptimizedListsCollector().getAllOptimizedLists(limeElement) + else -> emptyMap() + } return when { limeElement is LimeStruct && (limeElement.functions.isNotEmpty() || optimizedLists.isNotEmpty()) -> generateFilesForElement(limeElement, optimizedLists) @@ -91,31 +93,36 @@ internal class JniTemplates( private fun generateFilesForElement( limeElement: LimeNamedElement, - optimizedLists: Map> + optimizedLists: Map>, ): List { val containerData = mutableMapOf("container" to limeElement, "internalNamespace" to internalNamespace) val fileName = fileNameRules.getElementFileName(limeElement) - val headerFile = GeneratedFile( - TemplateEngine.render("jni/Header", containerData, nameResolvers, generatorPredicates.predicates), - fileNameRules.getHeaderFilePath(fileName) - ) + val headerFile = + GeneratedFile( + TemplateEngine.render("jni/Header", containerData, nameResolvers, generatorPredicates.predicates), + fileNameRules.getHeaderFilePath(fileName), + ) val implIncludes = jniIncludeCollector.collectImports(limeElement) + Include.createInternalInclude("$fileName.h") containerData["includes"] = implIncludes.distinct().sorted() + listOfNotNull(JniIncludeResolver.exceptionThrowerInclude.takeIf { hasThrowingFunctions(limeElement) }) - val implFile = GeneratedFile( - TemplateEngine.render("jni/Implementation", containerData, nameResolvers, generatorPredicates.predicates), - fileNameRules.getImplementationFilePath(fileName) - ) + val implFile = + GeneratedFile( + TemplateEngine.render("jni/Implementation", containerData, nameResolvers, generatorPredicates.predicates), + fileNameRules.getImplementationFilePath(fileName), + ) return listOf(headerFile, implFile) + optimizedLists.keys.flatMap { generateOptimizedListFiles(limeReferenceMap[it], optimizedLists[it]) } } - private fun generateOptimizedListFiles(limeElement: LimeElement?, lists: List?): List { + private fun generateOptimizedListFiles( + limeElement: LimeElement?, + lists: List?, + ): List { if (limeElement !is LimeNamedElement || lists.isNullOrEmpty()) return emptyList() val containerFileName = fileNameRules.getElementFileName(limeElement) @@ -127,36 +134,39 @@ internal class JniTemplates( private fun generateOptimizedListFile( limeList: LimeList, containerFileName: String, - containerData: MutableMap + containerData: MutableMap, ): List { val elementFileNamePrefix = limeList.elementType.type.actualType.name val fileName = "${containerFileName}_${elementFileNamePrefix}LazyNativeList" containerData["listType"] = LimeDirectTypeRef(limeList, attributes = optimizedAttributes) containerData["elementType"] = limeList.elementType - val headerFile = GeneratedFile( - TemplateEngine.render( - "jni/LazyNativeListHeader", - containerData, - nameResolvers, - generatorPredicates.predicates - ), - fileNameRules.getHeaderFilePath(fileName) - ) + val headerFile = + GeneratedFile( + TemplateEngine.render( + "jni/LazyNativeListHeader", + containerData, + nameResolvers, + generatorPredicates.predicates, + ), + fileNameRules.getHeaderFilePath(fileName), + ) - val implIncludes = jniIncludeResolver.resolveElementImports(limeList.elementType) + - Include.createInternalInclude("$fileName.h") + val implIncludes = + jniIncludeResolver.resolveElementImports(limeList.elementType) + + Include.createInternalInclude("$fileName.h") containerData["includes"] = implIncludes.distinct().sorted() - val implFile = GeneratedFile( - TemplateEngine.render( - "jni/LazyNativeListImpl", - containerData, - nameResolvers, - generatorPredicates.predicates - ), - fileNameRules.getImplementationFilePath(fileName) - ) + val implFile = + GeneratedFile( + TemplateEngine.render( + "jni/LazyNativeListImpl", + containerData, + nameResolvers, + generatorPredicates.predicates, + ), + fileNameRules.getImplementationFilePath(fileName), + ) return listOf(headerFile, implFile) } @@ -177,11 +187,11 @@ internal class JniTemplates( mapOf( "internalNamespace" to internalNamespace, "internalPackages" to fullInternalPackages, - "durationPackage" to (fullInternalPackages + "time").joinToString("/") - ) + "durationPackage" to (fullInternalPackages + "time").joinToString("/"), + ), ), fileNameRules.getHeaderFilePath(fileName), - GeneratedFile.SourceSet.COMMON + GeneratedFile.SourceSet.COMMON, ) fun generateConversionUtilsImplementationFile(fileName: String) = @@ -191,73 +201,81 @@ internal class JniTemplates( mapOf( "internalNamespace" to internalNamespace, "internalPackages" to fullInternalPackages, - "durationPackage" to (fullInternalPackages + "time").joinToString("/") - ) + "durationPackage" to (fullInternalPackages + "time").joinToString("/"), + ), ), fileNameRules.getImplementationFilePath(fileName), - GeneratedFile.SourceSet.COMMON + GeneratedFile.SourceSet.COMMON, ) private fun generateStructConversionFiles(limeStruct: LimeStruct): List { val fileName = fileNameRules.getConversionFileName(limeStruct) val selfInclude = Include.createInternalInclude("$fileName.h") - val fieldConversionIncludes = limeStruct.fields - .filter { generatorPredicates.shouldRetain(it) } - .flatMap { jniIncludeResolver.resolveElementImports(it) } + val fieldConversionIncludes = + limeStruct.fields + .filter { generatorPredicates.shouldRetain(it) } + .flatMap { jniIncludeResolver.resolveElementImports(it) } // Conversion includes need to be added to the header file instead of the impl file, for unity builds. - val headerIncludes = cppIncludeResolver.resolveElementImports(limeStruct).distinct().sorted() + - fieldConversionIncludes.distinct().minus(selfInclude).sorted() - - val mustacheData = mutableMapOf( - "struct" to limeStruct, - "includes" to headerIncludes, - "internalNamespace" to internalNamespace - ) - val headerFile = GeneratedFile( - TemplateEngine.render("jni/StructConversionHeader", mustacheData, nameResolvers), - fileNameRules.getHeaderFilePath(fileName) - ) + val headerIncludes = + cppIncludeResolver.resolveElementImports(limeStruct).distinct().sorted() + + fieldConversionIncludes.distinct().minus(selfInclude).sorted() + + val mustacheData = + mutableMapOf( + "struct" to limeStruct, + "includes" to headerIncludes, + "internalNamespace" to internalNamespace, + ) + val headerFile = + GeneratedFile( + TemplateEngine.render("jni/StructConversionHeader", mustacheData, nameResolvers), + fileNameRules.getHeaderFilePath(fileName), + ) mustacheData["includes"] = listOf(selfInclude) + limeStruct.fields.filter { CommonGeneratorPredicates.needsImportsForSkippedField(it, LimeAttributeType.JAVA, limeReferenceMap) }.flatMap { cppIncludeResolver.resolveElementImports(it.typeRef) } - val implFile = GeneratedFile( - TemplateEngine.render( - "jni/StructConversionImplementation", - mustacheData, - nameResolvers, - generatorPredicates.predicates - ), - fileNameRules.getImplementationFilePath(fileName) - ) + val implFile = + GeneratedFile( + TemplateEngine.render( + "jni/StructConversionImplementation", + mustacheData, + nameResolvers, + generatorPredicates.predicates, + ), + fileNameRules.getImplementationFilePath(fileName), + ) return listOf(headerFile, implFile) } private fun generateEnumConversionFiles(limeEnumeration: LimeEnumeration): List { - val mustacheData = mutableMapOf( - "enum" to limeEnumeration, - "includes" to cppIncludeResolver.resolveElementImports(limeEnumeration).distinct().sorted(), - "internalNamespace" to internalNamespace - ) + val mustacheData = + mutableMapOf( + "enum" to limeEnumeration, + "includes" to cppIncludeResolver.resolveElementImports(limeEnumeration).distinct().sorted(), + "internalNamespace" to internalNamespace, + ) val fileName = fileNameRules.getConversionFileName(limeEnumeration) - val headerFile = GeneratedFile( - TemplateEngine.render("jni/EnumConversionHeader", mustacheData, nameResolvers), - fileNameRules.getHeaderFilePath(fileName) - ) + val headerFile = + GeneratedFile( + TemplateEngine.render("jni/EnumConversionHeader", mustacheData, nameResolvers), + fileNameRules.getHeaderFilePath(fileName), + ) mustacheData["includes"] = listOf(Include.createInternalInclude("$fileName.h")) - val implFile = GeneratedFile( - TemplateEngine.render( - "jni/EnumConversionImplementation", - mustacheData, - nameResolvers, - generatorPredicates.predicates - ), - fileNameRules.getImplementationFilePath(fileName) - ) + val implFile = + GeneratedFile( + TemplateEngine.render( + "jni/EnumConversionImplementation", + mustacheData, + nameResolvers, + generatorPredicates.predicates, + ), + fileNameRules.getImplementationFilePath(fileName), + ) return listOf(headerFile, implFile) } @@ -266,26 +284,29 @@ internal class JniTemplates( val fileName = fileNameRules.getConversionFileName(limeElement) val selfInclude = Include.createInternalInclude("$fileName.h") // Conversion includes need to be added to the header file instead of the impl file, for unity builds. - val headerIncludes = cppIncludeResolver.resolveElementImports(limeElement).distinct().sorted() + - jniIncludeCollector.collectImports(limeElement).distinct().minus(selfInclude).sorted() - - val mustacheData = mutableMapOf( - "model" to limeElement, - "includes" to headerIncludes, - "basePackages" to basePackages, - "internalPackages" to fullInternalPackages, - "internalNamespace" to internalNamespace, - "descendantInterfaces" to descendantInterfaces - ) - val headerFile = GeneratedFile( - TemplateEngine.render( - "jni/InstanceConversionHeader", - mustacheData, - nameResolvers, - generatorPredicates.predicates - ), - fileNameRules.getHeaderFilePath(fileName) - ) + val headerIncludes = + cppIncludeResolver.resolveElementImports(limeElement).distinct().sorted() + + jniIncludeCollector.collectImports(limeElement).distinct().minus(selfInclude).sorted() + + val mustacheData = + mutableMapOf( + "model" to limeElement, + "includes" to headerIncludes, + "basePackages" to basePackages, + "internalPackages" to fullInternalPackages, + "internalNamespace" to internalNamespace, + "descendantInterfaces" to descendantInterfaces, + ) + val headerFile = + GeneratedFile( + TemplateEngine.render( + "jni/InstanceConversionHeader", + mustacheData, + nameResolvers, + generatorPredicates.predicates, + ), + fileNameRules.getHeaderFilePath(fileName), + ) mustacheData["includes"] = listOf(selfInclude) + when (limeElement) { @@ -293,44 +314,48 @@ internal class JniTemplates( jniIncludeResolver.resolveInstanceConversionIncludes(limeElement).sorted() else -> emptyList() } - val implFile = GeneratedFile( - TemplateEngine.render( - "jni/InstanceConversionImplementation", - mustacheData, - nameResolvers, - generatorPredicates.predicates - ), - fileNameRules.getImplementationFilePath(fileName) - ) + val implFile = + GeneratedFile( + TemplateEngine.render( + "jni/InstanceConversionImplementation", + mustacheData, + nameResolvers, + generatorPredicates.predicates, + ), + fileNameRules.getImplementationFilePath(fileName), + ) return listOf(headerFile, implFile) } private fun generateCppProxyFiles(limeElement: LimeNamedElement): List { - val mustacheData = mutableMapOf( - "container" to limeElement, - "includes" to cppIncludeResolver.resolveElementImports(limeElement).distinct().sorted(), - "internalNamespace" to internalNamespace - ) + val mustacheData = + mutableMapOf( + "container" to limeElement, + "includes" to cppIncludeResolver.resolveElementImports(limeElement).distinct().sorted(), + "internalNamespace" to internalNamespace, + ) val fileName = fileNameRules.getElementFileName(limeElement) + "CppProxy" - val headerFile = GeneratedFile( - TemplateEngine.render("jni/CppProxyHeader", mustacheData, nameResolvers, generatorPredicates.predicates), - fileNameRules.getHeaderFilePath(fileName) - ) + val headerFile = + GeneratedFile( + TemplateEngine.render("jni/CppProxyHeader", mustacheData, nameResolvers, generatorPredicates.predicates), + fileNameRules.getHeaderFilePath(fileName), + ) val selfInclude = Include.createInternalInclude("$fileName.h") val includes = jniIncludeCollector.collectImports(limeElement).distinct().minus(selfInclude).sorted() mustacheData["includes"] = listOf(selfInclude) + includes - val implFile = GeneratedFile( - TemplateEngine.render( - "jni/CppProxyImplementation", - mustacheData, - nameResolvers, - generatorPredicates.predicates - ), - fileNameRules.getImplementationFilePath(fileName) - ) + val implFile = + GeneratedFile( + TemplateEngine.render( + "jni/CppProxyImplementation", + mustacheData, + nameResolvers, + generatorPredicates.predicates, + ), + fileNameRules.getImplementationFilePath(fileName), + ) return listOf(headerFile, implFile) } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/jni/JniTypeSignatureNameResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/jni/JniTypeSignatureNameResolver.kt index 9d418ac5c7..b686afa0bb 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/jni/JniTypeSignatureNameResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/jni/JniTypeSignatureNameResolver.kt @@ -31,7 +31,6 @@ internal class JniTypeSignatureNameResolver( private val baseNameResolver: JniNameResolver, private val internalPackages: List, ) : NameResolver { - override fun resolveName(element: Any) = when (element) { is LimeType -> resolveTypeSignature(element) diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftCommentsProcessor.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftCommentsProcessor.kt index a5be7244c9..d40ecf08f1 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftCommentsProcessor.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftCommentsProcessor.kt @@ -31,8 +31,11 @@ import com.vladsch.flexmark.util.sequence.CharSubSequence * Parse markdown comments and process links */ class SwiftCommentsProcessor(werror: Boolean) : CommentsProcessor(Formatter.builder(formatterOptions).build(), werror) { - - override fun processLink(linkNode: LinkRef, linkReference: String, limeFullName: String) { + override fun processLink( + linkNode: LinkRef, + linkReference: String, + limeFullName: String, + ) { linkNode.reference = CharSubSequence.of(linkReference) linkNode.referenceOpeningMarker = CharSubSequence.of("`") linkNode.referenceClosingMarker = CharSubSequence.of("`") @@ -46,8 +49,9 @@ class SwiftCommentsProcessor(werror: Boolean) : CommentsProcessor(Formatter.buil override val nullReference = "nil" companion object { - private val formatterOptions = MutableDataSet() - .set(Formatter.FORMATTER_EMULATION_PROFILE, ParserEmulationProfile.PEGDOWN) - .toImmutable() + private val formatterOptions = + MutableDataSet() + .set(Formatter.FORMATTER_EMULATION_PROFILE, ParserEmulationProfile.PEGDOWN) + .toImmutable() } } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftFieldsValidator.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftFieldsValidator.kt index 8ca681549b..ce71700494 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftFieldsValidator.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftFieldsValidator.kt @@ -28,7 +28,6 @@ import com.here.gluecodium.model.lime.LimeField * Validate that all deprecated fields have default values. */ internal class SwiftFieldsValidator(private val logger: LimeLogger) { - fun validate(limeElements: Collection): Boolean { val validationResults = limeElements.filterIsInstance().map { validateField(it) } return !validationResults.contains(false) diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftGenerator.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftGenerator.kt index a082cec26b..c012960cf4 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftGenerator.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftGenerator.kt @@ -59,7 +59,6 @@ import java.util.logging.Logger * Generates Swift bindings on top of C++ API. */ internal class SwiftGenerator : Generator { - private lateinit var internalNamespace: List private lateinit var rootNamespace: List private lateinit var commentsProcessor: CommentsProcessor @@ -76,7 +75,7 @@ internal class SwiftGenerator : Generator { collectOwnImports = true, parentTypeFilter = { true }, collectTypeAliasImports = true, - collectValueImports = true + collectValueImports = true, ) override val shortName = "swift" @@ -94,10 +93,12 @@ internal class SwiftGenerator : Generator { } override fun generate(limeModel: LimeModel): List { - val cbridgeFilteredModel = LimeModelFilter - .filter(limeModel) { LimeModelSkipPredicates.shouldRetainElement(it, activeTags, SWIFT, retainFunctionsAndFields = true) } - val swiftFilteredModel = LimeModelFilter - .filter(limeModel) { LimeModelSkipPredicates.shouldRetainElement(it, activeTags, SWIFT, retainFunctionsAndFields = false) } + val cbridgeFilteredModel = + LimeModelFilter + .filter(limeModel) { LimeModelSkipPredicates.shouldRetainElement(it, activeTags, SWIFT, retainFunctionsAndFields = true) } + val swiftFilteredModel = + LimeModelFilter + .filter(limeModel) { LimeModelSkipPredicates.shouldRetainElement(it, activeTags, SWIFT, retainFunctionsAndFields = false) } val limeLogger = LimeLogger(logger, limeModel.fileNameMap) val swiftSignatureResolver = SwiftSignatureResolver(cbridgeFilteredModel.referenceMap, nameRules, activeTags) @@ -105,11 +106,12 @@ internal class SwiftGenerator : Generator { LimeOverloadsValidator(swiftSignatureResolver, limeLogger, validateCustomConstructors = true) val weakPropertiesValidator = SwiftWeakAttributeValidator(limeLogger) val fieldsValidator = SwiftFieldsValidator(limeLogger) - val validationResults = listOf( - overloadsValidator.validate(cbridgeFilteredModel.referenceMap.values), - weakPropertiesValidator.validate(cbridgeFilteredModel.referenceMap.values), - fieldsValidator.validate(cbridgeFilteredModel.referenceMap.values) - ) + val validationResults = + listOf( + overloadsValidator.validate(cbridgeFilteredModel.referenceMap.values), + weakPropertiesValidator.validate(cbridgeFilteredModel.referenceMap.values), + fieldsValidator.validate(cbridgeFilteredModel.referenceMap.values), + ) if (validationResults.contains(false)) { throw GluecodiumExecutionException("Validation errors found, see log for details.") } @@ -118,29 +120,32 @@ internal class SwiftGenerator : Generator { PlatformSignatureResolver(cbridgeFilteredModel.referenceMap, SWIFT, nameRules, activeTags) val cbridgeNameResolver = CBridgeNameResolver(cbridgeFilteredModel.referenceMap, nameRules, internalPrefix ?: "", cbridgeSignatureResolver) - val cBridgeGenerator = CBridgeGenerator( - limeReferenceMap = cbridgeFilteredModel.referenceMap, - rootNamespace = rootNamespace, - nameCache = CppNameCache(rootNamespace, cbridgeFilteredModel.referenceMap, cppNameRules), - internalNamespace = internalNamespace, - cppNameRules = cppNameRules, - nameResolver = cbridgeNameResolver, - activeTags = activeTags - ) + val cBridgeGenerator = + CBridgeGenerator( + limeReferenceMap = cbridgeFilteredModel.referenceMap, + rootNamespace = rootNamespace, + nameCache = CppNameCache(rootNamespace, cbridgeFilteredModel.referenceMap, cppNameRules), + internalNamespace = internalNamespace, + cppNameRules = cppNameRules, + nameResolver = cbridgeNameResolver, + activeTags = activeTags, + ) val swiftNameResolver = SwiftNameResolver(limeModel.referenceMap, nameRules, limeLogger, commentsProcessor, swiftSignatureResolver) - val nameResolvers = mapOf( - "" to swiftNameResolver, - "CBridge" to cbridgeNameResolver, - "mangled" to SwiftMangledNameResolver(swiftNameResolver), - "visibility" to SwiftVisibilityResolver(swiftFilteredModel.referenceMap) - ) + val nameResolvers = + mapOf( + "" to swiftNameResolver, + "CBridge" to cbridgeNameResolver, + "mangled" to SwiftMangledNameResolver(swiftNameResolver), + "visibility" to SwiftVisibilityResolver(swiftFilteredModel.referenceMap), + ) val predicates = SwiftGeneratorPredicates(nameRules, swiftSignatureResolver, swiftFilteredModel.referenceMap) val descendantInterfaces = LimeTypeHelper.collectDescendantInterfaces(swiftFilteredModel.topElements) - val swiftFiles = swiftFilteredModel.topElements.map { - generateSwiftFile(it, nameResolvers, predicates, descendantInterfaces) - } + val swiftFiles = + swiftFilteredModel.topElements.map { + generateSwiftFile(it, nameResolvers, predicates, descendantInterfaces) + } if (commentsProcessor.hasError) { throw GluecodiumExecutionException("Validation errors found, see log for details.") } @@ -153,7 +158,7 @@ internal class SwiftGenerator : Generator { cBridgeGenerator.genericTypesCollector, swiftNameResolver, nameResolvers, - predicates + predicates, ) + generateBuiltinOptionals(nameResolvers + ("C++" to cBridgeGenerator.cppNameResolver)) + cBridgeGenerator.generateHelpers() + generateRefHolder() @@ -163,24 +168,24 @@ internal class SwiftGenerator : Generator { limeElement: LimeNamedElement, nameResolvers: Map, predicates: SwiftGeneratorPredicates, - descendantInterfaces: Map> + descendantInterfaces: Map>, ): GeneratedFile { - val imports = importsCollector.collectImports(limeElement) val allExceptions = LimeTypeHelper.getAllTypes(limeElement).filterIsInstance() - val templateData = mapOf( - "model" to limeElement, - "internalPrefix" to internalPrefix, - "imports" to imports.distinct().sorted() - FOUNDATION, - "allExceptions" to allExceptions, - "definitionTemplate" to selectDefinitionTemplate(limeElement), - "conversionTemplate" to selectConversionTemplate(limeElement), - "conversionVisibility" to conversionVisibility, - "descendantInterfaces" to descendantInterfaces - ) + val templateData = + mapOf( + "model" to limeElement, + "internalPrefix" to internalPrefix, + "imports" to imports.distinct().sorted() - FOUNDATION, + "allExceptions" to allExceptions, + "definitionTemplate" to selectDefinitionTemplate(limeElement), + "conversionTemplate" to selectConversionTemplate(limeElement), + "conversionVisibility" to conversionVisibility, + "descendantInterfaces" to descendantInterfaces, + ) return GeneratedFile( TemplateEngine.render("swift/SwiftFile", templateData, nameResolvers, predicates.predicates), - nameRules.getImplementationFileName(limeElement) + nameRules.getImplementationFileName(limeElement), ) } @@ -189,37 +194,39 @@ internal class SwiftGenerator : Generator { genericTypesCollector: CBridgeGenerator.GenericTypesCollector, swiftNameResolver: SwiftNameResolver, nameResolvers: Map, - predicates: SwiftGeneratorPredicates + predicates: SwiftGeneratorPredicates, ): List { - val allTypes = limeModel.flatMap { LimeTypeHelper.getAllTypes(it) } val allParentTypes = LimeTypeHelper.getAllParentTypes(allTypes) val genericTypes = genericTypesCollector.getAllGenericTypes(allTypes + allParentTypes) - val listsFile = generateCollectionsFile( - genericTypes.filterIsInstance(), - "swift/SwiftLists", - "swift/Collections.swift", - swiftNameResolver, - nameResolvers, - predicates - ) - val mapsFile = generateCollectionsFile( - genericTypes.filterIsInstance(), - "swift/SwiftMaps", - "swift/Dictionaries.swift", - swiftNameResolver, - nameResolvers, - predicates - ) - val setsFile = generateCollectionsFile( - genericTypes.filterIsInstance(), - "swift/SwiftSets", - "swift/Sets.swift", - swiftNameResolver, - nameResolvers, - predicates - ) + val listsFile = + generateCollectionsFile( + genericTypes.filterIsInstance(), + "swift/SwiftLists", + "swift/Collections.swift", + swiftNameResolver, + nameResolvers, + predicates, + ) + val mapsFile = + generateCollectionsFile( + genericTypes.filterIsInstance(), + "swift/SwiftMaps", + "swift/Dictionaries.swift", + swiftNameResolver, + nameResolvers, + predicates, + ) + val setsFile = + generateCollectionsFile( + genericTypes.filterIsInstance(), + "swift/SwiftSets", + "swift/Sets.swift", + swiftNameResolver, + nameResolvers, + predicates, + ) return listOf(listsFile, mapsFile, setsFile) } @@ -230,24 +237,26 @@ internal class SwiftGenerator : Generator { fileName: String, swiftNameResolver: SwiftNameResolver, nameResolvers: Map, - predicates: SwiftGeneratorPredicates + predicates: SwiftGeneratorPredicates, ): GeneratedFile { val imports = collections.flatMap { importsCollector.collectImports(it) } - val templateData = mapOf( - "imports" to imports.sorted().distinct() - FOUNDATION, - "internalPrefix" to internalPrefix, - "collections" to collections.sortedBy { swiftNameResolver.resolveName(it) } - ) + val templateData = + mapOf( + "imports" to imports.sorted().distinct() - FOUNDATION, + "internalPrefix" to internalPrefix, + "collections" to collections.sortedBy { swiftNameResolver.resolveName(it) }, + ) val content = TemplateEngine.render(templateName, templateData, nameResolvers, predicates.predicates) return GeneratedFile(content, fileName) } private fun generateBuiltinOptionals(nameResolvers: Map): GeneratedFile { - val types = listOf( - TypeId.BOOLEAN, TypeId.FLOAT, TypeId.DOUBLE, - TypeId.INT8, TypeId.UINT8, TypeId.INT16, TypeId.UINT16, - TypeId.INT32, TypeId.UINT32, TypeId.INT64, TypeId.UINT64 - ) + val types = + listOf( + TypeId.BOOLEAN, TypeId.FLOAT, TypeId.DOUBLE, + TypeId.INT8, TypeId.UINT8, TypeId.INT16, TypeId.UINT16, + TypeId.INT32, TypeId.UINT32, TypeId.INT64, TypeId.UINT64, + ) val content = TemplateEngine.render("swift/BuiltinOptionals", types, nameResolvers) return GeneratedFile(content, "swift/BuiltinOptionals.swift", GeneratedFile.SourceSet.COMMON) @@ -291,7 +300,7 @@ internal class SwiftGenerator : Generator { listOf( Generator.copyCommonFile("swift/BuiltinConversions.swift", ""), Generator.copyCommonFile("swift/CollectionOf.swift", ""), - Generator.copyCommonFile("swift/NativeBase.swift", "") + Generator.copyCommonFile("swift/NativeBase.swift", ""), ) } } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftGeneratorPredicates.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftGeneratorPredicates.kt index b3cd4a849d..f56a289fad 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftGeneratorPredicates.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftGeneratorPredicates.kt @@ -46,83 +46,89 @@ import com.here.gluecodium.model.lime.LimeTypeRef internal class SwiftGeneratorPredicates( nameRules: SwiftNameRules, private val signatureResolver: SwiftSignatureResolver, - private val limeReferenceMap: Map + private val limeReferenceMap: Map, ) { - val predicates = mapOf( - "hasAnyComment" to { limeElement: Any -> - CommonGeneratorPredicates.hasAnyComment(limeElement, "Swift") - }, - "hasCppTypeAttribute" to { limeGenericType: Any -> - when (limeGenericType) { - is LimeList -> hasCppTypeAttribute(limeGenericType.elementType) - is LimeSet -> hasCppTypeAttribute(limeGenericType.elementType) - is LimeMap -> - hasCppTypeAttribute(limeGenericType.keyType) || hasCppTypeAttribute(limeGenericType.valueType) - else -> false - } - }, - "hasDeprecatedEnumerators" to { limeEnumeration: Any -> - limeEnumeration is LimeEnumeration && - limeEnumeration.enumerators.any { it.attributes.have(LimeAttributeType.DEPRECATED) } - }, - "hasDurationType" to { limeGenericType: Any -> - when (limeGenericType) { - is LimeList -> hasDurationType(limeGenericType.elementType) - is LimeSet -> hasDurationType(limeGenericType.elementType) - is LimeMap -> hasDurationType(limeGenericType.keyType) || hasDurationType(limeGenericType.valueType) - else -> false - } - }, - "hasInternalAvailableFields" to { limeStruct: Any -> - limeStruct is LimeStruct && limeStruct.availableFields.isNotEmpty() && - limeStruct.availableFields.any { CommonGeneratorPredicates.isInternal(it, SWIFT) } - }, - "hasInternalFields" to { limeStruct: Any -> - limeStruct is LimeStruct && limeStruct.fields.isNotEmpty() && - limeStruct.fields.any { CommonGeneratorPredicates.isInternal(it, SWIFT) } - }, - "hasTypeRepository" to { CommonGeneratorPredicates.hasTypeRepository(it) }, - "isInternal" to { it is LimeNamedElement && CommonGeneratorPredicates.isInternal(it, SWIFT) }, - "isNestedInternal" to { limeElement: Any -> - limeElement is LimeNamedElement && generateSequence(limeElement) { - limeReferenceMap[it.path.parent.toString()] as? LimeNamedElement - }.any { CommonGeneratorPredicates.isInternal(it, SWIFT) } - }, - "isOverriding" to { limeFunction: Any -> - limeFunction is LimeFunction && limeFunction.isConstructor && - signatureResolver.isOverloadingConstructor(limeFunction) - }, - "isPublic" to { it is LimeNamedElement && !CommonGeneratorPredicates.isInternal(it, SWIFT) }, - "isRefEquatable" to { limeField: Any -> - limeField is LimeField && isRefEquatable(limeField) - }, - "needsAllFieldsConstructor" to { limeStruct: Any -> - when { - limeStruct !is LimeStruct -> false - limeStruct.fieldConstructors.isEmpty() -> true - limeStruct.attributes.have(LimeAttributeType.IMMUTABLE) -> limeStruct.allFieldsConstructor == null - else -> false - } - }, - "needsExplicitHashable" to { limeStruct: Any -> - limeStruct is LimeStruct && limeStruct.attributes.have(LimeAttributeType.EQUATABLE) && - limeStruct.fields.any { isRefEquatable(it) } - }, - "needsReducedConstructor" to fun(limeStruct: Any): Boolean { - if (limeStruct !is LimeStruct) return false - val internalFields = limeStruct.fields.filter { CommonGeneratorPredicates.isInternal(it, SWIFT) } - return internalFields.isNotEmpty() && internalFields.all { it.defaultValue != null } - }, - "skipDeclaration" to fun(limeType: Any): Boolean { - if (limeType !is LimeType) return false - val externalDescriptor = limeType.external?.swift - return externalDescriptor != null && externalDescriptor[LimeExternalDescriptor.CONVERTER_NAME] == null - }, - "skipTypeAlias" to { limeException: Any -> - limeException is LimeException && - nameRules.getName(limeException) == nameRules.getName(limeException.errorType.type) - } - ) + val predicates = + mapOf( + "hasAnyComment" to { limeElement: Any -> + CommonGeneratorPredicates.hasAnyComment(limeElement, "Swift") + }, + "hasCppTypeAttribute" to { limeGenericType: Any -> + when (limeGenericType) { + is LimeList -> hasCppTypeAttribute(limeGenericType.elementType) + is LimeSet -> hasCppTypeAttribute(limeGenericType.elementType) + is LimeMap -> + hasCppTypeAttribute(limeGenericType.keyType) || hasCppTypeAttribute(limeGenericType.valueType) + else -> false + } + }, + "hasDeprecatedEnumerators" to { limeEnumeration: Any -> + limeEnumeration is LimeEnumeration && + limeEnumeration.enumerators.any { it.attributes.have(LimeAttributeType.DEPRECATED) } + }, + "hasDurationType" to { limeGenericType: Any -> + when (limeGenericType) { + is LimeList -> hasDurationType(limeGenericType.elementType) + is LimeSet -> hasDurationType(limeGenericType.elementType) + is LimeMap -> hasDurationType(limeGenericType.keyType) || hasDurationType(limeGenericType.valueType) + else -> false + } + }, + "hasInternalAvailableFields" to { limeStruct: Any -> + limeStruct is LimeStruct && limeStruct.availableFields.isNotEmpty() && + limeStruct.availableFields.any { CommonGeneratorPredicates.isInternal(it, SWIFT) } + }, + "hasInternalFields" to { limeStruct: Any -> + limeStruct is LimeStruct && limeStruct.fields.isNotEmpty() && + limeStruct.fields.any { CommonGeneratorPredicates.isInternal(it, SWIFT) } + }, + "hasTypeRepository" to { CommonGeneratorPredicates.hasTypeRepository(it) }, + "isInternal" to { it is LimeNamedElement && CommonGeneratorPredicates.isInternal(it, SWIFT) }, + "isNestedInternal" to { limeElement: Any -> + limeElement is LimeNamedElement && + generateSequence(limeElement) { + limeReferenceMap[it.path.parent.toString()] as? LimeNamedElement + }.any { CommonGeneratorPredicates.isInternal(it, SWIFT) } + }, + "isOverriding" to { limeFunction: Any -> + limeFunction is LimeFunction && limeFunction.isConstructor && + signatureResolver.isOverloadingConstructor(limeFunction) + }, + "isPublic" to { it is LimeNamedElement && !CommonGeneratorPredicates.isInternal(it, SWIFT) }, + "isRefEquatable" to { limeField: Any -> + limeField is LimeField && isRefEquatable(limeField) + }, + "needsAllFieldsConstructor" to { limeStruct: Any -> + when { + limeStruct !is LimeStruct -> false + limeStruct.fieldConstructors.isEmpty() -> true + limeStruct.attributes.have(LimeAttributeType.IMMUTABLE) -> limeStruct.allFieldsConstructor == null + else -> false + } + }, + "needsExplicitHashable" to { limeStruct: Any -> + limeStruct is LimeStruct && limeStruct.attributes.have(LimeAttributeType.EQUATABLE) && + limeStruct.fields.any { isRefEquatable(it) } + }, + "needsReducedConstructor" to + + fun(limeStruct: Any): Boolean { + if (limeStruct !is LimeStruct) return false + val internalFields = limeStruct.fields.filter { CommonGeneratorPredicates.isInternal(it, SWIFT) } + return internalFields.isNotEmpty() && internalFields.all { it.defaultValue != null } + }, + "skipDeclaration" to + + fun(limeType: Any): Boolean { + if (limeType !is LimeType) return false + val externalDescriptor = limeType.external?.swift + return externalDescriptor != null && externalDescriptor[LimeExternalDescriptor.CONVERTER_NAME] == null + }, + "skipTypeAlias" to { limeException: Any -> + limeException is LimeException && + nameRules.getName(limeException) == nameRules.getName(limeException.errorType.type) + }, + ) private fun isRefEquatable(limeField: LimeField): Boolean { val limeType = limeField.typeRef.type.actualType diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftImportsResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftImportsResolver.kt index a8e3cc2466..91be847d5c 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftImportsResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftImportsResolver.kt @@ -31,7 +31,6 @@ import com.here.gluecodium.model.lime.LimeTypeRef import com.here.gluecodium.model.lime.LimeValue internal class SwiftImportsResolver : ImportsResolver { - override fun resolveElementImports(limeElement: LimeElement): List = when (limeElement) { is LimeTypeRef -> resolveElementImports(limeElement.type) diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftMangledNameResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftMangledNameResolver.kt index af00d46196..7bb790b524 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftMangledNameResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftMangledNameResolver.kt @@ -25,7 +25,6 @@ import com.here.gluecodium.model.lime.LimeType import com.here.gluecodium.model.lime.LimeTypeRef internal class SwiftMangledNameResolver(private val baseNameResolver: SwiftNameResolver) : NameResolver { - override fun resolveName(element: Any): String = when (element) { is LimeTypeRef -> resolveTypeName(element.type.actualType) diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftNameResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftNameResolver.kt index 0c1aa7dea1..7788f8b54c 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftNameResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftNameResolver.kt @@ -60,9 +60,8 @@ internal class SwiftNameResolver( private val nameRules: SwiftNameRules, private val limeLogger: LimeLogger, private val commentsProcessor: CommentsProcessor, - private val signatureResolver: SwiftSignatureResolver + private val signatureResolver: SwiftSignatureResolver, ) : ReferenceMapBasedResolver(limeReferenceMap), NameResolver { - private val limeToSwiftNames = buildPathMap() override fun resolveName(element: Any): String = @@ -164,15 +163,16 @@ internal class SwiftNameResolver( } private fun resolveDurationValue(limeValue: LimeValue.Duration): String { - val multiplier = when (limeValue.timeUnit) { - TimeUnit.DAY -> 3600 * 24 - TimeUnit.HOUR -> 3600 - TimeUnit.MINUTE -> 60 - TimeUnit.SECOND -> null - TimeUnit.MILLISECOND -> 1e-3 - TimeUnit.MICROSECOND -> 1e-6 - TimeUnit.NANOSECOND -> 1e-9 - } + val multiplier = + when (limeValue.timeUnit) { + TimeUnit.DAY -> 3600 * 24 + TimeUnit.HOUR -> 3600 + TimeUnit.MINUTE -> 60 + TimeUnit.SECOND -> null + TimeUnit.MILLISECOND -> 1e-3 + TimeUnit.MICROSECOND -> 1e-6 + TimeUnit.NANOSECOND -> 1e-9 + } val multiplierSuffix = multiplier?.let { " * $it" } ?: "" return limeValue.value + multiplierSuffix } @@ -212,8 +212,9 @@ internal class SwiftNameResolver( private fun resolveFullName(limeElement: LimeNamedElement) = getNestedNames(limeElement).joinToString(".") private fun getNestedNames(limeElement: LimeNamedElement): List { - val parentElement = limeReferenceMap.takeIf { limeElement.path.hasParent } - ?.get(limeElement.path.parent.toString()) as? LimeNamedElement + val parentElement = + limeReferenceMap.takeIf { limeElement.path.hasParent } + ?.get(limeElement.path.parent.toString()) as? LimeNamedElement val name = if (limeElement is LimeFunction && limeElement.isConstructor) "init" else resolveName(limeElement) return when { @@ -232,19 +233,21 @@ internal class SwiftNameResolver( } private fun buildPathMap(): Map { - val result = limeReferenceMap.values - .filterIsInstance() - .filterNot { it is LimeParameter } - .associateBy({ it.path.toAmbiguousString() }, { resolveFullName(it) }) - .toMutableMap() + val result = + limeReferenceMap.values + .filterIsInstance() + .filterNot { it is LimeParameter } + .associateBy({ it.path.toAmbiguousString() }, { resolveFullName(it) }) + .toMutableMap() limeReferenceMap.values.filterIsInstance().forEach { function -> val ambiguousKey = function.path.toAmbiguousString() val functionCommentRef = resolveCommentRef(function, signatureResolver) result[ambiguousKey] = functionCommentRef - val unambiguousKey = ambiguousKey + - function.parameters.joinToString(prefix = "(", postfix = ")", separator = ",") { it.typeRef.toString() } + val unambiguousKey = + ambiguousKey + + function.parameters.joinToString(prefix = "(", postfix = ")", separator = ",") { it.typeRef.toString() } result[unambiguousKey] = functionCommentRef result += function.parameters.associateBy({ it.fullName }, { "$functionCommentRef.${resolveName(it)}" }) @@ -252,18 +255,23 @@ internal class SwiftNameResolver( val properties = limeReferenceMap.values.filterIsInstance() result += properties.associateBy({ it.path.toAmbiguousString() + ".get" }, { resolveFullName(it) }) - result += properties.filter { it.setter != null } - .associateBy({ it.path.toAmbiguousString() + ".set" }, { resolveFullName(it) }) + result += + properties.filter { it.setter != null } + .associateBy({ it.path.toAmbiguousString() + ".set" }, { resolveFullName(it) }) return result } - private fun resolveCommentRef(limeFunction: LimeFunction, signatureResolver: SwiftSignatureResolver): String { + private fun resolveCommentRef( + limeFunction: LimeFunction, + signatureResolver: SwiftSignatureResolver, + ): String { val fullName = resolveFullName(limeFunction) - return fullName + when { - signatureResolver.isOverloaded(limeFunction) -> - limeFunction.parameters.joinToString(prefix = "(", postfix = ")") { resolveTypeRefName(it.typeRef) } - else -> "(...)" - } + return fullName + + when { + signatureResolver.isOverloaded(limeFunction) -> + limeFunction.parameters.joinToString(prefix = "(", postfix = ")") { resolveTypeRefName(it.typeRef) } + else -> "(...)" + } } } diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftNameRules.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftNameRules.kt index 35a4cf9e27..2598a29762 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftNameRules.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftNameRules.kt @@ -29,19 +29,16 @@ import com.here.gluecodium.model.lime.LimeProperty import java.io.File class SwiftNameRules(nameRuleSet: NameRuleSet) : NameRules(nameRuleSet) { - override fun getName(limeElement: LimeElement) = - getPlatformName(limeElement as? LimeNamedElement) ?: super.getName(limeElement) + override fun getName(limeElement: LimeElement) = getPlatformName(limeElement as? LimeNamedElement) ?: super.getName(limeElement) - override fun getPropertyName(limeProperty: LimeProperty) = - getPlatformName(limeProperty) ?: super.getPropertyName(limeProperty) + override fun getPropertyName(limeProperty: LimeProperty) = getPlatformName(limeProperty) ?: super.getPropertyName(limeProperty) fun getImplementationFileName(limeElement: LimeNamedElement): String { return TARGET_DIRECTORY + limeElement.path.head.joinToString(File.separator) + File.separator + getName(limeElement) + ".swift" } - private fun getPlatformName(limeElement: LimeNamedElement?) = - limeElement?.attributes?.get(SWIFT, NAME) + private fun getPlatformName(limeElement: LimeNamedElement?) = limeElement?.attributes?.get(SWIFT, NAME) companion object { val TARGET_DIRECTORY = "swift" + File.separator diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftSignatureResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftSignatureResolver.kt index f20f668134..86904046cb 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftSignatureResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftSignatureResolver.kt @@ -28,9 +28,8 @@ import com.here.gluecodium.model.lime.LimeParameter internal class SwiftSignatureResolver( limeReferenceMap: Map, nameRules: SwiftNameRules, - activeTags: Set + activeTags: Set, ) : PlatformSignatureResolver(limeReferenceMap, LimeAttributeType.SWIFT, nameRules, activeTags) { - fun isOverloadingConstructor(limeFunction: LimeFunction): Boolean { val container = getContainer(limeFunction) ?: return false val allFunctions = getOwnFunctions(container) + getParentFunctions(container) diff --git a/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftVisibilityResolver.kt b/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftVisibilityResolver.kt index 5a3699b064..82f2f0ad88 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftVisibilityResolver.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/generator/swift/SwiftVisibilityResolver.kt @@ -31,7 +31,6 @@ import com.here.gluecodium.model.lime.LimeType internal class SwiftVisibilityResolver(limeReferenceMap: Map) : ReferenceMapBasedResolver(limeReferenceMap), NameResolver { - override fun resolveName(element: Any): String = when (element) { // Swift protocols have no type nesting, so all their types are "outside". @@ -40,11 +39,13 @@ internal class SwiftVisibilityResolver(limeReferenceMap: Map): Boolean { - val validationResults = limeElements.filterIsInstance().map { validateProperty(it) } + - limeElements.filterIsInstance().map { validateInterface(it) } + val validationResults = + limeElements.filterIsInstance().map { validateProperty(it) } + + limeElements.filterIsInstance().map { validateInterface(it) } return !validationResults.contains(false) } @@ -50,7 +50,7 @@ internal class SwiftWeakAttributeValidator(private val logger: LimeLogger) { !actualType.attributes.have(SWIFT, WEAK) -> { logger.error( limeProperty, - "An interface type held by `@Swift(Weak)` property should be marked with `@Swift(Weak) as well." + "An interface type held by `@Swift(Weak)` property should be marked with `@Swift(Weak) as well.", ) false } @@ -58,7 +58,7 @@ internal class SwiftWeakAttributeValidator(private val logger: LimeLogger) { logger.error( limeProperty, "An interface type held by `@Swift(Weak)` property can only have function or properties " + - "that return nullable values (or `void`)." + "that return nullable values (or `void`).", ) false } @@ -73,7 +73,7 @@ internal class SwiftWeakAttributeValidator(private val logger: LimeLogger) { logger.error( limeInterface, "An interface marked as `@Swift(Weak)` can only have function or properties " + - "that return nullable values (or `void`)." + "that return nullable values (or `void`).", ) false } diff --git a/gluecodium/src/main/java/com/here/gluecodium/validator/LimeAsyncValidator.kt b/gluecodium/src/main/java/com/here/gluecodium/validator/LimeAsyncValidator.kt index f7f5258ef1..25a318cb43 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/validator/LimeAsyncValidator.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/validator/LimeAsyncValidator.kt @@ -33,7 +33,6 @@ import com.here.gluecodium.model.lime.LimeProperty * Validates the correct usage of `@Async` attribute. */ internal class LimeAsyncValidator(private val logger: LimeLogger) { - fun validate(limeModel: LimeModel): Boolean { val allElements = limeModel.referenceMap.values val containers = allElements.filterIsInstance() @@ -45,26 +44,29 @@ internal class LimeAsyncValidator(private val logger: LimeLogger) { return !validationResults.contains(false) } - private fun validateContainer(limeContainer: LimeContainer) = - limeContainer.functions.map { validateFunction(it, limeContainer) } + private fun validateContainer(limeContainer: LimeContainer) = limeContainer.functions.map { validateFunction(it, limeContainer) } - private fun validateFunction(limeFunction: LimeFunction, limeContainer: LimeContainer) = - when { - !limeFunction.attributes.have(ASYNC) -> true - limeContainer is LimeInterface -> { - logger.error(limeFunction, "`@Async` attribute cannot be used in interfaces") - false - } - limeFunction.isConstructor -> { - logger.error(limeFunction, "`@Async` attribute cannot be used on constructors") - false - } - else -> true + private fun validateFunction( + limeFunction: LimeFunction, + limeContainer: LimeContainer, + ) = when { + !limeFunction.attributes.have(ASYNC) -> true + limeContainer is LimeInterface -> { + logger.error(limeFunction, "`@Async` attribute cannot be used in interfaces") + false + } + limeFunction.isConstructor -> { + logger.error(limeFunction, "`@Async` attribute cannot be used on constructors") + false } + else -> true + } private fun validateNonFunction(limeElement: LimeNamedElement) = if (limeElement.attributes.have(ASYNC)) { logger.error(limeElement, "`@Async` attribute can only be used on functions") false - } else true + } else { + true + } } diff --git a/gluecodium/src/main/java/com/here/gluecodium/validator/LimeConstantRefsValidator.kt b/gluecodium/src/main/java/com/here/gluecodium/validator/LimeConstantRefsValidator.kt index c05a350bcb..9026be8051 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/validator/LimeConstantRefsValidator.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/validator/LimeConstantRefsValidator.kt @@ -32,10 +32,12 @@ import com.here.gluecodium.model.lime.LimeValue */ internal class LimeConstantRefsValidator(private val logger: LimeLogger) : LimeValuesVisitor() { - fun validate(limeModel: LimeModel) = !traverseModel(limeModel).contains(false) - override fun visitValue(parentElement: LimeNamedElement, limeValue: LimeValue?): Boolean { + override fun visitValue( + parentElement: LimeNamedElement, + limeValue: LimeValue?, + ): Boolean { if (limeValue !is LimeValue.Constant) { return true } diff --git a/gluecodium/src/main/java/com/here/gluecodium/validator/LimeExternalTypesValidator.kt b/gluecodium/src/main/java/com/here/gluecodium/validator/LimeExternalTypesValidator.kt index 8aba937d5d..2448de56ed 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/validator/LimeExternalTypesValidator.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/validator/LimeExternalTypesValidator.kt @@ -34,7 +34,6 @@ import com.here.gluecodium.model.lime.LimeNamedElement * * Should not have "@Cpp(Name)" attribute. */ internal class LimeExternalTypesValidator(private val logger: LimeLogger) { - fun validate(limeModel: LimeModel): Boolean { val allElements = limeModel.referenceMap.values.filterIsInstance() val validationResults = @@ -48,7 +47,7 @@ internal class LimeExternalTypesValidator(private val logger: LimeLogger) { private fun validateExternalNames( allElements: List, referenceMap: Map, - valueName: String + valueName: String, ) = allElements .filter { it.external?.cpp?.get(valueName) != null } .map { validateExternalElement(it, referenceMap, valueName) } @@ -56,13 +55,13 @@ internal class LimeExternalTypesValidator(private val logger: LimeLogger) { private fun validateExternalElement( limeElement: LimeNamedElement, referenceMap: Map, - propertyName: String + propertyName: String, ) = when { !isInExternalType(limeElement, referenceMap) -> { logger.error( limeElement, "an element with '$propertyName' also" + - " needs to have 'cpp: externalType' set for itself or one of its enclosing elements" + " needs to have 'cpp: externalType' set for itself or one of its enclosing elements", ) false } @@ -70,7 +69,7 @@ internal class LimeExternalTypesValidator(private val logger: LimeLogger) { logger.error( limeElement, "an element with 'cpp: $propertyName' cannot" + - " have '@Cpp(Name)' set at the same time" + " have '@Cpp(Name)' set at the same time", ) false } @@ -79,7 +78,7 @@ internal class LimeExternalTypesValidator(private val logger: LimeLogger) { private fun isInExternalType( limeElement: LimeNamedElement, - referenceMap: Map + referenceMap: Map, ) = generateSequence(limeElement) { when { it.path.tail.isNotEmpty() -> referenceMap[it.path.parent.toString()] as? LimeNamedElement diff --git a/gluecodium/src/main/java/com/here/gluecodium/validator/LimeFieldConstructorsValidator.kt b/gluecodium/src/main/java/com/here/gluecodium/validator/LimeFieldConstructorsValidator.kt index 48d33464a7..d396b4a056 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/validator/LimeFieldConstructorsValidator.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/validator/LimeFieldConstructorsValidator.kt @@ -32,7 +32,6 @@ import com.here.gluecodium.model.lime.LimeStruct * * Validates that all omitted fields have default values. */ internal class LimeFieldConstructorsValidator(private val logger: LimeLogger) { - fun validate(limeModel: LimeModel): Boolean { val allFieldConstructors = limeModel.referenceMap.values.filterIsInstance() val validationResults = allFieldConstructors.map { validateFieldConstructor(it) } @@ -52,19 +51,21 @@ internal class LimeFieldConstructorsValidator(private val logger: LimeLogger) { if (fieldConstructor.omittedFields.any { it.defaultValue == null }) { logger.error( fieldConstructor.struct, - "all fields omitted by a field constructor should have default values" + "all fields omitted by a field constructor should have default values", ) return false } return true } - private fun validateRef(limeStruct: LimeStruct, limeFieldRef: LimeFieldRef) = - try { - limeFieldRef.field - true - } catch (e: LimeModelLoaderException) { - logger.error(limeStruct, e.message ?: "") - false - } + private fun validateRef( + limeStruct: LimeStruct, + limeFieldRef: LimeFieldRef, + ) = try { + limeFieldRef.field + true + } catch (e: LimeModelLoaderException) { + logger.error(limeStruct, e.message ?: "") + false + } } diff --git a/gluecodium/src/main/java/com/here/gluecodium/validator/LimeFunctionsValidator.kt b/gluecodium/src/main/java/com/here/gluecodium/validator/LimeFunctionsValidator.kt index 42d3b9ca15..be6f1f77b2 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/validator/LimeFunctionsValidator.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/validator/LimeFunctionsValidator.kt @@ -29,17 +29,19 @@ import com.here.gluecodium.model.lime.LimeInterface import com.here.gluecodium.model.lime.LimeModel internal class LimeFunctionsValidator(private val logger: LimeLogger) { - fun validate(limeModel: LimeModel): Boolean { - val validationResults = limeModel.referenceMap.values - .filterIsInstance() - .map { validateFunction(it, limeModel.referenceMap) } + val validationResults = + limeModel.referenceMap.values + .filterIsInstance() + .map { validateFunction(it, limeModel.referenceMap) } return !validationResults.contains(false) } - private fun validateFunction(limeFunction: LimeFunction, referenceMap: Map): Boolean { - + private fun validateFunction( + limeFunction: LimeFunction, + referenceMap: Map, + ): Boolean { var result = true val thrownType = limeFunction.thrownType?.typeRef?.type?.actualType diff --git a/gluecodium/src/main/java/com/here/gluecodium/validator/LimeGenericTypesValidator.kt b/gluecodium/src/main/java/com/here/gluecodium/validator/LimeGenericTypesValidator.kt index 990f4a4bc8..abd53ae4eb 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/validator/LimeGenericTypesValidator.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/validator/LimeGenericTypesValidator.kt @@ -38,27 +38,28 @@ import com.here.gluecodium.model.lime.LimeTypeRef */ internal class LimeGenericTypesValidator(private val logger: LimeLogger) : LimeTypeRefsVisitor() { - fun validate(limeModel: LimeModel) = !traverseModel(limeModel).contains(false) - override fun visitTypeRef(parentElement: LimeNamedElement, limeTypeRef: LimeTypeRef?) = - when (val referredType = limeTypeRef?.type) { - is LimeSet -> - validateGenericType(parentElement, referredType.elementType, "set element") - is LimeMap -> validateGenericType(parentElement, referredType.keyType, "map key") - else -> true - } + override fun visitTypeRef( + parentElement: LimeNamedElement, + limeTypeRef: LimeTypeRef?, + ) = when (val referredType = limeTypeRef?.type) { + is LimeSet -> + validateGenericType(parentElement, referredType.elementType, "set element") + is LimeMap -> validateGenericType(parentElement, referredType.keyType, "map key") + else -> true + } private fun validateGenericType( parentElement: LimeNamedElement, elementTypeRef: LimeTypeRef, - elementDescription: String + elementDescription: String, ): Boolean { val result = isHashable(elementTypeRef) if (!result) { logger.error( parentElement, - "$elementDescription type ${elementTypeRef.type.fullName} is not hashable" + "$elementDescription type ${elementTypeRef.type.fullName} is not hashable", ) } return result diff --git a/gluecodium/src/main/java/com/here/gluecodium/validator/LimeInheritanceValidator.kt b/gluecodium/src/main/java/com/here/gluecodium/validator/LimeInheritanceValidator.kt index 0f58170281..67c123c95f 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/validator/LimeInheritanceValidator.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/validator/LimeInheritanceValidator.kt @@ -32,7 +32,6 @@ import com.here.gluecodium.model.lime.LimePath * interfaces. */ internal class LimeInheritanceValidator(private val logger: LimeLogger) { - fun validate(limeModel: LimeModel): Boolean { val allElements = limeModel.referenceMap.values val validationResults = @@ -64,7 +63,6 @@ internal class LimeInheritanceValidator(private val logger: LimeLogger) { } limeClass.parents.drop(1).map { it.type.actualType } .any { it !is LimeInterface || !it.isNarrow } -> { - logger.error(limeClass, MULTIPLE_INHERITANCE_MESSAGE) false } @@ -90,7 +88,6 @@ internal class LimeInheritanceValidator(private val logger: LimeLogger) { } limeInterface.parents.drop(1).map { it.type.actualType } .any { it !is LimeInterface || !it.isNarrow } -> { - logger.error(limeInterface, MULTIPLE_INHERITANCE_MESSAGE) false } @@ -100,7 +97,7 @@ internal class LimeInheritanceValidator(private val logger: LimeLogger) { private fun hasInheritanceLoop( limeContainer: LimeContainerWithInheritance, - visitedPaths: Set = emptySet() + visitedPaths: Set = emptySet(), ): Boolean { val containerPath = limeContainer.path if (visitedPaths.contains(containerPath)) return true diff --git a/gluecodium/src/main/java/com/here/gluecodium/validator/LimeOptimizedListsValidator.kt b/gluecodium/src/main/java/com/here/gluecodium/validator/LimeOptimizedListsValidator.kt index 8f13ea03e1..d890cf82c8 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/validator/LimeOptimizedListsValidator.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/validator/LimeOptimizedListsValidator.kt @@ -40,17 +40,17 @@ import com.here.gluecodium.model.lime.LimeTypeRef * * type of a field in an `@Immutable` struct */ internal class LimeOptimizedListsValidator(private val logger: LimeLogger) { - fun validate(limeModel: LimeModel): Boolean { val allElements = limeModel.referenceMap.values - val validationResults = allElements.filterIsInstance().map { validateConstant(it) } + - allElements.filterIsInstance().map { validateTypeAlias(it) } + - allElements.filterIsInstance().map { validateException(it) } + - allElements.filterIsInstance().map { validateParent(it) } + - allElements.filterIsInstance().map { validateLambda(it) } + - allElements.filterIsInstance().map { validateFunction(it) } + - allElements.filterIsInstance().map { validateProperty(it) } + - allElements.filterIsInstance().map { validateStruct(it) } + val validationResults = + allElements.filterIsInstance().map { validateConstant(it) } + + allElements.filterIsInstance().map { validateTypeAlias(it) } + + allElements.filterIsInstance().map { validateException(it) } + + allElements.filterIsInstance().map { validateParent(it) } + + allElements.filterIsInstance().map { validateLambda(it) } + + allElements.filterIsInstance().map { validateFunction(it) } + + allElements.filterIsInstance().map { validateProperty(it) } + + allElements.filterIsInstance().map { validateStruct(it) } return !validationResults.contains(false) } @@ -143,7 +143,6 @@ internal class LimeOptimizedListsValidator(private val logger: LimeLogger) { companion object { private const val LIST_TYPE_MESSAGE = "`@Optimized` attribute can only be used with `List<>` type" - private fun isOptimized(limeTypeRef: LimeTypeRef?) = - limeTypeRef?.attributes?.have(LimeAttributeType.OPTIMIZED) ?: false + private fun isOptimized(limeTypeRef: LimeTypeRef?) = limeTypeRef?.attributes?.have(LimeAttributeType.OPTIMIZED) ?: false } } diff --git a/gluecodium/src/main/java/com/here/gluecodium/validator/LimeOverloadsValidator.kt b/gluecodium/src/main/java/com/here/gluecodium/validator/LimeOverloadsValidator.kt index 1e74117d9c..3521e38bd7 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/validator/LimeOverloadsValidator.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/validator/LimeOverloadsValidator.kt @@ -28,7 +28,7 @@ import com.here.gluecodium.model.lime.LimeSignatureResolver internal class LimeOverloadsValidator( private val signatureResolver: LimeSignatureResolver, private val logger: LimeLogger, - private val validateCustomConstructors: Boolean = false + private val validateCustomConstructors: Boolean = false, ) { fun validate(limeModel: Collection): Boolean { val validationResults = @@ -37,22 +37,24 @@ internal class LimeOverloadsValidator( return !validationResults.contains(false) } - private fun validateFunction(limeFunction: LimeFunction, signatureResolver: LimeSignatureResolver) = - when { - signatureResolver.hasSignatureClash(limeFunction) -> { - logger.error(limeFunction, "function has conflicting overloads") - false - } - validateCustomConstructors && signatureResolver.hasConstructorSignatureClash(limeFunction) -> { - logger.error(limeFunction, "constructor has conflicting overloads") - false - } - else -> true + private fun validateFunction( + limeFunction: LimeFunction, + signatureResolver: LimeSignatureResolver, + ) = when { + signatureResolver.hasSignatureClash(limeFunction) -> { + logger.error(limeFunction, "function has conflicting overloads") + false } + validateCustomConstructors && signatureResolver.hasConstructorSignatureClash(limeFunction) -> { + logger.error(limeFunction, "constructor has conflicting overloads") + false + } + else -> true + } private fun validateFieldConstructor( limeFieldConstructor: LimeFieldConstructor, - signatureResolver: LimeSignatureResolver + signatureResolver: LimeSignatureResolver, ): Boolean { if (validateCustomConstructors) { if (signatureResolver.hasConstructorSignatureClash(limeFieldConstructor.asFunction())) { diff --git a/gluecodium/src/main/java/com/here/gluecodium/validator/LimePropertiesValidator.kt b/gluecodium/src/main/java/com/here/gluecodium/validator/LimePropertiesValidator.kt index 29eb685802..461716481b 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/validator/LimePropertiesValidator.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/validator/LimePropertiesValidator.kt @@ -29,11 +29,11 @@ import com.here.gluecodium.model.lime.LimeModel import com.here.gluecodium.model.lime.LimeProperty internal class LimePropertiesValidator(private val logger: LimeLogger) { - fun validate(limeModel: LimeModel): Boolean { - val validationResults = limeModel.referenceMap.values - .filterIsInstance() - .map { validateProperties(it) } + val validationResults = + limeModel.referenceMap.values + .filterIsInstance() + .map { validateProperties(it) } return !validationResults.contains(false) } @@ -48,7 +48,7 @@ internal class LimePropertiesValidator(private val logger: LimeLogger) { private fun validateProperty( limeProperty: LimeProperty, allPropertyNames: List, - parentElement: LimeContainerWithInheritance + parentElement: LimeContainerWithInheritance, ): Boolean { var result = true if (allPropertyNames.filter { it == limeProperty.name }.size > 1) { diff --git a/gluecodium/src/main/java/com/here/gluecodium/validator/LimeSerializableStructsValidator.kt b/gluecodium/src/main/java/com/here/gluecodium/validator/LimeSerializableStructsValidator.kt index 8fb60fdef0..bef619005c 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/validator/LimeSerializableStructsValidator.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/validator/LimeSerializableStructsValidator.kt @@ -27,13 +27,13 @@ import com.here.gluecodium.model.lime.LimeStruct // Validate serializable structs to ensure their fields have serializable types. internal class LimeSerializableStructsValidator(private val logger: LimeLogger) { - fun validate(limeModel: LimeModel): Boolean { val allElements = limeModel.referenceMap.values - val validationResults = allElements - .filterIsInstance() - .filter { it.attributes.have(LimeAttributeType.SERIALIZABLE) } - .map { validateStruct(it) } + val validationResults = + allElements + .filterIsInstance() + .filter { it.attributes.have(LimeAttributeType.SERIALIZABLE) } + .map { validateStruct(it) } return !validationResults.contains(false) } diff --git a/gluecodium/src/main/java/com/here/gluecodium/validator/LimeSkipValidator.kt b/gluecodium/src/main/java/com/here/gluecodium/validator/LimeSkipValidator.kt index 8cdbee6ebc..6f616afa9b 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/validator/LimeSkipValidator.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/validator/LimeSkipValidator.kt @@ -37,7 +37,6 @@ import com.here.gluecodium.model.lime.LimeStruct * Validate fields and enumerators against having a platform-skip attribute. */ internal class LimeSkipValidator(private val logger: LimeLogger) { - fun validate(limeModel: LimeModel): Boolean { val enumerators = limeModel.referenceMap.values.filterIsInstance() val structs = limeModel.referenceMap.values.filterIsInstance() @@ -51,7 +50,9 @@ internal class LimeSkipValidator(private val logger: LimeLogger) { return@map if (limeElement.attributes.have(it, SKIP)) { logger.error(limeElement, getErrorMessage(limeElement, it)) false - } else true + } else { + true + } } private fun validateFields(limeStruct: LimeStruct) = @@ -59,12 +60,16 @@ internal class LimeSkipValidator(private val logger: LimeLogger) { !limeStruct.fields.filter { it.defaultValue == null }.flatMap { validateSkipAttributes(it) }.contains(false) companion object { - private fun getErrorMessage(limeElement: LimeNamedElement, limeAttributeType: LimeAttributeType): String { - val typePrefix = when (limeElement) { - is LimeField -> "field of an immutable struct without a default value" - is LimeEnumerator -> "enumerator" - else -> throw GluecodiumExecutionException("Unsupported element type ${limeElement.javaClass.name}") - } + private fun getErrorMessage( + limeElement: LimeNamedElement, + limeAttributeType: LimeAttributeType, + ): String { + val typePrefix = + when (limeElement) { + is LimeField -> "field of an immutable struct without a default value" + is LimeEnumerator -> "enumerator" + else -> throw GluecodiumExecutionException("Unsupported element type ${limeElement.javaClass.name}") + } return "$typePrefix cannot be marked with a `@$limeAttributeType(Skip)` attribute" } } diff --git a/gluecodium/src/main/java/com/here/gluecodium/validator/LimeStructsValidator.kt b/gluecodium/src/main/java/com/here/gluecodium/validator/LimeStructsValidator.kt index a2161a6002..f77b3f9a81 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/validator/LimeStructsValidator.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/validator/LimeStructsValidator.kt @@ -32,7 +32,6 @@ import com.here.gluecodium.model.lime.LimeStruct * * or if it has any `internal` fields which don't have default values set. */ internal class LimeStructsValidator(private val logger: LimeLogger, private val strictMode: Boolean) { - fun validate(limeModel: LimeModel): Boolean { val allStructs = limeModel.referenceMap.values.filterIsInstance() val constrValidationResults = allStructs.map { validateConstructability(it) } @@ -51,7 +50,7 @@ internal class LimeStructsValidator(private val logger: LimeLogger, private val instanceFunctions.isNotEmpty() && limeStruct.fields.isEmpty() -> { logger.error( limeStruct, - "instance functions are not supported for structs without fields" + "instance functions are not supported for structs without fields", ) false } @@ -73,7 +72,7 @@ internal class LimeStructsValidator(private val logger: LimeLogger, private val logger.error( limeStruct, "if any internal field does not have a default value, " + - "the struct should have at least one explicit constructor" + "the struct should have at least one explicit constructor", ) result = false } diff --git a/gluecodium/src/main/java/com/here/gluecodium/validator/LimeTypeRefTargetValidator.kt b/gluecodium/src/main/java/com/here/gluecodium/validator/LimeTypeRefTargetValidator.kt index 27a0596c5c..09be5b2def 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/validator/LimeTypeRefTargetValidator.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/validator/LimeTypeRefTargetValidator.kt @@ -34,21 +34,23 @@ import com.here.gluecodium.model.lime.LimeTypeRef */ internal class LimeTypeRefTargetValidator(private val logger: LimeLogger) : LimeTypeRefsVisitor() { - fun validate(limeModel: LimeModel) = !traverseModel(limeModel).contains(false) - override fun visitTypeRef(parentElement: LimeNamedElement, limeTypeRef: LimeTypeRef?): Boolean { + override fun visitTypeRef( + parentElement: LimeNamedElement, + limeTypeRef: LimeTypeRef?, + ): Boolean { val referredType = limeTypeRef?.type?.actualType return when { referredType is LimeException && ( parentElement !is LimeFunction || parentElement.thrownType?.typeRef?.type !== referredType - ) -> { + ) -> { logger.error( parentElement, "refers to an exception type ${referredType.fullName} " + - "which cannot be used outside of a `throws` clause." + "which cannot be used outside of a `throws` clause.", ) false } diff --git a/gluecodium/src/main/java/com/here/gluecodium/validator/LimeTypeRefsValidator.kt b/gluecodium/src/main/java/com/here/gluecodium/validator/LimeTypeRefsValidator.kt index 3a94d0bdec..3a0f8089a6 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/validator/LimeTypeRefsValidator.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/validator/LimeTypeRefsValidator.kt @@ -32,10 +32,12 @@ import com.here.gluecodium.model.lime.LimeTypeRef */ internal class LimeTypeRefsValidator(private val logger: LimeLogger) : LimeTypeRefsVisitor() { - fun validate(limeModel: LimeModel) = !traverseModel(limeModel).contains(false) - override fun visitTypeRef(parentElement: LimeNamedElement, limeTypeRef: LimeTypeRef?): Boolean { + override fun visitTypeRef( + parentElement: LimeNamedElement, + limeTypeRef: LimeTypeRef?, + ): Boolean { if (limeTypeRef == null) { return true } @@ -49,11 +51,13 @@ internal class LimeTypeRefsValidator(private val logger: LimeLogger) : } } - private fun validateTypeRef(parentElement: LimeNamedElement, limeTypeRef: LimeTypeRef) = - try { - limeTypeRef.type - } catch (e: LimeModelLoaderException) { - logger.error(parentElement, e.message ?: "") - null - } + private fun validateTypeRef( + parentElement: LimeNamedElement, + limeTypeRef: LimeTypeRef, + ) = try { + limeTypeRef.type + } catch (e: LimeModelLoaderException) { + logger.error(parentElement, e.message ?: "") + null + } } diff --git a/gluecodium/src/main/java/com/here/gluecodium/validator/LimeValuesValidator.kt b/gluecodium/src/main/java/com/here/gluecodium/validator/LimeValuesValidator.kt index b3fa402b25..55cf1f0636 100644 --- a/gluecodium/src/main/java/com/here/gluecodium/validator/LimeValuesValidator.kt +++ b/gluecodium/src/main/java/com/here/gluecodium/validator/LimeValuesValidator.kt @@ -37,7 +37,6 @@ import com.here.gluecodium.model.lime.LimeValue * Validates values assigned to constants and fields for correctness. */ internal class LimeValuesValidator(private val logger: LimeLogger) { - fun validate(limeModel: LimeModel): Boolean { val allFields = limeModel.referenceMap.values.filterIsInstance() val allConstants = limeModel.referenceMap.values.filterIsInstance() @@ -45,10 +44,12 @@ internal class LimeValuesValidator(private val logger: LimeLogger) { return !validationResults.contains(false) } - private fun validateField(limeField: LimeField) = - limeField.defaultValue?.let { validateValue(limeField, it) } ?: true + private fun validateField(limeField: LimeField) = limeField.defaultValue?.let { validateValue(limeField, it) } ?: true - private fun validateValue(limeElement: LimeTypedElement, limeValue: LimeValue): Boolean { + private fun validateValue( + limeElement: LimeTypedElement, + limeValue: LimeValue, + ): Boolean { val actualType = limeElement.typeRef.type.actualType when (limeValue) { is LimeValue.Literal -> if (!validateLiteral(limeElement, actualType, limeValue)) return false @@ -58,26 +59,30 @@ internal class LimeValuesValidator(private val logger: LimeLogger) { return false } } - is LimeValue.InitializerList -> if (!isCollectionType(actualType)) { - logger.error(limeElement, "initializer list values can only be assigned to collection types") - return false - } + is LimeValue.InitializerList -> + if (!isCollectionType(actualType)) { + logger.error(limeElement, "initializer list values can only be assigned to collection types") + return false + } is LimeValue.KeyValuePair -> { logger.error(limeElement, "key-value pair values can only be used inside initializer lists") return false } - is LimeValue.Null -> if (!limeElement.typeRef.isNullable) { - logger.error(limeElement, "`null` value can only be assigned to a nullable type") - return false - } - is LimeValue.Special -> if (actualType !is LimeBasicType || !actualType.typeId.isNumericType) { - logger.error(limeElement, "special numeric values can only be assigned to numeric types") - return false - } - is LimeValue.StructInitializer -> if (actualType !is LimeStruct) { - logger.error(limeElement, "struct initializer values can only be assigned to `struct` types") - return false - } + is LimeValue.Null -> + if (!limeElement.typeRef.isNullable) { + logger.error(limeElement, "`null` value can only be assigned to a nullable type") + return false + } + is LimeValue.Special -> + if (actualType !is LimeBasicType || !actualType.typeId.isNumericType) { + logger.error(limeElement, "special numeric values can only be assigned to numeric types") + return false + } + is LimeValue.StructInitializer -> + if (actualType !is LimeStruct) { + logger.error(limeElement, "struct initializer values can only be assigned to `struct` types") + return false + } else -> {} } return true @@ -86,7 +91,7 @@ internal class LimeValuesValidator(private val logger: LimeLogger) { private fun validateLiteral( limeElement: LimeNamedElement, limeType: LimeType, - limeValue: LimeValue.Literal + limeValue: LimeValue.Literal, ): Boolean { if (limeType !is LimeBasicType) { logger.error(limeElement, "literal values cannot be assigned to non-basic types") @@ -95,7 +100,7 @@ internal class LimeValuesValidator(private val logger: LimeLogger) { if (limeType.typeId == TypeId.BLOB || limeType.typeId == TypeId.DURATION) { logger.error( limeElement, - "string or numeric literal values cannot be assigned to `Blob` or `Duration` types" + "string or numeric literal values cannot be assigned to `Blob` or `Duration` types", ) return false } @@ -110,10 +115,11 @@ internal class LimeValuesValidator(private val logger: LimeLogger) { return true } - private fun isCollectionType(limeType: LimeType) = when { - limeType is LimeGenericType -> true - limeType !is LimeBasicType -> false - limeType.typeId == TypeId.BLOB -> true - else -> false - } + private fun isCollectionType(limeType: LimeType) = + when { + limeType is LimeGenericType -> true + limeType !is LimeBasicType -> false + limeType.typeId == TypeId.BLOB -> true + else -> false + } } diff --git a/gluecodium/src/test/java/com/here/gluecodium/GluecodiumIntegrationTest.kt b/gluecodium/src/test/java/com/here/gluecodium/GluecodiumIntegrationTest.kt index 3f387ff492..cd62ed0985 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/GluecodiumIntegrationTest.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/GluecodiumIntegrationTest.kt @@ -32,17 +32,17 @@ import java.io.File @RunWith(JUnit4::class) class GluecodiumIntegrationTest { - @Rule @JvmField val outputFolder = TemporaryFolder() private val mainFile = GeneratedFile("I'm a main file", "mainsubdir/mainfile", GeneratedFile.SourceSet.MAIN) - private val commonFile = GeneratedFile( - "I'm a common file", - "commonsubdir/commonfile", - GeneratedFile.SourceSet.COMMON - ) + private val commonFile = + GeneratedFile( + "I'm a common file", + "commonsubdir/commonfile", + GeneratedFile.SourceSet.COMMON, + ) @Test fun `output with common code in subdirectory writes all files`() { @@ -51,16 +51,18 @@ class GluecodiumIntegrationTest { val expectedMainFile = File("$mainDir/${mainFile.targetFile}") val expectedCommonFile = File("$commonDir/${commonFile.targetFile}") - val gluecodiumOptions = GluecodiumOptions( - outputDir = mainDir, - commonOutputDir = commonDir, - isEnableCaching = true - ) - val generatorOptions = GeneratorOptions( - cppInternalNamespace = listOf("gluecodium"), - javaNonNullAnnotation = Pair("NonNull", listOf("android", "support", "annotation")), - javaNullableAnnotation = Pair("Nullable", listOf("android", "support", "annotation")) - ) + val gluecodiumOptions = + GluecodiumOptions( + outputDir = mainDir, + commonOutputDir = commonDir, + isEnableCaching = true, + ) + val generatorOptions = + GeneratorOptions( + cppInternalNamespace = listOf("gluecodium"), + javaNonNullAnnotation = Pair("NonNull", listOf("android", "support", "annotation")), + javaNullableAnnotation = Pair("Nullable", listOf("android", "support", "annotation")), + ) val gluecodium = Gluecodium(gluecodiumOptions, generatorOptions) gluecodium.output("cpp", listOf(mainFile, commonFile)) diff --git a/gluecodium/src/test/java/com/here/gluecodium/SmokeTest.kt b/gluecodium/src/test/java/com/here/gluecodium/SmokeTest.kt index afec42cc4d..7d3e44a3cc 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/SmokeTest.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/SmokeTest.kt @@ -47,7 +47,7 @@ class SmokeTest( private val featureDirectory: File, private val dumpDirectory: File, private val generatorName: String, - @Suppress("UNUSED_PARAMETER") featureName: String + @Suppress("UNUSED_PARAMETER") featureName: String, ) { @JvmField @Rule @@ -63,10 +63,11 @@ class SmokeTest( val commandLineOptions = File(inputDirectory, "commandlineoptions.txt") if (commandLineOptions.exists()) { // read command line options and replace INPUT_FOLDER with absolute input path from test - val commands = commandLineOptions.readText() - .replace("\$INPUT_FOLDER", inputDirectory.toString()) - .replace("\$AUX_FOLDER", auxDirectory.toString()) - .split("\\s".toRegex()) + val commands = + commandLineOptions.readText() + .replace("\$INPUT_FOLDER", inputDirectory.toString()) + .replace("\$AUX_FOLDER", auxDirectory.toString()) + .split("\\s".toRegex()) val options = OptionReader.read(commands.toTypedArray()) TestCase.assertNotNull("Failed to read commandlineoptions.txt", options) return options!! @@ -95,10 +96,11 @@ class SmokeTest( val validationShouldFail = File(inputDirectory, "validationfail.txt").exists() val generatorDirectories = listOf(generatorName) + (ADDITIONAL_GENERATOR_DIRS[generatorName] ?: emptyList()) - val referenceFiles = generatorDirectories - .map { generatorDirectoryName -> File(outputDirectory, generatorDirectoryName) } - .flatMap { listFilesRecursively(it) } - .filterNot { it.name.lowercase(Locale.getDefault()).startsWith(IGNORE_PREFIX) } + val referenceFiles = + generatorDirectories + .map { generatorDirectoryName -> File(outputDirectory, generatorDirectoryName) } + .flatMap { listFilesRecursively(it) } + .filterNot { it.name.lowercase(Locale.getDefault()).startsWith(IGNORE_PREFIX) } assumeFalse("No reference files were found", referenceFiles.isEmpty()) @@ -119,7 +121,7 @@ class SmokeTest( val generatedContent = generatedContents[relativePath] errorCollector.checkNotNull( "File was not generated: $relativePath, generated files:\n${generatedContents.keys.joinToString("\n")}", - generatedContent + generatedContent, ) if (generatedContent != null) { @@ -130,7 +132,7 @@ class SmokeTest( errorCollector.checkEquals( "File content differs for file: $relativePath", expectedWithImportantDifferences, - generatedWithImportantDifferences + generatedWithImportantDifferences, ) if (expectedWithImportantDifferences != generatedWithImportantDifferences) { @@ -144,12 +146,13 @@ class SmokeTest( } companion object { - private val TEST_OPTIONS = GeneratorOptions( - cppInternalNamespace = listOf("gluecodium"), - internalPrefix = "foobar_", - javaNonNullAnnotation = Pair("NonNull", listOf("android", "support", "annotation")), - javaNullableAnnotation = Pair("Nullable", listOf("android", "support", "annotation")) - ) + private val TEST_OPTIONS = + GeneratorOptions( + cppInternalNamespace = listOf("gluecodium"), + internalPrefix = "foobar_", + javaNonNullAnnotation = Pair("NonNull", listOf("android", "support", "annotation")), + javaNullableAnnotation = Pair("Nullable", listOf("android", "support", "annotation")), + ) private const val FEATURE_INPUT_FOLDER = "input" private const val FEATURE_AUX_FOLDER = "auxiliary" @@ -194,7 +197,7 @@ class SmokeTest( directory, File(dumpActualDir, directory.name), generatorName, - getFeatureName(testResourcesDirectory, directory) + getFeatureName(testResourcesDirectory, directory), ) } } @@ -213,8 +216,10 @@ class SmokeTest( return result } - private fun getRelativePath(directory: File, file: File) = - directory.toPath().relativize(file.toPath()).toString() + private fun getRelativePath( + directory: File, + file: File, + ) = directory.toPath().relativize(file.toPath()).toString() private fun ignoreUnimportantDifferences(text: String) = text @@ -223,7 +228,9 @@ class SmokeTest( // treat Windows path separators as if they were Unix ones .split('\n').joinToString("\n") { if (it.startsWith("#include")) it.replace('/', '\\') else it } - private fun getFeatureName(parentDirectory: File, featureDirectory: File) = - getRelativePath(parentDirectory, featureDirectory).replace("/", "") + private fun getFeatureName( + parentDirectory: File, + featureDirectory: File, + ) = getRelativePath(parentDirectory, featureDirectory).replace("/", "") } } diff --git a/gluecodium/src/test/java/com/here/gluecodium/cache/SplitSourceSetCacheTest.kt b/gluecodium/src/test/java/com/here/gluecodium/cache/SplitSourceSetCacheTest.kt index bd693e9fb3..d913d1173d 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/cache/SplitSourceSetCacheTest.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/cache/SplitSourceSetCacheTest.kt @@ -36,7 +36,6 @@ import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class SplitSourceSetCacheTest { - private val mainFile = GeneratedFile("I'm a main file", "main", GeneratedFile.SourceSet.MAIN) private val commonFile = GeneratedFile("I'm a common file", "common", GeneratedFile.SourceSet.COMMON) diff --git a/gluecodium/src/test/java/com/here/gluecodium/cli/OptionReaderTest.kt b/gluecodium/src/test/java/com/here/gluecodium/cli/OptionReaderTest.kt index 32feeffc26..891902501c 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/cli/OptionReaderTest.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/cli/OptionReaderTest.kt @@ -85,9 +85,10 @@ class OptionReaderTest { @Throws(OptionReaderException::class) fun inputOptionTwoFolders() { // Arrange, Act - val options = OptionReader.read( - arrayOf("-input", TEST_INPUT_TWO_FOLDERS[0], "-input", TEST_INPUT_TWO_FOLDERS[1]) - ) + val options = + OptionReader.read( + arrayOf("-input", TEST_INPUT_TWO_FOLDERS[0], "-input", TEST_INPUT_TWO_FOLDERS[1]), + ) // Assert assertNotNull(options!!.first.idlSources) @@ -162,8 +163,10 @@ class OptionReaderTest { assertEquals("", options!!.second.copyrightHeaderContents) } - private fun prepareToRead(optionName: String, optionValue: String): Array = - arrayOf("-input", TEST_INPUT_SINGLE_FOLDER[0], optionName, optionValue) + private fun prepareToRead( + optionName: String, + optionValue: String, + ): Array = arrayOf("-input", TEST_INPUT_SINGLE_FOLDER[0], optionName, optionValue) companion object { private val TEST_INPUT_SINGLE_FOLDER = arrayOf("dirA") diff --git a/gluecodium/src/test/java/com/here/gluecodium/generator/common/NameHelperTest.kt b/gluecodium/src/test/java/com/here/gluecodium/generator/common/NameHelperTest.kt index 7abf970f5e..ead3f3bc03 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/generator/common/NameHelperTest.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/generator/common/NameHelperTest.kt @@ -27,148 +27,132 @@ import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class NameHelperTest { @Test - fun fromLowerCamelToLowerCamel() = - assertEquals(LOWER_CAMEL_CASE, NameHelper.toLowerCamelCase(LOWER_CAMEL_CASE)) + fun fromLowerCamelToLowerCamel() = assertEquals(LOWER_CAMEL_CASE, NameHelper.toLowerCamelCase(LOWER_CAMEL_CASE)) @Test - fun fromUpperCamelToLowerCamel() = - assertEquals(LOWER_CAMEL_CASE, NameHelper.toLowerCamelCase(UPPER_CAMEL_CASE)) + fun fromUpperCamelToLowerCamel() = assertEquals(LOWER_CAMEL_CASE, NameHelper.toLowerCamelCase(UPPER_CAMEL_CASE)) @Test - fun fromLowerSnakeCaseToLowerCamel() = - assertEquals(LOWER_CAMEL_CASE, NameHelper.toLowerCamelCase(LOWER_SNAKE_CASE)) + fun fromLowerSnakeCaseToLowerCamel() = assertEquals(LOWER_CAMEL_CASE, NameHelper.toLowerCamelCase(LOWER_SNAKE_CASE)) @Test - fun fromUpperSnakeCaseToLowerCamel() = - assertEquals(LOWER_CAMEL_CASE, NameHelper.toLowerCamelCase(UPPER_SNAKE_CASE)) + fun fromUpperSnakeCaseToLowerCamel() = assertEquals(LOWER_CAMEL_CASE, NameHelper.toLowerCamelCase(UPPER_SNAKE_CASE)) @Test - fun fromLowerCaseToLowerCamel() = - assertEquals(LOWER_CASE, NameHelper.toLowerCamelCase(LOWER_CASE)) + fun fromLowerCaseToLowerCamel() = assertEquals(LOWER_CASE, NameHelper.toLowerCamelCase(LOWER_CASE)) @Test - fun fromUpperCaseToLowerCamel() = - assertEquals(LOWER_CASE, NameHelper.toLowerCamelCase(UPPER_CASE)) + fun fromUpperCaseToLowerCamel() = assertEquals(LOWER_CASE, NameHelper.toLowerCamelCase(UPPER_CASE)) @Test - fun fromLowerCamelToUpperCamel() = - assertEquals(UPPER_CAMEL_CASE, NameHelper.toUpperCamelCase(LOWER_CAMEL_CASE)) + fun fromLowerCamelToUpperCamel() = assertEquals(UPPER_CAMEL_CASE, NameHelper.toUpperCamelCase(LOWER_CAMEL_CASE)) @Test - fun fromUpperCamelToUpperCamel() = - assertEquals(UPPER_CAMEL_CASE, NameHelper.toUpperCamelCase(UPPER_CAMEL_CASE)) + fun fromUpperCamelToUpperCamel() = assertEquals(UPPER_CAMEL_CASE, NameHelper.toUpperCamelCase(UPPER_CAMEL_CASE)) @Test - fun fromLowerSnakeCaseToUpperCamel() = - assertEquals(UPPER_CAMEL_CASE, NameHelper.toUpperCamelCase(LOWER_SNAKE_CASE)) + fun fromLowerSnakeCaseToUpperCamel() = assertEquals(UPPER_CAMEL_CASE, NameHelper.toUpperCamelCase(LOWER_SNAKE_CASE)) @Test - fun fromUpperSnakeCaseToUpperCamel() = - assertEquals(UPPER_CAMEL_CASE, NameHelper.toUpperCamelCase(UPPER_SNAKE_CASE)) + fun fromUpperSnakeCaseToUpperCamel() = assertEquals(UPPER_CAMEL_CASE, NameHelper.toUpperCamelCase(UPPER_SNAKE_CASE)) @Test - fun fromLowerCaseToUpperCamel() = - assertEquals(SIMPLE_UPPER_CAMEL_CASE, NameHelper.toUpperCamelCase(LOWER_CASE)) + fun fromLowerCaseToUpperCamel() = assertEquals(SIMPLE_UPPER_CAMEL_CASE, NameHelper.toUpperCamelCase(LOWER_CASE)) @Test - fun fromUpperCaseToUpperCamel() = - assertEquals(SIMPLE_UPPER_CAMEL_CASE, NameHelper.toUpperCamelCase(UPPER_CASE)) + fun fromUpperCaseToUpperCamel() = assertEquals(SIMPLE_UPPER_CAMEL_CASE, NameHelper.toUpperCamelCase(UPPER_CASE)) @Test - fun fromLowerCamelToUpperSnakeCase() = - assertEquals(UPPER_SNAKE_CASE, NameHelper.toUpperSnakeCase(LOWER_CAMEL_CASE)) + fun fromLowerCamelToUpperSnakeCase() = assertEquals(UPPER_SNAKE_CASE, NameHelper.toUpperSnakeCase(LOWER_CAMEL_CASE)) @Test - fun fromUpperCamelToUpperSnakeCase() = - assertEquals(UPPER_SNAKE_CASE, NameHelper.toUpperSnakeCase(UPPER_CAMEL_CASE)) + fun fromUpperCamelToUpperSnakeCase() = assertEquals(UPPER_SNAKE_CASE, NameHelper.toUpperSnakeCase(UPPER_CAMEL_CASE)) @Test - fun fromLowerSnakeCaseToUpperSnakeCase() = - assertEquals(UPPER_SNAKE_CASE, NameHelper.toUpperSnakeCase(LOWER_SNAKE_CASE)) + fun fromLowerSnakeCaseToUpperSnakeCase() = assertEquals(UPPER_SNAKE_CASE, NameHelper.toUpperSnakeCase(LOWER_SNAKE_CASE)) @Test - fun fromUpperSnakeCaseToUpperSnakeCase() = - assertEquals(UPPER_SNAKE_CASE, NameHelper.toUpperSnakeCase(UPPER_SNAKE_CASE)) + fun fromUpperSnakeCaseToUpperSnakeCase() = assertEquals(UPPER_SNAKE_CASE, NameHelper.toUpperSnakeCase(UPPER_SNAKE_CASE)) @Test - fun fromUpperCaseToUpperSnakeCase() = - assertEquals(UPPER_CASE, NameHelper.toUpperSnakeCase(UPPER_CASE)) + fun fromUpperCaseToUpperSnakeCase() = assertEquals(UPPER_CASE, NameHelper.toUpperSnakeCase(UPPER_CASE)) @Test - fun fromLowerCaseToUpperSnakeCase() = - assertEquals(UPPER_CASE, NameHelper.toUpperSnakeCase(LOWER_CASE)) + fun fromLowerCaseToUpperSnakeCase() = assertEquals(UPPER_CASE, NameHelper.toUpperSnakeCase(LOWER_CASE)) @Test - fun fromLowerCamelToLowerSnakeCase() = - assertEquals(LOWER_SNAKE_CASE, NameHelper.toLowerSnakeCase(LOWER_CAMEL_CASE)) + fun fromLowerCamelToLowerSnakeCase() = assertEquals(LOWER_SNAKE_CASE, NameHelper.toLowerSnakeCase(LOWER_CAMEL_CASE)) @Test - fun fromUpperCamelToLowerSnakeCase() = - assertEquals(LOWER_SNAKE_CASE, NameHelper.toLowerSnakeCase(UPPER_CAMEL_CASE)) + fun fromUpperCamelToLowerSnakeCase() = assertEquals(LOWER_SNAKE_CASE, NameHelper.toLowerSnakeCase(UPPER_CAMEL_CASE)) @Test - fun fromLowerSnakeCaseToLowerSnakeCase() = - assertEquals(LOWER_SNAKE_CASE, NameHelper.toLowerSnakeCase(LOWER_SNAKE_CASE)) + fun fromLowerSnakeCaseToLowerSnakeCase() = assertEquals(LOWER_SNAKE_CASE, NameHelper.toLowerSnakeCase(LOWER_SNAKE_CASE)) @Test - fun fromUpperSnakeCaseToLowerSnakeCase() = - assertEquals(LOWER_SNAKE_CASE, NameHelper.toLowerSnakeCase(UPPER_SNAKE_CASE)) + fun fromUpperSnakeCaseToLowerSnakeCase() = assertEquals(LOWER_SNAKE_CASE, NameHelper.toLowerSnakeCase(UPPER_SNAKE_CASE)) @Test - fun fromUpperCaseToLowerSnakeCase() = - assertEquals(LOWER_CASE, NameHelper.toLowerSnakeCase(UPPER_CASE)) + fun fromUpperCaseToLowerSnakeCase() = assertEquals(LOWER_CASE, NameHelper.toLowerSnakeCase(UPPER_CASE)) @Test - fun fromLowerCaseToLowerSnakeCase() = - assertEquals(LOWER_CASE, NameHelper.toLowerSnakeCase(LOWER_CASE)) + fun fromLowerCaseToLowerSnakeCase() = assertEquals(LOWER_CASE, NameHelper.toLowerSnakeCase(LOWER_CASE)) @Test - fun `join lower camel case`() = assertEquals( - "$LOWER_CAMEL_CASE$UPPER_CAMEL_CASE", - NameHelper.joinToLowerCamelCase(listOf(LOWER_SNAKE_CASE, UPPER_CAMEL_CASE)) - ) + fun `join lower camel case`() = + assertEquals( + "$LOWER_CAMEL_CASE$UPPER_CAMEL_CASE", + NameHelper.joinToLowerCamelCase(listOf(LOWER_SNAKE_CASE, UPPER_CAMEL_CASE)), + ) @Test - fun `join lower camel case with null`() = assertEquals( - "$LOWER_CAMEL_CASE$UPPER_CAMEL_CASE", - NameHelper.joinToLowerCamelCase(listOf(UPPER_SNAKE_CASE, null, UPPER_CAMEL_CASE, null)) - ) + fun `join lower camel case with null`() = + assertEquals( + "$LOWER_CAMEL_CASE$UPPER_CAMEL_CASE", + NameHelper.joinToLowerCamelCase(listOf(UPPER_SNAKE_CASE, null, UPPER_CAMEL_CASE, null)), + ) @Test - fun `join lower snake case`() = assertEquals( - LOWER_SNAKE_CASE + "_$LOWER_SNAKE_CASE", - NameHelper.joinToLowerSnakeCase(listOf(UPPER_SNAKE_CASE, UPPER_CAMEL_CASE)) - ) + fun `join lower snake case`() = + assertEquals( + LOWER_SNAKE_CASE + "_$LOWER_SNAKE_CASE", + NameHelper.joinToLowerSnakeCase(listOf(UPPER_SNAKE_CASE, UPPER_CAMEL_CASE)), + ) @Test - fun `join lower snake case with null`() = assertEquals( - LOWER_SNAKE_CASE + "_$LOWER_SNAKE_CASE", - NameHelper.joinToLowerSnakeCase(listOf(LOWER_CAMEL_CASE, null, UPPER_CAMEL_CASE, null)) - ) + fun `join lower snake case with null`() = + assertEquals( + LOWER_SNAKE_CASE + "_$LOWER_SNAKE_CASE", + NameHelper.joinToLowerSnakeCase(listOf(LOWER_CAMEL_CASE, null, UPPER_CAMEL_CASE, null)), + ) @Test - fun `join upper camel case`() = assertEquals( - "$UPPER_CAMEL_CASE$UPPER_CAMEL_CASE", - NameHelper.joinToUpperCamelCase(listOf(LOWER_SNAKE_CASE, UPPER_CAMEL_CASE)) - ) + fun `join upper camel case`() = + assertEquals( + "$UPPER_CAMEL_CASE$UPPER_CAMEL_CASE", + NameHelper.joinToUpperCamelCase(listOf(LOWER_SNAKE_CASE, UPPER_CAMEL_CASE)), + ) @Test - fun `join upper camel case with null`() = assertEquals( - "$UPPER_CAMEL_CASE$UPPER_CAMEL_CASE", - NameHelper.joinToUpperCamelCase(listOf(LOWER_SNAKE_CASE, null, UPPER_CAMEL_CASE, null)) - ) + fun `join upper camel case with null`() = + assertEquals( + "$UPPER_CAMEL_CASE$UPPER_CAMEL_CASE", + NameHelper.joinToUpperCamelCase(listOf(LOWER_SNAKE_CASE, null, UPPER_CAMEL_CASE, null)), + ) @Test - fun `join upper snake case`() = assertEquals( - UPPER_SNAKE_CASE + "_$UPPER_SNAKE_CASE", - NameHelper.joinToUpperSnakeCase(listOf(LOWER_CAMEL_CASE, UPPER_CAMEL_CASE)) - ) + fun `join upper snake case`() = + assertEquals( + UPPER_SNAKE_CASE + "_$UPPER_SNAKE_CASE", + NameHelper.joinToUpperSnakeCase(listOf(LOWER_CAMEL_CASE, UPPER_CAMEL_CASE)), + ) @Test - fun `join upper snake case with null`() = assertEquals( - UPPER_SNAKE_CASE + "_$UPPER_SNAKE_CASE", - NameHelper.joinToUpperSnakeCase(listOf(LOWER_SNAKE_CASE, null, UPPER_CAMEL_CASE, null)) - ) + fun `join upper snake case with null`() = + assertEquals( + UPPER_SNAKE_CASE + "_$UPPER_SNAKE_CASE", + NameHelper.joinToUpperSnakeCase(listOf(LOWER_SNAKE_CASE, null, UPPER_CAMEL_CASE, null)), + ) companion object { private const val LOWER_CAMEL_CASE = "someTestString" diff --git a/gluecodium/src/test/java/com/here/gluecodium/generator/common/templates/NameResolverHelperTest.kt b/gluecodium/src/test/java/com/here/gluecodium/generator/common/templates/NameResolverHelperTest.kt index 10b47d9f86..b46d807c0b 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/generator/common/templates/NameResolverHelperTest.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/generator/common/templates/NameResolverHelperTest.kt @@ -40,10 +40,10 @@ class NameResolverHelperTest { @Before fun setUp() { - helper.nameResolvers[""] = object : NameResolver { - override fun resolveName(element: Any) = - if (element === genericElement) "foo" else "bar" - } + helper.nameResolvers[""] = + object : NameResolver { + override fun resolveName(element: Any) = if (element === genericElement) "foo" else "bar" + } every { options.parameters } returns parameters every { options.tagInfo.type } returns MustacheTagType.VARIABLE } @@ -81,10 +81,10 @@ class NameResolverHelperTest { fun executeStringParameter() { every { options.peek() } returns genericElement parameters.add("nonsense") - helper.nameResolvers["nonsense"] = object : NameResolver { - override fun resolveName(element: Any) = - if (element === genericElement) "baz" else "fizz" - } + helper.nameResolvers["nonsense"] = + object : NameResolver { + override fun resolveName(element: Any) = if (element === genericElement) "baz" else "fizz" + } helper.execute(options) @@ -114,10 +114,10 @@ class NameResolverHelperTest { fun executeTwoParameters() { parameters.add(genericElement) parameters.add("nonsense") - helper.nameResolvers["nonsense"] = object : NameResolver { - override fun resolveName(element: Any) = - if (element === genericElement) "baz" else "fizz" - } + helper.nameResolvers["nonsense"] = + object : NameResolver { + override fun resolveName(element: Any) = if (element === genericElement) "baz" else "fizz" + } helper.execute(options) @@ -139,10 +139,10 @@ class NameResolverHelperTest { parameters.add(genericElement) parameters.add("nonsense") parameters.add("foo") - helper.nameResolvers["nonsense"] = object : NameResolver { - override fun resolveName(element: Any) = - if (element === genericElement) "baz" else "fizz" - } + helper.nameResolvers["nonsense"] = + object : NameResolver { + override fun resolveName(element: Any) = if (element === genericElement) "baz" else "fizz" + } helper.execute(options) @@ -154,11 +154,12 @@ class NameResolverHelperTest { parameters.add(genericElement) parameters.add("nonsense") parameters.add("getter") - helper.nameResolvers["nonsense"] = object : NameResolver { - override fun resolveName(element: Any) = throw IllegalArgumentException() - override fun resolveGetterName(element: Any) = - if (element === genericElement) "baz" else "fizz" - } + helper.nameResolvers["nonsense"] = + object : NameResolver { + override fun resolveName(element: Any) = throw IllegalArgumentException() + + override fun resolveGetterName(element: Any) = if (element === genericElement) "baz" else "fizz" + } helper.execute(options) @@ -170,11 +171,12 @@ class NameResolverHelperTest { parameters.add(genericElement) parameters.add("nonsense") parameters.add("setter") - helper.nameResolvers["nonsense"] = object : NameResolver { - override fun resolveName(element: Any) = throw IllegalArgumentException() - override fun resolveSetterName(element: Any) = - if (element === genericElement) "baz" else "fizz" - } + helper.nameResolvers["nonsense"] = + object : NameResolver { + override fun resolveName(element: Any) = throw IllegalArgumentException() + + override fun resolveSetterName(element: Any) = if (element === genericElement) "baz" else "fizz" + } helper.execute(options) @@ -186,10 +188,12 @@ class NameResolverHelperTest { parameters.add(genericElement) parameters.add("nonsense") parameters.add("getter") - helper.nameResolvers["nonsense"] = object : NameResolver { - override fun resolveName(element: Any) = throw IllegalArgumentException() - override fun resolveGetterName(element: Any): String? = null - } + helper.nameResolvers["nonsense"] = + object : NameResolver { + override fun resolveName(element: Any) = throw IllegalArgumentException() + + override fun resolveGetterName(element: Any): String? = null + } helper.execute(options) @@ -201,10 +205,12 @@ class NameResolverHelperTest { parameters.add(genericElement) parameters.add("nonsense") parameters.add("setter") - helper.nameResolvers["nonsense"] = object : NameResolver { - override fun resolveName(element: Any) = throw IllegalArgumentException() - override fun resolveSetterName(element: Any): String? = null - } + helper.nameResolvers["nonsense"] = + object : NameResolver { + override fun resolveName(element: Any) = throw IllegalArgumentException() + + override fun resolveSetterName(element: Any): String? = null + } helper.execute(options) @@ -216,11 +222,12 @@ class NameResolverHelperTest { parameters.add(genericElement) parameters.add("nonsense") parameters.add("ref") - helper.nameResolvers["nonsense"] = object : NameResolver { - override fun resolveName(element: Any) = throw IllegalArgumentException() - override fun resolveReferenceName(element: Any) = - if (element === genericElement) "baz" else "fizz" - } + helper.nameResolvers["nonsense"] = + object : NameResolver { + override fun resolveName(element: Any) = throw IllegalArgumentException() + + override fun resolveReferenceName(element: Any) = if (element === genericElement) "baz" else "fizz" + } helper.execute(options) @@ -232,10 +239,12 @@ class NameResolverHelperTest { parameters.add(genericElement) parameters.add("nonsense") parameters.add("ref") - helper.nameResolvers["nonsense"] = object : NameResolver { - override fun resolveName(element: Any) = throw IllegalArgumentException() - override fun resolveReferenceName(element: Any): String? = null - } + helper.nameResolvers["nonsense"] = + object : NameResolver { + override fun resolveName(element: Any) = throw IllegalArgumentException() + + override fun resolveReferenceName(element: Any): String? = null + } helper.execute(options) diff --git a/gluecodium/src/test/java/com/here/gluecodium/generator/cpp/CppSkipAttributesValidatorTest.kt b/gluecodium/src/test/java/com/here/gluecodium/generator/cpp/CppSkipAttributesValidatorTest.kt index 07f5e40e99..15e045b6ec 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/generator/cpp/CppSkipAttributesValidatorTest.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/generator/cpp/CppSkipAttributesValidatorTest.kt @@ -39,7 +39,6 @@ import org.junit.runners.Parameterized @RunWith(Parameterized::class) class CppSkipAttributesValidatorTest(private val limeElement: LimeNamedElement, private val expectedResult: Boolean) { - private val allElements = mutableMapOf() private val limeModel = LimeModel(allElements, emptyList()) @@ -58,26 +57,27 @@ class CppSkipAttributesValidatorTest(private val limeElement: LimeNamedElement, @JvmStatic @Parameterized.Parameters - fun testData() = listOf( - arrayOf( - LimeFieldConstructor( - EMPTY_PATH, - structRef = LimeLazyTypeRef("", emptyMap()), - attributes = cppSkipAttributes + fun testData() = + listOf( + arrayOf( + LimeFieldConstructor( + EMPTY_PATH, + structRef = LimeLazyTypeRef("", emptyMap()), + attributes = cppSkipAttributes, + ), + true, ), - true - ), - arrayOf( - LimeConstant( - EMPTY_PATH, - typeRef = LimeBasicTypeRef.INT, - value = LimeValue.ZERO, - attributes = cppSkipAttributes + arrayOf( + LimeConstant( + EMPTY_PATH, + typeRef = LimeBasicTypeRef.INT, + value = LimeValue.ZERO, + attributes = cppSkipAttributes, + ), + true, ), - true - ), - arrayOf(object : LimeNamedElement(EMPTY_PATH) {}, true), - arrayOf(object : LimeNamedElement(EMPTY_PATH, attributes = cppSkipAttributes) {}, false), - ) + arrayOf(object : LimeNamedElement(EMPTY_PATH) {}, true), + arrayOf(object : LimeNamedElement(EMPTY_PATH, attributes = cppSkipAttributes) {}, false), + ) } } diff --git a/gluecodium/src/test/java/com/here/gluecodium/generator/cpp/TopologicalSortTest.kt b/gluecodium/src/test/java/com/here/gluecodium/generator/cpp/TopologicalSortTest.kt index 34fefd6c98..11f9b51ce6 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/generator/cpp/TopologicalSortTest.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/generator/cpp/TopologicalSortTest.kt @@ -45,9 +45,8 @@ import org.junit.runners.Parameterized class TopologicalSortTest( @Suppress("UNUSED_PARAMETER") testName: String, private val elements: List, - private val expectedOrder: List + private val expectedOrder: List, ) { - @Test fun checkOrder() { val sortedElements = TopologicalSort(elements).sort() @@ -73,12 +72,13 @@ class TopologicalSortTest( private val LIME_ENUM = LimeEnumeration(createPath(ENUM_NAME)) - private val LIME_ALIAS = createTypeAlias( - TYPE_DEF_NAME, - createTypeRef( - TYPE_A + private val LIME_ALIAS = + createTypeAlias( + TYPE_DEF_NAME, + createTypeRef( + TYPE_A, + ), ) - ) @JvmStatic @Parameterized.Parameters(name = "{0}") @@ -88,224 +88,231 @@ class TopologicalSortTest( "sortIndependentStructsKeepsSameOrder", listOf( createStruct(FIRST_STRUCT_NAME, TYPE_A, TYPE_B), - createStruct(SECOND_STRUCT_NAME, TYPE_B, TYPE_C) + createStruct(SECOND_STRUCT_NAME, TYPE_B, TYPE_C), ), - listOf(0, 1) + listOf(0, 1), ), arrayOf( "sortDependentStructs", listOf( createStruct(FIRST_STRUCT_NAME, TYPE_A, SECOND_STRUCT_NAME), - createStruct(SECOND_STRUCT_NAME, TYPE_B, TYPE_C) + createStruct(SECOND_STRUCT_NAME, TYPE_B, TYPE_C), ), - listOf(1, 0) + listOf(1, 0), ), arrayOf( "sortSortedDependentStructsKeepsSameOrder", listOf( createStruct(FIRST_STRUCT_NAME, TYPE_A, TYPE_B), - createStruct(SECOND_STRUCT_NAME, TYPE_B, FIRST_STRUCT_NAME) + createStruct(SECOND_STRUCT_NAME, TYPE_B, FIRST_STRUCT_NAME), ), - listOf(0, 1) + listOf(0, 1), ), arrayOf( "sortMultipleStructsWithDependencies", listOf( createStruct(FIRST_STRUCT_NAME, SECOND_STRUCT_NAME, THIRD_STRUCT_NAME), createStruct(SECOND_STRUCT_NAME, TYPE_B, THIRD_STRUCT_NAME), - createStruct(THIRD_STRUCT_NAME, TYPE_A, TYPE_B) + createStruct(THIRD_STRUCT_NAME, TYPE_A, TYPE_B), ), - listOf(2, 1, 0) + listOf(2, 1, 0), ), arrayOf( "sortEnumWithStructDependingOnIt", listOf(createStruct(FIRST_STRUCT_NAME, TYPE_A, ENUM_NAME), LIME_ENUM), - listOf(1, 0) + listOf(1, 0), ), arrayOf( "enumWithStructNotDependingOnItKeepsSameOrder", listOf(createStruct(FIRST_STRUCT_NAME, TYPE_A, TYPE_B), LIME_ENUM), - listOf(0, 1) + listOf(0, 1), ), arrayOf( "enumWithUsingDependingOnIt", listOf(createTypeAlias(TYPE_DEF_NAME, createTypeRef(ENUM_NAME)), LIME_ENUM), - listOf(1, 0) + listOf(1, 0), ), arrayOf( "enumWithUsingNotDependingOnItKeepsSameOrder", listOf(LIME_ALIAS, LIME_ENUM), - listOf(0, 1) + listOf(0, 1), ), arrayOf( "enumWithConstantDependingOnIt", listOf(createConstant(ENUM_NAME), LIME_ENUM), - listOf(1, 0) + listOf(1, 0), ), arrayOf( "enumWithConstantNotDependingOnItKeepsSameOrder", listOf(createConstant(TYPE_A), LIME_ENUM), - listOf(0, 1) + listOf(0, 1), ), arrayOf( "constantDependingOnStruct", listOf( createConstant(FIRST_STRUCT_NAME), - createStruct(FIRST_STRUCT_NAME, TYPE_A, TYPE_B) + createStruct(FIRST_STRUCT_NAME, TYPE_A, TYPE_B), ), - listOf(1, 0) + listOf(1, 0), ), arrayOf( "constantNotDependingOnStructKeepsSameOrder", listOf( createConstant(TYPE_A), - createStruct(FIRST_STRUCT_NAME, TYPE_A, TYPE_B) + createStruct(FIRST_STRUCT_NAME, TYPE_A, TYPE_B), ), - listOf(0, 1) + listOf(0, 1), ), arrayOf( "constantDependingOnDefinition", listOf(createConstantWithAliasType(), LIME_ALIAS), - listOf(1, 0) + listOf(1, 0), ), arrayOf( "constantNotDependingOnDefinitionKeepsSameOrder", listOf(createConstant(TYPE_B), LIME_ALIAS), - listOf(0, 1) + listOf(0, 1), ), arrayOf( "usingDependingOnUsing", listOf( createTypeAlias( "anotherShortcut", - LimeDirectTypeRef(createTypeAlias(TYPE_DEF_NAME, createTypeRef(TYPE_A))) + LimeDirectTypeRef(createTypeAlias(TYPE_DEF_NAME, createTypeRef(TYPE_A))), ), - LIME_ALIAS + LIME_ALIAS, ), - listOf(1, 0) + listOf(1, 0), ), arrayOf( "usingNotDependingOnUsingKeepsSameOrder", listOf(LIME_ALIAS, createTypeAlias("anotherShortcut", createTypeRef(TYPE_B))), - listOf(0, 1) + listOf(0, 1), ), arrayOf( "usingDependingOnStruct", listOf( createTypeAlias(TYPE_DEF_NAME, createTypeRef(FIRST_STRUCT_NAME)), - createStruct(FIRST_STRUCT_NAME, TYPE_A, TYPE_B) + createStruct(FIRST_STRUCT_NAME, TYPE_A, TYPE_B), ), - listOf(1, 0) + listOf(1, 0), ), arrayOf( "usingNotDependingOnStructKeepsSameOrder", listOf( createTypeAlias(TYPE_DEF_NAME, createTypeRef(TYPE_C)), - createStruct(FIRST_STRUCT_NAME, TYPE_A, TYPE_B) + createStruct(FIRST_STRUCT_NAME, TYPE_A, TYPE_B), ), - listOf(0, 1) + listOf(0, 1), ), arrayOf( "usingFunctionTypeRefDependingOnStruct", listOf( createTypeAlias( TYPE_DEF_NAME, - LimeDirectTypeRef(LimeLambda(createPath(FIRST_STRUCT_NAME))) + LimeDirectTypeRef(LimeLambda(createPath(FIRST_STRUCT_NAME))), ), - createStruct(FIRST_STRUCT_NAME, TYPE_A, TYPE_B) + createStruct(FIRST_STRUCT_NAME, TYPE_A, TYPE_B), ), - listOf(1, 0) + listOf(1, 0), ), arrayOf( "structDependingOnDefinition", listOf( createStruct(FIRST_STRUCT_NAME, TYPE_DEF_NAME, TYPE_B), - LIME_ALIAS + LIME_ALIAS, ), - listOf(1, 0) + listOf(1, 0), ), arrayOf( "structNotDependingOnDefinitionKeepsSameOrder", listOf( createStruct(FIRST_STRUCT_NAME, TYPE_A, TYPE_B), - createTypeAlias(TYPE_DEF_NAME, createTypeRef(TYPE_C)) + createTypeAlias(TYPE_DEF_NAME, createTypeRef(TYPE_C)), ), - listOf(0, 1) + listOf(0, 1), ), arrayOf( "sortStructsDependentThroughMethodReturnType", listOf( LimeStruct( path = createPath(FIRST_STRUCT_NAME), - functions = listOf( - LimeFunction( - createPath("x"), - returnType = LimeReturnType(createTypeRef(SECOND_STRUCT_NAME)) - ) - ) + functions = + listOf( + LimeFunction( + createPath("x"), + returnType = LimeReturnType(createTypeRef(SECOND_STRUCT_NAME)), + ), + ), ), - createStruct(SECOND_STRUCT_NAME, TYPE_B, TYPE_C) + createStruct(SECOND_STRUCT_NAME, TYPE_B, TYPE_C), ), - listOf(1, 0) + listOf(1, 0), ), arrayOf( "sortStructsDependentThroughMethodParameter", listOf( LimeStruct( path = createPath(FIRST_STRUCT_NAME), - functions = listOf( - LimeFunction( - createPath("x"), - parameters = listOf( - LimeParameter( - createPath("x"), - typeRef = createTypeRef(SECOND_STRUCT_NAME) - ) - ) - ) - ) + functions = + listOf( + LimeFunction( + createPath("x"), + parameters = + listOf( + LimeParameter( + createPath("x"), + typeRef = createTypeRef(SECOND_STRUCT_NAME), + ), + ), + ), + ), ), - createStruct(SECOND_STRUCT_NAME, TYPE_B, TYPE_C) + createStruct(SECOND_STRUCT_NAME, TYPE_B, TYPE_C), ), - listOf(1, 0) + listOf(1, 0), ), arrayOf( "sortStructsDependentThroughMethodThrownType", listOf( LimeStruct( path = createPath(FIRST_STRUCT_NAME), - functions = listOf( - LimeFunction( - createPath("x"), - thrownType = LimeThrownType( - LimeDirectTypeRef( - LimeException( - LimePath.EMPTY_PATH, errorType = createTypeRef(SECOND_STRUCT_NAME) - ) - ) - ) - ) - ) + functions = + listOf( + LimeFunction( + createPath("x"), + thrownType = + LimeThrownType( + LimeDirectTypeRef( + LimeException( + LimePath.EMPTY_PATH, + errorType = createTypeRef(SECOND_STRUCT_NAME), + ), + ), + ), + ), + ), ), - createStruct(SECOND_STRUCT_NAME, TYPE_B, TYPE_C) + createStruct(SECOND_STRUCT_NAME, TYPE_B, TYPE_C), ), - listOf(1, 0) + listOf(1, 0), ), arrayOf( "sortStructDependentOnSelfDoesNotCrash", listOf( LimeStruct( path = createPath(FIRST_STRUCT_NAME), - functions = listOf( - LimeFunction( - createPath("x"), - returnType = LimeReturnType(createTypeRef(FIRST_STRUCT_NAME)) - ) - ) - ) + functions = + listOf( + LimeFunction( + createPath("x"), + returnType = LimeReturnType(createTypeRef(FIRST_STRUCT_NAME)), + ), + ), + ), ), - listOf(0) - ) + listOf(0), + ), ) } } diff --git a/gluecodium/src/test/java/com/here/gluecodium/generator/cpp/TopologicalSortTestHelper.kt b/gluecodium/src/test/java/com/here/gluecodium/generator/cpp/TopologicalSortTestHelper.kt index ae4daeb455..3aa5fce592 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/generator/cpp/TopologicalSortTestHelper.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/generator/cpp/TopologicalSortTestHelper.kt @@ -32,28 +32,34 @@ import com.here.gluecodium.model.lime.LimeValue internal object TopologicalSortTestHelper { fun createPath(name: String) = LimePath(emptyList(), listOf(name)) - fun createTypeRef(typeName: String) = - LimeDirectTypeRef(object : LimeType(createPath(typeName)) {}) + fun createTypeRef(typeName: String) = LimeDirectTypeRef(object : LimeType(createPath(typeName)) {}) - fun createStruct(name: String, firstType: String, secondType: String): LimeStruct { + fun createStruct( + name: String, + firstType: String, + secondType: String, + ): LimeStruct { val path = createPath(name) return LimeStruct( path = path, - fields = listOf( - LimeField(path.child("x"), typeRef = createTypeRef(firstType)), - LimeField(path.child("y"), typeRef = createTypeRef(secondType)) - ) + fields = + listOf( + LimeField(path.child("x"), typeRef = createTypeRef(firstType)), + LimeField(path.child("y"), typeRef = createTypeRef(secondType)), + ), ) } - fun createTypeAlias(name: String, typeRef: LimeTypeRef) = - LimeTypeAlias(path = createPath(name), typeRef = typeRef) + fun createTypeAlias( + name: String, + typeRef: LimeTypeRef, + ) = LimeTypeAlias(path = createPath(name), typeRef = typeRef) fun createConstant(typeName: String) = LimeConstant( path = createPath("fixed"), typeRef = createTypeRef(typeName), - value = LimeValue.ZERO + value = LimeValue.ZERO, ) fun createConstantWithAliasType(): LimeConstant { @@ -61,7 +67,7 @@ internal object TopologicalSortTestHelper { return LimeConstant( path = createPath("fixed"), typeRef = LimeDirectTypeRef(typeAlias), - value = LimeValue.ZERO + value = LimeValue.ZERO, ) } } diff --git a/gluecodium/src/test/java/com/here/gluecodium/generator/dart/DartOverloadsValidatorFieldConstructorsTest.kt b/gluecodium/src/test/java/com/here/gluecodium/generator/dart/DartOverloadsValidatorFieldConstructorsTest.kt index ca509fc442..45db1b62af 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/generator/dart/DartOverloadsValidatorFieldConstructorsTest.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/generator/dart/DartOverloadsValidatorFieldConstructorsTest.kt @@ -38,7 +38,6 @@ import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class DartOverloadsValidatorFieldConstructorsTest { - private val allElements = mutableMapOf() private val fc1 = LimeFieldConstructor(EMPTY_PATH, structRef = LimeLazyTypeRef("", allElements)) private val fc2 = LimeFieldConstructor(EMPTY_PATH, structRef = LimeLazyTypeRef("", allElements)) diff --git a/gluecodium/src/test/java/com/here/gluecodium/generator/dart/DartOverloadsValidatorTest.kt b/gluecodium/src/test/java/com/here/gluecodium/generator/dart/DartOverloadsValidatorTest.kt index 6e2ae576ff..363a0473fd 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/generator/dart/DartOverloadsValidatorTest.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/generator/dart/DartOverloadsValidatorTest.kt @@ -42,15 +42,15 @@ import org.junit.runners.Parameterized @RunWith(Parameterized::class) class DartOverloadsValidatorTest(factory: (List) -> LimeContainer, private val hasConstructors: Boolean) { - private val fooFunction = LimeFunction(LimePath.EMPTY_PATH) private val barFunction = LimeFunction(LimePath.EMPTY_PATH) private val fooConstructor = LimeFunction(LimePath.EMPTY_PATH, isConstructor = true) private val barConstructor = LimeFunction(LimePath.EMPTY_PATH, isConstructor = true) private val functions = mutableListOf() - private val dartDefaultAttributes = LimeAttributes.Builder() - .addAttribute(LimeAttributeType.DART, LimeAttributeValueType.DEFAULT) - .build() + private val dartDefaultAttributes = + LimeAttributes.Builder() + .addAttribute(LimeAttributeType.DART, LimeAttributeValueType.DEFAULT) + .build() private val allElements = listOf(factory(functions)) @@ -112,11 +112,12 @@ class DartOverloadsValidatorTest(factory: (List) -> LimeContainer, fun validateDefaultConstructorsNoOverloads() { assumeTrue(hasConstructors) - val fooDefaultConstructor = LimeFunction( - LimePath.EMPTY_PATH, - isConstructor = true, - attributes = dartDefaultAttributes - ) + val fooDefaultConstructor = + LimeFunction( + LimePath.EMPTY_PATH, + isConstructor = true, + attributes = dartDefaultAttributes, + ) every { nameResolver.resolveName(fooDefaultConstructor) } returns "foo" every { nameResolver.resolveName(barConstructor) } returns "foo" functions += fooDefaultConstructor @@ -129,16 +130,18 @@ class DartOverloadsValidatorTest(factory: (List) -> LimeContainer, fun validateDefaultConstructorsWithOverloads() { assumeTrue(hasConstructors) - val fooDefaultConstructor = LimeFunction( - LimePath.EMPTY_PATH, - isConstructor = true, - attributes = dartDefaultAttributes - ) - val barDefaultConstructor = LimeFunction( - LimePath.EMPTY_PATH, - isConstructor = true, - attributes = dartDefaultAttributes - ) + val fooDefaultConstructor = + LimeFunction( + LimePath.EMPTY_PATH, + isConstructor = true, + attributes = dartDefaultAttributes, + ) + val barDefaultConstructor = + LimeFunction( + LimePath.EMPTY_PATH, + isConstructor = true, + attributes = dartDefaultAttributes, + ) every { nameResolver.resolveName(fooDefaultConstructor) } returns "foo" every { nameResolver.resolveName(barDefaultConstructor) } returns "bar" functions += fooDefaultConstructor @@ -150,10 +153,11 @@ class DartOverloadsValidatorTest(factory: (List) -> LimeContainer, companion object { @JvmStatic @Parameterized.Parameters(name = "{0}") - fun testData(): Collection> = listOf( - arrayOf({ functions: List -> LimeClass(LimePath.EMPTY_PATH, functions = functions) }, true), - arrayOf({ functions: List -> LimeInterface(LimePath.EMPTY_PATH, functions = functions) }, false), - arrayOf({ functions: List -> LimeStruct(LimePath.EMPTY_PATH, functions = functions) }, true) - ) + fun testData(): Collection> = + listOf( + arrayOf({ functions: List -> LimeClass(LimePath.EMPTY_PATH, functions = functions) }, true), + arrayOf({ functions: List -> LimeInterface(LimePath.EMPTY_PATH, functions = functions) }, false), + arrayOf({ functions: List -> LimeStruct(LimePath.EMPTY_PATH, functions = functions) }, true), + ) } } diff --git a/gluecodium/src/test/java/com/here/gluecodium/generator/swift/SwiftFieldsValidatorTest.kt b/gluecodium/src/test/java/com/here/gluecodium/generator/swift/SwiftFieldsValidatorTest.kt index 7177b2f7cd..d08a68fc5c 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/generator/swift/SwiftFieldsValidatorTest.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/generator/swift/SwiftFieldsValidatorTest.kt @@ -36,7 +36,6 @@ import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class SwiftFieldsValidatorTest { - private lateinit var validator: SwiftFieldsValidator @Before @@ -54,34 +53,37 @@ class SwiftFieldsValidatorTest { @Test fun validateFieldWithDeprecatedOnly() { - val limeField = LimeField( - EMPTY_PATH, - typeRef = LimeBasicTypeRef.INT, - attributes = LimeAttributes.Builder().addAttribute(DEPRECATED).build() - ) + val limeField = + LimeField( + EMPTY_PATH, + typeRef = LimeBasicTypeRef.INT, + attributes = LimeAttributes.Builder().addAttribute(DEPRECATED).build(), + ) assertFalse(validator.validate(listOf(limeField))) } @Test fun validateFieldWithDefaultValueOnly() { - val limeField = LimeField( - EMPTY_PATH, - typeRef = LimeBasicTypeRef.INT, - defaultValue = LimeValue.ZERO - ) + val limeField = + LimeField( + EMPTY_PATH, + typeRef = LimeBasicTypeRef.INT, + defaultValue = LimeValue.ZERO, + ) assertTrue(validator.validate(listOf(limeField))) } @Test fun validateFieldWithDeprecatedAndDefaultValue() { - val limeField = LimeField( - EMPTY_PATH, - typeRef = LimeBasicTypeRef.INT, - attributes = LimeAttributes.Builder().addAttribute(DEPRECATED).build(), - defaultValue = LimeValue.ZERO - ) + val limeField = + LimeField( + EMPTY_PATH, + typeRef = LimeBasicTypeRef.INT, + attributes = LimeAttributes.Builder().addAttribute(DEPRECATED).build(), + defaultValue = LimeValue.ZERO, + ) assertTrue(validator.validate(listOf(limeField))) } diff --git a/gluecodium/src/test/java/com/here/gluecodium/generator/swift/SwiftWeakAttributeValidatorTest.kt b/gluecodium/src/test/java/com/here/gluecodium/generator/swift/SwiftWeakAttributeValidatorTest.kt index 8f18b4b9a0..bd8df02ebd 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/generator/swift/SwiftWeakAttributeValidatorTest.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/generator/swift/SwiftWeakAttributeValidatorTest.kt @@ -44,7 +44,6 @@ import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class SwiftWeakAttributeValidatorTest { - private val barPath = LimePath(emptyList(), listOf("Bar")) private val fooPath = barPath.child("foo") private val nullableBool = LimeBasicTypeRef(LimeBasicType.TypeId.BOOLEAN, isNullable = true) @@ -70,12 +69,13 @@ class SwiftWeakAttributeValidatorTest { @Test fun validatePropertyInClass() { - val limeProperty = LimeProperty( - fooPath, - typeRef = nullableBool, - getter = dummyFunction, - attributes = weakAttributes - ) + val limeProperty = + LimeProperty( + fooPath, + typeRef = nullableBool, + getter = dummyFunction, + attributes = weakAttributes, + ) limeReferenceMap[barPath.toString()] = LimeClass(barPath) assertTrue(validator.validate(listOf(limeProperty))) @@ -83,12 +83,13 @@ class SwiftWeakAttributeValidatorTest { @Test fun validatePropertyNonNullable() { - val limeProperty = LimeProperty( - fooPath, - typeRef = LimeBasicTypeRef.DOUBLE, - getter = dummyFunction, - attributes = weakAttributes - ) + val limeProperty = + LimeProperty( + fooPath, + typeRef = LimeBasicTypeRef.DOUBLE, + getter = dummyFunction, + attributes = weakAttributes, + ) limeReferenceMap[barPath.toString()] = LimeInterface(barPath) assertFalse(validator.validate(listOf(limeProperty))) @@ -96,12 +97,13 @@ class SwiftWeakAttributeValidatorTest { @Test fun validatePropertyValidNonInterface() { - val limeProperty = LimeProperty( - fooPath, - typeRef = nullableBool, - getter = dummyFunction, - attributes = weakAttributes - ) + val limeProperty = + LimeProperty( + fooPath, + typeRef = nullableBool, + getter = dummyFunction, + attributes = weakAttributes, + ) limeReferenceMap[barPath.toString()] = LimeInterface(barPath) assertTrue(validator.validate(listOf(limeProperty))) @@ -110,12 +112,13 @@ class SwiftWeakAttributeValidatorTest { @Test fun validatePropertyInvalidInterfaceVoid() { val limeInterface = LimeInterface(EMPTY_PATH, functions = listOf(LimeFunction(EMPTY_PATH))) - val limeProperty = LimeProperty( - fooPath, - typeRef = LimeDirectTypeRef(limeInterface, isNullable = true), - getter = dummyFunction, - attributes = weakAttributes - ) + val limeProperty = + LimeProperty( + fooPath, + typeRef = LimeDirectTypeRef(limeInterface, isNullable = true), + getter = dummyFunction, + attributes = weakAttributes, + ) limeReferenceMap[barPath.toString()] = LimeInterface(barPath) assertFalse(validator.validate(listOf(limeProperty))) @@ -125,12 +128,13 @@ class SwiftWeakAttributeValidatorTest { fun validatePropertyValidInterfaceVoid() { val limeInterface = LimeInterface(EMPTY_PATH, functions = listOf(LimeFunction(EMPTY_PATH)), attributes = weakAttributes) - val limeProperty = LimeProperty( - fooPath, - typeRef = LimeDirectTypeRef(limeInterface, isNullable = true), - getter = dummyFunction, - attributes = weakAttributes - ) + val limeProperty = + LimeProperty( + fooPath, + typeRef = LimeDirectTypeRef(limeInterface, isNullable = true), + getter = dummyFunction, + attributes = weakAttributes, + ) limeReferenceMap[barPath.toString()] = LimeInterface(barPath) assertTrue(validator.validate(listOf(limeProperty))) @@ -140,12 +144,13 @@ class SwiftWeakAttributeValidatorTest { fun validatePropertyValidInterfaceNullable() { val limeFunction = LimeFunction(EMPTY_PATH, returnType = LimeReturnType(nullableBool)) val limeInterface = LimeInterface(EMPTY_PATH, functions = listOf(limeFunction), attributes = weakAttributes) - val limeProperty = LimeProperty( - fooPath, - typeRef = LimeDirectTypeRef(limeInterface, isNullable = true), - getter = dummyFunction, - attributes = weakAttributes - ) + val limeProperty = + LimeProperty( + fooPath, + typeRef = LimeDirectTypeRef(limeInterface, isNullable = true), + getter = dummyFunction, + attributes = weakAttributes, + ) limeReferenceMap[barPath.toString()] = LimeInterface(barPath) assertTrue(validator.validate(listOf(limeProperty))) @@ -156,12 +161,13 @@ class SwiftWeakAttributeValidatorTest { val limeFunction = LimeFunction(EMPTY_PATH, returnType = LimeReturnType(LimeBasicTypeRef(LimeBasicType.TypeId.BOOLEAN))) val limeInterface = LimeInterface(EMPTY_PATH, functions = listOf(limeFunction), attributes = weakAttributes) - val limeProperty = LimeProperty( - fooPath, - typeRef = LimeDirectTypeRef(limeInterface, isNullable = true), - getter = dummyFunction, - attributes = weakAttributes - ) + val limeProperty = + LimeProperty( + fooPath, + typeRef = LimeDirectTypeRef(limeInterface, isNullable = true), + getter = dummyFunction, + attributes = weakAttributes, + ) limeReferenceMap[barPath.toString()] = LimeInterface(barPath) assertFalse(validator.validate(listOf(limeProperty))) diff --git a/gluecodium/src/test/java/com/here/gluecodium/output/FileOutputTest.kt b/gluecodium/src/test/java/com/here/gluecodium/output/FileOutputTest.kt index f171088107..f210c53727 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/output/FileOutputTest.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/output/FileOutputTest.kt @@ -63,10 +63,11 @@ class FileOutputTest { } companion object { - private val FILES = listOf( - GeneratedFile("CONTENT1", "PATH1_1/PATH1_2/FILE1"), - GeneratedFile("", "PATH2/FILE2"), - GeneratedFile("CONTENT3", "FILE3") - ) + private val FILES = + listOf( + GeneratedFile("CONTENT1", "PATH1_1/PATH1_2/FILE1"), + GeneratedFile("", "PATH2/FILE2"), + GeneratedFile("CONTENT3", "FILE3"), + ) } } diff --git a/gluecodium/src/test/java/com/here/gluecodium/test/NiceErrorCollector.kt b/gluecodium/src/test/java/com/here/gluecodium/test/NiceErrorCollector.kt index 4e0cc35730..a94d7d326e 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/test/NiceErrorCollector.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/test/NiceErrorCollector.kt @@ -31,7 +31,10 @@ class NiceErrorCollector : ErrorCollector() { * Adds a failure with the given `message` to the table if `actualValue` is not null. * Execution continues, but the test will fail at the end if the match fails. */ - fun checkNotNull(message: String, value: T?) { + fun checkNotNull( + message: String, + value: T?, + ) { checkSucceeds { assertNotNull(message, value) value @@ -47,7 +50,11 @@ class NiceErrorCollector : ErrorCollector() { * ComparisonFailure object. This allows IntelliJ to format the message nicely with a link to * a diff of the values. */ - fun checkEquals(message: String, expectedValue: T, actualValue: T) { + fun checkEquals( + message: String, + expectedValue: T, + actualValue: T, + ) { checkSucceeds { assertEquals(message, expectedValue, actualValue) actualValue diff --git a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeAsyncValidatorTest.kt b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeAsyncValidatorTest.kt index fb9a2706e4..e0b689a93f 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeAsyncValidatorTest.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeAsyncValidatorTest.kt @@ -39,7 +39,6 @@ import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class LimeAsyncValidatorTest { - private val allElements = mutableMapOf() private val limeModel = LimeModel(allElements, emptyList()) @@ -111,12 +110,13 @@ class LimeAsyncValidatorTest { @Test fun validateAsyncProperty() { - allElements[""] = LimeProperty( - EMPTY_PATH, - typeRef = LimeBasicTypeRef.INT, - getter = LimeFunction(EMPTY_PATH), - attributes = asyncAttributes - ) + allElements[""] = + LimeProperty( + EMPTY_PATH, + typeRef = LimeBasicTypeRef.INT, + getter = LimeFunction(EMPTY_PATH), + attributes = asyncAttributes, + ) assertFalse(validator.validate(limeModel)) } diff --git a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeConstantRefsValidatorTest.kt b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeConstantRefsValidatorTest.kt index 9122663432..5e7b05d2eb 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeConstantRefsValidatorTest.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeConstantRefsValidatorTest.kt @@ -38,61 +38,66 @@ import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class LimeConstantRefsValidatorTest { - private val allElements = mutableMapOf() private val limeModel = LimeModel(allElements, emptyList()) - private val dummyEnumeratorRef = object : LimeConstantRef() { - override val element = LimeEnumerator(EMPTY_PATH) - override val typeRef = LimeBasicTypeRef.INT - } - private val throwingEnumeratorRef = object : LimeConstantRef() { - override val element - get() = throw LimeModelLoaderException("") - override val typeRef = LimeBasicTypeRef.INT - } + private val dummyEnumeratorRef = + object : LimeConstantRef() { + override val element = LimeEnumerator(EMPTY_PATH) + override val typeRef = LimeBasicTypeRef.INT + } + private val throwingEnumeratorRef = + object : LimeConstantRef() { + override val element + get() = throw LimeModelLoaderException("") + override val typeRef = LimeBasicTypeRef.INT + } private val validator = LimeConstantRefsValidator(mockk(relaxed = true)) @Test fun validateFieldWithValidRef() { - allElements[""] = LimeField( - EMPTY_PATH, - typeRef = LimeBasicTypeRef.INT, - defaultValue = LimeValue.Constant(LimeBasicTypeRef.INT, dummyEnumeratorRef) - ) + allElements[""] = + LimeField( + EMPTY_PATH, + typeRef = LimeBasicTypeRef.INT, + defaultValue = LimeValue.Constant(LimeBasicTypeRef.INT, dummyEnumeratorRef), + ) assertTrue(validator.validate(limeModel)) } @Test fun validateFieldWithInvalidRef() { - allElements[""] = LimeField( - EMPTY_PATH, - typeRef = LimeBasicTypeRef.INT, - defaultValue = LimeValue.Constant(LimeBasicTypeRef.INT, throwingEnumeratorRef) - ) + allElements[""] = + LimeField( + EMPTY_PATH, + typeRef = LimeBasicTypeRef.INT, + defaultValue = LimeValue.Constant(LimeBasicTypeRef.INT, throwingEnumeratorRef), + ) assertFalse(validator.validate(limeModel)) } @Test fun validateConstantWithValidRef() { - allElements[""] = LimeConstant( - EMPTY_PATH, - typeRef = LimeBasicTypeRef.INT, - value = LimeValue.Constant(LimeBasicTypeRef.INT, dummyEnumeratorRef) - ) + allElements[""] = + LimeConstant( + EMPTY_PATH, + typeRef = LimeBasicTypeRef.INT, + value = LimeValue.Constant(LimeBasicTypeRef.INT, dummyEnumeratorRef), + ) assertTrue(validator.validate(limeModel)) } @Test fun validateConstantWithInvalidRef() { - allElements[""] = LimeConstant( - EMPTY_PATH, - typeRef = LimeBasicTypeRef.INT, - value = LimeValue.Constant(LimeBasicTypeRef.INT, throwingEnumeratorRef) - ) + allElements[""] = + LimeConstant( + EMPTY_PATH, + typeRef = LimeBasicTypeRef.INT, + value = LimeValue.Constant(LimeBasicTypeRef.INT, throwingEnumeratorRef), + ) assertFalse(validator.validate(limeModel)) } diff --git a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeExternalTypesValidatorTest.kt b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeExternalTypesValidatorTest.kt index 4ae1ce28d4..454ef27481 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeExternalTypesValidatorTest.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeExternalTypesValidatorTest.kt @@ -40,7 +40,6 @@ import org.junit.runners.Parameterized @RunWith(Parameterized::class) class LimeExternalTypesValidatorTest(private val valueName: String) { - private val allElements = mutableMapOf() private val limeModel = LimeModel(allElements, emptyList()) @@ -48,27 +47,31 @@ class LimeExternalTypesValidatorTest(private val valueName: String) { @Test fun validateAsExternalType() { - allElements[""] = object : LimeType( - EMPTY_PATH, - external = LimeExternalDescriptor.Builder() - .addValue(CPP_TAG, INCLUDE_NAME, "") - .addValue(CPP_TAG, valueName, "") - .build() - ) {} + allElements[""] = + object : LimeType( + EMPTY_PATH, + external = + LimeExternalDescriptor.Builder() + .addValue(CPP_TAG, INCLUDE_NAME, "") + .addValue(CPP_TAG, valueName, "") + .build(), + ) {} assertTrue(validator.validate(limeModel)) } @Test fun validateInExternalType() { - allElements[""] = object : LimeType( - EMPTY_PATH, - external = LimeExternalDescriptor.Builder().addValue(CPP_TAG, INCLUDE_NAME, "").build() - ) {} - allElements["foo"] = object : LimeNamedElement( - LimePath(emptyList(), listOf("foo")), - external = LimeExternalDescriptor.Builder().addValue(CPP_TAG, valueName, "").build() - ) {} + allElements[""] = + object : LimeType( + EMPTY_PATH, + external = LimeExternalDescriptor.Builder().addValue(CPP_TAG, INCLUDE_NAME, "").build(), + ) {} + allElements["foo"] = + object : LimeNamedElement( + LimePath(emptyList(), listOf("foo")), + external = LimeExternalDescriptor.Builder().addValue(CPP_TAG, valueName, "").build(), + ) {} assertTrue(validator.validate(limeModel)) } @@ -76,10 +79,11 @@ class LimeExternalTypesValidatorTest(private val valueName: String) { @Test fun validateWithoutExternalType() { allElements[""] = object : LimeType(EMPTY_PATH) {} - allElements["foo"] = object : LimeNamedElement( - LimePath(emptyList(), listOf("foo")), - external = LimeExternalDescriptor.Builder().addValue(CPP_TAG, valueName, "").build() - ) {} + allElements["foo"] = + object : LimeNamedElement( + LimePath(emptyList(), listOf("foo")), + external = LimeExternalDescriptor.Builder().addValue(CPP_TAG, valueName, "").build(), + ) {} assertFalse(validator.validate(limeModel)) } @@ -87,10 +91,11 @@ class LimeExternalTypesValidatorTest(private val valueName: String) { companion object { @JvmStatic @Parameterized.Parameters - fun testData() = listOf( - arrayOf(NAME_NAME), - arrayOf(GETTER_NAME_NAME), - arrayOf(SETTER_NAME_NAME) - ) + fun testData() = + listOf( + arrayOf(NAME_NAME), + arrayOf(GETTER_NAME_NAME), + arrayOf(SETTER_NAME_NAME), + ) } } diff --git a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeFieldConstructorsValidatorTest.kt b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeFieldConstructorsValidatorTest.kt index 231dc355cd..3c729fb977 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeFieldConstructorsValidatorTest.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeFieldConstructorsValidatorTest.kt @@ -40,7 +40,6 @@ import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class LimeFieldConstructorsValidatorTest { - private val allElements = mutableMapOf() private val limeModel = LimeModel(allElements, emptyList()) @@ -49,16 +48,20 @@ class LimeFieldConstructorsValidatorTest { LimeField(LimePath(emptyList(), listOf("bar")), typeRef = LimeBasicTypeRef.INT, defaultValue = LimeValue.ZERO) private val limeStruct = LimeStruct(EMPTY_PATH, fields = listOf(fooField, barField)) private val structTypeRef = LimeDirectTypeRef(limeStruct) - private val fooFieldRef = object : LimeFieldRef() { override val field = fooField } + private val fooFieldRef = + object : LimeFieldRef() { + override val field = fooField + } private val validator = LimeFieldConstructorsValidator(mockk(relaxed = true)) @Test fun validateThrowingFieldRef() { - val throwingFieldRef = object : LimeFieldRef() { - override val field - get() = throw LimeModelLoaderException("") - } + val throwingFieldRef = + object : LimeFieldRef() { + override val field + get() = throw LimeModelLoaderException("") + } allElements[""] = LimeFieldConstructor(EMPTY_PATH, structRef = structTypeRef, fieldRefs = listOf(throwingFieldRef)) assertFalse(validator.validate(limeModel)) @@ -66,11 +69,12 @@ class LimeFieldConstructorsValidatorTest { @Test fun validateDuplicateEntries() { - allElements[""] = LimeFieldConstructor( - EMPTY_PATH, - structRef = structTypeRef, - fieldRefs = listOf(fooFieldRef, fooFieldRef) - ) + allElements[""] = + LimeFieldConstructor( + EMPTY_PATH, + structRef = structTypeRef, + fieldRefs = listOf(fooFieldRef, fooFieldRef), + ) assertFalse(validator.validate(limeModel)) } @@ -84,11 +88,17 @@ class LimeFieldConstructorsValidatorTest { @Test fun validateNonDefaultedOmitted() { - allElements[""] = LimeFieldConstructor( - EMPTY_PATH, - structRef = structTypeRef, - fieldRefs = listOf(object : LimeFieldRef() { override val field = barField }) - ) + allElements[""] = + LimeFieldConstructor( + EMPTY_PATH, + structRef = structTypeRef, + fieldRefs = + listOf( + object : LimeFieldRef() { + override val field = barField + }, + ), + ) assertFalse(validator.validate(limeModel)) } diff --git a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeFunctionsValidatorRefsTest.kt b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeFunctionsValidatorRefsTest.kt index fba1590a4d..1f4aa73ff8 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeFunctionsValidatorRefsTest.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeFunctionsValidatorRefsTest.kt @@ -39,7 +39,6 @@ import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class LimeFunctionsValidatorRefsTest { - private val allElements = mutableMapOf() private val barPath = LimePath(emptyList(), listOf("foo", "bar")) diff --git a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeFunctionsValidatorThrowsTest.kt b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeFunctionsValidatorThrowsTest.kt index f340a3071e..4ad1adce51 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeFunctionsValidatorThrowsTest.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeFunctionsValidatorThrowsTest.kt @@ -40,7 +40,6 @@ import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class LimeFunctionsValidatorThrowsTest { - private val fooPath = LimePath(emptyList(), listOf("foo")) private val barPath = fooPath.child("bar") diff --git a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeGenericTypesValidatorTest.kt b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeGenericTypesValidatorTest.kt index 6616cb8dc9..9aff8de61a 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeGenericTypesValidatorTest.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeGenericTypesValidatorTest.kt @@ -46,9 +46,8 @@ import org.junit.runners.Parameterized @RunWith(Parameterized::class) class LimeGenericTypesValidatorTest( private val limeType: LimeType, - private val expectedResult: Boolean + private val expectedResult: Boolean, ) { - private val allElements = mutableMapOf() private val limeModel = LimeModel(allElements, emptyList()) @@ -74,32 +73,33 @@ class LimeGenericTypesValidatorTest( companion object { @JvmStatic @Parameterized.Parameters - fun testData() = listOf( - arrayOf(LimeBasicType(LimeBasicType.TypeId.FLOAT), true), - arrayOf(LimeBasicType(LimeBasicType.TypeId.BLOB), false), - arrayOf(LimeBasicType(LimeBasicType.TypeId.DATE), true), - arrayOf(LimeEnumeration(EMPTY_PATH), true), - arrayOf(LimeList(LimeBasicTypeRef.INT), true), - arrayOf(LimeSet(LimeBasicTypeRef.INT), true), - arrayOf(LimeMap(LimeBasicTypeRef.INT, LimeBasicTypeRef.INT), true), - arrayOf( - LimeStruct( - EMPTY_PATH, - attributes = - LimeAttributes.Builder().addAttribute(LimeAttributeType.EQUATABLE).build() + fun testData() = + listOf( + arrayOf(LimeBasicType(LimeBasicType.TypeId.FLOAT), true), + arrayOf(LimeBasicType(LimeBasicType.TypeId.BLOB), false), + arrayOf(LimeBasicType(LimeBasicType.TypeId.DATE), true), + arrayOf(LimeEnumeration(EMPTY_PATH), true), + arrayOf(LimeList(LimeBasicTypeRef.INT), true), + arrayOf(LimeSet(LimeBasicTypeRef.INT), true), + arrayOf(LimeMap(LimeBasicTypeRef.INT, LimeBasicTypeRef.INT), true), + arrayOf( + LimeStruct( + EMPTY_PATH, + attributes = + LimeAttributes.Builder().addAttribute(LimeAttributeType.EQUATABLE).build(), + ), + true, ), - true - ), - arrayOf(LimeClass(EMPTY_PATH), true), - arrayOf(LimeInterface(EMPTY_PATH), true), - arrayOf(LimeTypeAlias(EMPTY_PATH, typeRef = LimeBasicTypeRef.INT), true), - arrayOf( - LimeTypeAlias( - EMPTY_PATH, - typeRef = LimeBasicTypeRef(LimeBasicType.TypeId.INT32, isNullable = true) + arrayOf(LimeClass(EMPTY_PATH), true), + arrayOf(LimeInterface(EMPTY_PATH), true), + arrayOf(LimeTypeAlias(EMPTY_PATH, typeRef = LimeBasicTypeRef.INT), true), + arrayOf( + LimeTypeAlias( + EMPTY_PATH, + typeRef = LimeBasicTypeRef(LimeBasicType.TypeId.INT32, isNullable = true), + ), + false, ), - false ) - ) } } diff --git a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeInheritanceValidatorClassTest.kt b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeInheritanceValidatorClassTest.kt index 18c741f2c7..3321dd98cb 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeInheritanceValidatorClassTest.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeInheritanceValidatorClassTest.kt @@ -37,7 +37,6 @@ import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class LimeInheritanceValidatorClassTest { - private val allElements = mutableMapOf() private val limeModel = LimeModel(allElements, emptyList()) @@ -114,10 +113,11 @@ class LimeInheritanceValidatorClassTest { fun validateClassWithClassAndNarrowParents() { val anotherClass = LimeClass(fooPath, isOpen = true) val narrowInterface = LimeInterface(barPath, isNarrow = true) - allElements[""] = LimeClass( - EMPTY_PATH, - parents = listOf(LimeDirectTypeRef(anotherClass), LimeDirectTypeRef(narrowInterface)) - ) + allElements[""] = + LimeClass( + EMPTY_PATH, + parents = listOf(LimeDirectTypeRef(anotherClass), LimeDirectTypeRef(narrowInterface)), + ) assertTrue(validator.validate(limeModel)) } @@ -128,10 +128,11 @@ class LimeInheritanceValidatorClassTest { val anotherClass = LimeClass(fooPath, parents = listOf(LimeDirectTypeRef(grandparentInterface))) val narrowInterface = LimeInterface(barPath, isNarrow = true, parents = listOf(LimeDirectTypeRef(grandparentInterface))) - allElements[""] = LimeClass( - EMPTY_PATH, - parents = listOf(LimeDirectTypeRef(anotherClass), LimeDirectTypeRef(narrowInterface)) - ) + allElements[""] = + LimeClass( + EMPTY_PATH, + parents = listOf(LimeDirectTypeRef(anotherClass), LimeDirectTypeRef(narrowInterface)), + ) assertFalse(validator.validate(limeModel)) } @@ -140,10 +141,11 @@ class LimeInheritanceValidatorClassTest { fun validateClassWithTwoInterfaceParents() { val anotherInterface = LimeInterface(fooPath) val yetAnotherInterface = LimeInterface(barPath) - allElements[""] = LimeClass( - EMPTY_PATH, - parents = listOf(LimeDirectTypeRef(anotherInterface), LimeDirectTypeRef(yetAnotherInterface)) - ) + allElements[""] = + LimeClass( + EMPTY_PATH, + parents = listOf(LimeDirectTypeRef(anotherInterface), LimeDirectTypeRef(yetAnotherInterface)), + ) assertFalse(validator.validate(limeModel)) } @@ -152,10 +154,11 @@ class LimeInheritanceValidatorClassTest { fun validateClassWithInterfaceAndNarrowParents() { val anotherInterface = LimeInterface(fooPath) val narrowInterface = LimeInterface(barPath, isNarrow = true) - allElements[""] = LimeClass( - EMPTY_PATH, - parents = listOf(LimeDirectTypeRef(anotherInterface), LimeDirectTypeRef(narrowInterface)) - ) + allElements[""] = + LimeClass( + EMPTY_PATH, + parents = listOf(LimeDirectTypeRef(anotherInterface), LimeDirectTypeRef(narrowInterface)), + ) assertTrue(validator.validate(limeModel)) } @@ -166,10 +169,11 @@ class LimeInheritanceValidatorClassTest { val anotherInterface = LimeInterface(fooPath, parents = listOf(LimeDirectTypeRef(grandparentInterface))) val narrowInterface = LimeInterface(barPath, isNarrow = true, parents = listOf(LimeDirectTypeRef(grandparentInterface))) - allElements[""] = LimeClass( - EMPTY_PATH, - parents = listOf(LimeDirectTypeRef(anotherInterface), LimeDirectTypeRef(narrowInterface)) - ) + allElements[""] = + LimeClass( + EMPTY_PATH, + parents = listOf(LimeDirectTypeRef(anotherInterface), LimeDirectTypeRef(narrowInterface)), + ) assertFalse(validator.validate(limeModel)) } diff --git a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeInheritanceValidatorInterfaceTest.kt b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeInheritanceValidatorInterfaceTest.kt index 38c819f891..d634f064fb 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeInheritanceValidatorInterfaceTest.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeInheritanceValidatorInterfaceTest.kt @@ -37,7 +37,6 @@ import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class LimeInheritanceValidatorInterfaceTest { - private val allElements = mutableMapOf() private val limeModel = LimeModel(allElements, emptyList()) @@ -96,10 +95,11 @@ class LimeInheritanceValidatorInterfaceTest { fun validateInterfaceWithTwoInterfaceParents() { val anotherInterface = LimeInterface(fooPath) val yetAnotherInterface = LimeInterface(barPath) - allElements[""] = LimeInterface( - EMPTY_PATH, - parents = listOf(LimeDirectTypeRef(anotherInterface), LimeDirectTypeRef(yetAnotherInterface)) - ) + allElements[""] = + LimeInterface( + EMPTY_PATH, + parents = listOf(LimeDirectTypeRef(anotherInterface), LimeDirectTypeRef(yetAnotherInterface)), + ) assertFalse(validator.validate(limeModel)) } @@ -108,10 +108,11 @@ class LimeInheritanceValidatorInterfaceTest { fun validateInterfaceWithInterfaceAndNarrowParents() { val anotherInterface = LimeInterface(fooPath) val narrowInterface = LimeInterface(barPath, isNarrow = true) - allElements[""] = LimeInterface( - EMPTY_PATH, - parents = listOf(LimeDirectTypeRef(anotherInterface), LimeDirectTypeRef(narrowInterface)) - ) + allElements[""] = + LimeInterface( + EMPTY_PATH, + parents = listOf(LimeDirectTypeRef(anotherInterface), LimeDirectTypeRef(narrowInterface)), + ) assertTrue(validator.validate(limeModel)) } @@ -122,10 +123,11 @@ class LimeInheritanceValidatorInterfaceTest { val anotherInterface = LimeInterface(fooPath, parents = listOf(LimeDirectTypeRef(grandparentInterface))) val narrowInterface = LimeInterface(barPath, isNarrow = true, parents = listOf(LimeDirectTypeRef(grandparentInterface))) - allElements[""] = LimeInterface( - EMPTY_PATH, - parents = listOf(LimeDirectTypeRef(anotherInterface), LimeDirectTypeRef(narrowInterface)) - ) + allElements[""] = + LimeInterface( + EMPTY_PATH, + parents = listOf(LimeDirectTypeRef(anotherInterface), LimeDirectTypeRef(narrowInterface)), + ) assertFalse(validator.validate(limeModel)) } diff --git a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeOptimizedListsValidatorTest.kt b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeOptimizedListsValidatorTest.kt index 7f46846c42..799647d59a 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeOptimizedListsValidatorTest.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeOptimizedListsValidatorTest.kt @@ -51,7 +51,6 @@ import org.junit.runners.Parameterized @RunWith(Parameterized::class) class LimeOptimizedListsValidatorTest(private val limeElement: LimeNamedElement, private val expectedResult: Boolean) { - private val allElements = mutableMapOf() private val limeModel = LimeModel(allElements, emptyList()) @@ -73,66 +72,67 @@ class LimeOptimizedListsValidatorTest(private val limeElement: LimeNamedElement, @JvmStatic @Parameterized.Parameters - fun testData() = listOf( - arrayOf(LimeConstant(EMPTY_PATH, typeRef = typeRef, value = LimeValue.ZERO), true), - arrayOf(LimeConstant(EMPTY_PATH, typeRef = optimizedListTypeRef, value = LimeValue.ZERO), false), - arrayOf(LimeTypeAlias(EMPTY_PATH, typeRef = typeRef), true), - arrayOf(LimeTypeAlias(EMPTY_PATH, typeRef = optimizedListTypeRef), false), - arrayOf(LimeException(EMPTY_PATH, errorType = typeRef), true), - arrayOf(LimeException(EMPTY_PATH, errorType = optimizedListTypeRef), false), - arrayOf(object : LimeContainerWithInheritance(EMPTY_PATH) {}, true), - arrayOf(object : LimeContainerWithInheritance(EMPTY_PATH, parents = listOf(typeRef)) {}, true), - arrayOf(object : LimeContainerWithInheritance(EMPTY_PATH, parents = listOf(optimizedListTypeRef)) {}, false), - arrayOf(LimeLambda(EMPTY_PATH), true), - arrayOf(LimeLambda(EMPTY_PATH, returnType = LimeReturnType(typeRef)), true), - arrayOf(LimeLambda(EMPTY_PATH, returnType = LimeReturnType(optimizedListTypeRef)), false), - arrayOf(LimeLambda(EMPTY_PATH, parameters = listOf(LimeLambdaParameter(typeRef, EMPTY_PATH))), true), - arrayOf(LimeLambda(EMPTY_PATH, parameters = listOf(LimeLambdaParameter(optimizedListTypeRef, EMPTY_PATH))), false), - arrayOf(LimeFunction(EMPTY_PATH), true), - arrayOf(LimeFunction(EMPTY_PATH, parameters = listOf(LimeParameter(EMPTY_PATH, typeRef = typeRef))), true), - arrayOf( - LimeFunction( - EMPTY_PATH, - parameters = listOf(LimeParameter(EMPTY_PATH, typeRef = optimizedListTypeRef)) + fun testData() = + listOf( + arrayOf(LimeConstant(EMPTY_PATH, typeRef = typeRef, value = LimeValue.ZERO), true), + arrayOf(LimeConstant(EMPTY_PATH, typeRef = optimizedListTypeRef, value = LimeValue.ZERO), false), + arrayOf(LimeTypeAlias(EMPTY_PATH, typeRef = typeRef), true), + arrayOf(LimeTypeAlias(EMPTY_PATH, typeRef = optimizedListTypeRef), false), + arrayOf(LimeException(EMPTY_PATH, errorType = typeRef), true), + arrayOf(LimeException(EMPTY_PATH, errorType = optimizedListTypeRef), false), + arrayOf(object : LimeContainerWithInheritance(EMPTY_PATH) {}, true), + arrayOf(object : LimeContainerWithInheritance(EMPTY_PATH, parents = listOf(typeRef)) {}, true), + arrayOf(object : LimeContainerWithInheritance(EMPTY_PATH, parents = listOf(optimizedListTypeRef)) {}, false), + arrayOf(LimeLambda(EMPTY_PATH), true), + arrayOf(LimeLambda(EMPTY_PATH, returnType = LimeReturnType(typeRef)), true), + arrayOf(LimeLambda(EMPTY_PATH, returnType = LimeReturnType(optimizedListTypeRef)), false), + arrayOf(LimeLambda(EMPTY_PATH, parameters = listOf(LimeLambdaParameter(typeRef, EMPTY_PATH))), true), + arrayOf(LimeLambda(EMPTY_PATH, parameters = listOf(LimeLambdaParameter(optimizedListTypeRef, EMPTY_PATH))), false), + arrayOf(LimeFunction(EMPTY_PATH), true), + arrayOf(LimeFunction(EMPTY_PATH, parameters = listOf(LimeParameter(EMPTY_PATH, typeRef = typeRef))), true), + arrayOf( + LimeFunction( + EMPTY_PATH, + parameters = listOf(LimeParameter(EMPTY_PATH, typeRef = optimizedListTypeRef)), + ), + false, ), - false - ), - arrayOf(LimeFunction(EMPTY_PATH, thrownType = LimeThrownType(typeRef)), true), - arrayOf(LimeFunction(EMPTY_PATH, thrownType = LimeThrownType(optimizedListTypeRef)), false), - arrayOf(LimeFunction(EMPTY_PATH, returnType = LimeReturnType(typeRef)), true), - arrayOf(LimeFunction(EMPTY_PATH, returnType = LimeReturnType(optimizedTypeRef)), false), - arrayOf(LimeFunction(EMPTY_PATH, returnType = LimeReturnType(optimizedListTypeRef)), true), - arrayOf(LimeProperty(EMPTY_PATH, typeRef = typeRef, getter = LimeFunction(EMPTY_PATH)), true), - arrayOf(LimeProperty(EMPTY_PATH, typeRef = optimizedTypeRef, getter = LimeFunction(EMPTY_PATH)), false), - arrayOf(LimeProperty(EMPTY_PATH, typeRef = optimizedListTypeRef, getter = LimeFunction(EMPTY_PATH)), true), - arrayOf( - LimeProperty( - EMPTY_PATH, - typeRef = optimizedListTypeRef, - getter = LimeFunction(EMPTY_PATH), - setter = LimeFunction(EMPTY_PATH) + arrayOf(LimeFunction(EMPTY_PATH, thrownType = LimeThrownType(typeRef)), true), + arrayOf(LimeFunction(EMPTY_PATH, thrownType = LimeThrownType(optimizedListTypeRef)), false), + arrayOf(LimeFunction(EMPTY_PATH, returnType = LimeReturnType(typeRef)), true), + arrayOf(LimeFunction(EMPTY_PATH, returnType = LimeReturnType(optimizedTypeRef)), false), + arrayOf(LimeFunction(EMPTY_PATH, returnType = LimeReturnType(optimizedListTypeRef)), true), + arrayOf(LimeProperty(EMPTY_PATH, typeRef = typeRef, getter = LimeFunction(EMPTY_PATH)), true), + arrayOf(LimeProperty(EMPTY_PATH, typeRef = optimizedTypeRef, getter = LimeFunction(EMPTY_PATH)), false), + arrayOf(LimeProperty(EMPTY_PATH, typeRef = optimizedListTypeRef, getter = LimeFunction(EMPTY_PATH)), true), + arrayOf( + LimeProperty( + EMPTY_PATH, + typeRef = optimizedListTypeRef, + getter = LimeFunction(EMPTY_PATH), + setter = LimeFunction(EMPTY_PATH), + ), + false, ), - false - ), - arrayOf(LimeStruct(EMPTY_PATH), true), - arrayOf(LimeStruct(EMPTY_PATH, fields = listOf(LimeField(EMPTY_PATH, typeRef = typeRef))), true), - arrayOf(LimeStruct(EMPTY_PATH, fields = listOf(LimeField(EMPTY_PATH, typeRef = optimizedListTypeRef))), false), - arrayOf( - LimeStruct( - EMPTY_PATH, - fields = listOf(LimeField(EMPTY_PATH, typeRef = optimizedTypeRef)), - attributes = immutableAttributes + arrayOf(LimeStruct(EMPTY_PATH), true), + arrayOf(LimeStruct(EMPTY_PATH, fields = listOf(LimeField(EMPTY_PATH, typeRef = typeRef))), true), + arrayOf(LimeStruct(EMPTY_PATH, fields = listOf(LimeField(EMPTY_PATH, typeRef = optimizedListTypeRef))), false), + arrayOf( + LimeStruct( + EMPTY_PATH, + fields = listOf(LimeField(EMPTY_PATH, typeRef = optimizedTypeRef)), + attributes = immutableAttributes, + ), + false, ), - false - ), - arrayOf( - LimeStruct( - EMPTY_PATH, - fields = listOf(LimeField(EMPTY_PATH, typeRef = optimizedListTypeRef)), - attributes = immutableAttributes + arrayOf( + LimeStruct( + EMPTY_PATH, + fields = listOf(LimeField(EMPTY_PATH, typeRef = optimizedListTypeRef)), + attributes = immutableAttributes, + ), + true, ), - true - ), - ) + ) } } diff --git a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeOverloadsValidatorFieldConstructorsTest.kt b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeOverloadsValidatorFieldConstructorsTest.kt index d41530fc08..c82d78f4b0 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeOverloadsValidatorFieldConstructorsTest.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeOverloadsValidatorFieldConstructorsTest.kt @@ -39,16 +39,16 @@ import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class LimeOverloadsValidatorFieldConstructorsTest { - private val allElements = mutableMapOf() private val fooPath = LimePath(emptyList(), listOf("foo")) private val fooRef = LimeLazyTypeRef("foo", allElements) private val fcPath1 = fooPath.child("", "1") private val fcPath2 = fooPath.child("", "2") private val weePath = fooPath.child("wee") - private val limeFieldRef = object : LimeFieldRef() { - override val field = LimeField(fooPath.child("bar"), typeRef = LimeBasicTypeRef.INT) - } + private val limeFieldRef = + object : LimeFieldRef() { + override val field = LimeField(fooPath.child("bar"), typeRef = LimeBasicTypeRef.INT) + } private val validatorNoCustomConstructors = LimeOverloadsValidator(LimeSignatureResolver(allElements), mockk(relaxed = true), false) @@ -104,11 +104,12 @@ class LimeOverloadsValidatorFieldConstructorsTest { @Test fun validateFieldCustomConstructorsInvalid() { val fieldConstructor = LimeFieldConstructor(fcPath1, structRef = fooRef, fieldRefs = listOf(limeFieldRef)) - val customConstructor = LimeFunction( - weePath, - isConstructor = true, - parameters = listOf(LimeParameter(weePath.child("baz"), typeRef = LimeBasicTypeRef.INT)) - ) + val customConstructor = + LimeFunction( + weePath, + isConstructor = true, + parameters = listOf(LimeParameter(weePath.child("baz"), typeRef = LimeBasicTypeRef.INT)), + ) allElements[fcPath1.toString()] = fieldConstructor allElements[weePath.toString()] = customConstructor allElements[fooPath.toString()] = diff --git a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeOverloadsValidatorTest.kt b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeOverloadsValidatorTest.kt index 3d6df60bb9..446df83316 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeOverloadsValidatorTest.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeOverloadsValidatorTest.kt @@ -39,7 +39,7 @@ class LimeOverloadsValidatorTest( private val limeMethod1: LimeFunction, private val limeMethod2: LimeFunction, private val expectedResultNoConstructors: Boolean, - private val expectedResultWithConstructors: Boolean + private val expectedResultWithConstructors: Boolean, ) { private val allElements = mutableMapOf() @@ -73,49 +73,50 @@ class LimeOverloadsValidatorTest( @JvmStatic @Parameterized.Parameters - fun testData() = listOf( - arrayOf( - LimeFunction(barPath.withSuffix("0")), - LimeFunction(barPath.withSuffix("1"), parameters = listOf(limeParameter)), - true, - true - ), - arrayOf( - LimeFunction(barPath.withSuffix("0"), parameters = listOf(limeParameter)), - LimeFunction(barPath.withSuffix("1"), parameters = listOf(limeParameter)), - false, - false - ), - arrayOf( - LimeFunction(barPath.withSuffix("0"), isConstructor = true), - LimeFunction(barPath.withSuffix("1"), isConstructor = true, parameters = listOf(limeParameter)), - true, - true - ), - arrayOf( - LimeFunction(barPath.withSuffix("0"), isConstructor = true, parameters = listOf(limeParameter)), - LimeFunction(barPath.withSuffix("1"), isConstructor = true, parameters = listOf(limeParameter)), - false, - false - ), - arrayOf( - LimeFunction(barPath.withSuffix("0")), - LimeFunction(barPath.withSuffix("1"), isConstructor = true, parameters = listOf(limeParameter)), - true, - true - ), - arrayOf( - LimeFunction(barPath.withSuffix("0"), parameters = listOf(limeParameter)), - LimeFunction(barPath.withSuffix("1"), isConstructor = true, parameters = listOf(limeParameter)), - false, - false - ), - arrayOf( - LimeFunction(barPath, isConstructor = true, parameters = listOf(limeParameter)), - LimeFunction(fooPath.child("wee"), isConstructor = true, parameters = listOf(limeParameter)), - true, - false + fun testData() = + listOf( + arrayOf( + LimeFunction(barPath.withSuffix("0")), + LimeFunction(barPath.withSuffix("1"), parameters = listOf(limeParameter)), + true, + true, + ), + arrayOf( + LimeFunction(barPath.withSuffix("0"), parameters = listOf(limeParameter)), + LimeFunction(barPath.withSuffix("1"), parameters = listOf(limeParameter)), + false, + false, + ), + arrayOf( + LimeFunction(barPath.withSuffix("0"), isConstructor = true), + LimeFunction(barPath.withSuffix("1"), isConstructor = true, parameters = listOf(limeParameter)), + true, + true, + ), + arrayOf( + LimeFunction(barPath.withSuffix("0"), isConstructor = true, parameters = listOf(limeParameter)), + LimeFunction(barPath.withSuffix("1"), isConstructor = true, parameters = listOf(limeParameter)), + false, + false, + ), + arrayOf( + LimeFunction(barPath.withSuffix("0")), + LimeFunction(barPath.withSuffix("1"), isConstructor = true, parameters = listOf(limeParameter)), + true, + true, + ), + arrayOf( + LimeFunction(barPath.withSuffix("0"), parameters = listOf(limeParameter)), + LimeFunction(barPath.withSuffix("1"), isConstructor = true, parameters = listOf(limeParameter)), + false, + false, + ), + arrayOf( + LimeFunction(barPath, isConstructor = true, parameters = listOf(limeParameter)), + LimeFunction(fooPath.child("wee"), isConstructor = true, parameters = listOf(limeParameter)), + true, + false, + ), ) - ) } } diff --git a/gluecodium/src/test/java/com/here/gluecodium/validator/LimePropertiesValidatorTest.kt b/gluecodium/src/test/java/com/here/gluecodium/validator/LimePropertiesValidatorTest.kt index 53d772780d..a81f9c4a76 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/validator/LimePropertiesValidatorTest.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/validator/LimePropertiesValidatorTest.kt @@ -42,39 +42,43 @@ import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class LimePropertiesValidatorTest { - private val allElements = mutableMapOf() private val fooPath = LimePath(emptyList(), listOf("foo")) private val limeModel = LimeModel(allElements, emptyList()) private val limeFunction = LimeFunction(EMPTY_PATH) - private val limePropertyFoo = LimeProperty( - fooPath, - typeRef = LimeBasicTypeRef.INT, - getter = limeFunction - ) - private val limePropertyBar = LimeProperty( - LimePath(emptyList(), listOf("bar")), - typeRef = LimeBasicTypeRef.INT, - getter = limeFunction - ) - private val limePropertyFoo2 = LimeProperty( - LimePath(listOf("baz"), listOf("foo")), - typeRef = LimeBasicTypeRef.INT, - getter = limeFunction - ) - private val limeContainerDoubleFoo = object : LimeContainerWithInheritance( - EMPTY_PATH, - properties = listOf(limePropertyFoo, limePropertyFoo2) - ) {} + private val limePropertyFoo = + LimeProperty( + fooPath, + typeRef = LimeBasicTypeRef.INT, + getter = limeFunction, + ) + private val limePropertyBar = + LimeProperty( + LimePath(emptyList(), listOf("bar")), + typeRef = LimeBasicTypeRef.INT, + getter = limeFunction, + ) + private val limePropertyFoo2 = + LimeProperty( + LimePath(listOf("baz"), listOf("foo")), + typeRef = LimeBasicTypeRef.INT, + getter = limeFunction, + ) + private val limeContainerDoubleFoo = + object : LimeContainerWithInheritance( + EMPTY_PATH, + properties = listOf(limePropertyFoo, limePropertyFoo2), + ) {} private val cachedAttributes = LimeAttributes.Builder().addAttribute(LimeAttributeType.CACHED).build() private val cppRefAttributes = LimeAttributes.Builder().addAttribute(LimeAttributeType.CPP, LimeAttributeValueType.REF).build() - private val cppRefProperty = LimeProperty( - fooPath.child("bar"), - typeRef = LimeBasicTypeRef.INT, - getter = limeFunction, - attributes = cppRefAttributes - ) + private val cppRefProperty = + LimeProperty( + fooPath.child("bar"), + typeRef = LimeBasicTypeRef.INT, + getter = limeFunction, + attributes = cppRefAttributes, + ) private val validator = LimePropertiesValidator(mockk(relaxed = true)) @@ -87,10 +91,11 @@ class LimePropertiesValidatorTest { @Test fun validatePropertiesNoNameClash() { - allElements[""] = object : LimeContainerWithInheritance( - EMPTY_PATH, - properties = listOf(limePropertyFoo, limePropertyBar) - ) {} + allElements[""] = + object : LimeContainerWithInheritance( + EMPTY_PATH, + properties = listOf(limePropertyFoo, limePropertyBar), + ) {} assertTrue(validator.validate(limeModel)) } @@ -104,44 +109,48 @@ class LimePropertiesValidatorTest { @Test fun validateInheritanceNoOwnProperties() { - allElements[""] = object : LimeContainerWithInheritance( - EMPTY_PATH, - parents = listOf(LimeDirectTypeRef(limeContainerDoubleFoo)) - ) {} + allElements[""] = + object : LimeContainerWithInheritance( + EMPTY_PATH, + parents = listOf(LimeDirectTypeRef(limeContainerDoubleFoo)), + ) {} assertTrue(validator.validate(limeModel)) } @Test fun validatePropertiesInheritanceNoNameClash() { - allElements[""] = object : LimeContainerWithInheritance( - EMPTY_PATH, - parents = listOf(LimeDirectTypeRef(limeContainerDoubleFoo)), - properties = listOf(limePropertyBar) - ) {} + allElements[""] = + object : LimeContainerWithInheritance( + EMPTY_PATH, + parents = listOf(LimeDirectTypeRef(limeContainerDoubleFoo)), + properties = listOf(limePropertyBar), + ) {} assertTrue(validator.validate(limeModel)) } @Test fun validatePropertiesInheritanceWithNameClash() { - allElements[""] = object : LimeContainerWithInheritance( - EMPTY_PATH, - parents = listOf(LimeDirectTypeRef(limeContainerDoubleFoo)), - properties = listOf(limePropertyFoo) - ) {} + allElements[""] = + object : LimeContainerWithInheritance( + EMPTY_PATH, + parents = listOf(LimeDirectTypeRef(limeContainerDoubleFoo)), + properties = listOf(limePropertyFoo), + ) {} assertFalse(validator.validate(limeModel)) } @Test fun validateCachedReadOnlyProperty() { - val limeProperty = LimeProperty( - path = fooPath, - typeRef = LimeBasicTypeRef.INT, - getter = limeFunction, - attributes = cachedAttributes - ) + val limeProperty = + LimeProperty( + path = fooPath, + typeRef = LimeBasicTypeRef.INT, + getter = limeFunction, + attributes = cachedAttributes, + ) allElements[""] = object : LimeContainerWithInheritance(EMPTY_PATH, properties = listOf(limeProperty)) {} @@ -150,13 +159,14 @@ class LimePropertiesValidatorTest { @Test fun validateCachedReadWriteProperty() { - val limeProperty = LimeProperty( - path = fooPath, - typeRef = LimeBasicTypeRef.INT, - getter = limeFunction, - setter = limeFunction, - attributes = cachedAttributes - ) + val limeProperty = + LimeProperty( + path = fooPath, + typeRef = LimeBasicTypeRef.INT, + getter = limeFunction, + setter = limeFunction, + attributes = cachedAttributes, + ) allElements[""] = object : LimeContainerWithInheritance(EMPTY_PATH, properties = listOf(limeProperty)) {} diff --git a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeSerializableStructsValidatorTest.kt b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeSerializableStructsValidatorTest.kt index 8b2f99e0c0..016280b85c 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeSerializableStructsValidatorTest.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeSerializableStructsValidatorTest.kt @@ -40,7 +40,6 @@ import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class LimeSerializableStructsValidatorTest { - private val allElements = mutableMapOf() private val limeModel = LimeModel(allElements, emptyList()) diff --git a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeSkipValidatorTest.kt b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeSkipValidatorTest.kt index 59e39f5401..b947a39799 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeSkipValidatorTest.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeSkipValidatorTest.kt @@ -44,7 +44,6 @@ import org.junit.runners.Parameterized @RunWith(Parameterized::class) class LimeSkipValidatorTest(private val platformAttribute: LimeAttributeType?) { - private val allElements = mutableMapOf() private val limeModel = LimeModel(allElements, emptyList()) @@ -65,11 +64,12 @@ class LimeSkipValidatorTest(private val platformAttribute: LimeAttributeType?) { val attributesBuilder = LimeAttributes.Builder() if (platformAttribute != null) attributesBuilder.addAttribute(platformAttribute, SKIP) val limeField = LimeField(EMPTY_PATH, typeRef = LimeBasicTypeRef.INT, attributes = attributesBuilder.build()) - allElements[""] = LimeStruct( - EMPTY_PATH, - fields = listOf(limeField), - attributes = LimeAttributes.Builder().addAttribute(IMMUTABLE).build() - ) + allElements[""] = + LimeStruct( + EMPTY_PATH, + fields = listOf(limeField), + attributes = LimeAttributes.Builder().addAttribute(IMMUTABLE).build(), + ) val expectedResult = platformAttribute == null assertEquals(expectedResult, validator.validate(limeModel)) @@ -77,10 +77,11 @@ class LimeSkipValidatorTest(private val platformAttribute: LimeAttributeType?) { @Test fun validateStructWithImmutableFields() { - val immutableStruct = LimeStruct( - EMPTY_PATH, - attributes = LimeAttributes.Builder().addAttribute(IMMUTABLE).build() - ) + val immutableStruct = + LimeStruct( + EMPTY_PATH, + attributes = LimeAttributes.Builder().addAttribute(IMMUTABLE).build(), + ) val attributesBuilder = LimeAttributes.Builder() if (platformAttribute != null) attributesBuilder.addAttribute(platformAttribute, SKIP) val limeField = @@ -95,35 +96,39 @@ class LimeSkipValidatorTest(private val platformAttribute: LimeAttributeType?) { fun validateImmutableStructWithDefaultValue() { val attributesBuilder = LimeAttributes.Builder() if (platformAttribute != null) attributesBuilder.addAttribute(platformAttribute, SKIP) - val limeField = LimeField( - EMPTY_PATH, - typeRef = LimeBasicTypeRef.INT, - attributes = attributesBuilder.build(), - defaultValue = LimeValue.ZERO - ) - allElements[""] = LimeStruct( - EMPTY_PATH, - fields = listOf(limeField), - attributes = LimeAttributes.Builder().addAttribute(IMMUTABLE).build() - ) + val limeField = + LimeField( + EMPTY_PATH, + typeRef = LimeBasicTypeRef.INT, + attributes = attributesBuilder.build(), + defaultValue = LimeValue.ZERO, + ) + allElements[""] = + LimeStruct( + EMPTY_PATH, + fields = listOf(limeField), + attributes = LimeAttributes.Builder().addAttribute(IMMUTABLE).build(), + ) assertTrue(validator.validate(limeModel)) } @Test fun validateStructWithImmutableFieldsWithDefaultValue() { - val immutableStruct = LimeStruct( - EMPTY_PATH, - attributes = LimeAttributes.Builder().addAttribute(IMMUTABLE).build() - ) + val immutableStruct = + LimeStruct( + EMPTY_PATH, + attributes = LimeAttributes.Builder().addAttribute(IMMUTABLE).build(), + ) val attributesBuilder = LimeAttributes.Builder() if (platformAttribute != null) attributesBuilder.addAttribute(platformAttribute, SKIP) - val limeField = LimeField( - EMPTY_PATH, - typeRef = LimeDirectTypeRef(immutableStruct), - attributes = attributesBuilder.build(), - defaultValue = LimeValue.ZERO - ) + val limeField = + LimeField( + EMPTY_PATH, + typeRef = LimeDirectTypeRef(immutableStruct), + attributes = attributesBuilder.build(), + defaultValue = LimeValue.ZERO, + ) allElements[""] = LimeStruct(EMPTY_PATH, fields = listOf(limeField)) assertTrue(validator.validate(limeModel)) diff --git a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeStructsValidatorStrictTest.kt b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeStructsValidatorStrictTest.kt index 574edf8388..82f0432c1d 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeStructsValidatorStrictTest.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeStructsValidatorStrictTest.kt @@ -39,7 +39,6 @@ import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class LimeStructsValidatorStrictTest { - private val allElements = mutableMapOf() private val limeModel = LimeModel(allElements, emptyList()) @@ -62,12 +61,13 @@ class LimeStructsValidatorStrictTest { @Test fun validateImmutableStructWithFieldConstructors() { - allElements[""] = LimeStruct( - EMPTY_PATH, - fields = listOf(limeField), - attributes = immutableAttributes, - fieldConstructors = listOf(fieldConstructor) - ) + allElements[""] = + LimeStruct( + EMPTY_PATH, + fields = listOf(limeField), + attributes = immutableAttributes, + fieldConstructors = listOf(fieldConstructor), + ) assertTrue(validator.validate(limeModel)) } @@ -75,12 +75,13 @@ class LimeStructsValidatorStrictTest { @Test fun validateImmutableStructWithCustomConstructors() { val customConstructor = LimeFunction(EMPTY_PATH, isConstructor = true) - allElements[""] = LimeStruct( - EMPTY_PATH, - fields = listOf(limeField), - attributes = immutableAttributes, - functions = listOf(customConstructor) - ) + allElements[""] = + LimeStruct( + EMPTY_PATH, + fields = listOf(limeField), + attributes = immutableAttributes, + functions = listOf(customConstructor), + ) assertTrue(validator.validate(limeModel)) } @@ -94,11 +95,12 @@ class LimeStructsValidatorStrictTest { @Test fun validateMutableStructWithFieldConstructors() { - allElements[""] = LimeStruct( - EMPTY_PATH, - fields = listOf(limeField), - fieldConstructors = listOf(fieldConstructor) - ) + allElements[""] = + LimeStruct( + EMPTY_PATH, + fields = listOf(limeField), + fieldConstructors = listOf(fieldConstructor), + ) assertTrue(validator.validate(limeModel)) } @@ -119,11 +121,12 @@ class LimeStructsValidatorStrictTest { @Test fun validateInternalFieldWithFieldConstructors() { - allElements[""] = LimeStruct( - EMPTY_PATH, - fields = listOf(internalField), - fieldConstructors = listOf(fieldConstructor) - ) + allElements[""] = + LimeStruct( + EMPTY_PATH, + fields = listOf(internalField), + fieldConstructors = listOf(fieldConstructor), + ) assertTrue(validator.validate(limeModel)) } @@ -137,12 +140,13 @@ class LimeStructsValidatorStrictTest { @Test fun validateInternalFieldWithDefaultValue() { - val internalFieldWithDefault = LimeField( - EMPTY_PATH, - typeRef = LimeBasicTypeRef.INT, - attributes = internalAttributes, - defaultValue = LimeValue.ZERO - ) + val internalFieldWithDefault = + LimeField( + EMPTY_PATH, + typeRef = LimeBasicTypeRef.INT, + attributes = internalAttributes, + defaultValue = LimeValue.ZERO, + ) allElements[""] = LimeStruct(EMPTY_PATH, fields = listOf(internalFieldWithDefault)) assertTrue(validator.validate(limeModel)) diff --git a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeStructsValidatorTest.kt b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeStructsValidatorTest.kt index dba1855b05..3bfea1a77b 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeStructsValidatorTest.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeStructsValidatorTest.kt @@ -35,7 +35,6 @@ import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class LimeStructsValidatorTest { - private val allElements = mutableMapOf() private val limeModel = LimeModel(allElements, emptyList()) diff --git a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeTypeRefTargetValidatorTest.kt b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeTypeRefTargetValidatorTest.kt index f7c58691a6..af43775727 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeTypeRefTargetValidatorTest.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeTypeRefTargetValidatorTest.kt @@ -40,7 +40,6 @@ import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class LimeTypeRefTargetValidatorTest { - private val allElements = mutableMapOf() private val limeModel = LimeModel(allElements, emptyList()) diff --git a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeTypeRefsValidatorTest.kt b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeTypeRefsValidatorTest.kt index 1b6cb9ee77..8c4b970e77 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeTypeRefsValidatorTest.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeTypeRefsValidatorTest.kt @@ -42,22 +42,25 @@ import org.junit.runners.Parameterized @RunWith(Parameterized::class) class LimeTypeRefsValidatorTest(private val createElement: (LimeTypeRef) -> LimeElement) { - private val allElements = mutableMapOf() private val limeModel = LimeModel(allElements, emptyList()) - private val dummyTypeRef = object : LimeTypeRef() { - override val elementFullName = "" - override val type = LimeBasicType(LimeBasicType.TypeId.VOID) - override val isNullable = false - override fun asNullable() = this - } - private val throwingTypeRef = object : LimeTypeRef() { - override val elementFullName = "" - override val type - get() = throw LimeModelLoaderException("") - override val isNullable = false - override fun asNullable() = this - } + private val dummyTypeRef = + object : LimeTypeRef() { + override val elementFullName = "" + override val type = LimeBasicType(LimeBasicType.TypeId.VOID) + override val isNullable = false + + override fun asNullable() = this + } + private val throwingTypeRef = + object : LimeTypeRef() { + override val elementFullName = "" + override val type + get() = throw LimeModelLoaderException("") + override val isNullable = false + + override fun asNullable() = this + } private val validator = LimeTypeRefsValidator(mockk(relaxed = true)) @@ -65,7 +68,7 @@ class LimeTypeRefsValidatorTest(private val createElement: (LimeTypeRef) -> Lime path = EMPTY_PATH, comment = LimeComment(), attributes = null, - typeRef = limeTypeRef + typeRef = limeTypeRef, ) @Test @@ -85,20 +88,21 @@ class LimeTypeRefsValidatorTest(private val createElement: (LimeTypeRef) -> Lime companion object { @JvmStatic @Parameterized.Parameters - fun testData() = listOf( - arrayOf<(LimeTypeRef) -> LimeElement>({ DummyTypedElement(it) }), - arrayOf<(LimeTypeRef) -> LimeElement>( - { LimeFunction(EMPTY_PATH, returnType = LimeReturnType(it)) } - ), - arrayOf<(LimeTypeRef) -> LimeElement>({ - LimeFunction( - EMPTY_PATH, - thrownType = LimeThrownType(it) - ) - }), - arrayOf<(LimeTypeRef) -> LimeElement>({ LimeClass(EMPTY_PATH, parents = listOf(it)) }), - arrayOf<(LimeTypeRef) -> LimeElement>({ LimeTypeAlias(EMPTY_PATH, typeRef = it) }), - arrayOf<(LimeTypeRef) -> LimeElement>({ LimeException(EMPTY_PATH, errorType = it) }) - ) + fun testData() = + listOf( + arrayOf<(LimeTypeRef) -> LimeElement>({ DummyTypedElement(it) }), + arrayOf<(LimeTypeRef) -> LimeElement>( + { LimeFunction(EMPTY_PATH, returnType = LimeReturnType(it)) }, + ), + arrayOf<(LimeTypeRef) -> LimeElement>({ + LimeFunction( + EMPTY_PATH, + thrownType = LimeThrownType(it), + ) + }), + arrayOf<(LimeTypeRef) -> LimeElement>({ LimeClass(EMPTY_PATH, parents = listOf(it)) }), + arrayOf<(LimeTypeRef) -> LimeElement>({ LimeTypeAlias(EMPTY_PATH, typeRef = it) }), + arrayOf<(LimeTypeRef) -> LimeElement>({ LimeException(EMPTY_PATH, errorType = it) }), + ) } } diff --git a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeValuesValidatorTest.kt b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeValuesValidatorTest.kt index a6adb5e3cd..837633075a 100644 --- a/gluecodium/src/test/java/com/here/gluecodium/validator/LimeValuesValidatorTest.kt +++ b/gluecodium/src/test/java/com/here/gluecodium/validator/LimeValuesValidatorTest.kt @@ -45,7 +45,7 @@ import org.junit.runners.Parameterized class LimeValuesValidatorTest( private val limeTypeRef: LimeTypeRef, private val limeValue: LimeValue, - private val expectedResult: Boolean + private val expectedResult: Boolean, ) { private val allElements = mutableMapOf() private val limeModel = LimeModel(allElements, emptyList()) @@ -72,70 +72,71 @@ class LimeValuesValidatorTest( @JvmStatic @Parameterized.Parameters - fun testData() = listOf( - arrayOf(LimeBasicTypeRef.INT, LimeValue.Literal(fooTypeRef, ""), true), - arrayOf(LimeBasicTypeRef.FLOAT, LimeValue.Literal(fooTypeRef, ""), true), - arrayOf(LimeBasicTypeRef(LimeBasicType.TypeId.BOOLEAN), LimeValue.Literal(fooTypeRef, ""), true), - arrayOf(LimeBasicTypeRef(LimeBasicType.TypeId.STRING), LimeValue.Literal(fooTypeRef, ""), true), - arrayOf( - LimeBasicTypeRef(LimeBasicType.TypeId.DATE), - LimeValue.Literal(fooTypeRef, "2022-02-04T09:15:17Z"), - true - ), - arrayOf(LimeBasicTypeRef(LimeBasicType.TypeId.DATE), LimeValue.Literal(fooTypeRef, "bar"), false), - arrayOf(LimeBasicTypeRef(LimeBasicType.TypeId.LOCALE), LimeValue.Literal(fooTypeRef, "en-US"), true), - arrayOf(LimeBasicTypeRef(LimeBasicType.TypeId.LOCALE), LimeValue.Literal(fooTypeRef, "und"), true), - arrayOf(LimeBasicTypeRef(LimeBasicType.TypeId.LOCALE), LimeValue.Literal(fooTypeRef, "42"), false), - arrayOf(LimeBasicTypeRef(LimeBasicType.TypeId.BLOB), LimeValue.Literal(fooTypeRef, ""), false), - arrayOf(fooTypeRef, LimeValue.Literal(fooTypeRef, ""), false), - arrayOf( - LimeDirectTypeRef(fooType), - LimeValue.Constant( - fooTypeRef, - object : LimeConstantRef() { - override val element = object : LimeNamedElement(EMPTY_PATH) {} - override val typeRef = LimeDirectTypeRef(fooType) - } + fun testData() = + listOf( + arrayOf(LimeBasicTypeRef.INT, LimeValue.Literal(fooTypeRef, ""), true), + arrayOf(LimeBasicTypeRef.FLOAT, LimeValue.Literal(fooTypeRef, ""), true), + arrayOf(LimeBasicTypeRef(LimeBasicType.TypeId.BOOLEAN), LimeValue.Literal(fooTypeRef, ""), true), + arrayOf(LimeBasicTypeRef(LimeBasicType.TypeId.STRING), LimeValue.Literal(fooTypeRef, ""), true), + arrayOf( + LimeBasicTypeRef(LimeBasicType.TypeId.DATE), + LimeValue.Literal(fooTypeRef, "2022-02-04T09:15:17Z"), + true, + ), + arrayOf(LimeBasicTypeRef(LimeBasicType.TypeId.DATE), LimeValue.Literal(fooTypeRef, "bar"), false), + arrayOf(LimeBasicTypeRef(LimeBasicType.TypeId.LOCALE), LimeValue.Literal(fooTypeRef, "en-US"), true), + arrayOf(LimeBasicTypeRef(LimeBasicType.TypeId.LOCALE), LimeValue.Literal(fooTypeRef, "und"), true), + arrayOf(LimeBasicTypeRef(LimeBasicType.TypeId.LOCALE), LimeValue.Literal(fooTypeRef, "42"), false), + arrayOf(LimeBasicTypeRef(LimeBasicType.TypeId.BLOB), LimeValue.Literal(fooTypeRef, ""), false), + arrayOf(fooTypeRef, LimeValue.Literal(fooTypeRef, ""), false), + arrayOf( + LimeDirectTypeRef(fooType), + LimeValue.Constant( + fooTypeRef, + object : LimeConstantRef() { + override val element = object : LimeNamedElement(EMPTY_PATH) {} + override val typeRef = LimeDirectTypeRef(fooType) + }, + ), + true, ), - true - ), - arrayOf( - fooTypeRef, - LimeValue.Constant( + arrayOf( fooTypeRef, - object : LimeConstantRef() { - override val element = object : LimeNamedElement(EMPTY_PATH) {} - override val typeRef = LimeBasicTypeRef.INT - } + LimeValue.Constant( + fooTypeRef, + object : LimeConstantRef() { + override val element = object : LimeNamedElement(EMPTY_PATH) {} + override val typeRef = LimeBasicTypeRef.INT + }, + ), + false, + ), + arrayOf( + LimeDirectTypeRef(object : LimeGenericType() {}), + LimeValue.InitializerList(fooTypeRef, emptyList()), + true, + ), + arrayOf( + LimeBasicTypeRef(LimeBasicType.TypeId.BLOB), + LimeValue.InitializerList(fooTypeRef, emptyList()), + true, + ), + arrayOf(fooTypeRef, LimeValue.InitializerList(fooTypeRef, emptyList()), false), + arrayOf(fooTypeRef, LimeValue.KeyValuePair(LimeValue.ZERO, LimeValue.ZERO), false), + arrayOf( + LimeDirectTypeRef(object : LimeType(EMPTY_PATH) {}, isNullable = true), + LimeValue.Null(fooTypeRef), + true, + ), + arrayOf(fooTypeRef, LimeValue.Null(fooTypeRef), false), + arrayOf(LimeBasicTypeRef.INT, LimeValue.Special(fooTypeRef, LimeValue.Special.ValueId.NAN), true), + arrayOf(fooTypeRef, LimeValue.Special(fooTypeRef, LimeValue.Special.ValueId.NAN), false), + arrayOf( + LimeDirectTypeRef(LimeStruct(EMPTY_PATH)), + LimeValue.StructInitializer(fooTypeRef, emptyList()), + true, ), - false - ), - arrayOf( - LimeDirectTypeRef(object : LimeGenericType() {}), - LimeValue.InitializerList(fooTypeRef, emptyList()), - true - ), - arrayOf( - LimeBasicTypeRef(LimeBasicType.TypeId.BLOB), - LimeValue.InitializerList(fooTypeRef, emptyList()), - true - ), - arrayOf(fooTypeRef, LimeValue.InitializerList(fooTypeRef, emptyList()), false), - arrayOf(fooTypeRef, LimeValue.KeyValuePair(LimeValue.ZERO, LimeValue.ZERO), false), - arrayOf( - LimeDirectTypeRef(object : LimeType(EMPTY_PATH) {}, isNullable = true), - LimeValue.Null(fooTypeRef), - true - ), - arrayOf(fooTypeRef, LimeValue.Null(fooTypeRef), false), - arrayOf(LimeBasicTypeRef.INT, LimeValue.Special(fooTypeRef, LimeValue.Special.ValueId.NAN), true), - arrayOf(fooTypeRef, LimeValue.Special(fooTypeRef, LimeValue.Special.ValueId.NAN), false), - arrayOf( - LimeDirectTypeRef(LimeStruct(EMPTY_PATH)), - LimeValue.StructInitializer(fooTypeRef, emptyList()), - true - ), - arrayOf(fooTypeRef, LimeValue.StructInitializer(fooTypeRef, emptyList()), false), - ) + arrayOf(fooTypeRef, LimeValue.StructInitializer(fooTypeRef, emptyList()), false), + ) } } diff --git a/lime-loader/src/main/java/com/here/gluecodium/loader/AntlrLimeConverter.kt b/lime-loader/src/main/java/com/here/gluecodium/loader/AntlrLimeConverter.kt index 784184544c..4d0b7b64dc 100644 --- a/lime-loader/src/main/java/com/here/gluecodium/loader/AntlrLimeConverter.kt +++ b/lime-loader/src/main/java/com/here/gluecodium/loader/AntlrLimeConverter.kt @@ -38,11 +38,10 @@ import org.antlr.v4.runtime.tree.ParseTreeWalker import java.util.Locale internal object AntlrLimeConverter { - fun convertAnnotations( limePath: LimePath, annotations: List, - parentAttributes: LimeAttributes? = null + parentAttributes: LimeAttributes? = null, ): LimeAttributes { val attributes = LimeAttributes.Builder() annotations.forEach { convertAnnotation(it, attributes, limePath) } @@ -56,7 +55,7 @@ internal object AntlrLimeConverter { private fun propagateParentAttributes( parentAttributes: LimeAttributes, - attributes: LimeAttributes.Builder + attributes: LimeAttributes.Builder, ) { parentAttributes .get(LimeAttributeType.DEPRECATED, LimeAttributeValueType.MESSAGE, LimeComment::class.java) @@ -76,7 +75,11 @@ internal object AntlrLimeConverter { } } - fun parseStructuredComment(commentString: String, lineNumber: Int, limePath: LimePath): LimeStructuredComment { + fun parseStructuredComment( + commentString: String, + lineNumber: Int, + limePath: LimePath, + ): LimeStructuredComment { val lexer = LimedocLexer(CharStreams.fromString(commentString)) val parser = LimedocParser(CommonTokenStream(lexer)) parser.removeErrorListeners() @@ -91,7 +94,7 @@ internal object AntlrLimeConverter { private fun convertAnnotation( annotationContext: LimeParser.AnnotationContext, attributes: LimeAttributes.Builder, - limePath: LimePath + limePath: LimePath, ) { val attributeType = convertAnnotationType(annotationContext) val annotationValues = annotationContext.annotationValue() @@ -115,32 +118,35 @@ internal object AntlrLimeConverter { annotationValues.forEach { val valueType = convertAnnotationValueType(it, attributeType) val rawValue = convertAnnotationValue(it) - val value = when { - attributeType == LimeAttributeType.DEPRECATED -> { - val stringValue = rawValue as? String - ?: throw LimeLoadingException("Unsupported attribute value: '$rawValue'") - parseStructuredComment( - stringValue, - annotationContext.getStart().line, - limePath.child("@deprecated") - ).description + val value = + when { + attributeType == LimeAttributeType.DEPRECATED -> { + val stringValue = + rawValue as? String + ?: throw LimeLoadingException("Unsupported attribute value: '$rawValue'") + parseStructuredComment( + stringValue, + annotationContext.getStart().line, + limePath.child("@deprecated"), + ).description + } + rawValue is String -> makeSafeString(rawValue) + else -> rawValue } - rawValue is String -> makeSafeString(rawValue) - else -> rawValue - } attributes.addAttribute(attributeType, valueType, value) } } private fun addSkipAttribute( attributes: LimeAttributes.Builder, - valueContext: LimeParser.AnnotationValueContext + valueContext: LimeParser.AnnotationValueContext, ) { val valueTypeText = valueContext.simpleId()?.text - val value = when (valueTypeText?.lowercase(Locale.getDefault())) { - null, "tag" -> convertAnnotationValue(valueContext) - else -> valueTypeText - } + val value = + when (valueTypeText?.lowercase(Locale.getDefault())) { + null, "tag" -> convertAnnotationValue(valueContext) + else -> valueTypeText + } val valueList = if (value is List<*>) value else listOf(value) valueList.filterIsInstance().forEach { @@ -153,13 +159,14 @@ internal object AntlrLimeConverter { private fun addEnableIfAttribute( attributes: LimeAttributes.Builder, - valueContext: LimeParser.AnnotationValueContext + valueContext: LimeParser.AnnotationValueContext, ) { val valueTypeText = valueContext.simpleId()?.text - val value = when (valueTypeText?.lowercase(Locale.getDefault())) { - null, "tag" -> convertAnnotationValue(valueContext) - else -> valueTypeText - } + val value = + when (valueTypeText?.lowercase(Locale.getDefault())) { + null, "tag" -> convertAnnotationValue(valueContext) + else -> valueTypeText + } val valueList = if (value is List<*>) value else listOf(value) valueList.filterIsInstance().forEach { @@ -169,7 +176,7 @@ internal object AntlrLimeConverter { private fun addVisibilityAttribute( attributes: LimeAttributes.Builder, - valueContext: LimeParser.AnnotationValueContext + valueContext: LimeParser.AnnotationValueContext, ) { val value = convertAnnotationValue(valueContext) if (value == true) { @@ -206,11 +213,12 @@ internal object AntlrLimeConverter { private fun convertAnnotationValueType( ctx: LimeParser.AnnotationValueContext, - attributeType: LimeAttributeType + attributeType: LimeAttributeType, ): LimeAttributeValueType { - val id = ctx.simpleId()?.text ?: return ( - attributeType.defaultValueType - ?: throw LimeLoadingException("Attribute type $attributeType does not support values") + val id = + ctx.simpleId()?.text ?: return ( + attributeType.defaultValueType + ?: throw LimeLoadingException("Attribute type $attributeType does not support values") ) return when (id) { "Name" -> LimeAttributeValueType.NAME @@ -273,14 +281,21 @@ internal object AntlrLimeConverter { private val durationLiteralRegex = """(\d+)([dhimnsu]+)""".toRegex() - fun convertDurationLiteral(limeTypeRef: LimeTypeRef, isNegative: Boolean, literalText: String): LimeValue.Duration { + fun convertDurationLiteral( + limeTypeRef: LimeTypeRef, + isNegative: Boolean, + literalText: String, + ): LimeValue.Duration { val match = durationLiteralRegex.matchEntire(literalText) - val valueText = match?.groups?.get(1)?.value - ?: throw LimeLoadingException("Invalid `Duration` literal: '$literalText'") - val timeUnitText = match.groups.get(2)?.value - ?: throw LimeLoadingException("Invalid `Duration` literal: '$literalText'") - val timeUnit = LimeValue.Duration.TimeUnit.fromString[timeUnitText] - ?: throw LimeLoadingException("Unsupported time unit: '$timeUnitText'") + val valueText = + match?.groups?.get(1)?.value + ?: throw LimeLoadingException("Invalid `Duration` literal: '$literalText'") + val timeUnitText = + match.groups.get(2)?.value + ?: throw LimeLoadingException("Invalid `Duration` literal: '$literalText'") + val timeUnit = + LimeValue.Duration.TimeUnit.fromString[timeUnitText] + ?: throw LimeLoadingException("Unsupported time unit: '$timeUnitText'") val sign = if (isNegative) "-" else "" return LimeValue.Duration(limeTypeRef, sign + valueText, timeUnit) } diff --git a/lime-loader/src/main/java/com/here/gluecodium/loader/AntlrLimeModelBuilder.kt b/lime-loader/src/main/java/com/here/gluecodium/loader/AntlrLimeModelBuilder.kt index ce0dbee708..0ac8e9cde6 100644 --- a/lime-loader/src/main/java/com/here/gluecodium/loader/AntlrLimeModelBuilder.kt +++ b/lime-loader/src/main/java/com/here/gluecodium/loader/AntlrLimeModelBuilder.kt @@ -59,9 +59,8 @@ import java.util.LinkedList internal class AntlrLimeModelBuilder( private val referenceResolver: LimeReferenceResolver, - contextStack: ModelBuilderContextStack = ModelBuilderContextStack() + contextStack: ModelBuilderContextStack = ModelBuilderContextStack(), ) : AntlrLimeModelBuilderBase(contextStack) { - private val pathStack = LinkedList() private val structuredCommentsStack = LinkedList() @@ -83,7 +82,7 @@ internal class AntlrLimeModelBuilder( override fun exitPackageHeader(ctx: LimeParser.PackageHeaderContext) { pathStack.push( - LimePath(ctx.identifier().simpleId().map { convertSimpleId(it) }, emptyList()) + LimePath(ctx.identifier().simpleId().map { convertSimpleId(it) }, emptyList()), ) } @@ -96,7 +95,7 @@ internal class AntlrLimeModelBuilder( val ambiguousImports = imports.groupBy { it.name }.values.filter { it.size > 1 } if (ambiguousImports.isNotEmpty()) { throw ParseCancellationException( - "Ambiguous imports: " + ambiguousImports.joinToString() + "Ambiguous imports: " + ambiguousImports.joinToString(), ) } } @@ -106,57 +105,59 @@ internal class AntlrLimeModelBuilder( } override fun exitContainer(ctx: LimeParser.ContainerContext) { - val parentTypes = ctx.parentTypes()?.identifier()?.map { - LimeAmbiguousTypeRef( - relativePath = it.simpleId().map { simpleId -> convertSimpleId(simpleId) }, - parentPaths = listOf(currentPath) + currentPath.allParents, - imports = imports, - referenceMap = referenceResolver.referenceMap - ) - } ?: emptyList() + val parentTypes = + ctx.parentTypes()?.identifier()?.map { + LimeAmbiguousTypeRef( + relativePath = it.simpleId().map { simpleId -> convertSimpleId(simpleId) }, + parentPaths = listOf(currentPath) + currentPath.allParents, + imports = imports, + referenceMap = referenceResolver.referenceMap, + ) + } ?: emptyList() val comment = parseStructuredComment(ctx.docComment(), ctx).description val attributes = AntlrLimeConverter.convertAnnotations(currentPath, ctx.annotation()) val externalDescriptor = parseExternalDescriptor(ctx.externalDescriptor()) - val limeElement = if (ctx.Interface() == null) { - LimeClass( - path = currentPath, - comment = comment, - attributes = attributes, - external = externalDescriptor, - parents = parentTypes, - structs = getPreviousResults(LimeStruct::class.java), - enumerations = getPreviousResults(LimeEnumeration::class.java), - constants = getPreviousResults(LimeConstant::class.java), - typeAliases = getPreviousResults(LimeTypeAlias::class.java), - functions = getPreviousResults(LimeFunction::class.java), - properties = getPreviousResults(LimeProperty::class.java), - exceptions = getPreviousResults(LimeException::class.java), - classes = getPreviousResults(LimeClass::class.java), - interfaces = getPreviousResults(LimeInterface::class.java), - lambdas = getPreviousResults(LimeLambda::class.java), - isOpen = ctx.Open() != null - ) - } else { - LimeInterface( - path = currentPath, - comment = comment, - attributes = attributes, - external = externalDescriptor, - parents = parentTypes, - structs = getPreviousResults(LimeStruct::class.java), - enumerations = getPreviousResults(LimeEnumeration::class.java), - constants = getPreviousResults(LimeConstant::class.java), - typeAliases = getPreviousResults(LimeTypeAlias::class.java), - functions = getPreviousResults(LimeFunction::class.java), - properties = getPreviousResults(LimeProperty::class.java), - exceptions = getPreviousResults(LimeException::class.java), - classes = getPreviousResults(LimeClass::class.java), - interfaces = getPreviousResults(LimeInterface::class.java), - lambdas = getPreviousResults(LimeLambda::class.java), - isNarrow = ctx.Narrow() != null - ) - } + val limeElement = + if (ctx.Interface() == null) { + LimeClass( + path = currentPath, + comment = comment, + attributes = attributes, + external = externalDescriptor, + parents = parentTypes, + structs = getPreviousResults(LimeStruct::class.java), + enumerations = getPreviousResults(LimeEnumeration::class.java), + constants = getPreviousResults(LimeConstant::class.java), + typeAliases = getPreviousResults(LimeTypeAlias::class.java), + functions = getPreviousResults(LimeFunction::class.java), + properties = getPreviousResults(LimeProperty::class.java), + exceptions = getPreviousResults(LimeException::class.java), + classes = getPreviousResults(LimeClass::class.java), + interfaces = getPreviousResults(LimeInterface::class.java), + lambdas = getPreviousResults(LimeLambda::class.java), + isOpen = ctx.Open() != null, + ) + } else { + LimeInterface( + path = currentPath, + comment = comment, + attributes = attributes, + external = externalDescriptor, + parents = parentTypes, + structs = getPreviousResults(LimeStruct::class.java), + enumerations = getPreviousResults(LimeEnumeration::class.java), + constants = getPreviousResults(LimeConstant::class.java), + typeAliases = getPreviousResults(LimeTypeAlias::class.java), + functions = getPreviousResults(LimeFunction::class.java), + properties = getPreviousResults(LimeProperty::class.java), + exceptions = getPreviousResults(LimeException::class.java), + classes = getPreviousResults(LimeClass::class.java), + interfaces = getPreviousResults(LimeInterface::class.java), + lambdas = getPreviousResults(LimeLambda::class.java), + isNarrow = ctx.Narrow() != null, + ) + } storeResultAndPopStacks(limeElement) } @@ -167,29 +168,31 @@ internal class AntlrLimeModelBuilder( } override fun exitFunction(ctx: LimeParser.FunctionContext) { - val returnType = ctx.returnType() - ?.let { - LimeReturnType( - typeMapper.mapTypeRef(currentPath, it.typeRef()), - getComment("return", it.docComment(), it) - ) - } ?: LimeReturnType.VOID + val returnType = + ctx.returnType() + ?.let { + LimeReturnType( + typeMapper.mapTypeRef(currentPath, it.typeRef()), + getComment("return", it.docComment(), it), + ) + } ?: LimeReturnType.VOID val exceptionType = ctx.throwsClause()?.let { LimeThrownType( typeMapper.mapTypeRef(currentPath, it.typeRef()), - getComment("throws", it.docComment(), it) + getComment("throws", it.docComment(), it), ) } - val limeElement = LimeFunction( - path = currentPath, - comment = structuredCommentsStack.peek().description, - attributes = AntlrLimeConverter.convertAnnotations(currentPath, ctx.annotation()), - returnType = returnType, - parameters = getPreviousResults(LimeParameter::class.java), - thrownType = exceptionType, - isStatic = ctx.Static() != null - ) + val limeElement = + LimeFunction( + path = currentPath, + comment = structuredCommentsStack.peek().description, + attributes = AntlrLimeConverter.convertAnnotations(currentPath, ctx.annotation()), + returnType = returnType, + parameters = getPreviousResults(LimeParameter::class.java), + thrownType = exceptionType, + isStatic = ctx.Static() != null, + ) storeResultAndPopStacks(limeElement) structuredCommentsStack.pop() @@ -207,46 +210,50 @@ internal class AntlrLimeModelBuilder( ctx.throwsClause()?.let { LimeThrownType( typeMapper.mapTypeRef(currentPath, it.typeRef()), - getComment("throws", it.docComment(), it) + getComment("throws", it.docComment(), it), ) } - val limeElement = LimeFunction( - path = currentPath, - comment = structuredCommentsStack.peek().description, - attributes = AntlrLimeConverter.convertAnnotations(currentPath, ctx.annotation()), - returnType = LimeReturnType(classTypeRef), - parameters = getPreviousResults(LimeParameter::class.java), - thrownType = exceptionType, - isStatic = true, - isConstructor = true - ) + val limeElement = + LimeFunction( + path = currentPath, + comment = structuredCommentsStack.peek().description, + attributes = AntlrLimeConverter.convertAnnotations(currentPath, ctx.annotation()), + returnType = LimeReturnType(classTypeRef), + parameters = getPreviousResults(LimeParameter::class.java), + thrownType = exceptionType, + isStatic = true, + isConstructor = true, + ) storeResultAndPopStacks(limeElement) structuredCommentsStack.pop() } override fun enterFieldConstructor(ctx: LimeParser.FieldConstructorContext) { - val idx = when (val ctxParent = ctx.parent) { - is LimeParser.StructContext -> ctxParent.fieldConstructor().indexOf(ctx) - else -> throw LimeLoadingException("Invalid syntax context: '$ctx'") - } + val idx = + when (val ctxParent = ctx.parent) { + is LimeParser.StructContext -> ctxParent.fieldConstructor().indexOf(ctx) + else -> throw LimeLoadingException("Invalid syntax context: '$ctx'") + } pathStack.push(currentPath.child("", idx.toString())) structuredCommentsStack.push(parseStructuredComment(ctx.docComment(), ctx)) } override fun exitFieldConstructor(ctx: LimeParser.FieldConstructorContext) { val structTypeRef = LimeLazyTypeRef(currentPath.parent.toString(), referenceResolver.referenceMap) - val fieldRefs = ctx.fieldParameter().map { - val attributes = AntlrLimeConverter.convertAnnotations(currentPath, it.annotation()) - LimeLazyFieldRef(structTypeRef, convertSimpleId(it.simpleId()), attributes) - } - val limeElement = LimeFieldConstructor( - path = currentPath, - comment = structuredCommentsStack.peek().description, - attributes = AntlrLimeConverter.convertAnnotations(currentPath, ctx.annotation()), - structRef = structTypeRef, - fieldRefs = fieldRefs, - ) + val fieldRefs = + ctx.fieldParameter().map { + val attributes = AntlrLimeConverter.convertAnnotations(currentPath, it.annotation()) + LimeLazyFieldRef(structTypeRef, convertSimpleId(it.simpleId()), attributes) + } + val limeElement = + LimeFieldConstructor( + path = currentPath, + comment = structuredCommentsStack.peek().description, + attributes = AntlrLimeConverter.convertAnnotations(currentPath, ctx.annotation()), + structRef = structTypeRef, + fieldRefs = fieldRefs, + ) storeResultAndPopStacks(limeElement) structuredCommentsStack.pop() @@ -259,12 +266,13 @@ internal class AntlrLimeModelBuilder( } override fun exitParameter(ctx: LimeParser.ParameterContext) { - val limeElement = LimeParameter( - path = currentPath, - comment = getComment("param", currentPath.name, ctx.docComment(), ctx), - attributes = AntlrLimeConverter.convertAnnotations(currentPath, ctx.annotation()), - typeRef = typeMapper.mapTypeRef(currentPath, ctx.typeRef()) - ) + val limeElement = + LimeParameter( + path = currentPath, + comment = getComment("param", currentPath.name, ctx.docComment(), ctx), + attributes = AntlrLimeConverter.convertAnnotations(currentPath, ctx.annotation()), + typeRef = typeMapper.mapTypeRef(currentPath, ctx.typeRef()), + ) storeResultAndPopStacks(limeElement) } @@ -285,72 +293,79 @@ internal class AntlrLimeModelBuilder( val getterPath = currentPath.child("get") val getterContext = ctx.getter() if (getterContext == null) { - getter = LimeFunction( - path = getterPath, - comment = getComment("get", emptyList(), ctx).withExcluded(propertyComment.isExcluded), - attributes = AntlrLimeConverter.convertAnnotations(currentPath, emptyList(), propertyAttributes), - returnType = LimeReturnType(propertyType, propertyComment), - isStatic = propertyIsStatic - ) - setter = LimeFunction( - path = currentPath.child("set"), - comment = getComment("set", emptyList(), ctx).withExcluded(propertyComment.isExcluded), - attributes = AntlrLimeConverter.convertAnnotations(currentPath, emptyList(), propertyAttributes), - parameters = listOf( - LimeParameter( - getterPath.child("value"), - propertyComment, - typeRef = propertyType - ) - ), - isStatic = propertyIsStatic - ) + getter = + LimeFunction( + path = getterPath, + comment = getComment("get", emptyList(), ctx).withExcluded(propertyComment.isExcluded), + attributes = AntlrLimeConverter.convertAnnotations(currentPath, emptyList(), propertyAttributes), + returnType = LimeReturnType(propertyType, propertyComment), + isStatic = propertyIsStatic, + ) + setter = + LimeFunction( + path = currentPath.child("set"), + comment = getComment("set", emptyList(), ctx).withExcluded(propertyComment.isExcluded), + attributes = AntlrLimeConverter.convertAnnotations(currentPath, emptyList(), propertyAttributes), + parameters = + listOf( + LimeParameter( + getterPath.child("value"), + propertyComment, + typeRef = propertyType, + ), + ), + isStatic = propertyIsStatic, + ) } else { val getterAttributes = AntlrLimeConverter.convertAnnotations(currentPath, getterContext.annotation(), propertyAttributes) val getterExternalDescriptor = parseExternalDescriptor(getterContext.externalDescriptor()) val getterComment = getComment("get", getterContext.docComment(), getterContext) - getter = LimeFunction( - path = getterPath, - comment = getterComment.withExcluded(propertyComment.isExcluded), - attributes = getterAttributes, - external = getterExternalDescriptor, - returnType = LimeReturnType(propertyType, propertyComment), - isStatic = propertyIsStatic - ) - setter = ctx.setter()?.let { - val setterAttributes = - AntlrLimeConverter.convertAnnotations(currentPath, it.annotation(), propertyAttributes) - val setterExternalDescriptor = - parseExternalDescriptor(it.externalDescriptor()) - val setterComment = getComment("set", it.docComment(), it) + getter = LimeFunction( - path = currentPath.child("set"), - comment = setterComment.withExcluded(propertyComment.isExcluded), - attributes = setterAttributes, - external = setterExternalDescriptor, - parameters = listOf( - LimeParameter( - getterPath.child("value"), - propertyComment, - typeRef = propertyType - ) - ), - isStatic = propertyIsStatic + path = getterPath, + comment = getterComment.withExcluded(propertyComment.isExcluded), + attributes = getterAttributes, + external = getterExternalDescriptor, + returnType = LimeReturnType(propertyType, propertyComment), + isStatic = propertyIsStatic, ) - } + setter = + ctx.setter()?.let { + val setterAttributes = + AntlrLimeConverter.convertAnnotations(currentPath, it.annotation(), propertyAttributes) + val setterExternalDescriptor = + parseExternalDescriptor(it.externalDescriptor()) + val setterComment = getComment("set", it.docComment(), it) + LimeFunction( + path = currentPath.child("set"), + comment = setterComment.withExcluded(propertyComment.isExcluded), + attributes = setterAttributes, + external = setterExternalDescriptor, + parameters = + listOf( + LimeParameter( + getterPath.child("value"), + propertyComment, + typeRef = propertyType, + ), + ), + isStatic = propertyIsStatic, + ) + } } - val limeElement = LimeProperty( - path = currentPath, - comment = propertyComment, - attributes = propertyAttributes, - typeRef = propertyType, - getter = getter, - setter = setter, - isStatic = propertyIsStatic - ) + val limeElement = + LimeProperty( + path = currentPath, + comment = propertyComment, + attributes = propertyAttributes, + typeRef = propertyType, + getter = getter, + setter = setter, + isStatic = propertyIsStatic, + ) storeResultAndPopStacks(limeElement) } @@ -363,24 +378,25 @@ internal class AntlrLimeModelBuilder( override fun exitStruct(ctx: LimeParser.StructContext) { val attributes = AntlrLimeConverter.convertAnnotations(currentPath, ctx.annotation()) val externalDescriptor = parseExternalDescriptor(ctx.externalDescriptor()) - val limeElement = LimeStruct( - path = currentPath, - comment = structuredCommentsStack.peek().description, - attributes = attributes, - external = externalDescriptor, - fields = getPreviousResults(LimeField::class.java), - typeAliases = getPreviousResults(LimeTypeAlias::class.java), - functions = getPreviousResults(LimeFunction::class.java), - exceptions = getPreviousResults(LimeException::class.java), - constants = getPreviousResults(LimeConstant::class.java), - constructorComment = structuredCommentsStack.peek().getTagBlock("constructor"), - structs = getPreviousResults(LimeStruct::class.java), - classes = getPreviousResults(LimeClass::class.java), - interfaces = getPreviousResults(LimeInterface::class.java), - enumerations = getPreviousResults(LimeEnumeration::class.java), - lambdas = getPreviousResults(LimeLambda::class.java), - fieldConstructors = getPreviousResults(LimeFieldConstructor::class.java) - ) + val limeElement = + LimeStruct( + path = currentPath, + comment = structuredCommentsStack.peek().description, + attributes = attributes, + external = externalDescriptor, + fields = getPreviousResults(LimeField::class.java), + typeAliases = getPreviousResults(LimeTypeAlias::class.java), + functions = getPreviousResults(LimeFunction::class.java), + exceptions = getPreviousResults(LimeException::class.java), + constants = getPreviousResults(LimeConstant::class.java), + constructorComment = structuredCommentsStack.peek().getTagBlock("constructor"), + structs = getPreviousResults(LimeStruct::class.java), + classes = getPreviousResults(LimeClass::class.java), + interfaces = getPreviousResults(LimeInterface::class.java), + enumerations = getPreviousResults(LimeEnumeration::class.java), + lambdas = getPreviousResults(LimeLambda::class.java), + fieldConstructors = getPreviousResults(LimeFieldConstructor::class.java), + ) storeResultAndPopStacks(limeElement) structuredCommentsStack.pop() @@ -396,20 +412,22 @@ internal class AntlrLimeModelBuilder( val limeTypeRef = typeMapper.mapTypeRef(currentPath, ctx.typeRef()) val defaultValueCtx = ctx.literalConstant() - val defaultValue = when { - defaultValueCtx != null -> convertLiteralConstant(limeTypeRef, defaultValueCtx) - limeTypeRef.isNullable -> LimeValue.Null(limeTypeRef) - else -> null - } + val defaultValue = + when { + defaultValueCtx != null -> convertLiteralConstant(limeTypeRef, defaultValueCtx) + limeTypeRef.isNullable -> LimeValue.Null(limeTypeRef) + else -> null + } - val limeElement = LimeField( - path = currentPath, - comment = parseStructuredComment(ctx.docComment(), ctx).description, - attributes = attributes, - external = externalDescriptor, - typeRef = limeTypeRef, - defaultValue = defaultValue - ) + val limeElement = + LimeField( + path = currentPath, + comment = parseStructuredComment(ctx.docComment(), ctx).description, + attributes = attributes, + external = externalDescriptor, + typeRef = limeTypeRef, + defaultValue = defaultValue, + ) storeResultAndPopStacks(limeElement) } @@ -421,13 +439,14 @@ internal class AntlrLimeModelBuilder( override fun exitEnumeration(ctx: LimeParser.EnumerationContext) { val attributes = AntlrLimeConverter.convertAnnotations(currentPath, ctx.annotation()) val externalDescriptor = parseExternalDescriptor(ctx.externalDescriptor()) - val limeElement = LimeEnumeration( - path = currentPath, - comment = parseStructuredComment(ctx.docComment(), ctx).description, - attributes = attributes, - external = externalDescriptor, - enumerators = getPreviousResults(LimeEnumerator::class.java) - ) + val limeElement = + LimeEnumeration( + path = currentPath, + comment = parseStructuredComment(ctx.docComment(), ctx).description, + attributes = attributes, + external = externalDescriptor, + enumerators = getPreviousResults(LimeEnumerator::class.java), + ) storeResultAndPopStacks(limeElement) } @@ -438,13 +457,14 @@ internal class AntlrLimeModelBuilder( override fun exitEnumerator(ctx: LimeParser.EnumeratorContext) { val siblings = parentContext?.previousResults?.filterIsInstance() ?: emptyList() - val limeElement = LimeEnumerator( - path = currentPath, - comment = parseStructuredComment(ctx.docComment(), ctx).description, - attributes = AntlrLimeConverter.convertAnnotations(currentPath, ctx.annotation()), - explicitValue = ctx.literalConstant()?.let { convertLiteralConstant(LimeBasicTypeRef.INT, it) }, - previous = siblings.lastOrNull() - ) + val limeElement = + LimeEnumerator( + path = currentPath, + comment = parseStructuredComment(ctx.docComment(), ctx).description, + attributes = AntlrLimeConverter.convertAnnotations(currentPath, ctx.annotation()), + explicitValue = ctx.literalConstant()?.let { convertLiteralConstant(LimeBasicTypeRef.INT, it) }, + previous = siblings.lastOrNull(), + ) storeResultAndPopStacks(limeElement) } @@ -455,13 +475,14 @@ internal class AntlrLimeModelBuilder( override fun exitConstant(ctx: LimeParser.ConstantContext) { val limeTypeRef = typeMapper.mapTypeRef(currentPath, ctx.typeRef()) - val limeElement = LimeConstant( - path = currentPath, - comment = parseStructuredComment(ctx.docComment(), ctx).description, - attributes = AntlrLimeConverter.convertAnnotations(currentPath, ctx.annotation()), - typeRef = limeTypeRef, - value = convertLiteralConstant(limeTypeRef, ctx.literalConstant()) - ) + val limeElement = + LimeConstant( + path = currentPath, + comment = parseStructuredComment(ctx.docComment(), ctx).description, + attributes = AntlrLimeConverter.convertAnnotations(currentPath, ctx.annotation()), + typeRef = limeTypeRef, + value = convertLiteralConstant(limeTypeRef, ctx.literalConstant()), + ) storeResultAndPopStacks(limeElement) } @@ -471,12 +492,13 @@ internal class AntlrLimeModelBuilder( } override fun exitTypealias(ctx: LimeParser.TypealiasContext) { - val limeElement = LimeTypeAlias( - path = currentPath, - comment = parseStructuredComment(ctx.docComment(), ctx).description, - attributes = AntlrLimeConverter.convertAnnotations(currentPath, ctx.annotation()), - typeRef = typeMapper.mapTypeRef(currentPath, ctx.typeRef()) - ) + val limeElement = + LimeTypeAlias( + path = currentPath, + comment = parseStructuredComment(ctx.docComment(), ctx).description, + attributes = AntlrLimeConverter.convertAnnotations(currentPath, ctx.annotation()), + typeRef = typeMapper.mapTypeRef(currentPath, ctx.typeRef()), + ) storeResultAndPopStacks(limeElement) } @@ -486,12 +508,13 @@ internal class AntlrLimeModelBuilder( } override fun exitException(ctx: LimeParser.ExceptionContext) { - val limeElement = LimeException( - path = currentPath, - comment = parseStructuredComment(ctx.docComment(), ctx).description, - attributes = AntlrLimeConverter.convertAnnotations(currentPath, ctx.annotation()), - errorType = typeMapper.mapSimpleTypeRef(currentPath, ctx.simpleTypeRef()) - ) + val limeElement = + LimeException( + path = currentPath, + comment = parseStructuredComment(ctx.docComment(), ctx).description, + attributes = AntlrLimeConverter.convertAnnotations(currentPath, ctx.annotation()), + errorType = typeMapper.mapSimpleTypeRef(currentPath, ctx.simpleTypeRef()), + ) storeResultAndPopStacks(limeElement) } @@ -502,36 +525,41 @@ internal class AntlrLimeModelBuilder( } override fun exitLambda(ctx: LimeParser.LambdaContext) { - val parameters = ctx.lambdaParameter().mapIndexed { index, it -> - val simpleId = it.simpleId() - val isNamedParameter = simpleId != null - val path = if (isNamedParameter) { - currentPath.child(convertSimpleId(simpleId)) - } else { - currentPath.child("p$index") - } + val parameters = + ctx.lambdaParameter().mapIndexed { index, it -> + val simpleId = it.simpleId() + val isNamedParameter = simpleId != null + val path = + if (isNamedParameter) { + currentPath.child(convertSimpleId(simpleId)) + } else { + currentPath.child("p$index") + } - LimeLambdaParameter( - typeRef = typeMapper.mapTypeRef(currentPath, it.typeRef()), - path = path, - isNamedParameter = isNamedParameter, - comment = getComment("param", path.name, null, ctx), - attributes = AntlrLimeConverter.convertAnnotations( - currentPath, - it.typeRef().simpleTypeRef().annotation() + LimeLambdaParameter( + typeRef = typeMapper.mapTypeRef(currentPath, it.typeRef()), + path = path, + isNamedParameter = isNamedParameter, + comment = getComment("param", path.name, null, ctx), + attributes = + AntlrLimeConverter.convertAnnotations( + currentPath, + it.typeRef().simpleTypeRef().annotation(), + ), ) + } + val limeElement = + LimeLambda( + path = currentPath, + comment = parseStructuredComment(ctx.docComment(), ctx).description, + attributes = AntlrLimeConverter.convertAnnotations(currentPath, ctx.annotation()), + parameters = parameters, + returnType = + LimeReturnType( + typeMapper.mapTypeRef(currentPath, ctx.typeRef()), + getComment("return", null, ctx), + ), ) - } - val limeElement = LimeLambda( - path = currentPath, - comment = parseStructuredComment(ctx.docComment(), ctx).description, - attributes = AntlrLimeConverter.convertAnnotations(currentPath, ctx.annotation()), - parameters = parameters, - returnType = LimeReturnType( - typeMapper.mapTypeRef(currentPath, ctx.typeRef()), - getComment("return", null, ctx) - ) - ) storeResultAndPopStacks(limeElement) } @@ -553,55 +581,61 @@ internal class AntlrLimeModelBuilder( private fun convertLiteralConstant( limeTypeRef: LimeTypeRef, - ctx: LimeParser.LiteralConstantContext + ctx: LimeParser.LiteralConstantContext, ): LimeValue { when { ctx.elementRef() != null -> { - val enumeratorRef = LimeAmbiguousConstantRef( - relativePath = ctx.elementRef().identifier().simpleId().map { convertSimpleId(it) }, - parentPaths = listOf(currentPath) + currentPath.allParents + imports, - imports = imports, - referenceMap = referenceResolver.referenceMap - ) + val enumeratorRef = + LimeAmbiguousConstantRef( + relativePath = ctx.elementRef().identifier().simpleId().map { convertSimpleId(it) }, + parentPaths = listOf(currentPath) + currentPath.allParents + imports, + imports = imports, + referenceMap = referenceResolver.referenceMap, + ) return LimeValue.Constant(limeTypeRef, enumeratorRef) } ctx.positionalEnumeratorRef() != null -> { - val enumerationRef = LimeAmbiguousTypeRef( - relativePath = ctx.positionalEnumeratorRef().identifier().simpleId().map { convertSimpleId(it) }, - parentPaths = listOf(currentPath) + currentPath.allParents + imports, - imports = imports, - referenceMap = referenceResolver.referenceMap - ) - val enumeratorRef = LimePositionalEnumeratorRef( - typeRef = enumerationRef, - index = ctx.positionalEnumeratorRef().IntegerLiteral().text.toInt() - ) + val enumerationRef = + LimeAmbiguousTypeRef( + relativePath = ctx.positionalEnumeratorRef().identifier().simpleId().map { convertSimpleId(it) }, + parentPaths = listOf(currentPath) + currentPath.allParents + imports, + imports = imports, + referenceMap = referenceResolver.referenceMap, + ) + val enumeratorRef = + LimePositionalEnumeratorRef( + typeRef = enumerationRef, + index = ctx.positionalEnumeratorRef().IntegerLiteral().text.toInt(), + ) return LimeValue.Constant(limeTypeRef, enumeratorRef) } ctx.structInitializer() != null -> { - val values = ctx.structInitializer().literalConstant() - .mapIndexed { idx: Int, childCtx: LimeParser.LiteralConstantContext -> - val fieldTypeRef = LimePositionalTypeRef(limeTypeRef, idx) - convertLiteralConstant(fieldTypeRef, childCtx) - } + val values = + ctx.structInitializer().literalConstant() + .mapIndexed { idx: Int, childCtx: LimeParser.LiteralConstantContext -> + val fieldTypeRef = LimePositionalTypeRef(limeTypeRef, idx) + convertLiteralConstant(fieldTypeRef, childCtx) + } return LimeValue.StructInitializer(limeTypeRef, values) } ctx.listInitializer() != null -> { - val values = ctx.listInitializer().literalConstant().map { - val elementTypeRef = LimePositionalTypeRef(limeTypeRef, 0) - convertLiteralConstant(elementTypeRef, it) - } + val values = + ctx.listInitializer().literalConstant().map { + val elementTypeRef = LimePositionalTypeRef(limeTypeRef, 0) + convertLiteralConstant(elementTypeRef, it) + } return LimeValue.InitializerList(limeTypeRef, values) } ctx.mapInitializer() != null -> { - val values = ctx.mapInitializer().keyValuePair().map { - val keyTypeRef = LimePositionalTypeRef(limeTypeRef, 0) - val valueTypeRef = LimePositionalTypeRef(limeTypeRef, 1) - LimeValue.KeyValuePair( - convertLiteralConstant(keyTypeRef, it.literalConstant().first()), - convertLiteralConstant(valueTypeRef, it.literalConstant().last()) - ) - } + val values = + ctx.mapInitializer().keyValuePair().map { + val keyTypeRef = LimePositionalTypeRef(limeTypeRef, 0) + val valueTypeRef = LimePositionalTypeRef(limeTypeRef, 1) + LimeValue.KeyValuePair( + convertLiteralConstant(keyTypeRef, it.literalConstant().first()), + convertLiteralConstant(valueTypeRef, it.literalConstant().last()), + ) + } return LimeValue.InitializerList(limeTypeRef, values) } ctx.durationLiteral() != null -> { @@ -613,20 +647,21 @@ internal class AntlrLimeModelBuilder( ctx.NanLiteral() != null -> return LimeValue.Special(limeTypeRef, ValueId.NAN) ctx.InfinityLiteral() != null -> return LimeValue.Special( limeTypeRef, - if (ctx.Minus() != null) ValueId.NEGATIVE_INFINITY else ValueId.INFINITY + if (ctx.Minus() != null) ValueId.NEGATIVE_INFINITY else ValueId.INFINITY, ) } - val literalString = when { - ctx.singleLineStringLiteral() != null -> - AntlrLimeConverter.convertSingleLineStringLiteral(ctx.singleLineStringLiteral()) - ctx.multiLineStringLiteral() != null -> - AntlrLimeConverter.convertMultiLineStringLiteral(ctx.multiLineStringLiteral()) - ctx.BooleanLiteral() != null -> ctx.BooleanLiteral().text - ctx.IntegerLiteral() != null -> ctx.IntegerLiteral().text - ctx.DoubleLiteral() != null -> ctx.DoubleLiteral().text - else -> throw LimeLoadingException("Unsupported literal: '$ctx'") - } + val literalString = + when { + ctx.singleLineStringLiteral() != null -> + AntlrLimeConverter.convertSingleLineStringLiteral(ctx.singleLineStringLiteral()) + ctx.multiLineStringLiteral() != null -> + AntlrLimeConverter.convertMultiLineStringLiteral(ctx.multiLineStringLiteral()) + ctx.BooleanLiteral() != null -> ctx.BooleanLiteral().text + ctx.IntegerLiteral() != null -> ctx.IntegerLiteral().text + ctx.DoubleLiteral() != null -> ctx.DoubleLiteral().text + else -> throw LimeLoadingException("Unsupported literal: '$ctx'") + } return LimeValue.Literal(limeTypeRef, if (ctx.Minus() != null) "-$literalString" else literalString) } @@ -641,14 +676,14 @@ internal class AntlrLimeModelBuilder( private fun getComment( commentTag: String, commentContexts: List?, - currentContext: ParserRuleContext + currentContext: ParserRuleContext, ) = getComment(commentTag, "", commentContexts, currentContext) private fun getComment( commentTag: String, elementName: String, commentContexts: List?, - currentContext: ParserRuleContext + currentContext: ParserRuleContext, ): LimeComment { val commentFromParent = structuredCommentsStack.peek().getTagBlock(commentTag, elementName) val ownComment = @@ -665,7 +700,7 @@ internal class AntlrLimeModelBuilder( val position = currentContext.getStart() throw ParseCancellationException( "line ${position.line}:${position.charPositionInLine}, " + - "redundant documentation comment defined" + "redundant documentation comment defined", ) } } @@ -673,17 +708,18 @@ internal class AntlrLimeModelBuilder( private fun parseStructuredComment( commentContexts: List, - ctx: ParserRuleContext + ctx: ParserRuleContext, ): LimeStructuredComment { - val commentString = commentContexts.joinToString(separator = "\n") { - when { - it.DelimitedCommentOpen() != null -> - it.DelimitedCommentText()?.text?.dropLast(2) ?: "" - it.LineCommentOpen() != null -> - it.LineCommentText()?.text?.trimEnd { ch -> ch == '\n' } ?: "" - else -> "" - } - }.trimIndent().split('\n').joinToString("\n") { line -> line.trimEnd() } + val commentString = + commentContexts.joinToString(separator = "\n") { + when { + it.DelimitedCommentOpen() != null -> + it.DelimitedCommentText()?.text?.dropLast(2) ?: "" + it.LineCommentOpen() != null -> + it.LineCommentText()?.text?.trimEnd { ch -> ch == '\n' } ?: "" + else -> "" + } + }.trimIndent().split('\n').joinToString("\n") { line -> line.trimEnd() } return AntlrLimeConverter.parseStructuredComment(commentString, ctx.getStart().line, currentPath) } @@ -696,7 +732,7 @@ internal class AntlrLimeModelBuilder( builder.addValue( convertSimpleId(it.simpleId(0)), convertSimpleId(it.simpleId(1)), - AntlrLimeConverter.convertSingleLineStringLiteral(it.singleLineStringLiteral()) + AntlrLimeConverter.convertSingleLineStringLiteral(it.singleLineStringLiteral()), ) } diff --git a/lime-loader/src/main/java/com/here/gluecodium/loader/AntlrLimeModelBuilderBase.kt b/lime-loader/src/main/java/com/here/gluecodium/loader/AntlrLimeModelBuilderBase.kt index 7af09be691..ebb26ab17e 100644 --- a/lime-loader/src/main/java/com/here/gluecodium/loader/AntlrLimeModelBuilderBase.kt +++ b/lime-loader/src/main/java/com/here/gluecodium/loader/AntlrLimeModelBuilderBase.kt @@ -29,9 +29,8 @@ import org.antlr.v4.runtime.tree.ErrorNode import org.antlr.v4.runtime.tree.TerminalNode internal abstract class AntlrLimeModelBuilderBase( - contextStack: ModelBuilderContextStack + contextStack: ModelBuilderContextStack, ) : ContextBasedModelBuilder(contextStack), LimeParserListener { - // Context handling override fun enterEveryRule(ctx: ParserRuleContext) = openContext() diff --git a/lime-loader/src/main/java/com/here/gluecodium/loader/AntlrLimeReferenceResolver.kt b/lime-loader/src/main/java/com/here/gluecodium/loader/AntlrLimeReferenceResolver.kt index 788042ef65..7918b199bc 100644 --- a/lime-loader/src/main/java/com/here/gluecodium/loader/AntlrLimeReferenceResolver.kt +++ b/lime-loader/src/main/java/com/here/gluecodium/loader/AntlrLimeReferenceResolver.kt @@ -44,10 +44,12 @@ internal class AntlrLimeReferenceResolver : LimeReferenceResolver { } } - override fun registerElement(element: LimeNamedElement) = - registerElement(element.path.toString(), element) + override fun registerElement(element: LimeNamedElement) = registerElement(element.path.toString(), element) - override fun registerElement(key: String, element: LimeElement) { + override fun registerElement( + key: String, + element: LimeElement, + ) { referenceCache[key] = element } diff --git a/lime-loader/src/main/java/com/here/gluecodium/loader/AntlrLimedocBuilder.kt b/lime-loader/src/main/java/com/here/gluecodium/loader/AntlrLimedocBuilder.kt index e1de4d88da..94f77e7b33 100644 --- a/lime-loader/src/main/java/com/here/gluecodium/loader/AntlrLimedocBuilder.kt +++ b/lime-loader/src/main/java/com/here/gluecodium/loader/AntlrLimedocBuilder.kt @@ -25,7 +25,6 @@ import com.here.gluecodium.model.lime.LimeComment import com.here.gluecodium.model.lime.LimePath internal class AntlrLimedocBuilder(private val currentPath: LimePath) : LimedocParserBaseListener() { - private val commentsCollector = mutableMapOf, LimeComment>() private val contentCollector = mutableListOf>() @@ -52,17 +51,19 @@ internal class AntlrLimedocBuilder(private val currentPath: LimePath) : LimedocP } override fun exitDecriptionFirstWord(ctx: LimedocParser.DecriptionFirstWordContext) { - contentCollector += when { - ctx.inlineTag() != null -> convertInlineTag(ctx.inlineTag()) - else -> listOf("" to ctx.text) - } + contentCollector += + when { + ctx.inlineTag() != null -> convertInlineTag(ctx.inlineTag()) + else -> listOf("" to ctx.text) + } } override fun exitDescriptionContent(ctx: LimedocParser.DescriptionContentContext) { - contentCollector += when { - ctx.inlineTag() != null -> convertInlineTag(ctx.inlineTag()) - else -> listOf("" to unescapeText(ctx.text)) - } + contentCollector += + when { + ctx.inlineTag() != null -> convertInlineTag(ctx.inlineTag()) + else -> listOf("" to unescapeText(ctx.text)) + } } override fun exitBlockTag(ctx: LimedocParser.BlockTagContext) { @@ -74,10 +75,11 @@ internal class AntlrLimedocBuilder(private val currentPath: LimePath) : LimedocP } override fun exitBlockTagContent(ctx: LimedocParser.BlockTagContentContext) { - contentCollector += when { - ctx.inlineTag() != null -> convertInlineTag(ctx.inlineTag()) - else -> listOf("" to unescapeText(ctx.text)) - } + contentCollector += + when { + ctx.inlineTag() != null -> convertInlineTag(ctx.inlineTag()) + else -> listOf("" to unescapeText(ctx.text)) + } } // Private functions diff --git a/lime-loader/src/main/java/com/here/gluecodium/loader/AntlrTypeMapper.kt b/lime-loader/src/main/java/com/here/gluecodium/loader/AntlrTypeMapper.kt index 8e2a576bcf..63a982f751 100644 --- a/lime-loader/src/main/java/com/here/gluecodium/loader/AntlrTypeMapper.kt +++ b/lime-loader/src/main/java/com/here/gluecodium/loader/AntlrTypeMapper.kt @@ -35,37 +35,41 @@ import com.here.gluecodium.model.lime.LimeTypeRef internal class AntlrTypeMapper( private val imports: List, private val referenceMap: Map, - private val identifierConverter: (LimeParser.SimpleIdContext) -> String + private val identifierConverter: (LimeParser.SimpleIdContext) -> String, ) { - - fun mapTypeRef(currentPath: LimePath, typeRef: LimeParser.TypeRefContext) = - mapSimpleTypeRef(currentPath, typeRef.simpleTypeRef(), typeRef.Quest() != null) + fun mapTypeRef( + currentPath: LimePath, + typeRef: LimeParser.TypeRefContext, + ) = mapSimpleTypeRef(currentPath, typeRef.simpleTypeRef(), typeRef.Quest() != null) fun mapSimpleTypeRef( currentPath: LimePath, typeRef: LimeParser.SimpleTypeRefContext, - isOptional: Boolean = false + isOptional: Boolean = false, ): LimeTypeRef { val attributes = AntlrLimeConverter.convertAnnotations(currentPath, typeRef.annotation()) return when { - typeRef.predefinedType() != null -> LimeBasicTypeRef( - mapPredefinedType(typeRef.predefinedType()), - isOptional, - attributes - ) - typeRef.genericType() != null -> LimeDirectTypeRef( - mapGenericType(currentPath, typeRef.genericType()), - isOptional, - attributes - ) - else -> LimeAmbiguousTypeRef( - relativePath = typeRef.identifier().simpleId().map { identifierConverter(it) }, - parentPaths = listOf(currentPath) + currentPath.allParents, - imports = imports, - referenceMap = referenceMap, - isNullable = isOptional, - attributes = attributes - ) + typeRef.predefinedType() != null -> + LimeBasicTypeRef( + mapPredefinedType(typeRef.predefinedType()), + isOptional, + attributes, + ) + typeRef.genericType() != null -> + LimeDirectTypeRef( + mapGenericType(currentPath, typeRef.genericType()), + isOptional, + attributes, + ) + else -> + LimeAmbiguousTypeRef( + relativePath = typeRef.identifier().simpleId().map { identifierConverter(it) }, + parentPaths = listOf(currentPath) + currentPath.allParents, + imports = imports, + referenceMap = referenceMap, + isNullable = isOptional, + attributes = attributes, + ) } } @@ -93,7 +97,7 @@ internal class AntlrTypeMapper( private fun mapGenericType( currentPath: LimePath, - genericType: LimeParser.GenericTypeContext + genericType: LimeParser.GenericTypeContext, ): LimeType = when { genericType.listType() != null -> @@ -103,7 +107,7 @@ internal class AntlrTypeMapper( genericType.mapType() != null -> LimeMap( mapTypeRef(currentPath, genericType.mapType().typeRef().first()), - mapTypeRef(currentPath, genericType.mapType().typeRef().last()) + mapTypeRef(currentPath, genericType.mapType().typeRef().last()), ) else -> throw LimeLoadingException("Unrecognized generic type: $genericType") } diff --git a/lime-loader/src/main/java/com/here/gluecodium/loader/LimeBasedLimeModelLoader.kt b/lime-loader/src/main/java/com/here/gluecodium/loader/LimeBasedLimeModelLoader.kt index 78b0a42fa3..d8fe285d64 100644 --- a/lime-loader/src/main/java/com/here/gluecodium/loader/LimeBasedLimeModelLoader.kt +++ b/lime-loader/src/main/java/com/here/gluecodium/loader/LimeBasedLimeModelLoader.kt @@ -38,32 +38,38 @@ import java.util.logging.Logger class LimeBasedLimeModelLoader : LimeModelLoader { private val logger = Logger.getLogger(LimeBasedLimeModelLoader::class.java.name) - override fun loadModel(idlSources: List, auxiliaryIdlSources: List): LimeModel { + override fun loadModel( + idlSources: List, + auxiliaryIdlSources: List, + ): LimeModel { val resolvedIdlSources = idlSources.flatMap { listFilesRecursively(it) }.toSet() val resolvedAuxSources = auxiliaryIdlSources.flatMap { listFilesRecursively(it) }.toSet() val referenceResolver = AntlrLimeReferenceResolver() val elementNameToFileName = mutableMapOf() val fileNameToImports = mutableMapOf>() - val loadedElements = (resolvedIdlSources + resolvedAuxSources) - .map { fileName -> - loadFile(fileName, referenceResolver, fileNameToImports) - ?.onEach { elementNameToFileName[it.fullName] = fileName } - } + val loadedElements = + (resolvedIdlSources + resolvedAuxSources) + .map { fileName -> + loadFile(fileName, referenceResolver, fileNameToImports) + ?.onEach { elementNameToFileName[it.fullName] = fileName } + } if (loadedElements.any { it == null }) { throw LimeLoadingException("Syntax errors found, see log for details.") } val excludedIdlFiles = resolvedAuxSources - resolvedIdlSources - val filteredElements = loadedElements.filterNotNull().flatten() - .groupBy { excludedIdlFiles.contains(elementNameToFileName[it.fullName]) } - val limeModel = LimeModel( - referenceResolver.referenceMap, - filteredElements[false] ?: emptyList(), - filteredElements[true] ?: emptyList(), - elementNameToFileName - ) + val filteredElements = + loadedElements.filterNotNull().flatten() + .groupBy { excludedIdlFiles.contains(elementNameToFileName[it.fullName]) } + val limeModel = + LimeModel( + referenceResolver.referenceMap, + filteredElements[false] ?: emptyList(), + filteredElements[true] ?: emptyList(), + elementNameToFileName, + ) validateModel(limeModel, fileNameToImports) return limeModel @@ -71,7 +77,7 @@ class LimeBasedLimeModelLoader : LimeModelLoader { private fun validateModel( limeModel: LimeModel, - fileNameToImports: Map> + fileNameToImports: Map>, ) { val limeLogger = LimeLogger(logger, limeModel.fileNameMap) val validationResult = @@ -84,7 +90,7 @@ class LimeBasedLimeModelLoader : LimeModelLoader { private fun loadFile( fileName: String, referenceResolver: LimeReferenceResolver, - fileNameToImports: MutableMap> + fileNameToImports: MutableMap>, ): List? { val errorListener = ThrowingErrorListener() diff --git a/lime-loader/src/main/java/com/here/gluecodium/loader/LimeStructuredComment.kt b/lime-loader/src/main/java/com/here/gluecodium/loader/LimeStructuredComment.kt index b8627d73df..fe10db4311 100644 --- a/lime-loader/src/main/java/com/here/gluecodium/loader/LimeStructuredComment.kt +++ b/lime-loader/src/main/java/com/here/gluecodium/loader/LimeStructuredComment.kt @@ -23,8 +23,10 @@ import com.here.gluecodium.model.lime.LimeComment internal class LimeStructuredComment( val description: LimeComment, - private val tagBlocks: Map, LimeComment> + private val tagBlocks: Map, LimeComment>, ) { - fun getTagBlock(tag: String, parameter: String = "") = - tagBlocks[Pair(tag, parameter)] ?: LimeComment() + fun getTagBlock( + tag: String, + parameter: String = "", + ) = tagBlocks[Pair(tag, parameter)] ?: LimeComment() } diff --git a/lime-loader/src/main/java/com/here/gluecodium/loader/ThrowingErrorListener.kt b/lime-loader/src/main/java/com/here/gluecodium/loader/ThrowingErrorListener.kt index 7d04dc72fa..d2382986c1 100644 --- a/lime-loader/src/main/java/com/here/gluecodium/loader/ThrowingErrorListener.kt +++ b/lime-loader/src/main/java/com/here/gluecodium/loader/ThrowingErrorListener.kt @@ -32,7 +32,7 @@ internal class ThrowingErrorListener(private val lineOffset: Int = 0) : BaseErro line: Int, charPositionInLine: Int, msg: String, - e: RecognitionException? + e: RecognitionException?, ) { throw ParseCancellationException("line ${line + lineOffset}:$charPositionInLine, $msg") } diff --git a/lime-loader/src/main/java/com/here/gluecodium/validator/LimeImportsValidator.kt b/lime-loader/src/main/java/com/here/gluecodium/validator/LimeImportsValidator.kt index 7b0da57c69..18dcc04dcc 100644 --- a/lime-loader/src/main/java/com/here/gluecodium/validator/LimeImportsValidator.kt +++ b/lime-loader/src/main/java/com/here/gluecodium/validator/LimeImportsValidator.kt @@ -25,16 +25,17 @@ import com.here.gluecodium.model.lime.LimeModel import com.here.gluecodium.model.lime.LimePath internal class LimeImportsValidator(private val logger: LimeLogger) { - - fun validate(limeModel: LimeModel, fileNameToImports: Map>) = - !fileNameToImports.entries.map { - validateFileImports(it.key, it.value, limeModel.referenceMap) - }.contains(false) + fun validate( + limeModel: LimeModel, + fileNameToImports: Map>, + ) = !fileNameToImports.entries.map { + validateFileImports(it.key, it.value, limeModel.referenceMap) + }.contains(false) private fun validateFileImports( fileName: String, imports: List, - referenceMap: Map + referenceMap: Map, ): Boolean { val unresolvedImports = imports.filterNot { referenceMap.containsKey(it.toString()) } unresolvedImports.forEach { logger.errorWithFileName(fileName, "import '$it' cannot be resolved") } diff --git a/lime-loader/src/test/java/com/here/gluecodium/loader/AntlrLimeModelBuilderTest.kt b/lime-loader/src/test/java/com/here/gluecodium/loader/AntlrLimeModelBuilderTest.kt index e9aba9f1c7..586ad8c256 100644 --- a/lime-loader/src/test/java/com/here/gluecodium/loader/AntlrLimeModelBuilderTest.kt +++ b/lime-loader/src/test/java/com/here/gluecodium/loader/AntlrLimeModelBuilderTest.kt @@ -39,7 +39,9 @@ import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class AntlrLimeModelBuilderTest { @MockK private lateinit var referenceResolver: AntlrLimeReferenceResolver + @MockK private lateinit var packageHeaderContext: LimeParser.PackageHeaderContext + @MockK private lateinit var propertyContext: LimeParser.PropertyContext private val contextStack = MockContextStack() diff --git a/lime-loader/src/test/java/com/here/gluecodium/loader/LimeBasedLimeModelLoaderTest.kt b/lime-loader/src/test/java/com/here/gluecodium/loader/LimeBasedLimeModelLoaderTest.kt index 9b28b348dd..1b9d8b6ea0 100644 --- a/lime-loader/src/test/java/com/here/gluecodium/loader/LimeBasedLimeModelLoaderTest.kt +++ b/lime-loader/src/test/java/com/here/gluecodium/loader/LimeBasedLimeModelLoaderTest.kt @@ -45,7 +45,7 @@ class LimeBasedLimeModelLoaderTest { modelLoader["loadFile"]( any(), any(), - any>>() + any>>(), ) } answers { listOf(object : LimeNamedElement(LimePath(listOf(firstArg()), emptyList())) {}) @@ -71,7 +71,7 @@ class LimeBasedLimeModelLoaderTest { modelLoader["loadFile"]( match { it.endsWith("bar.lime") }, any(), - any>>() + any>>(), ) } } @@ -86,7 +86,7 @@ class LimeBasedLimeModelLoaderTest { modelLoader["loadFile"]( match { it.endsWith("bar.lime") }, any(), - any>>() + any>>(), ) } } @@ -104,7 +104,7 @@ class LimeBasedLimeModelLoaderTest { modelLoader["loadFile"]( match { it.endsWith("bar.lime") }, any(), - any>>() + any>>(), ) } } diff --git a/lime-runtime/src/main/java/com/here/gluecodium/common/CaseInsensitiveMap.kt b/lime-runtime/src/main/java/com/here/gluecodium/common/CaseInsensitiveMap.kt index bda2fbc8b2..0a9c9774b2 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/common/CaseInsensitiveMap.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/common/CaseInsensitiveMap.kt @@ -25,40 +25,63 @@ import java.util.function.Function // Mark `Any` as non-nullable class CaseInsensitiveMap : HashMap() { - override fun compute(key: String, remappingFunction: BiFunction) = - super.compute(key.lowercase(Locale.getDefault()), remappingFunction) + override fun compute( + key: String, + remappingFunction: BiFunction, + ) = super.compute(key.lowercase(Locale.getDefault()), remappingFunction) - override fun computeIfAbsent(key: String, mappingFunction: Function) = - super.computeIfAbsent(key.lowercase(Locale.getDefault()), mappingFunction) + override fun computeIfAbsent( + key: String, + mappingFunction: Function, + ) = super.computeIfAbsent(key.lowercase(Locale.getDefault()), mappingFunction) override fun computeIfPresent( key: String, - remappingFunction: BiFunction + remappingFunction: BiFunction, ) = super.computeIfPresent(key.lowercase(Locale.getDefault()), remappingFunction) override fun containsKey(key: String) = super.containsKey(key.lowercase(Locale.getDefault())) override fun get(key: String) = super.get(key.lowercase(Locale.getDefault())) - override fun getOrDefault(key: String, defaultValue: V) = - super.getOrDefault(key.lowercase(Locale.getDefault()), defaultValue) + override fun getOrDefault( + key: String, + defaultValue: V, + ) = super.getOrDefault(key.lowercase(Locale.getDefault()), defaultValue) - override fun merge(key: String, value: V, remappingFunction: BiFunction) = - super.merge(key.lowercase(Locale.getDefault()), value, remappingFunction) + override fun merge( + key: String, + value: V, + remappingFunction: BiFunction, + ) = super.merge(key.lowercase(Locale.getDefault()), value, remappingFunction) - override fun put(key: String, value: V) = super.put(key.lowercase(Locale.getDefault()), value) + override fun put( + key: String, + value: V, + ) = super.put(key.lowercase(Locale.getDefault()), value) - override fun putAll(from: Map) = - super.putAll(from.mapKeys { it.key.lowercase(Locale.getDefault()) }) + override fun putAll(from: Map) = super.putAll(from.mapKeys { it.key.lowercase(Locale.getDefault()) }) - override fun putIfAbsent(key: String, value: V) = super.putIfAbsent(key.lowercase(Locale.getDefault()), value) + override fun putIfAbsent( + key: String, + value: V, + ) = super.putIfAbsent(key.lowercase(Locale.getDefault()), value) override fun remove(key: String) = super.remove(key.lowercase(Locale.getDefault())) - override fun remove(key: String, value: V) = super.remove(key.lowercase(Locale.getDefault()), value) + override fun remove( + key: String, + value: V, + ) = super.remove(key.lowercase(Locale.getDefault()), value) - override fun replace(key: String, value: V) = super.replace(key.lowercase(Locale.getDefault()), value) + override fun replace( + key: String, + value: V, + ) = super.replace(key.lowercase(Locale.getDefault()), value) - override fun replace(key: String, oldValue: V, newValue: V) = - super.replace(key.lowercase(Locale.getDefault()), oldValue, newValue) + override fun replace( + key: String, + oldValue: V, + newValue: V, + ) = super.replace(key.lowercase(Locale.getDefault()), oldValue, newValue) } diff --git a/lime-runtime/src/main/java/com/here/gluecodium/common/CaseInsensitiveSet.kt b/lime-runtime/src/main/java/com/here/gluecodium/common/CaseInsensitiveSet.kt index 7fbb502743..b4b18bf777 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/common/CaseInsensitiveSet.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/common/CaseInsensitiveSet.kt @@ -23,7 +23,6 @@ import java.util.Locale class CaseInsensitiveSet(elements: Collection = emptySet()) : HashSet(elements.map { it.lowercase(Locale.getDefault()) }) { - override fun add(element: String) = super.add(element.lowercase(Locale.getDefault())) override fun addAll(elements: Collection) = super.addAll(elements.map { it.lowercase(Locale.getDefault()) }) diff --git a/lime-runtime/src/main/java/com/here/gluecodium/common/ContextBasedModelBuilder.kt b/lime-runtime/src/main/java/com/here/gluecodium/common/ContextBasedModelBuilder.kt index b50d0c800b..ecbf7f391c 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/common/ContextBasedModelBuilder.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/common/ContextBasedModelBuilder.kt @@ -47,8 +47,7 @@ abstract class ContextBasedModelBuilder(private val contextStack: ModelBuilde * @param clazz Class object representing the type of the result to get * @return A list of items */ - protected fun getPreviousResults(clazz: Class) = - previousResults.filterIsInstance(clazz) + protected fun getPreviousResults(clazz: Class) = previousResults.filterIsInstance(clazz) protected fun openContext() = contextStack.openContext() @@ -58,6 +57,5 @@ abstract class ContextBasedModelBuilder(private val contextStack: ModelBuilde contextStack.closeContext() } - protected fun storeResult(element: E) = - contextStack.currentContext.currentResults.add(element) + protected fun storeResult(element: E) = contextStack.currentContext.currentResults.add(element) } diff --git a/lime-runtime/src/main/java/com/here/gluecodium/common/LimeLogger.kt b/lime-runtime/src/main/java/com/here/gluecodium/common/LimeLogger.kt index bf99b37742..0d3f7c79f6 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/common/LimeLogger.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/common/LimeLogger.kt @@ -26,28 +26,38 @@ import java.util.logging.Logger class LimeLogger( private val logger: Logger, - private val elementNameToFileName: Map + private val elementNameToFileName: Map, ) { - fun error(limeElement: LimeNamedElement, message: String) = - log(Level.SEVERE, getFileName(limeElement), limeElement.fullName, message) + fun error( + limeElement: LimeNamedElement, + message: String, + ) = log(Level.SEVERE, getFileName(limeElement), limeElement.fullName, message) - fun error(elementName: String, message: String) = - log(Level.SEVERE, getFileName(elementName), elementName, message) + fun error( + elementName: String, + message: String, + ) = log(Level.SEVERE, getFileName(elementName), elementName, message) - fun errorWithFileName(fileName: String, message: String) = - log(Level.SEVERE, fileName, null, message) + fun errorWithFileName( + fileName: String, + message: String, + ) = log(Level.SEVERE, fileName, null, message) - fun warning(limeElement: LimeNamedElement, message: String) = - log(Level.WARNING, getFileName(limeElement), limeElement.fullName, message) + fun warning( + limeElement: LimeNamedElement, + message: String, + ) = log(Level.WARNING, getFileName(limeElement), limeElement.fullName, message) - fun warning(elementName: String, message: String) = - log(Level.WARNING, getFileName(elementName), elementName, message) + fun warning( + elementName: String, + message: String, + ) = log(Level.WARNING, getFileName(elementName), elementName, message) private fun log( logLevel: Level, fileName: String, elementName: String?, - message: String + message: String, ) { val elementInfix = elementName?.let { ", element $it" } ?: "" logger.log(logLevel, "File $fileName$elementInfix: $message") @@ -57,7 +67,7 @@ class LimeLogger( val containerKey = (limeElement.path.head + limeElement.path.container).joinToString(".") return elementNameToFileName[containerKey] ?: throw LimeModelLoaderException( - "Failed to resolve file name for ${limeElement.fullName} element" + "Failed to resolve file name for ${limeElement.fullName} element", ) } diff --git a/lime-runtime/src/main/java/com/here/gluecodium/common/LimeModelFilter.kt b/lime-runtime/src/main/java/com/here/gluecodium/common/LimeModelFilter.kt index 867fc0b845..c954a98f5c 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/common/LimeModelFilter.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/common/LimeModelFilter.kt @@ -41,8 +41,10 @@ import com.here.gluecodium.model.lime.LimeValue * Stateless LIME model filter. See below for the stateful private implementation. */ object LimeModelFilter { - fun filter(limeModel: LimeModel, predicate: (LimeNamedElement) -> Boolean) = - LimeModelFilterImpl(limeModel, predicate).filter() + fun filter( + limeModel: LimeModel, + predicate: (LimeNamedElement) -> Boolean, + ) = LimeModelFilterImpl(limeModel, predicate).filter() } /** @@ -58,7 +60,6 @@ object LimeModelFilter { * remaining overload "Foo.doBar:1" now. */ private class LimeModelFilterImpl(private val limeModel: LimeModel, predicate: (LimeNamedElement) -> Boolean) { - private val referenceMap = limeModel.referenceMap.toMutableMap() private val droppedElements = mutableSetOf() @@ -133,7 +134,7 @@ private class LimeModelFilterImpl(private val limeModel: LimeModel, predicate: ( interfaces = interfaces.filter(predicate).map { filterInterface(it) }, lambdas = lambdas.filter(predicate), parents = parents.map { it.remap(referenceMap) }, - isOpen = isOpen + isOpen = isOpen, ) }.also { remap(it) } @@ -155,7 +156,7 @@ private class LimeModelFilterImpl(private val limeModel: LimeModel, predicate: ( interfaces = interfaces.filter(predicate).map { filterInterface(it) }, lambdas = lambdas.filter(predicate), parents = parents.map { it.remap(referenceMap) }, - isNarrow = isNarrow + isNarrow = isNarrow, ) }.also { remap(it) } @@ -177,29 +178,30 @@ private class LimeModelFilterImpl(private val limeModel: LimeModel, predicate: ( interfaces = interfaces.filter(predicate).map { filterInterface(it) }, enumerations = enumerations.filter(predicate).map { filterEnum(it) }, lambdas = lambdas.filter(predicate), - fieldConstructors = fieldConstructors.filter(predicate).map { filterFieldConstructor(it) } + fieldConstructors = fieldConstructors.filter(predicate).map { filterFieldConstructor(it) }, ) }.also { remap(it) } private fun filterEnum(limeEnum: LimeEnumeration) = limeEnum.run { val filteredEnumerators = enumerators.filter(predicate) - val relinkedEnumerators = filteredEnumerators.mapIndexed { idx, it -> - LimeEnumerator( - path = it.path, - comment = it.comment, - attributes = it.attributes, - explicitValue = it.explicitValue, - previous = filteredEnumerators.getOrNull(idx - 1) - ) - } + val relinkedEnumerators = + filteredEnumerators.mapIndexed { idx, it -> + LimeEnumerator( + path = it.path, + comment = it.comment, + attributes = it.attributes, + explicitValue = it.explicitValue, + previous = filteredEnumerators.getOrNull(idx - 1), + ) + } LimeEnumeration( path = path, comment = comment, attributes = attributes, external = external, - enumerators = relinkedEnumerators + enumerators = relinkedEnumerators, ) }.also { remap(it) } @@ -210,7 +212,7 @@ private class LimeModelFilterImpl(private val limeModel: LimeModel, predicate: ( comment = comment, attributes = attributes, typeRef = typeRef, - value = filterValue(value) + value = filterValue(value), ) }.also { remap(it) } @@ -222,7 +224,7 @@ private class LimeModelFilterImpl(private val limeModel: LimeModel, predicate: ( attributes = attributes, external = external, typeRef = typeRef, - defaultValue = defaultValue?.let { filterValue(it) } + defaultValue = defaultValue?.let { filterValue(it) }, ) }.also { remap(it) } @@ -234,7 +236,7 @@ private class LimeModelFilterImpl(private val limeModel: LimeModel, predicate: ( comment = comment, attributes = attributes, structRef = remappedStructRef, - fieldRefs = fieldRefs.map { LimeLazyFieldRef(remappedStructRef, it.field.name, it.attributes) } + fieldRefs = fieldRefs.map { LimeLazyFieldRef(remappedStructRef, it.field.name, it.attributes) }, ) }.also { remap(it) } @@ -255,7 +257,7 @@ private class LimeModelFilterImpl(private val limeModel: LimeModel, predicate: ( typeRef = typeRef, getter = getter, setter = setter?.takeIf(predicate), - isStatic = isStatic + isStatic = isStatic, ) } } diff --git a/lime-runtime/src/main/java/com/here/gluecodium/common/LimeModelSkipPredicates.kt b/lime-runtime/src/main/java/com/here/gluecodium/common/LimeModelSkipPredicates.kt index 324bfb5c65..c06bbff92f 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/common/LimeModelSkipPredicates.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/common/LimeModelSkipPredicates.kt @@ -35,7 +35,7 @@ object LimeModelSkipPredicates { limeElement: LimeNamedElement, activeTags: Set, platformAttribute: LimeAttributeType? = null, - retainFunctionsAndFields: Boolean = false + retainFunctionsAndFields: Boolean = false, ) = when { isSkippedByTags(limeElement, activeTags) -> false retainFunctionsAndFields && @@ -49,7 +49,7 @@ object LimeModelSkipPredicates { limeElement: LimeNamedElement, activeTags: Set, platformAttribute: LimeAttributeType, - limeReferenceMap: Map + limeReferenceMap: Map, ) = when { !shouldRetainElement(limeElement, activeTags, platformAttribute) -> false !limeElement.path.hasParent -> true @@ -59,7 +59,10 @@ object LimeModelSkipPredicates { } } - private fun isSkippedByTags(limeElement: LimeNamedElement, activeTags: Set): Boolean { + private fun isSkippedByTags( + limeElement: LimeNamedElement, + activeTags: Set, + ): Boolean { val isEnabled = hasTagsMatch(limeElement, LimeAttributeType.ENABLE_IF, TAG, activeTags) if (isEnabled == false) return true @@ -70,7 +73,7 @@ object LimeModelSkipPredicates { private fun isSkippedByTagsOnPlatform( limeElement: LimeNamedElement, activeTags: Set, - platformAttribute: LimeAttributeType + platformAttribute: LimeAttributeType, ): Boolean { val isEnabled = hasTagsMatch(limeElement, platformAttribute, ENABLE_IF, activeTags) if (isEnabled == false) return true @@ -83,7 +86,7 @@ object LimeModelSkipPredicates { limeElement: LimeNamedElement, attributeType: LimeAttributeType, attributeValueType: LimeAttributeValueType, - activeTags: Set + activeTags: Set, ): Boolean? = when (val attributeTags = limeElement.attributes.get(attributeType, attributeValueType, Any::class.java)) { true -> true diff --git a/lime-runtime/src/main/java/com/here/gluecodium/common/LimeTypeRefsVisitor.kt b/lime-runtime/src/main/java/com/here/gluecodium/common/LimeTypeRefsVisitor.kt index ad56d08316..8a4e1379bd 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/common/LimeTypeRefsVisitor.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/common/LimeTypeRefsVisitor.kt @@ -39,8 +39,9 @@ abstract class LimeTypeRefsVisitor { protected fun traverseModel(allElements: Collection): List { val allLambdasAsFunctions = allElements.filterIsInstance().map { it.asFunction() } val allFunctions = allElements.filterIsInstance() + allLambdasAsFunctions - val allTypedElements = allElements.filterIsInstance() + - allLambdasAsFunctions.flatMap { it.parameters } + val allTypedElements = + allElements.filterIsInstance() + + allLambdasAsFunctions.flatMap { it.parameters } val allContainers = allElements.filterIsInstance() return allTypedElements.map { visitTypeRef(it, it.typeRef) } + @@ -54,11 +55,15 @@ abstract class LimeTypeRefsVisitor { protected fun traverseTypes(allTypes: Collection): List { val allFunctions = allTypes.filterIsInstance().flatMap { it.functions } - val allElements = allTypes + allFunctions + allFunctions.flatMap { it.parameters } + - allTypes.filterIsInstance().flatMap { it.properties + it.constants } + - allTypes.filterIsInstance().flatMap { it.fields } + val allElements = + allTypes + allFunctions + allFunctions.flatMap { it.parameters } + + allTypes.filterIsInstance().flatMap { it.properties + it.constants } + + allTypes.filterIsInstance().flatMap { it.fields } return traverseModel(allElements) } - abstract fun visitTypeRef(parentElement: LimeNamedElement, limeTypeRef: LimeTypeRef?): T + abstract fun visitTypeRef( + parentElement: LimeNamedElement, + limeTypeRef: LimeTypeRef?, + ): T } diff --git a/lime-runtime/src/main/java/com/here/gluecodium/common/LimeValuesVisitor.kt b/lime-runtime/src/main/java/com/here/gluecodium/common/LimeValuesVisitor.kt index 77df76be7c..8139eb468b 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/common/LimeValuesVisitor.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/common/LimeValuesVisitor.kt @@ -32,5 +32,8 @@ abstract class LimeValuesVisitor { allElements.filterIsInstance().map { visitValue(it, it.value) } } - abstract fun visitValue(parentElement: LimeNamedElement, limeValue: LimeValue?): T + abstract fun visitValue( + parentElement: LimeNamedElement, + limeValue: LimeValue?, + ): T } diff --git a/lime-runtime/src/main/java/com/here/gluecodium/common/StringHelper.kt b/lime-runtime/src/main/java/com/here/gluecodium/common/StringHelper.kt index c7f0a339f8..d7416fb1f1 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/common/StringHelper.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/common/StringHelper.kt @@ -20,8 +20,9 @@ package com.here.gluecodium.common object StringHelper { - fun escapeString(value: String) = value.replace("\\", "\\\\").replace("\"", "\\\"") - .replace("\n", "\\n").replace("\r", "\\r").replace("\t", "\\t").replace("\b", "\\b") + fun escapeString(value: String) = + value.replace("\\", "\\\\").replace("\"", "\\\"") + .replace("\n", "\\n").replace("\r", "\\r").replace("\t", "\\t").replace("\b", "\\b") fun escapeStringLiteral(literal: String) = "\"${escapeString(literal)}\"" } diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeAmbiguityResolver.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeAmbiguityResolver.kt index b964110e7b..49d39e3ddf 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeAmbiguityResolver.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeAmbiguityResolver.kt @@ -35,10 +35,11 @@ object LimeAmbiguityResolver { relativePath: List, parentPaths: List, imports: List, - referenceMap: Map + referenceMap: Map, ): T { - val importedKeys = imports.filter { it.name == relativePath.first() } - .map { it.child(relativePath.drop(1)).toString() } + val importedKeys = + imports.filter { it.name == relativePath.first() } + .map { it.child(relativePath.drop(1)).toString() } val localKeys = parentPaths.map { it.child(relativePath).toString() } val resolvedTypes = (importedKeys + localKeys).distinct().mapNotNull { referenceMap[it] as? T } diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeAmbiguousConstantRef.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeAmbiguousConstantRef.kt index b86655934d..d4d4356617 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeAmbiguousConstantRef.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeAmbiguousConstantRef.kt @@ -30,9 +30,8 @@ class LimeAmbiguousConstantRef( private val relativePath: List, private val parentPaths: List, private val imports: List, - referenceMap: Map + referenceMap: Map, ) : LimeConstantRef() { - override val element by lazy { LimeAmbiguityResolver.resolve(relativePath, parentPaths, imports, referenceMap) } @@ -44,6 +43,5 @@ class LimeAmbiguousConstantRef( } } - override fun remap(referenceMap: Map) = - LimeAmbiguousConstantRef(relativePath, parentPaths, imports, referenceMap) + override fun remap(referenceMap: Map) = LimeAmbiguousConstantRef(relativePath, parentPaths, imports, referenceMap) } diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeAmbiguousTypeRef.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeAmbiguousTypeRef.kt index 73e93bd5d0..bcf6500ecb 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeAmbiguousTypeRef.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeAmbiguousTypeRef.kt @@ -32,9 +32,8 @@ class LimeAmbiguousTypeRef( private val imports: List, private val referenceMap: Map, override val isNullable: Boolean = false, - attributes: LimeAttributes? = null + attributes: LimeAttributes? = null, ) : LimeTypeRef(attributes) { - override val type by lazy { LimeAmbiguityResolver.resolve(relativePath, parentPaths, imports, referenceMap) } diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeAttributeType.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeAttributeType.kt index 4873e3021b..6b292d66a3 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeAttributeType.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeAttributeType.kt @@ -23,7 +23,7 @@ import com.here.gluecodium.common.CaseInsensitiveMap enum class LimeAttributeType( private val tag: String, - val defaultValueType: LimeAttributeValueType? = null + val defaultValueType: LimeAttributeValueType? = null, ) { CPP("Cpp", LimeAttributeValueType.NAME), JAVA("Java", LimeAttributeValueType.NAME), @@ -40,7 +40,8 @@ enum class LimeAttributeType( OPTIMIZED("Optimized"), OVERLOADED("Overloaded"), SERIALIZABLE("Serializable"), - SKIP("Skip", LimeAttributeValueType.TAG); + SKIP("Skip", LimeAttributeValueType.TAG), + ; override fun toString() = tag diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeAttributeValueType.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeAttributeValueType.kt index 516c70d1e1..96afed97fc 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeAttributeValueType.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeAttributeValueType.kt @@ -41,7 +41,8 @@ enum class LimeAttributeValueType(private val tag: String) { TAG("Tag"), TYPE("Type"), TO_STRING("ToString"), - WEAK("Weak"); + WEAK("Weak"), + ; override fun toString() = tag } diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeAttributes.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeAttributes.kt index 0884d2808a..88eebbdeac 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeAttributes.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeAttributes.kt @@ -25,39 +25,45 @@ import java.lang.UnsupportedOperationException import java.util.Locale class LimeAttributes private constructor( - private val attributes: Map> + private val attributes: Map>, ) : Map { fun have(type: LimeAttributeType) = attributes[type] != null - fun have(attributeType: LimeAttributeType, valueType: LimeAttributeValueType) = - when (val value = attributes[attributeType]?.get(valueType)) { - is Boolean -> value - null -> false - else -> true - } + fun have( + attributeType: LimeAttributeType, + valueType: LimeAttributeValueType, + ) = when (val value = attributes[attributeType]?.get(valueType)) { + is Boolean -> value + null -> false + else -> true + } fun get( attributeType: LimeAttributeType, valueType: LimeAttributeValueType, - clazz: Class + clazz: Class, ): T? { val value = attributes[attributeType]?.get(valueType) return if (clazz.isInstance(value)) clazz.cast(value) else null } - fun get(attributeType: LimeAttributeType, valueType: LimeAttributeValueType) = - get(attributeType, valueType, String::class.java) + fun get( + attributeType: LimeAttributeType, + valueType: LimeAttributeValueType, + ) = get(attributeType, valueType, String::class.java) - override fun toString() = attributes.entries.sortedBy { it.key }.joinToString("\n") { - val attributeType = it.key - if (it.value.isEmpty()) { - return@joinToString "@$attributeType" - } - val valuesString = it.value.entries.joinToString(", ") { nameValue -> - createValueString(attributeType, nameValue.key, nameValue.value) + override fun toString() = + attributes.entries.sortedBy { it.key }.joinToString("\n") { + val attributeType = it.key + if (it.value.isEmpty()) { + return@joinToString "@$attributeType" + } + val valuesString = + it.value.entries.joinToString(", ") { nameValue -> + createValueString(attributeType, nameValue.key, nameValue.value) + } + "@$attributeType($valuesString)" } - "@$attributeType($valuesString)" - } override val entries get() = throw UnsupportedOperationException() @@ -89,7 +95,7 @@ class LimeAttributes private constructor( private fun createValueString( attributeType: LimeAttributeType, valueType: LimeAttributeValueType, - literal: Any + literal: Any, ): String { val prefix = if (valueType != attributeType.defaultValueType || literal is List<*>) valueType.toString() else "" val suffix = createValueLiteral(literal) @@ -120,7 +126,7 @@ class LimeAttributes private constructor( fun addAttribute( attributeType: LimeAttributeType, valueType: LimeAttributeValueType, - newValue: Any? = true + newValue: Any? = true, ): Builder { if (newValue == null) return this attributes.getOrPut(attributeType, { mutableMapOf() }).compute(valueType) { _, oldValue -> @@ -139,7 +145,7 @@ class LimeAttributes private constructor( fun addAttributeIfAbsent( attributeType: LimeAttributeType, valueType: LimeAttributeValueType, - newValue: Any? = true + newValue: Any? = true, ): Builder { if (attributes[attributeType]?.get(valueType) == null) { addAttribute(attributeType, valueType, newValue) diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeBasicType.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeBasicType.kt index 4e3ad1b080..1dc8dfb2a6 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeBasicType.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeBasicType.kt @@ -23,7 +23,7 @@ class LimeBasicType(val typeId: TypeId) : LimeType(path = LimePath.EMPTY_PATH) { enum class TypeId( private val tag: String, val isIntegerType: Boolean = false, - val isNumericType: Boolean = isIntegerType + val isNumericType: Boolean = isIntegerType, ) { VOID("Void"), INT8("Byte", true), @@ -41,7 +41,8 @@ class LimeBasicType(val typeId: TypeId) : LimeType(path = LimePath.EMPTY_PATH) { BLOB("Blob"), DATE("Date"), DURATION("Duration"), - LOCALE("Locale"); + LOCALE("Locale"), + ; override fun toString() = tag } diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeBasicTypeRef.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeBasicTypeRef.kt index 22084ebc56..6e95574bd3 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeBasicTypeRef.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeBasicTypeRef.kt @@ -22,7 +22,7 @@ package com.here.gluecodium.model.lime class LimeBasicTypeRef( typeId: LimeBasicType.TypeId, override val isNullable: Boolean = false, - attributes: LimeAttributes? = null + attributes: LimeAttributes? = null, ) : LimeTypeRef(attributes) { override val elementFullName = typeId.name override val type = LimeBasicType(typeId) diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeClass.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeClass.kt index 540f9de2e7..c8ea91ae0f 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeClass.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeClass.kt @@ -35,25 +35,25 @@ class LimeClass( interfaces: List = emptyList(), lambdas: List = emptyList(), parents: List = emptyList(), - isOpen: Boolean = false + isOpen: Boolean = false, ) : LimeContainerWithInheritance( - path = path, - comment = comment, - attributes = attributes, - external = external, - structs = structs, - enumerations = enumerations, - constants = constants, - typeAliases = typeAliases, - functions = functions, - properties = properties, - exceptions = exceptions, - classes = classes, - interfaces = interfaces, - lambdas = lambdas, - parents = parents, - isOpen = isOpen -) { + path = path, + comment = comment, + attributes = attributes, + external = external, + structs = structs, + enumerations = enumerations, + constants = constants, + typeAliases = typeAliases, + functions = functions, + properties = properties, + exceptions = exceptions, + classes = classes, + interfaces = interfaces, + lambdas = lambdas, + parents = parents, + isOpen = isOpen, + ) { val parentClass get() = parents.map { it.type.actualType }.firstOrNull { it is LimeClass } diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeComment.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeComment.kt index 7fd79976c6..0b78c12265 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeComment.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeComment.kt @@ -28,7 +28,7 @@ package com.here.gluecodium.model.lime class LimeComment( val path: LimePath = LimePath.EMPTY_PATH, private val taggedSections: List> = emptyList(), - val isExcluded: Boolean = false + val isExcluded: Boolean = false, ) { constructor(comment: String, path: LimePath = LimePath.EMPTY_PATH) : this(path, listOf("" to comment)) @@ -42,15 +42,15 @@ class LimeComment( fun withPath(newPath: LimePath) = LimeComment(newPath, taggedSections, isExcluded) - fun withExcluded(newExcluded: Boolean) = - if (newExcluded != isExcluded) LimeComment(path, taggedSections, newExcluded) else this + fun withExcluded(newExcluded: Boolean) = if (newExcluded != isExcluded) LimeComment(path, taggedSections, newExcluded) else this - override fun toString() = taggedSections.joinToString("") { - when (it.first) { - "" -> escapeText(it.second) - else -> "{@${it.first} ${escapeText(it.second)}}" - } - }.trim() + override fun toString() = + taggedSections.joinToString("") { + when (it.first) { + "" -> escapeText(it.second) + else -> "{@${it.first} ${escapeText(it.second)}}" + } + }.trim() private fun escapeText(text: String) = text.replace("""[@{}\\]""".toRegex()) { "\\${it.value}" } } diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeConstant.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeConstant.kt index d0211a28eb..3fc61f08a8 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeConstant.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeConstant.kt @@ -24,5 +24,5 @@ class LimeConstant( comment: LimeComment = LimeComment(), attributes: LimeAttributes? = null, typeRef: LimeTypeRef, - val value: LimeValue + val value: LimeValue, ) : LimeTypedElement(path, comment, attributes, typeRef = typeRef) diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeContainer.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeContainer.kt index 8105dabb6f..7f9c413bc0 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeContainer.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeContainer.kt @@ -36,9 +36,8 @@ abstract class LimeContainer( val exceptions: List = emptyList(), val classes: List = emptyList(), val interfaces: List = emptyList(), - val lambdas: List = emptyList() + val lambdas: List = emptyList(), ) : LimeType(path, comment, attributes, external) { - val constructors get() = functions.filter { it.isConstructor } } diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeContainerWithInheritance.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeContainerWithInheritance.kt index 70a3d0baa9..9f52985b81 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeContainerWithInheritance.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeContainerWithInheritance.kt @@ -35,31 +35,33 @@ abstract class LimeContainerWithInheritance( interfaces: List = emptyList(), lambdas: List = emptyList(), val parents: List = emptyList(), - val isOpen: Boolean = false + val isOpen: Boolean = false, ) : LimeContainer( - path = path, - comment = comment, - attributes = attributes, - external = external, - structs = structs, - enumerations = enumerations, - constants = constants, - typeAliases = typeAliases, - functions = functions, - properties = properties, - exceptions = exceptions, - classes = classes, - interfaces = interfaces, - lambdas = lambdas -) { + path = path, + comment = comment, + attributes = attributes, + external = external, + structs = structs, + enumerations = enumerations, + constants = constants, + typeAliases = typeAliases, + functions = functions, + properties = properties, + exceptions = exceptions, + classes = classes, + interfaces = interfaces, + lambdas = lambdas, + ) { val parentInterfaces get() = parents.map { it.type.actualType }.filterIsInstance() val inheritedFunctions: List - get() = parents.mapNotNull { it.type.actualType as? LimeContainerWithInheritance } - .flatMap { it.functions + it.inheritedFunctions } + get() = + parents.mapNotNull { it.type.actualType as? LimeContainerWithInheritance } + .flatMap { it.functions + it.inheritedFunctions } val inheritedProperties: List - get() = parents.mapNotNull { it.type.actualType as? LimeContainerWithInheritance } - .flatMap { it.properties + it.inheritedProperties } + get() = + parents.mapNotNull { it.type.actualType as? LimeContainerWithInheritance } + .flatMap { it.properties + it.inheritedProperties } } diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeDirectTypeRef.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeDirectTypeRef.kt index 6d7c84bc51..d267731a8e 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeDirectTypeRef.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeDirectTypeRef.kt @@ -25,7 +25,7 @@ package com.here.gluecodium.model.lime class LimeDirectTypeRef( override val type: LimeType, override val isNullable: Boolean = false, - attributes: LimeAttributes? = null + attributes: LimeAttributes? = null, ) : LimeTypeRef(attributes) { override fun asNullable() = if (isNullable) this else LimeDirectTypeRef(type, true) } diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeEnumeration.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeEnumeration.kt index 6d82a91123..9e721781e8 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeEnumeration.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeEnumeration.kt @@ -24,9 +24,8 @@ class LimeEnumeration( comment: LimeComment = LimeComment(), attributes: LimeAttributes? = null, external: LimeExternalDescriptor? = null, - val enumerators: List = emptyList() + val enumerators: List = emptyList(), ) : LimeType(path, comment, attributes, external) { - @Suppress("unused") val aliasEnumerators get() = enumerators.filter { it.isAlias } diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeEnumerator.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeEnumerator.kt index c0f8dc6bea..22bb49eb5c 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeEnumerator.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeEnumerator.kt @@ -24,7 +24,7 @@ class LimeEnumerator( comment: LimeComment = LimeComment(), attributes: LimeAttributes? = null, val explicitValue: LimeValue? = null, - private val previous: LimeEnumerator? = null + private val previous: LimeEnumerator? = null, ) : LimeNamedElement(path = path, comment = comment, attributes = attributes) { val value get() = explicitValue ?: computeValue() diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeException.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeException.kt index 8d61f30bd9..e37dbf33ff 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeException.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeException.kt @@ -23,5 +23,5 @@ class LimeException( path: LimePath, comment: LimeComment = LimeComment(), attributes: LimeAttributes? = null, - val errorType: LimeTypeRef + val errorType: LimeTypeRef, ) : LimeType(path, comment, attributes) diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeExternalDescriptor.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeExternalDescriptor.kt index b8adc18f43..752fa60a3d 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeExternalDescriptor.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeExternalDescriptor.kt @@ -22,7 +22,7 @@ package com.here.gluecodium.model.lime import com.here.gluecodium.common.CaseInsensitiveMap class LimeExternalDescriptor private constructor( - private val descriptors: Map> + private val descriptors: Map>, ) { val cpp get() = descriptors[CPP_TAG] @@ -33,8 +33,7 @@ class LimeExternalDescriptor private constructor( val dart get() = descriptors[DART_TAG] - operator fun plus(other: LimeExternalDescriptor) = - LimeExternalDescriptor(descriptors + other.descriptors) + operator fun plus(other: LimeExternalDescriptor) = LimeExternalDescriptor(descriptors + other.descriptors) override fun toString() = descriptors.entries.flatMap { entry -> @@ -44,7 +43,11 @@ class LimeExternalDescriptor private constructor( class Builder { private val descriptors = CaseInsensitiveMap>() - fun addValue(tag: String, name: String, value: String): Builder { + fun addValue( + tag: String, + name: String, + value: String, + ): Builder { descriptors.getOrPut(tag, { CaseInsensitiveMap() })[name] = value return this } diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeField.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeField.kt index b93b4c300c..2d6851932a 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeField.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeField.kt @@ -25,5 +25,5 @@ class LimeField( attributes: LimeAttributes? = null, external: LimeExternalDescriptor? = null, typeRef: LimeTypeRef, - val defaultValue: LimeValue? = null + val defaultValue: LimeValue? = null, ) : LimeTypedElement(path, comment, attributes, external, typeRef) diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeFieldConstructor.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeFieldConstructor.kt index cb0418c72e..6d51d8e3db 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeFieldConstructor.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeFieldConstructor.kt @@ -24,7 +24,7 @@ class LimeFieldConstructor( comment: LimeComment = LimeComment(), attributes: LimeAttributes? = null, val structRef: LimeTypeRef, - val fieldRefs: List = emptyList() + val fieldRefs: List = emptyList(), ) : LimeNamedElement(path, comment, attributes) { val struct get() = structRef.type as LimeStruct @@ -33,13 +33,14 @@ class LimeFieldConstructor( val omittedFields get() = struct.fields - fields.toSet() - fun asFunction() = LimeFunction( - path = path, - comment = comment, - attributes = attributes, - returnType = LimeReturnType(structRef), - parameters = fields.map { LimeParameter(path.child(it.name), typeRef = it.typeRef) }, - isStatic = true, - isConstructor = true - ) + fun asFunction() = + LimeFunction( + path = path, + comment = comment, + attributes = attributes, + returnType = LimeReturnType(structRef), + parameters = fields.map { LimeParameter(path.child(it.name), typeRef = it.typeRef) }, + isStatic = true, + isConstructor = true, + ) } diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeFunction.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeFunction.kt index 4be5f5ecb2..39e1ab1fa0 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeFunction.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeFunction.kt @@ -28,7 +28,7 @@ class LimeFunction( val parameters: List = emptyList(), val thrownType: LimeThrownType? = null, val isStatic: Boolean = false, - val isConstructor: Boolean = false + val isConstructor: Boolean = false, ) : LimeNamedElement(path, comment, attributes, external) { val exception: LimeException? get() = thrownType?.typeRef?.type?.let { it.actualType as? LimeException } diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeInterface.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeInterface.kt index 696d249e1d..7cf1dc25da 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeInterface.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeInterface.kt @@ -35,22 +35,22 @@ class LimeInterface( interfaces: List = emptyList(), lambdas: List = emptyList(), parents: List = emptyList(), - val isNarrow: Boolean = false + val isNarrow: Boolean = false, ) : LimeContainerWithInheritance( - path = path, - comment = comment, - attributes = attributes, - external = external, - structs = structs, - enumerations = enumerations, - constants = constants, - typeAliases = typeAliases, - functions = functions, - properties = properties, - exceptions = exceptions, - classes = classes, - interfaces = interfaces, - lambdas = lambdas, - parents = parents, - isOpen = true -) + path = path, + comment = comment, + attributes = attributes, + external = external, + structs = structs, + enumerations = enumerations, + constants = constants, + typeAliases = typeAliases, + functions = functions, + properties = properties, + exceptions = exceptions, + classes = classes, + interfaces = interfaces, + lambdas = lambdas, + parents = parents, + isOpen = true, + ) diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeLambda.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeLambda.kt index d8b1cf5239..a138afd2a5 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeLambda.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeLambda.kt @@ -24,16 +24,16 @@ class LimeLambda( comment: LimeComment = LimeComment(), attributes: LimeAttributes? = null, val parameters: List = emptyList(), - val returnType: LimeReturnType = LimeReturnType.VOID + val returnType: LimeReturnType = LimeReturnType.VOID, ) : LimeType(path, comment, attributes) { - - fun asFunction() = LimeFunction( - path = path.child("call"), - comment = comment, - attributes = attributes, - returnType = returnType, - parameters = parameters.map { it.asLimeParameter() } - ) + fun asFunction() = + LimeFunction( + path = path.child("call"), + comment = comment, + attributes = attributes, + returnType = returnType, + parameters = parameters.map { it.asLimeParameter() }, + ) val functions get() = listOf(asFunction()) diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeLambdaParameter.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeLambdaParameter.kt index f9735b1217..e28d14c25f 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeLambdaParameter.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeLambdaParameter.kt @@ -24,11 +24,9 @@ class LimeLambdaParameter( path: LimePath, comment: LimeComment = LimeComment(), attributes: LimeAttributes? = null, - @Suppress("unused") val isNamedParameter: Boolean = false + @Suppress("unused") val isNamedParameter: Boolean = false, ) : LimeTypedElement(path, comment, attributes, typeRef = typeRef) { - - fun asLimeParameter() = - LimeParameter(path = path, comment = comment, attributes = attributes, typeRef = typeRef) + fun asLimeParameter() = LimeParameter(path = path, comment = comment, attributes = attributes, typeRef = typeRef) @Suppress("unused") fun parameterName() = path.name diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeLazyFieldRef.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeLazyFieldRef.kt index ea4815bf47..ddf650af1c 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeLazyFieldRef.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeLazyFieldRef.kt @@ -26,10 +26,10 @@ package com.here.gluecodium.model.lime */ class LimeLazyFieldRef(structTypeRef: LimeTypeRef, fieldName: String, attributes: LimeAttributes? = null) : LimeFieldRef(attributes) { - override val field by lazy { - val limeStruct = structTypeRef.type.actualType as? LimeStruct - ?: throw LimeModelLoaderException("Type ${structTypeRef.elementFullName} is not a struct") + val limeStruct = + structTypeRef.type.actualType as? LimeStruct + ?: throw LimeModelLoaderException("Type ${structTypeRef.elementFullName} is not a struct") limeStruct.fields.find { it.name == fieldName } ?: throw LimeModelLoaderException("Field ${structTypeRef.elementFullName}.$fieldName was not found") } diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeLazyTypeRef.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeLazyTypeRef.kt index b2fc0d6359..46ba41eefb 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeLazyTypeRef.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeLazyTypeRef.kt @@ -28,17 +28,14 @@ package com.here.gluecodium.model.lime class LimeLazyTypeRef( override val elementFullName: String, private val referenceMap: Map, - override val isNullable: Boolean = false + override val isNullable: Boolean = false, ) : LimeTypeRef() { - override val type by lazy { referenceMap[elementFullName] as? LimeType ?: throw LimeModelLoaderException("Type $elementFullName was not found") } - override fun asNullable() = - if (isNullable) this else LimeLazyTypeRef(elementFullName, referenceMap, true) + override fun asNullable() = if (isNullable) this else LimeLazyTypeRef(elementFullName, referenceMap, true) - override fun remap(referenceMap: Map) = - LimeLazyTypeRef(elementFullName, referenceMap, isNullable) + override fun remap(referenceMap: Map) = LimeLazyTypeRef(elementFullName, referenceMap, isNullable) } diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeModel.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeModel.kt index e26ee1c7d3..dc14fb24b9 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeModel.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeModel.kt @@ -23,5 +23,5 @@ class LimeModel( val referenceMap: Map, val topElements: List, val auxiliaryElements: List = emptyList(), - val fileNameMap: Map = emptyMap() + val fileNameMap: Map = emptyMap(), ) diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeModelLoader.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeModelLoader.kt index a17bb416b0..49a83ecc7f 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeModelLoader.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeModelLoader.kt @@ -27,7 +27,10 @@ import java.util.ServiceLoader * rest of the binary to an absolute minimum. */ interface LimeModelLoader { - fun loadModel(idlSources: List, auxiliaryIdlSources: List): LimeModel + fun loadModel( + idlSources: List, + auxiliaryIdlSources: List, + ): LimeModel companion object { fun getLoaders() = ServiceLoader.load(LimeModelLoader::class.java).iterator().asSequence() diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeNamedElement.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeNamedElement.kt index 9fcc8b0459..77fdbf5ad4 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeNamedElement.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeNamedElement.kt @@ -23,9 +23,8 @@ abstract class LimeNamedElement protected constructor( val path: LimePath, val comment: LimeComment = LimeComment(), attributes: LimeAttributes? = null, - val external: LimeExternalDescriptor? = null + val external: LimeExternalDescriptor? = null, ) : LimeElement(attributes) { - open val name get() = path.name diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeParameter.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeParameter.kt index 18ec6d358d..56eaf29056 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeParameter.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeParameter.kt @@ -23,7 +23,7 @@ class LimeParameter( path: LimePath, comment: LimeComment = LimeComment(), attributes: LimeAttributes? = null, - typeRef: LimeTypeRef + typeRef: LimeTypeRef, ) : LimeTypedElement(path, comment, attributes, typeRef = typeRef) { override val fullName: String get() = "${path.parent.withSuffix(path.disambiguator)}.${path.name}" diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimePath.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimePath.kt index c5e48cd1f4..eeb3ffd618 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimePath.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimePath.kt @@ -32,7 +32,7 @@ package com.here.gluecodium.model.lime data class LimePath( val head: List, val tail: List, - val disambiguator: String = "" + val disambiguator: String = "", ) : Comparable { val container get() = tail.first() @@ -52,11 +52,15 @@ data class LimePath( val hasParent get() = tail.size > 1 - fun child(childName: String, disambiguator: String? = null) = - LimePath(head, tail + childName, disambiguator ?: this.disambiguator) + fun child( + childName: String, + disambiguator: String? = null, + ) = LimePath(head, tail + childName, disambiguator ?: this.disambiguator) - fun child(childNames: List, disambiguator: String? = null) = - LimePath(head, tail + childNames, disambiguator ?: this.disambiguator) + fun child( + childNames: List, + disambiguator: String? = null, + ) = LimePath(head, tail + childNames, disambiguator ?: this.disambiguator) fun withSuffix(disambiguator: String) = LimePath(head, tail, disambiguator) diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimePositionalEnumeratorRef.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimePositionalEnumeratorRef.kt index fbef9c8237..c37a067748 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimePositionalEnumeratorRef.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimePositionalEnumeratorRef.kt @@ -27,9 +27,8 @@ package com.here.gluecodium.model.lime */ class LimePositionalEnumeratorRef( override val typeRef: LimeTypeRef, - private val index: Int + private val index: Int, ) : LimeConstantRef() { - override val element by lazy { val limeType = typeRef.type.actualType as? LimeEnumeration val stringIndex = index.toString() @@ -37,6 +36,5 @@ class LimePositionalEnumeratorRef( ?: throw LimeModelLoaderException("Enumerator ${typeRef.elementFullName}($index) was not found") } - override fun remap(referenceMap: Map) = - LimePositionalEnumeratorRef(typeRef.remap(referenceMap), index) + override fun remap(referenceMap: Map) = LimePositionalEnumeratorRef(typeRef.remap(referenceMap), index) } diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimePositionalTypeRef.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimePositionalTypeRef.kt index e96a9c12a1..5466365e32 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimePositionalTypeRef.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimePositionalTypeRef.kt @@ -28,19 +28,17 @@ package com.here.gluecodium.model.lime class LimePositionalTypeRef( private val parentTypeRef: LimeTypeRef, private val index: Int, - override val isNullable: Boolean = false + override val isNullable: Boolean = false, ) : LimeTypeRef() { - override val type by lazy { val limeType = parentTypeRef.type.actualType limeType.childTypes.getOrNull(index)?.type ?: throw LimeModelLoaderException( - "Type ${parentTypeRef.elementFullName}[$index] was not found" + "Type ${parentTypeRef.elementFullName}[$index] was not found", ) } override fun asNullable() = if (isNullable) this else LimePositionalTypeRef(parentTypeRef, index, true) - override fun remap(referenceMap: Map) = - LimePositionalTypeRef(parentTypeRef.remap(referenceMap), index, isNullable) + override fun remap(referenceMap: Map) = LimePositionalTypeRef(parentTypeRef.remap(referenceMap), index, isNullable) } diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeProperty.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeProperty.kt index c15acaca53..8f4fc9758f 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeProperty.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeProperty.kt @@ -26,5 +26,5 @@ class LimeProperty( typeRef: LimeTypeRef, val getter: LimeFunction, val setter: LimeFunction? = null, - val isStatic: Boolean = false + val isStatic: Boolean = false, ) : LimeTypedElement(path, comment, attributes, typeRef = typeRef) diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeReferenceResolver.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeReferenceResolver.kt index d29f1c7119..82fe60d400 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeReferenceResolver.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeReferenceResolver.kt @@ -21,7 +21,13 @@ package com.here.gluecodium.model.lime interface LimeReferenceResolver { val referenceMap: Map + fun computeUniquePath(limePath: LimePath): LimePath + fun registerElement(element: LimeNamedElement) - fun registerElement(key: String, element: LimeElement) + + fun registerElement( + key: String, + element: LimeElement, + ) } diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeReturnType.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeReturnType.kt index 701786bf36..cfdd668323 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeReturnType.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeReturnType.kt @@ -27,11 +27,12 @@ import com.here.gluecodium.model.lime.LimeBasicType.TypeId class LimeReturnType( val typeRef: LimeTypeRef, val comment: LimeComment = LimeComment(), - attributes: LimeAttributes? = null + attributes: LimeAttributes? = null, ) : LimeElement(attributes) { val isVoid - get() = !typeRef.isNullable && - typeRef.type.actualType.let { it is LimeBasicType && it.typeId == TypeId.VOID } + get() = + !typeRef.isNullable && + typeRef.type.actualType.let { it is LimeBasicType && it.typeId == TypeId.VOID } companion object { val VOID = LimeReturnType(LimeBasicTypeRef(TypeId.VOID)) diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeSignatureResolver.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeSignatureResolver.kt index 054feac8a6..5664893470 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeSignatureResolver.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeSignatureResolver.kt @@ -25,20 +25,17 @@ package com.here.gluecodium.model.lime * be overridden if needed (e.g. to account for type-erased generics in Java, etc.). */ open class LimeSignatureResolver(private val referenceMap: Map) { - private val signatureCache = hashMapOf>() - fun getSignature(limeFunction: LimeFunction) = - signatureCache.getOrPut(limeFunction.path.toString()) { computeSignature(limeFunction) } + fun getSignature(limeFunction: LimeFunction) = signatureCache.getOrPut(limeFunction.path.toString()) { computeSignature(limeFunction) } - fun getSignature(limeLambda: LimeLambda) = - limeLambda.asFunction().let { getSignature(it) + getTypeName(it.returnType.typeRef) } + fun getSignature(limeLambda: LimeLambda) = limeLambda.asFunction().let { getSignature(it) + getTypeName(it.returnType.typeRef) } fun isOverloaded(limeFunction: LimeFunction) = getAllOverloads(limeFunction).count() > 1 fun hasSignatureClash( limeFunction: LimeFunction, - functions: List = getAllOverloads(limeFunction) + functions: List = getAllOverloads(limeFunction), ): Boolean { val signature = getSignature(limeFunction) return functions.map { getSignature(it) }.count { it == signature } > 1 @@ -50,8 +47,7 @@ open class LimeSignatureResolver(private val referenceMap: Map { val parentElement = getContainer(limeFunction) ?: return listOf(limeFunction) @@ -73,8 +69,10 @@ open class LimeSignatureResolver(private val referenceMap: Map = emptyList(), val fields: List = emptyList(), val constructorComment: LimeComment = LimeComment(), - val fieldConstructors: List = emptyList() + val fieldConstructors: List = emptyList(), ) : LimeContainer( - path = path, - comment = comment, - attributes = attributes, - external = external, - structs = structs, - enumerations = enumerations, - constants = constants, - typeAliases = typeAliases, - functions = functions, - exceptions = exceptions, - classes = classes, - interfaces = interfaces, - lambdas = lambdas -) { + path = path, + comment = comment, + attributes = attributes, + external = external, + structs = structs, + enumerations = enumerations, + constants = constants, + typeAliases = typeAliases, + functions = functions, + exceptions = exceptions, + classes = classes, + interfaces = interfaces, + lambdas = lambdas, + ) { override val childTypes get() = fields.map { it.typeRef } diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeThrownType.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeThrownType.kt index 70848ec078..aa5ab3942c 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeThrownType.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeThrownType.kt @@ -24,5 +24,5 @@ package com.here.gluecodium.model.lime */ class LimeThrownType( val typeRef: LimeTypeRef, - val comment: LimeComment = LimeComment() + val comment: LimeComment = LimeComment(), ) diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeType.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeType.kt index c9497490ea..92ac70aa98 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeType.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeType.kt @@ -23,7 +23,7 @@ abstract class LimeType protected constructor( path: LimePath, comment: LimeComment = LimeComment(), attributes: LimeAttributes? = null, - external: LimeExternalDescriptor? = null + external: LimeExternalDescriptor? = null, ) : LimeNamedElement(path, comment, attributes, external) { open val childTypes = emptyList() diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeTypeAlias.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeTypeAlias.kt index 6ce53682b2..d9365de88d 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeTypeAlias.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeTypeAlias.kt @@ -31,7 +31,7 @@ class LimeTypeAlias( path: LimePath, comment: LimeComment = LimeComment(), attributes: LimeAttributes? = null, - val typeRef: LimeTypeRef + val typeRef: LimeTypeRef, ) : LimeType(path, comment, attributes) { override val actualType get() = typeRef.type.actualType diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeTypeHelper.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeTypeHelper.kt index 024f9f475f..be890f2a71 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeTypeHelper.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeTypeHelper.kt @@ -25,13 +25,13 @@ import java.time.format.DateTimeFormatter import java.util.Locale object LimeTypeHelper { - fun getAllTypes(limeElement: LimeNamedElement): List { val limeType = limeElement as? LimeType ?: return emptyList() - val nestedContainerTypes = (limeType as? LimeContainer)?.let { - it.structs + it.enumerations + it.exceptions + it.typeAliases + it.classes + it.interfaces + it.lambdas - } ?: emptyList() + val nestedContainerTypes = + (limeType as? LimeContainer)?.let { + it.structs + it.enumerations + it.exceptions + it.typeAliases + it.classes + it.interfaces + it.lambdas + } ?: emptyList() return listOf(limeType) + nestedContainerTypes.flatMap { getAllTypes(it) } } @@ -40,9 +40,10 @@ object LimeTypeHelper { when (limeElement) { is LimeConstant -> listOf(limeElement.value) is LimeField -> listOfNotNull(limeElement.defaultValue) - is LimeContainerWithInheritance -> ( - limeElement.constants + limeElement.structs + - limeElement.classes + limeElement.interfaces + is LimeContainerWithInheritance -> + ( + limeElement.constants + limeElement.structs + + limeElement.classes + limeElement.interfaces ).flatMap { getAllValues(it) } is LimeStruct -> @@ -73,21 +74,26 @@ object LimeTypeHelper { return result } - private fun computeInheritanceDistance(limeContainer: LimeContainerWithInheritance, parentFullName: String): Int? { + private fun computeInheritanceDistance( + limeContainer: LimeContainerWithInheritance, + parentFullName: String, + ): Int? { if (limeContainer.parents.isEmpty()) return null val parentTypes = limeContainer.parents.map { it.type.actualType } if (parentTypes.any { it.fullName == parentFullName }) return 1 - val parentDistances = parentTypes.filterIsInstance() - .mapNotNull { computeInheritanceDistance(it, parentFullName) } + val parentDistances = + parentTypes.filterIsInstance() + .mapNotNull { computeInheritanceDistance(it, parentFullName) } return parentDistances.minOrNull()?.let { it + 1 } } fun dateLiteralEpochSeconds(literalText: String): Long? { - val epochSeconds = try { - Instant.from(DateTimeFormatter.ISO_DATE_TIME.parse(literalText)).epochSecond - } catch (e: DateTimeException) { - return null - } + val epochSeconds = + try { + Instant.from(DateTimeFormatter.ISO_DATE_TIME.parse(literalText)).epochSecond + } catch (e: DateTimeException) { + return null + } return epochSeconds } diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeTypedElement.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeTypedElement.kt index f3af280f52..1de50f6fc8 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeTypedElement.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeTypedElement.kt @@ -24,5 +24,5 @@ abstract class LimeTypedElement protected constructor( comment: LimeComment, attributes: LimeAttributes?, external: LimeExternalDescriptor? = null, - val typeRef: LimeTypeRef + val typeRef: LimeTypeRef, ) : LimeNamedElement(path, comment, attributes, external) diff --git a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeValue.kt b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeValue.kt index 4b04d4be2a..342fdd73d0 100644 --- a/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeValue.kt +++ b/lime-runtime/src/main/java/com/here/gluecodium/model/lime/LimeValue.kt @@ -61,7 +61,8 @@ sealed class LimeValue(open val typeRef: LimeTypeRef) : LimeElement() { enum class ValueId(private val tag: String) { NAN("NaN"), INFINITY("Infinity"), - NEGATIVE_INFINITY("-Infinity"); + NEGATIVE_INFINITY("-Infinity"), + ; override fun toString() = tag } @@ -93,7 +94,8 @@ sealed class LimeValue(open val typeRef: LimeTypeRef) : LimeElement() { SECOND("s"), MILLISECOND("ms"), MICROSECOND("us"), - NANOSECOND("ns"); + NANOSECOND("ns"), + ; override fun toString() = suffix diff --git a/lime-runtime/src/test/java/com/here/gluecodium/common/ContextBasedModelBuilderTest.kt b/lime-runtime/src/test/java/com/here/gluecodium/common/ContextBasedModelBuilderTest.kt index 92cadf1159..8f96f4a9f4 100644 --- a/lime-runtime/src/test/java/com/here/gluecodium/common/ContextBasedModelBuilderTest.kt +++ b/lime-runtime/src/test/java/com/here/gluecodium/common/ContextBasedModelBuilderTest.kt @@ -27,7 +27,6 @@ import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class ContextBasedModelBuilderTest { - private val resultObject = Any() private val contextStack = MockContextStack() @@ -35,7 +34,6 @@ class ContextBasedModelBuilderTest { private class TestableModelBuilder(contextStack: ModelBuilderContextStack) : ContextBasedModelBuilder(contextStack) { - fun doCloseContext() { super.closeContext() } diff --git a/lime-runtime/src/test/java/com/here/gluecodium/common/LimeLoggerTest.kt b/lime-runtime/src/test/java/com/here/gluecodium/common/LimeLoggerTest.kt index d81b5049a6..88ad7773f6 100644 --- a/lime-runtime/src/test/java/com/here/gluecodium/common/LimeLoggerTest.kt +++ b/lime-runtime/src/test/java/com/here/gluecodium/common/LimeLoggerTest.kt @@ -34,7 +34,6 @@ import java.util.logging.Logger @RunWith(JUnit4::class) class LimeLoggerTest { - @MockK private lateinit var javaLogger: Logger private val namesMap = mapOf("mo.del.foo" to "FooFile.lime") diff --git a/lime-runtime/src/test/java/com/here/gluecodium/model/lime/LimeAmbiguityResolverTest.kt b/lime-runtime/src/test/java/com/here/gluecodium/model/lime/LimeAmbiguityResolverTest.kt index 6f8216e7d8..6fa2d6fe5f 100644 --- a/lime-runtime/src/test/java/com/here/gluecodium/model/lime/LimeAmbiguityResolverTest.kt +++ b/lime-runtime/src/test/java/com/here/gluecodium/model/lime/LimeAmbiguityResolverTest.kt @@ -45,7 +45,7 @@ class LimeAmbiguityResolverTest { relativePath, parentPaths, imports, - referenceMap + referenceMap, ) } diff --git a/lime-runtime/src/test/java/com/here/gluecodium/test/AssertHelpers.kt b/lime-runtime/src/test/java/com/here/gluecodium/test/AssertHelpers.kt index 999ce05221..80f895d376 100644 --- a/lime-runtime/src/test/java/com/here/gluecodium/test/AssertHelpers.kt +++ b/lime-runtime/src/test/java/com/here/gluecodium/test/AssertHelpers.kt @@ -22,7 +22,10 @@ package com.here.gluecodium.test import org.junit.Assert.assertTrue object AssertHelpers { - fun assertContains(expected: T, actual: Collection) { + fun assertContains( + expected: T, + actual: Collection, + ) { assertTrue(actual.contains(expected)) } }