package org.jetbrains.dokka.plugability import com.google.gson.Gson import org.jetbrains.dokka.DokkaConfiguration import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty import kotlin.reflect.KProperty1 import kotlin.reflect.full.createInstance private typealias ExtensionDelegate = ReadOnlyProperty> abstract class DokkaPlugin { private val extensionDelegates = mutableListOf>() @PublishedApi internal var context: DokkaContext? = null protected inline fun plugin(): T = context?.plugin(T::class) ?: throwIllegalQuery() protected fun extensionPoint() = object : ReadOnlyProperty> { override fun getValue(thisRef: DokkaPlugin, property: KProperty<*>) = ExtensionPoint( thisRef::class.qualifiedName ?: throw AssertionError("Plugin must be named class"), property.name ) } protected fun extending(isFallback: Boolean = false, definition: ExtendingDSL.() -> Extension) = if (isFallback) { ExtensionProvider { definition().markedAsFallback() } } else { ExtensionProvider(definition) } protected class ExtensionProvider internal constructor( private val definition: ExtendingDSL.() -> Extension ) { operator fun provideDelegate(thisRef: DokkaPlugin, property: KProperty<*>) = lazy { ExtendingDSL( thisRef::class.qualifiedName ?: throw AssertionError("Plugin must be named class"), property.name ).definition() }.also { thisRef.extensionDelegates += property } } internal fun internalInstall(ctx: DokkaContextConfiguration, configuration: DokkaConfiguration) { extensionDelegates.asSequence() .filterIsInstance>>() // should be always true .map { it.get(this) } .forEach { if (it.condition.invoke(configuration)) ctx.addExtensionDependencies(it) } } } interface Configurable { val pluginsConfiguration: Map } interface ConfigurableBlock inline fun Configurable.pluginConfiguration(block: T.() -> Unit) { val instance = T::class.createInstance().apply(block) val mutablePluginsConfiguration = pluginsConfiguration as MutableMap mutablePluginsConfiguration[P::class.qualifiedName!!] = Gson().toJson(instance, T::class.java) } inline fun P.query(extension: P.() -> ExtensionPoint): List = context?.let { it[extension()] } ?: throwIllegalQuery() inline fun P.querySingle(extension: P.() -> ExtensionPoint): E = context?.single(extension()) ?: throwIllegalQuery() fun throwIllegalQuery(): Nothing = throw IllegalStateException("Querying about plugins is only possible with dokka context initialised") inline fun configuration(context: DokkaContext): ReadOnlyProperty { return object : ReadOnlyProperty { override fun getValue(thisRef: Any?, property: KProperty<*>): R { return context.configuration.pluginsConfiguration.get(T::class.qualifiedName ?: throw AssertionError("Plugin must be named class")).let { Gson().fromJson(it, R::class.java) } } } }