Skip to content

Commit

Permalink
Generate Int-parameter overload for Long-parameter functions
Browse files Browse the repository at this point in the history
  • Loading branch information
drewhamilton committed Oct 3, 2023
1 parent aabb943 commit 78653af
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,14 @@ internal fun writeResources(
TypeSpec.objectBuilder("FormattedResources")
.apply {
mergedResources.forEach { mergedResource ->
addFunction(mergedResource.toFunSpec(packageStringsType))
val funSpec = mergedResource.toFunSpec(packageStringsType)
addFunction(funSpec)

if (mergedResource.arguments.any { it.type == Long::class }) {
// Since Ints are used more commonly than Longs, provide an overload to accept Ints
// for Long arguments:
addFunction(mergedResource.toIntOverloadFunSpec(funSpec))
}
}
}
.addModifiers(maxVisibility.toKModifier())
Expand Down Expand Up @@ -216,6 +223,43 @@ private fun MergedResource.Visibility.toKModifier(): KModifier {
}
}

private fun MergedResource.toIntOverloadFunSpec(overloaded: FunSpec): FunSpec {
return FunSpec.builder(name.value)
.apply { if (description != null) addKdoc(description) }
.apply {
arguments.forEach { argument ->
val parameterSpec = if (argument.type == Long::class) {
ParameterSpec(
name = argument.name,
type = Int::class.asClassName(),
)
} else {
argument.toParameterSpec()
}
addParameter(parameterSpec)
}
}
.returns(Types.FormattedResource)
.apply {
addCode(
buildCodeBlock {
add("return %N(⇥\n", overloaded)
arguments.forEach { argument ->
val argumentInvocation = if (argument.type == Long::class) {
"%L.toLong(),\n"
} else {
"%L,\n"
}
add(argumentInvocation, argument.name)
}
add("⇤)\n")
}
)
}
.addModifiers(visibility.toKModifier(), KModifier.INLINE)
.build()
}

private object Types {
val ArrayMap = ClassName("androidx.collection", "ArrayMap")
val Calendar = ClassName("android.icu.util", "Calendar")
Expand Down
3 changes: 2 additions & 1 deletion tests/src/main/kotlin/app/cash/paraphrase/tests/TypesTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -315,7 +315,8 @@ class TypesTest {
}

@Test fun typeOrdinal() {
val formattedZero = context.getString(FormattedResources.type_ordinal(0))
val zero = 0 // Requires an int overload to be invoked
val formattedZero = context.getString(FormattedResources.type_ordinal(zero))
assertThat(formattedZero).isEqualTo("A 0th B")
val formattedOne = context.getString(FormattedResources.type_ordinal(1))
assertThat(formattedOne).isEqualTo("A 1st B")
Expand Down

0 comments on commit 78653af

Please sign in to comment.