-
Notifications
You must be signed in to change notification settings - Fork 451
/
lenses.kt
58 lines (53 loc) · 1.92 KB
/
lenses.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package arrow.optics.plugin.internals
import arrow.optics.plugin.OpticsProcessorOptions
import java.util.Locale
internal fun OpticsProcessorOptions.generateLenses(ele: ADT, target: LensTarget) =
Snippet(
`package` = ele.packageName,
name = ele.simpleName,
content = processElement(ele, target.foci),
)
private fun String.toUpperCamelCase(): String =
split(" ")
.joinToString(
"",
transform = {
it.replaceFirstChar {
if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString()
}
},
)
private fun OpticsProcessorOptions.processElement(adt: ADT, foci: List<Focus>): String {
val sourceClassNameWithParams = "${adt.sourceClassName}${adt.angledTypeParameters}"
return foci.joinToString(separator = "\n") { focus ->
val firstLine = when {
adt.typeParameters.isEmpty() ->
"${adt.visibilityModifierName} $inlineText val ${adt.sourceClassName}.Companion.${focus.lensParamName()}: $Lens<${adt.sourceClassName}, ${focus.className}> $inlineText get()"
else ->
"${adt.visibilityModifierName} $inlineText fun ${adt.angledTypeParameters} ${adt.sourceClassName}.Companion.${focus.lensParamName()}(): $Lens<$sourceClassNameWithParams, ${focus.className}>"
}
"""
|$firstLine = $Lens(
| get = { ${adt.sourceName}: $sourceClassNameWithParams -> ${adt.sourceName}.${
focus.paramName.plusIfNotBlank(
prefix = "`",
postfix = "`",
)
} },
| set = { ${adt.sourceName}: $sourceClassNameWithParams, value: ${focus.className} -> ${adt.sourceName}.copy(${
focus.paramName.plusIfNotBlank(
prefix = "`",
postfix = "`",
)
} = value) }
|)
|
""".trimMargin()
}
}
fun Focus.lensParamName(): String =
when (this) {
is NullableFocus -> "nullable${paramName.toUpperCamelCase()}"
is OptionFocus -> "option${paramName.toUpperCamelCase()}"
is NonNullFocus -> paramName
}