diff --git a/.github/workflows/functional-tests.yml b/.github/workflows/functional-tests.yml
index 85a38471e8..1dad97b338 100644
--- a/.github/workflows/functional-tests.yml
+++ b/.github/workflows/functional-tests.yml
@@ -26,7 +26,7 @@ jobs:
- name: Install JDK
uses: actions/setup-java@v1
with:
- java-version: 11
+ java-version: 17
- name: Cache Gradle packages
uses: actions/cache@v2
with:
@@ -63,7 +63,7 @@ jobs:
- name: Install JDK
uses: actions/setup-java@v1
with:
- java-version: 11
+ java-version: 17
- name: Cache Gradle packages
uses: actions/cache@v2
with:
@@ -125,7 +125,7 @@ jobs:
- name: Install JDK
uses: actions/setup-java@v1
with:
- java-version: 11
+ java-version: 17
- name: Cache Gradle packages
uses: actions/cache@v2
with:
@@ -195,7 +195,7 @@ jobs:
- name: Install JDK
uses: actions/setup-java@v1
with:
- java-version: 11
+ java-version: 17
- name: Cache Gradle packages
uses: actions/cache@v2
with:
@@ -236,7 +236,7 @@ jobs:
- name: Install JDK
uses: actions/setup-java@v1
with:
- java-version: 11
+ java-version: 17
- name: Cache Gradle packages
uses: actions/cache@v2
with:
@@ -275,7 +275,7 @@ jobs:
- name: Install JDK
uses: actions/setup-java@v1
with:
- java-version: 11
+ java-version: 17
- name: Cache Gradle packages
uses: actions/cache@v2
with:
@@ -339,7 +339,7 @@ jobs:
- name: Install JDK
uses: actions/setup-java@v1
with:
- java-version: 11
+ java-version: 17
- name: Cache Gradle packages
uses: actions/cache@v2
with:
diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml
index d218d75ad1..1226326e0b 100644
--- a/.github/workflows/unit-tests.yml
+++ b/.github/workflows/unit-tests.yml
@@ -12,7 +12,7 @@ jobs:
- name: Install JDK
uses: actions/setup-java@v1
with:
- java-version: 11
+ java-version: 17
- name: Cache Gradle packages
uses: actions/cache@v2
with:
diff --git a/.idea/kotlinc.xml b/.idea/kotlinc.xml
index c49c8d4104..ed1378c907 100644
--- a/.idea/kotlinc.xml
+++ b/.idea/kotlinc.xml
@@ -5,9 +5,9 @@
-
+
-
+
\ No newline at end of file
diff --git a/build.gradle b/build.gradle
index c6370d9b12..9dfce4e713 100644
--- a/build.gradle
+++ b/build.gradle
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2016-2019 HERE Europe B.V.
+ * Copyright (C) 2016-2024 HERE Europe B.V.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,9 +23,9 @@ buildscript {
mavenCentral()
}
dependencies {
- classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.21"
- classpath "org.jfrog.buildinfo:build-info-extractor-gradle:4.13.0"
- classpath "com.diffplug.spotless:spotless-plugin-gradle:5.10.2"
+ classpath libs.kotlin.gradle.plugin
+ classpath libs.build.info.extractor.gradle
+ classpath libs.spotless.plugin.gradle
modules {
module("org.jetbrains.trove4j:trove4j") {
@@ -35,12 +35,13 @@ buildscript {
}
}
plugins {
- id 'nebula.lint' version '16.9.0'
+ alias libs.plugins.nebula.lint
}
allprojects {
repositories {
mavenCentral()
+ google()
}
configurations.all {
@@ -58,15 +59,22 @@ allprojects {
compileJava {
options.encoding = "UTF-8"
+ sourceCompatibility = JavaVersion.VERSION_11
+ targetCompatibility = JavaVersion.VERSION_11
+ }
+ compileTestJava {
+ options.encoding = "UTF-8"
+ sourceCompatibility = JavaVersion.VERSION_11
+ targetCompatibility = JavaVersion.VERSION_11
}
compileKotlin {
kotlinOptions {
- jvmTarget = "1.8"
+ jvmTarget = JavaVersion.VERSION_11.toString()
}
}
compileTestKotlin {
kotlinOptions {
- jvmTarget = "1.8"
+ jvmTarget = JavaVersion.VERSION_11.toString()
}
}
diff --git a/cmake/modules/gluecodium/gluecodium/details/gradle/wrapper/gradle-wrapper.properties b/cmake/modules/gluecodium/gluecodium/details/gradle/wrapper/gradle-wrapper.properties
index 41dfb87909..15de90249f 100644
--- a/cmake/modules/gluecodium/gluecodium/details/gradle/wrapper/gradle-wrapper.properties
+++ b/cmake/modules/gluecodium/gluecodium/details/gradle/wrapper/gradle-wrapper.properties
@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
diff --git a/functional-tests/build.gradle b/functional-tests/build.gradle
index ff0a2d5fb3..10db38913b 100644
--- a/functional-tests/build.gradle
+++ b/functional-tests/build.gradle
@@ -1,3 +1,22 @@
+/*
+ * Copyright (C) 2016-2024 HERE Europe B.V.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * License-Filename: LICENSE
+ */
+
ext {
ndkVersion = '24.0.8215888'
compileSdkVersion = 31
@@ -67,6 +86,25 @@ public class BuildCMakeNativeHost extends DefaultTask {
ext.BuildCMakeNativeHost = BuildCMakeNativeHost
+static def dependJavaTasksOnNativeBuild(tasks, isHostOnly) {
+ tasks.configureEach { task ->
+ ['Debug', 'Release'].each { buildType ->
+ if (task.name == "javaPreCompile${buildType}" ||
+ task.name == "javaPreCompile${buildType}UnitTest" ||
+ task.name == "compile${buildType}UnitTestJavaWithJavac" ||
+ task.name == "package${buildType}Resources" ||
+ task.name == "generate${buildType}ResValues" ||
+ task.name == "process${buildType}Manifest") {
+ if (isHostOnly) {
+ task.dependsOn "build${buildType}NativeHost"
+ } else {
+ task.dependsOn "externalNativeBuild${buildType}"
+ }
+ }
+ }
+ }
+}
+
buildscript {
repositories {
google()
@@ -74,14 +112,14 @@ buildscript {
mavenCentral()
}
dependencies {
- classpath 'com.android.tools.build:gradle:7.2.1'
- classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.21"
+ classpath libs.android.tools.build.gradle
+ classpath libs.kotlin.gradle.plugin
def gluecodiumVersion = project.hasProperty('gluecodiumVersion')
? project.property('gluecodiumVersion').toString().trim() : '+'
classpath "com.here.gluecodium:gluecodium-gradle:${gluecodiumVersion}"
- classpath 'com.diffplug.spotless:spotless-plugin-gradle:5.10.2'
+ classpath libs.spotless.plugin.gradle
modules {
module("org.jetbrains.trove4j:trove4j") {
diff --git a/functional-tests/functional/build.gradle b/functional-tests/functional/build.gradle
index 1f94ead5c7..e52d028b9d 100644
--- a/functional-tests/functional/build.gradle
+++ b/functional-tests/functional/build.gradle
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2016-2019 HERE Europe B.V.
+ * Copyright (C) 2016-2024 HERE Europe B.V.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -32,6 +32,8 @@ android {
ndkVersion rootProject.ndkVersion
compileSdkVersion rootProject.compileSdkVersion
+ namespace 'com.here.gluecodium.test.functional'
+
defaultConfig {
minSdkVersion rootProject.minSdkVersion
targetSdkVersion rootProject.targetSdkVersion
@@ -87,19 +89,20 @@ android {
def typeName = variant.name
def typeCapitalised = typeName.capitalize()
- def buildNativeProject = task("build${typeCapitalised}NativeHost", type: BuildCMakeNativeHost) {
+ tasks.register("build${typeCapitalised}NativeHost", BuildCMakeNativeHost) {
projectDir = rootProject.projectDir
buildDir = file(buildNativeHostDir('functional', typeName))
cmakeParameters = getCMakeCommonParameters()
target = 'functional'
buildType = variant.buildType.name
+ dependsOn("generate${typeCapitalised}BuildConfig")
}
buildConfigField "String", "NATIVE_LIB_HOST_DIR", "\"${buildNativeHostDir('functional', typeName)}/functional\""
}
}
-task generateJavadoc(type: Javadoc) {
+tasks.register('generateJavadoc', Javadoc) {
source = android.sourceSets.main.java.srcDirs
classpath += files(android.getBootClasspath().join(File.pathSeparator))
exclude '**/jni/**', '**.xml'
@@ -112,34 +115,21 @@ task generateJavadoc(type: Javadoc) {
}
}
-tasks.configureEach { task ->
- // Java compilation depends on .java/.jar files created by CMake
- if (task.name == 'javaPreCompileDebug' || task.name == 'compileDebugUnitTestJavaWithJavac') {
- if (!rootProject.isHostOnly()) {
- task.dependsOn 'externalNativeBuildDebug'
- }
- task.dependsOn 'buildDebugNativeHost'
- }
- if (task.name == 'javaPreCompileRelease' || task.name == 'compileReleaseUnitTestJavaWithJavac') {
- if (!rootProject.isHostOnly()) {
- task.dependsOn 'externalNativeBuildRelease'
- }
- task.dependsOn 'buildReleaseNativeHost'
- }
+dependJavaTasksOnNativeBuild(tasks, rootProject.isHostOnly())
+tasks.configureEach { task ->
if (task.name == 'generateJavadoc') {
task.mustRunAfter 'buildDebugNativeHost', 'buildReleaseNativeHost', 'externalNativeBuildDebug', 'externalNativeBuildRelease'
}
}
dependencies {
- implementation 'androidx.annotation:annotation:1.1.0'
+ implementation libs.androidx.annotation
- testImplementation 'junit:junit:4.13.2'
- testImplementation "org.powermock:powermock-reflect:2.0.9"
- testImplementation 'org.robolectric:robolectric:4.5.1'
- testImplementation 'org.hamcrest:hamcrest:2.2'
- testImplementation 'org.hamcrest:hamcrest-library:2.2'
+ testImplementation libs.junit
+ testImplementation libs.powermock.reflect
+ testImplementation libs.robolectric
+ testImplementation libs.bundles.hamcrest
}
apply plugin: 'com.diffplug.spotless'
diff --git a/functional-tests/gradle.properties b/functional-tests/gradle.properties
index 41cd353695..1f53f813a2 100644
--- a/functional-tests/gradle.properties
+++ b/functional-tests/gradle.properties
@@ -1,3 +1,4 @@
minifyDebugBuilds=false
org.gradle.jvmargs=-Xmx4096m
-android.useAndroidX=true
\ No newline at end of file
+android.useAndroidX=true
+android.defaults.buildfeatures.buildconfig=true
\ No newline at end of file
diff --git a/functional-tests/gradle/wrapper/gradle-wrapper.properties b/functional-tests/gradle/wrapper/gradle-wrapper.properties
index 41dfb87909..15de90249f 100644
--- a/functional-tests/gradle/wrapper/gradle-wrapper.properties
+++ b/functional-tests/gradle/wrapper/gradle-wrapper.properties
@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
diff --git a/functional-tests/namerules/build.gradle b/functional-tests/namerules/build.gradle
index 36e4a8a92e..f8601f1c8b 100644
--- a/functional-tests/namerules/build.gradle
+++ b/functional-tests/namerules/build.gradle
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2016-2019 HERE Europe B.V.
+ * Copyright (C) 2016-2024 HERE Europe B.V.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,8 +21,6 @@ apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
-apply plugin: 'kotlin-android-extensions'
-
project.buildDir = "${rootProject.buildDir}"
def getCMakeCommonParameters() {
@@ -33,6 +31,7 @@ def getCMakeCommonParameters() {
android {
ndkVersion rootProject.ndkVersion
compileSdkVersion rootProject.compileSdkVersion
+ namespace 'com.here.gluecodium.test.namerules'
defaultConfig {
minSdkVersion rootProject.minSdkVersion
@@ -78,49 +77,38 @@ android {
targetCompatibility JavaVersion.VERSION_1_8
}
+ kotlinOptions {
+ jvmTarget = JavaVersion.VERSION_1_8.toString()
+ }
+
libraryVariants.all { variant ->
def typeName = variant.name
def typeCapitalised = typeName.capitalize()
- def buildNativeProject = task("build${typeCapitalised}NativeHost", type: BuildCMakeNativeHost) {
+ tasks.register("build${typeCapitalised}NativeHost", BuildCMakeNativeHost) {
projectDir = project.projectDir
buildDir = file(buildNativeHostDir('namerules', typeName))
cmakeParameters = getCMakeCommonParameters()
target = 'namerules'
buildType = variant.buildType.name
+ dependsOn("generateGluecodiumSources")
}
buildConfigField "String", "NATIVE_LIB_HOST_DIR", "\"${buildNativeHostDir('namerules', typeName)}\""
}
}
-tasks.configureEach { task ->
- // Java compilation depends on .java/.jar files created by CMake
- if (task.name == 'javaPreCompileDebug' || task.name == 'compileDebugUnitTestJavaWithJavac') {
- if (!rootProject.isHostOnly()) {
- task.dependsOn 'externalNativeBuildDebug'
- }
- task.dependsOn 'buildDebugNativeHost'
- }
- if (task.name == 'javaPreCompileRelease' || task.name == 'compileReleaseUnitTestJavaWithJavac') {
- if (!rootProject.isHostOnly()) {
- task.dependsOn 'externalNativeBuildRelease'
- }
- task.dependsOn 'buildReleaseNativeHost'
- }
-}
+dependJavaTasksOnNativeBuild(tasks, rootProject.isHostOnly())
dependencies {
- implementation 'androidx.annotation:annotation:1.1.0'
+ implementation libs.androidx.annotation
- implementation "org.jetbrains.kotlin:kotlin-reflect:1.6.21"
- implementation "org.jetbrains.kotlin:kotlin-stdlib:1.6.21"
+ implementation libs.bundles.kotlin
- testImplementation 'junit:junit:4.13.2'
- testImplementation "org.powermock:powermock-reflect:2.0.9"
- testImplementation 'org.robolectric:robolectric:4.5.1'
- testImplementation 'org.hamcrest:hamcrest:2.2'
- testImplementation 'org.hamcrest:hamcrest-library:2.2'
+ testImplementation libs.junit
+ testImplementation libs.powermock.reflect
+ testImplementation libs.robolectric
+ testImplementation libs.bundles.hamcrest
}
apply plugin: 'gluecodium.gradle'
diff --git a/functional-tests/settings.gradle b/functional-tests/settings.gradle
index 665de09086..b0c21b7085 100644
--- a/functional-tests/settings.gradle
+++ b/functional-tests/settings.gradle
@@ -1,3 +1,11 @@
include ':functional', ':namerules'
project(':functional').projectDir=new File(rootProject.projectDir, 'functional')
-project(':namerules').projectDir=new File(rootProject.projectDir, 'namerules')
\ No newline at end of file
+project(':namerules').projectDir=new File(rootProject.projectDir, 'namerules')
+
+dependencyResolutionManagement {
+ versionCatalogs {
+ libs {
+ from(files("../gradle/libs.versions.toml"))
+ }
+ }
+}
diff --git a/gluecodium-gradle/build.gradle b/gluecodium-gradle/build.gradle
index b73ad0d853..ae1f501bd4 100644
--- a/gluecodium-gradle/build.gradle
+++ b/gluecodium-gradle/build.gradle
@@ -1,3 +1,22 @@
+/*
+ * Copyright (C) 2016-2024 HERE Europe B.V.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * License-Filename: LICENSE
+ */
+
plugins {
id 'java-gradle-plugin'
}
@@ -9,15 +28,14 @@ repositories {
dependencies {
implementation project(":gluecodium")
- implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.6.21'
- implementation('com.android.tools.build:gradle:7.2.1') {
+ implementation libs.kotlin.stdlib
+ implementation (libs.android.tools.build.gradle) {
exclude group: 'net.sf.proguard', module: 'proguard-gradle'
}
- implementation 'com.natpryce:konfig:1.6.10.0'
+ implementation libs.natpryce.konfig
- testImplementation 'io.mockk:mockk-dsl-jvm:1.12.2'
- testImplementation 'io.mockk:mockk:1.12.2'
- testImplementation 'junit:junit:4.13.2'
+ testImplementation libs.bundles.mockk
+ testImplementation libs.junit
}
gradlePlugin {
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/build.gradle b/gluecodium/build.gradle
index 89138f23cb..b8a3427a5a 100644
--- a/gluecodium/build.gradle
+++ b/gluecodium/build.gradle
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2016-2019 HERE Europe B.V.
+ * Copyright (C) 2016-2024 HERE Europe B.V.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,31 +18,27 @@
*/
plugins {
- id "com.lazan.dependency-export" version "0.5"
+ alias libs.plugins.lazan.dependency.export
}
dependencies {
api project(":lime-runtime")
implementation project(":lime-loader")
- compileOnly 'com.android.tools:annotations:25.3.0'
- implementation 'com.google.guava:guava:31.1-jre'
- implementation 'com.natpryce:konfig:1.6.10.0'
- implementation 'com.vladsch.flexmark:flexmark:0.64.0'
- implementation 'com.vladsch.flexmark:flexmark-ext-tables:0.64.0'
- implementation 'com.vladsch.flexmark:flexmark-util:0.64.0'
- implementation 'commons-cli:commons-cli:1.5.0'
- implementation 'org.apache.logging.log4j:log4j-core:2.18.0'
- implementation 'org.jetbrains.kotlin:kotlin-reflect:1.6.21'
- implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.6.21'
- implementation 'org.jetbrains:annotations:23.0.0'
- implementation 'org.slf4j:slf4j-api:1.7.36'
- implementation 'org.slf4j:slf4j-log4j12:1.7.36'
- implementation 'org.trimou:trimou-core:2.5.1.Final'
+ compileOnly libs.android.annotations
+ implementation libs.guava
+ implementation libs.natpryce.konfig
+ implementation libs.bundles.flexmark
+ implementation libs.commons.cli
+ implementation libs.apache.log4j.core
+ implementation libs.bundles.kotlin
+ implementation libs.jetbrains.annotations
+ implementation libs.slf4j.api
+ implementation libs.slf4j.log4j12
+ implementation libs.trimou.core
testImplementation files({ project(":lime-runtime").sourceSets.test.output })
- testImplementation 'io.mockk:mockk-dsl-jvm:1.12.5'
- testImplementation 'io.mockk:mockk:1.12.5'
- testImplementation 'junit:junit:4.13.2'
+ testImplementation libs.bundles.mockk
+ testImplementation libs.junit
}
apply plugin: 'application'
@@ -57,7 +53,7 @@ jar {
apply plugin: 'jacoco'
jacoco {
- toolVersion = '0.8.4'
+ toolVersion = libs.versions.jacoco.get()
}
jacocoTestCoverageVerification {
violationRules {
@@ -72,9 +68,9 @@ jacocoTestCoverageVerification {
}
jacocoTestReport {
reports {
- csv.enabled true
- html.enabled true
- xml.enabled true
+ csv.required = true
+ html.required = true
+ xml.required = true
csv.destination file("${buildDir}/reports/coverage/coverageReport.csv")
html.destination file("${buildDir}/reports/coverage/html")
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 3ea6624d51..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() == standardNullReference) {
- 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,13 +107,19 @@ 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 = standardNullReference
+ open val nullReference = STANDART_NULL_REFERENCE
companion object {
- private const val standardNullReference = "null"
+ private const val STANDART_NULL_REFERENCE = "null"
}
}
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