Scripts/convention/src/main/kotlin/io/gitlab/jfronny/scripts/codegen/Generator.kt

36 lines
1.9 KiB
Kotlin

package io.gitlab.jfronny.scripts.codegen
abstract class Generator<T> {
private var finalized = false
protected abstract fun generateFinalized(): T
fun finalize(): T {
val fin = generateFinalized()
finalized = true
return fin
}
protected fun <T> ensureMutable(action: () -> T): T {
if (finalized) throw IllegalAccessException("Attempted to access CodeGenerator after it was finalized")
return action()
}
protected data class ImmutableMap<Key, Value>(private val inner: Map<Key, Value>): Map<Key, Value> by inner
companion object {
@JvmStatic protected val primitivePattern = Regex("(?:byte|short|int|long|float|double|boolean|char)")
@JvmStatic protected val singleModifierPattern = Regex("(?:public|private|protected|static|final|abstract|transient|synchronized|volatile)")
@JvmStatic protected val modifierPattern = Regex("(?:$singleModifierPattern(?: $singleModifierPattern)*)")
@JvmStatic protected val packagePattern = Regex("(?:[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)*)")
@JvmStatic protected val classNamePattern = Regex("(?:[A-Z][A-Za-z0-9_\$]*)")
@JvmStatic protected val pathPattern = Regex("(?:([a-z]+/)*[a-zA-Z][a-zA-Z0-9_.]*)")
@JvmStatic protected val classPattern = Regex("(?:(?:(?:$packagePattern\\.)?$classNamePattern)|$primitivePattern)")
@JvmStatic protected val importPattern = Regex("(?:$packagePattern\\.(?:\\*|$classNamePattern))")
@JvmStatic protected val classEntryPattern = Regex("(?:[a-zA-Z][a-zA-Z_\$0-9]*)")
@JvmStatic protected val classListPattern = Regex("(?:$classPattern(?:, $classPattern)*)")
@JvmStatic protected fun check(name: String, type: String, pattern: Regex): Unit {
if (!pattern.matches(name)) throw IllegalArgumentException("$type \"$name\" is not a valid $type")
}
}
}