aboutsummaryrefslogtreecommitdiff
path: root/core/src/main/kotlin/Kotlin/DeclarationLinkResolver.kt
blob: 275972fafa7f063e071f5d57b66062b2639c2d08 (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
package org.jetbrains.dokka

import com.google.inject.Inject
import org.jetbrains.dokka.Model.DescriptorSignatureProvider
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.idea.kdoc.resolveKDocLink

class DeclarationLinkResolver
        @Inject constructor(val resolutionFacade: DokkaResolutionFacade,
                            val refGraph: NodeReferenceGraph,
                            val logger: DokkaLogger,
                            val options: DocumentationOptions,
                            val externalDocumentationLinkResolver: ExternalDocumentationLinkResolver,
                            val descriptorSignatureProvider: DescriptorSignatureProvider) {


    fun tryResolveContentLink(fromDescriptor: DeclarationDescriptor, href: String): ContentBlock? {
        val symbol = try {
            val symbols = resolveKDocLink(resolutionFacade.resolveSession.bindingContext,
                    resolutionFacade, fromDescriptor, null, href.split('.').toList())
            findTargetSymbol(symbols)
        } catch(e: Exception) {
            null
        }

        // don't include unresolved links in generated doc
        // assume that if an href doesn't contain '/', it's not an attempt to reference an external file
        if (symbol != null) {
            val externalHref = externalDocumentationLinkResolver.buildExternalDocumentationLink(symbol)
            if (externalHref != null) {
                return ContentExternalLink(externalHref)
            }
            val signature = descriptorSignatureProvider.signature(symbol)
            return ContentNodeLazyLink(href, { -> refGraph.lookupOrWarn(signature, logger) })
        }
        if ("/" in href) {
            return ContentExternalLink(href)
        }
        return null
    }

    fun resolveContentLink(fromDescriptor: DeclarationDescriptor, href: String) =
            tryResolveContentLink(fromDescriptor, href) ?: run {
                logger.warn("Unresolved link to $href in doc comment of ${fromDescriptor.signatureWithSourceLocation()}")
                ContentExternalLink("#")
            }

    fun findTargetSymbol(symbols: Collection<DeclarationDescriptor>): DeclarationDescriptor? {
        if (symbols.isEmpty()) {
            return null
        }
        val symbol = symbols.first()
        if (symbol is CallableMemberDescriptor && symbol.kind == CallableMemberDescriptor.Kind.FAKE_OVERRIDE) {
            return symbol.overriddenDescriptors.firstOrNull()
        }
        return symbol
    }

}