-
Notifications
You must be signed in to change notification settings - Fork 9
Generate enum classes #10
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
47 commits
Select commit
Hold shift + click to select a range
acb26cd
Implement models for ValueSet and CodeSystem
ellykits c3d4f4f
Update StructureDefinition model to inlcude Binding property
ellykits 3e93a3a
Implement TypeSpec for generating enum classes
ellykits 32e5c7f
Implement logic for generating enum classes
ellykits e5ef44c
Merge branch 'google:main' into implement-enums
ellykits 78eec34
Delete commented code
ellykits 22f9d1f
Fix imports
ellykits 94a0337
Implement EnumerationTypeGenerator
ellykits 4738d83
Wrap enumarated codes type with Enumeration class
ellykits 8df843a
Fix using enums types for r4 and r4b
ellykits 3d52009
Implement Enumeration of and toElement functions
ellykits e803d2e
Resolve issues with generated surrogate classes
ellykits 921df63
Delete unused properties
ellykits 428e133
Implement functionality for retrieving enum constant from code
ellykits 3ac0125
Implement the control getDisplay and getDefinition methods
ellykits 0f4bc97
Fix enum constant formatting
ellykits 641f441
Generate enums only for commonbinding elements
ellykits fd7790e
Revert json formatting
ellykits 0a2d310
Fix failing test
ellykits 9f6e905
Merge branch 'main' into implement-enums
ellykits 9a72b99
Resolve PR feedback
ellykits 7453d2f
Document enum class constant naming convention
ellykits ae1e472
Merge remote-tracking branch 'ellykits/main' into HEAD
ellykits 57f2b73
Generate Enumeration for supported versions
ellykits 2035e39
Refactor enum generation
ellykits 9029290
Update README
ellykits 8f4394c
Split extensions into separate files
ellykits 6f2e8ad
Refactor implementation
ellykits d8302db
Delete unused annotations
ellykits 07a0b91
Delete unused property
ellykits b15baf0
Update README
ellykits 8d191cd
Refactor implementation to use idiomatic functional programming concepts
ellykits 0fc46e1
Update README.md
ellykits fedae8b
Fix setting null for display and definition properties
ellykits 10615b5
Refactor code
ellykits 2a52fa4
Improve kdoc and inline comments documentation
ellykits 28d05d9
Refactor model Concept
ellykits 0f0ec1d
Format table
ellykits 0330b05
Implement String#capitalized function
ellykits eda675e
Refactor enum class code generation
ellykits 459a056
Improve code documentation
ellykits ca6bd8c
Refactor code for generating enum constants
ellykits 263f2ae
Update Include.isValueSystemSupported() function logic
ellykits b573ee1
Fix grammar
ellykits d2b7b29
Improve documentation and code refactor
ellykits be9cd27
Merge branch 'implement-enums' of github.com:ellykits/kotlin-fhir int…
ellykits b2e1558
Refactor code to re-use model and surrogate TypeSpecGenerators
ellykits File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
308 changes: 308 additions & 0 deletions
308
fhir-codegen/gradle-plugin/src/main/kotlin/com/google/fhir/codegen/EnumTypeSpecGenerator.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,308 @@ | ||
/* | ||
* Copyright 2025 Google LLC | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package com.google.fhir.codegen | ||
|
||
import com.google.fhir.codegen.schema.codesystem.CodeSystem | ||
import com.google.fhir.codegen.schema.codesystem.Concept as CodeSystemConcept | ||
import com.google.fhir.codegen.schema.isValueSystemSupported | ||
import com.google.fhir.codegen.schema.normalizeEnumName | ||
import com.google.fhir.codegen.schema.sanitizeKDoc | ||
import com.google.fhir.codegen.schema.valueset.Concept as ValueSystemConcept | ||
import com.google.fhir.codegen.schema.valueset.ValueSet | ||
import com.squareup.kotlinpoet.ClassName | ||
import com.squareup.kotlinpoet.FunSpec | ||
import com.squareup.kotlinpoet.KModifier | ||
import com.squareup.kotlinpoet.PropertySpec | ||
import com.squareup.kotlinpoet.TypeSpec | ||
import com.squareup.kotlinpoet.asClassName | ||
|
||
/** | ||
* Generates a [TypeSpec] for [Enum] class representation of FHIR data. The `Enum` class is | ||
* generated using information derived from the [ValueSet] and [CodeSystem] terminology resources. | ||
* Each generated enum class will contain the methods for retrieving the code, system, display and | ||
* definition of each `Enum` class constant. | ||
*/ | ||
class EnumTypeSpecGenerator(val codeSystemMap: Map<String, CodeSystem>) { | ||
|
||
ellykits marked this conversation as resolved.
Show resolved
Hide resolved
|
||
fun generate(enumClassName: String, valueSet: ValueSet): TypeSpec? { | ||
val fhirEnum = generateEnum(valueSet, codeSystemMap) ?: return null | ||
val typeSpec = | ||
TypeSpec.enumBuilder(enumClassName) | ||
.apply { | ||
fhirEnum.description?.sanitizeKDoc()?.let { addKdoc(it) } | ||
primaryConstructor( | ||
FunSpec.constructorBuilder() | ||
.addParameter("code", String::class) | ||
.addParameter("system", String::class) | ||
.addParameter("display", String::class.asClassName().copy(nullable = true)) | ||
.addParameter("definition", String::class.asClassName().copy(nullable = true)) | ||
.build() | ||
) | ||
|
||
fhirEnum.constants.forEach { | ||
addEnumConstant( | ||
it.name, | ||
TypeSpec.anonymousClassBuilder() | ||
.apply { | ||
if (!it.definition.isNullOrBlank()) addKdoc("%L", it.definition.sanitizeKDoc()) | ||
addSuperclassConstructorParameter("%S", it.code) | ||
addSuperclassConstructorParameter("%S", it.system) | ||
if (it.display != null) { | ||
addSuperclassConstructorParameter("%S", it.display) | ||
} else { | ||
addSuperclassConstructorParameter("null") | ||
} | ||
if (it.definition != null) { | ||
addSuperclassConstructorParameter("%S", it.definition) | ||
} else { | ||
addSuperclassConstructorParameter("null") | ||
} | ||
} | ||
.build(), | ||
) | ||
.addProperty( | ||
PropertySpec.builder("code", String::class, KModifier.PRIVATE) | ||
.initializer("code") | ||
.build() | ||
) | ||
.addProperty( | ||
PropertySpec.builder("system", String::class, KModifier.PRIVATE) | ||
.initializer("system") | ||
.build() | ||
) | ||
.addProperty( | ||
PropertySpec.builder( | ||
"display", | ||
String::class.asClassName().copy(nullable = true), | ||
KModifier.PRIVATE, | ||
) | ||
.initializer("display") | ||
.build() | ||
) | ||
.addProperty( | ||
PropertySpec.builder( | ||
"definition", | ||
String::class.asClassName().copy(nullable = true), | ||
KModifier.PRIVATE, | ||
) | ||
.initializer("definition") | ||
.build() | ||
) | ||
} | ||
addFunction( | ||
FunSpec.builder("toString") | ||
.addModifiers(KModifier.OVERRIDE) | ||
.addStatement("return code") | ||
.returns(String::class) | ||
.build() | ||
) | ||
addFunction( | ||
FunSpec.builder("getCode") | ||
.addModifiers(KModifier.PUBLIC) | ||
.returns(String::class) | ||
.addStatement("return code") | ||
.build() | ||
) | ||
addFunction( | ||
FunSpec.builder("getSystem") | ||
.addModifiers(KModifier.PUBLIC) | ||
.returns(String::class) | ||
ellykits marked this conversation as resolved.
Show resolved
Hide resolved
|
||
.addStatement("return system") | ||
.build() | ||
) | ||
addFunction( | ||
FunSpec.builder("getDisplay") | ||
.addModifiers(KModifier.PUBLIC) | ||
.returns(String::class.asClassName().copy(nullable = true)) | ||
.addStatement("return display") | ||
.build() | ||
) | ||
addFunction( | ||
FunSpec.builder("getDefinition") | ||
.addModifiers(KModifier.PUBLIC) | ||
.returns(String::class.asClassName().copy(nullable = true)) | ||
.addStatement("return definition") | ||
.build() | ||
) | ||
addType( | ||
TypeSpec.companionObjectBuilder() | ||
.addFunction( | ||
FunSpec.builder("fromCode") | ||
.addParameter("code", String::class) | ||
.returns(ClassName.bestGuess(enumClassName)) | ||
.beginControlFlow("return when (code)") | ||
.apply { | ||
fhirEnum.constants.forEach { addStatement("%S -> %L", it.code, it.name) } | ||
addStatement( | ||
"else -> throw IllegalArgumentException(\"Unknown code \$code for enum %L\")", | ||
enumClassName, | ||
) | ||
} | ||
.endControlFlow() | ||
.build() | ||
) | ||
.build() | ||
) | ||
} | ||
.build() | ||
return typeSpec | ||
} | ||
|
||
/** | ||
* Instantiates a [FhirEnum] to facilitate the generation of Kotlin enum classes. The enum | ||
* constants are derived from concepts defined in a `ValueSet`, a `CodeSystem`, or both. When both | ||
* are provided, the constants are generated by intersecting the concepts from the `ValueSet` and | ||
* the `CodeSystem`. If only one is provided, the constants are based solely on that source. Any | ||
* nested concepts are flattened, transformed, and included in the resulting enum constants. | ||
ellykits marked this conversation as resolved.
Show resolved
Hide resolved
|
||
*/ | ||
private fun generateEnum(valueSet: ValueSet, codeSystemMap: Map<String, CodeSystem>): FhirEnum? { | ||
val enumConstants = | ||
valueSet.compose | ||
?.include | ||
?.filter { it.isValueSystemSupported() } | ||
?.flatMap { include -> | ||
val system = include.system!! | ||
generateEnumConstants( | ||
system = system, | ||
codeSystemConcepts = codeSystemMap[system]?.concept, | ||
valueSetConcepts = include.concept, | ||
) | ||
} ?: emptyList() | ||
return if (enumConstants.isNotEmpty()) { | ||
FhirEnum(valueSet.description, enumConstants) | ||
} else { | ||
null | ||
} | ||
} | ||
|
||
private fun generateEnumConstants( | ||
system: String, | ||
codeSystemConcepts: List<CodeSystemConcept>?, | ||
valueSetConcepts: List<ValueSystemConcept>?, | ||
): List<FhirEnumConstant> { | ||
val valueSetConceptCodeSet = valueSetConcepts?.mapTo(hashSetOf()) { it.code } ?: emptySet() | ||
val flattenedCodeSystemConcepts = flattenCodeSystemConcepts(codeSystemConcepts) | ||
// Select concepts for enum generation. Prefer flattened CodeSystem concepts filtered | ||
// by codes present in the ValueSet. If no CodeSystem concepts exist, fall back to | ||
// ValueSet concepts, which include only code and system—the key properties for enums. | ||
// To address missing concepts in R4B and R5, we may need to add v3 CodeSystems like | ||
// CodeSystem-v3-AdministrativeGender, which are present in R4 but absent in later versions. | ||
return if (valueSetConceptCodeSet.isNotEmpty()) { | ||
if (flattenedCodeSystemConcepts.isNotEmpty()) { | ||
flattenedCodeSystemConcepts | ||
.filter { valueSetConceptCodeSet.contains(it.code) } | ||
.map { concept -> | ||
FhirEnumConstant( | ||
code = concept.code, | ||
system = system, | ||
name = concept.code.formatEnumConstantName(), | ||
display = concept.display, | ||
definition = concept.definition, | ||
) | ||
} | ||
} else { | ||
valueSetConcepts!!.map { concept -> | ||
FhirEnumConstant( | ||
code = concept.code, | ||
system = system, | ||
name = concept.code.formatEnumConstantName(), | ||
display = concept.display, | ||
definition = concept.definition, | ||
) | ||
} | ||
} | ||
} else | ||
flattenedCodeSystemConcepts.map { concept -> | ||
FhirEnumConstant( | ||
code = concept.code, | ||
system = system, | ||
name = concept.code.formatEnumConstantName(), | ||
display = concept.display, | ||
definition = concept.definition, | ||
) | ||
} | ||
} | ||
|
||
/** | ||
* Flattens a list of Concept objects, including all nested concepts, into a single, flat list. | ||
*/ | ||
private fun flattenCodeSystemConcepts( | ||
concepts: List<CodeSystemConcept>? | ||
): List<CodeSystemConcept> = | ||
concepts?.flatMap { currentConcept -> | ||
buildList { | ||
add(currentConcept) | ||
currentConcept.concept?.let { nestedConcepts -> | ||
addAll(flattenCodeSystemConcepts(nestedConcepts)) | ||
} | ||
} | ||
} ?: emptyList() | ||
|
||
/** | ||
* Transforms a FHIR code into a valid Kotlin enum constant name. | ||
* | ||
* This function applies a series of transformations to ensure the resulting name follows Kotlin | ||
* naming conventions and is a valid identifier. The transformations are applied in the following | ||
* order: | ||
* 1. For URLs (strings starting with "http"), extract only the last segment after the final dot | ||
* Example: "http://hl7.org/fhirpath/System.DateTime" → "DateTime" | ||
* 2. For special characters (>, <, >=, etc.), map them to descriptive names Example: ">" → | ||
* "GreaterThan", "<" → "LessThan" | ||
* | ||
* 3.1. Replace all remaining non-alphanumeric characters with underscores Example: | ||
* "some-value.123" → "some_value_123" | ||
* | ||
* 3.2. If the string starts with a digit, prefix it with an underscore to make it a valid | ||
* identifier Example: "123test" → "_123test" | ||
* | ||
* 3.3. Apply PascalCase to each segment between underscores while preserving the underscores | ||
* Example: "test_value" → "Test_Value" | ||
* | ||
* @return A valid Kotlin enum constant name | ||
*/ | ||
private fun String.formatEnumConstantName(): String { | ||
|
||
if (startsWith("http")) return substringAfterLast(".") | ||
|
||
when (this) { | ||
">" -> return "GreaterThan" | ||
"<" -> return "LessThan" | ||
">=" -> return "GreaterThanOrEqualTo" | ||
"<=" -> return "LessThanOrEqualTo" | ||
"<>", | ||
"!=" -> return "NotEqualTo" | ||
"=" -> return "EqualTo" | ||
"*" -> return "Multiply" | ||
"+" -> return "Plus" | ||
"-" -> return "Minus" | ||
"/" -> return "Divide" | ||
"%" -> return "Percent" | ||
} | ||
|
||
val withUnderscores = this.replace(Regex("[^a-zA-Z0-9]"), "_") | ||
|
||
val prefixed = | ||
if (withUnderscores.isNotEmpty() && withUnderscores.first().isDigit()) { | ||
"_$withUnderscores" | ||
} else { | ||
withUnderscores | ||
} | ||
return prefixed.split("_").joinToString("_") { part -> | ||
if (part.isEmpty()) "" else part.normalizeEnumName() | ||
} | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.