aboutsummaryrefslogtreecommitdiff
path: root/core/src/main/kotlin/plugability/DokkaContext.kt
blob: 692803dd635601932348123aa86216a03fd2ab46 (plain)
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
package org.jetbrains.dokka.plugability

import org.jetbrains.dokka.DokkaConfiguration
import org.jetbrains.dokka.EnvironmentAndFacade
import org.jetbrains.dokka.model.SourceSetCache
import org.jetbrains.dokka.model.SourceSetData
import org.jetbrains.dokka.utilities.DokkaLogger
import java.io.File
import java.net.URLClassLoader
import java.util.*
import kotlin.reflect.KClass
import kotlin.reflect.full.createInstance


interface DokkaContext {
    fun <T : DokkaPlugin> plugin(kclass: KClass<T>): T?

    operator fun <T, E> get(point: E): List<T>
            where T : Any, E : ExtensionPoint<T>

    fun <T, E> single(point: E): T where T : Any, E : ExtensionPoint<T>

    val sourceSetCache: SourceSetCache
    val logger: DokkaLogger
    val configuration: DokkaConfiguration
    val platforms: Map<SourceSetData, EnvironmentAndFacade>
    val unusedPoints: Collection<ExtensionPoint<*>>


    companion object {
        fun create(
            configuration: DokkaConfiguration,
            logger: DokkaLogger,
            sourceSets: Map<SourceSetData, EnvironmentAndFacade>,
            sourceSetsCache: SourceSetCache,
            pluginOverrides: List<DokkaPlugin>
        ): DokkaContext =
            DokkaContextConfigurationImpl(logger, configuration, sourceSets, sourceSetsCache).apply {
                // File(it.path) is a workaround for an incorrect filesystem in a File instance returned by Gradle.
                configuration.pluginsClasspath.map { File(it.path).toURI().toURL() }
                    .toTypedArray()
                    .let { URLClassLoader(it, this.javaClass.classLoader) }
                    .also { checkClasspath(it) }
                    .let { ServiceLoader.load(DokkaPlugin::class.java, it) }
                    .let { it + pluginOverrides }
                    .forEach { install(it) }
                applyExtensions()
            }.also { it.logInitialisationInfo() }
    }
}

inline fun <reified T : DokkaPlugin> DokkaContext.plugin(): T = plugin(T::class)
    ?: throw java.lang.IllegalStateException("Plugin ${T::class.qualifiedName} is not present in context.")

interface DokkaContextConfiguration {
    fun addExtensionDependencies(extension: Extension<*>)
}

private class DokkaContextConfigurationImpl(
    override val logger: DokkaLogger,
    override val configuration: DokkaConfiguration,
    override val platforms: Map<SourceSetData, EnvironmentAndFacade>,
    override val sourceSetCache: SourceSetCache
) : DokkaContext, DokkaContextConfiguration {
    private val plugins = mutableMapOf<KClass<*>, DokkaPlugin>()
    private val pluginStubs = mutableMapOf<KClass<*>, DokkaPlugin>()
    internal val extensions = mutableMapOf<ExtensionPoint<*>, MutableList<Extension<*>>>()
    val pointsUsed: MutableSet<ExtensionPoint<*>> = mutableSetOf()
    val pointsPopulated: MutableSet<ExtensionPoint<*>> = mutableSetOf()
    override val unusedPoints: Set<ExtensionPoint<*>>
        get() = pointsPopulated - pointsUsed

    private enum class State {
        UNVISITED,
        VISITING,
        VISITED;
    }

    internal val verticesWithState = mutableMapOf<Extension<*>, State>()
    internal val adjacencyList: MutableMap<Extension<*>, MutableList<Extension<*>>> = mutableMapOf()

    private fun topologicalSort() {

        val result: MutableList<Extension<*>> = mutableListOf()

        fun visit(n: Extension<*>) {
            val state = verticesWithState[n]
            if (state == State.VISITED)
                return
            if (state == State.VISITING)
                throw Error("Detected cycle in plugins graph")
            verticesWithState[n] = State.VISITING
            adjacencyList[n]?.forEach { visit(it) }
            verticesWithState[n] = State.VISITED
            result += n
        }

        for ((vertex, state) in verticesWithState) {
            if (state == State.UNVISITED)
                visit(vertex)
        }
        result.asReversed().forEach {
            pointsPopulated += it.extensionPoint
            extensions.getOrPut(it.extensionPoint, ::mutableListOf) += it
        }
    }

    @Suppress("UNCHECKED_CAST")
    override operator fun <T, E> get(point: E) where T : Any, E : ExtensionPoint<T> =
        actions(point).also { pointsUsed += point }.orEmpty() as List<T>

    @Suppress("UNCHECKED_CAST")
    override fun <T, E> single(point: E): T where T : Any, E : ExtensionPoint<T> {
        fun throwBadArity(substitution: String): Nothing = throw IllegalStateException(
            "$point was expected to have exactly one extension registered, but $substitution found."
        )
        pointsUsed += point

        val extensions = extensions[point].orEmpty() as List<Extension<T>>
        return when (extensions.size) {
            0 -> throwBadArity("none was")
            1 -> extensions.single().action.get(this)
            else -> {
                val notFallbacks = extensions.filterNot { it.isFallback }
                if (notFallbacks.size == 1) notFallbacks.single().action.get(this) else throwBadArity("many were")
            }
        }
    }

    private fun <E : ExtensionPoint<*>> actions(point: E) = extensions[point]?.map { it.action.get(this) }

    @Suppress("UNCHECKED_CAST")
    override fun <T : DokkaPlugin> plugin(kclass: KClass<T>) = (plugins[kclass] ?: pluginStubFor(kclass)) as T

    private fun <T : DokkaPlugin> pluginStubFor(kclass: KClass<T>): DokkaPlugin =
        pluginStubs.getOrPut(kclass) { kclass.createInstance().also { it.context = this } }

    fun install(plugin: DokkaPlugin) {
        plugins[plugin::class] = plugin
        plugin.context = this
        plugin.internalInstall(this, this.configuration)
    }

    override fun addExtensionDependencies(extension: Extension<*>) {
        val orderDsl = OrderDsl()
        extension.ordering?.invoke(orderDsl)

        verticesWithState += extension to State.UNVISITED
        adjacencyList.getOrPut(extension, ::mutableListOf) += orderDsl.following.toList()
        orderDsl.previous.forEach { adjacencyList.getOrPut(it, ::mutableListOf) += extension }
    }

    fun logInitialisationInfo() {
        val pluginNames = plugins.values.map { it::class.qualifiedName.toString() }

        val loadedListForDebug = extensions.run { keys + values.flatten() }.toList()
            .joinToString(prefix = "[\n", separator = ",\n", postfix = "\n]") { "\t$it" }

        logger.progress("Loaded plugins: $pluginNames")
        logger.progress("Loaded: $loadedListForDebug")

    }

    fun applyExtensions() {
        topologicalSort()
    }
}

private fun checkClasspath(classLoader: URLClassLoader) {
    classLoader.findResource(DokkaContext::class.java.name.replace('.', '/') + ".class")?.also {
        throw AssertionError(
            "Dokka API found on plugins classpath. This will lead to subtle bugs. " +
                    "Please fix your plugins dependencies or exclude dokka api artifact from plugin classpath"
        )
    }
}