From f3db3f313c599b84b1a9810723c6a503c0baf7a9 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Thu, 30 Nov 2017 19:04:11 +0300 Subject: New format stub --- .../main/kotlin/Formats/JavaLayoutHtmlFormat.kt | 45 ++++++++++++++++++++++ core/src/main/kotlin/Formats/StandardFormats.kt | 2 +- 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 core/src/main/kotlin/Formats/JavaLayoutHtmlFormat.kt (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Formats/JavaLayoutHtmlFormat.kt b/core/src/main/kotlin/Formats/JavaLayoutHtmlFormat.kt new file mode 100644 index 00000000..c023c477 --- /dev/null +++ b/core/src/main/kotlin/Formats/JavaLayoutHtmlFormat.kt @@ -0,0 +1,45 @@ +package org.jetbrains.dokka.formats + +import org.jetbrains.dokka.* +import org.jetbrains.dokka.Formats.KotlinFormatDescriptorBase + + +class JavaLayoutHtmlFormatDescriptor : KotlinFormatDescriptorBase() { + override val formatServiceClass = JavaLayoutHtmlFormatService::class + override val generatorServiceClass = JavaLayoutHtmlFormatGenerator::class +} + + +class JavaLayoutHtmlFormatService : FormatService { + override val extension: String + get() = TODO("not implemented") + + + override fun createOutputBuilder(to: StringBuilder, location: Location): FormattedOutputBuilder { + TODO("not implemented") + } +} + +class JavaLayoutHtmlFormatOutputBuilder : FormattedOutputBuilder { + override fun appendNodes(nodes: Iterable) { + TODO("not implemented") + } +} + +class JavaLayoutHtmlFormatGenerator : Generator { + override fun buildPages(nodes: Iterable) { + TODO("not implemented") + } + + override fun buildOutlines(nodes: Iterable) { + TODO("not implemented") + } + + override fun buildSupportFiles() { + TODO("not implemented") + } + + override fun buildPackageList(nodes: Iterable) { + TODO("not implemented") + } +} \ No newline at end of file diff --git a/core/src/main/kotlin/Formats/StandardFormats.kt b/core/src/main/kotlin/Formats/StandardFormats.kt index f3d638c6..c0c86f06 100644 --- a/core/src/main/kotlin/Formats/StandardFormats.kt +++ b/core/src/main/kotlin/Formats/StandardFormats.kt @@ -13,7 +13,7 @@ abstract class KotlinFormatDescriptorBase : FormatDescriptor { override val packageDocumentationBuilderClass = KotlinPackageDocumentationBuilder::class override val javaDocumentationBuilderClass = KotlinJavaDocumentationBuilder::class - override val generatorServiceClass = FileGenerator::class + override val generatorServiceClass: KClass = FileGenerator::class override val outlineServiceClass: KClass? = null override val sampleProcessingService: KClass = DefaultSampleProcessingService::class override val packageListServiceClass: KClass? = DefaultPackageListService::class -- cgit From 1b722f7c61ea3405b8f33612044b28f0b4087406 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Thu, 30 Nov 2017 20:34:25 +0300 Subject: WIP --- build.gradle | 1 + core/build.gradle | 2 + .../main/kotlin/Formats/JavaLayoutHtmlFormat.kt | 53 ++++++++++++++++++---- .../dokka/format/java-layout-html.properties | 2 +- 4 files changed, 47 insertions(+), 11 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/build.gradle b/build.gradle index 0002ee69..5772bc5d 100644 --- a/build.gradle +++ b/build.gradle @@ -33,6 +33,7 @@ allprojects { maven { url 'https://jitpack.io' } maven { url "https://teamcity.jetbrains.com/guestAuth/repository/download/Kotlin_dev_CompilerAllPlugins/$bundled_kotlin_compiler_version/maven" } ivy(repo) + maven { url "https://dl.bintray.com/kotlin/kotlinx.html" } } } diff --git a/core/build.gradle b/core/build.gradle index a8f0f275..d37b98b3 100644 --- a/core/build.gradle +++ b/core/build.gradle @@ -33,6 +33,8 @@ dependencies { compile intellijCoreAnalysis() + compile 'org.jetbrains.kotlinx:kotlinx-html-jvm:0.6.8' + //tools.jar def toolsJar = files(((URLClassLoader) ToolProvider.getSystemToolClassLoader()).getURLs().findAll { it.path.endsWith("jar") }) compileOnly toolsJar diff --git a/core/src/main/kotlin/Formats/JavaLayoutHtmlFormat.kt b/core/src/main/kotlin/Formats/JavaLayoutHtmlFormat.kt index c023c477..832c466e 100644 --- a/core/src/main/kotlin/Formats/JavaLayoutHtmlFormat.kt +++ b/core/src/main/kotlin/Formats/JavaLayoutHtmlFormat.kt @@ -1,7 +1,11 @@ -package org.jetbrains.dokka.formats +package org.jetbrains.dokka.Formats +import com.google.inject.Inject +import kotlinx.html.li +import kotlinx.html.stream.appendHTML +import kotlinx.html.ul import org.jetbrains.dokka.* -import org.jetbrains.dokka.Formats.KotlinFormatDescriptorBase +import java.io.File class JavaLayoutHtmlFormatDescriptor : KotlinFormatDescriptorBase() { @@ -22,24 +26,53 @@ class JavaLayoutHtmlFormatService : FormatService { class JavaLayoutHtmlFormatOutputBuilder : FormattedOutputBuilder { override fun appendNodes(nodes: Iterable) { - TODO("not implemented") + + } +} + + +class JavaLayoutHtmlFormatNavListBuilder @Inject constructor(private val locationService: LocationService) : OutlineFormatService { + override fun getOutlineFileName(location: Location): File { + TODO() + } + + override fun appendOutlineHeader(location: Location, node: DocumentationNode, to: StringBuilder) { + with(to.appendHTML()) { + //a(href = ) + li { + when { + node.kind == NodeKind.Package -> appendOutline(location, to, node.members) + } + } + } + } + + override fun appendOutlineLevel(to: StringBuilder, body: () -> Unit) { + with(to.appendHTML()) { + ul { body() } + } } + } -class JavaLayoutHtmlFormatGenerator : Generator { +class JavaLayoutHtmlFormatGenerator @Inject constructor( + private val outlineFormatService: OutlineFormatService +) : Generator { override fun buildPages(nodes: Iterable) { - TODO("not implemented") + } override fun buildOutlines(nodes: Iterable) { - TODO("not implemented") + for (node in nodes) { + if (node.kind == NodeKind.Module) { + //outlineFormatService.formatOutline() + } + } } - override fun buildSupportFiles() { - TODO("not implemented") - } + override fun buildSupportFiles() {} override fun buildPackageList(nodes: Iterable) { - TODO("not implemented") + } } \ No newline at end of file diff --git a/core/src/main/resources/dokka/format/java-layout-html.properties b/core/src/main/resources/dokka/format/java-layout-html.properties index c5c6bb15..fbb2bbed 100644 --- a/core/src/main/resources/dokka/format/java-layout-html.properties +++ b/core/src/main/resources/dokka/format/java-layout-html.properties @@ -1,2 +1,2 @@ -class=org.jetbrains.dokka.formats.JavaLayoutHtmlFormatDescriptor +class=org.jetbrains.dokka.Formats.JavaLayoutHtmlFormatDescriptor description=Produces Kotlin Style Docs with Javadoc like layout \ No newline at end of file -- cgit From 7acc52ba723eab08fe796fcfd68755e7f0eb6a66 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Sat, 2 Dec 2017 00:50:08 +0300 Subject: WIP: Refactoring, remove LocationService, rework FormatDescriptor --- core/build.gradle | 2 +- core/src/main/kotlin/Formats/FormatDescriptor.kt | 38 +++++++++-- core/src/main/kotlin/Formats/GFMFormatService.kt | 46 ++++++------- core/src/main/kotlin/Formats/HtmlFormatService.kt | 13 ++-- .../src/main/kotlin/Formats/HtmlTemplateService.kt | 2 +- .../main/kotlin/Formats/JavaLayoutHtmlFormat.kt | 22 ++++-- .../src/main/kotlin/Formats/JekyllFormatService.kt | 26 +++---- .../kotlin/Formats/KotlinWebsiteFormatService.kt | 67 +++++++++--------- .../Formats/KotlinWebsiteHtmlFormatService.kt | 26 +++---- .../main/kotlin/Formats/MarkdownFormatService.kt | 14 ++-- core/src/main/kotlin/Formats/PackageListService.kt | 9 ++- core/src/main/kotlin/Formats/StandardFormats.kt | 8 +-- .../main/kotlin/Formats/StructuredFormatService.kt | 19 +++--- core/src/main/kotlin/Formats/YamlOutlineService.kt | 8 ++- .../src/main/kotlin/Generation/ConsoleGenerator.kt | 42 ------------ core/src/main/kotlin/Generation/FileGenerator.kt | 17 +++-- core/src/main/kotlin/Generation/Generator.kt | 5 ++ .../kotlin/Locations/FoldersLocationService.kt | 40 ++++------- core/src/main/kotlin/Locations/LocationService.kt | 79 ++++++++++++++-------- .../Locations/SingleFolderLocationService.kt | 30 ++++---- core/src/main/kotlin/Utilities/DokkaModules.kt | 46 ++++++------- core/src/test/kotlin/TestAPI.kt | 15 ---- 22 files changed, 292 insertions(+), 282 deletions(-) delete mode 100644 core/src/main/kotlin/Generation/ConsoleGenerator.kt (limited to 'core/src/main/kotlin') diff --git a/core/build.gradle b/core/build.gradle index d37b98b3..b089dc07 100644 --- a/core/build.gradle +++ b/core/build.gradle @@ -22,7 +22,7 @@ dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib:$bundled_kotlin_compiler_version" compile "org.jetbrains.kotlin:kotlin-reflect:$bundled_kotlin_compiler_version" - compile group: 'com.google.inject', name: 'guice', version: '3.0' + compile group: 'com.google.inject', name: 'guice', version: '4.1.0' compile "org.jsoup:jsoup:1.8.3" compile "org.jetbrains.kotlin:kotlin-compiler:$bundled_kotlin_compiler_version" diff --git a/core/src/main/kotlin/Formats/FormatDescriptor.kt b/core/src/main/kotlin/Formats/FormatDescriptor.kt index da0156a7..fc0c4417 100644 --- a/core/src/main/kotlin/Formats/FormatDescriptor.kt +++ b/core/src/main/kotlin/Formats/FormatDescriptor.kt @@ -1,17 +1,47 @@ package org.jetbrains.dokka.Formats +import com.google.inject.Binder import org.jetbrains.dokka.* import org.jetbrains.dokka.Model.DescriptorSignatureProvider import org.jetbrains.dokka.Samples.SampleProcessingService +import org.jetbrains.dokka.Utilities.bind +import org.jetbrains.dokka.Utilities.toOptional +import org.jetbrains.dokka.Utilities.toType import kotlin.reflect.KClass interface FormatDescriptor { - val formatServiceClass: KClass? - val outlineServiceClass: KClass? - val generatorServiceClass: KClass + fun configureAnalysis(binder: Binder) + fun configureOutput(binder: Binder) +} + +interface FormatDescriptorAnalysisComponentProvider : FormatDescriptor { + val packageDocumentationBuilderClass: KClass val javaDocumentationBuilderClass: KClass val sampleProcessingService: KClass - val packageListServiceClass: KClass? val descriptorSignatureProvider: KClass + + + override fun configureAnalysis(binder: Binder): Unit = with(binder) { + bind() toType descriptorSignatureProvider + bind() toType packageDocumentationBuilderClass + bind() toType javaDocumentationBuilderClass + bind() toType sampleProcessingService + } } + +abstract class FileGeneratorBasedFormatDescriptor : FormatDescriptor, FormatDescriptorAnalysisComponentProvider { + + override fun configureOutput(binder: Binder): Unit = with(binder) { + bind() toOptional (outlineServiceClass) + bind() toOptional formatServiceClass + bind() toType generatorServiceClass + //bind() toType generatorServiceClass + bind() toOptional packageListServiceClass + } + + abstract val formatServiceClass: KClass? + abstract val outlineServiceClass: KClass? + abstract val generatorServiceClass: KClass + abstract val packageListServiceClass: KClass? +} \ No newline at end of file diff --git a/core/src/main/kotlin/Formats/GFMFormatService.kt b/core/src/main/kotlin/Formats/GFMFormatService.kt index f741561c..036ec856 100644 --- a/core/src/main/kotlin/Formats/GFMFormatService.kt +++ b/core/src/main/kotlin/Formats/GFMFormatService.kt @@ -4,14 +4,14 @@ import com.google.inject.Inject import com.google.inject.name.Named import org.jetbrains.dokka.Utilities.impliedPlatformsName -open class GFMOutputBuilder(to: StringBuilder, - location: Location, - locationService: LocationService, - languageService: LanguageService, - extension: String, - impliedPlatforms: List) - : MarkdownOutputBuilder(to, location, locationService, languageService, extension, impliedPlatforms) -{ +open class GFMOutputBuilder( + to: StringBuilder, + location: Location, + generator: NodeLocationAwareGenerator, + languageService: LanguageService, + extension: String, + impliedPlatforms: List +) : MarkdownOutputBuilder(to, location, generator, languageService, extension, impliedPlatforms) { override fun appendTable(vararg columns: String, body: () -> Unit) { to.appendln(columns.joinToString(" | ", "| ", " |")) to.appendln("|" + "---|".repeat(columns.size)) @@ -21,8 +21,7 @@ open class GFMOutputBuilder(to: StringBuilder, override fun appendUnorderedList(body: () -> Unit) { if (inTableCell) { wrapInTag("ul", body) - } - else { + } else { super.appendUnorderedList(body) } } @@ -30,8 +29,7 @@ open class GFMOutputBuilder(to: StringBuilder, override fun appendOrderedList(body: () -> Unit) { if (inTableCell) { wrapInTag("ol", body) - } - else { + } else { super.appendOrderedList(body) } } @@ -39,23 +37,25 @@ open class GFMOutputBuilder(to: StringBuilder, override fun appendListItem(body: () -> Unit) { if (inTableCell) { wrapInTag("li", body) - } - else { + } else { super.appendListItem(body) } } } -open class GFMFormatService(locationService: LocationService, - signatureGenerator: LanguageService, - linkExtension: String, - impliedPlatforms: List) -: MarkdownFormatService(locationService, signatureGenerator, linkExtension, impliedPlatforms) { +open class GFMFormatService( + generator: NodeLocationAwareGenerator, + signatureGenerator: LanguageService, + linkExtension: String, + impliedPlatforms: List +) : MarkdownFormatService(generator, signatureGenerator, linkExtension, impliedPlatforms) { - @Inject constructor(locationService: LocationService, - signatureGenerator: LanguageService, - @Named(impliedPlatformsName) impliedPlatforms: List) : this(locationService, signatureGenerator, "md", impliedPlatforms) + @Inject constructor( + generator: NodeLocationAwareGenerator, + signatureGenerator: LanguageService, + @Named(impliedPlatformsName) impliedPlatforms: List + ) : this(generator, signatureGenerator, "md", impliedPlatforms) override fun createOutputBuilder(to: StringBuilder, location: Location): FormattedOutputBuilder = - GFMOutputBuilder(to, location, locationService, languageService, extension, impliedPlatforms) + GFMOutputBuilder(to, location, generator, languageService, extension, impliedPlatforms) } diff --git a/core/src/main/kotlin/Formats/HtmlFormatService.kt b/core/src/main/kotlin/Formats/HtmlFormatService.kt index 5e05f51a..560d8597 100644 --- a/core/src/main/kotlin/Formats/HtmlFormatService.kt +++ b/core/src/main/kotlin/Formats/HtmlFormatService.kt @@ -5,16 +5,15 @@ import com.google.inject.name.Named import org.jetbrains.dokka.Utilities.impliedPlatformsName import java.io.File import java.nio.file.Path -import java.nio.file.Paths open class HtmlOutputBuilder(to: StringBuilder, location: Location, - locationService: LocationService, + generator: NodeLocationAwareGenerator, languageService: LanguageService, extension: String, impliedPlatforms: List, val templateService: HtmlTemplateService) - : StructuredOutputBuilder(to, location, locationService, languageService, extension, impliedPlatforms) + : StructuredOutputBuilder(to, location, generator, languageService, extension, impliedPlatforms) { override fun appendText(text: String) { to.append(text.htmlEscape()) @@ -95,18 +94,18 @@ open class HtmlOutputBuilder(to: StringBuilder, } } -open class HtmlFormatService @Inject constructor(@Named("folders") locationService: LocationService, +open class HtmlFormatService @Inject constructor(generator: NodeLocationAwareGenerator, signatureGenerator: LanguageService, val templateService: HtmlTemplateService, @Named(impliedPlatformsName) val impliedPlatforms: List) -: StructuredFormatService(locationService, signatureGenerator, "html"), OutlineFormatService { +: StructuredFormatService(generator, signatureGenerator, "html"), OutlineFormatService { override fun enumerateSupportFiles(callback: (String, String) -> Unit) { callback("/dokka/styles/style.css", "style.css") } override fun createOutputBuilder(to: StringBuilder, location: Location) = - HtmlOutputBuilder(to, location, locationService, languageService, extension, impliedPlatforms, templateService) + HtmlOutputBuilder(to, location, generator, languageService, extension, impliedPlatforms, templateService) override fun appendOutline(location: Location, to: StringBuilder, nodes: Iterable) { templateService.appendHeader(to, "Module Contents", locationService.calcPathToRoot(location)) @@ -123,7 +122,7 @@ open class HtmlFormatService @Inject constructor(@Named("folders") locationServi link.append(languageService.render(node, LanguageService.RenderMode.FULL)) val tempBuilder = StringBuilder() createOutputBuilder(tempBuilder, location).appendContent(link) - to.appendln("${tempBuilder.toString()}
") + to.appendln("$tempBuilder
") } override fun appendOutlineLevel(to: StringBuilder, body: () -> Unit) { diff --git a/core/src/main/kotlin/Formats/HtmlTemplateService.kt b/core/src/main/kotlin/Formats/HtmlTemplateService.kt index 010bc702..22832e34 100644 --- a/core/src/main/kotlin/Formats/HtmlTemplateService.kt +++ b/core/src/main/kotlin/Formats/HtmlTemplateService.kt @@ -16,7 +16,7 @@ interface HtmlTemplateService { to.appendln("") to.appendln("") } - override fun appendHeader(to: StringBuilder, title: String?, basePath: Path) { + override fun appendHeader(to: StringBuilder, title: String?, relativePathToRoot: String) { to.appendln("") to.appendln("") to.appendln("") diff --git a/core/src/main/kotlin/Formats/JavaLayoutHtmlFormat.kt b/core/src/main/kotlin/Formats/JavaLayoutHtmlFormat.kt index 832c466e..9fb72e37 100644 --- a/core/src/main/kotlin/Formats/JavaLayoutHtmlFormat.kt +++ b/core/src/main/kotlin/Formats/JavaLayoutHtmlFormat.kt @@ -1,16 +1,30 @@ package org.jetbrains.dokka.Formats +import com.google.inject.Binder import com.google.inject.Inject import kotlinx.html.li import kotlinx.html.stream.appendHTML import kotlinx.html.ul import org.jetbrains.dokka.* +import org.jetbrains.dokka.Kotlin.KotlinDescriptorSignatureProvider +import org.jetbrains.dokka.Samples.DefaultSampleProcessingService +import org.jetbrains.dokka.Utilities.bind +import org.jetbrains.dokka.Utilities.toType import java.io.File -class JavaLayoutHtmlFormatDescriptor : KotlinFormatDescriptorBase() { - override val formatServiceClass = JavaLayoutHtmlFormatService::class - override val generatorServiceClass = JavaLayoutHtmlFormatGenerator::class +class JavaLayoutHtmlFormatDescriptor : FormatDescriptor, FormatDescriptorAnalysisComponentProvider { + override val packageDocumentationBuilderClass = KotlinPackageDocumentationBuilder::class + override val javaDocumentationBuilderClass = KotlinJavaDocumentationBuilder::class + override val sampleProcessingService = DefaultSampleProcessingService::class + override val descriptorSignatureProvider = KotlinDescriptorSignatureProvider::class + + override fun configureOutput(binder: Binder): Unit = with(binder) { + bind() toType generatorServiceClass + } + + val formatServiceClass = JavaLayoutHtmlFormatService::class + val generatorServiceClass = JavaLayoutHtmlFormatGenerator::class } @@ -31,7 +45,7 @@ class JavaLayoutHtmlFormatOutputBuilder : FormattedOutputBuilder { } -class JavaLayoutHtmlFormatNavListBuilder @Inject constructor(private val locationService: LocationService) : OutlineFormatService { +class JavaLayoutHtmlFormatNavListBuilder @Inject constructor() : OutlineFormatService { override fun getOutlineFileName(location: Location): File { TODO() } diff --git a/core/src/main/kotlin/Formats/JekyllFormatService.kt b/core/src/main/kotlin/Formats/JekyllFormatService.kt index 6b97bbe0..a948dfa9 100644 --- a/core/src/main/kotlin/Formats/JekyllFormatService.kt +++ b/core/src/main/kotlin/Formats/JekyllFormatService.kt @@ -6,12 +6,11 @@ import org.jetbrains.dokka.Utilities.impliedPlatformsName open class JekyllOutputBuilder(to: StringBuilder, location: Location, - locationService: LocationService, + generator: NodeLocationAwareGenerator, languageService: LanguageService, extension: String, impliedPlatforms: List) - : MarkdownOutputBuilder(to, location, locationService, languageService, extension, impliedPlatforms) -{ + : MarkdownOutputBuilder(to, location, generator, languageService, extension, impliedPlatforms) { override fun appendNodes(nodes: Iterable) { to.appendln("---") appendFrontMatter(nodes, to) @@ -26,17 +25,20 @@ open class JekyllOutputBuilder(to: StringBuilder, } -open class JekyllFormatService(locationService: LocationService, - signatureGenerator: LanguageService, - linkExtension: String, - impliedPlatforms: List) -: MarkdownFormatService(locationService, signatureGenerator, linkExtension, impliedPlatforms) { +open class JekyllFormatService( + generator: NodeLocationAwareGenerator, + signatureGenerator: LanguageService, + linkExtension: String, + impliedPlatforms: List +) : MarkdownFormatService(generator, signatureGenerator, linkExtension, impliedPlatforms) { - @Inject constructor(locationService: LocationService, - signatureGenerator: LanguageService, - @Named(impliedPlatformsName) impliedPlatforms: List): this(locationService, signatureGenerator, "html", impliedPlatforms) + @Inject constructor( + generator: NodeLocationAwareGenerator, + signatureGenerator: LanguageService, + @Named(impliedPlatformsName) impliedPlatforms: List + ) : this(generator, signatureGenerator, "html", impliedPlatforms) override fun createOutputBuilder(to: StringBuilder, location: Location): FormattedOutputBuilder = - JekyllOutputBuilder(to, location, locationService, languageService, extension, impliedPlatforms) + JekyllOutputBuilder(to, location, generator, languageService, extension, impliedPlatforms) } diff --git a/core/src/main/kotlin/Formats/KotlinWebsiteFormatService.kt b/core/src/main/kotlin/Formats/KotlinWebsiteFormatService.kt index 08349980..a98002d4 100644 --- a/core/src/main/kotlin/Formats/KotlinWebsiteFormatService.kt +++ b/core/src/main/kotlin/Formats/KotlinWebsiteFormatService.kt @@ -6,14 +6,14 @@ import org.jetbrains.dokka.Utilities.impliedPlatformsName import org.jetbrains.kotlin.utils.addToStdlib.ifNotEmpty -open class KotlinWebsiteOutputBuilder(to: StringBuilder, - location: Location, - locationService: LocationService, - languageService: LanguageService, - extension: String, - impliedPlatforms: List) - : JekyllOutputBuilder(to, location, locationService, languageService, extension, impliedPlatforms) -{ +open class KotlinWebsiteOutputBuilder( + to: StringBuilder, + location: Location, + generator: NodeLocationAwareGenerator, + languageService: LanguageService, + extension: String, + impliedPlatforms: List +) : JekyllOutputBuilder(to, location, generator, languageService, extension, impliedPlatforms) { private var needHardLineBreaks = false private var insideDiv = 0 @@ -70,8 +70,7 @@ open class KotlinWebsiteOutputBuilder(to: StringBuilder, override fun appendHeader(level: Int, body: () -> Unit) { if (insideDiv > 0) { wrapInTag("p", body, newlineAfterClose = true) - } - else { + } else { super.appendHeader(level, body) } } @@ -79,8 +78,7 @@ open class KotlinWebsiteOutputBuilder(to: StringBuilder, override fun appendLine() { if (insideDiv > 0) { to.appendln("
") - } - else { + } else { super.appendLine() } } @@ -135,13 +133,14 @@ open class KotlinWebsiteOutputBuilder(to: StringBuilder, to.append("
") } + override fun appendIndentedSoftLineBreak() { if (needHardLineBreaks) { to.append("
    ") } } - private fun identifierClassName(kind: IdentifierKind) = when(kind) { + private fun identifierClassName(kind: IdentifierKind) = when (kind) { IdentifierKind.ParameterName -> "parameterName" IdentifierKind.SummarizedTypeName -> "summarizedTypeName" else -> "identifier" @@ -172,28 +171,29 @@ open class KotlinWebsiteOutputBuilder(to: StringBuilder, } } -class KotlinWebsiteFormatService @Inject constructor(locationService: LocationService, - signatureGenerator: LanguageService, - @Named(impliedPlatformsName) impliedPlatforms: List, - logger: DokkaLogger) - : JekyllFormatService(locationService, signatureGenerator, "html", impliedPlatforms) -{ +class KotlinWebsiteFormatService @Inject constructor( + generator: NodeLocationAwareGenerator, + signatureGenerator: LanguageService, + @Named(impliedPlatformsName) impliedPlatforms: List, + logger: DokkaLogger +) : JekyllFormatService(generator, signatureGenerator, "html", impliedPlatforms) { init { logger.warn("Format kotlin-website deprecated and will be removed in next release") } override fun createOutputBuilder(to: StringBuilder, location: Location) = - KotlinWebsiteOutputBuilder(to, location, locationService, languageService, extension, impliedPlatforms) + KotlinWebsiteOutputBuilder(to, location, generator, languageService, extension, impliedPlatforms) } -class KotlinWebsiteRunnableSamplesOutputBuilder(to: StringBuilder, - location: Location, - locationService: LocationService, - languageService: LanguageService, - extension: String, - impliedPlatforms: List) - : KotlinWebsiteOutputBuilder(to, location, locationService, languageService, extension, impliedPlatforms) { +class KotlinWebsiteRunnableSamplesOutputBuilder( + to: StringBuilder, + location: Location, + generator: NodeLocationAwareGenerator, + languageService: LanguageService, + extension: String, + impliedPlatforms: List +) : KotlinWebsiteOutputBuilder(to, location, generator, languageService, extension, impliedPlatforms) { override fun appendSampleBlockCode(language: String, imports: () -> Unit, body: () -> Unit) { div(to, "sample", markdown = true) { @@ -207,17 +207,18 @@ class KotlinWebsiteRunnableSamplesOutputBuilder(to: StringBuilder, } } -class KotlinWebsiteRunnableSamplesFormatService @Inject constructor(locationService: LocationService, - signatureGenerator: LanguageService, - @Named(impliedPlatformsName) impliedPlatforms: List, - logger: DokkaLogger) - : JekyllFormatService(locationService, signatureGenerator, "html", impliedPlatforms) { +class KotlinWebsiteRunnableSamplesFormatService @Inject constructor( + generator: NodeLocationAwareGenerator, + signatureGenerator: LanguageService, + @Named(impliedPlatformsName) impliedPlatforms: List, + logger: DokkaLogger +) : JekyllFormatService(generator, signatureGenerator, "html", impliedPlatforms) { init { logger.warn("Format kotlin-website-samples deprecated and will be removed in next release") } override fun createOutputBuilder(to: StringBuilder, location: Location) = - KotlinWebsiteRunnableSamplesOutputBuilder(to, location, locationService, languageService, extension, impliedPlatforms) + KotlinWebsiteRunnableSamplesOutputBuilder(to, location, generator, languageService, extension, impliedPlatforms) } diff --git a/core/src/main/kotlin/Formats/KotlinWebsiteHtmlFormatService.kt b/core/src/main/kotlin/Formats/KotlinWebsiteHtmlFormatService.kt index 378401f3..8fd53cdd 100644 --- a/core/src/main/kotlin/Formats/KotlinWebsiteHtmlFormatService.kt +++ b/core/src/main/kotlin/Formats/KotlinWebsiteHtmlFormatService.kt @@ -14,13 +14,14 @@ private object EmptyHtmlTemplateService : HtmlTemplateService { } -open class KotlinWebsiteHtmlOutputBuilder(to: StringBuilder, - location: Location, - locationService: LocationService, - languageService: LanguageService, - extension: String, - impliedPlatforms: List) - : HtmlOutputBuilder(to, location, locationService, languageService, extension, impliedPlatforms, EmptyHtmlTemplateService) { +open class KotlinWebsiteHtmlOutputBuilder( + to: StringBuilder, + location: Location, + generator: NodeLocationAwareGenerator, + languageService: LanguageService, + extension: String, + impliedPlatforms: List +) : HtmlOutputBuilder(to, location, generator, languageService, extension, impliedPlatforms, EmptyHtmlTemplateService) { private var needHardLineBreaks = false private var insideDiv = 0 @@ -169,14 +170,15 @@ open class KotlinWebsiteHtmlOutputBuilder(to: StringBuilder, } } -class KotlinWebsiteHtmlFormatService @Inject constructor(locationService: LocationService, - signatureGenerator: LanguageService, - @Named(impliedPlatformsName) impliedPlatforms: List) - : HtmlFormatService(locationService, signatureGenerator, EmptyHtmlTemplateService, impliedPlatforms) { +class KotlinWebsiteHtmlFormatService @Inject constructor( + generator: NodeLocationAwareGenerator, + signatureGenerator: LanguageService, + @Named(impliedPlatformsName) impliedPlatforms: List +) : HtmlFormatService(generator, signatureGenerator, EmptyHtmlTemplateService, impliedPlatforms) { override fun enumerateSupportFiles(callback: (String, String) -> Unit) {} override fun createOutputBuilder(to: StringBuilder, location: Location) = - KotlinWebsiteHtmlOutputBuilder(to, location, locationService, languageService, extension, impliedPlatforms) + KotlinWebsiteHtmlOutputBuilder(to, location, generator, languageService, extension, impliedPlatforms) } diff --git a/core/src/main/kotlin/Formats/MarkdownFormatService.kt b/core/src/main/kotlin/Formats/MarkdownFormatService.kt index a7c18a28..4265394f 100644 --- a/core/src/main/kotlin/Formats/MarkdownFormatService.kt +++ b/core/src/main/kotlin/Formats/MarkdownFormatService.kt @@ -21,11 +21,11 @@ private val TWO_LINE_BREAKS = System.lineSeparator() + System.lineSeparator() open class MarkdownOutputBuilder(to: StringBuilder, location: Location, - locationService: LocationService, + generator: NodeLocationAwareGenerator, languageService: LanguageService, extension: String, impliedPlatforms: List) - : StructuredOutputBuilder(to, location, locationService, languageService, extension, impliedPlatforms) + : StructuredOutputBuilder(to, location, generator, languageService, extension, impliedPlatforms) { private val listStack = ArrayDeque() protected var inTableCell = false @@ -225,15 +225,15 @@ open class MarkdownOutputBuilder(to: StringBuilder, } } -open class MarkdownFormatService(locationService: LocationService, +open class MarkdownFormatService(generator: NodeLocationAwareGenerator, signatureGenerator: LanguageService, linkExtension: String, val impliedPlatforms: List) -: StructuredFormatService(locationService, signatureGenerator, "md", linkExtension) { - @Inject constructor(locationService: LocationService, +: StructuredFormatService(generator, signatureGenerator, "md", linkExtension) { + @Inject constructor(generator: NodeLocationAwareGenerator, signatureGenerator: LanguageService, - @Named(impliedPlatformsName) impliedPlatforms: List): this(locationService, signatureGenerator, "md", impliedPlatforms) + @Named(impliedPlatformsName) impliedPlatforms: List): this(generator, signatureGenerator, "md", impliedPlatforms) override fun createOutputBuilder(to: StringBuilder, location: Location): FormattedOutputBuilder = - MarkdownOutputBuilder(to, location, locationService, languageService, extension, impliedPlatforms) + MarkdownOutputBuilder(to, location, generator, languageService, extension, impliedPlatforms) } diff --git a/core/src/main/kotlin/Formats/PackageListService.kt b/core/src/main/kotlin/Formats/PackageListService.kt index e7f4e952..be50fac4 100644 --- a/core/src/main/kotlin/Formats/PackageListService.kt +++ b/core/src/main/kotlin/Formats/PackageListService.kt @@ -7,10 +7,9 @@ interface PackageListService { fun formatPackageList(module: DocumentationModule): String } -class DefaultPackageListService @Inject constructor(locationService: FileLocationService, - val formatService: FormatService) : PackageListService { - - val locationService: FileLocationService = locationService.withExtension(formatService.linkExtension) +class DefaultPackageListService @Inject constructor( + val generator: FileGenerator, + val formatService: FormatService) : PackageListService { override fun formatPackageList(module: DocumentationModule): String { val packages = mutableSetOf() @@ -26,7 +25,7 @@ class DefaultPackageListService @Inject constructor(locationService: FileLocatio } NodeKind.Signature -> { if (relocated) - nonStandardLocations[node.name] = locationService.relativePathToLocation(module, node.owner!!) + nonStandardLocations[node.name] = generator.relativePathToLocation(module, node.owner!!) } NodeKind.ExternalClass -> { node.members.forEach { visit(it, relocated = true) } diff --git a/core/src/main/kotlin/Formats/StandardFormats.kt b/core/src/main/kotlin/Formats/StandardFormats.kt index c0c86f06..54544ebc 100644 --- a/core/src/main/kotlin/Formats/StandardFormats.kt +++ b/core/src/main/kotlin/Formats/StandardFormats.kt @@ -3,17 +3,17 @@ package org.jetbrains.dokka.Formats import org.jetbrains.dokka.* import org.jetbrains.dokka.Kotlin.KotlinAsJavaDescriptorSignatureProvider import org.jetbrains.dokka.Kotlin.KotlinDescriptorSignatureProvider -import org.jetbrains.dokka.Model.DescriptorSignatureProvider import org.jetbrains.dokka.Samples.DefaultSampleProcessingService import org.jetbrains.dokka.Samples.KotlinWebsiteSampleProcessingService import org.jetbrains.dokka.Samples.SampleProcessingService import kotlin.reflect.KClass -abstract class KotlinFormatDescriptorBase : FormatDescriptor { +abstract class KotlinFormatDescriptorBase : FileGeneratorBasedFormatDescriptor() { + override val packageDocumentationBuilderClass = KotlinPackageDocumentationBuilder::class override val javaDocumentationBuilderClass = KotlinJavaDocumentationBuilder::class - override val generatorServiceClass: KClass = FileGenerator::class + override val generatorServiceClass = FileGenerator::class override val outlineServiceClass: KClass? = null override val sampleProcessingService: KClass = DefaultSampleProcessingService::class override val packageListServiceClass: KClass? = DefaultPackageListService::class @@ -25,7 +25,7 @@ class HtmlFormatDescriptor : KotlinFormatDescriptorBase() { override val outlineServiceClass = HtmlFormatService::class } -class HtmlAsJavaFormatDescriptor : FormatDescriptor { +class HtmlAsJavaFormatDescriptor : FileGeneratorBasedFormatDescriptor() { override val formatServiceClass = HtmlFormatService::class override val outlineServiceClass = HtmlFormatService::class override val generatorServiceClass = FileGenerator::class diff --git a/core/src/main/kotlin/Formats/StructuredFormatService.kt b/core/src/main/kotlin/Formats/StructuredFormatService.kt index 5167a102..952e14cf 100644 --- a/core/src/main/kotlin/Formats/StructuredFormatService.kt +++ b/core/src/main/kotlin/Formats/StructuredFormatService.kt @@ -7,11 +7,13 @@ data class FormatLink(val text: String, val href: String) abstract class StructuredOutputBuilder(val to: StringBuilder, val location: Location, - val locationService: LocationService, + val generator: NodeLocationAwareGenerator, val languageService: LanguageService, val extension: String, val impliedPlatforms: List) : FormattedOutputBuilder { + protected fun DocumentationNode.location() = generator.location(this) + protected fun wrap(prefix: String, suffix: String, body: () -> Unit) { to.append(prefix) body() @@ -204,16 +206,16 @@ abstract class StructuredOutputBuilder(val to: StringBuilder, if (from.owner?.kind == NodeKind.GroupNode) return link(from.owner!!, to, extension, name) - return FormatLink(name(to), locationService.relativePathToLocation(from, to)) + return FormatLink(name(to), from.location().relativePathTo(to.location())) } fun locationHref(from: Location, to: DocumentationNode): String { val topLevelPage = to.references(RefKind.TopLevelPage).singleOrNull()?.to if (topLevelPage != null) { val signature = to.detailOrNull(NodeKind.Signature) - return from.relativePathTo(locationService.location(topLevelPage), signature?.name ?: to.name) + return from.relativePathTo(topLevelPage.location(), signature?.name ?: to.name) } - return from.relativePathTo(locationService.location(to)) + return from.relativePathTo(to.location()) } private fun DocumentationNode.isModuleOrPackage(): Boolean = @@ -349,7 +351,8 @@ abstract class StructuredOutputBuilder(val to: StringBuilder, overrides.forEach { appendParagraph { to.append("Overrides ") - val location = locationService.relativePathToLocation(this, it) + val location = location().relativePathTo(it.location()) + appendLink(FormatLink(it.owner!!.name + "." + it.name, location)) } } @@ -383,7 +386,7 @@ abstract class StructuredOutputBuilder(val to: StringBuilder, else platformsToShow - if(platforms.isEmpty()) return + if (platforms.isEmpty()) return appendParagraph { appendStrong { to.append("Platform and version requirements:") } @@ -674,9 +677,9 @@ abstract class StructuredOutputBuilder(val to: StringBuilder, } } -abstract class StructuredFormatService(locationService: LocationService, +abstract class StructuredFormatService(val generator: NodeLocationAwareGenerator, val languageService: LanguageService, override val extension: String, override final val linkExtension: String = extension) : FormatService { - val locationService: LocationService = locationService.withExtension(linkExtension) + } diff --git a/core/src/main/kotlin/Formats/YamlOutlineService.kt b/core/src/main/kotlin/Formats/YamlOutlineService.kt index 7968824c..c36f98eb 100644 --- a/core/src/main/kotlin/Formats/YamlOutlineService.kt +++ b/core/src/main/kotlin/Formats/YamlOutlineService.kt @@ -3,15 +3,17 @@ package org.jetbrains.dokka import com.google.inject.Inject import java.io.File -class YamlOutlineService @Inject constructor(val locationService: LocationService, - val languageService: LanguageService) : OutlineFormatService { +class YamlOutlineService @Inject constructor( + val generator: NodeLocationAwareGenerator, + val languageService: LanguageService +) : OutlineFormatService { override fun getOutlineFileName(location: Location): File = File("${location.path}.yml") var outlineLevel = 0 override fun appendOutlineHeader(location: Location, node: DocumentationNode, to: StringBuilder) { val indent = " ".repeat(outlineLevel) to.appendln("$indent- title: ${languageService.renderName(node)}") - to.appendln("$indent url: ${locationService.location(node).path}") + to.appendln("$indent url: ${generator.location(node).path}") } override fun appendOutlineLevel(to: StringBuilder, body: () -> Unit) { diff --git a/core/src/main/kotlin/Generation/ConsoleGenerator.kt b/core/src/main/kotlin/Generation/ConsoleGenerator.kt deleted file mode 100644 index 301f86b9..00000000 --- a/core/src/main/kotlin/Generation/ConsoleGenerator.kt +++ /dev/null @@ -1,42 +0,0 @@ -package org.jetbrains.dokka - -class ConsoleGenerator(val signatureGenerator: LanguageService, val locationService: LocationService) { - val IndentStep = " " - - fun generate(node: DocumentationNode, indent: String = "") { - println("@${locationService.location(node).path}") - generateHeader(node, indent) - //generateDetails(node, indent) - generateMembers(node, indent) - generateLinks(node, indent) - } - - fun generateHeader(node: DocumentationNode, indent: String = "") { - println(indent + signatureGenerator.render(node)) - val docString = node.content.toString() - if (!docString.isEmpty()) - println("$indent\"${docString.replace("\n", "\n$indent")}\"") - println() - } - - fun generateMembers(node: DocumentationNode, indent: String = "") { - val items = node.members.sortedBy { it.name } - for (child in items) - generate(child, indent + IndentStep) - } - - fun generateDetails(node: DocumentationNode, indent: String = "") { - val items = node.details - for (child in items) - generate(child, indent + " ") - } - - fun generateLinks(node: DocumentationNode, indent: String = "") { - val items = node.links - if (items.isEmpty()) - return - println("$indent Links") - for (child in items) - generate(child, indent + " ") - } -} \ No newline at end of file diff --git a/core/src/main/kotlin/Generation/FileGenerator.kt b/core/src/main/kotlin/Generation/FileGenerator.kt index e055c537..3193a5bc 100644 --- a/core/src/main/kotlin/Generation/FileGenerator.kt +++ b/core/src/main/kotlin/Generation/FileGenerator.kt @@ -1,22 +1,27 @@ package org.jetbrains.dokka import com.google.inject.Inject +import com.google.inject.name.Named import java.io.File import java.io.FileOutputStream import java.io.IOException import java.io.OutputStreamWriter -class FileGenerator @Inject constructor(val locationService: FileLocationService) : Generator { +class FileGenerator @Inject constructor(@Named("outputDir") val rootFile: File) : NodeLocationAwareGenerator { @set:Inject(optional = true) var outlineService: OutlineFormatService? = null @set:Inject(optional = true) lateinit var formatService: FormatService @set:Inject(optional = true) lateinit var options: DocumentationOptions @set:Inject(optional = true) var packageListService: PackageListService? = null + override fun location(node: DocumentationNode): FileLocation { + return FileLocation(File(rootFile, relativePathToNode(node.path.map { it.name }, node.members.any())).appendExtension(formatService.extension)) + } + override fun buildPages(nodes: Iterable) { - val specificLocationService = locationService.withExtension(formatService.extension) + //val specificLocationService = locationService.withExtension(formatService.extension) - for ((location, items) in nodes.groupBy { specificLocationService.location(it) }) { + for ((location, items) in nodes.groupBy { location(it) }) { val file = location.file file.parentFile?.mkdirsOrFail() try { @@ -34,7 +39,7 @@ class FileGenerator @Inject constructor(val locationService: FileLocationService override fun buildOutlines(nodes: Iterable) { val outlineService = this.outlineService ?: return - for ((location, items) in nodes.groupBy { locationService.location(it) }) { + for ((location, items) in nodes.groupBy { location(it) }) { val file = outlineService.getOutlineFileName(location) file.parentFile?.mkdirsOrFail() FileOutputStream(file).use { @@ -47,7 +52,7 @@ class FileGenerator @Inject constructor(val locationService: FileLocationService override fun buildSupportFiles() { formatService.enumerateSupportFiles { resource, targetPath -> - FileOutputStream(locationService.location(listOf(targetPath), false).file).use { + FileOutputStream(relativePathToNode(listOf(targetPath), false)).use { javaClass.getResourceAsStream(resource).copyTo(it) } } @@ -58,7 +63,7 @@ class FileGenerator @Inject constructor(val locationService: FileLocationService for (module in nodes) { - val moduleRoot = locationService.location(module).file.parentFile + val moduleRoot = location(module).file.parentFile val packageListFile = File(moduleRoot, "package-list") packageListFile.writeText("\$dokka.format:${options.outputFormat}\n" + diff --git a/core/src/main/kotlin/Generation/Generator.kt b/core/src/main/kotlin/Generation/Generator.kt index 76a5f350..003386ef 100644 --- a/core/src/main/kotlin/Generation/Generator.kt +++ b/core/src/main/kotlin/Generation/Generator.kt @@ -19,3 +19,8 @@ fun Generator.buildPage(node: DocumentationNode): Unit = buildPages(listOf(node) fun Generator.buildOutline(node: DocumentationNode): Unit = buildOutlines(listOf(node)) fun Generator.buildAll(node: DocumentationNode): Unit = buildAll(listOf(node)) + + +interface NodeLocationAwareGenerator: Generator { + fun location(node: DocumentationNode): Location +} \ No newline at end of file diff --git a/core/src/main/kotlin/Locations/FoldersLocationService.kt b/core/src/main/kotlin/Locations/FoldersLocationService.kt index 83e1cf6a..ae5301e7 100644 --- a/core/src/main/kotlin/Locations/FoldersLocationService.kt +++ b/core/src/main/kotlin/Locations/FoldersLocationService.kt @@ -3,28 +3,18 @@ package org.jetbrains.dokka import com.google.inject.Inject import com.google.inject.name.Named import java.io.File - -class FoldersLocationService @Inject constructor(@Named("outputDir") val rootFile: File, val extension: String) : FileLocationService { - constructor(root: String): this(File(root), "") - - override val root: Location - get() = FileLocation(rootFile) - - override fun withExtension(newExtension: String): FileLocationService { - return if (extension.isEmpty()) FoldersLocationService(rootFile, newExtension) else this - } - - override fun location(qualifiedName: List, hasMembers: Boolean): FileLocation { - return FileLocation(File(rootFile, relativePathToNode(qualifiedName, hasMembers)).appendExtension(extension)) - } -} - -fun relativePathToNode(qualifiedName: List, hasMembers: Boolean): String { - val parts = qualifiedName.map { identifierToFilename(it) }.filterNot { it.isEmpty() } - return if (!hasMembers) { - // leaf node, use file in owner's folder - parts.joinToString("/") - } else { - parts.joinToString("/") + (if (parts.none()) "" else "/") + "index" - } -} +// +//class FoldersLocationService @Inject constructor(@Named("outputDir") val rootFile: File, val extension: String) : FileLocationService { +// constructor(root: String): this(File(root), "") +// +// override val root: Location +// get() = FileLocation(rootFile) +// +// override fun withExtension(newExtension: String): FileLocationService { +// return if (extension.isEmpty()) FoldersLocationService(rootFile, newExtension) else this +// } +// +// override fun location(qualifiedName: List, hasMembers: Boolean): FileLocation { +// return FileLocation(File(rootFile, relativePathToNode(qualifiedName, hasMembers)).appendExtension(extension)) +// } +//} diff --git a/core/src/main/kotlin/Locations/LocationService.kt b/core/src/main/kotlin/Locations/LocationService.kt index a51ef8d4..6b7e0511 100644 --- a/core/src/main/kotlin/Locations/LocationService.kt +++ b/core/src/main/kotlin/Locations/LocationService.kt @@ -32,37 +32,51 @@ data class FileLocation(val file: File): Location { } } -/** - * Provides means of retrieving locations for [DocumentationNode](documentation nodes) - * - * `LocationService` determines where documentation for particular node should be generated - * - * * [FoldersLocationService] – represent packages and types as folders, members as files in those folders. - * * [SingleFolderLocationService] – all documentation is generated into single folder using fully qualified names - * for file names. - */ -interface LocationService { - fun withExtension(newExtension: String) = this - fun location(node: DocumentationNode): Location = location(node.path.map { it.name }, node.members.any()) - /** - * Calculates a location corresponding to the specified [qualifiedName]. - * @param hasMembers if true, the node for which the location is calculated has member nodes. - */ - fun location(qualifiedName: List, hasMembers: Boolean): Location - - val root: Location +fun relativePathToNode(qualifiedName: List, hasMembers: Boolean): String { + val parts = qualifiedName.map { identifierToFilename(it) }.filterNot { it.isEmpty() } + return if (!hasMembers) { + // leaf node, use file in owner's folder + parts.joinToString("/") + } else { + parts.joinToString("/") + (if (parts.none()) "" else "/") + "index" + } } -interface FileLocationService: LocationService { - override fun withExtension(newExtension: String): FileLocationService = this - - override fun location(node: DocumentationNode): FileLocation = location(node.path.map { it.name }, node.members.any()) - override fun location(qualifiedName: List, hasMembers: Boolean): FileLocation -} +// +///** +// * Provides means of retrieving locations for [DocumentationNode](documentation nodes) +// * +// * `LocationService` determines where documentation for particular node should be generated +// * +// * * [FoldersLocationService] – represent packages and types as folders, members as files in those folders. +// * * [SingleFolderLocationService] – all documentation is generated into single folder using fully qualified names +// * for file names. +// */ +//interface LocationService { +// fun withExtension(newExtension: String) = this +// +// fun location(node: DocumentationNode): Location = location(node.path.map { it.name }, node.members.any()) +// +// /** +// * Calculates a location corresponding to the specified [qualifiedName]. +// * @param hasMembers if true, the node for which the location is calculated has member nodes. +// */ +// fun location(qualifiedName: List, hasMembers: Boolean): Location +// +// val root: Location +//} +// +// +//interface FileLocationService: LocationService { +// override fun withExtension(newExtension: String): FileLocationService = this +// +// override fun location(node: DocumentationNode): FileLocation = location(node.path.map { it.name }, node.members.any()) +// override fun location(qualifiedName: List, hasMembers: Boolean): FileLocation +//} fun identifierToFilename(path: String): String { val escaped = path.replace('<', '-').replace('>', '-') @@ -70,9 +84,14 @@ fun identifierToFilename(path: String): String { return if (lowercase == "index") "--index--" else lowercase } -/** - * Returns relative location between two nodes. Used for relative links in documentation. - */ -fun LocationService.relativePathToLocation(owner: DocumentationNode, node: DocumentationNode): String { +///** +// * Returns relative location between two nodes. Used for relative links in documentation. +// */ +//fun LocationService.relativePathToLocation(owner: DocumentationNode, node: DocumentationNode): String { +// return location(owner).relativePathTo(location(node), null) +//} + + +fun NodeLocationAwareGenerator.relativePathToLocation(owner: DocumentationNode, node: DocumentationNode): String { return location(owner).relativePathTo(location(node), null) -} +} \ No newline at end of file diff --git a/core/src/main/kotlin/Locations/SingleFolderLocationService.kt b/core/src/main/kotlin/Locations/SingleFolderLocationService.kt index 1b4fdc28..25cf6f8e 100644 --- a/core/src/main/kotlin/Locations/SingleFolderLocationService.kt +++ b/core/src/main/kotlin/Locations/SingleFolderLocationService.kt @@ -3,18 +3,18 @@ package org.jetbrains.dokka import com.google.inject.Inject import com.google.inject.name.Named import java.io.File - -class SingleFolderLocationService @Inject constructor(@Named("outputDir") val rootFile: File, val extension: String) : FileLocationService { - constructor(root: String): this(File(root), "") - - override fun withExtension(newExtension: String): FileLocationService = - SingleFolderLocationService(rootFile, newExtension) - - override fun location(qualifiedName: List, hasMembers: Boolean): FileLocation { - val filename = qualifiedName.map { identifierToFilename(it) }.joinToString("-") - return FileLocation(File(rootFile, filename).appendExtension(extension)) - } - - override val root: Location - get() = FileLocation(rootFile) -} \ No newline at end of file +// +//class SingleFolderLocationService @Inject constructor(@Named("outputDir") val rootFile: File, val extension: String) : FileLocationService { +// constructor(root: String): this(File(root), "") +// +// override fun withExtension(newExtension: String): FileLocationService = +// SingleFolderLocationService(rootFile, newExtension) +// +// override fun location(qualifiedName: List, hasMembers: Boolean): FileLocation { +// val filename = qualifiedName.map { identifierToFilename(it) }.joinToString("-") +// return FileLocation(File(rootFile, filename).appendExtension(extension)) +// } +// +// override val root: Location +// get() = FileLocation(rootFile) +//} \ No newline at end of file diff --git a/core/src/main/kotlin/Utilities/DokkaModules.kt b/core/src/main/kotlin/Utilities/DokkaModules.kt index dfb114ec..9db08010 100644 --- a/core/src/main/kotlin/Utilities/DokkaModules.kt +++ b/core/src/main/kotlin/Utilities/DokkaModules.kt @@ -4,6 +4,7 @@ import com.google.inject.Binder import com.google.inject.Module import com.google.inject.Provider import com.google.inject.TypeLiteral +import com.google.inject.binder.AnnotatedBindingBuilder import com.google.inject.name.Names import org.jetbrains.dokka.* import org.jetbrains.dokka.Formats.FormatDescriptor @@ -11,6 +12,7 @@ import org.jetbrains.dokka.Model.DescriptorSignatureProvider import org.jetbrains.dokka.Samples.SampleProcessingService import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment import java.io.File +import kotlin.reflect.KClass const val impliedPlatformsName = "impliedPlatforms" @@ -22,12 +24,7 @@ class DokkaAnalysisModule(val environment: AnalysisEnvironment, override fun configure(binder: Binder) { binder.bind().toInstance(logger) - val descriptor = ServiceLocator.lookup("format", options.outputFormat) - binder.bind().to(descriptor.descriptorSignatureProvider.java) binder.registerCategory("language") - binder.bind().to(descriptor.packageDocumentationBuilderClass.java) - binder.bind().to(descriptor.javaDocumentationBuilderClass.java) - binder.bind().to(descriptor.sampleProcessingService.java) val coreEnvironment = environment.createCoreEnvironment() binder.bind().toInstance(coreEnvironment) @@ -40,6 +37,9 @@ class DokkaAnalysisModule(val environment: AnalysisEnvironment, binder.bind().toInstance(defaultPlatformsProvider) binder.bind().toInstance(nodeReferenceGraph) + + val descriptor = ServiceLocator.lookup("format", options.outputFormat) + descriptor.configureAnalysis(binder) } } @@ -56,35 +56,26 @@ class DokkaOutputModule(val options: DocumentationOptions, binder.bind(File::class.java).annotatedWith(Names.named("outputDir")).toInstance(File(options.outputDir)) - binder.bindNameAnnotated("singleFolder") - binder.bindNameAnnotated("singleFolder") - binder.bindNameAnnotated("folders") - binder.bindNameAnnotated("folders") +// binder.bindNameAnnotated("singleFolder") +// binder.bindNameAnnotated("singleFolder") +// binder.bindNameAnnotated("folders") +// binder.bindNameAnnotated("folders") // defaults - binder.bind(LocationService::class.java).to(FoldersLocationService::class.java) - binder.bind(FileLocationService::class.java).to(FoldersLocationService::class.java) +// binder.bind(LocationService::class.java).to(FoldersLocationService::class.java) +// binder.bind(FileLocationService::class.java).to(FoldersLocationService::class.java) binder.registerCategory("outline") binder.registerCategory("format") binder.registerCategory("generator") - val descriptor = ServiceLocator.lookup("format", options.outputFormat) - - descriptor.outlineServiceClass?.let { clazz -> - binder.bind(OutlineFormatService::class.java).to(clazz.java) - } - descriptor.formatServiceClass?.let { clazz -> - binder.bind(FormatService::class.java).to(clazz.java) - } - - binder.bind().to(descriptor.generatorServiceClass.java) - - descriptor.packageListServiceClass?.let { binder.bind().to(it.java) } - binder.bind().toInstance(options) binder.bind().toInstance(logger) binder.bind(StringListType).annotatedWith(Names.named(impliedPlatformsName)).toInstance(options.impliedPlatforms) + + val descriptor = ServiceLocator.lookup("format", options.outputFormat) + + descriptor.configureOutput(binder) } } @@ -100,4 +91,9 @@ private inline fun Binder.bindNameAnnotat } -inline fun Binder.bind() = bind(T::class.java) +inline fun Binder.bind(): AnnotatedBindingBuilder = bind(T::class.java) + +inline infix fun > AnnotatedBindingBuilder.toOptional(kClass: TKClass?) = + kClass?.let { to(it.java) } + +inline infix fun > AnnotatedBindingBuilder.toType(kClass: TKClass) = to(kClass.java) diff --git a/core/src/test/kotlin/TestAPI.kt b/core/src/test/kotlin/TestAPI.kt index ff8a5260..aa3eff48 100644 --- a/core/src/test/kotlin/TestAPI.kt +++ b/core/src/test/kotlin/TestAPI.kt @@ -270,21 +270,6 @@ fun ContentNode.toTestString(): String { }.toString() } -class InMemoryLocation(override val path: String): Location { - override fun relativePathTo(other: Location, anchor: String?): String = - if (anchor != null) other.path + "#" + anchor else other.path -} - -object InMemoryLocationService: LocationService { - override fun location(qualifiedName: List, hasMembers: Boolean) = - InMemoryLocation(relativePathToNode(qualifiedName, hasMembers)) - - override val root: Location - get() = InMemoryLocation("") -} - -val tempLocation = InMemoryLocation("") - val ContentRoot.path: String get() = when(this) { is KotlinSourceRoot -> path -- cgit From f08f711a4290b47149ae3454d698e78c9f4c8e16 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Sat, 2 Dec 2017 03:46:54 +0300 Subject: Fix Javadoc format --- core/src/main/kotlin/javadoc/dokka-adapters.kt | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/javadoc/dokka-adapters.kt b/core/src/main/kotlin/javadoc/dokka-adapters.kt index c98a3801..84dff8f0 100644 --- a/core/src/main/kotlin/javadoc/dokka-adapters.kt +++ b/core/src/main/kotlin/javadoc/dokka-adapters.kt @@ -1,12 +1,16 @@ package org.jetbrains.dokka.javadoc +import com.google.inject.Binder import com.google.inject.Inject import com.sun.tools.doclets.formats.html.HtmlDoclet import org.jetbrains.dokka.* import org.jetbrains.dokka.Formats.FormatDescriptor +import org.jetbrains.dokka.Formats.FormatDescriptorAnalysisComponentProvider import org.jetbrains.dokka.Kotlin.KotlinAsJavaDescriptorSignatureProvider import org.jetbrains.dokka.Model.DescriptorSignatureProvider import org.jetbrains.dokka.Samples.DefaultSampleProcessingService +import org.jetbrains.dokka.Utilities.bind +import org.jetbrains.dokka.Utilities.toType import kotlin.reflect.KClass class JavadocGenerator @Inject constructor(val options: DocumentationOptions, val logger: DokkaLogger) : Generator { @@ -30,13 +34,13 @@ class JavadocGenerator @Inject constructor(val options: DocumentationOptions, va } } -class JavadocFormatDescriptor : FormatDescriptor { - override val formatServiceClass = null - override val outlineServiceClass = null - override val generatorServiceClass = JavadocGenerator::class +class JavadocFormatDescriptor : FormatDescriptor, FormatDescriptorAnalysisComponentProvider { override val packageDocumentationBuilderClass = KotlinAsJavaDocumentationBuilder::class override val javaDocumentationBuilderClass = JavaPsiDocumentationBuilder::class override val sampleProcessingService = DefaultSampleProcessingService::class - override val packageListServiceClass: KClass? = null override val descriptorSignatureProvider = KotlinAsJavaDescriptorSignatureProvider::class + + override fun configureOutput(binder: Binder): Unit = with(binder) { + bind() toType JavadocGenerator::class + } } -- cgit From c1abcaf32abd4e2d74b9246385b3541096cdb5b9 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Sat, 2 Dec 2017 04:29:07 +0300 Subject: Extract Analysis components out of FormatDescriptor Fight with statically injected HtmlTemplateService --- core/src/main/kotlin/Formats/AnalysisComponents.kt | 45 ++++++++++++++++++++++ core/src/main/kotlin/Formats/FormatDescriptor.kt | 25 ++++-------- .../Formats/KotlinWebsiteHtmlFormatService.kt | 14 ++++--- core/src/main/kotlin/Formats/StandardFormats.kt | 42 ++++++++++---------- core/src/main/kotlin/Utilities/DokkaModules.kt | 5 --- core/src/main/kotlin/javadoc/dokka-adapters.kt | 13 ++----- 6 files changed, 84 insertions(+), 60 deletions(-) create mode 100644 core/src/main/kotlin/Formats/AnalysisComponents.kt (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Formats/AnalysisComponents.kt b/core/src/main/kotlin/Formats/AnalysisComponents.kt new file mode 100644 index 00000000..97e1311e --- /dev/null +++ b/core/src/main/kotlin/Formats/AnalysisComponents.kt @@ -0,0 +1,45 @@ +package org.jetbrains.dokka.Formats + +import com.google.inject.Binder +import org.jetbrains.dokka.* +import org.jetbrains.dokka.Kotlin.KotlinAsJavaDescriptorSignatureProvider +import org.jetbrains.dokka.Kotlin.KotlinDescriptorSignatureProvider +import org.jetbrains.dokka.Model.DescriptorSignatureProvider +import org.jetbrains.dokka.Samples.DefaultSampleProcessingService +import org.jetbrains.dokka.Samples.SampleProcessingService +import org.jetbrains.dokka.Utilities.bind +import org.jetbrains.dokka.Utilities.toType +import kotlin.reflect.KClass + + +interface FormatDescriptorAnalysisComponentProvider : FormatDescriptorAnalysisComponent { + + val packageDocumentationBuilderClass: KClass + val javaDocumentationBuilderClass: KClass + val sampleProcessingService: KClass + val descriptorSignatureProvider: KClass + + + override fun configureAnalysis(binder: Binder): Unit = with(binder) { + bind() toType descriptorSignatureProvider + bind() toType packageDocumentationBuilderClass + bind() toType javaDocumentationBuilderClass + bind() toType sampleProcessingService + } +} + + +object KotlinAsJava: FormatDescriptorAnalysisComponentProvider { + override val packageDocumentationBuilderClass = KotlinAsJavaDocumentationBuilder::class + override val javaDocumentationBuilderClass = JavaPsiDocumentationBuilder::class + override val sampleProcessingService = DefaultSampleProcessingService::class + override val descriptorSignatureProvider = KotlinAsJavaDescriptorSignatureProvider::class +} + + +object KotlinAsKotlin: FormatDescriptorAnalysisComponentProvider { + override val packageDocumentationBuilderClass = KotlinPackageDocumentationBuilder::class + override val javaDocumentationBuilderClass = KotlinJavaDocumentationBuilder::class + override val sampleProcessingService = DefaultSampleProcessingService::class + override val descriptorSignatureProvider = KotlinDescriptorSignatureProvider::class +} \ No newline at end of file diff --git a/core/src/main/kotlin/Formats/FormatDescriptor.kt b/core/src/main/kotlin/Formats/FormatDescriptor.kt index fc0c4417..d3861b82 100644 --- a/core/src/main/kotlin/Formats/FormatDescriptor.kt +++ b/core/src/main/kotlin/Formats/FormatDescriptor.kt @@ -9,33 +9,24 @@ import org.jetbrains.dokka.Utilities.toOptional import org.jetbrains.dokka.Utilities.toType import kotlin.reflect.KClass -interface FormatDescriptor { + +interface FormatDescriptorAnalysisComponent { fun configureAnalysis(binder: Binder) - fun configureOutput(binder: Binder) } -interface FormatDescriptorAnalysisComponentProvider : FormatDescriptor { - - val packageDocumentationBuilderClass: KClass - val javaDocumentationBuilderClass: KClass - val sampleProcessingService: KClass - val descriptorSignatureProvider: KClass +interface FormatDescriptorOutputComponent { + fun configureOutput(binder: Binder) +} +interface FormatDescriptor: FormatDescriptorAnalysisComponent, FormatDescriptorOutputComponent - override fun configureAnalysis(binder: Binder): Unit = with(binder) { - bind() toType descriptorSignatureProvider - bind() toType packageDocumentationBuilderClass - bind() toType javaDocumentationBuilderClass - bind() toType sampleProcessingService - } -} -abstract class FileGeneratorBasedFormatDescriptor : FormatDescriptor, FormatDescriptorAnalysisComponentProvider { +abstract class FileGeneratorBasedFormatDescriptor : FormatDescriptor { override fun configureOutput(binder: Binder): Unit = with(binder) { bind() toOptional (outlineServiceClass) bind() toOptional formatServiceClass - bind() toType generatorServiceClass + bind() toType generatorServiceClass //bind() toType generatorServiceClass bind() toOptional packageListServiceClass } diff --git a/core/src/main/kotlin/Formats/KotlinWebsiteHtmlFormatService.kt b/core/src/main/kotlin/Formats/KotlinWebsiteHtmlFormatService.kt index 8fd53cdd..208756c8 100644 --- a/core/src/main/kotlin/Formats/KotlinWebsiteHtmlFormatService.kt +++ b/core/src/main/kotlin/Formats/KotlinWebsiteHtmlFormatService.kt @@ -7,7 +7,7 @@ import org.jetbrains.kotlin.utils.addToStdlib.ifNotEmpty import java.nio.file.Path -private object EmptyHtmlTemplateService : HtmlTemplateService { +object EmptyHtmlTemplateService : HtmlTemplateService { override fun appendFooter(to: StringBuilder) {} override fun appendHeader(to: StringBuilder, title: String?, basePath: Path) {} @@ -20,8 +20,9 @@ open class KotlinWebsiteHtmlOutputBuilder( generator: NodeLocationAwareGenerator, languageService: LanguageService, extension: String, - impliedPlatforms: List -) : HtmlOutputBuilder(to, location, generator, languageService, extension, impliedPlatforms, EmptyHtmlTemplateService) { + impliedPlatforms: List, + templateService: HtmlTemplateService +) : HtmlOutputBuilder(to, location, generator, languageService, extension, impliedPlatforms, templateService) { private var needHardLineBreaks = false private var insideDiv = 0 @@ -173,12 +174,13 @@ open class KotlinWebsiteHtmlOutputBuilder( class KotlinWebsiteHtmlFormatService @Inject constructor( generator: NodeLocationAwareGenerator, signatureGenerator: LanguageService, - @Named(impliedPlatformsName) impliedPlatforms: List -) : HtmlFormatService(generator, signatureGenerator, EmptyHtmlTemplateService, impliedPlatforms) { + @Named(impliedPlatformsName) impliedPlatforms: List, + templateService: HtmlTemplateService +) : HtmlFormatService(generator, signatureGenerator, templateService, impliedPlatforms) { override fun enumerateSupportFiles(callback: (String, String) -> Unit) {} override fun createOutputBuilder(to: StringBuilder, location: Location) = - KotlinWebsiteHtmlOutputBuilder(to, location, generator, languageService, extension, impliedPlatforms) + KotlinWebsiteHtmlOutputBuilder(to, location, generator, languageService, extension, impliedPlatforms, templateService) } diff --git a/core/src/main/kotlin/Formats/StandardFormats.kt b/core/src/main/kotlin/Formats/StandardFormats.kt index 54544ebc..9de667ab 100644 --- a/core/src/main/kotlin/Formats/StandardFormats.kt +++ b/core/src/main/kotlin/Formats/StandardFormats.kt @@ -1,41 +1,34 @@ package org.jetbrains.dokka.Formats +import com.google.inject.Binder +import com.google.inject.Provider import org.jetbrains.dokka.* -import org.jetbrains.dokka.Kotlin.KotlinAsJavaDescriptorSignatureProvider -import org.jetbrains.dokka.Kotlin.KotlinDescriptorSignatureProvider -import org.jetbrains.dokka.Samples.DefaultSampleProcessingService import org.jetbrains.dokka.Samples.KotlinWebsiteSampleProcessingService -import org.jetbrains.dokka.Samples.SampleProcessingService +import org.jetbrains.dokka.Utilities.bind import kotlin.reflect.KClass -abstract class KotlinFormatDescriptorBase : FileGeneratorBasedFormatDescriptor() { - - override val packageDocumentationBuilderClass = KotlinPackageDocumentationBuilder::class - override val javaDocumentationBuilderClass = KotlinJavaDocumentationBuilder::class - +abstract class KotlinFormatDescriptorBase : FileGeneratorBasedFormatDescriptor(), FormatDescriptorAnalysisComponentProvider by KotlinAsKotlin { override val generatorServiceClass = FileGenerator::class override val outlineServiceClass: KClass? = null - override val sampleProcessingService: KClass = DefaultSampleProcessingService::class override val packageListServiceClass: KClass? = DefaultPackageListService::class - override val descriptorSignatureProvider = KotlinDescriptorSignatureProvider::class -} - -class HtmlFormatDescriptor : KotlinFormatDescriptorBase() { - override val formatServiceClass = HtmlFormatService::class - override val outlineServiceClass = HtmlFormatService::class } -class HtmlAsJavaFormatDescriptor : FileGeneratorBasedFormatDescriptor() { +abstract class HtmlFormatDescriptorBase : FileGeneratorBasedFormatDescriptor() { override val formatServiceClass = HtmlFormatService::class override val outlineServiceClass = HtmlFormatService::class override val generatorServiceClass = FileGenerator::class - override val packageDocumentationBuilderClass = KotlinAsJavaDocumentationBuilder::class - override val javaDocumentationBuilderClass = JavaPsiDocumentationBuilder::class - override val sampleProcessingService: KClass = DefaultSampleProcessingService::class - override val packageListServiceClass: KClass? = DefaultPackageListService::class - override val descriptorSignatureProvider = KotlinAsJavaDescriptorSignatureProvider::class + override val packageListServiceClass = DefaultPackageListService::class + + override fun configureOutput(binder: Binder): Unit = with(binder) { + super.configureOutput(binder) + bind().toProvider(Provider { HtmlTemplateService.default("style.css") }) + } } +class HtmlFormatDescriptor : HtmlFormatDescriptorBase(), FormatDescriptorAnalysisComponent by KotlinAsKotlin + +class HtmlAsJavaFormatDescriptor : HtmlFormatDescriptorBase(), FormatDescriptorAnalysisComponent by KotlinAsJava + class KotlinWebsiteFormatDescriptor : KotlinFormatDescriptorBase() { override val formatServiceClass = KotlinWebsiteFormatService::class override val outlineServiceClass = YamlOutlineService::class @@ -51,6 +44,11 @@ class KotlinWebsiteHtmlFormatDescriptor : KotlinFormatDescriptorBase() { override val formatServiceClass = KotlinWebsiteHtmlFormatService::class override val sampleProcessingService = KotlinWebsiteSampleProcessingService::class override val outlineServiceClass = YamlOutlineService::class + + override fun configureOutput(binder: Binder) = with(binder) { + super.configureOutput(binder) + bind().toInstance(EmptyHtmlTemplateService) + } } class JekyllFormatDescriptor : KotlinFormatDescriptorBase() { diff --git a/core/src/main/kotlin/Utilities/DokkaModules.kt b/core/src/main/kotlin/Utilities/DokkaModules.kt index 9db08010..a2d720ef 100644 --- a/core/src/main/kotlin/Utilities/DokkaModules.kt +++ b/core/src/main/kotlin/Utilities/DokkaModules.kt @@ -49,11 +49,6 @@ class DokkaOutputModule(val options: DocumentationOptions, val logger: DokkaLogger) : Module { override fun configure(binder: Binder) { binder.bind(LanguageService::class.java).to(KotlinLanguageService::class.java) - - binder.bind(HtmlTemplateService::class.java).toProvider(object : Provider { - override fun get(): HtmlTemplateService = HtmlTemplateService.default("style.css") - }) - binder.bind(File::class.java).annotatedWith(Names.named("outputDir")).toInstance(File(options.outputDir)) // binder.bindNameAnnotated("singleFolder") diff --git a/core/src/main/kotlin/javadoc/dokka-adapters.kt b/core/src/main/kotlin/javadoc/dokka-adapters.kt index 84dff8f0..bed211f6 100644 --- a/core/src/main/kotlin/javadoc/dokka-adapters.kt +++ b/core/src/main/kotlin/javadoc/dokka-adapters.kt @@ -5,13 +5,10 @@ import com.google.inject.Inject import com.sun.tools.doclets.formats.html.HtmlDoclet import org.jetbrains.dokka.* import org.jetbrains.dokka.Formats.FormatDescriptor -import org.jetbrains.dokka.Formats.FormatDescriptorAnalysisComponentProvider -import org.jetbrains.dokka.Kotlin.KotlinAsJavaDescriptorSignatureProvider -import org.jetbrains.dokka.Model.DescriptorSignatureProvider -import org.jetbrains.dokka.Samples.DefaultSampleProcessingService +import org.jetbrains.dokka.Formats.FormatDescriptorAnalysisComponent +import org.jetbrains.dokka.Formats.KotlinAsJava import org.jetbrains.dokka.Utilities.bind import org.jetbrains.dokka.Utilities.toType -import kotlin.reflect.KClass class JavadocGenerator @Inject constructor(val options: DocumentationOptions, val logger: DokkaLogger) : Generator { @@ -34,11 +31,7 @@ class JavadocGenerator @Inject constructor(val options: DocumentationOptions, va } } -class JavadocFormatDescriptor : FormatDescriptor, FormatDescriptorAnalysisComponentProvider { - override val packageDocumentationBuilderClass = KotlinAsJavaDocumentationBuilder::class - override val javaDocumentationBuilderClass = JavaPsiDocumentationBuilder::class - override val sampleProcessingService = DefaultSampleProcessingService::class - override val descriptorSignatureProvider = KotlinAsJavaDescriptorSignatureProvider::class +class JavadocFormatDescriptor : FormatDescriptor, FormatDescriptorAnalysisComponent by KotlinAsJava { override fun configureOutput(binder: Binder): Unit = with(binder) { bind() toType JavadocGenerator::class -- cgit From c7523225200a3e24d24fb3b0492d5c377246fc69 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Sat, 2 Dec 2017 04:57:45 +0300 Subject: Make possible to calculate path to root --- core/src/main/kotlin/Formats/HtmlFormatService.kt | 9 ++------- core/src/main/kotlin/Formats/HtmlTemplateService.kt | 6 +++--- core/src/main/kotlin/Formats/KotlinWebsiteHtmlFormatService.kt | 4 ++-- core/src/main/kotlin/Generation/FileGenerator.kt | 2 ++ core/src/main/kotlin/Generation/Generator.kt | 3 +++ core/src/main/kotlin/Locations/LocationService.kt | 6 ++++++ 6 files changed, 18 insertions(+), 12 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Formats/HtmlFormatService.kt b/core/src/main/kotlin/Formats/HtmlFormatService.kt index 560d8597..0073553c 100644 --- a/core/src/main/kotlin/Formats/HtmlFormatService.kt +++ b/core/src/main/kotlin/Formats/HtmlFormatService.kt @@ -80,7 +80,7 @@ open class HtmlOutputBuilder(to: StringBuilder, } override fun appendNodes(nodes: Iterable) { - templateService.appendHeader(to, getPageTitle(nodes), locationService.calcPathToRoot(location)) + templateService.appendHeader(to, getPageTitle(nodes), generator.relativeToRoot(location)) super.appendNodes(nodes) templateService.appendFooter(to) } @@ -108,7 +108,7 @@ open class HtmlFormatService @Inject constructor(generator: NodeLocationAwareGen HtmlOutputBuilder(to, location, generator, languageService, extension, impliedPlatforms, templateService) override fun appendOutline(location: Location, to: StringBuilder, nodes: Iterable) { - templateService.appendHeader(to, "Module Contents", locationService.calcPathToRoot(location)) + templateService.appendHeader(to, "Module Contents", generator.relativeToRoot(location)) super.appendOutline(location, to, nodes) templateService.appendFooter(to) } @@ -132,11 +132,6 @@ open class HtmlFormatService @Inject constructor(generator: NodeLocationAwareGen } } -private fun LocationService.calcPathToRoot(location: Location): Path { - val path = Paths.get(location.path) - return path.parent?.relativize(Paths.get(root.path + '/')) ?: path -} - fun getPageTitle(nodes: Iterable): String? { val breakdownByLocation = nodes.groupBy { node -> formatPageTitle(node) } return breakdownByLocation.keys.singleOrNull() diff --git a/core/src/main/kotlin/Formats/HtmlTemplateService.kt b/core/src/main/kotlin/Formats/HtmlTemplateService.kt index 22832e34..84e01910 100644 --- a/core/src/main/kotlin/Formats/HtmlTemplateService.kt +++ b/core/src/main/kotlin/Formats/HtmlTemplateService.kt @@ -1,9 +1,9 @@ package org.jetbrains.dokka -import java.nio.file.Path +import java.io.File interface HtmlTemplateService { - fun appendHeader(to: StringBuilder, title: String?, basePath: Path) + fun appendHeader(to: StringBuilder, title: String?, basePath: File) fun appendFooter(to: StringBuilder) companion object { @@ -16,7 +16,7 @@ interface HtmlTemplateService { to.appendln("") to.appendln("") } - override fun appendHeader(to: StringBuilder, title: String?, relativePathToRoot: String) { + override fun appendHeader(to: StringBuilder, title: String?, basePath: File) { to.appendln("") to.appendln("") to.appendln("") diff --git a/core/src/main/kotlin/Formats/KotlinWebsiteHtmlFormatService.kt b/core/src/main/kotlin/Formats/KotlinWebsiteHtmlFormatService.kt index 208756c8..6ced75b5 100644 --- a/core/src/main/kotlin/Formats/KotlinWebsiteHtmlFormatService.kt +++ b/core/src/main/kotlin/Formats/KotlinWebsiteHtmlFormatService.kt @@ -4,13 +4,13 @@ import com.google.inject.Inject import com.google.inject.name.Named import org.jetbrains.dokka.Utilities.impliedPlatformsName import org.jetbrains.kotlin.utils.addToStdlib.ifNotEmpty -import java.nio.file.Path +import java.io.File object EmptyHtmlTemplateService : HtmlTemplateService { override fun appendFooter(to: StringBuilder) {} - override fun appendHeader(to: StringBuilder, title: String?, basePath: Path) {} + override fun appendHeader(to: StringBuilder, title: String?, basePath: File) {} } diff --git a/core/src/main/kotlin/Generation/FileGenerator.kt b/core/src/main/kotlin/Generation/FileGenerator.kt index 3193a5bc..9c7c65e6 100644 --- a/core/src/main/kotlin/Generation/FileGenerator.kt +++ b/core/src/main/kotlin/Generation/FileGenerator.kt @@ -14,6 +14,8 @@ class FileGenerator @Inject constructor(@Named("outputDir") val rootFile: File) @set:Inject(optional = true) lateinit var options: DocumentationOptions @set:Inject(optional = true) var packageListService: PackageListService? = null + override val root: File = rootFile + override fun location(node: DocumentationNode): FileLocation { return FileLocation(File(rootFile, relativePathToNode(node.path.map { it.name }, node.members.any())).appendExtension(formatService.extension)) } diff --git a/core/src/main/kotlin/Generation/Generator.kt b/core/src/main/kotlin/Generation/Generator.kt index 003386ef..23286e29 100644 --- a/core/src/main/kotlin/Generation/Generator.kt +++ b/core/src/main/kotlin/Generation/Generator.kt @@ -1,5 +1,7 @@ package org.jetbrains.dokka +import java.io.File + interface Generator { fun buildPages(nodes: Iterable) fun buildOutlines(nodes: Iterable) @@ -23,4 +25,5 @@ fun Generator.buildAll(node: DocumentationNode): Unit = buildAll(listOf(node)) interface NodeLocationAwareGenerator: Generator { fun location(node: DocumentationNode): Location + val root: File } \ No newline at end of file diff --git a/core/src/main/kotlin/Locations/LocationService.kt b/core/src/main/kotlin/Locations/LocationService.kt index 6b7e0511..8ea45dae 100644 --- a/core/src/main/kotlin/Locations/LocationService.kt +++ b/core/src/main/kotlin/Locations/LocationService.kt @@ -94,4 +94,10 @@ fun identifierToFilename(path: String): String { fun NodeLocationAwareGenerator.relativePathToLocation(owner: DocumentationNode, node: DocumentationNode): String { return location(owner).relativePathTo(location(node), null) +} + + +fun NodeLocationAwareGenerator.relativeToRoot(from: Location): File { + val file = File(from.path) + return file.relativeTo(root) } \ No newline at end of file -- cgit From 5e9dd421cd323c138486cf8b38b6ce7158bcca8a Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Sat, 2 Dec 2017 05:18:41 +0300 Subject: Bind NodeLocationAwareGenerator to Generator --- core/src/main/kotlin/Formats/FormatDescriptor.kt | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Formats/FormatDescriptor.kt b/core/src/main/kotlin/Formats/FormatDescriptor.kt index d3861b82..aa00df97 100644 --- a/core/src/main/kotlin/Formats/FormatDescriptor.kt +++ b/core/src/main/kotlin/Formats/FormatDescriptor.kt @@ -2,8 +2,6 @@ package org.jetbrains.dokka.Formats import com.google.inject.Binder import org.jetbrains.dokka.* -import org.jetbrains.dokka.Model.DescriptorSignatureProvider -import org.jetbrains.dokka.Samples.SampleProcessingService import org.jetbrains.dokka.Utilities.bind import org.jetbrains.dokka.Utilities.toOptional import org.jetbrains.dokka.Utilities.toType @@ -18,16 +16,17 @@ interface FormatDescriptorOutputComponent { fun configureOutput(binder: Binder) } -interface FormatDescriptor: FormatDescriptorAnalysisComponent, FormatDescriptorOutputComponent +interface FormatDescriptor : FormatDescriptorAnalysisComponent, FormatDescriptorOutputComponent abstract class FileGeneratorBasedFormatDescriptor : FormatDescriptor { override fun configureOutput(binder: Binder): Unit = with(binder) { + bind() toType NodeLocationAwareGenerator::class + bind() toOptional (outlineServiceClass) bind() toOptional formatServiceClass - bind() toType generatorServiceClass - //bind() toType generatorServiceClass + bind() toType generatorServiceClass bind() toOptional packageListServiceClass } -- cgit From 1eab9404b8ecbd51e5270af0cc0c9545e68f35f2 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Sat, 2 Dec 2017 05:20:21 +0300 Subject: Remove categories to prevent injection errors When not NodeLocationAwareGenerator used --- core/src/main/kotlin/Utilities/DokkaModules.kt | 13 ------------- core/src/main/resources/dokka/generator/default.properties | 2 -- core/src/main/resources/dokka/generator/javadoc.properties | 2 -- core/src/main/resources/dokka/language/java.properties | 1 - core/src/main/resources/dokka/language/kotlin.properties | 1 - core/src/main/resources/dokka/outline/yaml.properties | 1 - 6 files changed, 20 deletions(-) delete mode 100644 core/src/main/resources/dokka/generator/default.properties delete mode 100644 core/src/main/resources/dokka/generator/javadoc.properties delete mode 100644 core/src/main/resources/dokka/language/java.properties delete mode 100644 core/src/main/resources/dokka/language/kotlin.properties delete mode 100644 core/src/main/resources/dokka/outline/yaml.properties (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Utilities/DokkaModules.kt b/core/src/main/kotlin/Utilities/DokkaModules.kt index a2d720ef..fcc2f692 100644 --- a/core/src/main/kotlin/Utilities/DokkaModules.kt +++ b/core/src/main/kotlin/Utilities/DokkaModules.kt @@ -51,19 +51,6 @@ class DokkaOutputModule(val options: DocumentationOptions, binder.bind(LanguageService::class.java).to(KotlinLanguageService::class.java) binder.bind(File::class.java).annotatedWith(Names.named("outputDir")).toInstance(File(options.outputDir)) -// binder.bindNameAnnotated("singleFolder") -// binder.bindNameAnnotated("singleFolder") -// binder.bindNameAnnotated("folders") -// binder.bindNameAnnotated("folders") - - // defaults -// binder.bind(LocationService::class.java).to(FoldersLocationService::class.java) -// binder.bind(FileLocationService::class.java).to(FoldersLocationService::class.java) - - binder.registerCategory("outline") - binder.registerCategory("format") - binder.registerCategory("generator") - binder.bind().toInstance(options) binder.bind().toInstance(logger) binder.bind(StringListType).annotatedWith(Names.named(impliedPlatformsName)).toInstance(options.impliedPlatforms) diff --git a/core/src/main/resources/dokka/generator/default.properties b/core/src/main/resources/dokka/generator/default.properties deleted file mode 100644 index a4a16200..00000000 --- a/core/src/main/resources/dokka/generator/default.properties +++ /dev/null @@ -1,2 +0,0 @@ -class=org.jetbrains.dokka.FileGenerator -description=Default documentation generator \ No newline at end of file diff --git a/core/src/main/resources/dokka/generator/javadoc.properties b/core/src/main/resources/dokka/generator/javadoc.properties deleted file mode 100644 index 4075704f..00000000 --- a/core/src/main/resources/dokka/generator/javadoc.properties +++ /dev/null @@ -1,2 +0,0 @@ -class=org.jetbrains.dokka.javadoc.JavadocGenerator -description=Produces output via JDK javadoc tool \ No newline at end of file diff --git a/core/src/main/resources/dokka/language/java.properties b/core/src/main/resources/dokka/language/java.properties deleted file mode 100644 index ab42f532..00000000 --- a/core/src/main/resources/dokka/language/java.properties +++ /dev/null @@ -1 +0,0 @@ -class=org.jetbrains.dokka.JavaLanguageService \ No newline at end of file diff --git a/core/src/main/resources/dokka/language/kotlin.properties b/core/src/main/resources/dokka/language/kotlin.properties deleted file mode 100644 index 16092007..00000000 --- a/core/src/main/resources/dokka/language/kotlin.properties +++ /dev/null @@ -1 +0,0 @@ -class=org.jetbrains.dokka.KotlinLanguageService \ No newline at end of file diff --git a/core/src/main/resources/dokka/outline/yaml.properties b/core/src/main/resources/dokka/outline/yaml.properties deleted file mode 100644 index 7268af37..00000000 --- a/core/src/main/resources/dokka/outline/yaml.properties +++ /dev/null @@ -1 +0,0 @@ -class=org.jetbrains.dokka.YamlOutlineService \ No newline at end of file -- cgit From ff8948350406b085ca7feeb5d8aabd74b9eadf83 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Sat, 2 Dec 2017 05:21:10 +0300 Subject: Fix outline file names, fix incorrect placement of support files --- core/src/main/kotlin/Generation/FileGenerator.kt | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Generation/FileGenerator.kt b/core/src/main/kotlin/Generation/FileGenerator.kt index 9c7c65e6..ea34a269 100644 --- a/core/src/main/kotlin/Generation/FileGenerator.kt +++ b/core/src/main/kotlin/Generation/FileGenerator.kt @@ -17,11 +17,14 @@ class FileGenerator @Inject constructor(@Named("outputDir") val rootFile: File) override val root: File = rootFile override fun location(node: DocumentationNode): FileLocation { - return FileLocation(File(rootFile, relativePathToNode(node.path.map { it.name }, node.members.any())).appendExtension(formatService.extension)) + return locationWithoutExtension(node).let { it.copy(file = it.file.appendExtension(formatService.linkExtension)) } + } + + fun locationWithoutExtension(node: DocumentationNode): FileLocation { + return FileLocation(File(rootFile, relativePathToNode(node.path.map { it.name }, node.members.any()))) } override fun buildPages(nodes: Iterable) { - //val specificLocationService = locationService.withExtension(formatService.extension) for ((location, items) in nodes.groupBy { location(it) }) { val file = location.file @@ -41,7 +44,7 @@ class FileGenerator @Inject constructor(@Named("outputDir") val rootFile: File) override fun buildOutlines(nodes: Iterable) { val outlineService = this.outlineService ?: return - for ((location, items) in nodes.groupBy { location(it) }) { + for ((location, items) in nodes.groupBy { locationWithoutExtension(it) }) { val file = outlineService.getOutlineFileName(location) file.parentFile?.mkdirsOrFail() FileOutputStream(file).use { @@ -54,7 +57,7 @@ class FileGenerator @Inject constructor(@Named("outputDir") val rootFile: File) override fun buildSupportFiles() { formatService.enumerateSupportFiles { resource, targetPath -> - FileOutputStream(relativePathToNode(listOf(targetPath), false)).use { + FileOutputStream(File(root, relativePathToNode(listOf(targetPath), false))).use { javaClass.getResourceAsStream(resource).copyTo(it) } } -- cgit From d6d5df5bc04be5274446e9f37a3e52672083da36 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Sat, 2 Dec 2017 05:58:30 +0300 Subject: Add actual relativePathToNode function --- core/src/main/kotlin/Generation/FileGenerator.kt | 2 +- core/src/main/kotlin/Locations/LocationService.kt | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Generation/FileGenerator.kt b/core/src/main/kotlin/Generation/FileGenerator.kt index ea34a269..3d25e932 100644 --- a/core/src/main/kotlin/Generation/FileGenerator.kt +++ b/core/src/main/kotlin/Generation/FileGenerator.kt @@ -21,7 +21,7 @@ class FileGenerator @Inject constructor(@Named("outputDir") val rootFile: File) } fun locationWithoutExtension(node: DocumentationNode): FileLocation { - return FileLocation(File(rootFile, relativePathToNode(node.path.map { it.name }, node.members.any()))) + return FileLocation(File(rootFile, relativePathToNode(node))) } override fun buildPages(nodes: Iterable) { diff --git a/core/src/main/kotlin/Locations/LocationService.kt b/core/src/main/kotlin/Locations/LocationService.kt index 8ea45dae..e453baca 100644 --- a/core/src/main/kotlin/Locations/LocationService.kt +++ b/core/src/main/kotlin/Locations/LocationService.kt @@ -44,6 +44,7 @@ fun relativePathToNode(qualifiedName: List, hasMembers: Boolean): String } } +fun relativePathToNode(node: DocumentationNode) = relativePathToNode(node.path.map { it.name }, node.members.any()) // -- cgit From 14ba5834fa3fff98672166dd24c05bd7aa13dc2a Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Tue, 5 Dec 2017 15:42:20 +0300 Subject: Fix overriding of default analysis services --- core/src/main/kotlin/Formats/AnalysisComponents.kt | 10 +++++----- core/src/main/kotlin/Formats/JavaLayoutHtmlFormat.kt | 2 +- core/src/main/kotlin/Formats/StandardFormats.kt | 18 ++++++++++++------ core/src/main/kotlin/javadoc/dokka-adapters.kt | 9 +++++---- 4 files changed, 23 insertions(+), 16 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Formats/AnalysisComponents.kt b/core/src/main/kotlin/Formats/AnalysisComponents.kt index 97e1311e..c4d97dbb 100644 --- a/core/src/main/kotlin/Formats/AnalysisComponents.kt +++ b/core/src/main/kotlin/Formats/AnalysisComponents.kt @@ -12,14 +12,14 @@ import org.jetbrains.dokka.Utilities.toType import kotlin.reflect.KClass -interface FormatDescriptorAnalysisComponentProvider : FormatDescriptorAnalysisComponent { - +interface DefaultAnalysisComponentServices { val packageDocumentationBuilderClass: KClass val javaDocumentationBuilderClass: KClass val sampleProcessingService: KClass val descriptorSignatureProvider: KClass +} - +interface DefaultAnalysisComponent : FormatDescriptorAnalysisComponent, DefaultAnalysisComponentServices { override fun configureAnalysis(binder: Binder): Unit = with(binder) { bind() toType descriptorSignatureProvider bind() toType packageDocumentationBuilderClass @@ -29,7 +29,7 @@ interface FormatDescriptorAnalysisComponentProvider : FormatDescriptorAnalysisCo } -object KotlinAsJava: FormatDescriptorAnalysisComponentProvider { +object KotlinAsJava : DefaultAnalysisComponentServices { override val packageDocumentationBuilderClass = KotlinAsJavaDocumentationBuilder::class override val javaDocumentationBuilderClass = JavaPsiDocumentationBuilder::class override val sampleProcessingService = DefaultSampleProcessingService::class @@ -37,7 +37,7 @@ object KotlinAsJava: FormatDescriptorAnalysisComponentProvider { } -object KotlinAsKotlin: FormatDescriptorAnalysisComponentProvider { +object KotlinAsKotlin : DefaultAnalysisComponentServices { override val packageDocumentationBuilderClass = KotlinPackageDocumentationBuilder::class override val javaDocumentationBuilderClass = KotlinJavaDocumentationBuilder::class override val sampleProcessingService = DefaultSampleProcessingService::class diff --git a/core/src/main/kotlin/Formats/JavaLayoutHtmlFormat.kt b/core/src/main/kotlin/Formats/JavaLayoutHtmlFormat.kt index 9fb72e37..f73cd23e 100644 --- a/core/src/main/kotlin/Formats/JavaLayoutHtmlFormat.kt +++ b/core/src/main/kotlin/Formats/JavaLayoutHtmlFormat.kt @@ -13,7 +13,7 @@ import org.jetbrains.dokka.Utilities.toType import java.io.File -class JavaLayoutHtmlFormatDescriptor : FormatDescriptor, FormatDescriptorAnalysisComponentProvider { +class JavaLayoutHtmlFormatDescriptor : FormatDescriptor, DefaultAnalysisComponent { override val packageDocumentationBuilderClass = KotlinPackageDocumentationBuilder::class override val javaDocumentationBuilderClass = KotlinJavaDocumentationBuilder::class override val sampleProcessingService = DefaultSampleProcessingService::class diff --git a/core/src/main/kotlin/Formats/StandardFormats.kt b/core/src/main/kotlin/Formats/StandardFormats.kt index 9de667ab..71af1991 100644 --- a/core/src/main/kotlin/Formats/StandardFormats.kt +++ b/core/src/main/kotlin/Formats/StandardFormats.kt @@ -1,19 +1,21 @@ package org.jetbrains.dokka.Formats import com.google.inject.Binder -import com.google.inject.Provider import org.jetbrains.dokka.* import org.jetbrains.dokka.Samples.KotlinWebsiteSampleProcessingService import org.jetbrains.dokka.Utilities.bind import kotlin.reflect.KClass -abstract class KotlinFormatDescriptorBase : FileGeneratorBasedFormatDescriptor(), FormatDescriptorAnalysisComponentProvider by KotlinAsKotlin { +abstract class KotlinFormatDescriptorBase + : FileGeneratorBasedFormatDescriptor(), + DefaultAnalysisComponent, + DefaultAnalysisComponentServices by KotlinAsKotlin { override val generatorServiceClass = FileGenerator::class override val outlineServiceClass: KClass? = null override val packageListServiceClass: KClass? = DefaultPackageListService::class } -abstract class HtmlFormatDescriptorBase : FileGeneratorBasedFormatDescriptor() { +abstract class HtmlFormatDescriptorBase : FileGeneratorBasedFormatDescriptor(), DefaultAnalysisComponent { override val formatServiceClass = HtmlFormatService::class override val outlineServiceClass = HtmlFormatService::class override val generatorServiceClass = FileGenerator::class @@ -21,13 +23,13 @@ abstract class HtmlFormatDescriptorBase : FileGeneratorBasedFormatDescriptor() { override fun configureOutput(binder: Binder): Unit = with(binder) { super.configureOutput(binder) - bind().toProvider(Provider { HtmlTemplateService.default("style.css") }) + bind().toProvider { HtmlTemplateService.default("style.css") } } } -class HtmlFormatDescriptor : HtmlFormatDescriptorBase(), FormatDescriptorAnalysisComponent by KotlinAsKotlin +class HtmlFormatDescriptor : HtmlFormatDescriptorBase(), DefaultAnalysisComponentServices by KotlinAsKotlin -class HtmlAsJavaFormatDescriptor : HtmlFormatDescriptorBase(), FormatDescriptorAnalysisComponent by KotlinAsJava +class HtmlAsJavaFormatDescriptor : HtmlFormatDescriptorBase(), DefaultAnalysisComponentServices by KotlinAsJava class KotlinWebsiteFormatDescriptor : KotlinFormatDescriptorBase() { override val formatServiceClass = KotlinWebsiteFormatService::class @@ -45,6 +47,10 @@ class KotlinWebsiteHtmlFormatDescriptor : KotlinFormatDescriptorBase() { override val sampleProcessingService = KotlinWebsiteSampleProcessingService::class override val outlineServiceClass = YamlOutlineService::class + override fun configureAnalysis(binder: Binder) { + super.configureAnalysis(binder) + } + override fun configureOutput(binder: Binder) = with(binder) { super.configureOutput(binder) bind().toInstance(EmptyHtmlTemplateService) diff --git a/core/src/main/kotlin/javadoc/dokka-adapters.kt b/core/src/main/kotlin/javadoc/dokka-adapters.kt index bed211f6..4676db18 100644 --- a/core/src/main/kotlin/javadoc/dokka-adapters.kt +++ b/core/src/main/kotlin/javadoc/dokka-adapters.kt @@ -4,9 +4,7 @@ import com.google.inject.Binder import com.google.inject.Inject import com.sun.tools.doclets.formats.html.HtmlDoclet import org.jetbrains.dokka.* -import org.jetbrains.dokka.Formats.FormatDescriptor -import org.jetbrains.dokka.Formats.FormatDescriptorAnalysisComponent -import org.jetbrains.dokka.Formats.KotlinAsJava +import org.jetbrains.dokka.Formats.* import org.jetbrains.dokka.Utilities.bind import org.jetbrains.dokka.Utilities.toType @@ -31,7 +29,10 @@ class JavadocGenerator @Inject constructor(val options: DocumentationOptions, va } } -class JavadocFormatDescriptor : FormatDescriptor, FormatDescriptorAnalysisComponent by KotlinAsJava { +class JavadocFormatDescriptor : + FormatDescriptor, + DefaultAnalysisComponent, + DefaultAnalysisComponentServices by KotlinAsJava { override fun configureOutput(binder: Binder): Unit = with(binder) { bind() toType JavadocGenerator::class -- cgit From 3683c18f3ca302d7afb8f5076290c6bd44f91ce5 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Tue, 5 Dec 2017 18:17:23 +0300 Subject: Fix PackageListService to use NodeLocationAwareGenerator for links --- core/src/main/kotlin/Formats/PackageListService.kt | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Formats/PackageListService.kt b/core/src/main/kotlin/Formats/PackageListService.kt index be50fac4..7b68098e 100644 --- a/core/src/main/kotlin/Formats/PackageListService.kt +++ b/core/src/main/kotlin/Formats/PackageListService.kt @@ -8,8 +8,9 @@ interface PackageListService { } class DefaultPackageListService @Inject constructor( - val generator: FileGenerator, - val formatService: FormatService) : PackageListService { + val generator: NodeLocationAwareGenerator, + val formatService: FormatService +) : PackageListService { override fun formatPackageList(module: DocumentationModule): String { val packages = mutableSetOf() -- cgit From 214e16e07d93b3565c433ed67b78796e80f43ec5 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Tue, 5 Dec 2017 18:25:08 +0300 Subject: Tidy around --- core/src/main/kotlin/Formats/StandardFormats.kt | 4 - .../kotlin/Locations/FoldersLocationService.kt | 20 ---- core/src/main/kotlin/Locations/Location.kt | 59 ++++++++++++ core/src/main/kotlin/Locations/LocationService.kt | 104 --------------------- .../Locations/SingleFolderLocationService.kt | 20 ---- core/src/main/kotlin/Utilities/DokkaModules.kt | 2 - 6 files changed, 59 insertions(+), 150 deletions(-) delete mode 100644 core/src/main/kotlin/Locations/FoldersLocationService.kt create mode 100644 core/src/main/kotlin/Locations/Location.kt delete mode 100644 core/src/main/kotlin/Locations/LocationService.kt delete mode 100644 core/src/main/kotlin/Locations/SingleFolderLocationService.kt (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Formats/StandardFormats.kt b/core/src/main/kotlin/Formats/StandardFormats.kt index 71af1991..dd67ac97 100644 --- a/core/src/main/kotlin/Formats/StandardFormats.kt +++ b/core/src/main/kotlin/Formats/StandardFormats.kt @@ -47,10 +47,6 @@ class KotlinWebsiteHtmlFormatDescriptor : KotlinFormatDescriptorBase() { override val sampleProcessingService = KotlinWebsiteSampleProcessingService::class override val outlineServiceClass = YamlOutlineService::class - override fun configureAnalysis(binder: Binder) { - super.configureAnalysis(binder) - } - override fun configureOutput(binder: Binder) = with(binder) { super.configureOutput(binder) bind().toInstance(EmptyHtmlTemplateService) diff --git a/core/src/main/kotlin/Locations/FoldersLocationService.kt b/core/src/main/kotlin/Locations/FoldersLocationService.kt deleted file mode 100644 index ae5301e7..00000000 --- a/core/src/main/kotlin/Locations/FoldersLocationService.kt +++ /dev/null @@ -1,20 +0,0 @@ -package org.jetbrains.dokka - -import com.google.inject.Inject -import com.google.inject.name.Named -import java.io.File -// -//class FoldersLocationService @Inject constructor(@Named("outputDir") val rootFile: File, val extension: String) : FileLocationService { -// constructor(root: String): this(File(root), "") -// -// override val root: Location -// get() = FileLocation(rootFile) -// -// override fun withExtension(newExtension: String): FileLocationService { -// return if (extension.isEmpty()) FoldersLocationService(rootFile, newExtension) else this -// } -// -// override fun location(qualifiedName: List, hasMembers: Boolean): FileLocation { -// return FileLocation(File(rootFile, relativePathToNode(qualifiedName, hasMembers)).appendExtension(extension)) -// } -//} diff --git a/core/src/main/kotlin/Locations/Location.kt b/core/src/main/kotlin/Locations/Location.kt new file mode 100644 index 00000000..17538ff5 --- /dev/null +++ b/core/src/main/kotlin/Locations/Location.kt @@ -0,0 +1,59 @@ +package org.jetbrains.dokka + +import java.io.File + +interface Location { + val path: String get + fun relativePathTo(other: Location, anchor: String? = null): String +} + +/** + * Represents locations in the documentation in the form of [path](File). + * + * $file: [File] for this location + * $path: [String] representing path of this location + */ +data class FileLocation(val file: File): Location { + override val path : String + get() = file.path + + override fun relativePathTo(other: Location, anchor: String?): String { + if (other !is FileLocation) { + throw IllegalArgumentException("$other is not a FileLocation") + } + if (file.path.substringBeforeLast(".") == other.file.path.substringBeforeLast(".") && anchor == null) { + return "./${file.name}" + } + val ownerFolder = file.parentFile!! + val relativePath = ownerFolder.toPath().relativize(other.file.toPath()).toString().replace(File.separatorChar, '/') + return if (anchor == null) relativePath else relativePath + "#" + anchor + } +} + + +fun relativePathToNode(qualifiedName: List, hasMembers: Boolean): String { + val parts = qualifiedName.map { identifierToFilename(it) }.filterNot { it.isEmpty() } + return if (!hasMembers) { + // leaf node, use file in owner's folder + parts.joinToString("/") + } else { + parts.joinToString("/") + (if (parts.none()) "" else "/") + "index" + } +} + +fun relativePathToNode(node: DocumentationNode) = relativePathToNode(node.path.map { it.name }, node.members.any()) + +fun identifierToFilename(path: String): String { + val escaped = path.replace('<', '-').replace('>', '-') + val lowercase = escaped.replace("[A-Z]".toRegex()) { matchResult -> "-" + matchResult.value.toLowerCase() } + return if (lowercase == "index") "--index--" else lowercase +} + +fun NodeLocationAwareGenerator.relativePathToLocation(owner: DocumentationNode, node: DocumentationNode): String { + return location(owner).relativePathTo(location(node), null) +} + +fun NodeLocationAwareGenerator.relativeToRoot(from: Location): File { + val file = File(from.path) + return file.relativeTo(root) +} \ No newline at end of file diff --git a/core/src/main/kotlin/Locations/LocationService.kt b/core/src/main/kotlin/Locations/LocationService.kt deleted file mode 100644 index e453baca..00000000 --- a/core/src/main/kotlin/Locations/LocationService.kt +++ /dev/null @@ -1,104 +0,0 @@ -package org.jetbrains.dokka - -import java.io.File - -interface Location { - val path: String get - fun relativePathTo(other: Location, anchor: String? = null): String -} - -/** - * Represents locations in the documentation in the form of [path](File). - * - * Locations are provided by [LocationService.location] function. - * - * $file: [File] for this location - * $path: [String] representing path of this location - */ -data class FileLocation(val file: File): Location { - override val path : String - get() = file.path - - override fun relativePathTo(other: Location, anchor: String?): String { - if (other !is FileLocation) { - throw IllegalArgumentException("$other is not a FileLocation") - } - if (file.path.substringBeforeLast(".") == other.file.path.substringBeforeLast(".") && anchor == null) { - return "./${file.name}" - } - val ownerFolder = file.parentFile!! - val relativePath = ownerFolder.toPath().relativize(other.file.toPath()).toString().replace(File.separatorChar, '/') - return if (anchor == null) relativePath else relativePath + "#" + anchor - } -} - - - -fun relativePathToNode(qualifiedName: List, hasMembers: Boolean): String { - val parts = qualifiedName.map { identifierToFilename(it) }.filterNot { it.isEmpty() } - return if (!hasMembers) { - // leaf node, use file in owner's folder - parts.joinToString("/") - } else { - parts.joinToString("/") + (if (parts.none()) "" else "/") + "index" - } -} - -fun relativePathToNode(node: DocumentationNode) = relativePathToNode(node.path.map { it.name }, node.members.any()) - - -// -///** -// * Provides means of retrieving locations for [DocumentationNode](documentation nodes) -// * -// * `LocationService` determines where documentation for particular node should be generated -// * -// * * [FoldersLocationService] – represent packages and types as folders, members as files in those folders. -// * * [SingleFolderLocationService] – all documentation is generated into single folder using fully qualified names -// * for file names. -// */ -//interface LocationService { -// fun withExtension(newExtension: String) = this -// -// fun location(node: DocumentationNode): Location = location(node.path.map { it.name }, node.members.any()) -// -// /** -// * Calculates a location corresponding to the specified [qualifiedName]. -// * @param hasMembers if true, the node for which the location is calculated has member nodes. -// */ -// fun location(qualifiedName: List, hasMembers: Boolean): Location -// -// val root: Location -//} -// -// -//interface FileLocationService: LocationService { -// override fun withExtension(newExtension: String): FileLocationService = this -// -// override fun location(node: DocumentationNode): FileLocation = location(node.path.map { it.name }, node.members.any()) -// override fun location(qualifiedName: List, hasMembers: Boolean): FileLocation -//} - -fun identifierToFilename(path: String): String { - val escaped = path.replace('<', '-').replace('>', '-') - val lowercase = escaped.replace("[A-Z]".toRegex()) { matchResult -> "-" + matchResult.value.toLowerCase() } - return if (lowercase == "index") "--index--" else lowercase -} - -///** -// * Returns relative location between two nodes. Used for relative links in documentation. -// */ -//fun LocationService.relativePathToLocation(owner: DocumentationNode, node: DocumentationNode): String { -// return location(owner).relativePathTo(location(node), null) -//} - - -fun NodeLocationAwareGenerator.relativePathToLocation(owner: DocumentationNode, node: DocumentationNode): String { - return location(owner).relativePathTo(location(node), null) -} - - -fun NodeLocationAwareGenerator.relativeToRoot(from: Location): File { - val file = File(from.path) - return file.relativeTo(root) -} \ No newline at end of file diff --git a/core/src/main/kotlin/Locations/SingleFolderLocationService.kt b/core/src/main/kotlin/Locations/SingleFolderLocationService.kt deleted file mode 100644 index 25cf6f8e..00000000 --- a/core/src/main/kotlin/Locations/SingleFolderLocationService.kt +++ /dev/null @@ -1,20 +0,0 @@ -package org.jetbrains.dokka - -import com.google.inject.Inject -import com.google.inject.name.Named -import java.io.File -// -//class SingleFolderLocationService @Inject constructor(@Named("outputDir") val rootFile: File, val extension: String) : FileLocationService { -// constructor(root: String): this(File(root), "") -// -// override fun withExtension(newExtension: String): FileLocationService = -// SingleFolderLocationService(rootFile, newExtension) -// -// override fun location(qualifiedName: List, hasMembers: Boolean): FileLocation { -// val filename = qualifiedName.map { identifierToFilename(it) }.joinToString("-") -// return FileLocation(File(rootFile, filename).appendExtension(extension)) -// } -// -// override val root: Location -// get() = FileLocation(rootFile) -//} \ No newline at end of file diff --git a/core/src/main/kotlin/Utilities/DokkaModules.kt b/core/src/main/kotlin/Utilities/DokkaModules.kt index fcc2f692..6b5e153e 100644 --- a/core/src/main/kotlin/Utilities/DokkaModules.kt +++ b/core/src/main/kotlin/Utilities/DokkaModules.kt @@ -24,8 +24,6 @@ class DokkaAnalysisModule(val environment: AnalysisEnvironment, override fun configure(binder: Binder) { binder.bind().toInstance(logger) - binder.registerCategory("language") - val coreEnvironment = environment.createCoreEnvironment() binder.bind().toInstance(coreEnvironment) -- cgit From 6ef35accd16533c84be5d0164739b146cfb55b73 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Mon, 11 Dec 2017 16:01:51 +0300 Subject: Fix optional binding --- core/src/main/kotlin/Formats/FormatDescriptor.kt | 10 ++++++---- core/src/main/kotlin/Utilities/DokkaModules.kt | 6 ++++-- 2 files changed, 10 insertions(+), 6 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Formats/FormatDescriptor.kt b/core/src/main/kotlin/Formats/FormatDescriptor.kt index aa00df97..a1120c00 100644 --- a/core/src/main/kotlin/Formats/FormatDescriptor.kt +++ b/core/src/main/kotlin/Formats/FormatDescriptor.kt @@ -3,6 +3,7 @@ package org.jetbrains.dokka.Formats import com.google.inject.Binder import org.jetbrains.dokka.* import org.jetbrains.dokka.Utilities.bind +import org.jetbrains.dokka.Utilities.lazyBind import org.jetbrains.dokka.Utilities.toOptional import org.jetbrains.dokka.Utilities.toType import kotlin.reflect.KClass @@ -23,11 +24,12 @@ abstract class FileGeneratorBasedFormatDescriptor : FormatDescriptor { override fun configureOutput(binder: Binder): Unit = with(binder) { bind() toType NodeLocationAwareGenerator::class - - bind() toOptional (outlineServiceClass) - bind() toOptional formatServiceClass bind() toType generatorServiceClass - bind() toOptional packageListServiceClass + + + lazyBind() toOptional (outlineServiceClass) + lazyBind() toOptional formatServiceClass + lazyBind() toOptional packageListServiceClass } abstract val formatServiceClass: KClass? diff --git a/core/src/main/kotlin/Utilities/DokkaModules.kt b/core/src/main/kotlin/Utilities/DokkaModules.kt index 6b5e153e..763e29a9 100644 --- a/core/src/main/kotlin/Utilities/DokkaModules.kt +++ b/core/src/main/kotlin/Utilities/DokkaModules.kt @@ -73,7 +73,9 @@ private inline fun Binder.bindNameAnnotat inline fun Binder.bind(): AnnotatedBindingBuilder = bind(T::class.java) -inline infix fun > AnnotatedBindingBuilder.toOptional(kClass: TKClass?) = - kClass?.let { to(it.java) } +inline fun Binder.lazyBind(): Lazy> = lazy { bind(T::class.java) } + +inline infix fun > Lazy>.toOptional(kClass: TKClass?) = + kClass?.let { value toType it } inline infix fun > AnnotatedBindingBuilder.toType(kClass: TKClass) = to(kClass.java) -- cgit From 799e3713f8b6a80b53a1b9f28a86844ed30b71ae Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Mon, 11 Dec 2017 18:28:08 +0300 Subject: Fix file extensions when FormatService.extension != linkExtension --- core/src/main/kotlin/Generation/FileGenerator.kt | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Generation/FileGenerator.kt b/core/src/main/kotlin/Generation/FileGenerator.kt index 3d25e932..bc08e180 100644 --- a/core/src/main/kotlin/Generation/FileGenerator.kt +++ b/core/src/main/kotlin/Generation/FileGenerator.kt @@ -2,6 +2,7 @@ package org.jetbrains.dokka import com.google.inject.Inject import com.google.inject.name.Named +import org.jetbrains.kotlin.utils.fileUtils.withReplacedExtensionOrNull import java.io.File import java.io.FileOutputStream import java.io.IOException @@ -17,22 +18,26 @@ class FileGenerator @Inject constructor(@Named("outputDir") val rootFile: File) override val root: File = rootFile override fun location(node: DocumentationNode): FileLocation { - return locationWithoutExtension(node).let { it.copy(file = it.file.appendExtension(formatService.linkExtension)) } + return FileLocation(fileForNode(node, formatService.linkExtension)) + } + + private fun fileForNode(node: DocumentationNode, extension: String = ""): File { + return File(root, relativePathToNode(node)).appendExtension(extension) } fun locationWithoutExtension(node: DocumentationNode): FileLocation { - return FileLocation(File(rootFile, relativePathToNode(node))) + return FileLocation(fileForNode(node)) } override fun buildPages(nodes: Iterable) { - for ((location, items) in nodes.groupBy { location(it) }) { - val file = location.file + for ((file, items) in nodes.groupBy { fileForNode(it, formatService.extension) }) { + file.parentFile?.mkdirsOrFail() try { FileOutputStream(file).use { OutputStreamWriter(it, Charsets.UTF_8).use { - it.write(formatService.format(location, items)) + it.write(formatService.format(location(items.first()), items)) } } } catch (e: Throwable) { -- cgit From dbd4774ffae19ff4d52cd21c7cb3906cdc3e0b5c Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Fri, 15 Dec 2017 01:00:32 +0300 Subject: Normalize file path's when using as URI --- core/src/main/kotlin/Formats/HtmlTemplateService.kt | 2 +- core/src/main/kotlin/Locations/Location.kt | 10 ++++++---- core/src/test/kotlin/format/FileGeneratorTestCase.kt | 7 ++----- 3 files changed, 9 insertions(+), 10 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Formats/HtmlTemplateService.kt b/core/src/main/kotlin/Formats/HtmlTemplateService.kt index 84e01910..a65a7b18 100644 --- a/core/src/main/kotlin/Formats/HtmlTemplateService.kt +++ b/core/src/main/kotlin/Formats/HtmlTemplateService.kt @@ -24,7 +24,7 @@ interface HtmlTemplateService { to.appendln("$title") } if (css != null) { - val cssPath = basePath.resolve(css) + val cssPath = basePath.resolve(css).toUnixString() to.appendln("") } to.appendln("") diff --git a/core/src/main/kotlin/Locations/Location.kt b/core/src/main/kotlin/Locations/Location.kt index 17538ff5..0e6572d9 100644 --- a/core/src/main/kotlin/Locations/Location.kt +++ b/core/src/main/kotlin/Locations/Location.kt @@ -13,8 +13,8 @@ interface Location { * $file: [File] for this location * $path: [String] representing path of this location */ -data class FileLocation(val file: File): Location { - override val path : String +data class FileLocation(val file: File) : Location { + override val path: String get() = file.path override fun relativePathTo(other: Location, anchor: String?): String { @@ -30,7 +30,6 @@ data class FileLocation(val file: File): Location { } } - fun relativePathToNode(qualifiedName: List, hasMembers: Boolean): String { val parts = qualifiedName.map { identifierToFilename(it) }.filterNot { it.isEmpty() } return if (!hasMembers) { @@ -41,6 +40,7 @@ fun relativePathToNode(qualifiedName: List, hasMembers: Boolean): String } } + fun relativePathToNode(node: DocumentationNode) = relativePathToNode(node.path.map { it.name }, node.members.any()) fun identifierToFilename(path: String): String { @@ -56,4 +56,6 @@ fun NodeLocationAwareGenerator.relativePathToLocation(owner: DocumentationNode, fun NodeLocationAwareGenerator.relativeToRoot(from: Location): File { val file = File(from.path) return file.relativeTo(root) -} \ No newline at end of file +} + +fun File.toUnixString() = toString().replace(File.separatorChar, '/') diff --git a/core/src/test/kotlin/format/FileGeneratorTestCase.kt b/core/src/test/kotlin/format/FileGeneratorTestCase.kt index 644d5baa..948426ea 100644 --- a/core/src/test/kotlin/format/FileGeneratorTestCase.kt +++ b/core/src/test/kotlin/format/FileGeneratorTestCase.kt @@ -1,9 +1,6 @@ package org.jetbrains.dokka.tests -import org.jetbrains.dokka.DocumentationNode -import org.jetbrains.dokka.FileGenerator -import org.jetbrains.dokka.FormatService -import org.jetbrains.dokka.relativeToRoot +import org.jetbrains.dokka.* import org.junit.Before import org.junit.Rule import org.junit.rules.TemporaryFolder @@ -30,7 +27,7 @@ abstract class FileGeneratorTestCase { if (sb.isNotBlank() && !sb.endsWith('\n')) { sb.appendln() } - sb.appendln("") + sb.appendln("") } sb.append(loc.file.readText()) } -- cgit From ec3d364e49268f1dfbc7619245ec36a49e780169 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Fri, 15 Dec 2017 22:01:02 +0300 Subject: Don't force bind LanguageService to KotlinLanguageService --- core/src/main/kotlin/Utilities/DokkaModules.kt | 1 - 1 file changed, 1 deletion(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Utilities/DokkaModules.kt b/core/src/main/kotlin/Utilities/DokkaModules.kt index 763e29a9..36704918 100644 --- a/core/src/main/kotlin/Utilities/DokkaModules.kt +++ b/core/src/main/kotlin/Utilities/DokkaModules.kt @@ -46,7 +46,6 @@ object StringListType : TypeLiteral<@JvmSuppressWildcards List>() class DokkaOutputModule(val options: DocumentationOptions, val logger: DokkaLogger) : Module { override fun configure(binder: Binder) { - binder.bind(LanguageService::class.java).to(KotlinLanguageService::class.java) binder.bind(File::class.java).annotatedWith(Names.named("outputDir")).toInstance(File(options.outputDir)) binder.bind().toInstance(options) -- cgit From 3eb23215edcd1cf92966f8d39afe754fef0c7a19 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Wed, 21 Feb 2018 11:51:06 +0300 Subject: Update bundled kotlin compiler --- build.gradle | 2 + core/build.gradle | 2 +- .../main/kotlin/Analysis/AnalysisEnvironment.kt | 53 ++++++++++++++++++++-- .../main/kotlin/Analysis/CoreKotlinCacheService.kt | 30 ++++++++++++ .../main/kotlin/Analysis/CoreProjectFileIndex.kt | 30 ++++++------ .../kotlin/Kotlin/DescriptorDocumentationParser.kt | 2 +- .../src/main/kotlin/Kotlin/DocumentationBuilder.kt | 10 ++++ gradle.properties | 4 +- 8 files changed, 111 insertions(+), 22 deletions(-) create mode 100644 core/src/main/kotlin/Analysis/CoreKotlinCacheService.kt (limited to 'core/src/main/kotlin') diff --git a/build.gradle b/build.gradle index ee76c9cb..f1748259 100644 --- a/build.gradle +++ b/build.gradle @@ -6,6 +6,7 @@ allprojects { def repo = { artifactPattern("https://teamcity.jetbrains.com/guestAuth/repository/download/Kotlin_dev_CompilerAllPlugins/[revision]/internal/[module](.[ext])") + artifactPattern("https://teamcity.jetbrains.com/guestAuth/repository/download/IntelliJMarkdownParser_Build/[revision]/([module]_[ext]/)[module](.[ext])") } buildscript { @@ -70,6 +71,7 @@ task wrapper(type: Wrapper) { def versions = DependenciesVersionGetter.getVersions(project, bundled_kotlin_compiler_version) ext.ideaVersion = versions["idea.build.id"] +ext.markdownVersion = versions["markdown.build.id"].replace("%20", " ") configurations { ideaIC diff --git a/core/build.gradle b/core/build.gradle index a8f0f275..1a93bb48 100644 --- a/core/build.gradle +++ b/core/build.gradle @@ -29,7 +29,7 @@ dependencies { compile "org.jetbrains.kotlin:kotlin-script-runtime:$bundled_kotlin_compiler_version" compile "teamcity:kotlin-ide-common:$bundled_kotlin_compiler_version" - compile "teamcity:markdown:$bundled_kotlin_compiler_version" + compile "teamcity:markdown:$markdownVersion" compile intellijCoreAnalysis() diff --git a/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt b/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt index 56249ac4..5522d4f0 100644 --- a/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt +++ b/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt @@ -1,5 +1,6 @@ package org.jetbrains.dokka +import com.google.common.collect.ImmutableMap import com.intellij.core.CoreApplicationEnvironment import com.intellij.core.CoreModuleManager import com.intellij.mock.MockComponentManager @@ -17,6 +18,7 @@ import com.intellij.psi.PsiElement import com.intellij.psi.search.GlobalSearchScope import com.intellij.util.io.URLUtil import org.jetbrains.kotlin.analyzer.* +import org.jetbrains.kotlin.caches.resolve.KotlinCacheService import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys import org.jetbrains.kotlin.cli.common.messages.MessageCollector import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles @@ -34,16 +36,19 @@ import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.load.java.structure.impl.JavaClassImpl import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.platform.JvmBuiltIns -import org.jetbrains.kotlin.psi.KtDeclaration -import org.jetbrains.kotlin.psi.KtElement -import org.jetbrains.kotlin.psi.KtFile +import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext +import org.jetbrains.kotlin.resolve.BindingTrace import org.jetbrains.kotlin.resolve.CompilerEnvironment +import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics import org.jetbrains.kotlin.resolve.jvm.JvmAnalyzerFacade import org.jetbrains.kotlin.resolve.jvm.JvmPlatformParameters import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatform import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.lazy.ResolveSession +import org.jetbrains.kotlin.types.KotlinType +import org.jetbrains.kotlin.util.slicedMap.ReadOnlySlice +import org.jetbrains.kotlin.util.slicedMap.WritableSlice import java.io.File /** @@ -158,7 +163,11 @@ class AnalysisEnvironment(val messageCollector: MessageCollector) : Disposable { val resolverForModule = resolverForProject.resolverForModule(module) val moduleDescriptor = resolverForProject.descriptorForModule(module) builtIns.initialize(moduleDescriptor, true) - return DokkaResolutionFacade(environment.project, moduleDescriptor, resolverForModule) + val created = DokkaResolutionFacade(environment.project, moduleDescriptor, resolverForModule) + val projectComponentManager = environment.project as MockComponentManager + projectComponentManager.registerService(KotlinCacheService::class.java, CoreKotlinCacheService(created)) + + return created } fun loadLanguageVersionSettings(languageVersionString: String?, apiVersionString: String?) { @@ -247,6 +256,42 @@ class DokkaResolutionFacade(override val project: Project, val resolveSession: ResolveSession get() = getFrontendService(ResolveSession::class.java) override fun analyze(element: KtElement, bodyResolveMode: BodyResolveMode): BindingContext { + if (element is KtDeclaration) { + val descriptor = resolveToDescriptor(element) + return object : BindingContext { + override fun getKeys(p0: WritableSlice?): Collection { + throw UnsupportedOperationException() + } + + override fun getType(p0: KtExpression): KotlinType? { + throw UnsupportedOperationException() + } + + override fun get(slice: ReadOnlySlice?, key: K): V? { + if (key != element) { + throw UnsupportedOperationException() + } + return when { + slice == BindingContext.DECLARATION_TO_DESCRIPTOR -> descriptor as V + slice == BindingContext.PRIMARY_CONSTRUCTOR_PARAMETER && (element as KtParameter).hasValOrVar() -> descriptor as V + else -> null + } + } + + override fun getDiagnostics(): Diagnostics { + throw UnsupportedOperationException() + } + + override fun addOwnDataTo(p0: BindingTrace, p1: Boolean) { + throw UnsupportedOperationException() + } + + override fun getSliceContents(p0: ReadOnlySlice): ImmutableMap { + throw UnsupportedOperationException() + } + + } + } throw UnsupportedOperationException() } diff --git a/core/src/main/kotlin/Analysis/CoreKotlinCacheService.kt b/core/src/main/kotlin/Analysis/CoreKotlinCacheService.kt new file mode 100644 index 00000000..31b8ffc7 --- /dev/null +++ b/core/src/main/kotlin/Analysis/CoreKotlinCacheService.kt @@ -0,0 +1,30 @@ +package org.jetbrains.dokka + +import com.intellij.psi.PsiFile +import org.jetbrains.kotlin.analyzer.ModuleInfo +import org.jetbrains.kotlin.caches.resolve.KotlinCacheService +import org.jetbrains.kotlin.idea.resolve.ResolutionFacade +import org.jetbrains.kotlin.psi.KtElement +import org.jetbrains.kotlin.resolve.TargetPlatform +import org.jetbrains.kotlin.resolve.diagnostics.KotlinSuppressCache + + +class CoreKotlinCacheService(private val resolutionFacade: DokkaResolutionFacade) : KotlinCacheService { + override fun getResolutionFacade(elements: List): ResolutionFacade { + return resolutionFacade + } + + override fun getResolutionFacadeByFile(file: PsiFile, platform: TargetPlatform): ResolutionFacade { + return resolutionFacade + } + + override fun getResolutionFacadeByModuleInfo(moduleInfo: ModuleInfo, platform: TargetPlatform): ResolutionFacade? { + return resolutionFacade + } + + override fun getSuppressionCache(): KotlinSuppressCache { + throw UnsupportedOperationException() + } + +} + diff --git a/core/src/main/kotlin/Analysis/CoreProjectFileIndex.kt b/core/src/main/kotlin/Analysis/CoreProjectFileIndex.kt index 2f2f94b3..4f6a7c76 100644 --- a/core/src/main/kotlin/Analysis/CoreProjectFileIndex.kt +++ b/core/src/main/kotlin/Analysis/CoreProjectFileIndex.kt @@ -228,24 +228,26 @@ class CoreProjectFileIndex(private val project: Project, contentRoots: List { + override fun getFiles(p0: OrderRootType): Array { throw UnsupportedOperationException() } - override fun getPresentableName(): String { + override fun getUrls(p0: OrderRootType): Array { throw UnsupportedOperationException() } - override fun getUrls(p0: OrderRootType?): Array { + override fun accept(p0: RootPolicy, p1: R?): R { throw UnsupportedOperationException() } - override fun getOwnerModule(): Module = module - override fun accept(p0: RootPolicy?, p1: R?): R { + override fun getPresentableName(): String { throw UnsupportedOperationException() } + override fun getOwnerModule(): Module = module + + override fun isValid(): Boolean { throw UnsupportedOperationException() } @@ -262,29 +264,29 @@ class CoreProjectFileIndex(private val project: Project, contentRoots: List { throw UnsupportedOperationException() } - override fun getJdk(): Sdk = sdk - - override fun getFiles(p0: OrderRootType?): Array { + override fun getUrls(p0: OrderRootType): Array { throw UnsupportedOperationException() } - override fun getPresentableName(): String { + override fun accept(p0: RootPolicy, p1: R?): R { throw UnsupportedOperationException() } - override fun getUrls(p0: OrderRootType?): Array { + override fun getJdkName(): String? { throw UnsupportedOperationException() } - override fun getOwnerModule(): Module { + override fun getJdk(): Sdk = sdk + + override fun getPresentableName(): String { throw UnsupportedOperationException() } - override fun accept(p0: RootPolicy?, p1: R?): R { + override fun getOwnerModule(): Module { throw UnsupportedOperationException() } @@ -358,7 +360,7 @@ class CoreProjectFileIndex(private val project: Project, contentRoots: List getModuleExtension(p0: Class?): T { + override fun getModuleExtension(p0: Class): T { throw UnsupportedOperationException() } diff --git a/core/src/main/kotlin/Kotlin/DescriptorDocumentationParser.kt b/core/src/main/kotlin/Kotlin/DescriptorDocumentationParser.kt index eb8c12d0..f2d9d3a7 100644 --- a/core/src/main/kotlin/Kotlin/DescriptorDocumentationParser.kt +++ b/core/src/main/kotlin/Kotlin/DescriptorDocumentationParser.kt @@ -81,7 +81,7 @@ class DescriptorDocumentationParser val suppressAnnotation = annotations.findAnnotation(FqName(Suppress::class.qualifiedName!!)) return if (suppressAnnotation != null) { @Suppress("UNCHECKED_CAST") - (suppressAnnotation.argumentValue("names") as List).any { it.value == "NOT_DOCUMENTED" } + (suppressAnnotation.argumentValue("names")?.value as List).any { it.value == "NOT_DOCUMENTED" } } else containingDeclaration?.isSuppressWarning() ?: false } diff --git a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt index 61bf50d6..916f89c9 100644 --- a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt +++ b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt @@ -15,7 +15,9 @@ import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi import org.jetbrains.kotlin.kdoc.psi.impl.KDocSection import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.load.java.structure.impl.JavaClassImpl +import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.FqName +import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtModifierListOwner import org.jetbrains.kotlin.psi.KtParameter import org.jetbrains.kotlin.resolve.DescriptorUtils @@ -779,6 +781,14 @@ class DocumentationBuilder "\"" + StringUtil.escapeStringCharacters(value) + "\"" is EnumEntrySyntheticClassDescriptor -> value.containingDeclaration.name.asString() + "." + value.name.asString() + is Pair<*, *> -> { + val (classId, name) = value + if (classId is ClassId && name is Name) { + classId.shortClassName.asString() + "." + name.asString() + } else { + value.toString() + } + } else -> value.toString() }.let { valueString -> DocumentationNode(valueString, Content.Empty, NodeKind.Value) diff --git a/gradle.properties b/gradle.properties index 4a6475b1..cabae269 100644 --- a/gradle.properties +++ b/gradle.properties @@ -2,8 +2,8 @@ dokka_version=0.9.16 dokka_publication_channel=dokka #Kotlin compiler and plugin -bundled_kotlin_compiler_version=1.2.20-dev-419 -kotlin_version=1.2.0 +bundled_kotlin_compiler_version=1.2.40-dev-529 +kotlin_version=1.2.21 kotlin_for_gradle_runtime_version=1.1.60 ant_version=1.9.6 -- cgit From 8db3b40a0e82ff0847d078cf496dfd6edc1464a5 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Wed, 7 Mar 2018 22:42:55 +0300 Subject: Bind language service back --- core/src/main/kotlin/Formats/FormatDescriptor.kt | 3 +++ 1 file changed, 3 insertions(+) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Formats/FormatDescriptor.kt b/core/src/main/kotlin/Formats/FormatDescriptor.kt index a1120c00..b497fb0f 100644 --- a/core/src/main/kotlin/Formats/FormatDescriptor.kt +++ b/core/src/main/kotlin/Formats/FormatDescriptor.kt @@ -26,6 +26,7 @@ abstract class FileGeneratorBasedFormatDescriptor : FormatDescriptor { bind() toType NodeLocationAwareGenerator::class bind() toType generatorServiceClass + bind() toType languageServiceClass lazyBind() toOptional (outlineServiceClass) lazyBind() toOptional formatServiceClass @@ -36,4 +37,6 @@ abstract class FileGeneratorBasedFormatDescriptor : FormatDescriptor { abstract val outlineServiceClass: KClass? abstract val generatorServiceClass: KClass abstract val packageListServiceClass: KClass? + + open val languageServiceClass: KClass = KotlinLanguageService::class } \ No newline at end of file -- cgit From d6ba6677cff2de399b8231127325af2cea210b50 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Thu, 22 Mar 2018 23:12:56 +0300 Subject: Fix external references to Java enum entries Fix #274 --- core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt | 5 ++++- core/src/test/kotlin/format/MarkdownFormatTest.kt | 5 +++++ core/testdata/format/enumRef.kt | 4 ++++ core/testdata/format/enumRef.md | 8 ++++++++ 4 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 core/testdata/format/enumRef.kt create mode 100644 core/testdata/format/enumRef.md (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt b/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt index 108cee78..ebea7183 100644 --- a/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt +++ b/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt @@ -5,6 +5,7 @@ import com.google.inject.Singleton import com.intellij.psi.PsiMethod import com.intellij.util.io.* import org.jetbrains.kotlin.descriptors.* +import org.jetbrains.kotlin.descriptors.impl.EnumEntrySyntheticClassDescriptor import org.jetbrains.kotlin.load.java.descriptors.JavaCallableMemberDescriptor import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor import org.jetbrains.kotlin.load.java.descriptors.JavaMethodDescriptor @@ -178,7 +179,9 @@ interface InboundExternalLinkResolutionService { class Javadoc : InboundExternalLinkResolutionService { override fun getPath(symbol: DeclarationDescriptor): String? { - if (symbol is JavaClassDescriptor) { + if (symbol is EnumEntrySyntheticClassDescriptor) { + return getPath(symbol.containingDeclaration)?.let { it + "#" + symbol.name.asString() } + } else if (symbol is JavaClassDescriptor) { return DescriptorUtils.getFqName(symbol).asString().replace(".", "/") + ".html" } else if (symbol is JavaCallableMemberDescriptor) { val containingClass = symbol.containingDeclaration as? JavaClassDescriptor ?: return null diff --git a/core/src/test/kotlin/format/MarkdownFormatTest.kt b/core/src/test/kotlin/format/MarkdownFormatTest.kt index f60969fc..f06f0e64 100644 --- a/core/src/test/kotlin/format/MarkdownFormatTest.kt +++ b/core/src/test/kotlin/format/MarkdownFormatTest.kt @@ -419,6 +419,11 @@ class MarkdownFormatTest: FileGeneratorTestCase() { verifyMarkdownNodeByName("companionImplements", "Foo") } + @Test fun enumRef() { + verifyMarkdownNode("enumRef") + } + + private fun buildMultiplePlatforms(path: String): DocumentationModule { val module = DocumentationModule("test") val options = DocumentationOptions( diff --git a/core/testdata/format/enumRef.kt b/core/testdata/format/enumRef.kt new file mode 100644 index 00000000..5c0b2de9 --- /dev/null +++ b/core/testdata/format/enumRef.kt @@ -0,0 +1,4 @@ +/** + * [java.math.RoundingMode.UP] + */ +fun f() {} \ No newline at end of file diff --git a/core/testdata/format/enumRef.md b/core/testdata/format/enumRef.md new file mode 100644 index 00000000..8b2a6650 --- /dev/null +++ b/core/testdata/format/enumRef.md @@ -0,0 +1,8 @@ +[test](index.md) / [f](./f.md) + +# f + +`fun f(): Unit` + +[java.math.RoundingMode.UP](http://docs.oracle.com/javase/6/docs/api/java/math/RoundingMode.html#UP) + -- cgit From 5eeab3e8c96b6e03435025f9adae38c7e9e3edab Mon Sep 17 00:00:00 2001 From: Håvard Kindem Date: Mon, 7 May 2018 10:46:00 +0200 Subject: Fix ClassCastException when generating JavaDoc Fixes #287 --- core/src/main/kotlin/Kotlin/DocumentationBuilder.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt index 916f89c9..17e4bc1a 100644 --- a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt +++ b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt @@ -887,7 +887,7 @@ fun DeclarationDescriptor.isDocumentationSuppressed(options: DocumentationOption } fun DeclarationDescriptor.sourcePsi() = - ((original as DeclarationDescriptorWithSource).source as? PsiSourceElement)?.psi + ((original as? DeclarationDescriptorWithSource)?.source as? PsiSourceElement)?.psi fun DeclarationDescriptor.isDeprecated(): Boolean = annotations.any { DescriptorUtils.getFqName(it.type.constructor.declarationDescriptor!!).asString() == "kotlin.Deprecated" -- cgit From 02039d818ca8c508908641e01fa480674276a785 Mon Sep 17 00:00:00 2001 From: Lukas Niemeier Date: Wed, 28 Mar 2018 23:57:34 +0200 Subject: Avoid unnecessary logging. --- core/src/main/kotlin/javadoc/dokka-adapters.kt | 1 - 1 file changed, 1 deletion(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/javadoc/dokka-adapters.kt b/core/src/main/kotlin/javadoc/dokka-adapters.kt index 4676db18..483fb3cd 100644 --- a/core/src/main/kotlin/javadoc/dokka-adapters.kt +++ b/core/src/main/kotlin/javadoc/dokka-adapters.kt @@ -13,7 +13,6 @@ class JavadocGenerator @Inject constructor(val options: DocumentationOptions, va override fun buildPages(nodes: Iterable) { val module = nodes.single() as DocumentationModule - DokkaConsoleLogger.report() HtmlDoclet.start(ModuleNodeAdapter(module, StandardReporter(logger), options.outputDir)) } -- cgit From b3fa0d91fd466c3319f3a37a1cc5e82be2b89697 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Wed, 16 May 2018 18:06:56 +0300 Subject: Fix link resolution context for inherited docs Fix #229 --- .../kotlin/Kotlin/DescriptorDocumentationParser.kt | 18 ++++++++++++++---- core/src/test/kotlin/format/MarkdownFormatTest.kt | 16 ++++++++++++++++ core/testdata/format/inheritedLink.1.kt | 10 ++++++++++ core/testdata/format/inheritedLink.kt | 11 +++++++++++ core/testdata/format/inheritedLink.md | 17 +++++++++++++++++ 5 files changed, 68 insertions(+), 4 deletions(-) create mode 100644 core/testdata/format/inheritedLink.1.kt create mode 100644 core/testdata/format/inheritedLink.kt create mode 100644 core/testdata/format/inheritedLink.md (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Kotlin/DescriptorDocumentationParser.kt b/core/src/main/kotlin/Kotlin/DescriptorDocumentationParser.kt index f2d9d3a7..6e44df74 100644 --- a/core/src/main/kotlin/Kotlin/DescriptorDocumentationParser.kt +++ b/core/src/main/kotlin/Kotlin/DescriptorDocumentationParser.kt @@ -8,14 +8,17 @@ import org.intellij.markdown.parser.LinkMap import org.jetbrains.dokka.* import org.jetbrains.dokka.Samples.SampleProcessingService import org.jetbrains.kotlin.descriptors.* +import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.kdoc.findKDoc import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.kdoc.parser.KDocKnownTag +import org.jetbrains.kotlin.kdoc.psi.api.KDoc import org.jetbrains.kotlin.kdoc.psi.impl.KDocSection import org.jetbrains.kotlin.kdoc.psi.impl.KDocTag import org.jetbrains.kotlin.load.java.descriptors.JavaCallableMemberDescriptor import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor import org.jetbrains.kotlin.name.FqName +import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.annotations.argumentValue import org.jetbrains.kotlin.resolve.constants.StringValue @@ -49,6 +52,13 @@ class DescriptorDocumentationParser } return Content.Empty to { node -> } } + + val contextDescriptor = + (PsiTreeUtil.getParentOfType(kdoc, KDoc::class.java)?.context as? KtDeclaration) + ?.takeIf { it != descriptor.original.sourcePsi() } + ?.resolveToDescriptorIfAny() + ?: descriptor + var kdocText = kdoc.getContent() // workaround for code fence parsing problem in IJ markdown parser if (kdocText.endsWith("```") || kdocText.endsWith("~~~")) { @@ -56,20 +66,20 @@ class DescriptorDocumentationParser } val tree = parseMarkdown(kdocText) val linkMap = LinkMap.buildLinkMap(tree.node, kdocText) - val content = buildContent(tree, LinkResolver(linkMap, { href -> linkResolver.resolveContentLink(descriptor, href) }), inline) + val content = buildContent(tree, LinkResolver(linkMap, { href -> linkResolver.resolveContentLink(contextDescriptor, href) }), inline) if (kdoc is KDocSection) { val tags = kdoc.getTags() tags.forEach { when (it.knownTag) { KDocKnownTag.SAMPLE -> - content.append(sampleService.resolveSample(descriptor, it.getSubjectName(), it)) + content.append(sampleService.resolveSample(contextDescriptor, it.getSubjectName(), it)) KDocKnownTag.SEE -> - content.addTagToSeeAlso(descriptor, it) + content.addTagToSeeAlso(contextDescriptor, it) else -> { val section = content.addSection(javadocSectionDisplayName(it.name), it.getSubjectName()) val sectionContent = it.getContent() val markdownNode = parseMarkdown(sectionContent) - buildInlineContentTo(markdownNode, section, LinkResolver(linkMap, { href -> linkResolver.resolveContentLink(descriptor, href) })) + buildInlineContentTo(markdownNode, section, LinkResolver(linkMap, { href -> linkResolver.resolveContentLink(contextDescriptor, href) })) } } } diff --git a/core/src/test/kotlin/format/MarkdownFormatTest.kt b/core/src/test/kotlin/format/MarkdownFormatTest.kt index f06f0e64..9e4c831d 100644 --- a/core/src/test/kotlin/format/MarkdownFormatTest.kt +++ b/core/src/test/kotlin/format/MarkdownFormatTest.kt @@ -423,6 +423,22 @@ class MarkdownFormatTest: FileGeneratorTestCase() { verifyMarkdownNode("enumRef") } + @Test fun inheritedLink() { + val filePath = "testdata/format/inheritedLink" + verifyOutput( + arrayOf( + contentRootFromPath("$filePath.kt"), + contentRootFromPath("$filePath.1.kt") + ), + ".md", + withJdk = true, + withKotlinRuntime = true, + includeNonPublic = false + ) { model, output -> + buildPagesAndReadInto(model.members.single { it.name == "p2" }.members.single().members, output) + } + } + private fun buildMultiplePlatforms(path: String): DocumentationModule { val module = DocumentationModule("test") diff --git a/core/testdata/format/inheritedLink.1.kt b/core/testdata/format/inheritedLink.1.kt new file mode 100644 index 00000000..29cc12b4 --- /dev/null +++ b/core/testdata/format/inheritedLink.1.kt @@ -0,0 +1,10 @@ +package p1 + +import java.util.LinkedList + +interface Foo { + + /** Says hello - [LinkedList]. */ + fun sayHello() : String + +} \ No newline at end of file diff --git a/core/testdata/format/inheritedLink.kt b/core/testdata/format/inheritedLink.kt new file mode 100644 index 00000000..86b8f4e2 --- /dev/null +++ b/core/testdata/format/inheritedLink.kt @@ -0,0 +1,11 @@ +package p2 + +import p1.Foo + +class FooBar : Foo { + + override fun sayHello(): String { + return "Hello!" + } + +} \ No newline at end of file diff --git a/core/testdata/format/inheritedLink.md b/core/testdata/format/inheritedLink.md new file mode 100644 index 00000000..e5af326c --- /dev/null +++ b/core/testdata/format/inheritedLink.md @@ -0,0 +1,17 @@ + +[test](../../index.md) / [p2](../index.md) / [FooBar](index.md) / [<init>](./-init-.md) + +# <init> + +`FooBar()` + +[test](../../index.md) / [p2](../index.md) / [FooBar](index.md) / [sayHello](./say-hello.md) + +# sayHello + +`fun sayHello(): String` + +Overrides [Foo.sayHello](../../p1/-foo/say-hello.md) + +Says hello - [LinkedList](http://docs.oracle.com/javase/6/docs/api/java/util/LinkedList.html). + -- cgit From ad95537c3f2eb5ba1478f82fd5b476d2309bc986 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Wed, 16 May 2018 18:46:07 +0300 Subject: Fix external links to packages with uppercase letters in dokka mode Fix #285 --- .../main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt b/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt index ebea7183..e19ecf76 100644 --- a/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt +++ b/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt @@ -214,13 +214,11 @@ interface InboundExternalLinkResolutionService { else return "$path/index.$extension" } - fun getPathWithoutExtension(symbol: DeclarationDescriptor): String { - if (symbol.containingDeclaration == null) - return identifierToFilename(symbol.name.asString()) - else if (symbol is PackageFragmentDescriptor) { - return symbol.fqName.asString() - } else { - return getPathWithoutExtension(symbol.containingDeclaration!!) + '/' + identifierToFilename(symbol.name.asString()) + private fun getPathWithoutExtension(symbol: DeclarationDescriptor): String { + return when { + symbol.containingDeclaration == null -> identifierToFilename(symbol.name.asString()) + symbol is PackageFragmentDescriptor -> identifierToFilename(symbol.fqName.asString()) + else -> getPathWithoutExtension(symbol.containingDeclaration!!) + '/' + identifierToFilename(symbol.name.asString()) } } -- cgit From 9865da2e6e6c038ab6c719a6a03bb09184542d20 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Thu, 17 May 2018 19:48:44 +0300 Subject: Fix incorrect link to stylesheet in html format --- core/src/main/kotlin/Formats/HtmlFormatService.kt | 5 ++--- core/src/main/kotlin/Generation/FileGenerator.kt | 4 +--- core/src/main/kotlin/Locations/Location.kt | 6 +++--- core/src/test/kotlin/format/FileGeneratorTestCase.kt | 2 +- 4 files changed, 7 insertions(+), 10 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Formats/HtmlFormatService.kt b/core/src/main/kotlin/Formats/HtmlFormatService.kt index 0073553c..0ad946be 100644 --- a/core/src/main/kotlin/Formats/HtmlFormatService.kt +++ b/core/src/main/kotlin/Formats/HtmlFormatService.kt @@ -4,7 +4,6 @@ import com.google.inject.Inject import com.google.inject.name.Named import org.jetbrains.dokka.Utilities.impliedPlatformsName import java.io.File -import java.nio.file.Path open class HtmlOutputBuilder(to: StringBuilder, location: Location, @@ -80,7 +79,7 @@ open class HtmlOutputBuilder(to: StringBuilder, } override fun appendNodes(nodes: Iterable) { - templateService.appendHeader(to, getPageTitle(nodes), generator.relativeToRoot(location)) + templateService.appendHeader(to, getPageTitle(nodes), generator.relativePathToRoot(location)) super.appendNodes(nodes) templateService.appendFooter(to) } @@ -108,7 +107,7 @@ open class HtmlFormatService @Inject constructor(generator: NodeLocationAwareGen HtmlOutputBuilder(to, location, generator, languageService, extension, impliedPlatforms, templateService) override fun appendOutline(location: Location, to: StringBuilder, nodes: Iterable) { - templateService.appendHeader(to, "Module Contents", generator.relativeToRoot(location)) + templateService.appendHeader(to, "Module Contents", generator.relativePathToRoot(location)) super.appendOutline(location, to, nodes) templateService.appendFooter(to) } diff --git a/core/src/main/kotlin/Generation/FileGenerator.kt b/core/src/main/kotlin/Generation/FileGenerator.kt index bc08e180..b7c6cf63 100644 --- a/core/src/main/kotlin/Generation/FileGenerator.kt +++ b/core/src/main/kotlin/Generation/FileGenerator.kt @@ -8,15 +8,13 @@ import java.io.FileOutputStream import java.io.IOException import java.io.OutputStreamWriter -class FileGenerator @Inject constructor(@Named("outputDir") val rootFile: File) : NodeLocationAwareGenerator { +class FileGenerator @Inject constructor(@Named("outputDir") override val root: File) : NodeLocationAwareGenerator { @set:Inject(optional = true) var outlineService: OutlineFormatService? = null @set:Inject(optional = true) lateinit var formatService: FormatService @set:Inject(optional = true) lateinit var options: DocumentationOptions @set:Inject(optional = true) var packageListService: PackageListService? = null - override val root: File = rootFile - override fun location(node: DocumentationNode): FileLocation { return FileLocation(fileForNode(node, formatService.linkExtension)) } diff --git a/core/src/main/kotlin/Locations/Location.kt b/core/src/main/kotlin/Locations/Location.kt index 0e6572d9..4cb0ac39 100644 --- a/core/src/main/kotlin/Locations/Location.kt +++ b/core/src/main/kotlin/Locations/Location.kt @@ -53,9 +53,9 @@ fun NodeLocationAwareGenerator.relativePathToLocation(owner: DocumentationNode, return location(owner).relativePathTo(location(node), null) } -fun NodeLocationAwareGenerator.relativeToRoot(from: Location): File { - val file = File(from.path) - return file.relativeTo(root) +fun NodeLocationAwareGenerator.relativePathToRoot(from: Location): File { + val file = File(from.path).parentFile + return root.relativeTo(file) } fun File.toUnixString() = toString().replace(File.separatorChar, '/') diff --git a/core/src/test/kotlin/format/FileGeneratorTestCase.kt b/core/src/test/kotlin/format/FileGeneratorTestCase.kt index 948426ea..ef9e815d 100644 --- a/core/src/test/kotlin/format/FileGeneratorTestCase.kt +++ b/core/src/test/kotlin/format/FileGeneratorTestCase.kt @@ -27,7 +27,7 @@ abstract class FileGeneratorTestCase { if (sb.isNotBlank() && !sb.endsWith('\n')) { sb.appendln() } - sb.appendln("") + sb.appendln("") } sb.append(loc.file.readText()) } -- cgit From ab3621abcc468cead0206d3c45f200f6c9ea10b9 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Fri, 18 May 2018 12:45:49 +0300 Subject: Enable suppression of generated files for Android plugin 3.2.0-alpha Fix #308 --- core/src/main/kotlin/DokkaBootstrapImpl.kt | 2 +- core/src/main/kotlin/Kotlin/DocumentationBuilder.kt | 2 +- runners/android-gradle-plugin/src/main/kotlin/mainAndroid.kt | 8 ++++++-- 3 files changed, 8 insertions(+), 4 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/DokkaBootstrapImpl.kt b/core/src/main/kotlin/DokkaBootstrapImpl.kt index 126a0175..aeaca8be 100644 --- a/core/src/main/kotlin/DokkaBootstrapImpl.kt +++ b/core/src/main/kotlin/DokkaBootstrapImpl.kt @@ -69,7 +69,7 @@ class DokkaBootstrapImpl : DokkaBootstrap { languageVersion, apiVersion, cacheRoot, - suppressedFiles.map { File(it) } + suppressedFiles.map { File(it) }.toSet() ) ) } diff --git a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt index 17e4bc1a..7b50fff5 100644 --- a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt +++ b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt @@ -53,7 +53,7 @@ class DocumentationOptions(val outputDir: String, val languageVersion: String?, val apiVersion: String?, cacheRoot: String? = null, - val suppressedFiles: List = emptyList()) { + val suppressedFiles: Set = emptySet()) { init { if (perPackageOptions.any { it.prefix == "" }) throw IllegalArgumentException("Please do not register packageOptions with all match pattern, use global settings instead") diff --git a/runners/android-gradle-plugin/src/main/kotlin/mainAndroid.kt b/runners/android-gradle-plugin/src/main/kotlin/mainAndroid.kt index f2261120..bd2e88c2 100644 --- a/runners/android-gradle-plugin/src/main/kotlin/mainAndroid.kt +++ b/runners/android-gradle-plugin/src/main/kotlin/mainAndroid.kt @@ -23,8 +23,12 @@ open class DokkaAndroidTask : DokkaTask() { @Input var noAndroidSdkLink: Boolean = false override fun collectSuppressedFiles(sourceRoots: List): List { - val generatedSubpath = "${project.buildDir}/generated/source".replace("/", File.separator) - return sourceRoots.filter { generatedSubpath in it.path }.flatMap { File(it.path).walk().toList() }.map { it.absolutePath } + val generatedRoot = project.buildDir.resolve("generated").absoluteFile + return sourceRoots + .map { File(it.path) } + .filter { it.startsWith(generatedRoot) } + .flatMap { it.walk().toList() } + .map { it.absolutePath } } init { -- cgit From dcd84d619665864b275591c93248f4637f6ee636 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Fri, 1 Jun 2018 21:42:34 +0300 Subject: Update bundled kotlin compiler to 1.2.60-dev-157 (cherry picked from commit efbcbd5) --- build.gradle | 1 + core/build.gradle | 2 +- .../main/kotlin/Analysis/AnalysisEnvironment.kt | 64 ++++++++++++---------- gradle.properties | 2 +- 4 files changed, 37 insertions(+), 32 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/build.gradle b/build.gradle index 35ec271e..e13af2b6 100644 --- a/build.gradle +++ b/build.gradle @@ -29,6 +29,7 @@ allprojects { repositories { mavenCentral() mavenLocal() + maven { url "https://dl.bintray.com/jetbrains/markdown" } maven { url "http://dl.bintray.com/kotlin/kotlin-eap" } maven { url "https://dl.bintray.com/kotlin/kotlin-dev" } maven { url 'https://jitpack.io' } diff --git a/core/build.gradle b/core/build.gradle index a87d3c97..a4538471 100644 --- a/core/build.gradle +++ b/core/build.gradle @@ -29,7 +29,7 @@ dependencies { compile "org.jetbrains.kotlin:kotlin-script-runtime:$bundled_kotlin_compiler_version" compile "teamcity:kotlin-ide-common:$bundled_kotlin_compiler_version" - compile "teamcity:markdown:$markdownVersion" + compile "org.jetbrains:markdown:$markdownVersion" compile intellijCoreAnalysis() diff --git a/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt b/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt index 5522d4f0..b2e4b490 100644 --- a/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt +++ b/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt @@ -131,32 +131,36 @@ class AnalysisEnvironment(val messageCollector: MessageCollector) : Disposable { } val resolverForProject = ResolverForProjectImpl( - "Dokka", - projectContext, - listOf(library, module), - { JvmAnalyzerFacade }, - { - when (it) { - library -> ModuleContent(emptyList(), GlobalSearchScope.notScope(sourcesScope)) - module -> ModuleContent(sourceFiles, sourcesScope) - else -> throw IllegalArgumentException("Unexpected module info") - } - }, - JvmPlatformParameters { - val file = (it as JavaClassImpl).psi.containingFile.virtualFile - if (file in sourcesScope) - module - else - library - }, - CompilerEnvironment, - packagePartProviderFactory = { info, content -> - JvmPackagePartProvider(configuration.languageVersionSettings, content.moduleContentScope).apply { - addRoots(javaRoots) - } - }, - builtIns = builtIns, - modulePlatforms = { JvmPlatform.multiTargetPlatform } + "Dokka", + projectContext, + listOf(library, module), + { + when (it) { + library -> ModuleContent(it, emptyList(), GlobalSearchScope.notScope(sourcesScope)) + module -> ModuleContent(it, emptyList(), sourcesScope) + else -> throw IllegalArgumentException("Unexpected module info") + } + }, + { + JvmPlatform.multiTargetPlatform + }, + LanguageSettingsProvider.Default /* TODO: Fix this */, + { JvmAnalyzerFacade }, + + JvmPlatformParameters { + val file = (it as JavaClassImpl).psi.containingFile.virtualFile + if (file in sourcesScope) + module + else + library + }, + CompilerEnvironment, + packagePartProviderFactory = { content -> + JvmPackagePartProvider(configuration.languageVersionSettings, content.moduleContentScope).apply { + addRoots(javaRoots) + } + }, + builtIns = builtIns ) resolverForProject.resolverForModule(library) // Required before module to initialize library properly @@ -241,6 +245,10 @@ fun contentRootFromPath(path: String): ContentRoot { class DokkaResolutionFacade(override val project: Project, override val moduleDescriptor: ModuleDescriptor, val resolverForModule: ResolverForModule) : ResolutionFacade { + override fun analyzeWithAllCompilerChecks(elements: Collection): AnalysisResult { + throw UnsupportedOperationException() + } + override fun tryGetFrontendService(element: PsiElement, serviceClass: Class): T? { return null } @@ -295,10 +303,6 @@ class DokkaResolutionFacade(override val project: Project, throw UnsupportedOperationException() } - override fun analyzeFullyAndGetResult(elements: Collection): AnalysisResult { - throw UnsupportedOperationException() - } - override fun getFrontendService(element: PsiElement, serviceClass: Class): T { throw UnsupportedOperationException() } diff --git a/gradle.properties b/gradle.properties index b060fc78..df409630 100644 --- a/gradle.properties +++ b/gradle.properties @@ -2,7 +2,7 @@ dokka_version=0.9.18-SNAPSHOT dokka_publication_channel=dokka #Kotlin compiler and plugin -bundled_kotlin_compiler_version=1.2.40-dev-529 +bundled_kotlin_compiler_version=1.2.60-dev-157 kotlin_version=1.2.21 kotlin_for_gradle_runtime_version=1.1.60 -- cgit From 9ea429920e07c77e1241c4beb172bb36735af783 Mon Sep 17 00:00:00 2001 From: aleksZubakov Date: Tue, 10 Jul 2018 19:27:16 +0300 Subject: Add js platform support --- .../main/kotlin/Analysis/AnalysisEnvironment.kt | 110 +++++++++++++++++---- core/src/main/kotlin/Generation/DokkaGenerator.kt | 24 +++-- .../main/kotlin/Generation/configurationImpl.kt | 13 ++- .../kotlin/org/jetbrains/dokka/configuration.kt | 22 +++++ runners/ant/src/main/kotlin/ant/dokka.kt | 5 +- runners/gradle-plugin/src/main/kotlin/main.kt | 2 + runners/maven-plugin/src/main/kotlin/DokkaMojo.kt | 4 + 7 files changed, 148 insertions(+), 32 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt b/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt index b2e4b490..453c0311 100644 --- a/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt +++ b/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt @@ -18,6 +18,8 @@ import com.intellij.psi.PsiElement import com.intellij.psi.search.GlobalSearchScope import com.intellij.util.io.URLUtil import org.jetbrains.kotlin.analyzer.* +import org.jetbrains.kotlin.builtins.jvm.JvmBuiltIns +import org.jetbrains.kotlin.caches.project.LibraryModuleInfo import org.jetbrains.kotlin.caches.resolve.KotlinCacheService import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys import org.jetbrains.kotlin.cli.common.messages.MessageCollector @@ -32,14 +34,17 @@ import org.jetbrains.kotlin.container.getService import org.jetbrains.kotlin.context.ProjectContext import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.ModuleDescriptor +import org.jetbrains.kotlin.idea.caches.resolve.JsAnalyzerFacade import org.jetbrains.kotlin.idea.resolve.ResolutionFacade +import org.jetbrains.kotlin.js.config.JSConfigurationKeys +import org.jetbrains.kotlin.js.resolve.JsPlatform import org.jetbrains.kotlin.load.java.structure.impl.JavaClassImpl import org.jetbrains.kotlin.name.Name -import org.jetbrains.kotlin.platform.JvmBuiltIns import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.BindingTrace import org.jetbrains.kotlin.resolve.CompilerEnvironment +import org.jetbrains.kotlin.resolve.TargetPlatform import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics import org.jetbrains.kotlin.resolve.jvm.JvmAnalyzerFacade import org.jetbrains.kotlin.resolve.jvm.JvmPlatformParameters @@ -59,7 +64,7 @@ import java.io.File * $messageCollector: required by compiler infrastructure and will receive all compiler messages * $body: optional and can be used to configure environment without creating local variable */ -class AnalysisEnvironment(val messageCollector: MessageCollector) : Disposable { +class AnalysisEnvironment(val messageCollector: MessageCollector, val analysisPlatform: Platform) : Disposable { val configuration = CompilerConfiguration() init { @@ -68,7 +73,12 @@ class AnalysisEnvironment(val messageCollector: MessageCollector) : Disposable { fun createCoreEnvironment(): KotlinCoreEnvironment { System.setProperty("idea.io.use.fallback", "true") - val environment = KotlinCoreEnvironment.createForProduction(this, configuration, EnvironmentConfigFiles.JVM_CONFIG_FILES) + + val configFiles = when (analysisPlatform) { + Platform.jvm -> EnvironmentConfigFiles.JVM_CONFIG_FILES + Platform.js -> EnvironmentConfigFiles.JS_CONFIG_FILES + } + val environment = KotlinCoreEnvironment.createForProduction(this, configuration, configFiles) val projectComponentManager = environment.project as MockComponentManager val projectFileIndex = CoreProjectFileIndex(environment.project, @@ -92,14 +102,71 @@ class AnalysisEnvironment(val messageCollector: MessageCollector) : Disposable { return environment } - fun createSourceModuleSearchScope(project: Project, sourceFiles: List): GlobalSearchScope { - // TODO: Fix when going to implement dokka for JS - return TopDownAnalyzerFacadeForJVM.newModuleSearchScope(project, sourceFiles) + fun createSourceModuleSearchScope(project: Project, sourceFiles: List): GlobalSearchScope = when (analysisPlatform) { + Platform.js -> GlobalSearchScope.filesScope(project, sourceFiles.map { it.virtualFile }.toSet()) + Platform.jvm -> TopDownAnalyzerFacadeForJVM.newModuleSearchScope(project, sourceFiles) } fun createResolutionFacade(environment: KotlinCoreEnvironment): DokkaResolutionFacade { + return when(analysisPlatform) { + Platform.jvm -> createJVMResolutionFacade(environment) + Platform.js -> createJSResolutionFacade(environment) + } + } + private fun createJSResolutionFacade(environment: KotlinCoreEnvironment): DokkaResolutionFacade { + val projectContext = ProjectContext(environment.project) + val sourceFiles = environment.getSourceFiles() + + val library = object : LibraryModuleInfo { + override val platform: TargetPlatform + get() = JsPlatform + + override fun getLibraryRoots(): Collection { + return classpath.map { it.absolutePath } + } + + override val name: Name = Name.special("") + override fun dependencies(): List = listOf(this) + } + val module = object : ModuleInfo { + override val name: Name = Name.special("") + override fun dependencies(): List = listOf(this, library) + } + + val sourcesScope = createSourceModuleSearchScope(environment.project, sourceFiles) + + val resolverForProject = ResolverForProjectImpl( + debugName = "Dokka", + projectContext = projectContext, + modules = listOf(library, module), + modulesContent = { + when (it) { + library -> ModuleContent(it, emptyList(), GlobalSearchScope.notScope(sourcesScope)) + module -> ModuleContent(it, emptyList(), sourcesScope) + else -> throw IllegalArgumentException("Unexpected module info") + } + }, + modulePlatforms = { JsPlatform.multiTargetPlatform }, + moduleLanguageSettingsProvider = LanguageSettingsProvider.Default /* TODO: Fix this */, + resolverForModuleFactoryByPlatform = { JsAnalyzerFacade }, + platformParameters = object : PlatformAnalysisParameters {}, + targetEnvironment = CompilerEnvironment, + builtIns = JsPlatform.builtIns + ) + + resolverForProject.resolverForModule(library) // Required before module to initialize library properly + val resolverForModule = resolverForProject.resolverForModule(module) + val moduleDescriptor = resolverForProject.descriptorForModule(module) + val created = DokkaResolutionFacade(environment.project, moduleDescriptor, resolverForModule) + val projectComponentManager = environment.project as MockComponentManager + projectComponentManager.registerService(KotlinCacheService::class.java, CoreKotlinCacheService(created)) + return created + + } + + private fun createJVMResolutionFacade(environment: KotlinCoreEnvironment): DokkaResolutionFacade { val projectContext = ProjectContext(environment.project) val sourceFiles = environment.getSourceFiles() @@ -131,30 +198,27 @@ class AnalysisEnvironment(val messageCollector: MessageCollector) : Disposable { } val resolverForProject = ResolverForProjectImpl( - "Dokka", - projectContext, - listOf(library, module), - { + debugName = "Dokka", + projectContext = projectContext, + modules = listOf(library, module), + modulesContent = { when (it) { library -> ModuleContent(it, emptyList(), GlobalSearchScope.notScope(sourcesScope)) module -> ModuleContent(it, emptyList(), sourcesScope) else -> throw IllegalArgumentException("Unexpected module info") } }, - { - JvmPlatform.multiTargetPlatform - }, - LanguageSettingsProvider.Default /* TODO: Fix this */, - { JvmAnalyzerFacade }, - - JvmPlatformParameters { + modulePlatforms = { JvmPlatform.multiTargetPlatform }, + moduleLanguageSettingsProvider = LanguageSettingsProvider.Default /* TODO: Fix this */, + resolverForModuleFactoryByPlatform = { JvmAnalyzerFacade }, + platformParameters = JvmPlatformParameters { val file = (it as JavaClassImpl).psi.containingFile.virtualFile if (file in sourcesScope) module else library }, - CompilerEnvironment, + targetEnvironment = CompilerEnvironment, packagePartProviderFactory = { content -> JvmPackagePartProvider(configuration.languageVersionSettings, content.moduleContentScope).apply { addRoots(javaRoots) @@ -191,7 +255,10 @@ class AnalysisEnvironment(val messageCollector: MessageCollector) : Disposable { * $paths: collection of files to add */ fun addClasspath(paths: List) { - configuration.addJvmClasspathRoots(paths) + when (analysisPlatform) { + Platform.js -> configuration.addAll(JSConfigurationKeys.LIBRARIES, paths.map{it.absolutePath}) + Platform.jvm -> configuration.addJvmClasspathRoots(paths) + } } /** @@ -199,7 +266,10 @@ class AnalysisEnvironment(val messageCollector: MessageCollector) : Disposable { * $path: path to add */ fun addClasspath(path: File) { - configuration.addJvmClasspathRoot(path) + when (analysisPlatform) { + Platform.js -> configuration.add(JSConfigurationKeys.LIBRARIES, path.absolutePath) + Platform.jvm -> configuration.addJvmClasspathRoot(path) + } } /** diff --git a/core/src/main/kotlin/Generation/DokkaGenerator.kt b/core/src/main/kotlin/Generation/DokkaGenerator.kt index 09e5cedf..a0a6eef7 100644 --- a/core/src/main/kotlin/Generation/DokkaGenerator.kt +++ b/core/src/main/kotlin/Generation/DokkaGenerator.kt @@ -35,9 +35,10 @@ class DokkaGenerator(val logger: DokkaLogger, private val documentationModule = DocumentationModule(moduleName) fun generate() { - val sourcesGroupedByPlatform = sources.groupBy { it.platforms.firstOrNull() } - for ((platform, roots) in sourcesGroupedByPlatform) { - appendSourceModule(platform, roots) + val sourcesGroupedByPlatform = sources.groupBy { it.platforms.firstOrNull() to it.analysisPlatform } + for ((platformsInfo, roots) in sourcesGroupedByPlatform) { + val (platform, analysisPlatform) = platformsInfo + appendSourceModule(platform, analysisPlatform, roots) } documentationModule.prepareForGeneration(options) @@ -49,9 +50,14 @@ class DokkaGenerator(val logger: DokkaLogger, logger.info("done in ${timeBuild / 1000} secs") } - private fun appendSourceModule(defaultPlatform: String?, sourceRoots: List) { + private fun appendSourceModule(defaultPlatform: String?, + analysisPlatform: Platform, + sourceRoots: List + + ) { + val sourcePaths = sourceRoots.map { it.path } - val environment = createAnalysisEnvironment(sourcePaths) + val environment = createAnalysisEnvironment(sourcePaths, analysisPlatform) logger.info("Module: $moduleName") logger.info("Output: ${File(options.outputDir)}") @@ -82,11 +88,13 @@ class DokkaGenerator(val logger: DokkaLogger, Disposer.dispose(environment) } - fun createAnalysisEnvironment(sourcePaths: List): AnalysisEnvironment { - val environment = AnalysisEnvironment(DokkaMessageCollector(logger)) + fun createAnalysisEnvironment(sourcePaths: List, analysisPlatform: Platform): AnalysisEnvironment { + val environment = AnalysisEnvironment(DokkaMessageCollector(logger), analysisPlatform) environment.apply { - addClasspath(PathUtil.getJdkClassesRootsFromCurrentJre()) + if (analysisPlatform == Platform.jvm) { + addClasspath(PathUtil.getJdkClassesRootsFromCurrentJre()) + } // addClasspath(PathUtil.getKotlinPathsForCompiler().getRuntimePath()) for (element in this@DokkaGenerator.classpath) { addClasspath(File(element)) diff --git a/core/src/main/kotlin/Generation/configurationImpl.kt b/core/src/main/kotlin/Generation/configurationImpl.kt index 34d4154e..0d916345 100644 --- a/core/src/main/kotlin/Generation/configurationImpl.kt +++ b/core/src/main/kotlin/Generation/configurationImpl.kt @@ -18,13 +18,22 @@ data class SourceLinkDefinitionImpl(override val path: String, } } -class SourceRootImpl(path: String, override val platforms: List = emptyList()) : SourceRoot { +class SourceRootImpl(path: String, override val platforms: List = emptyList(), + override val analysisPlatform: Platform = Platform.DEFAULT) : SourceRoot { override val path: String = File(path).absolutePath companion object { fun parseSourceRoot(sourceRoot: String): SourceRoot { val components = sourceRoot.split("::", limit = 2) - return SourceRootImpl(components.last(), if (components.size == 1) listOf() else components[0].split(',')) + + // TODO: create syntax for cli + val platform = if (components.size == 1) { + Platform.DEFAULT + } else { + Platform.fromString(components[0]) + } + + return SourceRootImpl(components.last(), emptyList(), platform) } } } diff --git a/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt b/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt index 90e5b5fc..b18e5daf 100644 --- a/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt +++ b/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt @@ -17,6 +17,27 @@ class UrlSerializer : ValueSerializer { override fun toJsonValue(value: URL?): Any? = value?.toExternalForm() } +enum class Platform(val key: String) { + jvm("jvm"), + js("js"); +// common("common"); + + + companion object { + val DEFAULT = jvm + + fun fromString(key: String): Platform { + return when (key.toLowerCase()) { + jvm.key -> jvm + js.key -> js +// common.key -> common + else -> TODO("write normal exception") + } + } + } + +} + interface DokkaConfiguration { val moduleName: String val classpath: List @@ -45,6 +66,7 @@ interface DokkaConfiguration { interface SourceRoot { val path: String val platforms: List + val analysisPlatform: Platform } interface SourceLinkDefinition { diff --git a/runners/ant/src/main/kotlin/ant/dokka.kt b/runners/ant/src/main/kotlin/ant/dokka.kt index d1b6bef5..58e2fa28 100644 --- a/runners/ant/src/main/kotlin/ant/dokka.kt +++ b/runners/ant/src/main/kotlin/ant/dokka.kt @@ -17,10 +17,11 @@ class AntLogger(val task: Task): DokkaLogger { class AntSourceLinkDefinition(var path: String? = null, var url: String? = null, var lineSuffix: String? = null) -class AntSourceRoot(var path: String? = null, var platforms: String? = null) { +class AntSourceRoot(var path: String? = null, var platforms: String? = null, + var platform: Platform = Platform.DEFAULT) { fun toSourceRoot(): SourceRootImpl? = path?.let { path -> - SourceRootImpl(path, platforms?.split(',').orEmpty()) + SourceRootImpl(path, platforms?.split(',').orEmpty(), platform) } } diff --git a/runners/gradle-plugin/src/main/kotlin/main.kt b/runners/gradle-plugin/src/main/kotlin/main.kt index 5f02cd0e..324ea8e0 100644 --- a/runners/gradle-plugin/src/main/kotlin/main.kt +++ b/runners/gradle-plugin/src/main/kotlin/main.kt @@ -396,6 +396,8 @@ class SourceRoot : DokkaConfiguration.SourceRoot, Serializable { override var platforms: List = arrayListOf() + override val analysisPlatform: Platform = Platform.DEFAULT + override fun toString(): String { return "${platforms.joinToString()}::$path" } diff --git a/runners/maven-plugin/src/main/kotlin/DokkaMojo.kt b/runners/maven-plugin/src/main/kotlin/DokkaMojo.kt index 09da90c6..6b86948d 100644 --- a/runners/maven-plugin/src/main/kotlin/DokkaMojo.kt +++ b/runners/maven-plugin/src/main/kotlin/DokkaMojo.kt @@ -39,6 +39,10 @@ abstract class AbstractDokkaMojo : AbstractMojo() { @Parameter override var platforms: List = emptyList() + + @Parameter + override var analysisPlatform: Platform = Platform.DEFAULT + } class PackageOptions : DokkaConfiguration.PackageOptions { -- cgit From 65b61e31b761071589e257381bea33557d932412 Mon Sep 17 00:00:00 2001 From: aleksZubakov Date: Thu, 12 Jul 2018 15:32:19 +0300 Subject: AnalysisEnvironment classpath for js platform fix --- .../src/main/kotlin/Analysis/AnalysisEnvironment.kt | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt b/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt index 453c0311..27881cad 100644 --- a/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt +++ b/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt @@ -102,14 +102,15 @@ class AnalysisEnvironment(val messageCollector: MessageCollector, val analysisPl return environment } - fun createSourceModuleSearchScope(project: Project, sourceFiles: List): GlobalSearchScope = when (analysisPlatform) { - Platform.js -> GlobalSearchScope.filesScope(project, sourceFiles.map { it.virtualFile }.toSet()) + fun createSourceModuleSearchScope(project: Project, sourceFiles: List): GlobalSearchScope = + when (analysisPlatform) { Platform.jvm -> TopDownAnalyzerFacadeForJVM.newModuleSearchScope(project, sourceFiles) - } + Platform.js -> GlobalSearchScope.filesScope(project, sourceFiles.map { it.virtualFile }.toSet()) + } fun createResolutionFacade(environment: KotlinCoreEnvironment): DokkaResolutionFacade { - return when(analysisPlatform) { + return when (analysisPlatform) { Platform.jvm -> createJVMResolutionFacade(environment) Platform.js -> createJSResolutionFacade(environment) } @@ -255,10 +256,10 @@ class AnalysisEnvironment(val messageCollector: MessageCollector, val analysisPl * $paths: collection of files to add */ fun addClasspath(paths: List) { - when (analysisPlatform) { - Platform.js -> configuration.addAll(JSConfigurationKeys.LIBRARIES, paths.map{it.absolutePath}) - Platform.jvm -> configuration.addJvmClasspathRoots(paths) + if (analysisPlatform == Platform.js) { + configuration.addAll(JSConfigurationKeys.LIBRARIES, paths.map { it.absolutePath }) } + configuration.addJvmClasspathRoots(paths) } /** @@ -266,10 +267,10 @@ class AnalysisEnvironment(val messageCollector: MessageCollector, val analysisPl * $path: path to add */ fun addClasspath(path: File) { - when (analysisPlatform) { - Platform.js -> configuration.add(JSConfigurationKeys.LIBRARIES, path.absolutePath) - Platform.jvm -> configuration.addJvmClasspathRoot(path) + if (analysisPlatform == Platform.js) { + configuration.add(JSConfigurationKeys.LIBRARIES, path.absolutePath) } + configuration.addJvmClasspathRoot(path) } /** -- cgit From b4fcc57ab7f335459131ce105924eeaa5fa77375 Mon Sep 17 00:00:00 2001 From: aleksZubakov Date: Thu, 12 Jul 2018 19:25:51 +0300 Subject: Add common platform support --- .../main/kotlin/Analysis/AnalysisEnvironment.kt | 73 +++++++++++++++++++--- .../kotlin/org/jetbrains/dokka/configuration.kt | 6 +- 2 files changed, 66 insertions(+), 13 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt b/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt index 27881cad..2558942b 100644 --- a/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt +++ b/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt @@ -18,6 +18,7 @@ import com.intellij.psi.PsiElement import com.intellij.psi.search.GlobalSearchScope import com.intellij.util.io.URLUtil import org.jetbrains.kotlin.analyzer.* +import org.jetbrains.kotlin.analyzer.common.CommonAnalyzerFacade import org.jetbrains.kotlin.builtins.jvm.JvmBuiltIns import org.jetbrains.kotlin.caches.project.LibraryModuleInfo import org.jetbrains.kotlin.caches.resolve.KotlinCacheService @@ -34,6 +35,7 @@ import org.jetbrains.kotlin.container.getService import org.jetbrains.kotlin.context.ProjectContext import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.ModuleDescriptor +import org.jetbrains.kotlin.descriptors.PackagePartProvider import org.jetbrains.kotlin.idea.caches.resolve.JsAnalyzerFacade import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.js.config.JSConfigurationKeys @@ -41,10 +43,7 @@ import org.jetbrains.kotlin.js.resolve.JsPlatform import org.jetbrains.kotlin.load.java.structure.impl.JavaClassImpl import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* -import org.jetbrains.kotlin.resolve.BindingContext -import org.jetbrains.kotlin.resolve.BindingTrace -import org.jetbrains.kotlin.resolve.CompilerEnvironment -import org.jetbrains.kotlin.resolve.TargetPlatform +import org.jetbrains.kotlin.resolve.* import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics import org.jetbrains.kotlin.resolve.jvm.JvmAnalyzerFacade import org.jetbrains.kotlin.resolve.jvm.JvmPlatformParameters @@ -75,7 +74,7 @@ class AnalysisEnvironment(val messageCollector: MessageCollector, val analysisPl System.setProperty("idea.io.use.fallback", "true") val configFiles = when (analysisPlatform) { - Platform.jvm -> EnvironmentConfigFiles.JVM_CONFIG_FILES + Platform.jvm, Platform.common -> EnvironmentConfigFiles.JVM_CONFIG_FILES Platform.js -> EnvironmentConfigFiles.JS_CONFIG_FILES } val environment = KotlinCoreEnvironment.createForProduction(this, configuration, configFiles) @@ -105,15 +104,67 @@ class AnalysisEnvironment(val messageCollector: MessageCollector, val analysisPl fun createSourceModuleSearchScope(project: Project, sourceFiles: List): GlobalSearchScope = when (analysisPlatform) { Platform.jvm -> TopDownAnalyzerFacadeForJVM.newModuleSearchScope(project, sourceFiles) - Platform.js -> GlobalSearchScope.filesScope(project, sourceFiles.map { it.virtualFile }.toSet()) + Platform.js, Platform.common -> GlobalSearchScope.filesScope(project, sourceFiles.map { it.virtualFile }.toSet()) } - fun createResolutionFacade(environment: KotlinCoreEnvironment): DokkaResolutionFacade { - return when (analysisPlatform) { - Platform.jvm -> createJVMResolutionFacade(environment) - Platform.js -> createJSResolutionFacade(environment) + fun createResolutionFacade(environment: KotlinCoreEnvironment): DokkaResolutionFacade = when (analysisPlatform) { + Platform.jvm -> createJVMResolutionFacade(environment) + Platform.js -> createJSResolutionFacade(environment) + Platform.common -> createCommonResolutionFacade(environment) + } + + fun createCommonResolutionFacade(environment: KotlinCoreEnvironment): DokkaResolutionFacade { + val projectContext = ProjectContext(environment.project) + val sourceFiles = environment.getSourceFiles() + + val library = object : LibraryModuleInfo { + override val platform: TargetPlatform + get() = TargetPlatform.Common + + override fun getLibraryRoots(): Collection { + return classpath.map { it.absolutePath } + } + + override val name: Name = Name.special("") + override fun dependencies(): List = listOf(this) + } + val module = object : ModuleInfo { + override val name: Name = Name.special("") + override fun dependencies(): List = listOf(this, library) } + + val sourcesScope = createSourceModuleSearchScope(environment.project, sourceFiles) + + val resolverForProject = ResolverForProjectImpl( + debugName = "Dokka", + projectContext = projectContext, + modules = listOf(module, library), + modulesContent = { + when (it) { + library -> ModuleContent(it, emptyList(), GlobalSearchScope.notScope(sourcesScope)) + module -> ModuleContent(it, emptyList(), GlobalSearchScope.allScope(environment.project)) + else -> throw IllegalArgumentException("Unexpected module info") + } + }, + modulePlatforms = { MultiTargetPlatform.Common }, + moduleLanguageSettingsProvider = LanguageSettingsProvider.Default /* TODO: Fix this */, + resolverForModuleFactoryByPlatform = { CommonAnalyzerFacade }, + platformParameters = object : PlatformAnalysisParameters {}, + targetEnvironment = CompilerEnvironment, + packagePartProviderFactory = { content -> + environment.createPackagePartProvider(content.moduleContentScope) + } + ) + + resolverForProject.resolverForModule(library) // Required before module to initialize library properly + val resolverForModule = resolverForProject.resolverForModule(module) + val moduleDescriptor = resolverForProject.descriptorForModule(module) + val created = DokkaResolutionFacade(environment.project, moduleDescriptor, resolverForModule) + val projectComponentManager = environment.project as MockComponentManager + projectComponentManager.registerService(KotlinCacheService::class.java, CoreKotlinCacheService(created)) + + return created } private fun createJSResolutionFacade(environment: KotlinCoreEnvironment): DokkaResolutionFacade { @@ -259,6 +310,7 @@ class AnalysisEnvironment(val messageCollector: MessageCollector, val analysisPl if (analysisPlatform == Platform.js) { configuration.addAll(JSConfigurationKeys.LIBRARIES, paths.map { it.absolutePath }) } + configuration.addAll(JSConfigurationKeys.LIBRARIES, paths.map { it.absolutePath }) configuration.addJvmClasspathRoots(paths) } @@ -270,6 +322,7 @@ class AnalysisEnvironment(val messageCollector: MessageCollector, val analysisPl if (analysisPlatform == Platform.js) { configuration.add(JSConfigurationKeys.LIBRARIES, path.absolutePath) } + configuration.add(JSConfigurationKeys.LIBRARIES, path.absolutePath) configuration.addJvmClasspathRoot(path) } diff --git a/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt b/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt index b18e5daf..d1794953 100644 --- a/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt +++ b/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt @@ -19,8 +19,8 @@ class UrlSerializer : ValueSerializer { enum class Platform(val key: String) { jvm("jvm"), - js("js"); -// common("common"); + js("js"), + common("common"); companion object { @@ -30,7 +30,7 @@ enum class Platform(val key: String) { return when (key.toLowerCase()) { jvm.key -> jvm js.key -> js -// common.key -> common + common.key -> common else -> TODO("write normal exception") } } -- cgit From eca10911658bc48cd5508fbe1fd371adc881f392 Mon Sep 17 00:00:00 2001 From: aleksZubakov Date: Thu, 12 Jul 2018 21:59:25 +0300 Subject: AnalysisPlatform refactoring --- .../main/kotlin/Analysis/AnalysisEnvironment.kt | 197 +++++++++------------ 1 file changed, 83 insertions(+), 114 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt b/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt index 2558942b..f03e9eea 100644 --- a/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt +++ b/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt @@ -19,6 +19,8 @@ import com.intellij.psi.search.GlobalSearchScope import com.intellij.util.io.URLUtil import org.jetbrains.kotlin.analyzer.* import org.jetbrains.kotlin.analyzer.common.CommonAnalyzerFacade +import org.jetbrains.kotlin.builtins.DefaultBuiltIns +import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.builtins.jvm.JvmBuiltIns import org.jetbrains.kotlin.caches.project.LibraryModuleInfo import org.jetbrains.kotlin.caches.resolve.KotlinCacheService @@ -108,19 +110,20 @@ class AnalysisEnvironment(val messageCollector: MessageCollector, val analysisPl } - fun createResolutionFacade(environment: KotlinCoreEnvironment): DokkaResolutionFacade = when (analysisPlatform) { - Platform.jvm -> createJVMResolutionFacade(environment) - Platform.js -> createJSResolutionFacade(environment) - Platform.common -> createCommonResolutionFacade(environment) - } - - fun createCommonResolutionFacade(environment: KotlinCoreEnvironment): DokkaResolutionFacade { + fun createResolutionFacade(environment: KotlinCoreEnvironment): DokkaResolutionFacade { val projectContext = ProjectContext(environment.project) val sourceFiles = environment.getSourceFiles() + + val targetPlatform = when (analysisPlatform) { + Platform.js -> JsPlatform + Platform.common -> TargetPlatform.Common + Platform.jvm -> JvmPlatform + } + val library = object : LibraryModuleInfo { override val platform: TargetPlatform - get() = TargetPlatform.Common + get() = targetPlatform override fun getLibraryRoots(): Collection { return classpath.map { it.absolutePath } @@ -135,31 +138,29 @@ class AnalysisEnvironment(val messageCollector: MessageCollector, val analysisPl } val sourcesScope = createSourceModuleSearchScope(environment.project, sourceFiles) + val modulesContent: (ModuleInfo) -> ModuleContent = { + when (it) { + library -> ModuleContent(it, emptyList(), GlobalSearchScope.notScope(sourcesScope)) + module -> ModuleContent(it, emptyList(), GlobalSearchScope.allScope(environment.project)) + else -> throw IllegalArgumentException("Unexpected module info") + } + } - val resolverForProject = ResolverForProjectImpl( - debugName = "Dokka", - projectContext = projectContext, - modules = listOf(module, library), - modulesContent = { - when (it) { - library -> ModuleContent(it, emptyList(), GlobalSearchScope.notScope(sourcesScope)) - module -> ModuleContent(it, emptyList(), GlobalSearchScope.allScope(environment.project)) - else -> throw IllegalArgumentException("Unexpected module info") - } - }, - modulePlatforms = { MultiTargetPlatform.Common }, - moduleLanguageSettingsProvider = LanguageSettingsProvider.Default /* TODO: Fix this */, - resolverForModuleFactoryByPlatform = { CommonAnalyzerFacade }, - platformParameters = object : PlatformAnalysisParameters {}, - targetEnvironment = CompilerEnvironment, - packagePartProviderFactory = { content -> - environment.createPackagePartProvider(content.moduleContentScope) + var builtIns: JvmBuiltIns? = null + + val resolverForProject = when (analysisPlatform) { + Platform.jvm -> { + builtIns = JvmBuiltIns(projectContext.storageManager) + createJvmResolverForProject(projectContext, module, library, modulesContent, sourcesScope, builtIns) } - ) + Platform.js -> createJsResolverForProject(projectContext, module, library, modulesContent) + Platform.common -> createCommonResolverForProject(projectContext, module, library, modulesContent, environment) + } resolverForProject.resolverForModule(library) // Required before module to initialize library properly val resolverForModule = resolverForProject.resolverForModule(module) val moduleDescriptor = resolverForProject.descriptorForModule(module) + builtIns?.initialize(moduleDescriptor, true) val created = DokkaResolutionFacade(environment.project, moduleDescriptor, resolverForModule) val projectComponentManager = environment.project as MockComponentManager projectComponentManager.registerService(KotlinCacheService::class.java, CoreKotlinCacheService(created)) @@ -167,99 +168,76 @@ class AnalysisEnvironment(val messageCollector: MessageCollector, val analysisPl return created } - private fun createJSResolutionFacade(environment: KotlinCoreEnvironment): DokkaResolutionFacade { - val projectContext = ProjectContext(environment.project) - val sourceFiles = environment.getSourceFiles() - - val library = object : LibraryModuleInfo { - override val platform: TargetPlatform - get() = JsPlatform - - override fun getLibraryRoots(): Collection { - return classpath.map { it.absolutePath } - } - - override val name: Name = Name.special("") - override fun dependencies(): List = listOf(this) - } - val module = object : ModuleInfo { - override val name: Name = Name.special("") - override fun dependencies(): List = listOf(this, library) - } - - val sourcesScope = createSourceModuleSearchScope(environment.project, sourceFiles) - - val resolverForProject = ResolverForProjectImpl( + private fun createCommonResolverForProject( + projectContext: ProjectContext, + module: ModuleInfo, + library: LibraryModuleInfo, + modulesContent: (ModuleInfo) -> ModuleContent, + environment: KotlinCoreEnvironment + ): ResolverForProjectImpl { + return ResolverForProjectImpl( debugName = "Dokka", projectContext = projectContext, - modules = listOf(library, module), - modulesContent = { - when (it) { - library -> ModuleContent(it, emptyList(), GlobalSearchScope.notScope(sourcesScope)) - module -> ModuleContent(it, emptyList(), sourcesScope) - else -> throw IllegalArgumentException("Unexpected module info") - } + modules = listOf(module, library), + modulesContent = modulesContent, + modulePlatforms = { MultiTargetPlatform.Common }, + moduleLanguageSettingsProvider = LanguageSettingsProvider.Default /* TODO: Fix this */, + resolverForModuleFactoryByPlatform = { CommonAnalyzerFacade }, + platformParameters = object : PlatformAnalysisParameters {}, + targetEnvironment = CompilerEnvironment, + packagePartProviderFactory = { content -> + environment.createPackagePartProvider(content.moduleContentScope) }, + builtIns = DefaultBuiltIns.Instance + ) + } + + private fun createJsResolverForProject( + projectContext: ProjectContext, + module: ModuleInfo, + library: LibraryModuleInfo, + modulesContent: (ModuleInfo) -> ModuleContent + ): ResolverForProjectImpl { + return ResolverForProjectImpl( + debugName = "Dokka", + projectContext = projectContext, + modules = listOf(module, library), + modulesContent = modulesContent, modulePlatforms = { JsPlatform.multiTargetPlatform }, moduleLanguageSettingsProvider = LanguageSettingsProvider.Default /* TODO: Fix this */, resolverForModuleFactoryByPlatform = { JsAnalyzerFacade }, platformParameters = object : PlatformAnalysisParameters {}, targetEnvironment = CompilerEnvironment, + packagePartProviderFactory = { PackagePartProvider.Empty }, builtIns = JsPlatform.builtIns ) - - resolverForProject.resolverForModule(library) // Required before module to initialize library properly - val resolverForModule = resolverForProject.resolverForModule(module) - val moduleDescriptor = resolverForProject.descriptorForModule(module) - val created = DokkaResolutionFacade(environment.project, moduleDescriptor, resolverForModule) - val projectComponentManager = environment.project as MockComponentManager - projectComponentManager.registerService(KotlinCacheService::class.java, CoreKotlinCacheService(created)) - return created - } - private fun createJVMResolutionFacade(environment: KotlinCoreEnvironment): DokkaResolutionFacade { - val projectContext = ProjectContext(environment.project) - val sourceFiles = environment.getSourceFiles() - - - val library = object : ModuleInfo { - override val name: Name = Name.special("") - override fun dependencies(): List = listOf(this) - } - val module = object : ModuleInfo { - override val name: Name = Name.special("") - override fun dependencies(): List = listOf(this, library) - } - - val sourcesScope = createSourceModuleSearchScope(environment.project, sourceFiles) - - val builtIns = JvmBuiltIns(projectContext.storageManager) - - + private fun createJvmResolverForProject( + projectContext: ProjectContext, + module: ModuleInfo, + library: LibraryModuleInfo, + modulesContent: (ModuleInfo) -> ModuleContent, + sourcesScope: GlobalSearchScope, + builtIns: KotlinBuiltIns + ): ResolverForProjectImpl { val javaRoots = classpath - .mapNotNull { - val rootFile = when { - it.extension == "jar" -> - StandardFileSystems.jar().findFileByPath("${it.absolutePath}${URLUtil.JAR_SEPARATOR}") - else -> - StandardFileSystems.local().findFileByPath(it.absolutePath) - } - - rootFile?.let { JavaRoot(it, JavaRoot.RootType.BINARY) } + .mapNotNull { + val rootFile = when { + it.extension == "jar" -> + StandardFileSystems.jar().findFileByPath("${it.absolutePath}${URLUtil.JAR_SEPARATOR}") + else -> + StandardFileSystems.local().findFileByPath(it.absolutePath) } - val resolverForProject = ResolverForProjectImpl( + rootFile?.let { JavaRoot(it, JavaRoot.RootType.BINARY) } + } + + return ResolverForProjectImpl( debugName = "Dokka", projectContext = projectContext, - modules = listOf(library, module), - modulesContent = { - when (it) { - library -> ModuleContent(it, emptyList(), GlobalSearchScope.notScope(sourcesScope)) - module -> ModuleContent(it, emptyList(), sourcesScope) - else -> throw IllegalArgumentException("Unexpected module info") - } - }, + modules = listOf(module, library), + modulesContent = modulesContent, modulePlatforms = { JvmPlatform.multiTargetPlatform }, moduleLanguageSettingsProvider = LanguageSettingsProvider.Default /* TODO: Fix this */, resolverForModuleFactoryByPlatform = { JvmAnalyzerFacade }, @@ -269,7 +247,8 @@ class AnalysisEnvironment(val messageCollector: MessageCollector, val analysisPl module else library - }, + } + , targetEnvironment = CompilerEnvironment, packagePartProviderFactory = { content -> JvmPackagePartProvider(configuration.languageVersionSettings, content.moduleContentScope).apply { @@ -278,16 +257,6 @@ class AnalysisEnvironment(val messageCollector: MessageCollector, val analysisPl }, builtIns = builtIns ) - - resolverForProject.resolverForModule(library) // Required before module to initialize library properly - val resolverForModule = resolverForProject.resolverForModule(module) - val moduleDescriptor = resolverForProject.descriptorForModule(module) - builtIns.initialize(moduleDescriptor, true) - val created = DokkaResolutionFacade(environment.project, moduleDescriptor, resolverForModule) - val projectComponentManager = environment.project as MockComponentManager - projectComponentManager.registerService(KotlinCacheService::class.java, CoreKotlinCacheService(created)) - - return created } fun loadLanguageVersionSettings(languageVersionString: String?, apiVersionString: String?) { -- cgit From fe20206eecd22cb4bd4de03efc0e9c28e1981bac Mon Sep 17 00:00:00 2001 From: aleksZubakov Date: Fri, 13 Jul 2018 15:04:56 +0300 Subject: Minor style fixes --- core/src/main/kotlin/Analysis/AnalysisEnvironment.kt | 3 +-- core/src/test/kotlin/TestAPI.kt | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt b/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt index f03e9eea..3d70bd84 100644 --- a/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt +++ b/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt @@ -247,8 +247,7 @@ class AnalysisEnvironment(val messageCollector: MessageCollector, val analysisPl module else library - } - , + }, targetEnvironment = CompilerEnvironment, packagePartProviderFactory = { content -> JvmPackagePartProvider(configuration.languageVersionSettings, content.moduleContentScope).apply { diff --git a/core/src/test/kotlin/TestAPI.kt b/core/src/test/kotlin/TestAPI.kt index 7042f41b..ae69412b 100644 --- a/core/src/test/kotlin/TestAPI.kt +++ b/core/src/test/kotlin/TestAPI.kt @@ -117,8 +117,7 @@ fun appendDocumentation(documentation: DocumentationModule, fun checkSourceExistsAndVerifyModel(source: String, modelConfig: ModelConfig = ModelConfig(), - verifier: (DocumentationModule) -> Unit -) { + verifier: (DocumentationModule) -> Unit) { if (!File(source).exists()) { throw IllegalArgumentException("Can't find test data file $source") } -- cgit From d458983871a6fa6af10b86bc7529a8851a63b265 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Fri, 15 Dec 2017 00:16:10 +0300 Subject: [backport] Add class hierarchy for JLH Original: 33426ea --- core/src/main/kotlin/Model/DocumentationNode.kt | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Model/DocumentationNode.kt b/core/src/main/kotlin/Model/DocumentationNode.kt index da85cabf..897e3ad3 100644 --- a/core/src/main/kotlin/Model/DocumentationNode.kt +++ b/core/src/main/kotlin/Model/DocumentationNode.kt @@ -104,6 +104,12 @@ open class DocumentationNode(val name: String, val platforms: List get() = references(RefKind.Platform).map { it.to.name } + val supertypes: List + get() = references(RefKind.Superclass).map { it.to } + + val superclass: DocumentationNode? + get() = supertypes.find { it.kind == NodeKind.Class } + // TODO: Should we allow node mutation? Model merge will copy by ref, so references are transparent, which could nice fun addReferenceTo(to: DocumentationNode, kind: RefKind) { references.add(DocumentationReference(this, to, kind)) -- cgit From 59069606904d297a5b4c9a8a95ad88eb30f7fd4f Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Wed, 20 Dec 2017 22:27:47 +0300 Subject: [backport] Make KotlinLanguageService render parameters Original: 7899f8e --- core/src/main/kotlin/Kotlin/KotlinLanguageService.kt | 1 + 1 file changed, 1 insertion(+) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt b/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt index f33c8c96..708facdb 100644 --- a/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt +++ b/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt @@ -17,6 +17,7 @@ class KotlinLanguageService : LanguageService { NodeKind.EnumItem, NodeKind.ExternalClass -> if (renderMode == RenderMode.FULL) identifier(node.name) + NodeKind.Parameter -> renderParameter(node, renderMode) NodeKind.TypeParameter -> renderTypeParameter(node, renderMode) NodeKind.Type, NodeKind.UpperBound -> renderType(node, renderMode) -- cgit From 63ab561b66974c52a7d13e0823bf94329c0cd7f7 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Fri, 15 Dec 2017 22:05:21 +0300 Subject: [backport] Make possible to generate signatures on output format side Original: 4469044 --- .../src/main/kotlin/Kotlin/DocumentationBuilder.kt | 1 + .../main/kotlin/Kotlin/KotlinLanguageService.kt | 28 ++++++++++++---------- core/src/main/kotlin/Model/DocumentationNode.kt | 1 + 3 files changed, 17 insertions(+), 13 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt index 7b50fff5..99d4d888 100644 --- a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt +++ b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt @@ -234,6 +234,7 @@ class DocumentationBuilder val externalLink = linkResolver.externalDocumentationLinkResolver.buildExternalDocumentationLink(classifierDescriptor) if (externalLink != null) { node.append(DocumentationNode(externalLink, Content.Empty, NodeKind.ExternalLink), RefKind.Link) + node.append(DocumentationNode(classifierDescriptor.fqNameUnsafe.asString(), Content.Empty, NodeKind.QualifiedName), RefKind.Detail) } else { link(node, classifierDescriptor, if (classifierDescriptor.isBoringBuiltinClass()) RefKind.HiddenLink else RefKind.Link) diff --git a/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt b/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt index 708facdb..b6f44716 100644 --- a/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt +++ b/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt @@ -48,8 +48,7 @@ class KotlinLanguageService : LanguageService { val typeParameter = functionWithTypeParameter.details(NodeKind.TypeParameter).first() if (functionWithTypeParameter.kind == NodeKind.Function) { renderFunction(functionWithTypeParameter, RenderMode.SUMMARY, SummarizingMapper(receiverKind, typeParameter.name)) - } - else { + } else { renderProperty(functionWithTypeParameter, RenderMode.SUMMARY, SummarizingMapper(receiverKind, typeParameter.name)) } } @@ -103,7 +102,7 @@ class KotlinLanguageService : LanguageService { fun renderReceiver(receiver: DocumentationNode, to: ContentBlock) } - private class SummarizingMapper(val kind: ReceiverKind, val typeParameterName: String): SignatureMapper { + private class SummarizingMapper(val kind: ReceiverKind, val typeParameterName: String) : SignatureMapper { override fun renderReceiver(receiver: DocumentationNode, to: ContentBlock) { to.append(ContentIdentifier(kind.receiverName, IdentifierKind.SummarizedTypeName)) to.text("<$typeParameterName>") @@ -117,7 +116,7 @@ class KotlinLanguageService : LanguageService { } private fun ContentBlock.renderList(nodes: List, separator: String = ", ", - noWrap: Boolean = false, renderItem: (T) -> Unit) { + noWrap: Boolean = false, renderItem: (T) -> Unit) { if (nodes.none()) return renderItem(nodes.first()) @@ -132,7 +131,7 @@ class KotlinLanguageService : LanguageService { } } - private fun ContentBlock.renderLinked(node: DocumentationNode, body: ContentBlock.(DocumentationNode)->Unit) { + private fun ContentBlock.renderLinked(node: DocumentationNode, body: ContentBlock.(DocumentationNode) -> Unit) { val to = node.links.firstOrNull() if (to == null) body(node) @@ -216,13 +215,13 @@ class KotlinLanguageService : LanguageService { private fun ContentBlock.renderModifier(node: DocumentationNode, nowrap: Boolean = false) { when (node.name) { - "final", "public", "var" -> {} + "final", "public", "var" -> { + } else -> { keyword(node.name) if (nowrap) { nbsp() - } - else { + } else { text(" ") } } @@ -239,11 +238,12 @@ class KotlinLanguageService : LanguageService { nbsp() symbol(":") nbsp() - renderList(constraints, noWrap=true) { + renderList(constraints, noWrap = true) { renderType(it, renderMode) } } } + private fun ContentBlock.renderParameter(node: DocumentationNode, renderMode: RenderMode) { if (renderMode == RenderMode.FULL) { renderAnnotationsForNode(node) @@ -402,8 +402,7 @@ class KotlinLanguageService : LanguageService { symbol(")") symbol(": ") renderType(node.detail(NodeKind.Type), renderMode) - } - else { + } else { symbol(")") } renderExtraTypeParameterConstraints(node, renderMode) @@ -429,7 +428,7 @@ class KotlinLanguageService : LanguageService { } } - private fun needReturnType(node: DocumentationNode) = when(node.kind) { + private fun needReturnType(node: DocumentationNode) = when (node.kind) { NodeKind.Constructor -> false else -> !node.isUnitReturnType() } @@ -476,4 +475,7 @@ class KotlinLanguageService : LanguageService { } } -fun DocumentationNode.qualifiedNameFromType() = (links.firstOrNull() ?: hiddenLinks.firstOrNull())?.qualifiedName() ?: name +fun DocumentationNode.qualifiedNameFromType() = + details.firstOrNull { it.kind == NodeKind.QualifiedName }?.name + ?: (links.firstOrNull() ?: hiddenLinks.firstOrNull())?.qualifiedName() + ?: name diff --git a/core/src/main/kotlin/Model/DocumentationNode.kt b/core/src/main/kotlin/Model/DocumentationNode.kt index 897e3ad3..4b108798 100644 --- a/core/src/main/kotlin/Model/DocumentationNode.kt +++ b/core/src/main/kotlin/Model/DocumentationNode.kt @@ -48,6 +48,7 @@ enum class NodeKind { Signature, ExternalLink, + QualifiedName, Platform, AllTypes, -- cgit From e4d3abee285844c002a8984efbae0bf0be23d237 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Thu, 28 Dec 2017 19:44:56 +0300 Subject: Build supertypes via Supertype nodes, not reference --- core/src/main/kotlin/Model/DocumentationNode.kt | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Model/DocumentationNode.kt b/core/src/main/kotlin/Model/DocumentationNode.kt index 4b108798..813ff0f5 100644 --- a/core/src/main/kotlin/Model/DocumentationNode.kt +++ b/core/src/main/kotlin/Model/DocumentationNode.kt @@ -1,5 +1,6 @@ package org.jetbrains.dokka +import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult import java.util.* enum class NodeKind { @@ -106,10 +107,10 @@ open class DocumentationNode(val name: String, get() = references(RefKind.Platform).map { it.to.name } val supertypes: List - get() = references(RefKind.Superclass).map { it.to } + get() = details(NodeKind.Supertype) val superclass: DocumentationNode? - get() = supertypes.find { it.kind == NodeKind.Class } + get() = supertypes.firstNotNullResult { it.links.firstOrNull { it.kind in NodeKind.classLike } } // TODO: Should we allow node mutation? Model merge will copy by ref, so references are transparent, which could nice fun addReferenceTo(to: DocumentationNode, kind: RefKind) { -- cgit From 93ce43340730111df977921e62cae93c2bcc4a5b Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Thu, 28 Dec 2017 20:27:28 +0300 Subject: [backport] Add uri.relativeTo Original: cca63f7 --- core/src/main/kotlin/Utilities/Uri.kt | 40 +++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 core/src/main/kotlin/Utilities/Uri.kt (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Utilities/Uri.kt b/core/src/main/kotlin/Utilities/Uri.kt new file mode 100644 index 00000000..5b520188 --- /dev/null +++ b/core/src/main/kotlin/Utilities/Uri.kt @@ -0,0 +1,40 @@ +package org.jetbrains.dokka + +import java.net.URI + + +fun URI.relativeTo(uri: URI): URI { + // Normalize paths to remove . and .. segments + val base = uri.normalize() + val child = this.normalize() + + fun StringBuilder.appendRelativePath() { + // Split paths into segments + var bParts = base.path.split('/').dropLastWhile { it.isEmpty() } + val cParts = child.path.split('/').dropLastWhile { it.isEmpty() } + + // Discard trailing segment of base path + if (bParts.isNotEmpty() && !base.path.endsWith("/")) { + bParts = bParts.dropLast(1) + } + + // Compute common prefix + val commonPartsSize = bParts.zip(cParts).count { (basePart, childPart) -> basePart == childPart } + bParts.drop(commonPartsSize).joinTo(this, separator = "") { "../" } + cParts.drop(commonPartsSize).joinTo(this, separator = "/") + } + + return URI.create(buildString { + if (base.path != child.path) { + appendRelativePath() + } + child.rawQuery?.let { + append("?") + append(it) + } + child.rawFragment?.let { + append("#") + append(it) + } + }) +} \ No newline at end of file -- cgit From 87705bf24f6f7e541dbdb14c44e00d0b90a81f37 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Thu, 28 Dec 2017 21:23:27 +0300 Subject: [backport] Add package list support for JLH Original: 4256adf --- .../JavaLayoutHtmlPackageListService.kt | 28 ++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 core/src/main/kotlin/Formats/JavaLayoutHtml/JavaLayoutHtmlPackageListService.kt (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Formats/JavaLayoutHtml/JavaLayoutHtmlPackageListService.kt b/core/src/main/kotlin/Formats/JavaLayoutHtml/JavaLayoutHtmlPackageListService.kt new file mode 100644 index 00000000..398758f2 --- /dev/null +++ b/core/src/main/kotlin/Formats/JavaLayoutHtml/JavaLayoutHtmlPackageListService.kt @@ -0,0 +1,28 @@ +package org.jetbrains.dokka.Formats + +import org.jetbrains.dokka.DocumentationModule +import org.jetbrains.dokka.ExternalDocumentationLinkResolver.Companion.DOKKA_PARAM_PREFIX +import org.jetbrains.dokka.NodeKind +import org.jetbrains.dokka.PackageListService + +class JavaLayoutHtmlPackageListService: PackageListService { + + private fun StringBuilder.appendParam(name: String, value: String) { + append(DOKKA_PARAM_PREFIX) + append(name) + append(":") + appendln(value) + } + + override fun formatPackageList(module: DocumentationModule): String { + val packages = module.members(NodeKind.Package).map { it.name } + + return buildString { + appendParam("format", "java-layout-html") + for (p in packages) { + appendln(p) + } + } + } + +} \ No newline at end of file -- cgit From bd30fa4c84d749976568be00307297ab015d9b2e Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Sun, 7 Jan 2018 01:49:34 +0300 Subject: [backport] Show type parameters substitution in class hierarchy Original: a06d6a8 --- core/src/main/kotlin/Model/DocumentationNode.kt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Model/DocumentationNode.kt b/core/src/main/kotlin/Model/DocumentationNode.kt index 813ff0f5..a145ae8d 100644 --- a/core/src/main/kotlin/Model/DocumentationNode.kt +++ b/core/src/main/kotlin/Model/DocumentationNode.kt @@ -1,6 +1,5 @@ package org.jetbrains.dokka -import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult import java.util.* enum class NodeKind { @@ -110,7 +109,7 @@ open class DocumentationNode(val name: String, get() = details(NodeKind.Supertype) val superclass: DocumentationNode? - get() = supertypes.firstNotNullResult { it.links.firstOrNull { it.kind in NodeKind.classLike } } + get() = supertypes.firstOrNull { it.links.any { it.kind in NodeKind.classLike } } // TODO: Should we allow node mutation? Model merge will copy by ref, so references are transparent, which could nice fun addReferenceTo(to: DocumentationNode, kind: RefKind) { @@ -163,7 +162,7 @@ val DocumentationNode.path: List } fun DocumentationNode.findOrCreatePackageNode(packageName: String, packageContent: Map, refGraph: NodeReferenceGraph): DocumentationNode { - val existingNode = members(NodeKind.Package).firstOrNull { it.name == packageName } + val existingNode = members(NodeKind.Package).firstOrNull { it.name == packageName } if (existingNode != null) { return existingNode } @@ -181,7 +180,8 @@ fun DocumentationNode.append(child: DocumentationNode, kind: RefKind) { RefKind.Detail -> child.addReferenceTo(this, RefKind.Owner) RefKind.Member -> child.addReferenceTo(this, RefKind.Owner) RefKind.Owner -> child.addReferenceTo(this, RefKind.Member) - else -> { /* Do not add any links back for other types */ } + else -> { /* Do not add any links back for other types */ + } } } -- cgit From c776aaab9af80987e3c073a40f92de748dbd38ca Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Thu, 11 Jan 2018 22:22:36 +0300 Subject: [backport] Support deep inheritance with external classes Original: 9e65c3d --- .../src/main/kotlin/Kotlin/DocumentationBuilder.kt | 70 ++++++++++++++-------- .../main/kotlin/Kotlin/KotlinLanguageService.kt | 2 +- core/src/main/kotlin/Model/DocumentationNode.kt | 19 +++++- .../main/kotlin/Model/DocumentationReference.kt | 3 +- core/src/test/kotlin/TestAPI.kt | 48 ++++++++------- core/src/test/kotlin/model/JavaTest.kt | 2 +- 6 files changed, 92 insertions(+), 52 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt index 99d4d888..11a36a4f 100644 --- a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt +++ b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt @@ -103,6 +103,10 @@ interface DefaultPlatformsProvider { fun getDefaultPlatforms(descriptor: DeclarationDescriptor): List } +val ignoredSupertypes = setOf( + "kotlin.Annotation", "kotlin.Enum", "kotlin.Any" +) + class DocumentationBuilder @Inject constructor(val resolutionFacade: DokkaResolutionFacade, val descriptorDocumentationParser: DescriptorDocumentationParser, @@ -173,7 +177,7 @@ class DocumentationBuilder val unwrappedType = superType.unwrap() if (unwrappedType is AbbreviatedType) { appendSupertype(descriptor, unwrappedType.abbreviation) - } else if (!ignoreSupertype(unwrappedType)) { + } else { appendType(unwrappedType, NodeKind.Supertype) val superclass = unwrappedType.constructor.declarationDescriptor link(superclass, descriptor, RefKind.Inheritor) @@ -181,15 +185,6 @@ class DocumentationBuilder } } - private fun ignoreSupertype(superType: KotlinType): Boolean { - val superClass = superType.constructor.declarationDescriptor as? ClassDescriptor - if (superClass != null) { - val fqName = DescriptorUtils.getFqNameSafe(superClass).asString() - return fqName == "kotlin.Annotation" || fqName == "kotlin.Enum" || fqName == "kotlin.Any" - } - return false - } - fun DocumentationNode.appendProjection(projection: TypeProjection, kind: NodeKind = NodeKind.Type) { if (projection.isStarProjection) { appendTextNode("*", NodeKind.Type) @@ -233,14 +228,25 @@ class DocumentationBuilder if (classifierDescriptor != null) { val externalLink = linkResolver.externalDocumentationLinkResolver.buildExternalDocumentationLink(classifierDescriptor) if (externalLink != null) { + val targetNode = refGraph.lookup(classifierDescriptor.signature()) ?: classifierDescriptor.build(true) node.append(DocumentationNode(externalLink, Content.Empty, NodeKind.ExternalLink), RefKind.Link) - node.append(DocumentationNode(classifierDescriptor.fqNameUnsafe.asString(), Content.Empty, NodeKind.QualifiedName), RefKind.Detail) + node.append(targetNode, RefKind.ExternalType) } else { link(node, classifierDescriptor, if (classifierDescriptor.isBoringBuiltinClass()) RefKind.HiddenLink else RefKind.Link) } + if (classifierDescriptor !is TypeParameterDescriptor) { + node.append( + DocumentationNode( + classifierDescriptor.fqNameUnsafe.asString(), + Content.Empty, + NodeKind.QualifiedName + ), RefKind.Detail + ) + } } + append(node, RefKind.Detail) node.appendAnnotations(kotlinType) for (typeArgument in kotlinType.arguments) { @@ -496,34 +502,42 @@ class DocumentationBuilder } fun DeclarationDescriptor.build(): DocumentationNode = when (this) { - is ClassDescriptor -> build() + is ClassifierDescriptor -> build() is ConstructorDescriptor -> build() is PropertyDescriptor -> build() is FunctionDescriptor -> build() - is TypeParameterDescriptor -> build() is ValueParameterDescriptor -> build() is ReceiverParameterDescriptor -> build() - is TypeAliasDescriptor -> build() else -> throw IllegalStateException("Descriptor $this is not known") } - fun TypeAliasDescriptor.build(): DocumentationNode { + fun ClassifierDescriptor.build(external: Boolean = false): DocumentationNode = when (this) { + is ClassDescriptor -> build(external) + is TypeAliasDescriptor -> build(external) + is TypeParameterDescriptor -> build() + else -> throw IllegalStateException("Descriptor $this is not known") + } + + fun TypeAliasDescriptor.build(external: Boolean = false): DocumentationNode { val node = nodeForDescriptor(this, NodeKind.TypeAlias) - node.appendAnnotations(this) + if (!external) { + node.appendAnnotations(this) + } node.appendModifiers(this) node.appendInPageChildren(typeConstructor.parameters, RefKind.Detail) node.appendType(underlyingType, NodeKind.TypeAliasUnderlyingType) - node.appendSourceLink(source) - node.appendDefaultPlatforms(this) - + if (!external) { + node.appendSourceLink(source) + node.appendDefaultPlatforms(this) + } register(this, node) return node } - fun ClassDescriptor.build(): DocumentationNode { + fun ClassDescriptor.build(external: Boolean = false): DocumentationNode { val kind = when { kind == ClassKind.OBJECT -> NodeKind.Object kind == ClassKind.INTERFACE -> NodeKind.Interface @@ -534,20 +548,24 @@ class DocumentationBuilder else -> NodeKind.Class } val node = nodeForDescriptor(this, kind) + register(this, node) typeConstructor.supertypes.forEach { node.appendSupertype(this, it) } if (getKind() != ClassKind.OBJECT && getKind() != ClassKind.ENUM_ENTRY) { node.appendInPageChildren(typeConstructor.parameters, RefKind.Detail) } - for ((descriptor, inheritedLinkKind, extraModifier) in collectMembersToDocument()) { - node.appendClassMember(descriptor, inheritedLinkKind, extraModifier) + if (!external) { + for ((descriptor, inheritedLinkKind, extraModifier) in collectMembersToDocument()) { + node.appendClassMember(descriptor, inheritedLinkKind, extraModifier) + } + node.appendAnnotations(this) } - node.appendAnnotations(this) node.appendModifiers(this) - node.appendSourceLink(source) - node.appendDefaultPlatforms(this) - register(this, node) + if (!external) { + node.appendSourceLink(source) + node.appendDefaultPlatforms(this) + } return node } diff --git a/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt b/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt index b6f44716..aa185de7 100644 --- a/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt +++ b/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt @@ -291,7 +291,7 @@ class KotlinLanguageService : LanguageService { } private fun ContentBlock.renderSupertypesForNode(node: DocumentationNode, renderMode: RenderMode) { - val supertypes = node.details(NodeKind.Supertype) + val supertypes = node.details(NodeKind.Supertype).filterNot { it.qualifiedNameFromType() in ignoredSupertypes } if (supertypes.any()) { nbsp() symbol(":") diff --git a/core/src/main/kotlin/Model/DocumentationNode.kt b/core/src/main/kotlin/Model/DocumentationNode.kt index a145ae8d..a792460f 100644 --- a/core/src/main/kotlin/Model/DocumentationNode.kt +++ b/core/src/main/kotlin/Model/DocumentationNode.kt @@ -104,12 +104,27 @@ open class DocumentationNode(val name: String, get() = references(RefKind.Deprecation).singleOrNull()?.to val platforms: List get() = references(RefKind.Platform).map { it.to.name } + val externalType: DocumentationNode? + get() = references(RefKind.ExternalType).map { it.to }.firstOrNull() val supertypes: List get() = details(NodeKind.Supertype) - val superclass: DocumentationNode? - get() = supertypes.firstOrNull { it.links.any { it.kind in NodeKind.classLike } } + val superclassType: DocumentationNode? + get() = when (kind) { + NodeKind.Supertype -> (links.firstOrNull { it.kind in NodeKind.classLike } ?: externalType)?.superclassType + NodeKind.Interface -> null + in NodeKind.classLike -> supertypes.firstOrNull { + it.links.any { it.kind in NodeKind.classLike } || + it.externalType != null + } + else -> null + } + + val superclassTypeSequence: Sequence + get() = generateSequence(superclassType) { + it.superclassType + } // TODO: Should we allow node mutation? Model merge will copy by ref, so references are transparent, which could nice fun addReferenceTo(to: DocumentationNode, kind: RefKind) { diff --git a/core/src/main/kotlin/Model/DocumentationReference.kt b/core/src/main/kotlin/Model/DocumentationReference.kt index a968f400..b0f011be 100644 --- a/core/src/main/kotlin/Model/DocumentationReference.kt +++ b/core/src/main/kotlin/Model/DocumentationReference.kt @@ -18,7 +18,8 @@ enum class RefKind { HiddenAnnotation, Deprecation, TopLevelPage, - Platform + Platform, + ExternalType } data class DocumentationReference(val from: DocumentationNode, val to: DocumentationNode, val kind: RefKind) { diff --git a/core/src/test/kotlin/TestAPI.kt b/core/src/test/kotlin/TestAPI.kt index aa3eff48..559b715e 100644 --- a/core/src/test/kotlin/TestAPI.kt +++ b/core/src/test/kotlin/TestAPI.kt @@ -6,7 +6,6 @@ import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.io.FileUtil import com.intellij.rt.execution.junit.FileComparisonFailure import org.jetbrains.dokka.* -import org.jetbrains.dokka.DokkaConfiguration.SourceLinkDefinition import org.jetbrains.dokka.Utilities.DokkaAnalysisModule import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity @@ -25,6 +24,7 @@ fun verifyModel(vararg roots: ContentRoot, format: String = "html", includeNonPublic: Boolean = true, perPackageOptions: List = emptyList(), + noStdlibLink: Boolean = true, verifier: (DocumentationModule) -> Unit) { val documentation = DocumentationModule("test") @@ -37,7 +37,7 @@ fun verifyModel(vararg roots: ContentRoot, sourceLinks = listOf(), perPackageOptions = perPackageOptions, generateIndexPages = false, - noStdlibLink = true, + noStdlibLink = noStdlibLink, cacheRoot = "default", languageVersion = null, apiVersion = null @@ -161,13 +161,15 @@ fun verifyOutput(roots: Array, withKotlinRuntime: Boolean = false, format: String = "html", includeNonPublic: Boolean = true, + noStdlibLink: Boolean = true, outputGenerator: (DocumentationModule, StringBuilder) -> Unit) { verifyModel( - *roots, - withJdk = withJdk, - withKotlinRuntime = withKotlinRuntime, - format = format, - includeNonPublic = includeNonPublic + *roots, + withJdk = withJdk, + withKotlinRuntime = withKotlinRuntime, + format = format, + includeNonPublic = includeNonPublic, + noStdlibLink = noStdlibLink ) { verifyModelOutput(it, outputExtension, roots.first().path, outputGenerator) } @@ -184,21 +186,25 @@ fun verifyModelOutput(it: DocumentationModule, assertEqualsIgnoringSeparators(expectedFile, output.toString()) } -fun verifyOutput(path: String, - outputExtension: String, - withJdk: Boolean = false, - withKotlinRuntime: Boolean = false, - format: String = "html", - includeNonPublic: Boolean = true, - outputGenerator: (DocumentationModule, StringBuilder) -> Unit) { +fun verifyOutput( + path: String, + outputExtension: String, + withJdk: Boolean = false, + withKotlinRuntime: Boolean = false, + format: String = "html", + includeNonPublic: Boolean = true, + noStdlibLink: Boolean = true, + outputGenerator: (DocumentationModule, StringBuilder) -> Unit +) { verifyOutput( - arrayOf(contentRootFromPath(path)), - outputExtension, - withJdk, - withKotlinRuntime, - format, - includeNonPublic, - outputGenerator + arrayOf(contentRootFromPath(path)), + outputExtension, + withJdk, + withKotlinRuntime, + format, + includeNonPublic, + noStdlibLink, + outputGenerator ) } diff --git a/core/src/test/kotlin/model/JavaTest.kt b/core/src/test/kotlin/model/JavaTest.kt index e6c22ee4..c2ede8f0 100644 --- a/core/src/test/kotlin/model/JavaTest.kt +++ b/core/src/test/kotlin/model/JavaTest.kt @@ -193,7 +193,7 @@ public class JavaTest { @Test fun enumValues() { verifyJavaPackageMember("testdata/java/enumValues.java") { cls -> val superTypes = cls.details(NodeKind.Supertype) - assertEquals(0, superTypes.size) + assertEquals(1, superTypes.size) assertEquals(1, cls.members(NodeKind.EnumItem).size) } } -- cgit From 1391dcca35a871881420c53755fed08bf47e4087 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Wed, 17 Jan 2018 20:01:20 +0300 Subject: [backport] Support propagating inherited extensions from libraries Original: bf2945d --- core/src/main/kotlin/DokkaBootstrapImpl.kt | 3 +- core/src/main/kotlin/Generation/DokkaGenerator.kt | 2 + .../main/kotlin/Generation/configurationImpl.kt | 47 ++--- .../src/main/kotlin/Kotlin/DocumentationBuilder.kt | 200 ++++++++++++++++----- .../Kotlin/ExternalDocumentationLinkResolver.kt | 2 +- core/src/main/kotlin/Model/DocumentationNode.kt | 2 + core/src/test/kotlin/TestAPI.kt | 32 ++-- .../kotlin/org/jetbrains/dokka/configuration.kt | 48 ++--- runners/cli/src/main/kotlin/cli/main.kt | 28 +-- runners/gradle-plugin/src/main/kotlin/main.kt | 51 +++--- 10 files changed, 273 insertions(+), 142 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/DokkaBootstrapImpl.kt b/core/src/main/kotlin/DokkaBootstrapImpl.kt index aeaca8be..b7787be8 100644 --- a/core/src/main/kotlin/DokkaBootstrapImpl.kt +++ b/core/src/main/kotlin/DokkaBootstrapImpl.kt @@ -69,7 +69,8 @@ class DokkaBootstrapImpl : DokkaBootstrap { languageVersion, apiVersion, cacheRoot, - suppressedFiles.map { File(it) }.toSet() + suppressedFiles.map { File(it) }.toSet(), + collectInheritedExtensionsFromLibraries ) ) } diff --git a/core/src/main/kotlin/Generation/DokkaGenerator.kt b/core/src/main/kotlin/Generation/DokkaGenerator.kt index 09e5cedf..33170f35 100644 --- a/core/src/main/kotlin/Generation/DokkaGenerator.kt +++ b/core/src/main/kotlin/Generation/DokkaGenerator.kt @@ -160,6 +160,8 @@ fun buildDocumentationModule(injector: Injector, with(injector.getInstance(DocumentationBuilder::class.java)) { documentationModule.appendFragments(fragments, packageDocs.packageContent, injector.getInstance(PackageDocumentationBuilder::class.java)) + + propagateExtensionFunctionsToSubclasses(fragments, resolutionFacade) } val javaFiles = coreEnvironment.getJavaSourceFiles().filter(filesToDocumentFilter) diff --git a/core/src/main/kotlin/Generation/configurationImpl.kt b/core/src/main/kotlin/Generation/configurationImpl.kt index 34d4154e..52e8446f 100644 --- a/core/src/main/kotlin/Generation/configurationImpl.kt +++ b/core/src/main/kotlin/Generation/configurationImpl.kt @@ -36,27 +36,28 @@ data class PackageOptionsImpl(override val prefix: String, override val suppress: Boolean = false) : DokkaConfiguration.PackageOptions data class DokkaConfigurationImpl( - override val moduleName: String, - override val classpath: List, - override val sourceRoots: List, - override val samples: List, - override val includes: List, - override val outputDir: String, - override val format: String, - override val includeNonPublic: Boolean, - override val includeRootPackage: Boolean, - override val reportUndocumented: Boolean, - override val skipEmptyPackages: Boolean, - override val skipDeprecated: Boolean, - override val jdkVersion: Int, - override val generateIndexPages: Boolean, - override val sourceLinks: List, - override val impliedPlatforms: List, - override val perPackageOptions: List, - override val externalDocumentationLinks: List, - override val noStdlibLink: Boolean, - override val cacheRoot: String?, - override val suppressedFiles: List, - override val languageVersion: String?, - override val apiVersion: String? + override val moduleName: String, + override val classpath: List, + override val sourceRoots: List, + override val samples: List, + override val includes: List, + override val outputDir: String, + override val format: String, + override val includeNonPublic: Boolean, + override val includeRootPackage: Boolean, + override val reportUndocumented: Boolean, + override val skipEmptyPackages: Boolean, + override val skipDeprecated: Boolean, + override val jdkVersion: Int, + override val generateIndexPages: Boolean, + override val sourceLinks: List, + override val impliedPlatforms: List, + override val perPackageOptions: List, + override val externalDocumentationLinks: List, + override val noStdlibLink: Boolean, + override val cacheRoot: String?, + override val suppressedFiles: List, + override val languageVersion: String?, + override val apiVersion: String?, + override val collectInheritedExtensionsFromLibraries: Boolean ) : DokkaConfiguration \ No newline at end of file diff --git a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt index 11a36a4f..125f9fd4 100644 --- a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt +++ b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt @@ -11,6 +11,9 @@ import org.jetbrains.kotlin.descriptors.annotations.Annotated import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor import org.jetbrains.kotlin.descriptors.impl.EnumEntrySyntheticClassDescriptor import org.jetbrains.kotlin.idea.kdoc.findKDoc +import org.jetbrains.kotlin.idea.util.fuzzyExtensionReceiverType +import org.jetbrains.kotlin.idea.util.makeNotNullable +import org.jetbrains.kotlin.idea.util.toFuzzyType import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi import org.jetbrains.kotlin.kdoc.psi.impl.KDocSection import org.jetbrains.kotlin.lexer.KtTokens @@ -25,10 +28,11 @@ import org.jetbrains.kotlin.resolve.constants.ConstantValue import org.jetbrains.kotlin.resolve.descriptorUtil.* import org.jetbrains.kotlin.resolve.findTopMostOverriddenDescriptors import org.jetbrains.kotlin.resolve.jvm.JavaDescriptorResolver +import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter +import org.jetbrains.kotlin.resolve.scopes.getDescriptorsFiltered import org.jetbrains.kotlin.resolve.source.PsiSourceElement import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.types.* -import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf import org.jetbrains.kotlin.types.typeUtil.supertypes import java.io.File import java.nio.file.Path @@ -53,7 +57,8 @@ class DocumentationOptions(val outputDir: String, val languageVersion: String?, val apiVersion: String?, cacheRoot: String? = null, - val suppressedFiles: Set = emptySet()) { + val suppressedFiles: Set = emptySet(), + val collectInheritedExtensionsFromLibraries: Boolean = false) { init { if (perPackageOptions.any { it.prefix == "" }) throw IllegalArgumentException("Please do not register packageOptions with all match pattern, use global settings instead") @@ -138,8 +143,20 @@ class DocumentationBuilder refGraph.register(descriptor.signature(), node) } - fun nodeForDescriptor(descriptor: T, kind: NodeKind): DocumentationNode where T : DeclarationDescriptor, T : Named { - val (doc, callback) = descriptorDocumentationParser.parseDocumentationAndDetails(descriptor, kind == NodeKind.Parameter) + fun nodeForDescriptor( + descriptor: T, + kind: NodeKind, + external: Boolean = false + ): DocumentationNode where T : DeclarationDescriptor, T : Named { + val (doc, callback) = + if (external) { + Content.Empty to { node -> } + } else { + descriptorDocumentationParser.parseDocumentationAndDetails( + descriptor, + kind == NodeKind.Parameter + ) + } val node = DocumentationNode(descriptor.name.asString(), doc, kind).withModifiers(descriptor) node.appendSignature(descriptor) callback(node) @@ -226,14 +243,20 @@ class DocumentationBuilder node.appendTextNode("?", NodeKind.NullabilityModifier) } if (classifierDescriptor != null) { - val externalLink = linkResolver.externalDocumentationLinkResolver.buildExternalDocumentationLink(classifierDescriptor) + val externalLink = + linkResolver.externalDocumentationLinkResolver.buildExternalDocumentationLink(classifierDescriptor) if (externalLink != null) { - val targetNode = refGraph.lookup(classifierDescriptor.signature()) ?: classifierDescriptor.build(true) - node.append(DocumentationNode(externalLink, Content.Empty, NodeKind.ExternalLink), RefKind.Link) - node.append(targetNode, RefKind.ExternalType) + if (classifierDescriptor !is TypeParameterDescriptor) { + val targetNode = + refGraph.lookup(classifierDescriptor.signature()) ?: classifierDescriptor.build(true) + node.append(targetNode, RefKind.ExternalType) + node.append(DocumentationNode(externalLink, Content.Empty, NodeKind.ExternalLink), RefKind.Link) + } } else { - link(node, classifierDescriptor, - if (classifierDescriptor.isBoringBuiltinClass()) RefKind.HiddenLink else RefKind.Link) + link( + node, classifierDescriptor, + if (classifierDescriptor.isBoringBuiltinClass()) RefKind.HiddenLink else RefKind.Link + ) } if (classifierDescriptor !is TypeParameterDescriptor) { node.append( @@ -280,6 +303,17 @@ class DocumentationBuilder } } + fun DocumentationNode.appendExternalLink(externalLink: String) { + append(DocumentationNode(externalLink, Content.Empty, NodeKind.ExternalLink), RefKind.Link) + } + + fun DocumentationNode.appendExternalLink(descriptor: DeclarationDescriptor) { + val target = linkResolver.externalDocumentationLinkResolver.buildExternalDocumentationLink(descriptor) + if (target != null) { + appendExternalLink(target) + } + } + fun DocumentationNode.appendSinceKotlin(annotation: DocumentationNode) { val kotlinVersion = annotation .detail(NodeKind.Parameter) @@ -426,15 +460,44 @@ class DocumentationBuilder declarations, allFqNames) } - propagateExtensionFunctionsToSubclasses(fragments) } - private fun propagateExtensionFunctionsToSubclasses(fragments: Collection) { - val allDescriptors = fragments.flatMap { it.getMemberScope().getContributedDescriptors() } - val allClasses = allDescriptors.filterIsInstance() - val classHierarchy = buildClassHierarchy(allClasses) + fun propagateExtensionFunctionsToSubclasses( + fragments: Collection, + resolutionFacade: DokkaResolutionFacade + ) { + + val moduleDescriptor = resolutionFacade.moduleDescriptor + + // Wide-collect all view descriptors + val allPackageViewDescriptors = generateSequence(listOf(moduleDescriptor.getPackage(FqName.ROOT))) { packages -> + packages + .flatMap { pkg -> + moduleDescriptor.getSubPackagesOf(pkg.fqName) { true } + }.map { fqName -> + moduleDescriptor.getPackage(fqName) + }.takeUnless { it.isEmpty() } + }.flatten() + + val allDescriptors = + if (options.collectInheritedExtensionsFromLibraries) { + allPackageViewDescriptors.map { it.memberScope } + } else { + fragments.asSequence().map { it.getMemberScope() } + }.flatMap { + it.getDescriptorsFiltered( + DescriptorKindFilter.CALLABLES + ).asSequence() + } + - val allExtensionFunctions = allDescriptors + val documentingDescriptors = fragments.flatMap { it.getMemberScope().getContributedDescriptors() } + val documentingClasses = documentingDescriptors.filterIsInstance() + + val classHierarchy = buildClassHierarchy(documentingClasses) + + val allExtensionFunctions = + allDescriptors .filterIsInstance() .filter { it.extensionReceiverParameter != null } val extensionFunctionsByName = allExtensionFunctions.groupBy { it.name } @@ -442,15 +505,31 @@ class DocumentationBuilder for (extensionFunction in allExtensionFunctions) { if (extensionFunction.dispatchReceiverParameter != null) continue val possiblyShadowingFunctions = extensionFunctionsByName[extensionFunction.name] - ?.filter { fn -> fn.canShadow(extensionFunction) } + ?.filter { fn -> fn.canShadow(extensionFunction) } ?: emptyList() if (extensionFunction.extensionReceiverParameter?.type?.isDynamic() == true) continue - val classDescriptor = extensionFunction.getExtensionClassDescriptor() ?: continue - val subclasses = classHierarchy[classDescriptor] ?: continue - subclasses.forEach { subclass -> + val subclasses = + classHierarchy.filter { (key) -> key.isExtensionApplicable(extensionFunction) } + if (subclasses.isEmpty()) continue + subclasses.values.flatten().forEach { subclass -> if (subclass.isExtensionApplicable(extensionFunction) && - possiblyShadowingFunctions.none { subclass.isExtensionApplicable(it) }) { + possiblyShadowingFunctions.none { subclass.isExtensionApplicable(it) }) { + + val hasExternalLink = + linkResolver.externalDocumentationLinkResolver.buildExternalDocumentationLink( + extensionFunction + ) != null + if (hasExternalLink) { + val containerDesc = + extensionFunction.containingDeclaration as? PackageFragmentDescriptor + if (containerDesc != null) { + val container = refGraph.lookup(containerDesc.signature()) + ?: containerDesc.buildExternal() + container.append(extensionFunction.buildExternal(), RefKind.Member) + } + } + refGraph.link(subclass.signature(), extensionFunction.signature(), RefKind.Extension) } } @@ -458,12 +537,9 @@ class DocumentationBuilder } private fun ClassDescriptor.isExtensionApplicable(extensionFunction: CallableMemberDescriptor): Boolean { - val receiverType = extensionFunction.extensionReceiverParameter!!.type - if (receiverType.arguments.any { it.type.constructor.declarationDescriptor is TypeParameterDescriptor }) { - val receiverClass = receiverType.constructor.declarationDescriptor - return receiverClass is ClassDescriptor && DescriptorUtils.isSubclass(this, receiverClass) - } - return defaultType.isSubtypeOf(receiverType) + val receiverType = extensionFunction.fuzzyExtensionReceiverType()?.makeNotNullable() + val classType = defaultType.toFuzzyType(declaredTypeParameters) + return receiverType != null && classType.checkIsSubtypeOf(receiverType) != null } private fun buildClassHierarchy(classes: List): Map> { @@ -511,6 +587,24 @@ class DocumentationBuilder else -> throw IllegalStateException("Descriptor $this is not known") } + fun PackageFragmentDescriptor.buildExternal(): DocumentationNode { + val node = DocumentationNode(fqName.asString(), Content.Empty, NodeKind.Package) + + val externalLink = linkResolver.externalDocumentationLinkResolver.buildExternalDocumentationLink(this) + if (externalLink != null) { + node.append(DocumentationNode(externalLink, Content.Empty, NodeKind.ExternalLink), RefKind.Link) + } + register(this, node) + return node + } + + fun CallableDescriptor.buildExternal(): DocumentationNode = when(this) { + is FunctionDescriptor -> build(true) + is PropertyDescriptor -> build(true) + else -> throw IllegalStateException("Descriptor $this is not known") + } + + fun ClassifierDescriptor.build(external: Boolean = false): DocumentationNode = when (this) { is ClassDescriptor -> build(external) is TypeAliasDescriptor -> build(external) @@ -547,7 +641,7 @@ class DocumentationBuilder isSubclassOfThrowable() -> NodeKind.Exception else -> NodeKind.Class } - val node = nodeForDescriptor(this, kind) + val node = nodeForDescriptor(this, kind, external) register(this, node) typeConstructor.supertypes.forEach { node.appendSupertype(this, it) @@ -632,12 +726,12 @@ class DocumentationBuilder return (receiver?.type?.constructor?.declarationDescriptor as? ClassDescriptor)?.isCompanionObject ?: false } - fun FunctionDescriptor.build(): DocumentationNode { + fun FunctionDescriptor.build(external: Boolean = false): DocumentationNode { if (ErrorUtils.containsErrorType(this)) { logger.warn("Found an unresolved type in ${signatureWithSourceLocation()}") } - val node = nodeForDescriptor(this, if (inCompanionObject()) NodeKind.CompanionObjectFunction else NodeKind.Function) + val node = nodeForDescriptor(this, if (inCompanionObject()) NodeKind.CompanionObjectFunction else NodeKind.Function, external) node.appendInPageChildren(typeParameters, RefKind.Detail) extensionReceiverParameter?.let { node.appendChild(it, RefKind.Detail) } @@ -645,8 +739,12 @@ class DocumentationBuilder node.appendType(returnType) node.appendAnnotations(this) node.appendModifiers(this) - node.appendSourceLink(source) - node.appendDefaultPlatforms(this) + if (!external) { + node.appendSourceLink(source) + node.appendDefaultPlatforms(this) + } else { + node.appendExternalLink(this) + } overriddenDescriptors.forEach { addOverrideLink(it, this) @@ -667,32 +765,42 @@ class DocumentationBuilder } } - fun PropertyDescriptor.build(): DocumentationNode { - val node = nodeForDescriptor(this, if (inCompanionObject()) NodeKind.CompanionObjectProperty else NodeKind.Property) + fun PropertyDescriptor.build(external: Boolean = false): DocumentationNode { + val node = nodeForDescriptor( + this, + if (inCompanionObject()) NodeKind.CompanionObjectProperty else NodeKind.Property, + external + ) node.appendInPageChildren(typeParameters, RefKind.Detail) extensionReceiverParameter?.let { node.appendChild(it, RefKind.Detail) } node.appendType(returnType) node.appendAnnotations(this) node.appendModifiers(this) - node.appendSourceLink(source) - if (isVar) { - node.appendTextNode("var", NodeKind.Modifier) - } - getter?.let { - if (!it.isDefault) { - node.addAccessorDocumentation(descriptorDocumentationParser.parseDocumentation(it), "Getter") + if (!external) { + node.appendSourceLink(source) + if (isVar) { + node.appendTextNode("var", NodeKind.Modifier) } - } - setter?.let { - if (!it.isDefault) { - node.addAccessorDocumentation(descriptorDocumentationParser.parseDocumentation(it), "Setter") + + getter?.let { + if (!it.isDefault) { + node.addAccessorDocumentation(descriptorDocumentationParser.parseDocumentation(it), "Getter") + } } + setter?.let { + if (!it.isDefault) { + node.addAccessorDocumentation(descriptorDocumentationParser.parseDocumentation(it), "Setter") + } + } + node.appendDefaultPlatforms(this) + } + if (external) { + node.appendExternalLink(this) } overriddenDescriptors.forEach { addOverrideLink(it, this) } - node.appendDefaultPlatforms(this) register(this, node) return node diff --git a/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt b/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt index e19ecf76..400326d2 100644 --- a/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt +++ b/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt @@ -155,8 +155,8 @@ class ExternalDocumentationLinkResolver @Inject constructor( fun buildExternalDocumentationLink(symbol: DeclarationDescriptor): String? { val packageFqName: FqName = when (symbol) { - is DeclarationDescriptorNonRoot -> symbol.parents.firstOrNull { it is PackageFragmentDescriptor }?.fqNameSafe ?: return null is PackageFragmentDescriptor -> symbol.fqName + is DeclarationDescriptorNonRoot -> symbol.parents.firstOrNull { it is PackageFragmentDescriptor }?.fqNameSafe ?: return null else -> return null } diff --git a/core/src/main/kotlin/Model/DocumentationNode.kt b/core/src/main/kotlin/Model/DocumentationNode.kt index a792460f..85ecdf87 100644 --- a/core/src/main/kotlin/Model/DocumentationNode.kt +++ b/core/src/main/kotlin/Model/DocumentationNode.kt @@ -209,6 +209,8 @@ fun DocumentationNode.appendTextNode(text: String, fun DocumentationNode.qualifiedName(): String { if (kind == NodeKind.Type) { return qualifiedNameFromType() + } else if (kind == NodeKind.Package) { + return name } return path.drop(1).map { it.name }.filter { it.length > 0 }.joinToString(".") } diff --git a/core/src/test/kotlin/TestAPI.kt b/core/src/test/kotlin/TestAPI.kt index 559b715e..aeff9284 100644 --- a/core/src/test/kotlin/TestAPI.kt +++ b/core/src/test/kotlin/TestAPI.kt @@ -25,22 +25,24 @@ fun verifyModel(vararg roots: ContentRoot, includeNonPublic: Boolean = true, perPackageOptions: List = emptyList(), noStdlibLink: Boolean = true, + collectInheritedExtensionsFromLibraries: Boolean = false, verifier: (DocumentationModule) -> Unit) { val documentation = DocumentationModule("test") val options = DocumentationOptions( - "", - format, - includeNonPublic = includeNonPublic, - skipEmptyPackages = false, - includeRootPackage = true, - sourceLinks = listOf(), - perPackageOptions = perPackageOptions, - generateIndexPages = false, - noStdlibLink = noStdlibLink, - cacheRoot = "default", - languageVersion = null, - apiVersion = null + "", + format, + includeNonPublic = includeNonPublic, + skipEmptyPackages = false, + includeRootPackage = true, + sourceLinks = listOf(), + perPackageOptions = perPackageOptions, + generateIndexPages = false, + noStdlibLink = noStdlibLink, + cacheRoot = "default", + languageVersion = null, + apiVersion = null, + collectInheritedExtensionsFromLibraries = collectInheritedExtensionsFromLibraries ) appendDocumentation(documentation, *roots, @@ -162,6 +164,7 @@ fun verifyOutput(roots: Array, format: String = "html", includeNonPublic: Boolean = true, noStdlibLink: Boolean = true, + collectInheritedExtensionsFromLibraries: Boolean = false, outputGenerator: (DocumentationModule, StringBuilder) -> Unit) { verifyModel( *roots, @@ -169,7 +172,8 @@ fun verifyOutput(roots: Array, withKotlinRuntime = withKotlinRuntime, format = format, includeNonPublic = includeNonPublic, - noStdlibLink = noStdlibLink + noStdlibLink = noStdlibLink, + collectInheritedExtensionsFromLibraries = collectInheritedExtensionsFromLibraries ) { verifyModelOutput(it, outputExtension, roots.first().path, outputGenerator) } @@ -194,6 +198,7 @@ fun verifyOutput( format: String = "html", includeNonPublic: Boolean = true, noStdlibLink: Boolean = true, + collectInheritedExtensionsFromLibraries: Boolean = false, outputGenerator: (DocumentationModule, StringBuilder) -> Unit ) { verifyOutput( @@ -204,6 +209,7 @@ fun verifyOutput( format, includeNonPublic, noStdlibLink, + collectInheritedExtensionsFromLibraries, outputGenerator ) } diff --git a/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt b/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt index 90e5b5fc..46a57278 100644 --- a/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt +++ b/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt @@ -41,6 +41,7 @@ interface DokkaConfiguration { val noStdlibLink: Boolean val cacheRoot: String? val suppressedFiles: List + val collectInheritedExtensionsFromLibraries: Boolean interface SourceRoot { val path: String @@ -82,29 +83,30 @@ interface DokkaConfiguration { } data class SerializeOnlyDokkaConfiguration( - override val moduleName: String, - override val classpath: List, - override val sourceRoots: List, - override val samples: List, - override val includes: List, - override val outputDir: String, - override val format: String, - override val includeNonPublic: Boolean, - override val includeRootPackage: Boolean, - override val reportUndocumented: Boolean, - override val skipEmptyPackages: Boolean, - override val skipDeprecated: Boolean, - override val jdkVersion: Int, - override val generateIndexPages: Boolean, - override val sourceLinks: List, - override val impliedPlatforms: List, - override val perPackageOptions: List, - override val externalDocumentationLinks: List, - override val noStdlibLink: Boolean, - override val cacheRoot: String?, - override val suppressedFiles: List, - override val languageVersion: String?, - override val apiVersion: String? + override val moduleName: String, + override val classpath: List, + override val sourceRoots: List, + override val samples: List, + override val includes: List, + override val outputDir: String, + override val format: String, + override val includeNonPublic: Boolean, + override val includeRootPackage: Boolean, + override val reportUndocumented: Boolean, + override val skipEmptyPackages: Boolean, + override val skipDeprecated: Boolean, + override val jdkVersion: Int, + override val generateIndexPages: Boolean, + override val sourceLinks: List, + override val impliedPlatforms: List, + override val perPackageOptions: List, + override val externalDocumentationLinks: List, + override val noStdlibLink: Boolean, + override val cacheRoot: String?, + override val suppressedFiles: List, + override val languageVersion: String?, + override val apiVersion: String?, + override val collectInheritedExtensionsFromLibraries: Boolean ) : DokkaConfiguration diff --git a/runners/cli/src/main/kotlin/cli/main.kt b/runners/cli/src/main/kotlin/cli/main.kt index fe945ed3..111e1420 100644 --- a/runners/cli/src/main/kotlin/cli/main.kt +++ b/runners/cli/src/main/kotlin/cli/main.kt @@ -62,6 +62,9 @@ class DokkaArguments { @set:Argument(value = "apiVersion", description = "Kotlin Api Version to pass to Kotlin Analysis") var apiVersion: String? = null + @set:Argument(value = "collectInheritedExtensionsFromLibraries", description = "Search for applicable extensions in libraries") + var collectInheritedExtensionsFromLibraries: Boolean = false + } @@ -106,18 +109,19 @@ object MainKt { val classPath = arguments.classpath.split(File.pathSeparatorChar).toList() val documentationOptions = DocumentationOptions( - arguments.outputDir.let { if (it.endsWith('/')) it else it + '/' }, - arguments.outputFormat, - skipDeprecated = arguments.nodeprecated, - sourceLinks = sourceLinks, - impliedPlatforms = arguments.impliedPlatforms.split(','), - perPackageOptions = parsePerPackageOptions(arguments.packageOptions), - jdkVersion = arguments.jdkVersion, - externalDocumentationLinks = parseLinks(arguments.links), - noStdlibLink = arguments.noStdlibLink, - cacheRoot = arguments.cacheRoot, - languageVersion = arguments.languageVersion, - apiVersion = arguments.apiVersion + arguments.outputDir.let { if (it.endsWith('/')) it else it + '/' }, + arguments.outputFormat, + skipDeprecated = arguments.nodeprecated, + sourceLinks = sourceLinks, + impliedPlatforms = arguments.impliedPlatforms.split(','), + perPackageOptions = parsePerPackageOptions(arguments.packageOptions), + jdkVersion = arguments.jdkVersion, + externalDocumentationLinks = parseLinks(arguments.links), + noStdlibLink = arguments.noStdlibLink, + cacheRoot = arguments.cacheRoot, + languageVersion = arguments.languageVersion, + apiVersion = arguments.apiVersion, + collectInheritedExtensionsFromLibraries = arguments.collectInheritedExtensionsFromLibraries ) val generator = DokkaGenerator( diff --git a/runners/gradle-plugin/src/main/kotlin/main.kt b/runners/gradle-plugin/src/main/kotlin/main.kt index 5f02cd0e..4812e217 100644 --- a/runners/gradle-plugin/src/main/kotlin/main.kt +++ b/runners/gradle-plugin/src/main/kotlin/main.kt @@ -134,6 +134,9 @@ open class DokkaTask : DefaultTask() { @Optional @Input var apiVersion: String? = null + @Input + var collectInheritedExtensionsFromLibraries: Boolean = false + @get:Internal internal val kotlinCompileBasedClasspathAndSourceRoots: ClasspathAndSourceRoots by lazy { extractClasspathAndSourceRootsFromKotlinTasks() } @@ -287,29 +290,31 @@ open class DokkaTask : DefaultTask() { val bootstrapProxy: DokkaBootstrap = automagicTypedProxy(javaClass.classLoader, bootstrapInstance) val configuration = SerializeOnlyDokkaConfiguration( - moduleName, - fullClasspath.map { it.absolutePath }, - sourceRoots, - samples.filterNotNull().map { project.file(it).absolutePath }, - includes.filterNotNull().map { project.file(it).absolutePath }, - outputDirectory, - outputFormat, - includeNonPublic, - false, - reportUndocumented, - skipEmptyPackages, - skipDeprecated, - jdkVersion, - true, - linkMappings, - impliedPlatforms, - perPackageOptions, - externalDocumentationLinks, - noStdlibLink, - cacheRoot, - collectSuppressedFiles(sourceRoots), - languageVersion, - apiVersion) + moduleName, + fullClasspath.map { it.absolutePath }, + sourceRoots, + samples.filterNotNull().map { project.file(it).absolutePath }, + includes.filterNotNull().map { project.file(it).absolutePath }, + outputDirectory, + outputFormat, + includeNonPublic, + false, + reportUndocumented, + skipEmptyPackages, + skipDeprecated, + jdkVersion, + true, + linkMappings, + impliedPlatforms, + perPackageOptions, + externalDocumentationLinks, + noStdlibLink, + cacheRoot, + collectSuppressedFiles(sourceRoots), + languageVersion, + apiVersion, + collectInheritedExtensionsFromLibraries + ) bootstrapProxy.configure( -- cgit From 2f1512f5ec7f23181cf5fcad96d9ee66507de472 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Sat, 20 Jan 2018 16:44:35 +0300 Subject: [backport] Add value for constants from Kotlin Original: fab0890 --- core/src/main/kotlin/Kotlin/DocumentationBuilder.kt | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt index 125f9fd4..39202173 100644 --- a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt +++ b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt @@ -23,6 +23,7 @@ import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtModifierListOwner import org.jetbrains.kotlin.psi.KtParameter +import org.jetbrains.kotlin.psi.KtVariableDeclaration import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.constants.ConstantValue import org.jetbrains.kotlin.resolve.descriptorUtil.* @@ -781,6 +782,11 @@ class DocumentationBuilder if (isVar) { node.appendTextNode("var", NodeKind.Modifier) } + if (isConst) { + val psi = sourcePsi() as? KtVariableDeclaration + val text = psi?.initializer?.text + text?.let { node.appendTextNode(it, NodeKind.Value) } + } getter?.let { if (!it.isDefault) { -- cgit From 85d2ea3a100001d3e5555786202e64ef3ea1679e Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Sat, 20 Jan 2018 17:26:00 +0300 Subject: [backport] Support constants from Java in KK mode Original: 7723826 --- core/src/main/kotlin/Kotlin/DocumentationBuilder.kt | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt index 39202173..d22c48f9 100644 --- a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt +++ b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt @@ -2,6 +2,7 @@ package org.jetbrains.dokka import com.google.inject.Inject import com.intellij.openapi.util.text.StringUtil +import com.intellij.psi.PsiField import com.intellij.psi.PsiJavaFile import org.jetbrains.dokka.DokkaConfiguration.* import org.jetbrains.dokka.Kotlin.DescriptorDocumentationParser @@ -782,12 +783,18 @@ class DocumentationBuilder if (isVar) { node.appendTextNode("var", NodeKind.Modifier) } + if (isConst) { - val psi = sourcePsi() as? KtVariableDeclaration - val text = psi?.initializer?.text - text?.let { node.appendTextNode(it, NodeKind.Value) } + val psi = sourcePsi() + val valueText = when (psi) { + is KtVariableDeclaration -> psi.initializer?.text + is PsiField -> psi.initializer?.text + else -> null + } + valueText?.let { node.appendTextNode(it, NodeKind.Value) } } + getter?.let { if (!it.isDefault) { node.addAccessorDocumentation(descriptorDocumentationParser.parseDocumentation(it), "Getter") -- cgit From f1252678883133709f13fa2d6b7adbce3156f112 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Wed, 31 Jan 2018 23:49:51 +0300 Subject: Refactor selecting of inbound link resolvers --- .../Kotlin/ExternalDocumentationLinkResolver.kt | 43 +++++++++++++++++----- core/src/main/kotlin/Utilities/ServiceLocator.kt | 16 ++++++-- .../inbound-link-resolver/dokka-default.properties | 2 + .../dokka/inbound-link-resolver/javadoc.properties | 2 + 4 files changed, 51 insertions(+), 12 deletions(-) create mode 100644 core/src/main/resources/dokka/inbound-link-resolver/dokka-default.properties create mode 100644 core/src/main/resources/dokka/inbound-link-resolver/javadoc.properties (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt b/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt index 400326d2..7be37177 100644 --- a/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt +++ b/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt @@ -4,6 +4,10 @@ import com.google.inject.Inject import com.google.inject.Singleton import com.intellij.psi.PsiMethod import com.intellij.util.io.* +import org.jetbrains.dokka.Formats.FileGeneratorBasedFormatDescriptor +import org.jetbrains.dokka.Formats.FormatDescriptor +import org.jetbrains.dokka.Utilities.ServiceLocator +import org.jetbrains.dokka.Utilities.lookup import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.impl.EnumEntrySyntheticClassDescriptor import org.jetbrains.kotlin.load.java.descriptors.JavaCallableMemberDescriptor @@ -21,6 +25,7 @@ import java.net.URL import java.net.URLConnection import java.nio.file.Path import java.security.MessageDigest +import kotlin.reflect.full.findAnnotation fun ByteArray.toHexString() = this.joinToString(separator = "") { "%02x".format(it) } @@ -129,13 +134,22 @@ class ExternalDocumentationLinkResolver @Inject constructor( .map { (key, value) -> key to value } .toMap() - val resolver = if (format == "javadoc") { - InboundExternalLinkResolutionService.Javadoc() - } else { - val linkExtension = paramsMap["linkExtension"]?.singleOrNull() ?: - throw RuntimeException("Failed to parse package list from $packageListUrl") - InboundExternalLinkResolutionService.Dokka(linkExtension) - } + + val defaultResolverDesc = services["dokka-default"]!! + val resolverDesc = services[format] + ?: defaultResolverDesc.takeIf { format in formatsWithDefaultResolver } + ?: defaultResolverDesc.also { + logger.warn("Couldn't find InboundExternalLinkResolutionService(format = `$format`) for $link, using Dokka default") + } + + + val resolverClass = javaClass.classLoader.loadClass(resolverDesc.className).kotlin + + val constructors = resolverClass.constructors + + val constructor = constructors.singleOrNull() + ?: constructors.first { it.findAnnotation() != null } + val resolver = constructor.call(paramsMap) as InboundExternalLinkResolutionService val rootInfo = ExternalDocumentationRoot(link.url, resolver, locations) @@ -170,6 +184,15 @@ class ExternalDocumentationLinkResolver @Inject constructor( companion object { const val DOKKA_PARAM_PREFIX = "\$dokka." + val services = ServiceLocator.allServices("inbound-link-resolver").associateBy { it.name } + private val formatsWithDefaultResolver = + ServiceLocator + .allServices("format") + .filter { + val desc = ServiceLocator.lookup(it) as? FileGeneratorBasedFormatDescriptor + desc?.generatorServiceClass == FileGenerator::class + }.map { it.name } + .toSet() } } @@ -177,7 +200,7 @@ class ExternalDocumentationLinkResolver @Inject constructor( interface InboundExternalLinkResolutionService { fun getPath(symbol: DeclarationDescriptor): String? - class Javadoc : InboundExternalLinkResolutionService { + class Javadoc(paramsMap: Map>) : InboundExternalLinkResolutionService { override fun getPath(symbol: DeclarationDescriptor): String? { if (symbol is EnumEntrySyntheticClassDescriptor) { return getPath(symbol.containingDeclaration)?.let { it + "#" + symbol.name.asString() } @@ -203,7 +226,9 @@ interface InboundExternalLinkResolutionService { } } - class Dokka(val extension: String) : InboundExternalLinkResolutionService { + class Dokka(val paramsMap: Map>) : InboundExternalLinkResolutionService { + val extension = paramsMap["linkExtension"]?.singleOrNull() ?: error("linkExtension not provided for Dokka resolver") + override fun getPath(symbol: DeclarationDescriptor): String? { val leafElement = when (symbol) { is CallableDescriptor, is TypeAliasDescriptor -> true diff --git a/core/src/main/kotlin/Utilities/ServiceLocator.kt b/core/src/main/kotlin/Utilities/ServiceLocator.kt index 71bfd21b..83c4c65c 100644 --- a/core/src/main/kotlin/Utilities/ServiceLocator.kt +++ b/core/src/main/kotlin/Utilities/ServiceLocator.kt @@ -14,12 +14,21 @@ class ServiceLookupException(message: String) : Exception(message) object ServiceLocator { fun lookup(clazz: Class, category: String, implementationName: String): T { val descriptor = lookupDescriptor(category, implementationName) + return lookup(clazz, descriptor) + } + + fun lookup( + clazz: Class, + descriptor: ServiceDescriptor + ): T { val loadedClass = javaClass.classLoader.loadClass(descriptor.className) val constructor = loadedClass.constructors - .filter { it.parameterTypes.isEmpty() } - .firstOrNull() ?: throw ServiceLookupException("Class ${descriptor.className} has no corresponding constructor") + .filter { it.parameterTypes.isEmpty() } + .firstOrNull() + ?: throw ServiceLookupException("Class ${descriptor.className} has no corresponding constructor") - val implementationRawType: Any = if (constructor.parameterTypes.isEmpty()) constructor.newInstance() else constructor.newInstance(constructor) + val implementationRawType: Any = + if (constructor.parameterTypes.isEmpty()) constructor.newInstance() else constructor.newInstance(constructor) if (!clazz.isInstance(implementationRawType)) { throw ServiceLookupException("Class ${descriptor.className} is not a subtype of ${clazz.name}") @@ -79,6 +88,7 @@ object ServiceLocator { } inline fun ServiceLocator.lookup(category: String, implementationName: String): T = lookup(T::class.java, category, implementationName) +inline fun ServiceLocator.lookup(desc: ServiceDescriptor): T = lookup(T::class.java, desc) private val ZipEntry.fileName: String get() = name.substringAfterLast("/", name) diff --git a/core/src/main/resources/dokka/inbound-link-resolver/dokka-default.properties b/core/src/main/resources/dokka/inbound-link-resolver/dokka-default.properties new file mode 100644 index 00000000..c484a920 --- /dev/null +++ b/core/src/main/resources/dokka/inbound-link-resolver/dokka-default.properties @@ -0,0 +1,2 @@ +class=org.jetbrains.dokka.InboundExternalLinkResolutionService$Dokka +description=Uses Dokka Default resolver \ No newline at end of file diff --git a/core/src/main/resources/dokka/inbound-link-resolver/javadoc.properties b/core/src/main/resources/dokka/inbound-link-resolver/javadoc.properties new file mode 100644 index 00000000..0d5d7d17 --- /dev/null +++ b/core/src/main/resources/dokka/inbound-link-resolver/javadoc.properties @@ -0,0 +1,2 @@ +class=org.jetbrains.dokka.InboundExternalLinkResolutionService$Javadoc +description=Uses Javadoc Default resolver \ No newline at end of file -- cgit From 71ef970eacfab2fd948ab3fba9aa01808cb7b211 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Thu, 1 Feb 2018 19:02:33 +0300 Subject: [backport] Implement inbound links in java layout html Original: 4641470 --- .../JavaLayoutHtmlPackageListService.kt | 86 ++++++++++++++++++++++ .../java-layout-html.properties | 2 + 2 files changed, 88 insertions(+) create mode 100644 core/src/main/resources/dokka/inbound-link-resolver/java-layout-html.properties (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Formats/JavaLayoutHtml/JavaLayoutHtmlPackageListService.kt b/core/src/main/kotlin/Formats/JavaLayoutHtml/JavaLayoutHtmlPackageListService.kt index 398758f2..d04ed64b 100644 --- a/core/src/main/kotlin/Formats/JavaLayoutHtml/JavaLayoutHtmlPackageListService.kt +++ b/core/src/main/kotlin/Formats/JavaLayoutHtml/JavaLayoutHtmlPackageListService.kt @@ -2,8 +2,13 @@ package org.jetbrains.dokka.Formats import org.jetbrains.dokka.DocumentationModule import org.jetbrains.dokka.ExternalDocumentationLinkResolver.Companion.DOKKA_PARAM_PREFIX +import org.jetbrains.dokka.InboundExternalLinkResolutionService import org.jetbrains.dokka.NodeKind import org.jetbrains.dokka.PackageListService +import org.jetbrains.kotlin.descriptors.* +import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe +import org.jetbrains.kotlin.resolve.descriptorUtil.isCompanionObject +import org.jetbrains.kotlin.types.KotlinType class JavaLayoutHtmlPackageListService: PackageListService { @@ -19,10 +24,91 @@ class JavaLayoutHtmlPackageListService: PackageListService { return buildString { appendParam("format", "java-layout-html") + appendParam("mode", "kotlin") for (p in packages) { appendln(p) } } } +} + +class JavaLayoutHtmlInboundLinkResolutionService(private val paramMap: Map>) : InboundExternalLinkResolutionService { + private fun getContainerPath(symbol: DeclarationDescriptor): String? { + return when (symbol) { + is PackageFragmentDescriptor -> symbol.fqName.asString() + "/" + is ClassifierDescriptor -> getContainerPath(symbol.findPackage()) + symbol.nameWithOuter() + ".html" + else -> null + } + } + + private fun DeclarationDescriptor.findPackage(): PackageFragmentDescriptor = + generateSequence(this) { it.containingDeclaration }.filterIsInstance().first() + + private fun ClassifierDescriptor.nameWithOuter(): String = + generateSequence(this) { it.containingDeclaration as? ClassifierDescriptor } + .toList().asReversed().joinToString(".") { it.name.asString() } + + private fun getPagePath(symbol: DeclarationDescriptor): String? { + return when (symbol) { + is PackageFragmentDescriptor -> getContainerPath(symbol) + "package-summary.html" + is ClassifierDescriptor -> getContainerPath(symbol) + "#" + is FunctionDescriptor, is PropertyDescriptor -> getContainerPath(symbol.containingDeclaration!!) + "#" + symbol.signatureForAnchorUrlEncoded() + else -> null + } + } + + private fun DeclarationDescriptor.signatureForAnchor(): String? { + + fun ReceiverParameterDescriptor.extractReceiverName(): String { + var receiverClass: DeclarationDescriptor = type.constructor.declarationDescriptor!! + if (receiverClass.isCompanionObject()) { + receiverClass = receiverClass.containingDeclaration!! + } else if (receiverClass is TypeParameterDescriptor) { + val upperBoundClass = receiverClass.upperBounds.singleOrNull()?.constructor?.declarationDescriptor + if (upperBoundClass != null) { + receiverClass = upperBoundClass + } + } + + return receiverClass.name.asString() + } + + fun KotlinType.qualifiedNameForSignature(): String { + val desc = constructor.declarationDescriptor + return desc?.fqNameUnsafe?.asString() ?: "" + } + + fun StringBuilder.appendReceiverAndCompanion(desc: CallableDescriptor) { + if (desc.containingDeclaration.isCompanionObject()) { + append("Companion.") + } + desc.extensionReceiverParameter?.let { + append("(") + append(it.extractReceiverName()) + append(").") + } + } + + return when(this) { + is FunctionDescriptor -> buildString { + appendReceiverAndCompanion(this@signatureForAnchor) + append(name.asString()) + valueParameters.joinTo(this, prefix = "(", postfix = ")") { + it.type.qualifiedNameForSignature() + } + } + is PropertyDescriptor -> buildString { + appendReceiverAndCompanion(this@signatureForAnchor) + append(name.asString()) + append(":") + append(returnType?.qualifiedNameForSignature()) + } + else -> null + } + } + + private fun DeclarationDescriptor.signatureForAnchorUrlEncoded(): String? = signatureForAnchor()?.urlEncoded() + + override fun getPath(symbol: DeclarationDescriptor) = getPagePath(symbol) } \ No newline at end of file diff --git a/core/src/main/resources/dokka/inbound-link-resolver/java-layout-html.properties b/core/src/main/resources/dokka/inbound-link-resolver/java-layout-html.properties new file mode 100644 index 00000000..3b61eabe --- /dev/null +++ b/core/src/main/resources/dokka/inbound-link-resolver/java-layout-html.properties @@ -0,0 +1,2 @@ +class=org.jetbrains.dokka.Formats.JavaLayoutHtmlInboundLinkResolutionService +description=Resolver for JavaLayoutHtml \ No newline at end of file -- cgit From 3e8448bf5d3f00cfaa7d4d6b4fbbf678aebc37b7 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Thu, 12 Apr 2018 03:06:15 +0300 Subject: [backport] Make possible to group extensions by receiver Original: d8e03a3 --- .../src/main/kotlin/Kotlin/DocumentationBuilder.kt | 42 ++++++++++++---------- 1 file changed, 24 insertions(+), 18 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt index d22c48f9..d7d30ebb 100644 --- a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt +++ b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt @@ -934,6 +934,30 @@ class DocumentationBuilder DocumentationNode(valueString, Content.Empty, NodeKind.Value) } } + + + fun DocumentationNode.getParentForPackageMember(descriptor: DeclarationDescriptor, + externalClassNodes: MutableMap, + allFqNames: Collection): DocumentationNode { + if (descriptor is CallableMemberDescriptor) { + val extensionClassDescriptor = descriptor.getExtensionClassDescriptor() + if (extensionClassDescriptor != null && isExtensionForExternalClass(descriptor, extensionClassDescriptor, allFqNames) && + !ErrorUtils.isError(extensionClassDescriptor)) { + val fqName = DescriptorUtils.getFqNameSafe(extensionClassDescriptor) + return externalClassNodes.getOrPut(fqName, { + val newNode = DocumentationNode(fqName.asString(), Content.Empty, NodeKind.ExternalClass) + val externalLink = linkResolver.externalDocumentationLinkResolver.buildExternalDocumentationLink(extensionClassDescriptor) + if (externalLink != null) { + newNode.append(DocumentationNode(externalLink, Content.Empty, NodeKind.ExternalLink), RefKind.Link) + } + append(newNode, RefKind.Member) + newNode + }) + } + } + return this + } + } val visibleToDocumentation = setOf(Visibilities.PROTECTED, Visibilities.PUBLIC) @@ -1033,24 +1057,6 @@ fun DeclarationDescriptor.isDeprecated(): Boolean = annotations.any { DescriptorUtils.getFqName(it.type.constructor.declarationDescriptor!!).asString() == "kotlin.Deprecated" } || (this is ConstructorDescriptor && containingDeclaration.isDeprecated()) -fun DocumentationNode.getParentForPackageMember(descriptor: DeclarationDescriptor, - externalClassNodes: MutableMap, - allFqNames: Collection): DocumentationNode { - if (descriptor is CallableMemberDescriptor) { - val extensionClassDescriptor = descriptor.getExtensionClassDescriptor() - if (extensionClassDescriptor != null && isExtensionForExternalClass(descriptor, extensionClassDescriptor, allFqNames) && - !ErrorUtils.isError(extensionClassDescriptor)) { - val fqName = DescriptorUtils.getFqNameSafe(extensionClassDescriptor) - return externalClassNodes.getOrPut(fqName, { - val newNode = DocumentationNode(fqName.asString(), Content.Empty, NodeKind.ExternalClass) - append(newNode, RefKind.Member) - newNode - }) - } - } - return this -} - fun CallableMemberDescriptor.getExtensionClassDescriptor(): ClassifierDescriptor? { val extensionReceiver = extensionReceiverParameter if (extensionReceiver != null) { -- cgit From 8883839b8796589a1fa02b3dca5d1aae172b5c56 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Fri, 13 Apr 2018 19:47:07 +0300 Subject: [backport] Fix problems in as-java java-layout-html mode Extract common part of LanguageServices & other improvements Original: 853262e --- core/src/main/kotlin/Java/JavadocParser.kt | 43 +++-- .../main/kotlin/Kotlin/DeclarationLinkResolver.kt | 2 +- .../main/kotlin/Kotlin/KotlinLanguageService.kt | 164 ++++++++---------- .../main/kotlin/Languages/CommonLanguageService.kt | 65 +++++++ .../kotlin/Languages/NewJavaLanguageService.kt | 190 +++++++++++++++++++++ core/src/main/kotlin/Model/DocumentationNode.kt | 2 +- .../main/kotlin/Model/DocumentationReference.kt | 2 +- 7 files changed, 353 insertions(+), 115 deletions(-) create mode 100644 core/src/main/kotlin/Languages/CommonLanguageService.kt create mode 100644 core/src/main/kotlin/Languages/NewJavaLanguageService.kt (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Java/JavadocParser.kt b/core/src/main/kotlin/Java/JavadocParser.kt index c25f5813..db61a00a 100644 --- a/core/src/main/kotlin/Java/JavadocParser.kt +++ b/core/src/main/kotlin/Java/JavadocParser.kt @@ -20,8 +20,10 @@ interface JavaDocumentationParser { fun parseDocumentation(element: PsiNamedElement): JavadocParseResult } -class JavadocParser(private val refGraph: NodeReferenceGraph, - private val logger: DokkaLogger) : JavaDocumentationParser { +class JavadocParser( + private val refGraph: NodeReferenceGraph, + private val logger: DokkaLogger +) : JavaDocumentationParser { override fun parseDocumentation(element: PsiNamedElement): JavadocParseResult { val docComment = (element as? PsiDocCommentOwner)?.docComment if (docComment == null) return JavadocParseResult.Empty @@ -31,7 +33,7 @@ class JavadocParser(private val refGraph: NodeReferenceGraph, result.append(para) para.convertJavadocElements(docComment.descriptionElements.dropWhile { it.text.trim().isEmpty() }) docComment.tags.forEach { tag -> - when(tag.name) { + when (tag.name) { "see" -> result.convertSeeTag(tag) "deprecated" -> { deprecatedContent = Content() @@ -50,9 +52,9 @@ class JavadocParser(private val refGraph: NodeReferenceGraph, private fun PsiDocTag.contentElements(): Iterable { val tagValueElements = children - .dropWhile { it.node?.elementType == JavaDocTokenType.DOC_TAG_NAME } - .dropWhile { it is PsiWhiteSpace } - .filterNot { it.node?.elementType == JavaDocTokenType.DOC_COMMENT_LEADING_ASTERISKS } + .dropWhile { it.node?.elementType == JavaDocTokenType.DOC_TAG_NAME } + .dropWhile { it is PsiWhiteSpace } + .filterNot { it.node?.elementType == JavaDocTokenType.DOC_COMMENT_LEADING_ASTERISKS } return if (getSubjectName() != null) tagValueElements.dropWhile { it is PsiDocTagValue } else tagValueElements } @@ -83,7 +85,7 @@ class JavadocParser(private val refGraph: NodeReferenceGraph, } } - private fun createBlock(element: Element): ContentBlock = when(element.tagName()) { + private fun createBlock(element: Element): ContentBlock = when (element.tagName()) { "p" -> ContentParagraph() "b", "strong" -> ContentStrong() "i", "em" -> ContentEmphasis() @@ -99,28 +101,26 @@ class JavadocParser(private val refGraph: NodeReferenceGraph, } private fun createLink(element: Element): ContentBlock { - val docref = element.attr("docref") - if (docref != null) { - return ContentNodeLazyLink(docref, { -> refGraph.lookupOrWarn(docref, logger)}) + if (element.hasAttr("docref")) { + val docref = element.attr("docref") + return ContentNodeLazyLink(docref, { -> refGraph.lookupOrWarn(docref, logger) }) } - val href = element.attr("href") - if (href != null) { - return ContentExternalLink(href) + return if (element.hasAttr("href")) { + val href = element.attr("href") + ContentExternalLink(href) } else { - return ContentBlock() + ContentBlock() } } private fun MutableContent.convertSeeTag(tag: PsiDocTag) { - val linkElement = tag.linkElement() - if (linkElement == null) { - return - } + val linkElement = tag.linkElement() ?: return val seeSection = findSectionByTag(ContentTags.SeeAlso) ?: addSection(ContentTags.SeeAlso, null) val linkSignature = resolveLink(linkElement) val text = ContentText(linkElement.text) if (linkSignature != null) { - val linkNode = ContentNodeLazyLink(tag.valueElement!!.text, { -> refGraph.lookupOrWarn(linkSignature, logger)}) + val linkNode = + ContentNodeLazyLink(tag.valueElement!!.text, { -> refGraph.lookupOrWarn(linkSignature, logger) }) linkNode.append(text) seeSection.append(linkNode) } else { @@ -136,8 +136,7 @@ class JavadocParser(private val refGraph: NodeReferenceGraph, val labelText = tag.dataElements.firstOrNull { it is PsiDocToken }?.text ?: valueElement!!.text val link = "${labelText.htmlEscape()}" if (tag.name == "link") "$link" else link - } - else if (valueElement != null) { + } else if (valueElement != null) { valueElement.text } else { "" @@ -153,7 +152,7 @@ class JavadocParser(private val refGraph: NodeReferenceGraph, } private fun PsiDocTag.linkElement(): PsiElement? = - valueElement ?: dataElements.firstOrNull { it !is PsiWhiteSpace } + valueElement ?: dataElements.firstOrNull { it !is PsiWhiteSpace } private fun resolveLink(valueElement: PsiElement?): String? { val target = valueElement?.reference?.resolve() diff --git a/core/src/main/kotlin/Kotlin/DeclarationLinkResolver.kt b/core/src/main/kotlin/Kotlin/DeclarationLinkResolver.kt index ffef399d..ec474900 100644 --- a/core/src/main/kotlin/Kotlin/DeclarationLinkResolver.kt +++ b/core/src/main/kotlin/Kotlin/DeclarationLinkResolver.kt @@ -41,7 +41,7 @@ class DeclarationLinkResolver val target = refGraph.lookup(signature) if (target == null) { - logger.warn("Can't find node by signature $signature, referenced at $referencedAt") + logger.warn("Can't find node by signature `$signature`, referenced at $referencedAt") } target }) diff --git a/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt b/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt index aa185de7..69a97848 100644 --- a/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt +++ b/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt @@ -5,8 +5,9 @@ import org.jetbrains.dokka.LanguageService.RenderMode /** * Implements [LanguageService] and provides rendering of symbols in Kotlin language */ -class KotlinLanguageService : LanguageService { - private val fullOnlyModifiers = setOf("public", "protected", "private", "inline", "noinline", "crossinline", "reified") +class KotlinLanguageService : CommonLanguageService() { + private val fullOnlyModifiers = + setOf("public", "protected", "private", "inline", "noinline", "crossinline", "reified") override fun render(node: DocumentationNode, renderMode: RenderMode): ContentNode { return content { @@ -22,7 +23,7 @@ class KotlinLanguageService : LanguageService { NodeKind.Type, NodeKind.UpperBound -> renderType(node, renderMode) - NodeKind.Modifier -> renderModifier(node) + NodeKind.Modifier -> renderModifier(this, node) NodeKind.Constructor, NodeKind.Function, NodeKind.CompanionObjectFunction -> renderFunction(node, renderMode) @@ -33,12 +34,6 @@ class KotlinLanguageService : LanguageService { } } - override fun renderName(node: DocumentationNode): String { - return when (node.kind) { - NodeKind.Constructor -> node.owner!!.name - else -> node.name - } - } override fun summarizeSignatures(nodes: List): ContentNode? { if (nodes.size < 2) return null @@ -47,9 +42,17 @@ class KotlinLanguageService : LanguageService { return content { val typeParameter = functionWithTypeParameter.details(NodeKind.TypeParameter).first() if (functionWithTypeParameter.kind == NodeKind.Function) { - renderFunction(functionWithTypeParameter, RenderMode.SUMMARY, SummarizingMapper(receiverKind, typeParameter.name)) + renderFunction( + functionWithTypeParameter, + RenderMode.SUMMARY, + SummarizingMapper(receiverKind, typeParameter.name) + ) } else { - renderProperty(functionWithTypeParameter, RenderMode.SUMMARY, SummarizingMapper(receiverKind, typeParameter.name)) + renderProperty( + functionWithTypeParameter, + RenderMode.SUMMARY, + SummarizingMapper(receiverKind, typeParameter.name) + ) } } } @@ -70,26 +73,27 @@ class KotlinLanguageService : LanguageService { companion object { private val arrayClasses = setOf( - "kotlin.Array", - "kotlin.BooleanArray", - "kotlin.ByteArray", - "kotlin.CharArray", - "kotlin.ShortArray", - "kotlin.IntArray", - "kotlin.LongArray", - "kotlin.FloatArray", - "kotlin.DoubleArray" + "kotlin.Array", + "kotlin.BooleanArray", + "kotlin.ByteArray", + "kotlin.CharArray", + "kotlin.ShortArray", + "kotlin.IntArray", + "kotlin.LongArray", + "kotlin.FloatArray", + "kotlin.DoubleArray" ) private val arrayOrListClasses = setOf("kotlin.List") + arrayClasses private val iterableClasses = setOf( - "kotlin.Collection", - "kotlin.Sequence", - "kotlin.Iterable", - "kotlin.Map", - "kotlin.String", - "kotlin.CharSequence") + arrayOrListClasses + "kotlin.Collection", + "kotlin.Sequence", + "kotlin.Iterable", + "kotlin.Map", + "kotlin.String", + "kotlin.CharSequence" + ) + arrayOrListClasses } private enum class ReceiverKind(val receiverName: String, val classes: Collection) { @@ -109,46 +113,14 @@ class KotlinLanguageService : LanguageService { } } - private fun ContentBlock.renderPackage(node: DocumentationNode) { - keyword("package") - text(" ") - identifier(node.name) - } - - private fun ContentBlock.renderList(nodes: List, separator: String = ", ", - noWrap: Boolean = false, renderItem: (T) -> Unit) { - if (nodes.none()) - return - renderItem(nodes.first()) - nodes.drop(1).forEach { - if (noWrap) { - symbol(separator.removeSuffix(" ")) - nbsp() - } else { - symbol(separator) - } - renderItem(it) - } - } - - private fun ContentBlock.renderLinked(node: DocumentationNode, body: ContentBlock.(DocumentationNode) -> Unit) { - val to = node.links.firstOrNull() - if (to == null) - body(node) - else - link(to) { - body(node) - } - } - private fun ContentBlock.renderFunctionalTypeParameterName(node: DocumentationNode, renderMode: RenderMode) { node.references(RefKind.HiddenAnnotation).map { it.to } - .find { it.name == "ParameterName" }?.let { - val parameterNameValue = it.detail(NodeKind.Parameter).detail(NodeKind.Value) - identifier(parameterNameValue.name.removeSurrounding("\""), IdentifierKind.ParameterName) - symbol(":") - nbsp() - } + .find { it.name == "ParameterName" }?.let { + val parameterNameValue = it.detail(NodeKind.Parameter).detail(NodeKind.Value) + identifier(parameterNameValue.name.removeSurrounding("\""), IdentifierKind.ParameterName) + symbol(":") + nbsp() + } } private fun ContentBlock.renderFunctionalType(node: DocumentationNode, renderMode: RenderMode) { @@ -198,7 +170,7 @@ class KotlinLanguageService : LanguageService { renderAnnotationsForNode(node) } renderModifiersForNode(node, renderMode, true) - renderLinked(node) { identifier(it.name, IdentifierKind.TypeName) } + renderLinked(this, node) { identifier(it.name, IdentifierKind.TypeName) } val typeArguments = node.details(NodeKind.Type) if (typeArguments.isNotEmpty()) { symbol("<") @@ -213,17 +185,16 @@ class KotlinLanguageService : LanguageService { } } - private fun ContentBlock.renderModifier(node: DocumentationNode, nowrap: Boolean = false) { + override fun renderModifier( + block: ContentBlock, + node: DocumentationNode, + nowrap: Boolean + ) { when (node.name) { "final", "public", "var" -> { } else -> { - keyword(node.name) - if (nowrap) { - nbsp() - } else { - text(" ") - } + super.renderModifier(block, node, nowrap) } } } @@ -275,9 +246,12 @@ class KotlinLanguageService : LanguageService { } private fun ContentBlock.renderExtraTypeParameterConstraints(node: DocumentationNode, renderMode: RenderMode) { - val parametersWithMultipleConstraints = node.details(NodeKind.TypeParameter).filter { it.details(NodeKind.UpperBound).size > 1 } + val parametersWithMultipleConstraints = + node.details(NodeKind.TypeParameter).filter { it.details(NodeKind.UpperBound).size > 1 } val parametersWithConstraints = parametersWithMultipleConstraints - .flatMap { parameter -> parameter.details(NodeKind.UpperBound).map { constraint -> parameter to constraint } } + .flatMap { parameter -> + parameter.details(NodeKind.UpperBound).map { constraint -> parameter to constraint } + } if (parametersWithMultipleConstraints.isNotEmpty()) { keyword(" where ") renderList(parametersWithConstraints) { @@ -303,9 +277,11 @@ class KotlinLanguageService : LanguageService { } } - private fun ContentBlock.renderModifiersForNode(node: DocumentationNode, - renderMode: RenderMode, - nowrap: Boolean = false) { + private fun ContentBlock.renderModifiersForNode( + node: DocumentationNode, + renderMode: RenderMode, + nowrap: Boolean = false + ) { val modifiers = node.details(NodeKind.Modifier) for (it in modifiers) { if (node.kind == org.jetbrains.dokka.NodeKind.Interface && it.name == "abstract") @@ -313,7 +289,7 @@ class KotlinLanguageService : LanguageService { if (renderMode == RenderMode.SUMMARY && it.name in fullOnlyModifiers) { continue } - renderModifier(it, nowrap) + renderModifier(this, it, nowrap) } } @@ -366,9 +342,11 @@ class KotlinLanguageService : LanguageService { } } - private fun ContentBlock.renderFunction(node: DocumentationNode, - renderMode: RenderMode, - signatureMapper: SignatureMapper? = null) { + private fun ContentBlock.renderFunction( + node: DocumentationNode, + renderMode: RenderMode, + signatureMapper: SignatureMapper? = null + ) { if (renderMode == RenderMode.FULL) { renderAnnotationsForNode(node) } @@ -408,7 +386,11 @@ class KotlinLanguageService : LanguageService { renderExtraTypeParameterConstraints(node, renderMode) } - private fun ContentBlock.renderReceiver(node: DocumentationNode, renderMode: RenderMode, signatureMapper: SignatureMapper?) { + private fun ContentBlock.renderReceiver( + node: DocumentationNode, + renderMode: RenderMode, + signatureMapper: SignatureMapper? + ) { val receiver = node.details(NodeKind.Receiver).singleOrNull() if (receiver != null) { if (signatureMapper != null) { @@ -434,11 +416,13 @@ class KotlinLanguageService : LanguageService { } fun DocumentationNode.isUnitReturnType(): Boolean = - detail(NodeKind.Type).hiddenLinks.firstOrNull()?.qualifiedName() == "kotlin.Unit" + detail(NodeKind.Type).hiddenLinks.firstOrNull()?.qualifiedName() == "kotlin.Unit" - private fun ContentBlock.renderProperty(node: DocumentationNode, - renderMode: RenderMode, - signatureMapper: SignatureMapper? = null) { + private fun ContentBlock.renderProperty( + node: DocumentationNode, + renderMode: RenderMode, + signatureMapper: SignatureMapper? = null + ) { if (renderMode == RenderMode.FULL) { renderAnnotationsForNode(node) } @@ -462,7 +446,7 @@ class KotlinLanguageService : LanguageService { } fun DocumentationNode.getPropertyKeyword() = - if (details(NodeKind.Modifier).any { it.name == "var" }) "var" else "val" + if (details(NodeKind.Modifier).any { it.name == "var" }) "var" else "val" fun ContentBlock.identifierOrDeprecated(node: DocumentationNode) { if (node.deprecation != null) { @@ -476,6 +460,6 @@ class KotlinLanguageService : LanguageService { } fun DocumentationNode.qualifiedNameFromType() = - details.firstOrNull { it.kind == NodeKind.QualifiedName }?.name - ?: (links.firstOrNull() ?: hiddenLinks.firstOrNull())?.qualifiedName() - ?: name + details.firstOrNull { it.kind == NodeKind.QualifiedName }?.name + ?: (links.firstOrNull() ?: hiddenLinks.firstOrNull())?.qualifiedName() + ?: name diff --git a/core/src/main/kotlin/Languages/CommonLanguageService.kt b/core/src/main/kotlin/Languages/CommonLanguageService.kt new file mode 100644 index 00000000..f155192d --- /dev/null +++ b/core/src/main/kotlin/Languages/CommonLanguageService.kt @@ -0,0 +1,65 @@ +package org.jetbrains.dokka + + +abstract class CommonLanguageService : LanguageService { + + protected fun ContentBlock.renderPackage(node: DocumentationNode) { + keyword("package") + nbsp() + identifier(node.name) + } + + override fun renderName(node: DocumentationNode): String { + return when (node.kind) { + NodeKind.Constructor -> node.owner!!.name + else -> node.name + } + } + + open fun renderModifier( + block: ContentBlock, + node: DocumentationNode, + nowrap: Boolean = false + ) = with(block) { + keyword(node.name) + if (nowrap) { + nbsp() + } else { + text(" ") + } + } + + protected fun renderLinked( + block: ContentBlock, + node: DocumentationNode, + body: ContentBlock.(DocumentationNode) -> Unit + ) = with(block) { + val to = node.links.firstOrNull() + if (to == null) + body(node) + else + link(to) { + this.body(node) + } + } + + protected fun ContentBlock.renderList( + nodes: List, separator: String = ", ", + noWrap: Boolean = false, renderItem: (T) -> Unit + ) { + if (nodes.none()) + return + renderItem(nodes.first()) + nodes.drop(1).forEach { + if (noWrap) { + symbol(separator.removeSuffix(" ")) + nbsp() + } else { + symbol(separator) + } + renderItem(it) + } + } + + +} \ No newline at end of file diff --git a/core/src/main/kotlin/Languages/NewJavaLanguageService.kt b/core/src/main/kotlin/Languages/NewJavaLanguageService.kt new file mode 100644 index 00000000..22ad62b2 --- /dev/null +++ b/core/src/main/kotlin/Languages/NewJavaLanguageService.kt @@ -0,0 +1,190 @@ +package org.jetbrains.dokka + +/** + * Implements [LanguageService] and provides rendering of symbols in Java language + */ +class NewJavaLanguageService : CommonLanguageService() { + override fun render(node: DocumentationNode, renderMode: LanguageService.RenderMode): ContentNode { + return content { + (when (node.kind) { + NodeKind.Package -> renderPackage(node) + in NodeKind.classLike -> renderClass(node) + + NodeKind.Modifier -> renderModifier(this, node) + NodeKind.TypeParameter -> renderTypeParameter(node) + NodeKind.Type, + NodeKind.UpperBound -> renderType(node) + + NodeKind.Constructor, + NodeKind.Function -> renderFunction(node) + NodeKind.Property -> renderProperty(node) + else -> "${node.kind}: ${node.name}" + }) + } + } + + override fun summarizeSignatures(nodes: List): ContentNode? = null + + + override fun renderModifier(block: ContentBlock, node: DocumentationNode, nowrap: Boolean) { + when (node.name) { + "open", "internal" -> { + } + else -> super.renderModifier(block, node, nowrap) + } + } + + fun getArrayElementType(node: DocumentationNode): DocumentationNode? = when (node.qualifiedName()) { + "kotlin.Array" -> + node.details(NodeKind.Type).singleOrNull()?.let { et -> getArrayElementType(et) ?: et } + ?: DocumentationNode("Object", node.content, NodeKind.ExternalClass) + + "kotlin.IntArray", "kotlin.LongArray", "kotlin.ShortArray", "kotlin.ByteArray", + "kotlin.CharArray", "kotlin.DoubleArray", "kotlin.FloatArray", "kotlin.BooleanArray" -> + DocumentationNode(node.name.removeSuffix("Array").toLowerCase(), node.content, NodeKind.Type) + + else -> null + } + + fun getArrayDimension(node: DocumentationNode): Int = when (node.qualifiedName()) { + "kotlin.Array" -> + 1 + (node.details(NodeKind.Type).singleOrNull()?.let { getArrayDimension(it) } ?: 0) + + "kotlin.IntArray", "kotlin.LongArray", "kotlin.ShortArray", "kotlin.ByteArray", + "kotlin.CharArray", "kotlin.DoubleArray", "kotlin.FloatArray", "kotlin.BooleanArray" -> + 1 + else -> 0 + } + + fun ContentBlock.renderType(node: DocumentationNode) { + when (node.name) { + "Unit" -> identifier("void") + "Int" -> identifier("int") + "Long" -> identifier("long") + "Double" -> identifier("double") + "Float" -> identifier("float") + "Char" -> identifier("char") + "Boolean" -> identifier("bool") + // TODO: render arrays + else -> renderLinked(this, node) { + identifier(node.name) + } + } + } + + private fun ContentBlock.renderTypeParameter(node: DocumentationNode) { + val constraints = node.details(NodeKind.UpperBound) + if (constraints.none()) + identifier(node.name) + else { + identifier(node.name) + text(" ") + keyword("extends") + text(" ") + constraints.forEach { renderType(node) } + } + } + + private fun ContentBlock.renderParameter(node: DocumentationNode) { + renderType(node.detail(NodeKind.Type)) + text(" ") + identifier(node.name) + } + + private fun ContentBlock.renderTypeParametersForNode(node: DocumentationNode) { + val typeParameters = node.details(NodeKind.TypeParameter) + if (typeParameters.any()) { + symbol("<") + renderList(typeParameters, noWrap = true) { + renderTypeParameter(it) + } + symbol(">") + text(" ") + } + } + +// private fun renderModifiersForNode(node: DocumentationNode): String { +// val modifiers = node.details(NodeKind.Modifier).map { renderModifier(it) }.filter { it != "" } +// if (modifiers.none()) +// return "" +// return modifiers.joinToString(" ", postfix = " ") +// } + + private fun ContentBlock.renderClassKind(node: DocumentationNode) { + when (node.kind) { + NodeKind.Interface -> { + keyword("interface") + } + NodeKind.EnumItem -> { + keyword("enum value") + } + NodeKind.Enum -> { + keyword("enum") + } + NodeKind.Class, NodeKind.Exception, NodeKind.Object -> { + keyword("class") + } + else -> throw IllegalArgumentException("Node $node is not a class-like object") + } + text(" ") + } + + private fun ContentBlock.renderClass(node: DocumentationNode) { + renderClassKind(node) + + identifier(node.name) + renderTypeParametersForNode(node) + } + + private fun ContentBlock.renderParameters(nodes: List) { + renderList(nodes) { + renderParameter(it) + } + } + + private fun ContentBlock.renderFunction(node: DocumentationNode) { + when (node.kind) { + NodeKind.Constructor -> identifier(node.owner?.name ?: "") + NodeKind.Function -> { + renderTypeParametersForNode(node) + renderType(node.detail(NodeKind.Type)) + text(" ") + identifier(node.name) + + } + else -> throw IllegalArgumentException("Node $node is not a function-like object") + } + + val receiver = node.details(NodeKind.Receiver).singleOrNull() + symbol("(") + if (receiver != null) + renderParameters(listOf(receiver) + node.details(NodeKind.Parameter)) + else + renderParameters(node.details(NodeKind.Parameter)) + + symbol(")") + } + + private fun ContentBlock.renderProperty(node: DocumentationNode) { + + when (node.kind) { + NodeKind.Property -> { + keyword("val") + text(" ") + } + else -> throw IllegalArgumentException("Node $node is not a property") + } + renderTypeParametersForNode(node) + val receiver = node.details(NodeKind.Receiver).singleOrNull() + if (receiver != null) { + renderType(receiver.detail(NodeKind.Type)) + symbol(".") + } + + identifier(node.name) + symbol(":") + text(" ") + renderType(node.detail(NodeKind.Type)) + + } +} \ No newline at end of file diff --git a/core/src/main/kotlin/Model/DocumentationNode.kt b/core/src/main/kotlin/Model/DocumentationNode.kt index 85ecdf87..84501d2b 100644 --- a/core/src/main/kotlin/Model/DocumentationNode.kt +++ b/core/src/main/kotlin/Model/DocumentationNode.kt @@ -63,7 +63,7 @@ enum class NodeKind { companion object { val classLike = setOf(Class, Interface, Enum, AnnotationClass, Exception, Object, TypeAlias) - val memberLike = setOf(Function, Property, Constructor, CompanionObjectFunction, CompanionObjectProperty, EnumItem) + val memberLike = setOf(Function, Property, Field, Constructor, CompanionObjectFunction, CompanionObjectProperty, EnumItem) } } diff --git a/core/src/main/kotlin/Model/DocumentationReference.kt b/core/src/main/kotlin/Model/DocumentationReference.kt index b0f011be..89ec1b3e 100644 --- a/core/src/main/kotlin/Model/DocumentationReference.kt +++ b/core/src/main/kotlin/Model/DocumentationReference.kt @@ -62,7 +62,7 @@ class NodeReferenceGraph() { fun lookupOrWarn(signature: String, logger: DokkaLogger): DocumentationNode? { val result = nodeMap[signature] if (result == null) { - logger.warn("Can't find node by signature $signature") + logger.warn("Can't find node by signature `$signature`") } return result } -- cgit From ad35def2efbb6eae6fae423bb639890aaa2cb93f Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Fri, 13 Jul 2018 18:36:31 +0300 Subject: Add missing urlEncoded function for JLH --- .../Formats/JavaLayoutHtml/JavaLayoutHtmlPackageListService.kt | 5 +---- core/src/main/kotlin/Utilities/Html.kt | 4 ++++ 2 files changed, 5 insertions(+), 4 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Formats/JavaLayoutHtml/JavaLayoutHtmlPackageListService.kt b/core/src/main/kotlin/Formats/JavaLayoutHtml/JavaLayoutHtmlPackageListService.kt index d04ed64b..6d9b5fd0 100644 --- a/core/src/main/kotlin/Formats/JavaLayoutHtml/JavaLayoutHtmlPackageListService.kt +++ b/core/src/main/kotlin/Formats/JavaLayoutHtml/JavaLayoutHtmlPackageListService.kt @@ -1,10 +1,7 @@ package org.jetbrains.dokka.Formats -import org.jetbrains.dokka.DocumentationModule +import org.jetbrains.dokka.* import org.jetbrains.dokka.ExternalDocumentationLinkResolver.Companion.DOKKA_PARAM_PREFIX -import org.jetbrains.dokka.InboundExternalLinkResolutionService -import org.jetbrains.dokka.NodeKind -import org.jetbrains.dokka.PackageListService import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe import org.jetbrains.kotlin.resolve.descriptorUtil.isCompanionObject diff --git a/core/src/main/kotlin/Utilities/Html.kt b/core/src/main/kotlin/Utilities/Html.kt index a5a93d9e..de1ce1a5 100644 --- a/core/src/main/kotlin/Utilities/Html.kt +++ b/core/src/main/kotlin/Utilities/Html.kt @@ -1,8 +1,12 @@ package org.jetbrains.dokka +import java.net.URLEncoder + /** * Replaces symbols reserved in HTML with their respective entities. * Replaces & with &, < with < and > with > */ fun String.htmlEscape(): String = replace("&", "&").replace("<", "<").replace(">", ">") + +fun String.urlEncoded(): String = URLEncoder.encode(this, "UTF-8") \ No newline at end of file -- cgit From 31a4a3804020130e7caf5826b317aaee5547c0d0 Mon Sep 17 00:00:00 2001 From: Douglas Sigelbaum Date: Fri, 20 Apr 2018 18:09:36 -0700 Subject: [backport] Use expression body Original: d889d4e --- core/src/main/kotlin/Kotlin/KotlinLanguageService.kt | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt b/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt index 69a97848..79350237 100644 --- a/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt +++ b/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt @@ -459,7 +459,8 @@ class KotlinLanguageService : CommonLanguageService() { } } -fun DocumentationNode.qualifiedNameFromType() = - details.firstOrNull { it.kind == NodeKind.QualifiedName }?.name +fun DocumentationNode.qualifiedNameFromType(): String { + return details.firstOrNull { it.kind == NodeKind.QualifiedName }?.name ?: (links.firstOrNull() ?: hiddenLinks.firstOrNull())?.qualifiedName() ?: name +} -- cgit From a3f16fd75c200020465f79563ca58b2833236865 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Tue, 24 Apr 2018 20:35:42 +0300 Subject: [backport] Stabilize signatures to fix linking from Java to Kotlin Basically there is 2 ways to get signature, from PSI and from descriptors, and there should be only one way in one session Original: adc09f2 --- .../main/kotlin/Analysis/AnalysisEnvironment.kt | 3 +- .../main/kotlin/Analysis/JavaResolveExtension.kt | 131 +++++++++++++++++++++ core/src/main/kotlin/Formats/AnalysisComponents.kt | 14 +-- .../kotlin/Java/JavaPsiDocumentationBuilder.kt | 6 +- core/src/main/kotlin/Java/JavadocParser.kt | 5 +- .../main/kotlin/Kotlin/DeclarationLinkResolver.kt | 7 +- .../kotlin/Kotlin/DescriptorDocumentationParser.kt | 6 +- .../src/main/kotlin/Kotlin/DocumentationBuilder.kt | 23 ++-- .../KotlinAsJavaDescriptorSignatureProvider.kt | 22 ---- .../Kotlin/KotlinAsJavaElementSignatureProvider.kt | 25 ++++ .../Kotlin/KotlinDescriptorSignatureProvider.kt | 9 -- .../Kotlin/KotlinElementSignatureProvider.kt | 31 +++++ .../kotlin/Model/DescriptorSignatureProvider.kt | 7 -- core/src/main/kotlin/Model/DocumentationNode.kt | 7 +- .../main/kotlin/Model/ElementSignatureProvider.kt | 9 ++ core/src/main/kotlin/Utilities/DokkaModules.kt | 3 - 16 files changed, 230 insertions(+), 78 deletions(-) create mode 100644 core/src/main/kotlin/Analysis/JavaResolveExtension.kt delete mode 100644 core/src/main/kotlin/Kotlin/KotlinAsJavaDescriptorSignatureProvider.kt create mode 100644 core/src/main/kotlin/Kotlin/KotlinAsJavaElementSignatureProvider.kt delete mode 100644 core/src/main/kotlin/Kotlin/KotlinDescriptorSignatureProvider.kt create mode 100644 core/src/main/kotlin/Kotlin/KotlinElementSignatureProvider.kt delete mode 100644 core/src/main/kotlin/Model/DescriptorSignatureProvider.kt create mode 100644 core/src/main/kotlin/Model/ElementSignatureProvider.kt (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt b/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt index b2e4b490..6854b323 100644 --- a/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt +++ b/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt @@ -29,6 +29,7 @@ import org.jetbrains.kotlin.cli.jvm.config.* import org.jetbrains.kotlin.cli.jvm.index.JavaRoot import org.jetbrains.kotlin.config.* import org.jetbrains.kotlin.container.getService +import org.jetbrains.kotlin.container.tryGetService import org.jetbrains.kotlin.context.ProjectContext import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.ModuleDescriptor @@ -250,7 +251,7 @@ class DokkaResolutionFacade(override val project: Project, } override fun tryGetFrontendService(element: PsiElement, serviceClass: Class): T? { - return null + return resolverForModule.componentProvider.tryGetService(serviceClass) } override fun resolveToDescriptor(declaration: KtDeclaration, bodyResolveMode: BodyResolveMode): DeclarationDescriptor { diff --git a/core/src/main/kotlin/Analysis/JavaResolveExtension.kt b/core/src/main/kotlin/Analysis/JavaResolveExtension.kt new file mode 100644 index 00000000..f8992d45 --- /dev/null +++ b/core/src/main/kotlin/Analysis/JavaResolveExtension.kt @@ -0,0 +1,131 @@ +/* + * Copyright 2010-2017 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@file:JvmName("JavaResolutionUtils") + +package org.jetbrains.dokka + +import com.intellij.psi.* +import org.jetbrains.kotlin.asJava.classes.KtLightClass +import org.jetbrains.kotlin.asJava.unwrapped +import org.jetbrains.kotlin.caches.resolve.KotlinCacheService +import org.jetbrains.kotlin.descriptors.* +import org.jetbrains.kotlin.idea.resolve.ResolutionFacade +import org.jetbrains.kotlin.incremental.components.NoLookupLocation +import org.jetbrains.kotlin.load.java.sources.JavaSourceElement +import org.jetbrains.kotlin.load.java.structure.* +import org.jetbrains.kotlin.load.java.structure.impl.* +import org.jetbrains.kotlin.name.Name +import org.jetbrains.kotlin.psi.KtClassOrObject +import org.jetbrains.kotlin.psi.KtDeclaration +import org.jetbrains.kotlin.psi.psiUtil.parameterIndex +import org.jetbrains.kotlin.resolve.jvm.JavaDescriptorResolver +import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatform +import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter +import org.jetbrains.kotlin.resolve.scopes.MemberScope + +// TODO: Remove that file + +@JvmOverloads +fun PsiMethod.getJavaMethodDescriptor(resolutionFacade: ResolutionFacade = javaResolutionFacade()): DeclarationDescriptor? { + val method = originalElement as? PsiMethod ?: return null + if (method.containingClass == null || !Name.isValidIdentifier(method.name)) return null + val resolver = method.getJavaDescriptorResolver(resolutionFacade) + return when { + method.isConstructor -> resolver?.resolveConstructor(JavaConstructorImpl(method)) + else -> resolver?.resolveMethod(JavaMethodImpl(method)) + } +} + +@JvmOverloads +fun PsiClass.getJavaClassDescriptor(resolutionFacade: ResolutionFacade = javaResolutionFacade()): ClassDescriptor? { + val psiClass = originalElement as? PsiClass ?: return null + return psiClass.getJavaDescriptorResolver(resolutionFacade)?.resolveClass(JavaClassImpl(psiClass)) +} + +@JvmOverloads +fun PsiField.getJavaFieldDescriptor(resolutionFacade: ResolutionFacade = javaResolutionFacade()): PropertyDescriptor? { + val field = originalElement as? PsiField ?: return null + return field.getJavaDescriptorResolver(resolutionFacade)?.resolveField(JavaFieldImpl(field)) +} + +@JvmOverloads +fun PsiMember.getJavaMemberDescriptor(resolutionFacade: ResolutionFacade = javaResolutionFacade()): DeclarationDescriptor? { + return when (this) { + is PsiEnumConstant -> containingClass?.getJavaClassDescriptor(resolutionFacade) + is PsiClass -> getJavaClassDescriptor(resolutionFacade) + is PsiMethod -> getJavaMethodDescriptor(resolutionFacade) + is PsiField -> getJavaFieldDescriptor(resolutionFacade) + else -> null + } +} + +@JvmOverloads +fun PsiMember.getJavaOrKotlinMemberDescriptor(resolutionFacade: ResolutionFacade = javaResolutionFacade()): DeclarationDescriptor? { + val callable = unwrapped + return when (callable) { + is PsiMember -> getJavaMemberDescriptor(resolutionFacade) + is KtDeclaration -> { + val descriptor = resolutionFacade.resolveToDescriptor(callable) + if (descriptor is ClassDescriptor && this is PsiMethod) descriptor.unsubstitutedPrimaryConstructor else descriptor + } + else -> null + } +} + +private fun PsiElement.getJavaDescriptorResolver(resolutionFacade: ResolutionFacade): JavaDescriptorResolver? { + return resolutionFacade.tryGetFrontendService(this, JavaDescriptorResolver::class.java) +} + +private fun JavaDescriptorResolver.resolveMethod(method: JavaMethod): DeclarationDescriptor? { + return getContainingScope(method) + ?.getContributedDescriptors(nameFilter = { true }, kindFilter = DescriptorKindFilter.CALLABLES) + ?.filterIsInstance() + ?.findByJavaElement(method) +} + +private fun JavaDescriptorResolver.resolveConstructor(constructor: JavaConstructor): ConstructorDescriptor? { + return resolveClass(constructor.containingClass)?.constructors?.findByJavaElement(constructor) +} + +private fun JavaDescriptorResolver.resolveField(field: JavaField): PropertyDescriptor? { + return getContainingScope(field)?.getContributedVariables(field.name, NoLookupLocation.FROM_IDE)?.findByJavaElement(field) +} + +private fun JavaDescriptorResolver.getContainingScope(member: JavaMember): MemberScope? { + val containingClass = resolveClass(member.containingClass) + return if (member.isStatic) + containingClass?.staticScope + else + containingClass?.defaultType?.memberScope +} + +private fun Collection.findByJavaElement(javaElement: JavaElement): T? { + return firstOrNull { member -> + val memberJavaElement = (member.original.source as? JavaSourceElement)?.javaElement + when { + memberJavaElement == javaElement -> + true + memberJavaElement is JavaElementImpl<*> && javaElement is JavaElementImpl<*> -> + memberJavaElement.psi.isEquivalentTo(javaElement.psi) + else -> + false + } + } +} + +fun PsiElement.javaResolutionFacade() = + KotlinCacheService.getInstance(project).getResolutionFacadeByFile(this.originalElement.containingFile, JvmPlatform) diff --git a/core/src/main/kotlin/Formats/AnalysisComponents.kt b/core/src/main/kotlin/Formats/AnalysisComponents.kt index c4d97dbb..d78d4a0c 100644 --- a/core/src/main/kotlin/Formats/AnalysisComponents.kt +++ b/core/src/main/kotlin/Formats/AnalysisComponents.kt @@ -2,9 +2,9 @@ package org.jetbrains.dokka.Formats import com.google.inject.Binder import org.jetbrains.dokka.* -import org.jetbrains.dokka.Kotlin.KotlinAsJavaDescriptorSignatureProvider -import org.jetbrains.dokka.Kotlin.KotlinDescriptorSignatureProvider -import org.jetbrains.dokka.Model.DescriptorSignatureProvider +import org.jetbrains.dokka.KotlinAsJavaElementSignatureProvider +import org.jetbrains.dokka.KotlinElementSignatureProvider +import org.jetbrains.dokka.ElementSignatureProvider import org.jetbrains.dokka.Samples.DefaultSampleProcessingService import org.jetbrains.dokka.Samples.SampleProcessingService import org.jetbrains.dokka.Utilities.bind @@ -16,12 +16,12 @@ interface DefaultAnalysisComponentServices { val packageDocumentationBuilderClass: KClass val javaDocumentationBuilderClass: KClass val sampleProcessingService: KClass - val descriptorSignatureProvider: KClass + val elementSignatureProvider: KClass } interface DefaultAnalysisComponent : FormatDescriptorAnalysisComponent, DefaultAnalysisComponentServices { override fun configureAnalysis(binder: Binder): Unit = with(binder) { - bind() toType descriptorSignatureProvider + bind() toType elementSignatureProvider bind() toType packageDocumentationBuilderClass bind() toType javaDocumentationBuilderClass bind() toType sampleProcessingService @@ -33,7 +33,7 @@ object KotlinAsJava : DefaultAnalysisComponentServices { override val packageDocumentationBuilderClass = KotlinAsJavaDocumentationBuilder::class override val javaDocumentationBuilderClass = JavaPsiDocumentationBuilder::class override val sampleProcessingService = DefaultSampleProcessingService::class - override val descriptorSignatureProvider = KotlinAsJavaDescriptorSignatureProvider::class + override val elementSignatureProvider = KotlinAsJavaElementSignatureProvider::class } @@ -41,5 +41,5 @@ object KotlinAsKotlin : DefaultAnalysisComponentServices { override val packageDocumentationBuilderClass = KotlinPackageDocumentationBuilder::class override val javaDocumentationBuilderClass = KotlinJavaDocumentationBuilder::class override val sampleProcessingService = DefaultSampleProcessingService::class - override val descriptorSignatureProvider = KotlinDescriptorSignatureProvider::class + override val elementSignatureProvider = KotlinElementSignatureProvider::class } \ No newline at end of file diff --git a/core/src/main/kotlin/Java/JavaPsiDocumentationBuilder.kt b/core/src/main/kotlin/Java/JavaPsiDocumentationBuilder.kt index cf2b0514..646096e5 100644 --- a/core/src/main/kotlin/Java/JavaPsiDocumentationBuilder.kt +++ b/core/src/main/kotlin/Java/JavaPsiDocumentationBuilder.kt @@ -45,10 +45,10 @@ class JavaPsiDocumentationBuilder : JavaDocumentationBuilder { private val refGraph: NodeReferenceGraph private val docParser: JavaDocumentationParser - @Inject constructor(options: DocumentationOptions, refGraph: NodeReferenceGraph, logger: DokkaLogger) { + @Inject constructor(options: DocumentationOptions, refGraph: NodeReferenceGraph, logger: DokkaLogger, signatureProvider: ElementSignatureProvider) { this.options = options this.refGraph = refGraph - this.docParser = JavadocParser(refGraph, logger) + this.docParser = JavadocParser(refGraph, logger, signatureProvider) } constructor(options: DocumentationOptions, refGraph: NodeReferenceGraph, docParser: JavaDocumentationParser) { @@ -61,7 +61,7 @@ class JavaPsiDocumentationBuilder : JavaDocumentationBuilder { if (skipFile(file) || file.classes.all { skipElement(it) }) { return } - val packageNode = module.findOrCreatePackageNode(file.packageName, emptyMap(), refGraph) + val packageNode = findOrCreatePackageNode(module, file.packageName, emptyMap(), refGraph) appendClasses(packageNode, file.classes) } diff --git a/core/src/main/kotlin/Java/JavadocParser.kt b/core/src/main/kotlin/Java/JavadocParser.kt index db61a00a..365ae298 100644 --- a/core/src/main/kotlin/Java/JavadocParser.kt +++ b/core/src/main/kotlin/Java/JavadocParser.kt @@ -22,7 +22,8 @@ interface JavaDocumentationParser { class JavadocParser( private val refGraph: NodeReferenceGraph, - private val logger: DokkaLogger + private val logger: DokkaLogger, + private val signatureProvider: ElementSignatureProvider ) : JavaDocumentationParser { override fun parseDocumentation(element: PsiNamedElement): JavadocParseResult { val docComment = (element as? PsiDocCommentOwner)?.docComment @@ -157,7 +158,7 @@ class JavadocParser( private fun resolveLink(valueElement: PsiElement?): String? { val target = valueElement?.reference?.resolve() if (target != null) { - return getSignature(target) + return signatureProvider.signature(target) } return null } diff --git a/core/src/main/kotlin/Kotlin/DeclarationLinkResolver.kt b/core/src/main/kotlin/Kotlin/DeclarationLinkResolver.kt index ec474900..d73bef4a 100644 --- a/core/src/main/kotlin/Kotlin/DeclarationLinkResolver.kt +++ b/core/src/main/kotlin/Kotlin/DeclarationLinkResolver.kt @@ -1,13 +1,10 @@ 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.descriptors.TypeAliasDescriptor import org.jetbrains.kotlin.idea.kdoc.resolveKDocLink -import org.jetbrains.kotlin.resolve.descriptorUtil.isEffectivelyPrivateApi -import org.jetbrains.kotlin.resolve.descriptorUtil.isEffectivelyPublicApi class DeclarationLinkResolver @Inject constructor(val resolutionFacade: DokkaResolutionFacade, @@ -15,7 +12,7 @@ class DeclarationLinkResolver val logger: DokkaLogger, val options: DocumentationOptions, val externalDocumentationLinkResolver: ExternalDocumentationLinkResolver, - val descriptorSignatureProvider: DescriptorSignatureProvider) { + val elementSignatureProvider: ElementSignatureProvider) { fun tryResolveContentLink(fromDescriptor: DeclarationDescriptor, href: String): ContentBlock? { @@ -34,7 +31,7 @@ class DeclarationLinkResolver if (externalHref != null) { return ContentExternalLink(externalHref) } - val signature = descriptorSignatureProvider.signature(symbol) + val signature = elementSignatureProvider.signature(symbol) val referencedAt = fromDescriptor.signatureWithSourceLocation() return ContentNodeLazyLink(href, { -> diff --git a/core/src/main/kotlin/Kotlin/DescriptorDocumentationParser.kt b/core/src/main/kotlin/Kotlin/DescriptorDocumentationParser.kt index 6e44df74..5f1118e8 100644 --- a/core/src/main/kotlin/Kotlin/DescriptorDocumentationParser.kt +++ b/core/src/main/kotlin/Kotlin/DescriptorDocumentationParser.kt @@ -33,7 +33,9 @@ class DescriptorDocumentationParser val linkResolver: DeclarationLinkResolver, val resolutionFacade: DokkaResolutionFacade, val refGraph: NodeReferenceGraph, - val sampleService: SampleProcessingService) + val sampleService: SampleProcessingService, + val signatureProvider: KotlinElementSignatureProvider + ) { fun parseDocumentation(descriptor: DeclarationDescriptor, inline: Boolean = false): Content = parseDocumentationAndDetails(descriptor, inline).first @@ -129,7 +131,7 @@ class DescriptorDocumentationParser fun parseJavadoc(descriptor: DeclarationDescriptor): Pair Unit> { val psi = ((descriptor as? DeclarationDescriptorWithSource)?.source as? PsiSourceElement)?.psi if (psi is PsiDocCommentOwner) { - val parseResult = JavadocParser(refGraph, logger).parseDocumentation(psi as PsiNamedElement) + val parseResult = JavadocParser(refGraph, logger, signatureProvider).parseDocumentation(psi as PsiNamedElement) return parseResult.content to { node -> parseResult.deprecatedContent?.let { val deprecationNode = DocumentationNode("", it, NodeKind.Modifier) diff --git a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt index d7d30ebb..05bd2cc7 100644 --- a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt +++ b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt @@ -18,7 +18,6 @@ import org.jetbrains.kotlin.idea.util.toFuzzyType import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi import org.jetbrains.kotlin.kdoc.psi.impl.KDocSection import org.jetbrains.kotlin.lexer.KtTokens -import org.jetbrains.kotlin.load.java.structure.impl.JavaClassImpl import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name @@ -29,7 +28,6 @@ import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.constants.ConstantValue import org.jetbrains.kotlin.resolve.descriptorUtil.* import org.jetbrains.kotlin.resolve.findTopMostOverriddenDescriptors -import org.jetbrains.kotlin.resolve.jvm.JavaDescriptorResolver import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.resolve.scopes.getDescriptorsFiltered import org.jetbrains.kotlin.resolve.source.PsiSourceElement @@ -192,14 +190,16 @@ class DocumentationBuilder appendTextNode(modifier, NodeKind.Modifier) } - fun DocumentationNode.appendSupertype(descriptor: ClassDescriptor, superType: KotlinType) { + fun DocumentationNode.appendSupertype(descriptor: ClassDescriptor, superType: KotlinType, backref: Boolean) { val unwrappedType = superType.unwrap() if (unwrappedType is AbbreviatedType) { - appendSupertype(descriptor, unwrappedType.abbreviation) + appendSupertype(descriptor, unwrappedType.abbreviation, backref) } else { appendType(unwrappedType, NodeKind.Supertype) val superclass = unwrappedType.constructor.declarationDescriptor - link(superclass, descriptor, RefKind.Inheritor) + if (backref) { + link(superclass, descriptor, RefKind.Inheritor) + } link(descriptor, superclass, RefKind.Superclass) } } @@ -457,7 +457,7 @@ class DocumentationBuilder if (options.skipEmptyPackages && declarations.none { it.isDocumented(options) }) continue logger.info(" package $packageName: ${declarations.count()} declarations") - val packageNode = findOrCreatePackageNode(packageName.asString(), packageContent, this@DocumentationBuilder.refGraph) + val packageNode = findOrCreatePackageNode(this, packageName.asString(), packageContent, this@DocumentationBuilder.refGraph) packageDocumentationBuilder.buildPackageDocumentation(this@DocumentationBuilder, packageName, packageNode, declarations, allFqNames) } @@ -646,7 +646,7 @@ class DocumentationBuilder val node = nodeForDescriptor(this, kind, external) register(this, node) typeConstructor.supertypes.forEach { - node.appendSupertype(this, it) + node.appendSupertype(this, it, !external) } if (getKind() != ClassKind.OBJECT && getKind() != ClassKind.ENUM_ENTRY) { node.appendInPageChildren(typeConstructor.parameters, RefKind.Detail) @@ -997,16 +997,11 @@ class KotlinJavaDocumentationBuilder val logger: DokkaLogger) : JavaDocumentationBuilder { override fun appendFile(file: PsiJavaFile, module: DocumentationModule, packageContent: Map) { val classDescriptors = file.classes.map { - val javaDescriptorResolver = resolutionFacade.getFrontendService(JavaDescriptorResolver::class.java) - - javaDescriptorResolver.resolveClass(JavaClassImpl(it)) ?: run { - logger.warn("Cannot find descriptor for Java class ${it.qualifiedName}") - null - } + it.getJavaClassDescriptor(resolutionFacade) } if (classDescriptors.any { it != null && it.isDocumented(options) }) { - val packageNode = module.findOrCreatePackageNode(file.packageName, packageContent, documentationBuilder.refGraph) + val packageNode = findOrCreatePackageNode(module, file.packageName, packageContent, documentationBuilder.refGraph) for (descriptor in classDescriptors.filterNotNull()) { with(documentationBuilder) { diff --git a/core/src/main/kotlin/Kotlin/KotlinAsJavaDescriptorSignatureProvider.kt b/core/src/main/kotlin/Kotlin/KotlinAsJavaDescriptorSignatureProvider.kt deleted file mode 100644 index a3be658e..00000000 --- a/core/src/main/kotlin/Kotlin/KotlinAsJavaDescriptorSignatureProvider.kt +++ /dev/null @@ -1,22 +0,0 @@ -package org.jetbrains.dokka.Kotlin - -import org.jetbrains.dokka.Model.DescriptorSignatureProvider -import org.jetbrains.dokka.getSignature -import org.jetbrains.dokka.sourcePsi -import org.jetbrains.kotlin.asJava.toLightElements -import org.jetbrains.kotlin.descriptors.DeclarationDescriptor -import org.jetbrains.kotlin.psi.KtElement - -class KotlinAsJavaDescriptorSignatureProvider : DescriptorSignatureProvider { - override fun signature(forDesc: DeclarationDescriptor): String { - val sourcePsi = forDesc.sourcePsi() - val javaLikePsi = if (sourcePsi is KtElement) { - sourcePsi.toLightElements().firstOrNull() - } else { - sourcePsi - } - - return getSignature(javaLikePsi) ?: - "not implemented for $forDesc with psi: $sourcePsi" - } -} \ No newline at end of file diff --git a/core/src/main/kotlin/Kotlin/KotlinAsJavaElementSignatureProvider.kt b/core/src/main/kotlin/Kotlin/KotlinAsJavaElementSignatureProvider.kt new file mode 100644 index 00000000..20ea179e --- /dev/null +++ b/core/src/main/kotlin/Kotlin/KotlinAsJavaElementSignatureProvider.kt @@ -0,0 +1,25 @@ +package org.jetbrains.dokka + +import com.intellij.psi.PsiElement +import org.jetbrains.kotlin.asJava.toLightElements +import org.jetbrains.kotlin.descriptors.DeclarationDescriptor +import org.jetbrains.kotlin.psi.KtElement + +class KotlinAsJavaElementSignatureProvider : ElementSignatureProvider { + + private fun PsiElement.javaLikePsi() = when { + this is KtElement -> toLightElements().firstOrNull() + else -> this + } + + override fun signature(forPsi: PsiElement): String { + return getSignature(forPsi.javaLikePsi()) ?: + "not implemented for $forPsi" + } + + override fun signature(forDesc: DeclarationDescriptor): String { + val sourcePsi = forDesc.sourcePsi() + return getSignature(sourcePsi?.javaLikePsi()) ?: + "not implemented for $forDesc with psi: $sourcePsi" + } +} \ No newline at end of file diff --git a/core/src/main/kotlin/Kotlin/KotlinDescriptorSignatureProvider.kt b/core/src/main/kotlin/Kotlin/KotlinDescriptorSignatureProvider.kt deleted file mode 100644 index 7ecd0389..00000000 --- a/core/src/main/kotlin/Kotlin/KotlinDescriptorSignatureProvider.kt +++ /dev/null @@ -1,9 +0,0 @@ -package org.jetbrains.dokka.Kotlin - -import org.jetbrains.dokka.Model.DescriptorSignatureProvider -import org.jetbrains.dokka.signature -import org.jetbrains.kotlin.descriptors.DeclarationDescriptor - -class KotlinDescriptorSignatureProvider : DescriptorSignatureProvider { - override fun signature(forDesc: DeclarationDescriptor): String = forDesc.signature() -} \ No newline at end of file diff --git a/core/src/main/kotlin/Kotlin/KotlinElementSignatureProvider.kt b/core/src/main/kotlin/Kotlin/KotlinElementSignatureProvider.kt new file mode 100644 index 00000000..4f788634 --- /dev/null +++ b/core/src/main/kotlin/Kotlin/KotlinElementSignatureProvider.kt @@ -0,0 +1,31 @@ +package org.jetbrains.dokka + +import com.intellij.psi.PsiElement +import com.intellij.psi.PsiMember +import com.intellij.psi.PsiNameIdentifierOwner +import org.jetbrains.kotlin.asJava.elements.KtLightElement +import org.jetbrains.kotlin.descriptors.DeclarationDescriptor +import org.jetbrains.kotlin.resolve.BindingContext +import javax.inject.Inject + +class KotlinElementSignatureProvider @Inject constructor( + val resolutionFacade: DokkaResolutionFacade +) : ElementSignatureProvider { + override fun signature(forPsi: PsiElement): String { + + val desc = when (forPsi) { + is KtLightElement<*, *> -> return signature(forPsi.kotlinOrigin!!) + is PsiMember -> forPsi.getJavaOrKotlinMemberDescriptor(resolutionFacade) + else -> resolutionFacade.resolveSession.bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, forPsi] + } + + if (desc == null && (forPsi as? PsiNameIdentifierOwner)?.name == "remove") { + (forPsi as? PsiMember)?.getJavaOrKotlinMemberDescriptor(resolutionFacade) + } + + return desc?.let { signature(it) } + ?: run { "no desc for $forPsi in ${(forPsi as? PsiMember)?.containingClass}" } + } + + override fun signature(forDesc: DeclarationDescriptor): String = forDesc.signature() +} \ No newline at end of file diff --git a/core/src/main/kotlin/Model/DescriptorSignatureProvider.kt b/core/src/main/kotlin/Model/DescriptorSignatureProvider.kt deleted file mode 100644 index 85584e3c..00000000 --- a/core/src/main/kotlin/Model/DescriptorSignatureProvider.kt +++ /dev/null @@ -1,7 +0,0 @@ -package org.jetbrains.dokka.Model - -import org.jetbrains.kotlin.descriptors.DeclarationDescriptor - -interface DescriptorSignatureProvider { - fun signature(forDesc: DeclarationDescriptor): String -} \ No newline at end of file diff --git a/core/src/main/kotlin/Model/DocumentationNode.kt b/core/src/main/kotlin/Model/DocumentationNode.kt index 84501d2b..4739d736 100644 --- a/core/src/main/kotlin/Model/DocumentationNode.kt +++ b/core/src/main/kotlin/Model/DocumentationNode.kt @@ -176,16 +176,17 @@ val DocumentationNode.path: List return parent.path + this } -fun DocumentationNode.findOrCreatePackageNode(packageName: String, packageContent: Map, refGraph: NodeReferenceGraph): DocumentationNode { - val existingNode = members(NodeKind.Package).firstOrNull { it.name == packageName } +fun findOrCreatePackageNode(module: DocumentationNode?, packageName: String, packageContent: Map, refGraph: NodeReferenceGraph): DocumentationNode { + val existingNode = refGraph.lookup(packageName) if (existingNode != null) { return existingNode } val newNode = DocumentationNode(packageName, packageContent.getOrElse(packageName) { Content.Empty }, NodeKind.Package) - append(newNode, RefKind.Member) + refGraph.register(packageName, newNode) + module?.append(newNode, RefKind.Member) return newNode } diff --git a/core/src/main/kotlin/Model/ElementSignatureProvider.kt b/core/src/main/kotlin/Model/ElementSignatureProvider.kt new file mode 100644 index 00000000..e8fdde6e --- /dev/null +++ b/core/src/main/kotlin/Model/ElementSignatureProvider.kt @@ -0,0 +1,9 @@ +package org.jetbrains.dokka + +import com.intellij.psi.PsiElement +import org.jetbrains.kotlin.descriptors.DeclarationDescriptor + +interface ElementSignatureProvider { + fun signature(forDesc: DeclarationDescriptor): String + fun signature(forPsi: PsiElement): String +} \ No newline at end of file diff --git a/core/src/main/kotlin/Utilities/DokkaModules.kt b/core/src/main/kotlin/Utilities/DokkaModules.kt index 36704918..907d5ca7 100644 --- a/core/src/main/kotlin/Utilities/DokkaModules.kt +++ b/core/src/main/kotlin/Utilities/DokkaModules.kt @@ -2,14 +2,11 @@ package org.jetbrains.dokka.Utilities import com.google.inject.Binder import com.google.inject.Module -import com.google.inject.Provider import com.google.inject.TypeLiteral import com.google.inject.binder.AnnotatedBindingBuilder import com.google.inject.name.Names import org.jetbrains.dokka.* import org.jetbrains.dokka.Formats.FormatDescriptor -import org.jetbrains.dokka.Model.DescriptorSignatureProvider -import org.jetbrains.dokka.Samples.SampleProcessingService import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment import java.io.File import kotlin.reflect.KClass -- cgit From 27deff9e3f8bb2190115f2e5f68f859f46af11a3 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Tue, 24 Apr 2018 20:37:18 +0300 Subject: Fix checking belonging to public API --- core/src/main/kotlin/Kotlin/DocumentationBuilder.kt | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt index 05bd2cc7..8fec0bfb 100644 --- a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt +++ b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt @@ -960,12 +960,10 @@ class DocumentationBuilder } -val visibleToDocumentation = setOf(Visibilities.PROTECTED, Visibilities.PUBLIC) - fun DeclarationDescriptor.isDocumented(options: DocumentationOptions): Boolean { return (options.effectivePackageOptions(fqNameSafe).includeNonPublic || this !is MemberDescriptor - || this.visibility in visibleToDocumentation) + || this.visibility.isPublicAPI) && !isDocumentationSuppressed(options) && (!options.effectivePackageOptions(fqNameSafe).skipDeprecated || !isDeprecated()) } -- cgit From 54874733ff84998d26e21b57384ad3b2ca151fc2 Mon Sep 17 00:00:00 2001 From: Douglas Sigelbaum Date: Tue, 24 Apr 2018 20:27:21 -0700 Subject: [backport] Added logic for inherited constants. Also, switched to using recursively inherited members instead of just inherited members in the immediate super class. Original: 56c3558 --- core/src/main/kotlin/Model/DocumentationNode.kt | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Model/DocumentationNode.kt b/core/src/main/kotlin/Model/DocumentationNode.kt index 4739d736..ca298802 100644 --- a/core/src/main/kotlin/Model/DocumentationNode.kt +++ b/core/src/main/kotlin/Model/DocumentationNode.kt @@ -1,5 +1,6 @@ package org.jetbrains.dokka +import org.jetbrains.dokka.Formats.constantValue import java.util.* enum class NodeKind { @@ -86,6 +87,8 @@ open class DocumentationNode(val name: String, get() = references(RefKind.Member).map { it.to } val inheritedMembers: List get() = references(RefKind.InheritedMember).map { it.to } + val allInheritedMembers: List + get() = recursiveInheritedMembers() val inheritedCompanionObjectMembers: List get() = references(RefKind.InheritedCompanionObjectMember).map { it.to } val extensions: List @@ -145,7 +148,6 @@ open class DocumentationNode(val name: String, } (content as MutableContent).body() } - fun details(kind: NodeKind): List = details.filter { it.kind == kind } fun members(kind: NodeKind): List = members.filter { it.kind == kind } fun inheritedMembers(kind: NodeKind): List = inheritedMembers.filter { it.kind == kind } @@ -217,3 +219,17 @@ fun DocumentationNode.qualifiedName(): String { } fun DocumentationNode.simpleName() = name.substringAfterLast('.') + +private fun DocumentationNode.recursiveInheritedMembers(): List { + val allInheritedMembers = mutableListOf() + recursiveInheritedMembers(allInheritedMembers) + return allInheritedMembers +} + +private fun DocumentationNode.recursiveInheritedMembers(allInheritedMembers: MutableList) { + allInheritedMembers.addAll(inheritedMembers) + System.out.println(allInheritedMembers.size) + inheritedMembers.groupBy { it.owner!! } .forEach { (node, _) -> + node.recursiveInheritedMembers(allInheritedMembers) + } +} \ No newline at end of file -- cgit From f8c358a6a5b269a8dcd5240db8dd14a497c261c2 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Thu, 26 Apr 2018 18:04:18 +0300 Subject: KT-24036: Don't show visibility modifiers in summary --- core/src/main/kotlin/Kotlin/KotlinLanguageService.kt | 9 ++++++--- core/src/main/kotlin/Languages/CommonLanguageService.kt | 1 + core/src/main/kotlin/Languages/NewJavaLanguageService.kt | 10 ++++++---- 3 files changed, 13 insertions(+), 7 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt b/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt index 79350237..613b9451 100644 --- a/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt +++ b/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt @@ -23,7 +23,7 @@ class KotlinLanguageService : CommonLanguageService() { NodeKind.Type, NodeKind.UpperBound -> renderType(node, renderMode) - NodeKind.Modifier -> renderModifier(this, node) + NodeKind.Modifier -> renderModifier(this, node, renderMode) NodeKind.Constructor, NodeKind.Function, NodeKind.CompanionObjectFunction -> renderFunction(node, renderMode) @@ -188,13 +188,16 @@ class KotlinLanguageService : CommonLanguageService() { override fun renderModifier( block: ContentBlock, node: DocumentationNode, + renderMode: RenderMode, nowrap: Boolean ) { when (node.name) { "final", "public", "var" -> { } else -> { - super.renderModifier(block, node, nowrap) + if (node.name !in fullOnlyModifiers || renderMode == RenderMode.FULL) { + super.renderModifier(block, node, renderMode, nowrap) + } } } } @@ -289,7 +292,7 @@ class KotlinLanguageService : CommonLanguageService() { if (renderMode == RenderMode.SUMMARY && it.name in fullOnlyModifiers) { continue } - renderModifier(this, it, nowrap) + renderModifier(this, it, renderMode, nowrap) } } diff --git a/core/src/main/kotlin/Languages/CommonLanguageService.kt b/core/src/main/kotlin/Languages/CommonLanguageService.kt index f155192d..edefa1b5 100644 --- a/core/src/main/kotlin/Languages/CommonLanguageService.kt +++ b/core/src/main/kotlin/Languages/CommonLanguageService.kt @@ -19,6 +19,7 @@ abstract class CommonLanguageService : LanguageService { open fun renderModifier( block: ContentBlock, node: DocumentationNode, + renderMode: LanguageService.RenderMode, nowrap: Boolean = false ) = with(block) { keyword(node.name) diff --git a/core/src/main/kotlin/Languages/NewJavaLanguageService.kt b/core/src/main/kotlin/Languages/NewJavaLanguageService.kt index 22ad62b2..0266c033 100644 --- a/core/src/main/kotlin/Languages/NewJavaLanguageService.kt +++ b/core/src/main/kotlin/Languages/NewJavaLanguageService.kt @@ -1,16 +1,18 @@ package org.jetbrains.dokka +import org.jetbrains.dokka.LanguageService.RenderMode + /** * Implements [LanguageService] and provides rendering of symbols in Java language */ class NewJavaLanguageService : CommonLanguageService() { - override fun render(node: DocumentationNode, renderMode: LanguageService.RenderMode): ContentNode { + override fun render(node: DocumentationNode, renderMode: RenderMode): ContentNode { return content { (when (node.kind) { NodeKind.Package -> renderPackage(node) in NodeKind.classLike -> renderClass(node) - NodeKind.Modifier -> renderModifier(this, node) + NodeKind.Modifier -> renderModifier(this, node, renderMode) NodeKind.TypeParameter -> renderTypeParameter(node) NodeKind.Type, NodeKind.UpperBound -> renderType(node) @@ -26,11 +28,11 @@ class NewJavaLanguageService : CommonLanguageService() { override fun summarizeSignatures(nodes: List): ContentNode? = null - override fun renderModifier(block: ContentBlock, node: DocumentationNode, nowrap: Boolean) { + override fun renderModifier(block: ContentBlock, node: DocumentationNode, renderMode: RenderMode, nowrap: Boolean) { when (node.name) { "open", "internal" -> { } - else -> super.renderModifier(block, node, nowrap) + else -> super.renderModifier(block, node, renderMode, nowrap) } } -- cgit From 9539284e5dd72e2676dc5d656b78f21c1c7035ee Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Thu, 26 Apr 2018 19:37:07 +0300 Subject: KT-24109: Fix generation of superclass sequence --- core/src/main/kotlin/Kotlin/DocumentationBuilder.kt | 10 +++++++++- core/src/main/kotlin/Model/DocumentationNode.kt | 16 +++++++++++++--- 2 files changed, 22 insertions(+), 4 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt index 8fec0bfb..cb35e568 100644 --- a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt +++ b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt @@ -34,6 +34,7 @@ import org.jetbrains.kotlin.resolve.source.PsiSourceElement import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.types.* import org.jetbrains.kotlin.types.typeUtil.supertypes +import org.jetbrains.kotlin.util.supertypesWithAny import java.io.File import java.nio.file.Path import java.nio.file.Paths @@ -645,7 +646,7 @@ class DocumentationBuilder } val node = nodeForDescriptor(this, kind, external) register(this, node) - typeConstructor.supertypes.forEach { + supertypesWithAnyPrecise().forEach { node.appendSupertype(this, it, !external) } if (getKind() != ClassKind.OBJECT && getKind() != ClassKind.ENUM_ENTRY) { @@ -1152,3 +1153,10 @@ fun DocumentationNode.generateAllTypesNode() { append(allTypesNode, RefKind.Member) } + +fun ClassDescriptor.supertypesWithAnyPrecise(): Collection { + if (KotlinBuiltIns.isAny(this)) { + return emptyList() + } + return typeConstructor.supertypesWithAny() +} \ No newline at end of file diff --git a/core/src/main/kotlin/Model/DocumentationNode.kt b/core/src/main/kotlin/Model/DocumentationNode.kt index ca298802..a89f5080 100644 --- a/core/src/main/kotlin/Model/DocumentationNode.kt +++ b/core/src/main/kotlin/Model/DocumentationNode.kt @@ -1,6 +1,7 @@ package org.jetbrains.dokka import org.jetbrains.dokka.Formats.constantValue +import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult import java.util.* enum class NodeKind { @@ -115,11 +116,12 @@ open class DocumentationNode(val name: String, val superclassType: DocumentationNode? get() = when (kind) { - NodeKind.Supertype -> (links.firstOrNull { it.kind in NodeKind.classLike } ?: externalType)?.superclassType + NodeKind.Supertype -> { + (links + listOfNotNull(externalType)).firstOrNull { it.kind in NodeKind.classLike }?.superclassType + } NodeKind.Interface -> null in NodeKind.classLike -> supertypes.firstOrNull { - it.links.any { it.kind in NodeKind.classLike } || - it.externalType != null + (it.links + listOfNotNull(it.externalType)).any { it.isSuperclassFor(this) } } else -> null } @@ -232,4 +234,12 @@ private fun DocumentationNode.recursiveInheritedMembers(allInheritedMembers: Mut inheritedMembers.groupBy { it.owner!! } .forEach { (node, _) -> node.recursiveInheritedMembers(allInheritedMembers) } +} + +private fun DocumentationNode.isSuperclassFor(node: DocumentationNode): Boolean { + return when(node.kind) { + NodeKind.Object, NodeKind.Class, NodeKind.Enum -> kind == NodeKind.Class + NodeKind.Exception -> kind == NodeKind.Class || kind == NodeKind.Exception + else -> false + } } \ No newline at end of file -- cgit From d8e3a6b6811569b77d2b523df6ade772ef38dde1 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Thu, 26 Apr 2018 21:29:36 +0300 Subject: KT-24113: Render inner classes names qualified --- core/src/main/kotlin/Kotlin/KotlinLanguageService.kt | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt b/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt index 613b9451..75d9fbbf 100644 --- a/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt +++ b/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt @@ -1,5 +1,6 @@ package org.jetbrains.dokka +import org.jetbrains.dokka.Formats.classNodeNameWithOuterClass import org.jetbrains.dokka.LanguageService.RenderMode /** @@ -170,7 +171,9 @@ class KotlinLanguageService : CommonLanguageService() { renderAnnotationsForNode(node) } renderModifiersForNode(node, renderMode, true) - renderLinked(this, node) { identifier(it.name, IdentifierKind.TypeName) } + renderLinked(this, node) { + identifier(it.typeDeclarationClass?.classNodeNameWithOuterClass() ?: it.name, IdentifierKind.TypeName) + } val typeArguments = node.details(NodeKind.Type) if (typeArguments.isNotEmpty()) { symbol("<") @@ -367,7 +370,7 @@ class KotlinLanguageService : CommonLanguageService() { renderReceiver(node, renderMode, signatureMapper) - if (node.kind != org.jetbrains.dokka.NodeKind.Constructor) + if (node.kind != NodeKind.Constructor) identifierOrDeprecated(node) symbol("(") @@ -467,3 +470,7 @@ fun DocumentationNode.qualifiedNameFromType(): String { ?: (links.firstOrNull() ?: hiddenLinks.firstOrNull())?.qualifiedName() ?: name } + + +private val DocumentationNode.typeDeclarationClass + get() = (links.firstOrNull { it.kind in NodeKind.classLike } ?: externalType) -- cgit From 9831944e07b5acd5558d901cefa0ba49c24d91ff Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Thu, 26 Apr 2018 22:24:20 +0300 Subject: [backport] Make accessible Original: 44ec370 KT-24039: Support Inherited xml attributes --- core/src/main/kotlin/Kotlin/KotlinLanguageService.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt b/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt index 75d9fbbf..b6474583 100644 --- a/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt +++ b/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt @@ -472,5 +472,5 @@ fun DocumentationNode.qualifiedNameFromType(): String { } -private val DocumentationNode.typeDeclarationClass +val DocumentationNode.typeDeclarationClass get() = (links.firstOrNull { it.kind in NodeKind.classLike } ?: externalType) -- cgit From eba83fb593ebae4c3d1498969feb0dc5a085689c Mon Sep 17 00:00:00 2001 From: Douglas Sigelbaum Date: Fri, 27 Apr 2018 10:42:49 -0700 Subject: [backport] Sort by lowercase name everywhere. Original: 2ca99c2 --- core/src/main/kotlin/Formats/OutlineService.kt | 2 +- core/src/main/kotlin/Formats/StructuredFormatService.kt | 2 +- core/src/main/kotlin/Kotlin/DocumentationBuilder.kt | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Formats/OutlineService.kt b/core/src/main/kotlin/Formats/OutlineService.kt index 3c31ba57..958e93af 100644 --- a/core/src/main/kotlin/Formats/OutlineService.kt +++ b/core/src/main/kotlin/Formats/OutlineService.kt @@ -16,7 +16,7 @@ interface OutlineFormatService { for (node in nodes) { appendOutlineHeader(location, node, to) if (node.members.any()) { - val sortedMembers = node.members.sortedBy { it.name } + val sortedMembers = node.members.sortedBy { it.name.toLowerCase() } appendOutlineLevel(to) { appendOutline(location, to, sortedMembers) } diff --git a/core/src/main/kotlin/Formats/StructuredFormatService.kt b/core/src/main/kotlin/Formats/StructuredFormatService.kt index 952e14cf..ebc9cde6 100644 --- a/core/src/main/kotlin/Formats/StructuredFormatService.kt +++ b/core/src/main/kotlin/Formats/StructuredFormatService.kt @@ -570,7 +570,7 @@ abstract class StructuredOutputBuilder(val to: StringBuilder, appendHeader(3) { appendText(caption) } - val children = if (sortMembers) members.sortedBy { it.name } else members + val children = if (sortMembers) members.sortedBy { it.name.toLowerCase() } else members val membersMap = children.groupBy { link(node, it) } diff --git a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt index cb35e568..88fe7095 100644 --- a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt +++ b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt @@ -1144,7 +1144,7 @@ fun DocumentationModule.prepareForGeneration(options: DocumentationOptions) { fun DocumentationNode.generateAllTypesNode() { val allTypes = members(NodeKind.Package) .flatMap { it.members.filter { it.kind in NodeKind.classLike || it.kind == NodeKind.ExternalClass } } - .sortedBy { if (it.kind == NodeKind.ExternalClass) it.name.substringAfterLast('.') else it.name } + .sortedBy { if (it.kind == NodeKind.ExternalClass) it.name.substringAfterLast('.').toLowerCase() else it.name.toLowerCase() } val allTypesNode = DocumentationNode("alltypes", Content.Empty, NodeKind.AllTypes) for (typeNode in allTypes) { -- cgit From 57a6bb55ddafbde4eab7c1c4344fff3ad3f0fe1f Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Fri, 27 Apr 2018 18:05:35 +0300 Subject: [backport] KT-24042: Fix structure of content paragraphs in Javadoc parser Original: edc0581 --- core/src/main/kotlin/Java/JavadocParser.kt | 29 +++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Java/JavadocParser.kt b/core/src/main/kotlin/Java/JavadocParser.kt index 365ae298..08ae5354 100644 --- a/core/src/main/kotlin/Java/JavadocParser.kt +++ b/core/src/main/kotlin/Java/JavadocParser.kt @@ -30,9 +30,18 @@ class JavadocParser( if (docComment == null) return JavadocParseResult.Empty val result = MutableContent() var deprecatedContent: Content? = null - val para = ContentParagraph() - result.append(para) - para.convertJavadocElements(docComment.descriptionElements.dropWhile { it.text.trim().isEmpty() }) + val firstParagraph = ContentParagraph() + firstParagraph.convertJavadocElements(docComment.descriptionElements.dropWhile { it.text.trim().isEmpty() }) + val paragraphs = firstParagraph.children.dropWhile { it !is ContentParagraph } + firstParagraph.children.removeAll(paragraphs) + if (!firstParagraph.isEmpty()) { + result.append(firstParagraph) + } + paragraphs.forEach { + result.append(it) + } + val attrs = mutableListOf() + var since: DocumentationNode? = null docComment.tags.forEach { tag -> when (tag.name) { "see" -> result.convertSeeTag(tag) @@ -70,20 +79,24 @@ class JavadocParser( } val doc = Jsoup.parse(htmlBuilder.toString().trim()) doc.body().childNodes().forEach { - convertHtmlNode(it) + convertHtmlNode(it)?.let { append(it) } } } - private fun ContentBlock.convertHtmlNode(node: Node) { + private fun convertHtmlNode(node: Node): ContentNode? { if (node is TextNode) { - append(ContentText(node.text())) + return ContentText(node.text()) } else if (node is Element) { val childBlock = createBlock(node) node.childNodes().forEach { - childBlock.convertHtmlNode(it) + val child = convertHtmlNode(it) + if (child != null) { + childBlock.append(child) + } } - append(childBlock) + return (childBlock) } + return null } private fun createBlock(element: Element): ContentBlock = when (element.tagName()) { -- cgit From 6cfaf04a6a0a34299d3a39803322b2eea2afbaac Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Fri, 27 Apr 2018 19:42:25 +0300 Subject: [backport] KT-24149: Fix resolution of links in Javadoc Original: edc0581 --- core/src/main/kotlin/Java/JavadocParser.kt | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Java/JavadocParser.kt b/core/src/main/kotlin/Java/JavadocParser.kt index 08ae5354..0869081b 100644 --- a/core/src/main/kotlin/Java/JavadocParser.kt +++ b/core/src/main/kotlin/Java/JavadocParser.kt @@ -1,10 +1,12 @@ package org.jetbrains.dokka import com.intellij.psi.* +import com.intellij.psi.impl.source.tree.JavaDocElementType import com.intellij.psi.javadoc.PsiDocTag import com.intellij.psi.javadoc.PsiDocTagValue import com.intellij.psi.javadoc.PsiDocToken import com.intellij.psi.javadoc.PsiInlineDocTag +import com.intellij.psi.util.PsiTreeUtil import org.jsoup.Jsoup import org.jsoup.nodes.Element import org.jsoup.nodes.Node @@ -130,11 +132,11 @@ class JavadocParser( private fun MutableContent.convertSeeTag(tag: PsiDocTag) { val linkElement = tag.linkElement() ?: return val seeSection = findSectionByTag(ContentTags.SeeAlso) ?: addSection(ContentTags.SeeAlso, null) - val linkSignature = resolveLink(linkElement) + val linkSignature = resolveLink(tag.referenceElement()) val text = ContentText(linkElement.text) if (linkSignature != null) { val linkNode = - ContentNodeLazyLink(tag.valueElement!!.text, { -> refGraph.lookupOrWarn(linkSignature, logger) }) + ContentNodeLazyLink((tag.valueElement ?: linkElement).text, { -> refGraph.lookupOrWarn(linkSignature, logger) }) linkNode.append(text) seeSection.append(linkNode) } else { @@ -144,7 +146,7 @@ class JavadocParser( private fun convertInlineDocTag(tag: PsiInlineDocTag) = when (tag.name) { "link", "linkplain" -> { - val valueElement = tag.linkElement() + val valueElement = tag.referenceElement() val linkSignature = resolveLink(valueElement) if (linkSignature != null) { val labelText = tag.dataElements.firstOrNull { it is PsiDocToken }?.text ?: valueElement!!.text @@ -165,6 +167,15 @@ class JavadocParser( else -> tag.text } + private fun PsiDocTag.referenceElement(): PsiElement? = + linkElement()?.let { + if (it.node.elementType == JavaDocElementType.DOC_REFERENCE_HOLDER) { + PsiTreeUtil.findChildOfType(it, PsiJavaCodeReferenceElement::class.java) + } else { + it + } + } + private fun PsiDocTag.linkElement(): PsiElement? = valueElement ?: dataElements.firstOrNull { it !is PsiWhiteSpace } -- cgit From 432868e8732085a0b160466ddbe8262b793b4f95 Mon Sep 17 00:00:00 2001 From: Sean McQuillan Date: Thu, 26 Apr 2018 18:03:04 -0700 Subject: [backport] Support for {@inheritDoc} including grand inheritance and skip levels. Original: f100b73 --- core/src/main/kotlin/Java/JavadocParser.kt | 127 +++++++++++++++++++++++++---- 1 file changed, 113 insertions(+), 14 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Java/JavadocParser.kt b/core/src/main/kotlin/Java/JavadocParser.kt index 0869081b..f88f557d 100644 --- a/core/src/main/kotlin/Java/JavadocParser.kt +++ b/core/src/main/kotlin/Java/JavadocParser.kt @@ -2,11 +2,10 @@ package org.jetbrains.dokka import com.intellij.psi.* import com.intellij.psi.impl.source.tree.JavaDocElementType -import com.intellij.psi.javadoc.PsiDocTag -import com.intellij.psi.javadoc.PsiDocTagValue -import com.intellij.psi.javadoc.PsiDocToken -import com.intellij.psi.javadoc.PsiInlineDocTag +import com.intellij.psi.javadoc.* import com.intellij.psi.util.PsiTreeUtil +import com.intellij.util.IncorrectOperationException +import com.intellij.util.containers.isNullOrEmpty import org.jsoup.Jsoup import org.jsoup.nodes.Element import org.jsoup.nodes.Node @@ -33,7 +32,7 @@ class JavadocParser( val result = MutableContent() var deprecatedContent: Content? = null val firstParagraph = ContentParagraph() - firstParagraph.convertJavadocElements(docComment.descriptionElements.dropWhile { it.text.trim().isEmpty() }) + firstParagraph.convertJavadocElements(docComment.descriptionElements.dropWhile { it.text.trim().isEmpty() }, element) val paragraphs = firstParagraph.children.dropWhile { it !is ContentParagraph } firstParagraph.children.removeAll(paragraphs) if (!firstParagraph.isEmpty()) { @@ -49,13 +48,13 @@ class JavadocParser( "see" -> result.convertSeeTag(tag) "deprecated" -> { deprecatedContent = Content() - deprecatedContent!!.convertJavadocElements(tag.contentElements()) + deprecatedContent!!.convertJavadocElements(tag.contentElements(), element) } else -> { val subjectName = tag.getSubjectName() val section = result.addSection(javadocSectionDisplayName(tag.name), subjectName) - section.convertJavadocElements(tag.contentElements()) + section.convertJavadocElements(tag.contentElements(), element) } } } @@ -70,19 +69,23 @@ class JavadocParser( return if (getSubjectName() != null) tagValueElements.dropWhile { it is PsiDocTagValue } else tagValueElements } - private fun ContentBlock.convertJavadocElements(elements: Iterable) { + private fun ContentBlock.convertJavadocElements(elements: Iterable, element: PsiNamedElement) { + val doc = Jsoup.parse(expandAllForElements(elements, element)) + doc.body().childNodes().forEach { + convertHtmlNode(it)?.let { append(it) } + } + } + + private fun expandAllForElements(elements: Iterable, element: PsiNamedElement): String { val htmlBuilder = StringBuilder() elements.forEach { if (it is PsiInlineDocTag) { - htmlBuilder.append(convertInlineDocTag(it)) + htmlBuilder.append(convertInlineDocTag(it, element)) } else { htmlBuilder.append(it.text) } } - val doc = Jsoup.parse(htmlBuilder.toString().trim()) - doc.body().childNodes().forEach { - convertHtmlNode(it)?.let { append(it) } - } + return htmlBuilder.toString().trim() } private fun convertHtmlNode(node: Node): ContentNode? { @@ -144,7 +147,7 @@ class JavadocParser( } } - private fun convertInlineDocTag(tag: PsiInlineDocTag) = when (tag.name) { + private fun convertInlineDocTag(tag: PsiInlineDocTag, element: PsiNamedElement) = when (tag.name) { "link", "linkplain" -> { val valueElement = tag.referenceElement() val linkSignature = resolveLink(valueElement) @@ -164,6 +167,18 @@ class JavadocParser( val escaped = text.toString().trimStart().htmlEscape() if (tag.name == "code") "$escaped" else escaped } + "inheritDoc" -> { + val result = (element as? PsiMethod)?.let { + // @{inheritDoc} is only allowed on functions + val parent = tag.parent + when (parent) { + is PsiDocComment -> element.findSuperDocCommentOrWarn() + is PsiDocTag -> element.findSuperDocTagOrWarn(parent) + else -> null + } + } + result ?: tag.text + } else -> tag.text } @@ -193,4 +208,88 @@ class JavadocParser( } return null } + + private fun PsiMethod.findSuperDocCommentOrWarn(): String { + val method = findFirstSuperMethodWithDocumentation(this) + if (method != null) { + val descriptionElements = method.docComment?.descriptionElements?.dropWhile { + it.text.trim().isEmpty() + } ?: return "" + + return expandAllForElements(descriptionElements, method) + } + logger.warn("No docs found on supertype with {@inheritDoc} method ${this.name} in ${this.containingFile.name}:${this.lineNumber()}") + return "" + } + + + private fun PsiMethod.findSuperDocTagOrWarn(elementToExpand: PsiDocTag): String { + val result = findFirstSuperMethodWithDocumentationforTag(elementToExpand, this) + + if (result != null) { + val (method, tag) = result + + val contentElements = tag.contentElements().dropWhile { it.text.trim().isEmpty() } + + val expandedString = expandAllForElements(contentElements, method) + + return expandedString + } + logger.warn("No docs found on supertype for @${elementToExpand.name} ${elementToExpand.getSubjectName()} with {@inheritDoc} method ${this.name} in ${this.containingFile.name}:${this.lineNumber()}") + return "" + } + + private fun findFirstSuperMethodWithDocumentation(current: PsiMethod): PsiMethod? { + val superMethods = current.findSuperMethods() + for (method in superMethods) { + val docs = method.docComment?.descriptionElements?.dropWhile { it.text.trim().isEmpty() } + if (!docs.isNullOrEmpty()) { + return method + } + } + for (method in superMethods) { + val result = findFirstSuperMethodWithDocumentation(method) + if (result != null) { + return result + } + } + + return null + } + + private fun findFirstSuperMethodWithDocumentationforTag(elementToExpand: PsiDocTag, current: PsiMethod): Pair? { + val superMethods = current.findSuperMethods() + val mappedFilteredTags = superMethods.map { + it to it.docComment?.tags?.filter { it.name == elementToExpand.name } + } + + for ((method, tags) in mappedFilteredTags) { + tags ?: continue + for (tag in tags) { + val (tagSubject, elementSubject) = when (tag.name) { + "throws" -> { + // match class names only for throws, ignore possibly fully qualified path + // TODO: Always match exactly here + tag.getSubjectName()?.split(".")?.last() to elementToExpand.getSubjectName()?.split(".")?.last() + } + else -> { + tag.getSubjectName() to elementToExpand.getSubjectName() + } + } + + if (tagSubject == elementSubject) { + return method to tag + } + } + } + + for (method in superMethods) { + val result = findFirstSuperMethodWithDocumentationforTag(elementToExpand, method) + if (result != null) { + return result + } + } + return null + } + } -- cgit From a16ae6c02e1ec7270fb161c63908b5b3831bce8e Mon Sep 17 00:00:00 2001 From: Sean McQuillan Date: Thu, 26 Apr 2018 18:03:04 -0700 Subject: [backport] Support for {@inheritDoc} including grand inheritance and skip levels. Original: 0eda743 --- core/src/main/kotlin/Java/JavadocParser.kt | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Java/JavadocParser.kt b/core/src/main/kotlin/Java/JavadocParser.kt index f88f557d..554cd2d3 100644 --- a/core/src/main/kotlin/Java/JavadocParser.kt +++ b/core/src/main/kotlin/Java/JavadocParser.kt @@ -1,6 +1,8 @@ package org.jetbrains.dokka import com.intellij.psi.* +import com.intellij.psi.impl.source.javadoc.CorePsiDocTagValueImpl +import com.intellij.psi.javadoc.* import com.intellij.psi.impl.source.tree.JavaDocElementType import com.intellij.psi.javadoc.* import com.intellij.psi.util.PsiTreeUtil @@ -41,14 +43,13 @@ class JavadocParser( paragraphs.forEach { result.append(it) } - val attrs = mutableListOf() - var since: DocumentationNode? = null docComment.tags.forEach { tag -> when (tag.name) { "see" -> result.convertSeeTag(tag) "deprecated" -> { - deprecatedContent = Content() - deprecatedContent!!.convertJavadocElements(tag.contentElements(), element) + deprecatedContent = Content().apply { + convertJavadocElements(tag.contentElements(), element) + } } else -> { val subjectName = tag.getSubjectName() -- cgit From ee0b640ad5c4a8cc1b65403dc2c48e7723b8f53a Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Thu, 3 May 2018 18:18:53 +0300 Subject: Fix resolution of package links --- core/src/main/kotlin/Kotlin/KotlinElementSignatureProvider.kt | 3 +++ 1 file changed, 3 insertions(+) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Kotlin/KotlinElementSignatureProvider.kt b/core/src/main/kotlin/Kotlin/KotlinElementSignatureProvider.kt index 4f788634..0a377dc1 100644 --- a/core/src/main/kotlin/Kotlin/KotlinElementSignatureProvider.kt +++ b/core/src/main/kotlin/Kotlin/KotlinElementSignatureProvider.kt @@ -3,8 +3,10 @@ package org.jetbrains.dokka import com.intellij.psi.PsiElement import com.intellij.psi.PsiMember import com.intellij.psi.PsiNameIdentifierOwner +import com.intellij.psi.PsiPackage import org.jetbrains.kotlin.asJava.elements.KtLightElement import org.jetbrains.kotlin.descriptors.DeclarationDescriptor +import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.resolve.BindingContext import javax.inject.Inject @@ -15,6 +17,7 @@ class KotlinElementSignatureProvider @Inject constructor( val desc = when (forPsi) { is KtLightElement<*, *> -> return signature(forPsi.kotlinOrigin!!) + is PsiPackage -> resolutionFacade.moduleDescriptor.getPackage(FqName(forPsi.qualifiedName)) is PsiMember -> forPsi.getJavaOrKotlinMemberDescriptor(resolutionFacade) else -> resolutionFacade.resolveSession.bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, forPsi] } -- cgit From 74b228108445a8a9024b6892f6562d77c658fc64 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Thu, 3 May 2018 18:20:33 +0300 Subject: [backport] KT-24152: Support implicit sections inheritance Original: 5636fac --- core/src/main/kotlin/Java/JavadocParser.kt | 40 +++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Java/JavadocParser.kt b/core/src/main/kotlin/Java/JavadocParser.kt index 554cd2d3..41b77aed 100644 --- a/core/src/main/kotlin/Java/JavadocParser.kt +++ b/core/src/main/kotlin/Java/JavadocParser.kt @@ -2,12 +2,12 @@ package org.jetbrains.dokka import com.intellij.psi.* import com.intellij.psi.impl.source.javadoc.CorePsiDocTagValueImpl -import com.intellij.psi.javadoc.* import com.intellij.psi.impl.source.tree.JavaDocElementType import com.intellij.psi.javadoc.* import com.intellij.psi.util.PsiTreeUtil import com.intellij.util.IncorrectOperationException import com.intellij.util.containers.isNullOrEmpty +import org.jetbrains.kotlin.utils.keysToMap import org.jsoup.Jsoup import org.jsoup.nodes.Element import org.jsoup.nodes.Node @@ -43,6 +43,17 @@ class JavadocParser( paragraphs.forEach { result.append(it) } + + if (element is PsiMethod) { + val tagsByName = element.searchInheritedTags() + for ((tagName, tags) in tagsByName) { + for ((tag, context) in tags) { + val section = result.addSection(javadocSectionDisplayName(tagName), tag.getSubjectName()) + section.convertJavadocElements(tag.contentElements(), context) + } + } + } + docComment.tags.forEach { tag -> when (tag.name) { "see" -> result.convertSeeTag(tag) @@ -51,6 +62,7 @@ class JavadocParser( convertJavadocElements(tag.contentElements(), element) } } + in tagsToInherit -> {} else -> { val subjectName = tag.getSubjectName() val section = result.addSection(javadocSectionDisplayName(tag.name), subjectName) @@ -62,6 +74,32 @@ class JavadocParser( return JavadocParseResult(result, deprecatedContent) } + private val tagsToInherit = setOf("param", "return", "throws") + + private data class TagWithContext(val tag: PsiDocTag, val context: PsiNamedElement) + + private fun PsiMethod.searchInheritedTags(): Map> { + + val output = tagsToInherit.keysToMap { mutableMapOf() } + + fun recursiveSearch(methods: Array) { + for (method in methods) { + recursiveSearch(method.findSuperMethods()) + } + for (method in methods) { + for (tag in method.docComment?.tags.orEmpty()) { + if (tag.name in tagsToInherit) { + output[tag.name]!![tag.getSubjectName()] = TagWithContext(tag, method) + } + } + } + } + + recursiveSearch(arrayOf(this)) + return output.mapValues { it.value.values } + } + + private fun PsiDocTag.contentElements(): Iterable { val tagValueElements = children .dropWhile { it.node?.elementType == JavaDocTokenType.DOC_TAG_NAME } -- cgit From a50de81d3d0ce88d2fd8e91a55b203ba49e66eb1 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Fri, 4 May 2018 00:32:40 +0300 Subject: [backport] KT-24028: Add type info to param and return section in javadoc Original: a603157 --- core/src/main/kotlin/Java/JavadocParser.kt | 23 +++++++++++++++++++++++ core/src/main/kotlin/Model/Content.kt | 30 +++++++++++++++++++++++++++++- 2 files changed, 52 insertions(+), 1 deletion(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Java/JavadocParser.kt b/core/src/main/kotlin/Java/JavadocParser.kt index 41b77aed..5e23e357 100644 --- a/core/src/main/kotlin/Java/JavadocParser.kt +++ b/core/src/main/kotlin/Java/JavadocParser.kt @@ -28,6 +28,18 @@ class JavadocParser( private val logger: DokkaLogger, private val signatureProvider: ElementSignatureProvider ) : JavaDocumentationParser { + + private fun ContentSection.appendTypeElement(signature: String, selector: (DocumentationNode) -> DocumentationNode?) { + append(LazyContentBlock { + val node = refGraph.lookupOrWarn(signature, logger)?.let(selector) + if (node != null) { + it.append(NodeRenderContent(node, LanguageService.RenderMode.SUMMARY)) + it.symbol(":") + it.text(" ") + } + }) + } + override fun parseDocumentation(element: PsiNamedElement): JavadocParseResult { val docComment = (element as? PsiDocCommentOwner)?.docComment if (docComment == null) return JavadocParseResult.Empty @@ -49,6 +61,17 @@ class JavadocParser( for ((tagName, tags) in tagsByName) { for ((tag, context) in tags) { val section = result.addSection(javadocSectionDisplayName(tagName), tag.getSubjectName()) + val signature = signatureProvider.signature(element) + when (tagName) { + "param" -> { + section.appendTypeElement(signature) { + it.details.find { it.kind == NodeKind.Parameter }?.detailOrNull(NodeKind.Type) + } + } + "return" -> { + section.appendTypeElement(signature) { it.detailOrNull(NodeKind.Type) } + } + } section.convertJavadocElements(tag.contentElements(), context) } } diff --git a/core/src/main/kotlin/Model/Content.kt b/core/src/main/kotlin/Model/Content.kt index 1f5bbc83..010ee7ca 100644 --- a/core/src/main/kotlin/Model/Content.kt +++ b/core/src/main/kotlin/Model/Content.kt @@ -9,7 +9,7 @@ object ContentEmpty : ContentNode { } open class ContentBlock() : ContentNode { - val children = arrayListOf() + open val children = arrayListOf() fun append(node: ContentNode) { children.add(node) @@ -27,6 +27,34 @@ open class ContentBlock() : ContentNode { get() = children.sumBy { it.textLength } } +class NodeRenderContent( + val node: DocumentationNode, + val mode: LanguageService.RenderMode +): ContentNode { + override val textLength: Int + get() = 0 //TODO: Clarify? +} + +class LazyContentBlock(private val fillChildren: (ContentBlock) -> Unit) : ContentBlock() { + private var computed = false + override val children: ArrayList + get() { + if (!computed) { + computed = true + fillChildren(this) + } + return super.children + } + + override fun equals(other: Any?): Boolean { + return other is LazyContentBlock && other.fillChildren == fillChildren && super.equals(other) + } + + override fun hashCode(): Int { + return super.hashCode() + 31 * fillChildren.hashCode() + } +} + enum class IdentifierKind { TypeName, ParameterName, -- cgit From cf8b820682cf7af82d15f46f742d63a7766fe95e Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Fri, 4 May 2018 18:31:06 +0300 Subject: KT-24270: Render platform-types with bang --- core/src/main/kotlin/Kotlin/DocumentationBuilder.kt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt index 88fe7095..c165045d 100644 --- a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt +++ b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt @@ -242,7 +242,9 @@ class DocumentationBuilder if (prefix != "") { node.appendTextNode(prefix, NodeKind.Modifier) } - if (kotlinType.isMarkedNullable) { + if (kotlinType.isNullabilityFlexible()) { + node.appendTextNode("!", NodeKind.NullabilityModifier) + } else if (kotlinType.isNullable()) { node.appendTextNode("?", NodeKind.NullabilityModifier) } if (classifierDescriptor != null) { -- cgit From b00dabc4c53a71f745c29a135541b02f8dd7d266 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Fri, 4 May 2018 21:35:02 +0300 Subject: [backport] KT-24271: Support external link resolution in JavadocParser Original: ace3914 --- .../main/kotlin/Analysis/AnalysisEnvironment.kt | 8 ++-- .../kotlin/Java/JavaPsiDocumentationBuilder.kt | 10 ++++- core/src/main/kotlin/Java/JavadocParser.kt | 51 ++++++++++++++++------ .../kotlin/Kotlin/DescriptorDocumentationParser.kt | 12 +++-- .../Kotlin/ExternalDocumentationLinkResolver.kt | 14 ++++-- .../Kotlin/KotlinElementSignatureProvider.kt | 30 ++++++------- core/src/main/kotlin/Utilities/DokkaModules.kt | 3 +- 7 files changed, 87 insertions(+), 41 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt b/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt index 6854b323..d31fe187 100644 --- a/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt +++ b/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt @@ -99,7 +99,7 @@ class AnalysisEnvironment(val messageCollector: MessageCollector) : Disposable { } - fun createResolutionFacade(environment: KotlinCoreEnvironment): DokkaResolutionFacade { + fun createResolutionFacade(environment: KotlinCoreEnvironment): Pair { val projectContext = ProjectContext(environment.project) val sourceFiles = environment.getSourceFiles() @@ -164,15 +164,17 @@ class AnalysisEnvironment(val messageCollector: MessageCollector) : Disposable { builtIns = builtIns ) - resolverForProject.resolverForModule(library) // Required before module to initialize library properly + val resolverForLibrary = resolverForProject.resolverForModule(library) // Required before module to initialize library properly val resolverForModule = resolverForProject.resolverForModule(module) + val libraryModuleDescriptor = resolverForProject.descriptorForModule(library) val moduleDescriptor = resolverForProject.descriptorForModule(module) builtIns.initialize(moduleDescriptor, true) + val libraryResolutionFacade = DokkaResolutionFacade(environment.project, libraryModuleDescriptor, resolverForLibrary) val created = DokkaResolutionFacade(environment.project, moduleDescriptor, resolverForModule) val projectComponentManager = environment.project as MockComponentManager projectComponentManager.registerService(KotlinCacheService::class.java, CoreKotlinCacheService(created)) - return created + return created to libraryResolutionFacade } fun loadLanguageVersionSettings(languageVersionString: String?, apiVersionString: String?) { diff --git a/core/src/main/kotlin/Java/JavaPsiDocumentationBuilder.kt b/core/src/main/kotlin/Java/JavaPsiDocumentationBuilder.kt index 646096e5..8b30a6b4 100644 --- a/core/src/main/kotlin/Java/JavaPsiDocumentationBuilder.kt +++ b/core/src/main/kotlin/Java/JavaPsiDocumentationBuilder.kt @@ -45,10 +45,16 @@ class JavaPsiDocumentationBuilder : JavaDocumentationBuilder { private val refGraph: NodeReferenceGraph private val docParser: JavaDocumentationParser - @Inject constructor(options: DocumentationOptions, refGraph: NodeReferenceGraph, logger: DokkaLogger, signatureProvider: ElementSignatureProvider) { + @Inject constructor( + options: DocumentationOptions, + refGraph: NodeReferenceGraph, + logger: DokkaLogger, + signatureProvider: ElementSignatureProvider, + externalDocumentationLinkResolver: ExternalDocumentationLinkResolver + ) { this.options = options this.refGraph = refGraph - this.docParser = JavadocParser(refGraph, logger, signatureProvider) + this.docParser = JavadocParser(refGraph, logger, signatureProvider, externalDocumentationLinkResolver) } constructor(options: DocumentationOptions, refGraph: NodeReferenceGraph, docParser: JavaDocumentationParser) { diff --git a/core/src/main/kotlin/Java/JavadocParser.kt b/core/src/main/kotlin/Java/JavadocParser.kt index 5e23e357..e1b15cb2 100644 --- a/core/src/main/kotlin/Java/JavadocParser.kt +++ b/core/src/main/kotlin/Java/JavadocParser.kt @@ -26,7 +26,8 @@ interface JavaDocumentationParser { class JavadocParser( private val refGraph: NodeReferenceGraph, private val logger: DokkaLogger, - private val signatureProvider: ElementSignatureProvider + private val signatureProvider: ElementSignatureProvider, + private val externalDocumentationLinkResolver: ExternalDocumentationLinkResolver ) : JavaDocumentationParser { private fun ContentSection.appendTypeElement(signature: String, selector: (DocumentationNode) -> DocumentationNode?) { @@ -197,25 +198,41 @@ class JavadocParser( private fun MutableContent.convertSeeTag(tag: PsiDocTag) { val linkElement = tag.linkElement() ?: return val seeSection = findSectionByTag(ContentTags.SeeAlso) ?: addSection(ContentTags.SeeAlso, null) - val linkSignature = resolveLink(tag.referenceElement()) + + val valueElement = tag.referenceElement() + val externalLink = resolveExternalLink(valueElement) val text = ContentText(linkElement.text) - if (linkSignature != null) { - val linkNode = - ContentNodeLazyLink((tag.valueElement ?: linkElement).text, { -> refGraph.lookupOrWarn(linkSignature, logger) }) - linkNode.append(text) - seeSection.append(linkNode) - } else { - seeSection.append(text) + + val linkSignature by lazy { resolveInternalLink(valueElement) } + val node = when { + externalLink != null -> { + val linkNode = ContentExternalLink(externalLink) + linkNode.append(text) + linkNode + } + linkSignature != null -> { + val linkNode = + ContentNodeLazyLink( + (tag.valueElement ?: linkElement).text, + { -> refGraph.lookupOrWarn(linkSignature, logger) } + ) + linkNode.append(text) + linkNode + } + else -> text } + seeSection.append(node) } private fun convertInlineDocTag(tag: PsiInlineDocTag, element: PsiNamedElement) = when (tag.name) { "link", "linkplain" -> { val valueElement = tag.referenceElement() - val linkSignature = resolveLink(valueElement) - if (linkSignature != null) { + val externalLink = resolveExternalLink(valueElement) + val linkSignature by lazy { resolveInternalLink(valueElement) } + if (externalLink != null || linkSignature != null) { val labelText = tag.dataElements.firstOrNull { it is PsiDocToken }?.text ?: valueElement!!.text - val link = "${labelText.htmlEscape()}" + val linkTarget = if (externalLink != null) "href=\"$externalLink\"" else "docref=\"$linkSignature\"" + val link = "${labelText.htmlEscape()}" if (tag.name == "link") "$link" else link } else if (valueElement != null) { valueElement.text @@ -256,7 +273,15 @@ class JavadocParser( private fun PsiDocTag.linkElement(): PsiElement? = valueElement ?: dataElements.firstOrNull { it !is PsiWhiteSpace } - private fun resolveLink(valueElement: PsiElement?): String? { + private fun resolveExternalLink(valueElement: PsiElement?): String? { + val target = valueElement?.reference?.resolve() + if (target != null) { + return externalDocumentationLinkResolver.buildExternalDocumentationLink(target) + } + return null + } + + private fun resolveInternalLink(valueElement: PsiElement?): String? { val target = valueElement?.reference?.resolve() if (target != null) { return signatureProvider.signature(target) diff --git a/core/src/main/kotlin/Kotlin/DescriptorDocumentationParser.kt b/core/src/main/kotlin/Kotlin/DescriptorDocumentationParser.kt index 5f1118e8..7817da18 100644 --- a/core/src/main/kotlin/Kotlin/DescriptorDocumentationParser.kt +++ b/core/src/main/kotlin/Kotlin/DescriptorDocumentationParser.kt @@ -34,8 +34,9 @@ class DescriptorDocumentationParser val resolutionFacade: DokkaResolutionFacade, val refGraph: NodeReferenceGraph, val sampleService: SampleProcessingService, - val signatureProvider: KotlinElementSignatureProvider - ) + val signatureProvider: KotlinElementSignatureProvider, + val externalDocumentationLinkResolver: ExternalDocumentationLinkResolver +) { fun parseDocumentation(descriptor: DeclarationDescriptor, inline: Boolean = false): Content = parseDocumentationAndDetails(descriptor, inline).first @@ -131,7 +132,12 @@ class DescriptorDocumentationParser fun parseJavadoc(descriptor: DeclarationDescriptor): Pair Unit> { val psi = ((descriptor as? DeclarationDescriptorWithSource)?.source as? PsiSourceElement)?.psi if (psi is PsiDocCommentOwner) { - val parseResult = JavadocParser(refGraph, logger, signatureProvider).parseDocumentation(psi as PsiNamedElement) + val parseResult = JavadocParser( + refGraph, + logger, + signatureProvider, + externalDocumentationLinkResolver + ).parseDocumentation(psi as PsiNamedElement) return parseResult.content to { node -> parseResult.deprecatedContent?.let { val deprecationNode = DocumentationNode("", it, NodeKind.Modifier) diff --git a/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt b/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt index 7be37177..c766b869 100644 --- a/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt +++ b/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt @@ -2,6 +2,7 @@ package org.jetbrains.dokka import com.google.inject.Inject import com.google.inject.Singleton +import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import com.intellij.util.io.* import org.jetbrains.dokka.Formats.FileGeneratorBasedFormatDescriptor @@ -10,10 +11,7 @@ import org.jetbrains.dokka.Utilities.ServiceLocator import org.jetbrains.dokka.Utilities.lookup import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.impl.EnumEntrySyntheticClassDescriptor -import org.jetbrains.kotlin.load.java.descriptors.JavaCallableMemberDescriptor -import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor -import org.jetbrains.kotlin.load.java.descriptors.JavaMethodDescriptor -import org.jetbrains.kotlin.load.java.descriptors.JavaPropertyDescriptor +import org.jetbrains.kotlin.load.java.descriptors.* import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe @@ -25,6 +23,7 @@ import java.net.URL import java.net.URLConnection import java.nio.file.Path import java.security.MessageDigest +import javax.inject.Named import kotlin.reflect.full.findAnnotation fun ByteArray.toHexString() = this.joinToString(separator = "") { "%02x".format(it) } @@ -32,6 +31,7 @@ fun ByteArray.toHexString() = this.joinToString(separator = "") { "%02x".format( @Singleton class ExternalDocumentationLinkResolver @Inject constructor( val options: DocumentationOptions, + @Named("libraryResolutionFacade") val libraryResolutionFacade: DokkaResolutionFacade, val logger: DokkaLogger ) { @@ -166,6 +166,12 @@ class ExternalDocumentationLinkResolver @Inject constructor( } } + fun buildExternalDocumentationLink(element: PsiElement): String? { + return element.extractDescriptor(libraryResolutionFacade)?.let { + buildExternalDocumentationLink(it) + } + } + fun buildExternalDocumentationLink(symbol: DeclarationDescriptor): String? { val packageFqName: FqName = when (symbol) { diff --git a/core/src/main/kotlin/Kotlin/KotlinElementSignatureProvider.kt b/core/src/main/kotlin/Kotlin/KotlinElementSignatureProvider.kt index 0a377dc1..bcac0182 100644 --- a/core/src/main/kotlin/Kotlin/KotlinElementSignatureProvider.kt +++ b/core/src/main/kotlin/Kotlin/KotlinElementSignatureProvider.kt @@ -2,7 +2,6 @@ package org.jetbrains.dokka import com.intellij.psi.PsiElement import com.intellij.psi.PsiMember -import com.intellij.psi.PsiNameIdentifierOwner import com.intellij.psi.PsiPackage import org.jetbrains.kotlin.asJava.elements.KtLightElement import org.jetbrains.kotlin.descriptors.DeclarationDescriptor @@ -14,21 +13,22 @@ class KotlinElementSignatureProvider @Inject constructor( val resolutionFacade: DokkaResolutionFacade ) : ElementSignatureProvider { override fun signature(forPsi: PsiElement): String { - - val desc = when (forPsi) { - is KtLightElement<*, *> -> return signature(forPsi.kotlinOrigin!!) - is PsiPackage -> resolutionFacade.moduleDescriptor.getPackage(FqName(forPsi.qualifiedName)) - is PsiMember -> forPsi.getJavaOrKotlinMemberDescriptor(resolutionFacade) - else -> resolutionFacade.resolveSession.bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, forPsi] - } - - if (desc == null && (forPsi as? PsiNameIdentifierOwner)?.name == "remove") { - (forPsi as? PsiMember)?.getJavaOrKotlinMemberDescriptor(resolutionFacade) - } - - return desc?.let { signature(it) } + return forPsi.extractDescriptor(resolutionFacade) + ?.let { signature(it) } ?: run { "no desc for $forPsi in ${(forPsi as? PsiMember)?.containingClass}" } } override fun signature(forDesc: DeclarationDescriptor): String = forDesc.signature() -} \ No newline at end of file +} + + +fun PsiElement.extractDescriptor(resolutionFacade: DokkaResolutionFacade): DeclarationDescriptor? { + val forPsi = this + + return when (forPsi) { + is KtLightElement<*, *> -> return (forPsi.kotlinOrigin!!).extractDescriptor(resolutionFacade) + is PsiPackage -> resolutionFacade.moduleDescriptor.getPackage(FqName(forPsi.qualifiedName)) + is PsiMember -> forPsi.getJavaOrKotlinMemberDescriptor(resolutionFacade) + else -> resolutionFacade.resolveSession.bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, forPsi] + } +} diff --git a/core/src/main/kotlin/Utilities/DokkaModules.kt b/core/src/main/kotlin/Utilities/DokkaModules.kt index 907d5ca7..732cbc48 100644 --- a/core/src/main/kotlin/Utilities/DokkaModules.kt +++ b/core/src/main/kotlin/Utilities/DokkaModules.kt @@ -24,8 +24,9 @@ class DokkaAnalysisModule(val environment: AnalysisEnvironment, val coreEnvironment = environment.createCoreEnvironment() binder.bind().toInstance(coreEnvironment) - val dokkaResolutionFacade = environment.createResolutionFacade(coreEnvironment) + val (dokkaResolutionFacade, libraryResolutionFacade) = environment.createResolutionFacade(coreEnvironment) binder.bind().toInstance(dokkaResolutionFacade) + binder.bind().annotatedWith(Names.named("libraryResolutionFacade")).toInstance(libraryResolutionFacade) binder.bind().toInstance(options) -- cgit From 3c6be4a1dbbcfec5e5438452f54857cce86d0d17 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Fri, 4 May 2018 21:35:36 +0300 Subject: Fix resolution of inbound links to constructors in Javadoc --- core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt b/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt index c766b869..a8129793 100644 --- a/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt +++ b/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt @@ -216,7 +216,7 @@ interface InboundExternalLinkResolutionService { val containingClass = symbol.containingDeclaration as? JavaClassDescriptor ?: return null val containingClassLink = getPath(containingClass) if (containingClassLink != null) { - if (symbol is JavaMethodDescriptor) { + if (symbol is JavaMethodDescriptor || symbol is JavaClassConstructorDescriptor) { val psi = symbol.sourcePsi() as? PsiMethod if (psi != null) { val params = psi.parameterList.parameters.joinToString { it.type.canonicalText } -- cgit From 6361dd32aaf567c8e03e4aa63006193dc67cca7b Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Sat, 5 May 2018 01:54:31 +0300 Subject: Fix relative uri's generation when there is matching trailing segments --- core/src/main/kotlin/Utilities/Uri.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Utilities/Uri.kt b/core/src/main/kotlin/Utilities/Uri.kt index 5b520188..9827c624 100644 --- a/core/src/main/kotlin/Utilities/Uri.kt +++ b/core/src/main/kotlin/Utilities/Uri.kt @@ -19,7 +19,7 @@ fun URI.relativeTo(uri: URI): URI { } // Compute common prefix - val commonPartsSize = bParts.zip(cParts).count { (basePart, childPart) -> basePart == childPart } + val commonPartsSize = bParts.zip(cParts).takeWhile { (basePart, childPart) -> basePart == childPart }.count() bParts.drop(commonPartsSize).joinTo(this, separator = "") { "../" } cParts.drop(commonPartsSize).joinTo(this, separator = "/") } -- cgit From e38d83905ff706b2d656f12896a6905f5a0729d7 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Sat, 5 May 2018 01:58:55 +0300 Subject: Fix inbound links to enum entries --- .../Formats/JavaLayoutHtml/JavaLayoutHtmlPackageListService.kt | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Formats/JavaLayoutHtml/JavaLayoutHtmlPackageListService.kt b/core/src/main/kotlin/Formats/JavaLayoutHtml/JavaLayoutHtmlPackageListService.kt index 6d9b5fd0..09bb2602 100644 --- a/core/src/main/kotlin/Formats/JavaLayoutHtml/JavaLayoutHtmlPackageListService.kt +++ b/core/src/main/kotlin/Formats/JavaLayoutHtml/JavaLayoutHtmlPackageListService.kt @@ -3,6 +3,7 @@ package org.jetbrains.dokka.Formats import org.jetbrains.dokka.* import org.jetbrains.dokka.ExternalDocumentationLinkResolver.Companion.DOKKA_PARAM_PREFIX import org.jetbrains.kotlin.descriptors.* +import org.jetbrains.kotlin.descriptors.impl.EnumEntrySyntheticClassDescriptor import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe import org.jetbrains.kotlin.resolve.descriptorUtil.isCompanionObject import org.jetbrains.kotlin.types.KotlinType @@ -33,7 +34,7 @@ class JavaLayoutHtmlPackageListService: PackageListService { class JavaLayoutHtmlInboundLinkResolutionService(private val paramMap: Map>) : InboundExternalLinkResolutionService { private fun getContainerPath(symbol: DeclarationDescriptor): String? { return when (symbol) { - is PackageFragmentDescriptor -> symbol.fqName.asString() + "/" + is PackageFragmentDescriptor -> symbol.fqName.asString().replace('.', '/') + "/" is ClassifierDescriptor -> getContainerPath(symbol.findPackage()) + symbol.nameWithOuter() + ".html" else -> null } @@ -49,6 +50,7 @@ class JavaLayoutHtmlInboundLinkResolutionService(private val paramMap: Map getContainerPath(symbol) + "package-summary.html" + is EnumEntrySyntheticClassDescriptor -> getContainerPath(symbol.containingDeclaration) + "#" + symbol.signatureForAnchorUrlEncoded() is ClassifierDescriptor -> getContainerPath(symbol) + "#" is FunctionDescriptor, is PropertyDescriptor -> getContainerPath(symbol.containingDeclaration!!) + "#" + symbol.signatureForAnchorUrlEncoded() else -> null @@ -88,6 +90,10 @@ class JavaLayoutHtmlInboundLinkResolutionService(private val paramMap: Map buildString { + append("ENUM_VALUE:") + append(name.asString()) + } is FunctionDescriptor -> buildString { appendReceiverAndCompanion(this@signatureForAnchor) append(name.asString()) -- cgit From 44ad68386658dde985207ea0aedb19c96d9b3f93 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Mon, 7 May 2018 16:37:12 +0300 Subject: [backport] KT-24277: Persist inpage anchors (aka bookmarks) from Javadoc Original: 4fddba5 --- core/src/main/kotlin/Java/JavadocParser.kt | 22 +++++++++++++--------- core/src/main/kotlin/Model/Content.kt | 2 ++ 2 files changed, 15 insertions(+), 9 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Java/JavadocParser.kt b/core/src/main/kotlin/Java/JavadocParser.kt index e1b15cb2..8cd274e7 100644 --- a/core/src/main/kotlin/Java/JavadocParser.kt +++ b/core/src/main/kotlin/Java/JavadocParser.kt @@ -183,15 +183,19 @@ class JavadocParser( } private fun createLink(element: Element): ContentBlock { - if (element.hasAttr("docref")) { - val docref = element.attr("docref") - return ContentNodeLazyLink(docref, { -> refGraph.lookupOrWarn(docref, logger) }) - } - return if (element.hasAttr("href")) { - val href = element.attr("href") - ContentExternalLink(href) - } else { - ContentBlock() + return when { + element.hasAttr("docref") -> { + val docref = element.attr("docref") + ContentNodeLazyLink(docref, { -> refGraph.lookupOrWarn(docref, logger) }) + } + element.hasAttr("href") -> { + val href = element.attr("href") + ContentExternalLink(href) + } + element.hasAttr("name") -> { + ContentBookmark(element.attr("name")) + } + else -> ContentBlock() } } diff --git a/core/src/main/kotlin/Model/Content.kt b/core/src/main/kotlin/Model/Content.kt index 010ee7ca..4f142ca4 100644 --- a/core/src/main/kotlin/Model/Content.kt +++ b/core/src/main/kotlin/Model/Content.kt @@ -148,6 +148,8 @@ class ContentExternalLink(val href : String) : ContentBlock() { children.hashCode() * 31 + href.hashCode() } +data class ContentBookmark(val name: String): ContentBlock() + class ContentUnorderedList() : ContentBlock() class ContentOrderedList() : ContentBlock() class ContentListItem() : ContentBlock() -- cgit From 4301503416ed45783a81250295adf4b5a86c4280 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Mon, 7 May 2018 17:28:22 +0300 Subject: [backport] KT-24299: Fix local links resolved in incorrect context Original: fababd4 --- core/src/main/kotlin/Java/JavadocParser.kt | 14 +++++++++++++- core/src/main/kotlin/Model/Content.kt | 1 + 2 files changed, 14 insertions(+), 1 deletion(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Java/JavadocParser.kt b/core/src/main/kotlin/Java/JavadocParser.kt index 8cd274e7..9f9ea017 100644 --- a/core/src/main/kotlin/Java/JavadocParser.kt +++ b/core/src/main/kotlin/Java/JavadocParser.kt @@ -12,6 +12,7 @@ import org.jsoup.Jsoup import org.jsoup.nodes.Element import org.jsoup.nodes.Node import org.jsoup.nodes.TextNode +import java.net.URI data class JavadocParseResult(val content: Content, val deprecatedContent: Content?) { companion object { @@ -190,7 +191,18 @@ class JavadocParser( } element.hasAttr("href") -> { val href = element.attr("href") - ContentExternalLink(href) + + val uri = try { + URI(href) + } catch (_: Exception) { + null + } + + if (uri?.isAbsolute == false) { + ContentLocalLink(href) + } else { + ContentExternalLink(href) + } } element.hasAttr("name") -> { ContentBookmark(element.attr("name")) diff --git a/core/src/main/kotlin/Model/Content.kt b/core/src/main/kotlin/Model/Content.kt index 4f142ca4..7c776bdb 100644 --- a/core/src/main/kotlin/Model/Content.kt +++ b/core/src/main/kotlin/Model/Content.kt @@ -149,6 +149,7 @@ class ContentExternalLink(val href : String) : ContentBlock() { } data class ContentBookmark(val name: String): ContentBlock() +data class ContentLocalLink(val href: String) : ContentBlock() class ContentUnorderedList() : ContentBlock() class ContentOrderedList() : ContentBlock() -- cgit From f301316151dc15b67d926423021abc5e3313aa2a Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Mon, 7 May 2018 20:08:43 +0300 Subject: KT-24300: Support inclusion overview.html into package summary --- core/src/main/kotlin/Generation/DokkaGenerator.kt | 15 ++++- core/src/main/kotlin/Model/PackageDocs.kt | 69 ++++++++++++++++++++++- 2 files changed, 82 insertions(+), 2 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Generation/DokkaGenerator.kt b/core/src/main/kotlin/Generation/DokkaGenerator.kt index 33170f35..91471849 100644 --- a/core/src/main/kotlin/Generation/DokkaGenerator.kt +++ b/core/src/main/kotlin/Generation/DokkaGenerator.kt @@ -20,7 +20,6 @@ import org.jetbrains.kotlin.config.JVMConfigurationKeys import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.resolve.LazyTopDownAnalyzer import org.jetbrains.kotlin.resolve.TopDownAnalysisMode -import org.jetbrains.kotlin.utils.PathUtil import java.io.File import kotlin.system.measureTimeMillis @@ -157,6 +156,8 @@ fun buildDocumentationModule(injector: Injector, } } + parseJavaPackageDocs(packageDocs, coreEnvironment) + with(injector.getInstance(DocumentationBuilder::class.java)) { documentationModule.appendFragments(fragments, packageDocs.packageContent, injector.getInstance(PackageDocumentationBuilder::class.java)) @@ -170,6 +171,18 @@ fun buildDocumentationModule(injector: Injector, } } +fun parseJavaPackageDocs(packageDocs: PackageDocs, coreEnvironment: KotlinCoreEnvironment) { + val contentRoots = coreEnvironment.configuration.get(JVMConfigurationKeys.CONTENT_ROOTS) + ?.filterIsInstance() + ?.map { it.file } + ?: listOf() + contentRoots.forEach { root -> + root.walkTopDown().filter { it.name == "overview.html" }.forEach { + packageDocs.parseJava(it.path, it.relativeTo(root).parent.replace("/", ".")) + } + } +} + fun KotlinCoreEnvironment.getJavaSourceFiles(): List { val sourceRoots = configuration.get(JVMConfigurationKeys.CONTENT_ROOTS) diff --git a/core/src/main/kotlin/Model/PackageDocs.kt b/core/src/main/kotlin/Model/PackageDocs.kt index 1f6bdcb9..5b628914 100644 --- a/core/src/main/kotlin/Model/PackageDocs.kt +++ b/core/src/main/kotlin/Model/PackageDocs.kt @@ -2,16 +2,25 @@ package org.jetbrains.dokka import com.google.inject.Inject import com.google.inject.Singleton +import com.intellij.ide.highlighter.JavaFileType +import com.intellij.psi.PsiClass +import com.intellij.psi.PsiFileFactory +import com.intellij.psi.util.PsiTreeUtil +import com.intellij.util.LocalTimeCounter import org.intellij.markdown.MarkdownElementTypes import org.intellij.markdown.MarkdownTokenTypes import org.intellij.markdown.parser.LinkMap +import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor import java.io.File @Singleton class PackageDocs @Inject constructor(val linkResolver: DeclarationLinkResolver?, - val logger: DokkaLogger) + val logger: DokkaLogger, + val environment: KotlinCoreEnvironment, + val refGraph: NodeReferenceGraph, + val elementSignatureProvider: ElementSignatureProvider) { val moduleContent: MutableContent = MutableContent() private val _packageContent: MutableMap = hashMapOf() @@ -40,6 +49,64 @@ class PackageDocs } } + private fun parseHtmlAsJavadoc(text: String, packageName: String, file: File) { + val javadocText = text + .replace("*/", "*/") + .removeSurrounding("", "", true).trim() + .removeSurrounding("", "", true) + .lineSequence() + .map { "* $it" } + .joinToString (separator = "\n", prefix = "/**\n", postfix = "\n*/") + parseJavadoc(javadocText, packageName, file) + } + + private fun CharSequence.removeSurrounding(prefix: CharSequence, suffix: CharSequence, ignoringCase: Boolean = false): CharSequence { + if ((length >= prefix.length + suffix.length) && startsWith(prefix, ignoringCase) && endsWith(suffix, ignoringCase)) { + return subSequence(prefix.length, length - suffix.length) + } + return subSequence(0, length) + } + + + private fun parseJavadoc(text: String, packageName: String, file: File) { + + val psiFileFactory = PsiFileFactory.getInstance(environment.project) + val psiFile = psiFileFactory.createFileFromText( + file.nameWithoutExtension + ".java", + JavaFileType.INSTANCE, + "package $packageName; $text\npublic class C {}", + LocalTimeCounter.currentTime(), + false, + true + ) + + val psiClass = PsiTreeUtil.getChildOfType(psiFile, PsiClass::class.java)!! + val parser = JavadocParser(refGraph, logger, elementSignatureProvider, linkResolver?.externalDocumentationLinkResolver!!) + findOrCreatePackageContent(packageName).apply { + val content = parser.parseDocumentation(psiClass).content + children.addAll(content.children) + content.sections.forEach { + addSection(it.tag, it.subjectName).children.addAll(it.children) + } + } + } + + + fun parseJava(fileName: String, packageName: String) { + val file = File(fileName) + if (file.exists()) { + val text = file.readText() + + val trimmedText = text.trim() + + if (trimmedText.startsWith("/**")) { + parseJavadoc(text, packageName, file) + } else if (trimmedText.toLowerCase().startsWith("")) { + parseHtmlAsJavadoc(trimmedText, packageName, file) + } + } + } + private fun findTargetContent(heading: String): MutableContent { if (heading.startsWith("Module") || heading.startsWith("module")) { return moduleContent -- cgit From b46ec0a7ccfb3a7347fd5d3717cc4b3aedf75429 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Tue, 8 May 2018 01:44:16 +0300 Subject: Fix nullability detection --- core/src/main/kotlin/Kotlin/DocumentationBuilder.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt index c165045d..e6a75277 100644 --- a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt +++ b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt @@ -244,7 +244,7 @@ class DocumentationBuilder } if (kotlinType.isNullabilityFlexible()) { node.appendTextNode("!", NodeKind.NullabilityModifier) - } else if (kotlinType.isNullable()) { + } else if (kotlinType.isMarkedNullable) { node.appendTextNode("?", NodeKind.NullabilityModifier) } if (classifierDescriptor != null) { -- cgit From 9715d6300d6e0082a3e900c7e5cff873b8c294f2 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Sat, 26 May 2018 00:12:38 +0300 Subject: Provide signature for packages --- core/src/main/kotlin/Java/JavaPsiDocumentationBuilder.kt | 1 + 1 file changed, 1 insertion(+) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Java/JavaPsiDocumentationBuilder.kt b/core/src/main/kotlin/Java/JavaPsiDocumentationBuilder.kt index 8b30a6b4..6d5825e9 100644 --- a/core/src/main/kotlin/Java/JavaPsiDocumentationBuilder.kt +++ b/core/src/main/kotlin/Java/JavaPsiDocumentationBuilder.kt @@ -14,6 +14,7 @@ import org.jetbrains.kotlin.psi.KtModifierListOwner import java.io.File fun getSignature(element: PsiElement?) = when(element) { + is PsiPackage -> element.qualifiedName is PsiClass -> element.qualifiedName is PsiField -> element.containingClass!!.qualifiedName + "$" + element.name is PsiMethod -> -- cgit From 633fda36403e8c5483054737d285dd01b5c190bb Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Sat, 26 May 2018 00:15:47 +0300 Subject: KT-24025: Support constants in as java mode #KT-24025 fixed --- .../main/kotlin/Java/JavaPsiDocumentationBuilder.kt | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Java/JavaPsiDocumentationBuilder.kt b/core/src/main/kotlin/Java/JavaPsiDocumentationBuilder.kt index 6d5825e9..9eabc227 100644 --- a/core/src/main/kotlin/Java/JavaPsiDocumentationBuilder.kt +++ b/core/src/main/kotlin/Java/JavaPsiDocumentationBuilder.kt @@ -1,7 +1,9 @@ package org.jetbrains.dokka import com.google.inject.Inject +import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.* +import com.intellij.psi.impl.JavaConstantExpressionEvaluator import com.intellij.psi.util.InheritanceUtil import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.asJava.elements.KtLightDeclaration @@ -207,11 +209,28 @@ class JavaPsiDocumentationBuilder : JavaDocumentationBuilder { fun PsiField.build(): DocumentationNode { val node = nodeForElement(this, nodeKind()) node.appendType(type) - node.appendModifiers(this) + + node.appendConstantValueIfAny(this) register(this, node) return node } + private fun DocumentationNode.appendConstantValueIfAny(field: PsiField) { + val modifierList = field.modifierList ?: return + val initializer = field.initializer ?: return + if (field.type is PsiPrimitiveType && + modifierList.hasExplicitModifier(PsiModifier.FINAL) && + modifierList.hasExplicitModifier(PsiModifier.STATIC)) { + val value = JavaConstantExpressionEvaluator.computeConstantExpression(initializer, false) + val text = when(value) { + is String -> + "\"" + StringUtil.escapeStringCharacters(value) + "\"" + else -> value.toString() + } + append(DocumentationNode(text, Content.Empty, NodeKind.Value), RefKind.Detail) + } + } + private fun PsiField.nodeKind(): NodeKind = when { this is PsiEnumConstant -> NodeKind.EnumItem else -> NodeKind.Field -- cgit From f5746c40cbb44204edd137b3183ef0d04958047b Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Sat, 26 May 2018 00:19:54 +0300 Subject: KT-24624: Partial, more detailed signature on class page --- core/src/main/kotlin/Kotlin/KotlinLanguageService.kt | 20 ++++---------------- .../main/kotlin/Languages/CommonLanguageService.kt | 18 ++++++++++++++++++ .../main/kotlin/Languages/NewJavaLanguageService.kt | 9 +++++++-- 3 files changed, 29 insertions(+), 18 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt b/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt index b6474583..237fa9b9 100644 --- a/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt +++ b/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt @@ -7,6 +7,10 @@ import org.jetbrains.dokka.LanguageService.RenderMode * Implements [LanguageService] and provides rendering of symbols in Kotlin language */ class KotlinLanguageService : CommonLanguageService() { + override fun showModifierInSummary(node: DocumentationNode): Boolean { + return node.name !in fullOnlyModifiers + } + private val fullOnlyModifiers = setOf("public", "protected", "private", "inline", "noinline", "crossinline", "reified") @@ -283,22 +287,6 @@ class KotlinLanguageService : CommonLanguageService() { } } - private fun ContentBlock.renderModifiersForNode( - node: DocumentationNode, - renderMode: RenderMode, - nowrap: Boolean = false - ) { - val modifiers = node.details(NodeKind.Modifier) - for (it in modifiers) { - if (node.kind == org.jetbrains.dokka.NodeKind.Interface && it.name == "abstract") - continue - if (renderMode == RenderMode.SUMMARY && it.name in fullOnlyModifiers) { - continue - } - renderModifier(this, it, renderMode, nowrap) - } - } - private fun ContentBlock.renderAnnotationsForNode(node: DocumentationNode) { node.annotations.forEach { renderAnnotation(it) diff --git a/core/src/main/kotlin/Languages/CommonLanguageService.kt b/core/src/main/kotlin/Languages/CommonLanguageService.kt index edefa1b5..ddc95d32 100644 --- a/core/src/main/kotlin/Languages/CommonLanguageService.kt +++ b/core/src/main/kotlin/Languages/CommonLanguageService.kt @@ -62,5 +62,23 @@ abstract class CommonLanguageService : LanguageService { } } + abstract fun showModifierInSummary(node: DocumentationNode): Boolean + + protected fun ContentBlock.renderModifiersForNode( + node: DocumentationNode, + renderMode: LanguageService.RenderMode, + nowrap: Boolean = false + ) { + val modifiers = node.details(NodeKind.Modifier) + for (it in modifiers) { + if (node.kind == NodeKind.Interface && it.name == "abstract") + continue + if (renderMode == LanguageService.RenderMode.SUMMARY && !showModifierInSummary(it)) { + continue + } + renderModifier(this, it, renderMode, nowrap) + } + } + } \ No newline at end of file diff --git a/core/src/main/kotlin/Languages/NewJavaLanguageService.kt b/core/src/main/kotlin/Languages/NewJavaLanguageService.kt index 0266c033..fa9f70fd 100644 --- a/core/src/main/kotlin/Languages/NewJavaLanguageService.kt +++ b/core/src/main/kotlin/Languages/NewJavaLanguageService.kt @@ -6,11 +6,15 @@ import org.jetbrains.dokka.LanguageService.RenderMode * Implements [LanguageService] and provides rendering of symbols in Java language */ class NewJavaLanguageService : CommonLanguageService() { + override fun showModifierInSummary(node: DocumentationNode): Boolean { + return true + } + override fun render(node: DocumentationNode, renderMode: RenderMode): ContentNode { return content { (when (node.kind) { NodeKind.Package -> renderPackage(node) - in NodeKind.classLike -> renderClass(node) + in NodeKind.classLike -> renderClass(node, renderMode) NodeKind.Modifier -> renderModifier(this, node, renderMode) NodeKind.TypeParameter -> renderTypeParameter(node) @@ -131,7 +135,8 @@ class NewJavaLanguageService : CommonLanguageService() { text(" ") } - private fun ContentBlock.renderClass(node: DocumentationNode) { + private fun ContentBlock.renderClass(node: DocumentationNode, renderMode: RenderMode) { + renderModifiersForNode(node, renderMode) renderClassKind(node) identifier(node.name) -- cgit From 23861925232505dbd70344a1d690f2475bb022e8 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Mon, 4 Jun 2018 16:23:34 +0300 Subject: [backport] Introduce option to enable/disable jdk linking Original: 8e9e768 --- core/src/main/kotlin/DokkaBootstrapImpl.kt | 39 +++++++++++----------- .../main/kotlin/Generation/configurationImpl.kt | 1 + .../src/main/kotlin/Kotlin/DocumentationBuilder.kt | 6 +++- core/src/test/kotlin/TestAPI.kt | 9 +++++ .../test/kotlin/format/KotlinWebSiteFormatTest.kt | 1 + .../kotlin/format/KotlinWebSiteHtmlFormatTest.kt | 1 + core/src/test/kotlin/format/MarkdownFormatTest.kt | 2 ++ core/src/test/kotlin/model/JavaTest.kt | 4 +-- .../kotlin/org/jetbrains/dokka/configuration.kt | 2 ++ runners/ant/src/main/kotlin/ant/dokka.kt | 2 ++ runners/gradle-plugin/src/main/kotlin/main.kt | 14 +++++--- 11 files changed, 54 insertions(+), 27 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/DokkaBootstrapImpl.kt b/core/src/main/kotlin/DokkaBootstrapImpl.kt index b7787be8..e18ab6cf 100644 --- a/core/src/main/kotlin/DokkaBootstrapImpl.kt +++ b/core/src/main/kotlin/DokkaBootstrapImpl.kt @@ -52,25 +52,26 @@ class DokkaBootstrapImpl : DokkaBootstrap { includes, moduleName, DocumentationOptions( - outputDir, - format, - includeNonPublic, - includeRootPackage, - reportUndocumented, - skipEmptyPackages, - skipDeprecated, - jdkVersion, - generateIndexPages, - sourceLinks, - impliedPlatforms, - perPackageOptions, - externalDocumentationLinks, - noStdlibLink, - languageVersion, - apiVersion, - cacheRoot, - suppressedFiles.map { File(it) }.toSet(), - collectInheritedExtensionsFromLibraries + outputDir = outputDir, + outputFormat = format, + includeNonPublic = includeNonPublic, + includeRootPackage = includeRootPackage, + reportUndocumented = reportUndocumented, + skipEmptyPackages = skipEmptyPackages, + skipDeprecated = skipDeprecated, + jdkVersion = jdkVersion, + generateIndexPages = generateIndexPages, + sourceLinks = sourceLinks, + impliedPlatforms = impliedPlatforms, + perPackageOptions = perPackageOptions, + externalDocumentationLinks = externalDocumentationLinks, + noStdlibLink = noStdlibLink, + noJdkLink = noJdkLink, + languageVersion = languageVersion, + apiVersion = apiVersion, + cacheRoot = cacheRoot, + suppressedFiles = suppressedFiles.map { File(it) }.toSet(), + collectInheritedExtensionsFromLibraries = collectInheritedExtensionsFromLibraries ) ) } diff --git a/core/src/main/kotlin/Generation/configurationImpl.kt b/core/src/main/kotlin/Generation/configurationImpl.kt index 52e8446f..90e27b4b 100644 --- a/core/src/main/kotlin/Generation/configurationImpl.kt +++ b/core/src/main/kotlin/Generation/configurationImpl.kt @@ -55,6 +55,7 @@ data class DokkaConfigurationImpl( override val perPackageOptions: List, override val externalDocumentationLinks: List, override val noStdlibLink: Boolean, + override val noJdkLink: Boolean, override val cacheRoot: String?, override val suppressedFiles: List, override val languageVersion: String?, diff --git a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt index e6a75277..58f5e246 100644 --- a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt +++ b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt @@ -55,6 +55,7 @@ class DocumentationOptions(val outputDir: String, perPackageOptions: List = emptyList(), externalDocumentationLinks: List = emptyList(), noStdlibLink: Boolean, + noJdkLink: Boolean, val languageVersion: String?, val apiVersion: String?, cacheRoot: String? = null, @@ -72,7 +73,10 @@ class DocumentationOptions(val outputDir: String, fun effectivePackageOptions(pack: FqName): PackageOptions = effectivePackageOptions(pack.asString()) val defaultLinks = run { - val links = mutableListOf(ExternalDocumentationLink.Builder("http://docs.oracle.com/javase/$jdkVersion/docs/api/").build()) + val links = mutableListOf() + if (!noJdkLink) + links += ExternalDocumentationLink.Builder("http://docs.oracle.com/javase/$jdkVersion/docs/api/").build() + if (!noStdlibLink) links += ExternalDocumentationLink.Builder("https://kotlinlang.org/api/latest/jvm/stdlib/").build() links diff --git a/core/src/test/kotlin/TestAPI.kt b/core/src/test/kotlin/TestAPI.kt index aeff9284..953e3bab 100644 --- a/core/src/test/kotlin/TestAPI.kt +++ b/core/src/test/kotlin/TestAPI.kt @@ -39,6 +39,7 @@ fun verifyModel(vararg roots: ContentRoot, perPackageOptions = perPackageOptions, generateIndexPages = false, noStdlibLink = noStdlibLink, + noJdkLink = false, cacheRoot = "default", languageVersion = null, apiVersion = null, @@ -269,6 +270,14 @@ fun StringBuilder.appendNode(node: ContentNode): StringBuilder { is ContentBlock -> { appendChildren(node) } + is NodeRenderContent -> { + append("render(") + append(node.node) + append(",") + append(node.mode) + append(")") + } + is ContentSymbol -> { append(node.text) } is ContentEmpty -> { /* nothing */ } else -> throw IllegalStateException("Don't know how to format node $node") } diff --git a/core/src/test/kotlin/format/KotlinWebSiteFormatTest.kt b/core/src/test/kotlin/format/KotlinWebSiteFormatTest.kt index b971b54d..062cf0b5 100644 --- a/core/src/test/kotlin/format/KotlinWebSiteFormatTest.kt +++ b/core/src/test/kotlin/format/KotlinWebSiteFormatTest.kt @@ -54,6 +54,7 @@ class KotlinWebSiteFormatTest: FileGeneratorTestCase() { outputFormat = "html", generateIndexPages = false, noStdlibLink = true, + noJdkLink = true, languageVersion = null, apiVersion = null ) diff --git a/core/src/test/kotlin/format/KotlinWebSiteHtmlFormatTest.kt b/core/src/test/kotlin/format/KotlinWebSiteHtmlFormatTest.kt index 49fa6d2f..8076fb92 100644 --- a/core/src/test/kotlin/format/KotlinWebSiteHtmlFormatTest.kt +++ b/core/src/test/kotlin/format/KotlinWebSiteHtmlFormatTest.kt @@ -65,6 +65,7 @@ class KotlinWebSiteHtmlFormatTest: FileGeneratorTestCase() { outputFormat = "kotlin-website-html", generateIndexPages = false, noStdlibLink = true, + noJdkLink = true, languageVersion = null, apiVersion = null ) diff --git a/core/src/test/kotlin/format/MarkdownFormatTest.kt b/core/src/test/kotlin/format/MarkdownFormatTest.kt index 9e4c831d..3723e5ae 100644 --- a/core/src/test/kotlin/format/MarkdownFormatTest.kt +++ b/core/src/test/kotlin/format/MarkdownFormatTest.kt @@ -313,6 +313,7 @@ class MarkdownFormatTest: FileGeneratorTestCase() { outputFormat = "html", generateIndexPages = false, noStdlibLink = true, + noJdkLink = true, languageVersion = null, apiVersion = null ) @@ -447,6 +448,7 @@ class MarkdownFormatTest: FileGeneratorTestCase() { outputFormat = "html", generateIndexPages = false, noStdlibLink = true, + noJdkLink = true, languageVersion = null, apiVersion = null ) diff --git a/core/src/test/kotlin/model/JavaTest.kt b/core/src/test/kotlin/model/JavaTest.kt index c2ede8f0..66eb84f1 100644 --- a/core/src/test/kotlin/model/JavaTest.kt +++ b/core/src/test/kotlin/model/JavaTest.kt @@ -18,12 +18,12 @@ public class JavaTest { with(content.sections[0]) { assertEquals("Parameters", tag) assertEquals("name", subjectName) - assertEquals("is String parameter", toTestString()) + assertEquals("render(Type:String,SUMMARY): is String parameter", toTestString()) } with(content.sections[1]) { assertEquals("Parameters", tag) assertEquals("value", subjectName) - assertEquals("is int parameter", toTestString()) + assertEquals("render(Type:String,SUMMARY): is int parameter", toTestString()) } with(content.sections[2]) { assertEquals("Author", tag) diff --git a/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt b/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt index 46a57278..69d19944 100644 --- a/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt +++ b/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt @@ -39,6 +39,7 @@ interface DokkaConfiguration { val languageVersion: String? val apiVersion: String? val noStdlibLink: Boolean + val noJdkLink: Boolean val cacheRoot: String? val suppressedFiles: List val collectInheritedExtensionsFromLibraries: Boolean @@ -102,6 +103,7 @@ data class SerializeOnlyDokkaConfiguration( override val perPackageOptions: List, override val externalDocumentationLinks: List, override val noStdlibLink: Boolean, + override val noJdkLink: Boolean, override val cacheRoot: String?, override val suppressedFiles: List, override val languageVersion: String?, diff --git a/runners/ant/src/main/kotlin/ant/dokka.kt b/runners/ant/src/main/kotlin/ant/dokka.kt index d1b6bef5..79583a1f 100644 --- a/runners/ant/src/main/kotlin/ant/dokka.kt +++ b/runners/ant/src/main/kotlin/ant/dokka.kt @@ -40,6 +40,7 @@ class DokkaAntTask: Task() { var jdkVersion: Int = 6 var noStdlibLink: Boolean = false + var noJdkLink: Boolean = false var skipDeprecated: Boolean = false @@ -131,6 +132,7 @@ class DokkaAntTask: Task() { perPackageOptions = antPackageOptions, externalDocumentationLinks = antExternalDocumentationLinks.map { it.build() }, noStdlibLink = noStdlibLink, + noJdkLink = noJdkLink, cacheRoot = cacheRoot, languageVersion = languageVersion, apiVersion = apiVersion diff --git a/runners/gradle-plugin/src/main/kotlin/main.kt b/runners/gradle-plugin/src/main/kotlin/main.kt index 4812e217..d3a341e0 100644 --- a/runners/gradle-plugin/src/main/kotlin/main.kt +++ b/runners/gradle-plugin/src/main/kotlin/main.kt @@ -124,6 +124,9 @@ open class DokkaTask : DefaultTask() { @Input var noStdlibLink: Boolean = false + @Input + var noJdkLink: Boolean = false + @Optional @Input var cacheRoot: String? = null @@ -309,11 +312,12 @@ open class DokkaTask : DefaultTask() { perPackageOptions, externalDocumentationLinks, noStdlibLink, - cacheRoot, - collectSuppressedFiles(sourceRoots), - languageVersion, - apiVersion, - collectInheritedExtensionsFromLibraries + noJdkLink, + cacheRoot, + collectSuppressedFiles(sourceRoots), + languageVersion, + apiVersion, + collectInheritedExtensionsFromLibraries ) -- cgit From d228c23bf72e196476ac0b49871d54116e371110 Mon Sep 17 00:00:00 2001 From: Douglas Sigelbaum Date: Wed, 13 Jun 2018 12:11:06 -0700 Subject: Fix default param. --- core/src/main/kotlin/Kotlin/DocumentationBuilder.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt index 58f5e246..f1b8e3d3 100644 --- a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt +++ b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt @@ -55,7 +55,7 @@ class DocumentationOptions(val outputDir: String, perPackageOptions: List = emptyList(), externalDocumentationLinks: List = emptyList(), noStdlibLink: Boolean, - noJdkLink: Boolean, + noJdkLink: Boolean = false, val languageVersion: String?, val apiVersion: String?, cacheRoot: String? = null, -- cgit From 0485472951134685c434d148b6fe5b6393217023 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Sat, 9 Jun 2018 23:51:43 +0300 Subject: KT-24032: Fix parameter rendering in asJava mode #KT-24032 fixed --- core/src/main/kotlin/Java/JavaPsiDocumentationBuilder.kt | 12 +++++++----- core/src/main/kotlin/Languages/NewJavaLanguageService.kt | 2 +- 2 files changed, 8 insertions(+), 6 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Java/JavaPsiDocumentationBuilder.kt b/core/src/main/kotlin/Java/JavaPsiDocumentationBuilder.kt index 9eabc227..332afffb 100644 --- a/core/src/main/kotlin/Java/JavaPsiDocumentationBuilder.kt +++ b/core/src/main/kotlin/Java/JavaPsiDocumentationBuilder.kt @@ -148,11 +148,13 @@ class JavaPsiDocumentationBuilder : JavaDocumentationBuilder { hasSuppressDocTag(element) || skipElementBySuppressedFiles(element) - private fun skipElementByVisibility(element: Any): Boolean = element is PsiModifierListOwner && - !(options.effectivePackageOptions((element.containingFile as? PsiJavaFile)?.packageName ?: "").includeNonPublic) && - (element.hasModifierProperty(PsiModifier.PRIVATE) || - element.hasModifierProperty(PsiModifier.PACKAGE_LOCAL) || - element.isInternal()) + private fun skipElementByVisibility(element: Any): Boolean = + element is PsiModifierListOwner && + element !is PsiParameter && + !(options.effectivePackageOptions((element.containingFile as? PsiJavaFile)?.packageName ?: "").includeNonPublic) && + (element.hasModifierProperty(PsiModifier.PRIVATE) || + element.hasModifierProperty(PsiModifier.PACKAGE_LOCAL) || + element.isInternal()) private fun skipElementBySuppressedFiles(element: Any): Boolean = element is PsiElement && File(element.containingFile.virtualFile.path).absoluteFile in options.suppressedFiles diff --git a/core/src/main/kotlin/Languages/NewJavaLanguageService.kt b/core/src/main/kotlin/Languages/NewJavaLanguageService.kt index fa9f70fd..992cd090 100644 --- a/core/src/main/kotlin/Languages/NewJavaLanguageService.kt +++ b/core/src/main/kotlin/Languages/NewJavaLanguageService.kt @@ -20,7 +20,7 @@ class NewJavaLanguageService : CommonLanguageService() { NodeKind.TypeParameter -> renderTypeParameter(node) NodeKind.Type, NodeKind.UpperBound -> renderType(node) - + NodeKind.Parameter -> renderParameter(node) NodeKind.Constructor, NodeKind.Function -> renderFunction(node) NodeKind.Property -> renderProperty(node) -- cgit From f30807f4e78939fb59f8e46c39b3e538070aacfd Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Sun, 15 Jul 2018 00:48:46 +0300 Subject: Fix missing functions after rebase --- core/src/main/kotlin/Analysis/JavaResolveExtension.kt | 2 +- core/src/main/kotlin/Formats/JavaLayoutHtmlFormat.kt | 3 +-- core/src/main/kotlin/Generation/DokkaGenerator.kt | 1 + core/src/main/kotlin/Kotlin/KotlinLanguageService.kt | 1 - core/src/main/kotlin/Model/DocumentationNode.kt | 7 +++++-- 5 files changed, 8 insertions(+), 6 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Analysis/JavaResolveExtension.kt b/core/src/main/kotlin/Analysis/JavaResolveExtension.kt index f8992d45..4dc6b366 100644 --- a/core/src/main/kotlin/Analysis/JavaResolveExtension.kt +++ b/core/src/main/kotlin/Analysis/JavaResolveExtension.kt @@ -128,4 +128,4 @@ private fun Collection.findByJavaElemen } fun PsiElement.javaResolutionFacade() = - KotlinCacheService.getInstance(project).getResolutionFacadeByFile(this.originalElement.containingFile, JvmPlatform) + KotlinCacheService.getInstance(project).getResolutionFacadeByFile(this.originalElement.containingFile, JvmPlatform)!! diff --git a/core/src/main/kotlin/Formats/JavaLayoutHtmlFormat.kt b/core/src/main/kotlin/Formats/JavaLayoutHtmlFormat.kt index f73cd23e..885cdf6c 100644 --- a/core/src/main/kotlin/Formats/JavaLayoutHtmlFormat.kt +++ b/core/src/main/kotlin/Formats/JavaLayoutHtmlFormat.kt @@ -6,7 +6,6 @@ import kotlinx.html.li import kotlinx.html.stream.appendHTML import kotlinx.html.ul import org.jetbrains.dokka.* -import org.jetbrains.dokka.Kotlin.KotlinDescriptorSignatureProvider import org.jetbrains.dokka.Samples.DefaultSampleProcessingService import org.jetbrains.dokka.Utilities.bind import org.jetbrains.dokka.Utilities.toType @@ -17,7 +16,7 @@ class JavaLayoutHtmlFormatDescriptor : FormatDescriptor, DefaultAnalysisComponen override val packageDocumentationBuilderClass = KotlinPackageDocumentationBuilder::class override val javaDocumentationBuilderClass = KotlinJavaDocumentationBuilder::class override val sampleProcessingService = DefaultSampleProcessingService::class - override val descriptorSignatureProvider = KotlinDescriptorSignatureProvider::class + override val elementSignatureProvider = KotlinElementSignatureProvider::class override fun configureOutput(binder: Binder): Unit = with(binder) { bind() toType generatorServiceClass diff --git a/core/src/main/kotlin/Generation/DokkaGenerator.kt b/core/src/main/kotlin/Generation/DokkaGenerator.kt index 91471849..46fdaf0a 100644 --- a/core/src/main/kotlin/Generation/DokkaGenerator.kt +++ b/core/src/main/kotlin/Generation/DokkaGenerator.kt @@ -20,6 +20,7 @@ import org.jetbrains.kotlin.config.JVMConfigurationKeys import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.resolve.LazyTopDownAnalyzer import org.jetbrains.kotlin.resolve.TopDownAnalysisMode +import org.jetbrains.kotlin.utils.PathUtil import java.io.File import kotlin.system.measureTimeMillis diff --git a/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt b/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt index 237fa9b9..6088d3a5 100644 --- a/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt +++ b/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt @@ -1,6 +1,5 @@ package org.jetbrains.dokka -import org.jetbrains.dokka.Formats.classNodeNameWithOuterClass import org.jetbrains.dokka.LanguageService.RenderMode /** diff --git a/core/src/main/kotlin/Model/DocumentationNode.kt b/core/src/main/kotlin/Model/DocumentationNode.kt index a89f5080..a3388031 100644 --- a/core/src/main/kotlin/Model/DocumentationNode.kt +++ b/core/src/main/kotlin/Model/DocumentationNode.kt @@ -1,7 +1,5 @@ package org.jetbrains.dokka -import org.jetbrains.dokka.Formats.constantValue -import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult import java.util.* enum class NodeKind { @@ -242,4 +240,9 @@ private fun DocumentationNode.isSuperclassFor(node: DocumentationNode): Boolean NodeKind.Exception -> kind == NodeKind.Class || kind == NodeKind.Exception else -> false } +} + +fun DocumentationNode.classNodeNameWithOuterClass(): String { + assert(kind in NodeKind.classLike) + return path.dropWhile { it.kind == NodeKind.Package || it.kind == NodeKind.Module }.joinToString(separator = ".") { it.name } } \ No newline at end of file -- cgit From 93a9052d8434879f8fdf192d9d498285a6a31127 Mon Sep 17 00:00:00 2001 From: Zubakov Aleksey Date: Tue, 17 Jul 2018 17:13:01 +0300 Subject: NodeReferenceGraph style fixes --- core/src/main/kotlin/Model/DocumentationReference.kt | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Model/DocumentationReference.kt b/core/src/main/kotlin/Model/DocumentationReference.kt index 89ec1b3e..5db1f05a 100644 --- a/core/src/main/kotlin/Model/DocumentationReference.kt +++ b/core/src/main/kotlin/Model/DocumentationReference.kt @@ -37,24 +37,24 @@ class PendingDocumentationReference(val lazyNodeFrom: () -> DocumentationNode?, } } -class NodeReferenceGraph() { +class NodeReferenceGraph { private val nodeMap = hashMapOf() val references = arrayListOf() fun register(signature: String, node: DocumentationNode) { - nodeMap.put(signature, node) + nodeMap[signature] = node } fun link(fromNode: DocumentationNode, toSignature: String, kind: RefKind) { - references.add(PendingDocumentationReference({ -> fromNode}, { -> nodeMap[toSignature]}, kind)) + references.add(PendingDocumentationReference({ fromNode }, { nodeMap[toSignature] }, kind)) } fun link(fromSignature: String, toNode: DocumentationNode, kind: RefKind) { - references.add(PendingDocumentationReference({ -> nodeMap[fromSignature]}, { -> toNode}, kind)) + references.add(PendingDocumentationReference({ nodeMap[fromSignature] }, { toNode }, kind)) } fun link(fromSignature: String, toSignature: String, kind: RefKind) { - references.add(PendingDocumentationReference({ -> nodeMap[fromSignature]}, { -> nodeMap[toSignature]}, kind)) + references.add(PendingDocumentationReference({ nodeMap[fromSignature] }, { nodeMap[toSignature] }, kind)) } fun lookup(signature: String) = nodeMap[signature] -- cgit From 899c11d36f565cd192945573860568ff62c16ef2 Mon Sep 17 00:00:00 2001 From: aleksZubakov Date: Wed, 25 Jul 2018 17:24:00 +0300 Subject: Add logic of merging different platforms graphs --- .../main/kotlin/Formats/StructuredFormatService.kt | 12 +- core/src/main/kotlin/Generation/DokkaGenerator.kt | 232 ++++++++++++++++++++- .../src/main/kotlin/Kotlin/DocumentationBuilder.kt | 6 +- core/src/main/kotlin/Model/DocumentationNode.kt | 10 +- .../main/kotlin/Model/DocumentationReference.kt | 53 ++++- 5 files changed, 288 insertions(+), 25 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Formats/StructuredFormatService.kt b/core/src/main/kotlin/Formats/StructuredFormatService.kt index ebc9cde6..41c8f29a 100644 --- a/core/src/main/kotlin/Formats/StructuredFormatService.kt +++ b/core/src/main/kotlin/Formats/StructuredFormatService.kt @@ -514,15 +514,15 @@ abstract class StructuredOutputBuilder(val to: StringBuilder, appendSection("Exceptions", node.membersOrGroupMembers(NodeKind.Exception)) appendSection("Type Aliases", node.membersOrGroupMembers(NodeKind.TypeAlias)) appendSection("Extensions for External Classes", node.members(NodeKind.ExternalClass)) - appendSection("Enum Values", node.members(NodeKind.EnumItem), sortMembers = false, omitSamePlatforms = true) - appendSection("Constructors", node.members(NodeKind.Constructor), omitSamePlatforms = true) - appendSection("Properties", node.members(NodeKind.Property), omitSamePlatforms = true) + appendSection("Enum Values", node.membersOrGroupMembers(NodeKind.EnumItem), sortMembers = false, omitSamePlatforms = true) + appendSection("Constructors", node.membersOrGroupMembers(NodeKind.Constructor), omitSamePlatforms = true) + appendSection("Properties", node.membersOrGroupMembers(NodeKind.Property), omitSamePlatforms = true) appendSection("Inherited Properties", node.inheritedMembers(NodeKind.Property)) - appendSection("Functions", node.members(NodeKind.Function), omitSamePlatforms = true) + appendSection("Functions", node.membersOrGroupMembers(NodeKind.Function), omitSamePlatforms = true) appendSection("Inherited Functions", node.inheritedMembers(NodeKind.Function)) - appendSection("Companion Object Properties", node.members(NodeKind.CompanionObjectProperty), omitSamePlatforms = true) + appendSection("Companion Object Properties", node.membersOrGroupMembers(NodeKind.CompanionObjectProperty), omitSamePlatforms = true) appendSection("Inherited Companion Object Properties", node.inheritedCompanionObjectMembers(NodeKind.Property)) - appendSection("Companion Object Functions", node.members(NodeKind.CompanionObjectFunction), omitSamePlatforms = true) + appendSection("Companion Object Functions", node.membersOrGroupMembers(NodeKind.CompanionObjectFunction), omitSamePlatforms = true) appendSection("Inherited Companion Object Functions", node.inheritedCompanionObjectMembers(NodeKind.Function)) appendSection("Other members", node.members.filter { it.kind !in setOf( diff --git a/core/src/main/kotlin/Generation/DokkaGenerator.kt b/core/src/main/kotlin/Generation/DokkaGenerator.kt index 9de4396b..0c4b3b7e 100644 --- a/core/src/main/kotlin/Generation/DokkaGenerator.kt +++ b/core/src/main/kotlin/Generation/DokkaGenerator.kt @@ -2,6 +2,7 @@ package org.jetbrains.dokka import com.google.inject.Guice import com.google.inject.Injector +import com.intellij.openapi.application.PathManager import com.intellij.openapi.util.Disposer import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.psi.PsiFile @@ -17,6 +18,7 @@ import org.jetbrains.kotlin.cli.common.messages.MessageRenderer import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment import org.jetbrains.kotlin.cli.jvm.config.JavaSourceRoot import org.jetbrains.kotlin.config.JVMConfigurationKeys +import org.jetbrains.kotlin.config.KotlinSourceRoot import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.resolve.LazyTopDownAnalyzer import org.jetbrains.kotlin.resolve.TopDownAnalysisMode @@ -32,28 +34,34 @@ class DokkaGenerator(val logger: DokkaLogger, val moduleName: String, val options: DocumentationOptions) { - private val documentationModule = DocumentationModule(moduleName) + private val documentationModules: MutableList = mutableListOf() fun generate() { val sourcesGroupedByPlatform = sources.groupBy { it.platforms.firstOrNull() to it.analysisPlatform } for ((platformsInfo, roots) in sourcesGroupedByPlatform) { val (platform, analysisPlatform) = platformsInfo - appendSourceModule(platform, analysisPlatform, roots) + + val documentationModule = DocumentationModule(moduleName) + appendSourceModule(platform, analysisPlatform, roots, documentationModule) + documentationModules.add(documentationModule) } - documentationModule.prepareForGeneration(options) + + val totalDocumentationModule = DocumentationMerger(documentationModules).merge() + totalDocumentationModule.prepareForGeneration(options) val timeBuild = measureTimeMillis { logger.info("Generating pages... ") val outputInjector = Guice.createInjector(DokkaOutputModule(options, logger)) - outputInjector.getInstance(Generator::class.java).buildAll(documentationModule) + outputInjector.getInstance(Generator::class.java).buildAll(totalDocumentationModule) } logger.info("done in ${timeBuild / 1000} secs") } - private fun appendSourceModule(defaultPlatform: String?, - analysisPlatform: Platform, - sourceRoots: List - + private fun appendSourceModule( + defaultPlatform: String?, + analysisPlatform: Platform, + sourceRoots: List, + documentationModule: DocumentationModule ) { val sourcePaths = sourceRoots.map { it.path } @@ -81,6 +89,12 @@ class DokkaGenerator(val logger: DokkaLogger, DokkaAnalysisModule(environment, options, defaultPlatformsProvider, documentationModule.nodeRefGraph, logger)) buildDocumentationModule(injector, documentationModule, { isNotSample(it) }, includes) + documentationModule.nodeRefGraph.nodeMapView.forEach { (_, node) -> + node.addReferenceTo( + DocumentationNode(analysisPlatform.key, Content.Empty, NodeKind.Platform), + RefKind.Platform + ) + } val timeAnalyse = System.currentTimeMillis() - startAnalyse logger.info("done in ${timeAnalyse / 1000} secs") @@ -214,3 +228,205 @@ fun KotlinCoreEnvironment.getJavaSourceFiles(): List { } return result } + +class DocumentationMerger( + private val documentationModules: List +) { + private val producedNodeRefGraph: NodeReferenceGraph + private val signatureMap: Map + + init { + signatureMap = documentationModules + .flatMap { it.nodeRefGraph.nodeMapView.entries } + .map { (k, v) -> v to k } + .toMap() + + producedNodeRefGraph = NodeReferenceGraph() + documentationModules.map { it.nodeRefGraph } + .flatMap { it.references } + .distinct() + .forEach { producedNodeRefGraph.addReference(it) } + } + + private fun splitReferencesByKind( + source: List, + kind: RefKind + ): Pair, List> = + Pair(source.filter { it.kind == kind }, source.filterNot { it.kind == kind }) + + + private fun mergePackageReferences( + from: DocumentationNode, + packages: List + ): List { + val packagesByName = packages + .map { it.to } + .groupBy { it.name } + + val mutableList: MutableList = mutableListOf() + for ((name, listOfPackages) in packagesByName) { + val producedPackage = mergePackagesWithEqualNames(from, listOfPackages) + updatePendingReferences(name, producedPackage) + + mutableList.add( + DocumentationReference(from, producedPackage, RefKind.Member) + ) + } + + return mutableList + } + + private fun mergePackagesWithEqualNames( + from: DocumentationNode, + packages: List + ): DocumentationNode { + val references = packages.flatMap { it.allReferences() } + + val mergedPackage = + DocumentationNode( + packages.first().name, + Content.Empty, + NodeKind.Package + ) + + val mergedReferences = mergeReferences(mergedPackage, references) + + for (packageNode in packages) { + mergedPackage.updateContent { + for (otherChild in packageNode.content.children) { + children.add(otherChild) + } + } + } + + mergedPackage.dropReferences { true } // clear() + for (ref in mergedReferences.distinct()) { + mergedPackage.addReference(ref) + } + + from.append(mergedPackage, RefKind.Member) + + return mergedPackage + } + + + private fun mergeMembers( + from: DocumentationNode, + refs: List + ): List { + val membersBySignature: Map> = refs.map { it.to } + .filter { signatureMap.containsKey(it) } + .groupBy { signatureMap[it]!! } + + val mergedMembers: MutableList = mutableListOf() + for ((signature, members) in membersBySignature) { + val newNode = mergeMembersWithEqualSignature(signature, from, members) + + producedNodeRefGraph.register(signature, newNode) + updatePendingReferences(signature, newNode) + from.append(newNode, RefKind.Member) + + mergedMembers.add(DocumentationReference(from, newNode, RefKind.Member)) + } + + return mergedMembers + } + + private fun mergeMembersWithEqualSignature( + signature: String, + from: DocumentationNode, + refs: List + ): DocumentationNode { + if (refs.size == 1) { + val singleNode = refs.single() + singleNode.owner?.let { owner -> + singleNode.dropReferences { it.to == owner && it.kind == RefKind.Owner } + } + return singleNode + } + val groupNode = DocumentationNode(refs.first().name, Content.Empty, NodeKind.GroupNode) + groupNode.appendTextNode(signature, NodeKind.Signature, RefKind.Detail) + + for (node in refs) { + if (node != groupNode) { + node.owner?.let { owner -> + node.dropReferences { it.to == owner && it.kind == RefKind.Owner } + from.dropReferences { it.to == node && it.kind == RefKind.Member } + } + groupNode.append(node, RefKind.Member) + } + } + return groupNode + } + + + private fun mergeReferences( + from: DocumentationNode, + refs: List + ): List { + val allRefsToPackages = refs.map { it.to } + .all { it.kind == NodeKind.Package } + + if (allRefsToPackages) { + return mergePackageReferences(from, refs) + } + + val (memberRefs, notMemberRefs) = splitReferencesByKind(refs, RefKind.Member) + val mergedMembers = mergeMembers(from, memberRefs) + + return (mergedMembers + notMemberRefs).distinctBy { + it.kind to it.to.name + } + } + + + private fun updatePendingReferences( + signature: String, + nodeToUpdate: DocumentationNode + ) { + producedNodeRefGraph.references.forEach { + it.lazyNodeFrom.update(signature, nodeToUpdate) + it.lazyNodeTo.update(signature, nodeToUpdate) + } + } + + private fun NodeResolver.update(signature: String, nodeToUpdate: DocumentationNode) { + when (this) { + is NodeResolver.BySignature -> update(signature, nodeToUpdate) + is NodeResolver.Exact -> update(signature, nodeToUpdate) + } + } + + private fun NodeResolver.BySignature.update(signature: String, nodeToUpdate: DocumentationNode) { + if (signature == nodeToUpdate.name) { + nodeMap = producedNodeRefGraph.nodeMapView + } + } + + private fun NodeResolver.Exact.update(signature: String, nodeToUpdate: DocumentationNode) { + exactNode?.let { it -> + val equalSignature = + it.anyReference { ref -> ref.to.kind == NodeKind.Signature && ref.to.name == signature } + + if (equalSignature) { + exactNode = nodeToUpdate + } + } + } + + fun merge(): DocumentationModule { + val refs = documentationModules.flatMap { + it.allReferences() + } + val mergedDocumentationModule = DocumentationModule( + name = documentationModules.first().name, + nodeRefGraph = producedNodeRefGraph + ) + + mergeReferences(mergedDocumentationModule, refs) + + return mergedDocumentationModule + } + + +} \ No newline at end of file diff --git a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt index f1b8e3d3..e3675f9d 100644 --- a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt +++ b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt @@ -1079,7 +1079,7 @@ fun DeclarationDescriptor.signature(): String { is TypeAliasDescriptor -> DescriptorUtils.getFqName(this).asString() is PropertyDescriptor -> containingDeclaration.signature() + "$" + name + receiverSignature() - is FunctionDescriptor -> containingDeclaration.signature() + "$" + name + parameterSignature() + is FunctionDescriptor -> containingDeclaration.signature() + "$" + name + parameterSignature() + ":" + returnType?.signature() is ValueParameterDescriptor -> containingDeclaration.signature() + "/" + name is TypeParameterDescriptor -> containingDeclaration.signature() + "*" + name is ReceiverParameterDescriptor -> containingDeclaration.signature() + "/" + name @@ -1149,7 +1149,9 @@ fun DocumentationModule.prepareForGeneration(options: DocumentationOptions) { fun DocumentationNode.generateAllTypesNode() { val allTypes = members(NodeKind.Package) - .flatMap { it.members.filter { it.kind in NodeKind.classLike || it.kind == NodeKind.ExternalClass } } + .flatMap { it.members.filter { + it.kind in NodeKind.classLike || it.kind == NodeKind.ExternalClass + || (it.kind == NodeKind.GroupNode && it.anyReference { it.to.kind in NodeKind.classLike }) } } .sortedBy { if (it.kind == NodeKind.ExternalClass) it.name.substringAfterLast('.').toLowerCase() else it.name.toLowerCase() } val allTypesNode = DocumentationNode("alltypes", Content.Empty, NodeKind.AllTypes) diff --git a/core/src/main/kotlin/Model/DocumentationNode.kt b/core/src/main/kotlin/Model/DocumentationNode.kt index a3388031..bdb7cf20 100644 --- a/core/src/main/kotlin/Model/DocumentationNode.kt +++ b/core/src/main/kotlin/Model/DocumentationNode.kt @@ -134,6 +134,10 @@ open class DocumentationNode(val name: String, references.add(DocumentationReference(this, to, kind)) } + fun addReference(reference: DocumentationReference) { + references.add(reference) + } + fun dropReferences(predicate: (DocumentationReference) -> Boolean) { references.removeAll(predicate) } @@ -159,6 +163,8 @@ open class DocumentationNode(val name: String, fun member(kind: NodeKind): DocumentationNode = members.filter { it.kind == kind }.single() fun link(kind: NodeKind): DocumentationNode = links.filter { it.kind == kind }.single() + fun anyReference(predicate: (DocumentationReference) -> Boolean): Boolean = references.any(predicate) + fun references(kind: RefKind): List = references.filter { it.kind == kind } fun allReferences(): Set = references @@ -167,9 +173,9 @@ open class DocumentationNode(val name: String, } } -class DocumentationModule(name: String, content: Content = Content.Empty) +class DocumentationModule(name: String, content: Content = Content.Empty, val nodeRefGraph: NodeReferenceGraph = NodeReferenceGraph()) : DocumentationNode(name, content, NodeKind.Module) { - val nodeRefGraph = NodeReferenceGraph() + } val DocumentationNode.path: List diff --git a/core/src/main/kotlin/Model/DocumentationReference.kt b/core/src/main/kotlin/Model/DocumentationReference.kt index 5db1f05a..9223c17a 100644 --- a/core/src/main/kotlin/Model/DocumentationReference.kt +++ b/core/src/main/kotlin/Model/DocumentationReference.kt @@ -25,12 +25,27 @@ enum class RefKind { data class DocumentationReference(val from: DocumentationNode, val to: DocumentationNode, val kind: RefKind) { } -class PendingDocumentationReference(val lazyNodeFrom: () -> DocumentationNode?, - val lazyNodeTo: () -> DocumentationNode?, +sealed class NodeResolver { + abstract fun resolve(): DocumentationNode? + class BySignature(var signature: String, var nodeMap: Map) : NodeResolver() { + override fun resolve(): DocumentationNode? { + return nodeMap[signature] + } + } + + class Exact(var exactNode: DocumentationNode?) : NodeResolver() { + override fun resolve(): DocumentationNode? { + return exactNode + } + } +} + +class PendingDocumentationReference(val lazyNodeFrom: NodeResolver, + val lazyNodeTo: NodeResolver, val kind: RefKind) { fun resolve() { - val fromNode = lazyNodeFrom() - val toNode = lazyNodeTo() + val fromNode = lazyNodeFrom.resolve() + val toNode = lazyNodeTo.resolve() if (fromNode != null && toNode != null) { fromNode.addReferenceTo(toNode, kind) } @@ -39,6 +54,9 @@ class PendingDocumentationReference(val lazyNodeFrom: () -> DocumentationNode?, class NodeReferenceGraph { private val nodeMap = hashMapOf() + val nodeMapView: Map + get() = HashMap(nodeMap) + val references = arrayListOf() fun register(signature: String, node: DocumentationNode) { @@ -46,15 +64,36 @@ class NodeReferenceGraph { } fun link(fromNode: DocumentationNode, toSignature: String, kind: RefKind) { - references.add(PendingDocumentationReference({ fromNode }, { nodeMap[toSignature] }, kind)) + references.add( + PendingDocumentationReference( + NodeResolver.Exact(fromNode), + NodeResolver.BySignature(toSignature, nodeMap), + kind + )) } fun link(fromSignature: String, toNode: DocumentationNode, kind: RefKind) { - references.add(PendingDocumentationReference({ nodeMap[fromSignature] }, { toNode }, kind)) + references.add( + PendingDocumentationReference( + NodeResolver.BySignature(fromSignature, nodeMap), + NodeResolver.Exact(toNode), + kind + ) + ) } fun link(fromSignature: String, toSignature: String, kind: RefKind) { - references.add(PendingDocumentationReference({ nodeMap[fromSignature] }, { nodeMap[toSignature] }, kind)) + references.add( + PendingDocumentationReference( + NodeResolver.BySignature(fromSignature, nodeMap), + NodeResolver.BySignature(toSignature, nodeMap), + kind + ) + ) + } + + fun addReference(reference: PendingDocumentationReference) { + references.add(reference) } fun lookup(signature: String) = nodeMap[signature] -- cgit From 052a218dcf8bc565d5e78dc900a9647f0da5350a Mon Sep 17 00:00:00 2001 From: aleksZubakov Date: Wed, 1 Aug 2018 19:48:45 +0300 Subject: Refactoring, replace DocumentationOption with PassConfiguration --- core/src/main/kotlin/DokkaBootstrapImpl.kt | 32 +----- core/src/main/kotlin/Generation/DokkaGenerator.kt | 58 +++++------ core/src/main/kotlin/Generation/FileGenerator.kt | 5 +- .../main/kotlin/Generation/configurationImpl.kt | 70 ++++++++----- .../kotlin/Java/JavaPsiDocumentationBuilder.kt | 25 +++-- .../main/kotlin/Kotlin/DeclarationLinkResolver.kt | 4 +- .../kotlin/Kotlin/DescriptorDocumentationParser.kt | 2 +- .../src/main/kotlin/Kotlin/DocumentationBuilder.kt | 108 ++++++--------------- .../Kotlin/ExternalDocumentationLinkResolver.kt | 13 ++- .../Kotlin/KotlinAsJavaDocumentationBuilder.kt | 2 +- .../Samples/DefaultSampleProcessingService.kt | 2 +- .../KotlinWebsiteSampleProcessingService.kt | 4 +- core/src/main/kotlin/Utilities/DokkaModules.kt | 18 ++-- core/src/main/kotlin/javadoc/dokka-adapters.kt | 9 +- core/src/test/kotlin/TestAPI.kt | 44 +++++---- .../test/kotlin/format/KotlinWebSiteFormatTest.kt | 19 ++-- .../kotlin/format/KotlinWebSiteHtmlFormatTest.kt | 22 +++-- core/src/test/kotlin/format/MarkdownFormatTest.kt | 36 ++++--- .../kotlin/org/jetbrains/dokka/configuration.kt | 71 ++++++-------- runners/ant/src/main/kotlin/ant/dokka.kt | 49 +++++----- runners/cli/src/main/kotlin/cli/main.kt | 36 ++++--- runners/maven-plugin/src/main/kotlin/DokkaMojo.kt | 47 ++++----- 22 files changed, 323 insertions(+), 353 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/DokkaBootstrapImpl.kt b/core/src/main/kotlin/DokkaBootstrapImpl.kt index e18ab6cf..ccafcd12 100644 --- a/core/src/main/kotlin/DokkaBootstrapImpl.kt +++ b/core/src/main/kotlin/DokkaBootstrapImpl.kt @@ -2,7 +2,6 @@ package org.jetbrains.dokka import org.jetbrains.dokka.DokkaConfiguration.PackageOptions import ru.yole.jkid.deserialization.deserialize -import java.io.File import java.util.function.BiConsumer @@ -44,36 +43,7 @@ class DokkaBootstrapImpl : DokkaBootstrap { = configure(DokkaProxyLogger(logger), deserialize(serializedConfigurationJSON)) fun configure(logger: DokkaLogger, configuration: DokkaConfiguration) = with(configuration) { - generator = DokkaGenerator( - logger, - classpath, - sourceRoots, - samples, - includes, - moduleName, - DocumentationOptions( - outputDir = outputDir, - outputFormat = format, - includeNonPublic = includeNonPublic, - includeRootPackage = includeRootPackage, - reportUndocumented = reportUndocumented, - skipEmptyPackages = skipEmptyPackages, - skipDeprecated = skipDeprecated, - jdkVersion = jdkVersion, - generateIndexPages = generateIndexPages, - sourceLinks = sourceLinks, - impliedPlatforms = impliedPlatforms, - perPackageOptions = perPackageOptions, - externalDocumentationLinks = externalDocumentationLinks, - noStdlibLink = noStdlibLink, - noJdkLink = noJdkLink, - languageVersion = languageVersion, - apiVersion = apiVersion, - cacheRoot = cacheRoot, - suppressedFiles = suppressedFiles.map { File(it) }.toSet(), - collectInheritedExtensionsFromLibraries = collectInheritedExtensionsFromLibraries - ) - ) + generator = DokkaGenerator(configuration, logger) } override fun generate() = generator.generate() diff --git a/core/src/main/kotlin/Generation/DokkaGenerator.kt b/core/src/main/kotlin/Generation/DokkaGenerator.kt index 0c4b3b7e..2e46d908 100644 --- a/core/src/main/kotlin/Generation/DokkaGenerator.kt +++ b/core/src/main/kotlin/Generation/DokkaGenerator.kt @@ -2,13 +2,11 @@ package org.jetbrains.dokka import com.google.inject.Guice import com.google.inject.Injector -import com.intellij.openapi.application.PathManager import com.intellij.openapi.util.Disposer import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.psi.PsiFile import com.intellij.psi.PsiJavaFile import com.intellij.psi.PsiManager -import org.jetbrains.dokka.DokkaConfiguration.SourceRoot import org.jetbrains.dokka.Utilities.DokkaAnalysisModule import org.jetbrains.dokka.Utilities.DokkaOutputModule import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation @@ -18,7 +16,6 @@ import org.jetbrains.kotlin.cli.common.messages.MessageRenderer import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment import org.jetbrains.kotlin.cli.jvm.config.JavaSourceRoot import org.jetbrains.kotlin.config.JVMConfigurationKeys -import org.jetbrains.kotlin.config.KotlinSourceRoot import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.resolve.LazyTopDownAnalyzer import org.jetbrains.kotlin.resolve.TopDownAnalysisMode @@ -26,56 +23,49 @@ import org.jetbrains.kotlin.utils.PathUtil import java.io.File import kotlin.system.measureTimeMillis -class DokkaGenerator(val logger: DokkaLogger, - val classpath: List, - val sources: List, - val samples: List, - val includes: List, - val moduleName: String, - val options: DocumentationOptions) { +class DokkaGenerator(val dokkaConfiguration: DokkaConfiguration, + val logger: DokkaLogger) { private val documentationModules: MutableList = mutableListOf() - fun generate() { - val sourcesGroupedByPlatform = sources.groupBy { it.platforms.firstOrNull() to it.analysisPlatform } - for ((platformsInfo, roots) in sourcesGroupedByPlatform) { - val (platform, analysisPlatform) = platformsInfo - val documentationModule = DocumentationModule(moduleName) - appendSourceModule(platform, analysisPlatform, roots, documentationModule) + fun generate() = with(dokkaConfiguration) { + + + for (pass in passesConfigurations) { + val documentationModule = DocumentationModule(pass.moduleName) + appendSourceModule(pass, documentationModule) documentationModules.add(documentationModule) } val totalDocumentationModule = DocumentationMerger(documentationModules).merge() - totalDocumentationModule.prepareForGeneration(options) + totalDocumentationModule.prepareForGeneration(dokkaConfiguration) val timeBuild = measureTimeMillis { logger.info("Generating pages... ") - val outputInjector = Guice.createInjector(DokkaOutputModule(options, logger)) + val outputInjector = Guice.createInjector(DokkaOutputModule(dokkaConfiguration, logger)) outputInjector.getInstance(Generator::class.java).buildAll(totalDocumentationModule) } logger.info("done in ${timeBuild / 1000} secs") } private fun appendSourceModule( - defaultPlatform: String?, - analysisPlatform: Platform, - sourceRoots: List, + passConfiguration: DokkaConfiguration.PassConfiguration, documentationModule: DocumentationModule - ) { + ) = with(passConfiguration) { - val sourcePaths = sourceRoots.map { it.path } - val environment = createAnalysisEnvironment(sourcePaths, analysisPlatform) + val sourcePaths = passConfiguration.sourceRoots.map { it.path } + val environment = createAnalysisEnvironment(sourcePaths, passConfiguration) logger.info("Module: $moduleName") - logger.info("Output: ${File(options.outputDir)}") + logger.info("Output: ${File(dokkaConfiguration.outputDir)}") logger.info("Sources: ${sourcePaths.joinToString()}") logger.info("Classpath: ${environment.classpath.joinToString()}") logger.info("Analysing sources and libraries... ") val startAnalyse = System.currentTimeMillis() - val defaultPlatformAsList = defaultPlatform?.let { listOf(it) }.orEmpty() + val defaultPlatformAsList = listOf(passConfiguration.analysisPlatform.key) val defaultPlatformsProvider = object : DefaultPlatformsProvider { override fun getDefaultPlatforms(descriptor: DeclarationDescriptor): List { val containingFilePath = descriptor.sourcePsi()?.containingFile?.virtualFile?.canonicalPath @@ -86,9 +76,9 @@ class DokkaGenerator(val logger: DokkaLogger, } val injector = Guice.createInjector( - DokkaAnalysisModule(environment, options, defaultPlatformsProvider, documentationModule.nodeRefGraph, logger)) + DokkaAnalysisModule(environment, dokkaConfiguration, defaultPlatformsProvider, documentationModule.nodeRefGraph, passConfiguration, logger)) - buildDocumentationModule(injector, documentationModule, { isNotSample(it) }, includes) + buildDocumentationModule(injector, documentationModule, { isNotSample(it, passConfiguration.samples) }, includes) documentationModule.nodeRefGraph.nodeMapView.forEach { (_, node) -> node.addReferenceTo( DocumentationNode(analysisPlatform.key, Content.Empty, NodeKind.Platform), @@ -102,28 +92,28 @@ class DokkaGenerator(val logger: DokkaLogger, Disposer.dispose(environment) } - fun createAnalysisEnvironment(sourcePaths: List, analysisPlatform: Platform): AnalysisEnvironment { - val environment = AnalysisEnvironment(DokkaMessageCollector(logger), analysisPlatform) + fun createAnalysisEnvironment(sourcePaths: List, passConfiguration: DokkaConfiguration.PassConfiguration): AnalysisEnvironment { + val environment = AnalysisEnvironment(DokkaMessageCollector(logger), passConfiguration.analysisPlatform) environment.apply { if (analysisPlatform == Platform.jvm) { addClasspath(PathUtil.getJdkClassesRootsFromCurrentJre()) } // addClasspath(PathUtil.getKotlinPathsForCompiler().getRuntimePath()) - for (element in this@DokkaGenerator.classpath) { + for (element in passConfiguration.classpath) { addClasspath(File(element)) } addSources(sourcePaths) - addSources(this@DokkaGenerator.samples) + addSources(passConfiguration.samples) - loadLanguageVersionSettings(options.languageVersion, options.apiVersion) + loadLanguageVersionSettings(passConfiguration.languageVersion, passConfiguration.apiVersion) } return environment } - fun isNotSample(file: PsiFile): Boolean { + fun isNotSample(file: PsiFile, samples: List): Boolean { val sourceFile = File(file.virtualFile!!.path) return samples.none { sample -> val canonicalSample = File(sample).canonicalPath diff --git a/core/src/main/kotlin/Generation/FileGenerator.kt b/core/src/main/kotlin/Generation/FileGenerator.kt index b7c6cf63..eb6800b3 100644 --- a/core/src/main/kotlin/Generation/FileGenerator.kt +++ b/core/src/main/kotlin/Generation/FileGenerator.kt @@ -2,7 +2,6 @@ package org.jetbrains.dokka import com.google.inject.Inject import com.google.inject.name.Named -import org.jetbrains.kotlin.utils.fileUtils.withReplacedExtensionOrNull import java.io.File import java.io.FileOutputStream import java.io.IOException @@ -12,7 +11,7 @@ class FileGenerator @Inject constructor(@Named("outputDir") override val root: F @set:Inject(optional = true) var outlineService: OutlineFormatService? = null @set:Inject(optional = true) lateinit var formatService: FormatService - @set:Inject(optional = true) lateinit var options: DocumentationOptions + @set:Inject(optional = true) lateinit var dokkaConfiguration: DokkaConfiguration @set:Inject(optional = true) var packageListService: PackageListService? = null override fun location(node: DocumentationNode): FileLocation { @@ -74,7 +73,7 @@ class FileGenerator @Inject constructor(@Named("outputDir") override val root: F val moduleRoot = location(module).file.parentFile val packageListFile = File(moduleRoot, "package-list") - packageListFile.writeText("\$dokka.format:${options.outputFormat}\n" + + packageListFile.writeText("\$dokka.format:${dokkaConfiguration.format}\n" + packageListService!!.formatPackageList(module as DocumentationModule)) } diff --git a/core/src/main/kotlin/Generation/configurationImpl.kt b/core/src/main/kotlin/Generation/configurationImpl.kt index 8829682a..3e39b4ed 100644 --- a/core/src/main/kotlin/Generation/configurationImpl.kt +++ b/core/src/main/kotlin/Generation/configurationImpl.kt @@ -45,29 +45,47 @@ data class PackageOptionsImpl(override val prefix: String, override val suppress: Boolean = false) : DokkaConfiguration.PackageOptions data class DokkaConfigurationImpl( - override val moduleName: String, - override val classpath: List, - override val sourceRoots: List, - override val samples: List, - override val includes: List, - override val outputDir: String, - override val format: String, - override val includeNonPublic: Boolean, - override val includeRootPackage: Boolean, - override val reportUndocumented: Boolean, - override val skipEmptyPackages: Boolean, - override val skipDeprecated: Boolean, - override val jdkVersion: Int, - override val generateIndexPages: Boolean, - override val sourceLinks: List, - override val impliedPlatforms: List, - override val perPackageOptions: List, - override val externalDocumentationLinks: List, - override val noStdlibLink: Boolean, - override val noJdkLink: Boolean, - override val cacheRoot: String?, - override val suppressedFiles: List, - override val languageVersion: String?, - override val apiVersion: String?, - override val collectInheritedExtensionsFromLibraries: Boolean -) : DokkaConfiguration \ No newline at end of file + override val outputDir: String = "", + override val format: String = "html", + override val generateIndexPages: Boolean = false, + override val cacheRoot: String? = null, + override val impliedPlatforms: List = listOf(), + override val passesConfigurations: List = listOf() +) : DokkaConfiguration + +class PassConfigurationImpl ( + override val classpath: List = listOf(), + override val moduleName: String = "", + override val sourceRoots: List = listOf(), + override val samples: List = listOf(), + override val includes: List = listOf(), + override val includeNonPublic: Boolean = false, + override val includeRootPackage: Boolean = false, + override val reportUndocumented: Boolean = false, + override val skipEmptyPackages: Boolean = false, + override val skipDeprecated: Boolean = false, + override val jdkVersion: Int = 6, + override val sourceLinks: List = listOf(), + override val perPackageOptions: List = listOf(), + externalDocumentationLinks: List = listOf(), + override val languageVersion: String? = null, + override val apiVersion: String? = null, + override val noStdlibLink: Boolean = false, + override val noJdkLink: Boolean = false, + override val suppressedFiles: List = listOf(), + override val collectInheritedExtensionsFromLibraries: Boolean = false, + override val analysisPlatform: Platform = Platform.DEFAULT, + override val targets: List = listOf() +): DokkaConfiguration.PassConfiguration { + private val defaultLinks = run { + val links = mutableListOf() + if (!noJdkLink) + links += DokkaConfiguration.ExternalDocumentationLink.Builder("http://docs.oracle.com/javase/$jdkVersion/docs/api/").build() + + if (!noStdlibLink) + links += DokkaConfiguration.ExternalDocumentationLink.Builder("https://kotlinlang.org/api/latest/jvm/stdlib/").build() + links + } + override val externalDocumentationLinks = defaultLinks + externalDocumentationLinks +} + diff --git a/core/src/main/kotlin/Java/JavaPsiDocumentationBuilder.kt b/core/src/main/kotlin/Java/JavaPsiDocumentationBuilder.kt index 332afffb..1fe4d180 100644 --- a/core/src/main/kotlin/Java/JavaPsiDocumentationBuilder.kt +++ b/core/src/main/kotlin/Java/JavaPsiDocumentationBuilder.kt @@ -13,7 +13,6 @@ import org.jetbrains.kotlin.kdoc.psi.impl.KDocTag import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtModifierListOwner -import java.io.File fun getSignature(element: PsiElement?) = when(element) { is PsiPackage -> element.qualifiedName @@ -44,24 +43,24 @@ interface JavaDocumentationBuilder { } class JavaPsiDocumentationBuilder : JavaDocumentationBuilder { - private val options: DocumentationOptions + private val passConfiguration: DokkaConfiguration.PassConfiguration private val refGraph: NodeReferenceGraph private val docParser: JavaDocumentationParser @Inject constructor( - options: DocumentationOptions, - refGraph: NodeReferenceGraph, - logger: DokkaLogger, - signatureProvider: ElementSignatureProvider, - externalDocumentationLinkResolver: ExternalDocumentationLinkResolver + passConfiguration: DokkaConfiguration.PassConfiguration, + refGraph: NodeReferenceGraph, + logger: DokkaLogger, + signatureProvider: ElementSignatureProvider, + externalDocumentationLinkResolver: ExternalDocumentationLinkResolver ) { - this.options = options + this.passConfiguration = passConfiguration this.refGraph = refGraph this.docParser = JavadocParser(refGraph, logger, signatureProvider, externalDocumentationLinkResolver) } - constructor(options: DocumentationOptions, refGraph: NodeReferenceGraph, docParser: JavaDocumentationParser) { - this.options = options + constructor(passConfiguration: DokkaConfiguration.PassConfiguration, refGraph: NodeReferenceGraph, docParser: JavaDocumentationParser) { + this.passConfiguration = passConfiguration this.refGraph = refGraph this.docParser = docParser } @@ -141,7 +140,7 @@ class JavaPsiDocumentationBuilder : JavaDocumentationBuilder { } } - private fun skipFile(javaFile: PsiJavaFile): Boolean = options.effectivePackageOptions(javaFile.packageName).suppress + private fun skipFile(javaFile: PsiJavaFile): Boolean = passConfiguration.effectivePackageOptions(javaFile.packageName).suppress private fun skipElement(element: Any) = skipElementByVisibility(element) || @@ -151,13 +150,13 @@ class JavaPsiDocumentationBuilder : JavaDocumentationBuilder { private fun skipElementByVisibility(element: Any): Boolean = element is PsiModifierListOwner && element !is PsiParameter && - !(options.effectivePackageOptions((element.containingFile as? PsiJavaFile)?.packageName ?: "").includeNonPublic) && + !(passConfiguration.effectivePackageOptions((element.containingFile as? PsiJavaFile)?.packageName ?: "").includeNonPublic) && (element.hasModifierProperty(PsiModifier.PRIVATE) || element.hasModifierProperty(PsiModifier.PACKAGE_LOCAL) || element.isInternal()) private fun skipElementBySuppressedFiles(element: Any): Boolean = - element is PsiElement && File(element.containingFile.virtualFile.path).absoluteFile in options.suppressedFiles + element is PsiElement && element.containingFile.virtualFile.path in passConfiguration.suppressedFiles private fun PsiElement.isInternal(): Boolean { val ktElement = (this as? KtLightElement<*, *>)?.kotlinOrigin ?: return false diff --git a/core/src/main/kotlin/Kotlin/DeclarationLinkResolver.kt b/core/src/main/kotlin/Kotlin/DeclarationLinkResolver.kt index d73bef4a..c3a84e57 100644 --- a/core/src/main/kotlin/Kotlin/DeclarationLinkResolver.kt +++ b/core/src/main/kotlin/Kotlin/DeclarationLinkResolver.kt @@ -10,7 +10,7 @@ class DeclarationLinkResolver @Inject constructor(val resolutionFacade: DokkaResolutionFacade, val refGraph: NodeReferenceGraph, val logger: DokkaLogger, - val options: DocumentationOptions, + val passConfiguration: DokkaConfiguration.PassConfiguration, val externalDocumentationLinkResolver: ExternalDocumentationLinkResolver, val elementSignatureProvider: ElementSignatureProvider) { @@ -63,7 +63,7 @@ class DeclarationLinkResolver if (symbol is CallableMemberDescriptor && symbol.kind == CallableMemberDescriptor.Kind.FAKE_OVERRIDE) { return symbol.overriddenDescriptors.firstOrNull() } - if (symbol is TypeAliasDescriptor && !symbol.isDocumented(options)) { + if (symbol is TypeAliasDescriptor && !symbol.isDocumented(passConfiguration)) { return symbol.classDescriptor } return symbol diff --git a/core/src/main/kotlin/Kotlin/DescriptorDocumentationParser.kt b/core/src/main/kotlin/Kotlin/DescriptorDocumentationParser.kt index 7817da18..d0650d45 100644 --- a/core/src/main/kotlin/Kotlin/DescriptorDocumentationParser.kt +++ b/core/src/main/kotlin/Kotlin/DescriptorDocumentationParser.kt @@ -28,7 +28,7 @@ import org.jetbrains.kotlin.resolve.scopes.getDescriptorsFiltered import org.jetbrains.kotlin.resolve.source.PsiSourceElement class DescriptorDocumentationParser - @Inject constructor(val options: DocumentationOptions, + @Inject constructor(val options: DokkaConfiguration.PassConfiguration, val logger: DokkaLogger, val linkResolver: DeclarationLinkResolver, val resolutionFacade: DokkaResolutionFacade, diff --git a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt index e3675f9d..fb0b898a 100644 --- a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt +++ b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt @@ -4,7 +4,7 @@ import com.google.inject.Inject import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiField import com.intellij.psi.PsiJavaFile -import org.jetbrains.dokka.DokkaConfiguration.* +import org.jetbrains.dokka.DokkaConfiguration.PassConfiguration import org.jetbrains.dokka.Kotlin.DescriptorDocumentationParser import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.descriptors.* @@ -35,62 +35,8 @@ import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.types.* import org.jetbrains.kotlin.types.typeUtil.supertypes import org.jetbrains.kotlin.util.supertypesWithAny -import java.io.File -import java.nio.file.Path -import java.nio.file.Paths import com.google.inject.name.Named as GuiceNamed -class DocumentationOptions(val outputDir: String, - val outputFormat: String, - includeNonPublic: Boolean = false, - val includeRootPackage: Boolean = false, - reportUndocumented: Boolean = true, - val skipEmptyPackages: Boolean = true, - skipDeprecated: Boolean = false, - jdkVersion: Int = 6, - val generateIndexPages: Boolean = true, - val sourceLinks: List = emptyList(), - val impliedPlatforms: List = emptyList(), - // Sorted by pattern length - perPackageOptions: List = emptyList(), - externalDocumentationLinks: List = emptyList(), - noStdlibLink: Boolean, - noJdkLink: Boolean = false, - val languageVersion: String?, - val apiVersion: String?, - cacheRoot: String? = null, - val suppressedFiles: Set = emptySet(), - val collectInheritedExtensionsFromLibraries: Boolean = false) { - init { - if (perPackageOptions.any { it.prefix == "" }) - throw IllegalArgumentException("Please do not register packageOptions with all match pattern, use global settings instead") - } - - val perPackageOptions = perPackageOptions.sortedByDescending { it.prefix.length } - val rootPackageOptions = PackageOptionsImpl("", includeNonPublic, reportUndocumented, skipDeprecated) - - fun effectivePackageOptions(pack: String): PackageOptions = perPackageOptions.firstOrNull { pack == it.prefix || pack.startsWith(it.prefix + ".") } ?: rootPackageOptions - fun effectivePackageOptions(pack: FqName): PackageOptions = effectivePackageOptions(pack.asString()) - - val defaultLinks = run { - val links = mutableListOf() - if (!noJdkLink) - links += ExternalDocumentationLink.Builder("http://docs.oracle.com/javase/$jdkVersion/docs/api/").build() - - if (!noStdlibLink) - links += ExternalDocumentationLink.Builder("https://kotlinlang.org/api/latest/jvm/stdlib/").build() - links - } - - val externalDocumentationLinks = defaultLinks + externalDocumentationLinks - - val cacheRoot: Path? = when { - cacheRoot == "default" -> Paths.get(System.getProperty("user.home"), ".cache", "dokka") - cacheRoot != null -> Paths.get(cacheRoot) - else -> null - } -} - private fun isExtensionForExternalClass(extensionFunctionDescriptor: DeclarationDescriptor, extensionReceiverDescriptor: DeclarationDescriptor, allFqNames: Collection): Boolean { @@ -120,7 +66,7 @@ val ignoredSupertypes = setOf( class DocumentationBuilder @Inject constructor(val resolutionFacade: DokkaResolutionFacade, val descriptorDocumentationParser: DescriptorDocumentationParser, - val options: DocumentationOptions, + val passConfiguration: DokkaConfiguration.PassConfiguration, val refGraph: NodeReferenceGraph, val platformNodeRegistry: PlatformNodeRegistry, val logger: DokkaLogger, @@ -352,7 +298,7 @@ class DocumentationBuilder fun DocumentationNode.isSinceKotlin() = name == "SinceKotlin" && kind == NodeKind.Annotation fun DocumentationNode.appendSourceLink(sourceElement: SourceElement) { - appendSourceLink(sourceElement.getPsi(), options.sourceLinks) + appendSourceLink(sourceElement.getPsi(), passConfiguration.sourceLinks) } fun DocumentationNode.appendSignature(descriptor: DeclarationDescriptor) { @@ -360,7 +306,7 @@ class DocumentationBuilder } fun DocumentationNode.appendChild(descriptor: DeclarationDescriptor, kind: RefKind): DocumentationNode? { - if (!descriptor.isGenerated() && descriptor.isDocumented(options)) { + if (!descriptor.isGenerated() && descriptor.isDocumented(passConfiguration)) { val node = descriptor.build() append(node, kind) return node @@ -387,7 +333,7 @@ class DocumentationBuilder fun DocumentationNode.appendOrUpdateMember(descriptor: DeclarationDescriptor) { - if (descriptor.isGenerated() || !descriptor.isDocumented(options)) return + if (descriptor.isGenerated() || !descriptor.isDocumented(passConfiguration)) return val existingNode = refGraph.lookup(descriptor.signature()) if (existingNode != null) { @@ -459,10 +405,10 @@ class DocumentationBuilder val allFqNames = fragments.map { it.fqName }.distinct() for (packageName in allFqNames) { - if (packageName.isRoot && !options.includeRootPackage) continue + if (packageName.isRoot && !passConfiguration.includeRootPackage) continue val declarations = fragments.filter { it.fqName == packageName }.flatMap { it.getMemberScope().getContributedDescriptors() } - if (options.skipEmptyPackages && declarations.none { it.isDocumented(options) }) continue + if (passConfiguration.skipEmptyPackages && declarations.none { it.isDocumented(passConfiguration) }) continue logger.info(" package $packageName: ${declarations.count()} declarations") val packageNode = findOrCreatePackageNode(this, packageName.asString(), packageContent, this@DocumentationBuilder.refGraph) packageDocumentationBuilder.buildPackageDocumentation(this@DocumentationBuilder, packageName, packageNode, @@ -489,7 +435,7 @@ class DocumentationBuilder }.flatten() val allDescriptors = - if (options.collectInheritedExtensionsFromLibraries) { + if (passConfiguration.collectInheritedExtensionsFromLibraries) { allPackageViewDescriptors.map { it.memberScope } } else { fragments.asSequence().map { it.getMemberScope() } @@ -694,7 +640,7 @@ class DocumentationBuilder .mapTo(result) { ClassMember(it, extraModifier = "static") } val companionObjectDescriptor = companionObjectDescriptor - if (companionObjectDescriptor != null && companionObjectDescriptor.isDocumented(options)) { + if (companionObjectDescriptor != null && companionObjectDescriptor.isDocumented(passConfiguration)) { val descriptors = companionObjectDescriptor.defaultType.memberScope.getContributedDescriptors() val descriptorsToDocument = descriptors.filter { it !is CallableDescriptor || !it.isInheritedFromAny() } descriptorsToDocument.mapTo(result) { @@ -967,12 +913,12 @@ class DocumentationBuilder } -fun DeclarationDescriptor.isDocumented(options: DocumentationOptions): Boolean { - return (options.effectivePackageOptions(fqNameSafe).includeNonPublic +fun DeclarationDescriptor.isDocumented(passConfiguration: DokkaConfiguration.PassConfiguration): Boolean { + return (passConfiguration.effectivePackageOptions(fqNameSafe).includeNonPublic || this !is MemberDescriptor || this.visibility.isPublicAPI) - && !isDocumentationSuppressed(options) - && (!options.effectivePackageOptions(fqNameSafe).skipDeprecated || !isDeprecated()) + && !isDocumentationSuppressed(passConfiguration) + && (!passConfiguration.effectivePackageOptions(fqNameSafe).skipDeprecated || !isDeprecated()) } private fun DeclarationDescriptor.isGenerated() = this is CallableMemberDescriptor && kind != CallableMemberDescriptor.Kind.DECLARATION @@ -986,7 +932,7 @@ class KotlinPackageDocumentationBuilder : PackageDocumentationBuilder { val externalClassNodes = hashMapOf() declarations.forEach { descriptor -> with(documentationBuilder) { - if (descriptor.isDocumented(options)) { + if (descriptor.isDocumented(passConfiguration)) { val parent = packageNode.getParentForPackageMember(descriptor, externalClassNodes, allFqNames) parent.appendOrUpdateMember(descriptor) } @@ -998,14 +944,14 @@ class KotlinPackageDocumentationBuilder : PackageDocumentationBuilder { class KotlinJavaDocumentationBuilder @Inject constructor(val resolutionFacade: DokkaResolutionFacade, val documentationBuilder: DocumentationBuilder, - val options: DocumentationOptions, + val passConfiguration: DokkaConfiguration.PassConfiguration, val logger: DokkaLogger) : JavaDocumentationBuilder { override fun appendFile(file: PsiJavaFile, module: DocumentationModule, packageContent: Map) { val classDescriptors = file.classes.map { it.getJavaClassDescriptor(resolutionFacade) } - if (classDescriptors.any { it != null && it.isDocumented(options) }) { + if (classDescriptors.any { it != null && it.isDocumented(passConfiguration) }) { val packageNode = findOrCreatePackageNode(module, file.packageName, packageContent, documentationBuilder.refGraph) for (descriptor in classDescriptors.filterNotNull()) { @@ -1035,13 +981,13 @@ fun AnnotationDescriptor.mustBeDocumented(): Boolean { return annotationClass.isDocumentedAnnotation() } -fun DeclarationDescriptor.isDocumentationSuppressed(options: DocumentationOptions): Boolean { +fun DeclarationDescriptor.isDocumentationSuppressed(passConfiguration: DokkaConfiguration.PassConfiguration): Boolean { - if (options.effectivePackageOptions(fqNameSafe).suppress) return true + if (passConfiguration.effectivePackageOptions(fqNameSafe).suppress) return true val path = this.findPsi()?.containingFile?.virtualFile?.path if (path != null) { - if (File(path).absoluteFile in options.suppressedFiles) return true + if (path in passConfiguration.suppressedFiles) return true } val doc = findKDoc() @@ -1079,7 +1025,7 @@ fun DeclarationDescriptor.signature(): String { is TypeAliasDescriptor -> DescriptorUtils.getFqName(this).asString() is PropertyDescriptor -> containingDeclaration.signature() + "$" + name + receiverSignature() - is FunctionDescriptor -> containingDeclaration.signature() + "$" + name + parameterSignature() + ":" + returnType?.signature() + is FunctionDescriptor -> containingDeclaration.signature() + "$" + name + parameterSignature() + ":" + returnType?.signature() is ValueParameterDescriptor -> containingDeclaration.signature() + "/" + name is TypeParameterDescriptor -> containingDeclaration.signature() + "*" + name is ReceiverParameterDescriptor -> containingDeclaration.signature() + "/" + name @@ -1140,8 +1086,8 @@ fun DeclarationDescriptor.sourceLocation(): String? { return null } -fun DocumentationModule.prepareForGeneration(options: DocumentationOptions) { - if (options.generateIndexPages) { +fun DocumentationModule.prepareForGeneration(configuration: DokkaConfiguration) { + if (configuration.generateIndexPages) { generateAllTypesNode() } nodeRefGraph.resolveReferences() @@ -1167,4 +1113,12 @@ fun ClassDescriptor.supertypesWithAnyPrecise(): Collection { return emptyList() } return typeConstructor.supertypesWithAny() -} \ No newline at end of file +} + +fun PassConfiguration.effectivePackageOptions(pack: String): DokkaConfiguration.PackageOptions { + val rootPackageOptions = PackageOptionsImpl("", includeNonPublic, reportUndocumented, skipDeprecated) + return perPackageOptions.firstOrNull { pack == it.prefix || pack.startsWith(it.prefix + ".") } ?: rootPackageOptions +} + +fun PassConfiguration.effectivePackageOptions(pack: FqName): DokkaConfiguration.PackageOptions = effectivePackageOptions(pack.asString()) + diff --git a/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt b/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt index a8129793..2fc207b9 100644 --- a/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt +++ b/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt @@ -22,6 +22,7 @@ import java.net.HttpURLConnection import java.net.URL import java.net.URLConnection import java.nio.file.Path +import java.nio.file.Paths import java.security.MessageDigest import javax.inject.Named import kotlin.reflect.full.findAnnotation @@ -30,7 +31,8 @@ fun ByteArray.toHexString() = this.joinToString(separator = "") { "%02x".format( @Singleton class ExternalDocumentationLinkResolver @Inject constructor( - val options: DocumentationOptions, + val configuration: DokkaConfiguration, + val passConfiguration: DokkaConfiguration.PassConfiguration, @Named("libraryResolutionFacade") val libraryResolutionFacade: DokkaResolutionFacade, val logger: DokkaLogger ) { @@ -42,7 +44,12 @@ class ExternalDocumentationLinkResolver @Inject constructor( override fun toString(): String = rootUrl.toString() } - val cacheDir: Path? = options.cacheRoot?.resolve("packageListCache")?.apply { createDirectories() } + + val cacheDir: Path? = when { + configuration.cacheRoot == "default" -> Paths.get(System.getProperty("user.home"), ".cache", "dokka") + configuration.cacheRoot != null -> Paths.get(configuration.cacheRoot) + else -> null + }?.resolve("packageListCache")?.apply { createDirectories() } val cachedProtocols = setOf("http", "https", "ftp") @@ -157,7 +164,7 @@ class ExternalDocumentationLinkResolver @Inject constructor( } init { - options.externalDocumentationLinks.forEach { + passConfiguration.externalDocumentationLinks.forEach { try { loadPackageList(it) } catch (e: Exception) { diff --git a/core/src/main/kotlin/Kotlin/KotlinAsJavaDocumentationBuilder.kt b/core/src/main/kotlin/Kotlin/KotlinAsJavaDocumentationBuilder.kt index c7ed8292..be6dd2e1 100644 --- a/core/src/main/kotlin/Kotlin/KotlinAsJavaDocumentationBuilder.kt +++ b/core/src/main/kotlin/Kotlin/KotlinAsJavaDocumentationBuilder.kt @@ -28,7 +28,7 @@ class KotlinAsJavaDocumentationBuilder return } - val javaDocumentationBuilder = JavaPsiDocumentationBuilder(documentationBuilder.options, + val javaDocumentationBuilder = JavaPsiDocumentationBuilder(documentationBuilder.passConfiguration, documentationBuilder.refGraph, kotlinAsJavaDocumentationParser) diff --git a/core/src/main/kotlin/Samples/DefaultSampleProcessingService.kt b/core/src/main/kotlin/Samples/DefaultSampleProcessingService.kt index 116a5c02..f3f45c3f 100644 --- a/core/src/main/kotlin/Samples/DefaultSampleProcessingService.kt +++ b/core/src/main/kotlin/Samples/DefaultSampleProcessingService.kt @@ -20,7 +20,7 @@ import org.jetbrains.kotlin.resolve.scopes.ResolutionScope open class DefaultSampleProcessingService -@Inject constructor(val options: DocumentationOptions, +@Inject constructor(val configuration: DokkaConfiguration, val logger: DokkaLogger, val resolutionFacade: DokkaResolutionFacade) : SampleProcessingService { diff --git a/core/src/main/kotlin/Samples/KotlinWebsiteSampleProcessingService.kt b/core/src/main/kotlin/Samples/KotlinWebsiteSampleProcessingService.kt index b0988c35..b5801457 100644 --- a/core/src/main/kotlin/Samples/KotlinWebsiteSampleProcessingService.kt +++ b/core/src/main/kotlin/Samples/KotlinWebsiteSampleProcessingService.kt @@ -12,10 +12,10 @@ import org.jetbrains.kotlin.psi.psiUtil.prevLeaf import org.jetbrains.kotlin.resolve.ImportPath open class KotlinWebsiteSampleProcessingService -@Inject constructor(options: DocumentationOptions, +@Inject constructor(dokkaConfiguration: DokkaConfiguration, logger: DokkaLogger, resolutionFacade: DokkaResolutionFacade) - : DefaultSampleProcessingService(options, logger, resolutionFacade) { + : DefaultSampleProcessingService(dokkaConfiguration, logger, resolutionFacade) { private class SampleBuilder : KtTreeVisitorVoid() { val builder = StringBuilder() diff --git a/core/src/main/kotlin/Utilities/DokkaModules.kt b/core/src/main/kotlin/Utilities/DokkaModules.kt index 732cbc48..251d5c23 100644 --- a/core/src/main/kotlin/Utilities/DokkaModules.kt +++ b/core/src/main/kotlin/Utilities/DokkaModules.kt @@ -14,9 +14,10 @@ import kotlin.reflect.KClass const val impliedPlatformsName = "impliedPlatforms" class DokkaAnalysisModule(val environment: AnalysisEnvironment, - val options: DocumentationOptions, + val configuration: DokkaConfiguration, val defaultPlatformsProvider: DefaultPlatformsProvider, val nodeReferenceGraph: NodeReferenceGraph, + val passConfiguration: DokkaConfiguration.PassConfiguration, val logger: DokkaLogger) : Module { override fun configure(binder: Binder) { binder.bind().toInstance(logger) @@ -28,29 +29,30 @@ class DokkaAnalysisModule(val environment: AnalysisEnvironment, binder.bind().toInstance(dokkaResolutionFacade) binder.bind().annotatedWith(Names.named("libraryResolutionFacade")).toInstance(libraryResolutionFacade) - binder.bind().toInstance(options) + binder.bind().toInstance(configuration) + binder.bind().toInstance(passConfiguration) binder.bind().toInstance(defaultPlatformsProvider) binder.bind().toInstance(nodeReferenceGraph) - val descriptor = ServiceLocator.lookup("format", options.outputFormat) + val descriptor = ServiceLocator.lookup("format", configuration.format) descriptor.configureAnalysis(binder) } } object StringListType : TypeLiteral<@JvmSuppressWildcards List>() -class DokkaOutputModule(val options: DocumentationOptions, +class DokkaOutputModule(val configuration: DokkaConfiguration, val logger: DokkaLogger) : Module { override fun configure(binder: Binder) { - binder.bind(File::class.java).annotatedWith(Names.named("outputDir")).toInstance(File(options.outputDir)) + binder.bind(File::class.java).annotatedWith(Names.named("outputDir")).toInstance(File(configuration.outputDir)) - binder.bind().toInstance(options) + binder.bind().toInstance(configuration) binder.bind().toInstance(logger) - binder.bind(StringListType).annotatedWith(Names.named(impliedPlatformsName)).toInstance(options.impliedPlatforms) + binder.bind(StringListType).annotatedWith(Names.named(impliedPlatformsName)).toInstance(configuration.impliedPlatforms) - val descriptor = ServiceLocator.lookup("format", options.outputFormat) + val descriptor = ServiceLocator.lookup("format", configuration.format) descriptor.configureOutput(binder) } diff --git a/core/src/main/kotlin/javadoc/dokka-adapters.kt b/core/src/main/kotlin/javadoc/dokka-adapters.kt index 483fb3cd..1329876a 100644 --- a/core/src/main/kotlin/javadoc/dokka-adapters.kt +++ b/core/src/main/kotlin/javadoc/dokka-adapters.kt @@ -4,16 +4,19 @@ import com.google.inject.Binder import com.google.inject.Inject import com.sun.tools.doclets.formats.html.HtmlDoclet import org.jetbrains.dokka.* -import org.jetbrains.dokka.Formats.* +import org.jetbrains.dokka.Formats.DefaultAnalysisComponent +import org.jetbrains.dokka.Formats.DefaultAnalysisComponentServices +import org.jetbrains.dokka.Formats.FormatDescriptor +import org.jetbrains.dokka.Formats.KotlinAsJava import org.jetbrains.dokka.Utilities.bind import org.jetbrains.dokka.Utilities.toType -class JavadocGenerator @Inject constructor(val options: DocumentationOptions, val logger: DokkaLogger) : Generator { +class JavadocGenerator @Inject constructor(val configuration: DokkaConfiguration, val logger: DokkaLogger) : Generator { override fun buildPages(nodes: Iterable) { val module = nodes.single() as DocumentationModule - HtmlDoclet.start(ModuleNodeAdapter(module, StandardReporter(logger), options.outputDir)) + HtmlDoclet.start(ModuleNodeAdapter(module, StandardReporter(logger), configuration.outputDir)) } override fun buildOutlines(nodes: Iterable) { diff --git a/core/src/test/kotlin/TestAPI.kt b/core/src/test/kotlin/TestAPI.kt index 4a755130..b65efbe9 100644 --- a/core/src/test/kotlin/TestAPI.kt +++ b/core/src/test/kotlin/TestAPI.kt @@ -35,31 +35,35 @@ fun verifyModel(modelConfig: ModelConfig, verifier: (DocumentationModule) -> Unit) { val documentation = DocumentationModule("test") - val options = DocumentationOptions( - "", - modelConfig.format, - includeNonPublic = modelConfig.includeNonPublic, - skipEmptyPackages = false, - includeRootPackage = true, - sourceLinks = listOf(), - perPackageOptions = modelConfig.perPackageOptions, - generateIndexPages = false, - noStdlibLink = modelConfig.noStdlibLink, - noJdkLink = false, - cacheRoot = "default", - languageVersion = null, - apiVersion = null, - collectInheritedExtensionsFromLibraries = modelConfig.collectInheritedExtensionsFromLibraries + val passConfiguration = PassConfigurationImpl ( + includeNonPublic = modelConfig.includeNonPublic, + skipEmptyPackages = false, + includeRootPackage = true, + sourceLinks = listOf(), + perPackageOptions = modelConfig.perPackageOptions, + noStdlibLink = modelConfig.noStdlibLink, + noJdkLink = false, + languageVersion = null, + apiVersion = null, + collectInheritedExtensionsFromLibraries = modelConfig.collectInheritedExtensionsFromLibraries + ) + val configuration = DokkaConfigurationImpl( + outputDir = "", + format = modelConfig.format, + generateIndexPages = false, + cacheRoot = "default", + passesConfigurations = listOf(passConfiguration) ) - appendDocumentation(documentation, options, modelConfig) - documentation.prepareForGeneration(options) + appendDocumentation(documentation, configuration, passConfiguration, modelConfig) + documentation.prepareForGeneration(configuration) verifier(documentation) } fun appendDocumentation(documentation: DocumentationModule, - options: DocumentationOptions, + dokkaConfiguration: DokkaConfiguration, + passConfiguration: DokkaConfiguration.PassConfiguration, modelConfig: ModelConfig ) { val messageCollector = object : MessageCollector { @@ -108,13 +112,13 @@ fun appendDocumentation(documentation: DocumentationModule, } addRoots(modelConfig.roots.toList()) - loadLanguageVersionSettings(options.languageVersion, options.apiVersion) + loadLanguageVersionSettings(passConfiguration.languageVersion, passConfiguration.apiVersion) } val defaultPlatformsProvider = object : DefaultPlatformsProvider { override fun getDefaultPlatforms(descriptor: DeclarationDescriptor) = modelConfig.defaultPlatforms } val injector = Guice.createInjector( - DokkaAnalysisModule(environment, options, defaultPlatformsProvider, documentation.nodeRefGraph, DokkaConsoleLogger)) + DokkaAnalysisModule(environment, dokkaConfiguration, defaultPlatformsProvider, documentation.nodeRefGraph, passConfiguration, DokkaConsoleLogger)) buildDocumentationModule(injector, documentation) Disposer.dispose(environment) } diff --git a/core/src/test/kotlin/format/KotlinWebSiteFormatTest.kt b/core/src/test/kotlin/format/KotlinWebSiteFormatTest.kt index 643b5b2d..4f292e37 100644 --- a/core/src/test/kotlin/format/KotlinWebSiteFormatTest.kt +++ b/core/src/test/kotlin/format/KotlinWebSiteFormatTest.kt @@ -48,17 +48,20 @@ class KotlinWebSiteFormatTest: FileGeneratorTestCase() { private fun buildMultiplePlatforms(path: String): DocumentationModule { val module = DocumentationModule("test") - val options = DocumentationOptions( - outputDir = "", - outputFormat = "html", - generateIndexPages = false, - noStdlibLink = true, + val passConfiguration = PassConfigurationImpl(noStdlibLink = true, noJdkLink = true, languageVersion = null, apiVersion = null ) + val configuration = DokkaConfigurationImpl( + outputDir = "", + format = "html", + generateIndexPages = false, + passesConfigurations = listOf(passConfiguration) + ) + appendDocumentation( - module, options, ModelConfig( + module, configuration, passConfiguration, ModelConfig( roots = arrayOf(contentRootFromPath("testdata/format/website/$path/jvm.kt")), defaultPlatforms = listOf("JVM") ) @@ -67,13 +70,13 @@ class KotlinWebSiteFormatTest: FileGeneratorTestCase() { appendDocumentation( - module, options, ModelConfig( + module, configuration, passConfiguration, ModelConfig( roots = arrayOf(contentRootFromPath("testdata/format/website/$path/jre7.kt")), defaultPlatforms = listOf("JVM", "JRE7") ) ) appendDocumentation( - module, options, ModelConfig( + module, configuration, passConfiguration, ModelConfig( roots = arrayOf(contentRootFromPath("testdata/format/website/$path/js.kt")), defaultPlatforms = listOf("JS") ) diff --git a/core/src/test/kotlin/format/KotlinWebSiteHtmlFormatTest.kt b/core/src/test/kotlin/format/KotlinWebSiteHtmlFormatTest.kt index 3ae0930e..1901154f 100644 --- a/core/src/test/kotlin/format/KotlinWebSiteHtmlFormatTest.kt +++ b/core/src/test/kotlin/format/KotlinWebSiteHtmlFormatTest.kt @@ -64,29 +64,37 @@ abstract class BaseKotlinWebSiteHtmlFormatTest(val analysisPlatform: Platform): private fun buildMultiplePlatforms(path: String): DocumentationModule { val module = DocumentationModule("test") - val options = DocumentationOptions( - outputDir = "", - outputFormat = "kotlin-website-html", - generateIndexPages = false, + val passConfiguration = PassConfigurationImpl( noStdlibLink = true, noJdkLink = true, languageVersion = null, apiVersion = null ) + + val dokkaConfiguration = DokkaConfigurationImpl( + outputDir = "", + format = "kotlin-website-html", + generateIndexPages = false, + passesConfigurations = listOf( + passConfiguration + ) + + ) + appendDocumentation( - module, options, ModelConfig( + module, dokkaConfiguration, passConfiguration, ModelConfig( roots = arrayOf(contentRootFromPath("testdata/format/website-html/$path/jvm.kt")), defaultPlatforms = listOf("JVM") ) ) appendDocumentation( - module, options, ModelConfig( + module, dokkaConfiguration, passConfiguration, ModelConfig( roots = arrayOf(contentRootFromPath("testdata/format/website-html/$path/jre7.kt")), defaultPlatforms = listOf("JVM", "JRE7") ) ) appendDocumentation( - module, options, ModelConfig( + module, dokkaConfiguration, passConfiguration, ModelConfig( roots = arrayOf(contentRootFromPath("testdata/format/website-html/$path/js.kt")), defaultPlatforms = listOf("JS") ) diff --git a/core/src/test/kotlin/format/MarkdownFormatTest.kt b/core/src/test/kotlin/format/MarkdownFormatTest.kt index 4de70751..29d2d20f 100644 --- a/core/src/test/kotlin/format/MarkdownFormatTest.kt +++ b/core/src/test/kotlin/format/MarkdownFormatTest.kt @@ -1,7 +1,6 @@ package org.jetbrains.dokka.tests import org.jetbrains.dokka.* -import org.junit.Before import org.junit.Test abstract class BaseMarkdownFormatTest(val analysisPlatform: Platform): FileGeneratorTestCase() { @@ -249,16 +248,23 @@ abstract class BaseMarkdownFormatTest(val analysisPlatform: Platform): FileGener @Test fun packagePlatformsWithExtExtensions() { val path = "multiplatform/packagePlatformsWithExtExtensions" val module = DocumentationModule("test") - val options = DocumentationOptions( - outputDir = "", - outputFormat = "html", - generateIndexPages = false, + val passConfiguration = PassConfigurationImpl( noStdlibLink = true, noJdkLink = true, languageVersion = null, apiVersion = null ) - appendDocumentation(module, options, ModelConfig( + + val dokkaConfiguration = DokkaConfigurationImpl( + outputDir = "", + format = "html", + generateIndexPages = false, + passesConfigurations = listOf( + passConfiguration + ) + ) + + appendDocumentation(module, dokkaConfiguration, passConfiguration, ModelConfig( roots = arrayOf(contentRootFromPath("testdata/format/$path/jvm.kt")), defaultPlatforms = listOf("JVM"), withKotlinRuntime = true, @@ -373,24 +379,30 @@ abstract class BaseMarkdownFormatTest(val analysisPlatform: Platform): FileGener private fun buildMultiplePlatforms(path: String): DocumentationModule { val module = DocumentationModule("test") - val options = DocumentationOptions( - outputDir = "", - outputFormat = "html", - generateIndexPages = false, + val passConfiguration = PassConfigurationImpl( noStdlibLink = true, noJdkLink = true, languageVersion = null, apiVersion = null ) + val dokkaConfiguration = DokkaConfigurationImpl( + outputDir = "", + format = "html", + generateIndexPages = false, + passesConfigurations = listOf( + passConfiguration + ) + + ) appendDocumentation( - module, options, ModelConfig( + module, dokkaConfiguration, passConfiguration, ModelConfig( roots = arrayOf(contentRootFromPath("testdata/format/$path/jvm.kt")), defaultPlatforms = listOf("JVM"), analysisPlatform = Platform.jvm ) ) appendDocumentation( - module, options, ModelConfig( + module, dokkaConfiguration, passConfiguration, ModelConfig( roots = arrayOf(contentRootFromPath("testdata/format/$path/js.kt")), defaultPlatforms = listOf("JS"), analysisPlatform = Platform.js diff --git a/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt b/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt index 287b628a..e0fa27d1 100644 --- a/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt +++ b/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt @@ -39,31 +39,37 @@ enum class Platform(val key: String) { } interface DokkaConfiguration { - val moduleName: String - val classpath: List - val sourceRoots: List - val samples: List - val includes: List val outputDir: String val format: String - val includeNonPublic: Boolean - val includeRootPackage: Boolean - val reportUndocumented: Boolean - val skipEmptyPackages: Boolean - val skipDeprecated: Boolean - val jdkVersion: Int val generateIndexPages: Boolean - val sourceLinks: List - val impliedPlatforms: List - val perPackageOptions: List - val externalDocumentationLinks: List - val languageVersion: String? - val apiVersion: String? - val noStdlibLink: Boolean - val noJdkLink: Boolean val cacheRoot: String? - val suppressedFiles: List - val collectInheritedExtensionsFromLibraries: Boolean + val passesConfigurations: List + val impliedPlatforms: List + + interface PassConfiguration { + val moduleName: String + val classpath: List + val sourceRoots: List + val samples: List + val includes: List + val includeNonPublic: Boolean + val includeRootPackage: Boolean + val reportUndocumented: Boolean + val skipEmptyPackages: Boolean + val skipDeprecated: Boolean + val jdkVersion: Int + val sourceLinks: List + val perPackageOptions: List + val externalDocumentationLinks: List + val languageVersion: String? + val apiVersion: String? + val noStdlibLink: Boolean + val noJdkLink: Boolean + val suppressedFiles: List + val collectInheritedExtensionsFromLibraries: Boolean + val analysisPlatform: Platform + val targets: List + } interface SourceRoot { val path: String @@ -106,31 +112,12 @@ interface DokkaConfiguration { } data class SerializeOnlyDokkaConfiguration( - override val moduleName: String, - override val classpath: List, - override val sourceRoots: List, - override val samples: List, - override val includes: List, override val outputDir: String, override val format: String, - override val includeNonPublic: Boolean, - override val includeRootPackage: Boolean, - override val reportUndocumented: Boolean, - override val skipEmptyPackages: Boolean, - override val skipDeprecated: Boolean, - override val jdkVersion: Int, override val generateIndexPages: Boolean, - override val sourceLinks: List, - override val impliedPlatforms: List, - override val perPackageOptions: List, - override val externalDocumentationLinks: List, - override val noStdlibLink: Boolean, - override val noJdkLink: Boolean, override val cacheRoot: String?, - override val suppressedFiles: List, - override val languageVersion: String?, - override val apiVersion: String?, - override val collectInheritedExtensionsFromLibraries: Boolean + override val impliedPlatforms: List, + override val passesConfigurations: List ) : DokkaConfiguration diff --git a/runners/ant/src/main/kotlin/ant/dokka.kt b/runners/ant/src/main/kotlin/ant/dokka.kt index 0b1ccc13..4f629198 100644 --- a/runners/ant/src/main/kotlin/ant/dokka.kt +++ b/runners/ant/src/main/kotlin/ant/dokka.kt @@ -116,29 +116,34 @@ class DokkaAntTask: Task() { SourceLinkDefinitionImpl(File(path).canonicalFile.absolutePath, url, it.lineSuffix) } - val generator = DokkaGenerator( - AntLogger(this), - compileClasspath.list().toList(), - sourcePath.list().map { SourceRootImpl(it) } + antSourceRoots.mapNotNull { it.toSourceRoot() }, - samplesPath.list().toList(), - includesPath.list().toList(), - moduleName!!, - DocumentationOptions( - outputDir!!, - outputFormat, - skipDeprecated = skipDeprecated, - sourceLinks = sourceLinks, - jdkVersion = jdkVersion, - impliedPlatforms = impliedPlatforms.split(','), - perPackageOptions = antPackageOptions, - externalDocumentationLinks = antExternalDocumentationLinks.map { it.build() }, - noStdlibLink = noStdlibLink, - noJdkLink = noJdkLink, - cacheRoot = cacheRoot, - languageVersion = languageVersion, - apiVersion = apiVersion - ) + val passConfiguration = PassConfigurationImpl( + classpath = compileClasspath.list().toList(), + sourceRoots = sourcePath.list().map { SourceRootImpl(it) } + antSourceRoots.mapNotNull { it.toSourceRoot() }, + samples = samplesPath.list().toList(), + includes = includesPath.list().toList(), + moduleName = moduleName!!, + skipDeprecated = skipDeprecated, + sourceLinks = sourceLinks, + jdkVersion = jdkVersion, + perPackageOptions = antPackageOptions, + externalDocumentationLinks = antExternalDocumentationLinks.map { it.build() }, + noStdlibLink = noStdlibLink, + noJdkLink = noJdkLink, + languageVersion = languageVersion, + apiVersion = apiVersion ) + + val configuration = DokkaConfigurationImpl( + outputDir = outputDir!!, + format = outputFormat, + impliedPlatforms = impliedPlatforms.split(','), + cacheRoot = cacheRoot, + passesConfigurations = listOf( + passConfiguration + ) + ) + + val generator = DokkaGenerator(configuration, AntLogger(this)) generator.generate() } } \ No newline at end of file diff --git a/runners/cli/src/main/kotlin/cli/main.kt b/runners/cli/src/main/kotlin/cli/main.kt index f871f406..330de5e1 100644 --- a/runners/cli/src/main/kotlin/cli/main.kt +++ b/runners/cli/src/main/kotlin/cli/main.kt @@ -44,7 +44,7 @@ class DokkaArguments { @set:Argument(value = "impliedPlatforms", description = "List of implied platforms (comma-separated)") var impliedPlatforms: String = "" - @set:Argument(value = "packageOptions", description = "List of package options in format \"prefix,-deprecated,-privateApi,+warnUndocumented,+suppress;...\" ") + @set:Argument(value = "packageOptions", description = "List of package passConfiguration in format \"prefix,-deprecated,-privateApi,+warnUndocumented,+suppress;...\" ") var packageOptions: String = "" @set:Argument(value = "links", description = "External documentation links in format url^packageListUrl^^url2...") @@ -111,31 +111,37 @@ object MainKt { val classPath = arguments.classpath.split(File.pathSeparatorChar).toList() - val documentationOptions = DocumentationOptions( - arguments.outputDir.let { if (it.endsWith('/')) it else it + '/' }, - arguments.outputFormat, + val passConfig = PassConfigurationImpl( skipDeprecated = arguments.nodeprecated, sourceLinks = sourceLinks, - impliedPlatforms = arguments.impliedPlatforms.split(','), perPackageOptions = parsePerPackageOptions(arguments.packageOptions), jdkVersion = arguments.jdkVersion, externalDocumentationLinks = parseLinks(arguments.links), noStdlibLink = arguments.noStdlibLink, - cacheRoot = arguments.cacheRoot, languageVersion = arguments.languageVersion, apiVersion = arguments.apiVersion, collectInheritedExtensionsFromLibraries = arguments.collectInheritedExtensionsFromLibraries, - noJdkLink = arguments.noJdkLink + noJdkLink = arguments.noJdkLink, + sourceRoots = sources.map(SourceRootImpl.Companion::parseSourceRoot), + analysisPlatform = sources.map (SourceRootImpl.Companion::parseSourceRoot).single().analysisPlatform, + samples = samples, + includes = includes, + moduleName = arguments.moduleName, + classpath = classPath + ) + + val config = DokkaConfigurationImpl( + outputDir = arguments.outputDir.let { if (it.endsWith('/')) it else it + '/' }, + format = arguments.outputFormat, + impliedPlatforms = arguments.impliedPlatforms.split(','), + cacheRoot = arguments.cacheRoot, + + passesConfigurations = listOf( + passConfig + ) ) - val generator = DokkaGenerator( - DokkaConsoleLogger, - classPath, - sources.map(SourceRootImpl.Companion::parseSourceRoot), - samples, - includes, - arguments.moduleName, - documentationOptions) + val generator = DokkaGenerator(config, DokkaConsoleLogger) generator.generate() DokkaConsoleLogger.report() diff --git a/runners/maven-plugin/src/main/kotlin/DokkaMojo.kt b/runners/maven-plugin/src/main/kotlin/DokkaMojo.kt index ea55c8fe..78fd2d86 100644 --- a/runners/maven-plugin/src/main/kotlin/DokkaMojo.kt +++ b/runners/maven-plugin/src/main/kotlin/DokkaMojo.kt @@ -129,30 +129,33 @@ abstract class AbstractDokkaMojo : AbstractMojo() { return } - val gen = DokkaGenerator( - MavenDokkaLogger(log), - classpath, - sourceDirectories.map { SourceRootImpl(it) } + sourceRoots, - samplesDirs, - includeDirs + includes, - moduleName, - DocumentationOptions(getOutDir(), getOutFormat(), - sourceLinks = sourceLinks.map { SourceLinkDefinitionImpl(it.dir, it.url, it.urlSuffix) }, - jdkVersion = jdkVersion, - skipDeprecated = skipDeprecated, - skipEmptyPackages = skipEmptyPackages, - reportUndocumented = reportNotDocumented, - impliedPlatforms = impliedPlatforms, - perPackageOptions = perPackageOptions, - externalDocumentationLinks = externalDocumentationLinks.map { it.build() }, - noStdlibLink = noStdlibLink, - noJdkLink = noJdkLink, - cacheRoot = cacheRoot, - languageVersion = languageVersion, - apiVersion = apiVersion - ) + val passConfiguration = PassConfigurationImpl( + sourceLinks = sourceLinks.map { SourceLinkDefinitionImpl(it.dir, it.url, it.urlSuffix) }, + jdkVersion = jdkVersion, + skipDeprecated = skipDeprecated, + skipEmptyPackages = skipEmptyPackages, + reportUndocumented = reportNotDocumented, + perPackageOptions = perPackageOptions, + externalDocumentationLinks = externalDocumentationLinks.map { it.build() }, + noStdlibLink = noStdlibLink, + noJdkLink = noJdkLink, + languageVersion = languageVersion, + apiVersion = apiVersion + + ) + + val configuration = DokkaConfigurationImpl( + outputDir = getOutDir(), + format = getOutFormat(), + impliedPlatforms = impliedPlatforms, + cacheRoot = cacheRoot, + passesConfigurations = listOf( + passConfiguration + ) ) + val gen = DokkaGenerator(configuration, MavenDokkaLogger(log)) + gen.generate() } } -- cgit From ba09711a1ecbdaede86cab9e76d13ff1047f89b2 Mon Sep 17 00:00:00 2001 From: aleksZubakov Date: Thu, 2 Aug 2018 18:59:20 +0300 Subject: ExternalDocumentationLinkResolver refactoring, extract common dependencies from guice modules --- core/src/main/kotlin/Generation/DokkaGenerator.kt | 11 +- .../Kotlin/ExternalDocumentationLinkResolver.kt | 114 ++++++++++++++------- core/src/main/kotlin/Utilities/DokkaModules.kt | 19 ++-- core/src/test/kotlin/TestAPI.kt | 19 +++- 4 files changed, 112 insertions(+), 51 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Generation/DokkaGenerator.kt b/core/src/main/kotlin/Generation/DokkaGenerator.kt index 2e46d908..22d1519f 100644 --- a/core/src/main/kotlin/Generation/DokkaGenerator.kt +++ b/core/src/main/kotlin/Generation/DokkaGenerator.kt @@ -9,6 +9,7 @@ import com.intellij.psi.PsiJavaFile import com.intellij.psi.PsiManager import org.jetbrains.dokka.Utilities.DokkaAnalysisModule import org.jetbrains.dokka.Utilities.DokkaOutputModule +import org.jetbrains.dokka.Utilities.DokkaRunModule import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity import org.jetbrains.kotlin.cli.common.messages.MessageCollector @@ -27,6 +28,7 @@ class DokkaGenerator(val dokkaConfiguration: DokkaConfiguration, val logger: DokkaLogger) { private val documentationModules: MutableList = mutableListOf() + private val globalInjector = Guice.createInjector(DokkaRunModule(dokkaConfiguration)) fun generate() = with(dokkaConfiguration) { @@ -43,8 +45,9 @@ class DokkaGenerator(val dokkaConfiguration: DokkaConfiguration, val timeBuild = measureTimeMillis { logger.info("Generating pages... ") - val outputInjector = Guice.createInjector(DokkaOutputModule(dokkaConfiguration, logger)) - outputInjector.getInstance(Generator::class.java).buildAll(totalDocumentationModule) + val outputInjector = globalInjector.createChildInjector(DokkaOutputModule(dokkaConfiguration, logger)) + val instance = outputInjector.getInstance(Generator::class.java) + instance.buildAll(totalDocumentationModule) } logger.info("done in ${timeBuild / 1000} secs") } @@ -75,11 +78,11 @@ class DokkaGenerator(val dokkaConfiguration: DokkaConfiguration, } } - val injector = Guice.createInjector( + val injector = globalInjector.createChildInjector( DokkaAnalysisModule(environment, dokkaConfiguration, defaultPlatformsProvider, documentationModule.nodeRefGraph, passConfiguration, logger)) buildDocumentationModule(injector, documentationModule, { isNotSample(it, passConfiguration.samples) }, includes) - documentationModule.nodeRefGraph.nodeMapView.forEach { (_, node) -> + documentationModule.nodeRefGraph.nodeMapView.forEach { (_, node) -> // FIXME: change to full graph visiting node.addReferenceTo( DocumentationNode(analysisPlatform.key, Content.Empty, NodeKind.Platform), RefKind.Platform diff --git a/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt b/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt index 2fc207b9..9d986aee 100644 --- a/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt +++ b/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt @@ -29,21 +29,14 @@ import kotlin.reflect.full.findAnnotation fun ByteArray.toHexString() = this.joinToString(separator = "") { "%02x".format(it) } +typealias PackageFqNameToLocation = MutableMap + @Singleton -class ExternalDocumentationLinkResolver @Inject constructor( - val configuration: DokkaConfiguration, - val passConfiguration: DokkaConfiguration.PassConfiguration, - @Named("libraryResolutionFacade") val libraryResolutionFacade: DokkaResolutionFacade, - val logger: DokkaLogger +class PackageListProvider @Inject constructor( + val configuration: DokkaConfiguration, + val logger: DokkaLogger ) { - - val packageFqNameToLocation = mutableMapOf() - val formats = mutableMapOf() - - class ExternalDocumentationRoot(val rootUrl: URL, val resolver: InboundExternalLinkResolutionService, val locations: Map) { - override fun toString(): String = rootUrl.toString() - } - + val storage = mutableMapOf() val cacheDir: Path? = when { configuration.cacheRoot == "default" -> Paths.get(System.getProperty("user.home"), ".cache", "dokka") @@ -53,6 +46,25 @@ class ExternalDocumentationLinkResolver @Inject constructor( val cachedProtocols = setOf("http", "https", "ftp") + init { + for (conf in configuration.passesConfigurations) { + for (link in conf.externalDocumentationLinks) { + if (link in storage) { + continue + } + + try { + loadPackageList(link) + } catch (e: Exception) { + throw RuntimeException("Exception while loading package-list from $link", e) + } + } + + } + } + + + fun URL.doOpenConnectionToReadContent(timeout: Int = 10000, redirectsAllowed: Int = 16): URLConnection { val connection = this.openConnection() connection.connectTimeout = timeout @@ -127,23 +139,23 @@ class ExternalDocumentationLinkResolver @Inject constructor( val (params, packages) = packageListStream - .bufferedReader() - .useLines { lines -> lines.partition { it.startsWith(DOKKA_PARAM_PREFIX) } } + .bufferedReader() + .useLines { lines -> lines.partition { it.startsWith(ExternalDocumentationLinkResolver.DOKKA_PARAM_PREFIX) } } val paramsMap = params.asSequence() - .map { it.removePrefix(DOKKA_PARAM_PREFIX).split(":", limit = 2) } - .groupBy({ (key, _) -> key }, { (_, value) -> value }) + .map { it.removePrefix(ExternalDocumentationLinkResolver.DOKKA_PARAM_PREFIX).split(":", limit = 2) } + .groupBy({ (key, _) -> key }, { (_, value) -> value }) val format = paramsMap["format"]?.singleOrNull() ?: "javadoc" val locations = paramsMap["location"].orEmpty() - .map { it.split("\u001f", limit = 2) } - .map { (key, value) -> key to value } - .toMap() + .map { it.split("\u001f", limit = 2) } + .map { (key, value) -> key to value } + .toMap() - val defaultResolverDesc = services["dokka-default"]!! - val resolverDesc = services[format] + val defaultResolverDesc = ExternalDocumentationLinkResolver.services["dokka-default"]!! + val resolverDesc = ExternalDocumentationLinkResolver.services[format] ?: defaultResolverDesc.takeIf { format in formatsWithDefaultResolver } ?: defaultResolverDesc.also { logger.warn("Couldn't find InboundExternalLinkResolutionService(format = `$format`) for $link, using Dokka default") @@ -160,16 +172,52 @@ class ExternalDocumentationLinkResolver @Inject constructor( val rootInfo = ExternalDocumentationRoot(link.url, resolver, locations) - packages.map { FqName(it) }.forEach { packageFqNameToLocation[it] = rootInfo } + val packageFqNameToLocation = mutableMapOf() + storage[link] = packageFqNameToLocation + + val fqNames = packages.map { FqName(it) } + for(name in fqNames) { + packageFqNameToLocation[name] = rootInfo + } + } + + + + class ExternalDocumentationRoot(val rootUrl: URL, val resolver: InboundExternalLinkResolutionService, val locations: Map) { + override fun toString(): String = rootUrl.toString() } + companion object { + private val formatsWithDefaultResolver = + ServiceLocator + .allServices("format") + .filter { + val desc = ServiceLocator.lookup(it) as? FileGeneratorBasedFormatDescriptor + desc?.generatorServiceClass == FileGenerator::class + }.map { it.name } + .toSet() + + } + +} + +class ExternalDocumentationLinkResolver @Inject constructor( + val configuration: DokkaConfiguration, + val passConfiguration: DokkaConfiguration.PassConfiguration, + @Named("libraryResolutionFacade") val libraryResolutionFacade: DokkaResolutionFacade, + val logger: DokkaLogger, + val packageListProvider: PackageListProvider +) { + + val formats = mutableMapOf() + val packageFqNameToLocation = mutableMapOf() + init { - passConfiguration.externalDocumentationLinks.forEach { - try { - loadPackageList(it) - } catch (e: Exception) { - throw RuntimeException("Exception while loading package-list from $it", e) - } + val fqNameToLocationMaps = passConfiguration.externalDocumentationLinks + .mapNotNull { packageListProvider.storage[it] } + + for(map in fqNameToLocationMaps) { + packageFqNameToLocation.putAll(map) } } @@ -198,14 +246,6 @@ class ExternalDocumentationLinkResolver @Inject constructor( companion object { const val DOKKA_PARAM_PREFIX = "\$dokka." val services = ServiceLocator.allServices("inbound-link-resolver").associateBy { it.name } - private val formatsWithDefaultResolver = - ServiceLocator - .allServices("format") - .filter { - val desc = ServiceLocator.lookup(it) as? FileGeneratorBasedFormatDescriptor - desc?.generatorServiceClass == FileGenerator::class - }.map { it.name } - .toSet() } } diff --git a/core/src/main/kotlin/Utilities/DokkaModules.kt b/core/src/main/kotlin/Utilities/DokkaModules.kt index 251d5c23..c2e652b6 100644 --- a/core/src/main/kotlin/Utilities/DokkaModules.kt +++ b/core/src/main/kotlin/Utilities/DokkaModules.kt @@ -1,8 +1,6 @@ package org.jetbrains.dokka.Utilities -import com.google.inject.Binder -import com.google.inject.Module -import com.google.inject.TypeLiteral +import com.google.inject.* import com.google.inject.binder.AnnotatedBindingBuilder import com.google.inject.name.Names import org.jetbrains.dokka.* @@ -13,6 +11,16 @@ import kotlin.reflect.KClass const val impliedPlatformsName = "impliedPlatforms" +class DokkaRunModule(val configuration: DokkaConfiguration) : Module { + override fun configure(binder: Binder) { + binder.bind().toInstance(configuration) + binder.bind(StringListType).annotatedWith(Names.named(impliedPlatformsName)).toInstance(configuration.impliedPlatforms) + + binder.bind(File::class.java).annotatedWith(Names.named("outputDir")).toInstance(File(configuration.outputDir)) + } + +} + class DokkaAnalysisModule(val environment: AnalysisEnvironment, val configuration: DokkaConfiguration, val defaultPlatformsProvider: DefaultPlatformsProvider, @@ -29,7 +37,6 @@ class DokkaAnalysisModule(val environment: AnalysisEnvironment, binder.bind().toInstance(dokkaResolutionFacade) binder.bind().annotatedWith(Names.named("libraryResolutionFacade")).toInstance(libraryResolutionFacade) - binder.bind().toInstance(configuration) binder.bind().toInstance(passConfiguration) binder.bind().toInstance(defaultPlatformsProvider) @@ -46,11 +53,7 @@ object StringListType : TypeLiteral<@JvmSuppressWildcards List>() class DokkaOutputModule(val configuration: DokkaConfiguration, val logger: DokkaLogger) : Module { override fun configure(binder: Binder) { - binder.bind(File::class.java).annotatedWith(Names.named("outputDir")).toInstance(File(configuration.outputDir)) - - binder.bind().toInstance(configuration) binder.bind().toInstance(logger) - binder.bind(StringListType).annotatedWith(Names.named(impliedPlatformsName)).toInstance(configuration.impliedPlatforms) val descriptor = ServiceLocator.lookup("format", configuration.format) diff --git a/core/src/test/kotlin/TestAPI.kt b/core/src/test/kotlin/TestAPI.kt index b65efbe9..8974bd0b 100644 --- a/core/src/test/kotlin/TestAPI.kt +++ b/core/src/test/kotlin/TestAPI.kt @@ -7,6 +7,7 @@ import com.intellij.openapi.util.io.FileUtil import com.intellij.rt.execution.junit.FileComparisonFailure import org.jetbrains.dokka.* import org.jetbrains.dokka.Utilities.DokkaAnalysisModule +import org.jetbrains.dokka.Utilities.DokkaRunModule import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity import org.jetbrains.kotlin.cli.common.messages.MessageCollector @@ -117,8 +118,22 @@ fun appendDocumentation(documentation: DocumentationModule, val defaultPlatformsProvider = object : DefaultPlatformsProvider { override fun getDefaultPlatforms(descriptor: DeclarationDescriptor) = modelConfig.defaultPlatforms } - val injector = Guice.createInjector( - DokkaAnalysisModule(environment, dokkaConfiguration, defaultPlatformsProvider, documentation.nodeRefGraph, passConfiguration, DokkaConsoleLogger)) + + val globalInjector = Guice.createInjector( + DokkaRunModule(dokkaConfiguration) + ) + + val injector = globalInjector.createChildInjector( + DokkaAnalysisModule( + environment, + dokkaConfiguration, + defaultPlatformsProvider, + documentation.nodeRefGraph, + passConfiguration, + DokkaConsoleLogger + ) + ) + buildDocumentationModule(injector, documentation) Disposer.dispose(environment) } -- cgit From 77ce80517f79a774ef985be47ae00db828e34273 Mon Sep 17 00:00:00 2001 From: aleksZubakov Date: Mon, 6 Aug 2018 13:42:44 +0300 Subject: DocumentationMerger refactoring --- .../main/kotlin/Generation/DocumentationMerger.kt | 179 ++++++++++++++++ core/src/main/kotlin/Generation/DokkaGenerator.kt | 227 ++------------------- core/src/main/kotlin/Generation/FileGenerator.kt | 2 +- .../main/kotlin/Generation/configurationImpl.kt | 1 - .../src/main/kotlin/Kotlin/DocumentationBuilder.kt | 2 +- core/src/main/kotlin/Model/DocumentationNode.kt | 1 - .../main/kotlin/Model/DocumentationReference.kt | 26 +-- 7 files changed, 212 insertions(+), 226 deletions(-) create mode 100644 core/src/main/kotlin/Generation/DocumentationMerger.kt (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Generation/DocumentationMerger.kt b/core/src/main/kotlin/Generation/DocumentationMerger.kt new file mode 100644 index 00000000..c2089821 --- /dev/null +++ b/core/src/main/kotlin/Generation/DocumentationMerger.kt @@ -0,0 +1,179 @@ +package org.jetbrains.dokka.Generation + +import org.jetbrains.dokka.* + +class DocumentationMerger( + private val documentationModules: List +) { + private val producedNodeRefGraph: NodeReferenceGraph + private val signatureMap: Map + private val oldToNewNodeMap: MutableMap = mutableMapOf() + + init { + if (documentationModules.groupBy { it.name }.size > 1) { + throw IllegalArgumentException("Modules should have similar names") + } + + signatureMap = documentationModules + .flatMap { it.nodeRefGraph.nodeMapView.entries } + .associate { (k, v) -> v to k } + + + producedNodeRefGraph = NodeReferenceGraph() + documentationModules.map { it.nodeRefGraph } + .flatMap { it.references } + .distinct() + .forEach { producedNodeRefGraph.addReference(it) } + } + + private fun mergePackageReferences( + from: DocumentationNode, + packages: List + ): List { + + val packagesByName = packages + .map { it.to } + .groupBy { it.name } + + val mutableList = mutableListOf() + for ((name, listOfPackages) in packagesByName) { + val producedPackage = mergePackagesWithEqualNames(name, from, listOfPackages) + updatePendingReferences() + + mutableList.add( + DocumentationReference(from, producedPackage, RefKind.Member) + ) + } + + return mutableList + } + + private fun mergePackagesWithEqualNames( + name: String, + from: DocumentationNode, + packages: List + ): DocumentationNode { + val mergedPackage = DocumentationNode(name, Content.Empty, NodeKind.Package) + for (packageNode in packages) { + // TODO: Discuss + mergedPackage.updateContent { + for (otherChild in packageNode.content.children) { + children.add(otherChild) + } + } + oldToNewNodeMap[packageNode] = mergedPackage + } + mergedPackage.clear() + + val references = packages.flatMap { it.allReferences() } + val mergedReferences = mergeReferences(mergedPackage, references) + for (ref in mergedReferences.distinct()) { + mergedPackage.addReference(ref) + } + + from.append(mergedPackage, RefKind.Member) + + return mergedPackage + } + + private fun DocumentationNode.clear() = dropReferences { true } + + private fun mergeMembers( + from: DocumentationNode, + refs: List + ): List { + val membersBySignature: Map> = refs.map { it.to } + .groupBy { signatureMap[it]!! } + + val mergedMembers: MutableList = mutableListOf() + for ((signature, members) in membersBySignature) { + val newNode = mergeMembersWithEqualSignature(signature, from, members) + + producedNodeRefGraph.register(signature, newNode) + updatePendingReferences() + from.append(newNode, RefKind.Member) + + mergedMembers.add(DocumentationReference(from, newNode, RefKind.Member)) + } + + return mergedMembers + } + + private fun mergeMembersWithEqualSignature( + signature: String, + from: DocumentationNode, + refs: List + ): DocumentationNode { + val singleNode = refs.singleOrNull() + if (singleNode != null) { + singleNode.owner?.let { owner -> + singleNode.dropReferences { it.to == owner && it.kind == RefKind.Owner } + } + return singleNode + } + val groupNode = DocumentationNode(refs.first().name, Content.Empty, NodeKind.GroupNode) + groupNode.appendTextNode(signature, NodeKind.Signature, RefKind.Detail) + + for (node in refs) { + if (node != groupNode) { + node.owner?.let { owner -> + node.dropReferences { it.to == owner && it.kind == RefKind.Owner } + from.dropReferences { it.to == node && it.kind == RefKind.Member } + } + groupNode.append(node, RefKind.Member) + + oldToNewNodeMap[node] = groupNode + } + } + return groupNode + } + + + private fun mergeReferences( + from: DocumentationNode, + refs: List + ): List { + val (refsToPackages, usualRefs) = refs.partition { it.to.kind == NodeKind.Package } + val mergedPackages = mergePackageReferences(from, refsToPackages) + + val (refsToMembers, refsNotToMembers) = usualRefs.partition { it.kind == RefKind.Member } + val mergedMembers = mergeMembers(from, refsToMembers) + + // TODO: think about + return mergedPackages + (mergedMembers + refsNotToMembers).distinctBy { + it.to.kind to it.to.name + } + } + + + private fun updatePendingReferences() { + producedNodeRefGraph.references.forEach { + it.lazyNodeFrom.update() + it.lazyNodeTo.update() + } + } + + private fun NodeResolver.update() { + if (this is NodeResolver.Exact) { + if (exactNode != null && oldToNewNodeMap.containsKey(exactNode!!)) { + exactNode = oldToNewNodeMap[exactNode!!] + } + } + } + + fun merge(): DocumentationModule { + val mergedDocumentationModule = DocumentationModule( + name = documentationModules.first().name, + nodeRefGraph = producedNodeRefGraph + ) + + val refs = documentationModules.flatMap { + it.allReferences() + } + mergeReferences(mergedDocumentationModule, refs) + + return mergedDocumentationModule + } + + +} \ No newline at end of file diff --git a/core/src/main/kotlin/Generation/DokkaGenerator.kt b/core/src/main/kotlin/Generation/DokkaGenerator.kt index 22d1519f..37f62ed6 100644 --- a/core/src/main/kotlin/Generation/DokkaGenerator.kt +++ b/core/src/main/kotlin/Generation/DokkaGenerator.kt @@ -7,6 +7,7 @@ import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.psi.PsiFile import com.intellij.psi.PsiJavaFile import com.intellij.psi.PsiManager +import org.jetbrains.dokka.Generation.DocumentationMerger import org.jetbrains.dokka.Utilities.DokkaAnalysisModule import org.jetbrains.dokka.Utilities.DokkaOutputModule import org.jetbrains.dokka.Utilities.DokkaRunModule @@ -82,8 +83,8 @@ class DokkaGenerator(val dokkaConfiguration: DokkaConfiguration, DokkaAnalysisModule(environment, dokkaConfiguration, defaultPlatformsProvider, documentationModule.nodeRefGraph, passConfiguration, logger)) buildDocumentationModule(injector, documentationModule, { isNotSample(it, passConfiguration.samples) }, includes) - documentationModule.nodeRefGraph.nodeMapView.forEach { (_, node) -> // FIXME: change to full graph visiting - node.addReferenceTo( + documentationModule.visit { it -> + it.addReferenceTo( DocumentationNode(analysisPlatform.key, Content.Empty, NodeKind.Platform), RefKind.Platform ) @@ -95,7 +96,19 @@ class DokkaGenerator(val dokkaConfiguration: DokkaConfiguration, Disposer.dispose(environment) } - fun createAnalysisEnvironment(sourcePaths: List, passConfiguration: DokkaConfiguration.PassConfiguration): AnalysisEnvironment { + private fun DocumentationNode.visit(action: (DocumentationNode) -> Unit) { + action(this) + + for (member in members) { + member.visit(action) + } + } + + + fun createAnalysisEnvironment( + sourcePaths: List, + passConfiguration: DokkaConfiguration.PassConfiguration + ): AnalysisEnvironment { val environment = AnalysisEnvironment(DokkaMessageCollector(logger), passConfiguration.analysisPlatform) environment.apply { @@ -116,7 +129,7 @@ class DokkaGenerator(val dokkaConfiguration: DokkaConfiguration, return environment } - fun isNotSample(file: PsiFile, samples: List): Boolean { + private fun isNotSample(file: PsiFile, samples: List): Boolean { val sourceFile = File(file.virtualFile!!.path) return samples.none { sample -> val canonicalSample = File(sample).canonicalPath @@ -155,9 +168,7 @@ fun buildDocumentationModule(injector: Injector, val analyzer = resolutionFacade.getFrontendService(LazyTopDownAnalyzer::class.java) analyzer.analyzeDeclarations(TopDownAnalysisMode.TopLevelDeclarations, fragmentFiles) - val fragments = fragmentFiles - .map { resolutionFacade.resolveSession.getPackageFragment(it.packageFqName) } - .filterNotNull() + val fragments = fragmentFiles.mapNotNull { resolutionFacade.resolveSession.getPackageFragment(it.packageFqName) } .distinct() val packageDocs = injector.getInstance(PackageDocs::class.java) @@ -220,206 +231,4 @@ fun KotlinCoreEnvironment.getJavaSourceFiles(): List { } } return result -} - -class DocumentationMerger( - private val documentationModules: List -) { - private val producedNodeRefGraph: NodeReferenceGraph - private val signatureMap: Map - - init { - signatureMap = documentationModules - .flatMap { it.nodeRefGraph.nodeMapView.entries } - .map { (k, v) -> v to k } - .toMap() - - producedNodeRefGraph = NodeReferenceGraph() - documentationModules.map { it.nodeRefGraph } - .flatMap { it.references } - .distinct() - .forEach { producedNodeRefGraph.addReference(it) } - } - - private fun splitReferencesByKind( - source: List, - kind: RefKind - ): Pair, List> = - Pair(source.filter { it.kind == kind }, source.filterNot { it.kind == kind }) - - - private fun mergePackageReferences( - from: DocumentationNode, - packages: List - ): List { - val packagesByName = packages - .map { it.to } - .groupBy { it.name } - - val mutableList: MutableList = mutableListOf() - for ((name, listOfPackages) in packagesByName) { - val producedPackage = mergePackagesWithEqualNames(from, listOfPackages) - updatePendingReferences(name, producedPackage) - - mutableList.add( - DocumentationReference(from, producedPackage, RefKind.Member) - ) - } - - return mutableList - } - - private fun mergePackagesWithEqualNames( - from: DocumentationNode, - packages: List - ): DocumentationNode { - val references = packages.flatMap { it.allReferences() } - - val mergedPackage = - DocumentationNode( - packages.first().name, - Content.Empty, - NodeKind.Package - ) - - val mergedReferences = mergeReferences(mergedPackage, references) - - for (packageNode in packages) { - mergedPackage.updateContent { - for (otherChild in packageNode.content.children) { - children.add(otherChild) - } - } - } - - mergedPackage.dropReferences { true } // clear() - for (ref in mergedReferences.distinct()) { - mergedPackage.addReference(ref) - } - - from.append(mergedPackage, RefKind.Member) - - return mergedPackage - } - - - private fun mergeMembers( - from: DocumentationNode, - refs: List - ): List { - val membersBySignature: Map> = refs.map { it.to } - .filter { signatureMap.containsKey(it) } - .groupBy { signatureMap[it]!! } - - val mergedMembers: MutableList = mutableListOf() - for ((signature, members) in membersBySignature) { - val newNode = mergeMembersWithEqualSignature(signature, from, members) - - producedNodeRefGraph.register(signature, newNode) - updatePendingReferences(signature, newNode) - from.append(newNode, RefKind.Member) - - mergedMembers.add(DocumentationReference(from, newNode, RefKind.Member)) - } - - return mergedMembers - } - - private fun mergeMembersWithEqualSignature( - signature: String, - from: DocumentationNode, - refs: List - ): DocumentationNode { - if (refs.size == 1) { - val singleNode = refs.single() - singleNode.owner?.let { owner -> - singleNode.dropReferences { it.to == owner && it.kind == RefKind.Owner } - } - return singleNode - } - val groupNode = DocumentationNode(refs.first().name, Content.Empty, NodeKind.GroupNode) - groupNode.appendTextNode(signature, NodeKind.Signature, RefKind.Detail) - - for (node in refs) { - if (node != groupNode) { - node.owner?.let { owner -> - node.dropReferences { it.to == owner && it.kind == RefKind.Owner } - from.dropReferences { it.to == node && it.kind == RefKind.Member } - } - groupNode.append(node, RefKind.Member) - } - } - return groupNode - } - - - private fun mergeReferences( - from: DocumentationNode, - refs: List - ): List { - val allRefsToPackages = refs.map { it.to } - .all { it.kind == NodeKind.Package } - - if (allRefsToPackages) { - return mergePackageReferences(from, refs) - } - - val (memberRefs, notMemberRefs) = splitReferencesByKind(refs, RefKind.Member) - val mergedMembers = mergeMembers(from, memberRefs) - - return (mergedMembers + notMemberRefs).distinctBy { - it.kind to it.to.name - } - } - - - private fun updatePendingReferences( - signature: String, - nodeToUpdate: DocumentationNode - ) { - producedNodeRefGraph.references.forEach { - it.lazyNodeFrom.update(signature, nodeToUpdate) - it.lazyNodeTo.update(signature, nodeToUpdate) - } - } - - private fun NodeResolver.update(signature: String, nodeToUpdate: DocumentationNode) { - when (this) { - is NodeResolver.BySignature -> update(signature, nodeToUpdate) - is NodeResolver.Exact -> update(signature, nodeToUpdate) - } - } - - private fun NodeResolver.BySignature.update(signature: String, nodeToUpdate: DocumentationNode) { - if (signature == nodeToUpdate.name) { - nodeMap = producedNodeRefGraph.nodeMapView - } - } - - private fun NodeResolver.Exact.update(signature: String, nodeToUpdate: DocumentationNode) { - exactNode?.let { it -> - val equalSignature = - it.anyReference { ref -> ref.to.kind == NodeKind.Signature && ref.to.name == signature } - - if (equalSignature) { - exactNode = nodeToUpdate - } - } - } - - fun merge(): DocumentationModule { - val refs = documentationModules.flatMap { - it.allReferences() - } - val mergedDocumentationModule = DocumentationModule( - name = documentationModules.first().name, - nodeRefGraph = producedNodeRefGraph - ) - - mergeReferences(mergedDocumentationModule, refs) - - return mergedDocumentationModule - } - - } \ No newline at end of file diff --git a/core/src/main/kotlin/Generation/FileGenerator.kt b/core/src/main/kotlin/Generation/FileGenerator.kt index eb6800b3..d7b35581 100644 --- a/core/src/main/kotlin/Generation/FileGenerator.kt +++ b/core/src/main/kotlin/Generation/FileGenerator.kt @@ -10,7 +10,7 @@ import java.io.OutputStreamWriter class FileGenerator @Inject constructor(@Named("outputDir") override val root: File) : NodeLocationAwareGenerator { @set:Inject(optional = true) var outlineService: OutlineFormatService? = null - @set:Inject(optional = true) lateinit var formatService: FormatService + @set:Inject lateinit var formatService: FormatService @set:Inject(optional = true) lateinit var dokkaConfiguration: DokkaConfiguration @set:Inject(optional = true) var packageListService: PackageListService? = null diff --git a/core/src/main/kotlin/Generation/configurationImpl.kt b/core/src/main/kotlin/Generation/configurationImpl.kt index 3e39b4ed..f2a91002 100644 --- a/core/src/main/kotlin/Generation/configurationImpl.kt +++ b/core/src/main/kotlin/Generation/configurationImpl.kt @@ -26,7 +26,6 @@ class SourceRootImpl(path: String, override val platforms: List = emptyL fun parseSourceRoot(sourceRoot: String): SourceRoot { val components = sourceRoot.split("::", limit = 2) - // TODO: create syntax for cli val platform = if (components.size == 1) { Platform.DEFAULT } else { diff --git a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt index fb0b898a..be3eef71 100644 --- a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt +++ b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt @@ -1097,7 +1097,7 @@ fun DocumentationNode.generateAllTypesNode() { val allTypes = members(NodeKind.Package) .flatMap { it.members.filter { it.kind in NodeKind.classLike || it.kind == NodeKind.ExternalClass - || (it.kind == NodeKind.GroupNode && it.anyReference { it.to.kind in NodeKind.classLike }) } } + || (it.kind == NodeKind.GroupNode && it.members.all { it.kind in NodeKind.classLike }) } } .sortedBy { if (it.kind == NodeKind.ExternalClass) it.name.substringAfterLast('.').toLowerCase() else it.name.toLowerCase() } val allTypesNode = DocumentationNode("alltypes", Content.Empty, NodeKind.AllTypes) diff --git a/core/src/main/kotlin/Model/DocumentationNode.kt b/core/src/main/kotlin/Model/DocumentationNode.kt index bdb7cf20..23137364 100644 --- a/core/src/main/kotlin/Model/DocumentationNode.kt +++ b/core/src/main/kotlin/Model/DocumentationNode.kt @@ -163,7 +163,6 @@ open class DocumentationNode(val name: String, fun member(kind: NodeKind): DocumentationNode = members.filter { it.kind == kind }.single() fun link(kind: NodeKind): DocumentationNode = links.filter { it.kind == kind }.single() - fun anyReference(predicate: (DocumentationReference) -> Boolean): Boolean = references.any(predicate) fun references(kind: RefKind): List = references.filter { it.kind == kind } fun allReferences(): Set = references diff --git a/core/src/main/kotlin/Model/DocumentationReference.kt b/core/src/main/kotlin/Model/DocumentationReference.kt index 9223c17a..282d87d8 100644 --- a/core/src/main/kotlin/Model/DocumentationReference.kt +++ b/core/src/main/kotlin/Model/DocumentationReference.kt @@ -26,15 +26,15 @@ data class DocumentationReference(val from: DocumentationNode, val to: Documenta } sealed class NodeResolver { - abstract fun resolve(): DocumentationNode? - class BySignature(var signature: String, var nodeMap: Map) : NodeResolver() { - override fun resolve(): DocumentationNode? { - return nodeMap[signature] + abstract fun resolve(nodeRephGraph: NodeReferenceGraph): DocumentationNode? + class BySignature(var signature: String) : NodeResolver() { + override fun resolve(nodeRephGraph: NodeReferenceGraph): DocumentationNode? { + return nodeRephGraph.lookup(signature) } } class Exact(var exactNode: DocumentationNode?) : NodeResolver() { - override fun resolve(): DocumentationNode? { + override fun resolve(nodeRephGraph: NodeReferenceGraph): DocumentationNode? { return exactNode } } @@ -43,9 +43,9 @@ sealed class NodeResolver { class PendingDocumentationReference(val lazyNodeFrom: NodeResolver, val lazyNodeTo: NodeResolver, val kind: RefKind) { - fun resolve() { - val fromNode = lazyNodeFrom.resolve() - val toNode = lazyNodeTo.resolve() + fun resolve(nodeRephGraph: NodeReferenceGraph) { + val fromNode = lazyNodeFrom.resolve(nodeRephGraph) + val toNode = lazyNodeTo.resolve(nodeRephGraph) if (fromNode != null && toNode != null) { fromNode.addReferenceTo(toNode, kind) } @@ -67,7 +67,7 @@ class NodeReferenceGraph { references.add( PendingDocumentationReference( NodeResolver.Exact(fromNode), - NodeResolver.BySignature(toSignature, nodeMap), + NodeResolver.BySignature(toSignature), kind )) } @@ -75,7 +75,7 @@ class NodeReferenceGraph { fun link(fromSignature: String, toNode: DocumentationNode, kind: RefKind) { references.add( PendingDocumentationReference( - NodeResolver.BySignature(fromSignature, nodeMap), + NodeResolver.BySignature(fromSignature), NodeResolver.Exact(toNode), kind ) @@ -85,8 +85,8 @@ class NodeReferenceGraph { fun link(fromSignature: String, toSignature: String, kind: RefKind) { references.add( PendingDocumentationReference( - NodeResolver.BySignature(fromSignature, nodeMap), - NodeResolver.BySignature(toSignature, nodeMap), + NodeResolver.BySignature(fromSignature), + NodeResolver.BySignature(toSignature), kind ) ) @@ -107,7 +107,7 @@ class NodeReferenceGraph { } fun resolveReferences() { - references.forEach { it.resolve() } + references.forEach { it.resolve(this) } } } -- cgit From 4456ead8b702e4881321488969cb4ce1711e5663 Mon Sep 17 00:00:00 2001 From: aleksZubakov Date: Mon, 6 Aug 2018 17:14:28 +0300 Subject: Optional dependency bug workaround: google/guice#847 --- core/src/main/kotlin/Formats/FormatDescriptor.kt | 1 + core/src/main/kotlin/Generation/FileGenerator.kt | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Formats/FormatDescriptor.kt b/core/src/main/kotlin/Formats/FormatDescriptor.kt index b497fb0f..4bac8aa0 100644 --- a/core/src/main/kotlin/Formats/FormatDescriptor.kt +++ b/core/src/main/kotlin/Formats/FormatDescriptor.kt @@ -25,6 +25,7 @@ abstract class FileGeneratorBasedFormatDescriptor : FormatDescriptor { override fun configureOutput(binder: Binder): Unit = with(binder) { bind() toType NodeLocationAwareGenerator::class bind() toType generatorServiceClass + bind(generatorServiceClass.java) // https://github.com/google/guice/issues/847 bind() toType languageServiceClass diff --git a/core/src/main/kotlin/Generation/FileGenerator.kt b/core/src/main/kotlin/Generation/FileGenerator.kt index d7b35581..eb6800b3 100644 --- a/core/src/main/kotlin/Generation/FileGenerator.kt +++ b/core/src/main/kotlin/Generation/FileGenerator.kt @@ -10,7 +10,7 @@ import java.io.OutputStreamWriter class FileGenerator @Inject constructor(@Named("outputDir") override val root: File) : NodeLocationAwareGenerator { @set:Inject(optional = true) var outlineService: OutlineFormatService? = null - @set:Inject lateinit var formatService: FormatService + @set:Inject(optional = true) lateinit var formatService: FormatService @set:Inject(optional = true) lateinit var dokkaConfiguration: DokkaConfiguration @set:Inject(optional = true) var packageListService: PackageListService? = null -- cgit From fc517baac7ba381f0f4f2529e59700b1191dd0ce Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Wed, 10 Jan 2018 21:56:20 +0300 Subject: Fix crash on incorrect sample conversion --- .../KotlinWebsiteSampleProcessingService.kt | 48 ++++++++++++++++++++-- 1 file changed, 45 insertions(+), 3 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Samples/KotlinWebsiteSampleProcessingService.kt b/core/src/main/kotlin/Samples/KotlinWebsiteSampleProcessingService.kt index b5801457..b12e3a66 100644 --- a/core/src/main/kotlin/Samples/KotlinWebsiteSampleProcessingService.kt +++ b/core/src/main/kotlin/Samples/KotlinWebsiteSampleProcessingService.kt @@ -1,15 +1,18 @@ package org.jetbrains.dokka.Samples import com.google.inject.Inject -import com.intellij.psi.PsiElement -import com.intellij.psi.PsiWhiteSpace +import com.intellij.psi.* import com.intellij.psi.impl.source.tree.LeafPsiElement import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.dokka.* import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.allChildren import org.jetbrains.kotlin.psi.psiUtil.prevLeaf +import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.ImportPath +import java.io.PrintWriter +import java.io.StringWriter + open class KotlinWebsiteSampleProcessingService @Inject constructor(dokkaConfiguration: DokkaConfiguration, @@ -22,6 +25,10 @@ open class KotlinWebsiteSampleProcessingService val text: String get() = builder.toString() + val errors = mutableListOf() + + data class ConvertError(val e: Exception, val text: String, val loc: String) + fun KtValueArgument.extractStringArgumentValue() = (getArgumentExpression() as KtStringTemplateExpression) .entries.joinToString("") { it.text } @@ -92,16 +99,51 @@ open class KotlinWebsiteSampleProcessingService } } + private fun reportProblemConvertingElement(element: PsiElement, e: Exception) { + val text = element.text + val document = PsiDocumentManager.getInstance(element.project).getDocument(element.containingFile) + + val lineInfo = if (document != null) { + val lineNumber = document.getLineNumber(element.startOffset) + "$lineNumber, ${element.startOffset - document.getLineStartOffset(lineNumber)}" + } else { + "offset: ${element.startOffset}" + } + errors += ConvertError(e, text, lineInfo) + } + override fun visitElement(element: PsiElement) { if (element is LeafPsiElement) builder.append(element.text) - super.visitElement(element) + + element.acceptChildren(object : PsiElementVisitor() { + override fun visitElement(element: PsiElement) { + try { + element.accept(this@SampleBuilder) + } catch (e: Exception) { + try { + reportProblemConvertingElement(element, e) + } finally { + builder.append(element.text) //recover + } + } + } + }) } + } private fun PsiElement.buildSampleText(): String { val sampleBuilder = SampleBuilder() this.accept(sampleBuilder) + + sampleBuilder.errors.forEach { + val sw = StringWriter() + val pw = PrintWriter(sw) + it.e.printStackTrace(pw) + + logger.error("${containingFile.name}: (${it.loc}): Exception thrown while converting \n```\n${it.text}\n```\n$sw") + } return sampleBuilder.text } -- cgit From a838a096da246babd93dc518dec8d2470d1c14f5 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Wed, 10 Jan 2018 22:25:11 +0300 Subject: Convert assertFails in kws samples without message properly --- .../KotlinWebsiteSampleProcessingService.kt | 40 ++++++++++++++++------ .../format/website-html/sampleWithAsserts.html | 2 ++ .../format/website-html/sampleWithAsserts.kt | 2 ++ 3 files changed, 33 insertions(+), 11 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Samples/KotlinWebsiteSampleProcessingService.kt b/core/src/main/kotlin/Samples/KotlinWebsiteSampleProcessingService.kt index b12e3a66..4525e9d9 100644 --- a/core/src/main/kotlin/Samples/KotlinWebsiteSampleProcessingService.kt +++ b/core/src/main/kotlin/Samples/KotlinWebsiteSampleProcessingService.kt @@ -1,7 +1,10 @@ package org.jetbrains.dokka.Samples import com.google.inject.Inject -import com.intellij.psi.* +import com.intellij.psi.PsiDocumentManager +import com.intellij.psi.PsiElement +import com.intellij.psi.PsiElementVisitor +import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.impl.source.tree.LeafPsiElement import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.dokka.* @@ -61,27 +64,42 @@ open class KotlinWebsiteSampleProcessingService } fun convertAssertFails(expression: KtCallExpression) { - val (message, funcArgument) = expression.valueArguments + val valueArguments = expression.valueArguments + + val funcArgument: KtValueArgument + val message: KtValueArgument? + + if (valueArguments.size == 1) { + message = null + funcArgument = valueArguments.first() + } else { + message = valueArguments.first() + funcArgument = valueArguments.last() + } + builder.apply { - val argument = if (funcArgument.getArgumentExpression() is KtLambdaExpression) - PsiTreeUtil.findChildOfType(funcArgument, KtBlockExpression::class.java)?.text ?: "" - else - funcArgument.text + val argument = funcArgument.extractFunctionalArgumentText() append(argument.lines().joinToString(separator = "\n") { "// $it" }) append(" // ") - append(message.extractStringArgumentValue()) + if (message != null) { + append(message.extractStringArgumentValue()) + } append(" will fail") } } + private fun KtValueArgument.extractFunctionalArgumentText(): String { + return if (getArgumentExpression() is KtLambdaExpression) + PsiTreeUtil.findChildOfType(this, KtBlockExpression::class.java)?.text ?: "" + else + text + } + fun convertAssertFailsWith(expression: KtCallExpression) { val (funcArgument) = expression.valueArguments val (exceptionType) = expression.typeArguments builder.apply { - val argument = if (funcArgument.firstChild is KtLambdaExpression) - PsiTreeUtil.findChildOfType(funcArgument, KtBlockExpression::class.java)?.text ?: "" - else - funcArgument.text + val argument = funcArgument.extractFunctionalArgumentText() append(argument.lines().joinToString(separator = "\n") { "// $it" }) append(" // will fail with ") append(exceptionType.text) diff --git a/core/testdata/format/website-html/sampleWithAsserts.html b/core/testdata/format/website-html/sampleWithAsserts.html index e91232f5..2b2a9ac5 100644 --- a/core/testdata/format/website-html/sampleWithAsserts.html +++ b/core/testdata/format/website-html/sampleWithAsserts.html @@ -14,6 +14,8 @@ println("a() == b() is ${a() == b()}") // true // readSomeFile(File("some.txt")) // reading file now will fail // readSomeFile(File("some.txt")) // will fail with FileNotFoundException +// readSomeFile(File("some.txt")) // will fail + fun indented() { // A neq B println("a() != b() is ${a() != b()}") // false diff --git a/core/testdata/format/website-html/sampleWithAsserts.kt b/core/testdata/format/website-html/sampleWithAsserts.kt index b3bce11d..bb5848e6 100644 --- a/core/testdata/format/website-html/sampleWithAsserts.kt +++ b/core/testdata/format/website-html/sampleWithAsserts.kt @@ -26,6 +26,8 @@ fun sample() { assertFails("reading file now") { readSomeFile(File("some.txt")) } assertFailsWith { readSomeFile(File("some.txt")) } + assertFails { readSomeFile(File("some.txt")) } + fun indented() { assertFalse(a() != b(), "A neq B") } -- cgit From 1f45cac76a79abb6eaad99b541234cbf34fbce9c Mon Sep 17 00:00:00 2001 From: Zubakov Aleksey Date: Fri, 17 Aug 2018 13:00:06 +0300 Subject: Merger platforms bug fix, refactoring --- .../main/kotlin/Formats/StructuredFormatService.kt | 2 + .../main/kotlin/Generation/DocumentationMerger.kt | 58 ++++++++-------------- core/src/main/kotlin/Generation/DokkaGenerator.kt | 19 +------ .../src/main/kotlin/Kotlin/DocumentationBuilder.kt | 23 ++++++--- 4 files changed, 42 insertions(+), 60 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Formats/StructuredFormatService.kt b/core/src/main/kotlin/Formats/StructuredFormatService.kt index 41c8f29a..b810dfca 100644 --- a/core/src/main/kotlin/Formats/StructuredFormatService.kt +++ b/core/src/main/kotlin/Formats/StructuredFormatService.kt @@ -404,6 +404,8 @@ abstract class StructuredOutputBuilder(val to: StringBuilder, fun String.isKotlinVersion() = this.startsWith("Kotlin") + if (platforms.count() == 0) return emptySet() + // Calculating common platforms for items return platforms.reduce { result, platformsOfItem -> val otherKotlinVersion = result.find { it.isKotlinVersion() } diff --git a/core/src/main/kotlin/Generation/DocumentationMerger.kt b/core/src/main/kotlin/Generation/DocumentationMerger.kt index c2089821..c4a40df6 100644 --- a/core/src/main/kotlin/Generation/DocumentationMerger.kt +++ b/core/src/main/kotlin/Generation/DocumentationMerger.kt @@ -22,7 +22,6 @@ class DocumentationMerger( producedNodeRefGraph = NodeReferenceGraph() documentationModules.map { it.nodeRefGraph } .flatMap { it.references } - .distinct() .forEach { producedNodeRefGraph.addReference(it) } } @@ -30,7 +29,6 @@ class DocumentationMerger( from: DocumentationNode, packages: List ): List { - val packagesByName = packages .map { it.to } .groupBy { it.name } @@ -63,11 +61,13 @@ class DocumentationMerger( } oldToNewNodeMap[packageNode] = mergedPackage } - mergedPackage.clear() val references = packages.flatMap { it.allReferences() } val mergedReferences = mergeReferences(mergedPackage, references) - for (ref in mergedReferences.distinct()) { + for (ref in mergedReferences) { + if (ref.kind == RefKind.Owner) { + continue + } mergedPackage.addReference(ref) } @@ -76,8 +76,6 @@ class DocumentationMerger( return mergedPackage } - private fun DocumentationNode.clear() = dropReferences { true } - private fun mergeMembers( from: DocumentationNode, refs: List @@ -106,24 +104,17 @@ class DocumentationMerger( ): DocumentationNode { val singleNode = refs.singleOrNull() if (singleNode != null) { - singleNode.owner?.let { owner -> - singleNode.dropReferences { it.to == owner && it.kind == RefKind.Owner } - } + singleNode.dropReferences { it.kind == RefKind.Owner } return singleNode } val groupNode = DocumentationNode(refs.first().name, Content.Empty, NodeKind.GroupNode) groupNode.appendTextNode(signature, NodeKind.Signature, RefKind.Detail) for (node in refs) { - if (node != groupNode) { - node.owner?.let { owner -> - node.dropReferences { it.to == owner && it.kind == RefKind.Owner } - from.dropReferences { it.to == node && it.kind == RefKind.Member } - } - groupNode.append(node, RefKind.Member) + node.dropReferences { it.kind == RefKind.Owner } + groupNode.append(node, RefKind.Member) - oldToNewNodeMap[node] = groupNode - } + oldToNewNodeMap[node] = groupNode } return groupNode } @@ -140,25 +131,7 @@ class DocumentationMerger( val mergedMembers = mergeMembers(from, refsToMembers) // TODO: think about - return mergedPackages + (mergedMembers + refsNotToMembers).distinctBy { - it.to.kind to it.to.name - } - } - - - private fun updatePendingReferences() { - producedNodeRefGraph.references.forEach { - it.lazyNodeFrom.update() - it.lazyNodeTo.update() - } - } - - private fun NodeResolver.update() { - if (this is NodeResolver.Exact) { - if (exactNode != null && oldToNewNodeMap.containsKey(exactNode!!)) { - exactNode = oldToNewNodeMap[exactNode!!] - } - } + return mergedPackages + mergedMembers + refsNotToMembers } fun merge(): DocumentationModule { @@ -175,5 +148,18 @@ class DocumentationMerger( return mergedDocumentationModule } + private fun updatePendingReferences() { + for (ref in producedNodeRefGraph.references) { + ref.lazyNodeFrom.update() + ref.lazyNodeTo.update() + } + } + private fun NodeResolver.update() { + if (this is NodeResolver.Exact) { + if (exactNode != null && exactNode!! in oldToNewNodeMap) { + exactNode = oldToNewNodeMap[exactNode!!] + } + } + } } \ No newline at end of file diff --git a/core/src/main/kotlin/Generation/DokkaGenerator.kt b/core/src/main/kotlin/Generation/DokkaGenerator.kt index 37f62ed6..1193657e 100644 --- a/core/src/main/kotlin/Generation/DokkaGenerator.kt +++ b/core/src/main/kotlin/Generation/DokkaGenerator.kt @@ -69,13 +69,13 @@ class DokkaGenerator(val dokkaConfiguration: DokkaConfiguration, logger.info("Analysing sources and libraries... ") val startAnalyse = System.currentTimeMillis() - val defaultPlatformAsList = listOf(passConfiguration.analysisPlatform.key) + val defaultPlatformAsList = passConfiguration.targets val defaultPlatformsProvider = object : DefaultPlatformsProvider { override fun getDefaultPlatforms(descriptor: DeclarationDescriptor): List { val containingFilePath = descriptor.sourcePsi()?.containingFile?.virtualFile?.canonicalPath ?.let { File(it).absolutePath } val sourceRoot = containingFilePath?.let { path -> sourceRoots.find { path.startsWith(it.path) } } - return sourceRoot?.platforms ?: defaultPlatformAsList + return /*sourceRoot?.platforms ?: */defaultPlatformAsList } } @@ -83,12 +83,6 @@ class DokkaGenerator(val dokkaConfiguration: DokkaConfiguration, DokkaAnalysisModule(environment, dokkaConfiguration, defaultPlatformsProvider, documentationModule.nodeRefGraph, passConfiguration, logger)) buildDocumentationModule(injector, documentationModule, { isNotSample(it, passConfiguration.samples) }, includes) - documentationModule.visit { it -> - it.addReferenceTo( - DocumentationNode(analysisPlatform.key, Content.Empty, NodeKind.Platform), - RefKind.Platform - ) - } val timeAnalyse = System.currentTimeMillis() - startAnalyse logger.info("done in ${timeAnalyse / 1000} secs") @@ -96,15 +90,6 @@ class DokkaGenerator(val dokkaConfiguration: DokkaConfiguration, Disposer.dispose(environment) } - private fun DocumentationNode.visit(action: (DocumentationNode) -> Unit) { - action(this) - - for (member in members) { - member.visit(action) - } - } - - fun createAnalysisEnvironment( sourcePaths: List, passConfiguration: DokkaConfiguration.PassConfiguration diff --git a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt index be3eef71..c25a7069 100644 --- a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt +++ b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt @@ -889,23 +889,27 @@ class DocumentationBuilder } - fun DocumentationNode.getParentForPackageMember(descriptor: DeclarationDescriptor, - externalClassNodes: MutableMap, - allFqNames: Collection): DocumentationNode { + fun DocumentationNode.getParentForPackageMember( + descriptor: DeclarationDescriptor, + externalClassNodes: MutableMap, + allFqNames: Collection, + packageName: FqName + ): DocumentationNode { if (descriptor is CallableMemberDescriptor) { val extensionClassDescriptor = descriptor.getExtensionClassDescriptor() if (extensionClassDescriptor != null && isExtensionForExternalClass(descriptor, extensionClassDescriptor, allFqNames) && !ErrorUtils.isError(extensionClassDescriptor)) { val fqName = DescriptorUtils.getFqNameSafe(extensionClassDescriptor) - return externalClassNodes.getOrPut(fqName, { + return externalClassNodes.getOrPut(fqName) { val newNode = DocumentationNode(fqName.asString(), Content.Empty, NodeKind.ExternalClass) val externalLink = linkResolver.externalDocumentationLinkResolver.buildExternalDocumentationLink(extensionClassDescriptor) if (externalLink != null) { newNode.append(DocumentationNode(externalLink, Content.Empty, NodeKind.ExternalLink), RefKind.Link) } append(newNode, RefKind.Member) + refGraph.register("${packageName.asString()}:${extensionClassDescriptor.signature()}", newNode) newNode - }) + } } } return this @@ -933,7 +937,12 @@ class KotlinPackageDocumentationBuilder : PackageDocumentationBuilder { declarations.forEach { descriptor -> with(documentationBuilder) { if (descriptor.isDocumented(passConfiguration)) { - val parent = packageNode.getParentForPackageMember(descriptor, externalClassNodes, allFqNames) + val parent = packageNode.getParentForPackageMember( + descriptor, + externalClassNodes, + allFqNames, + packageName + ) parent.appendOrUpdateMember(descriptor) } } @@ -1025,7 +1034,7 @@ fun DeclarationDescriptor.signature(): String { is TypeAliasDescriptor -> DescriptorUtils.getFqName(this).asString() is PropertyDescriptor -> containingDeclaration.signature() + "$" + name + receiverSignature() - is FunctionDescriptor -> containingDeclaration.signature() + "$" + name + parameterSignature() + ":" + returnType?.signature() + is FunctionDescriptor -> containingDeclaration.signature() + "$" + name + parameterSignature() + ":" + returnType?.signature() is ValueParameterDescriptor -> containingDeclaration.signature() + "/" + name is TypeParameterDescriptor -> containingDeclaration.signature() + "*" + name is ReceiverParameterDescriptor -> containingDeclaration.signature() + "/" + name -- cgit From b265a9ffacb8f8e8e6226a9458a92697b02355a8 Mon Sep 17 00:00:00 2001 From: Zubakov Date: Mon, 27 Aug 2018 15:08:28 +0300 Subject: Ant runner default external links and classpath resolving fix --- core/src/main/kotlin/Utilities/ServiceLocator.kt | 2 +- runners/ant/src/main/kotlin/ant/dokka.kt | 14 +++++++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Utilities/ServiceLocator.kt b/core/src/main/kotlin/Utilities/ServiceLocator.kt index 83c4c65c..fca08f38 100644 --- a/core/src/main/kotlin/Utilities/ServiceLocator.kt +++ b/core/src/main/kotlin/Utilities/ServiceLocator.kt @@ -70,7 +70,7 @@ object ServiceLocator { "jar" -> { val file = JarFile(URL(it.file.substringBefore("!")).toFile()) try { - val jarPath = it.file.substringAfterLast("!").removePrefix("/") + val jarPath = it.file.substringAfterLast("!").removeSurrounding("/") file.entries() .asSequence() .filter { entry -> !entry.isDirectory && entry.path == jarPath && entry.extension == "properties" } diff --git a/runners/ant/src/main/kotlin/ant/dokka.kt b/runners/ant/src/main/kotlin/ant/dokka.kt index 9e38aa22..9428a7ce 100644 --- a/runners/ant/src/main/kotlin/ant/dokka.kt +++ b/runners/ant/src/main/kotlin/ant/dokka.kt @@ -53,7 +53,7 @@ class AntPassConfig(task: Task) : DokkaConfiguration.PassConfiguration { } override val perPackageOptions: MutableList = mutableListOf() override val externalDocumentationLinks: List - get() = buildExternalLinksBuilders.map { it.build() } + get() = buildExternalLinksBuilders.map { it.build() } + defaultExternalDocumentationLinks override var languageVersion: String? = null override var apiVersion: String? = null @@ -76,6 +76,18 @@ class AntPassConfig(task: Task) : DokkaConfiguration.PassConfiguration { private val buildExternalLinksBuilders: MutableList = mutableListOf() val antSourceLinkDefinition: MutableList = mutableListOf() + private val defaultExternalDocumentationLinks: List + get() { + val links = mutableListOf() + if (!noJdkLink) + links += DokkaConfiguration.ExternalDocumentationLink.Builder("http://docs.oracle.com/javase/$jdkVersion/docs/api/").build() + + if (!noStdlibLink) + links += DokkaConfiguration.ExternalDocumentationLink.Builder("https://kotlinlang.org/api/latest/jvm/stdlib/").build() + return links + } + + fun setSamples(ref: Path) { samplesPath.append(ref) } -- cgit From 0b43db4ff81746e44d06780d8d14bb49dc1d87aa Mon Sep 17 00:00:00 2001 From: Zubakov Date: Mon, 27 Aug 2018 16:27:41 +0300 Subject: Introduce origin reference kind, change documentation graph merge logic, minor refactoring --- .../main/kotlin/Formats/StructuredFormatService.kt | 28 +++++----- .../main/kotlin/Generation/DocumentationMerger.kt | 65 +++++++++++++--------- .../src/main/kotlin/Kotlin/DocumentationBuilder.kt | 2 +- core/src/main/kotlin/Model/DocumentationNode.kt | 4 ++ .../main/kotlin/Model/DocumentationReference.kt | 5 +- 5 files changed, 61 insertions(+), 43 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Formats/StructuredFormatService.kt b/core/src/main/kotlin/Formats/StructuredFormatService.kt index b810dfca..1ca636ec 100644 --- a/core/src/main/kotlin/Formats/StructuredFormatService.kt +++ b/core/src/main/kotlin/Formats/StructuredFormatService.kt @@ -192,22 +192,20 @@ abstract class StructuredOutputBuilder(val to: StringBuilder, } } - open fun link(from: DocumentationNode, - to: DocumentationNode, - name: (DocumentationNode) -> String = DocumentationNode::name): FormatLink = link(from, to, extension, name) + open fun link( + from: DocumentationNode, + to: DocumentationNode, + name: (DocumentationNode) -> String = DocumentationNode::name + ): FormatLink = link(from, to, extension, name) + + open fun link( + from: DocumentationNode, + to: DocumentationNode, + extension: String, + name: (DocumentationNode) -> String = DocumentationNode::name + ): FormatLink = + FormatLink(name(to), from.location().relativePathTo(to.location())) - open fun link(from: DocumentationNode, - to: DocumentationNode, - extension: String, - name: (DocumentationNode) -> String = DocumentationNode::name): FormatLink { - if (to.owner?.kind == NodeKind.GroupNode) - return link(from, to.owner!!, extension, name) - - if (from.owner?.kind == NodeKind.GroupNode) - return link(from.owner!!, to, extension, name) - - return FormatLink(name(to), from.location().relativePathTo(to.location())) - } fun locationHref(from: Location, to: DocumentationNode): String { val topLevelPage = to.references(RefKind.TopLevelPage).singleOrNull()?.to diff --git a/core/src/main/kotlin/Generation/DocumentationMerger.kt b/core/src/main/kotlin/Generation/DocumentationMerger.kt index c4a40df6..0394dce2 100644 --- a/core/src/main/kotlin/Generation/DocumentationMerger.kt +++ b/core/src/main/kotlin/Generation/DocumentationMerger.kt @@ -5,7 +5,7 @@ import org.jetbrains.dokka.* class DocumentationMerger( private val documentationModules: List ) { - private val producedNodeRefGraph: NodeReferenceGraph + private val producedNodeRefGraph: NodeReferenceGraph = NodeReferenceGraph() private val signatureMap: Map private val oldToNewNodeMap: MutableMap = mutableMapOf() @@ -19,7 +19,6 @@ class DocumentationMerger( .associate { (k, v) -> v to k } - producedNodeRefGraph = NodeReferenceGraph() documentationModules.map { it.nodeRefGraph } .flatMap { it.references } .forEach { producedNodeRefGraph.addReference(it) } @@ -33,17 +32,17 @@ class DocumentationMerger( .map { it.to } .groupBy { it.name } - val mutableList = mutableListOf() + val resultReferences = mutableListOf() for ((name, listOfPackages) in packagesByName) { val producedPackage = mergePackagesWithEqualNames(name, from, listOfPackages) updatePendingReferences() - mutableList.add( + resultReferences.add( DocumentationReference(from, producedPackage, RefKind.Member) ) } - return mutableList + return resultReferences } private fun mergePackagesWithEqualNames( @@ -52,14 +51,17 @@ class DocumentationMerger( packages: List ): DocumentationNode { val mergedPackage = DocumentationNode(name, Content.Empty, NodeKind.Package) - for (packageNode in packages) { - // TODO: Discuss + + for (contentToAppend in packages.map { it.content }.distinct()) { mergedPackage.updateContent { - for (otherChild in packageNode.content.children) { + for (otherChild in contentToAppend.children) { children.add(otherChild) } } - oldToNewNodeMap[packageNode] = mergedPackage + } + + for (node in packages) { + oldToNewNodeMap[node] = mergedPackage } val references = packages.flatMap { it.allReferences() } @@ -76,7 +78,7 @@ class DocumentationMerger( return mergedPackage } - private fun mergeMembers( + private fun mergeMemberReferences( from: DocumentationNode, refs: List ): List { @@ -85,7 +87,7 @@ class DocumentationMerger( val mergedMembers: MutableList = mutableListOf() for ((signature, members) in membersBySignature) { - val newNode = mergeMembersWithEqualSignature(signature, from, members) + val newNode = mergeMembersWithEqualSignature(signature, members) producedNodeRefGraph.register(signature, newNode) updatePendingReferences() @@ -99,23 +101,39 @@ class DocumentationMerger( private fun mergeMembersWithEqualSignature( signature: String, - from: DocumentationNode, - refs: List + nodes: List ): DocumentationNode { - val singleNode = refs.singleOrNull() + val singleNode = nodes.singleOrNull() if (singleNode != null) { singleNode.dropReferences { it.kind == RefKind.Owner } return singleNode } - val groupNode = DocumentationNode(refs.first().name, Content.Empty, NodeKind.GroupNode) + + val groupNode = DocumentationNode(nodes.first().name, Content.Empty, NodeKind.GroupNode) groupNode.appendTextNode(signature, NodeKind.Signature, RefKind.Detail) - for (node in refs) { + for (node in nodes) { node.dropReferences { it.kind == RefKind.Owner } - groupNode.append(node, RefKind.Member) + groupNode.append(node, RefKind.Origin) oldToNewNodeMap[node] = groupNode } + + // if nodes are classes, nested members should be also merged and + // inserted at the same level with class + if (nodes.all { it.kind == NodeKind.Class }) { + val members = nodes.flatMap { it.allReferences() }.filter { it.kind == RefKind.Member } + val mergedMembers = mergeMemberReferences(groupNode, members) + + for (ref in mergedMembers) { + if (ref.kind == RefKind.Owner) { + continue + } + + groupNode.append(ref.to, RefKind.Member) + } + } + return groupNode } @@ -124,13 +142,12 @@ class DocumentationMerger( from: DocumentationNode, refs: List ): List { - val (refsToPackages, usualRefs) = refs.partition { it.to.kind == NodeKind.Package } + val (refsToPackages, otherRefs) = refs.partition { it.to.kind == NodeKind.Package } val mergedPackages = mergePackageReferences(from, refsToPackages) - val (refsToMembers, refsNotToMembers) = usualRefs.partition { it.kind == RefKind.Member } - val mergedMembers = mergeMembers(from, refsToMembers) + val (refsToMembers, refsNotToMembers) = otherRefs.partition { it.kind == RefKind.Member } + val mergedMembers = mergeMemberReferences(from, refsToMembers) - // TODO: think about return mergedPackages + mergedMembers + refsNotToMembers } @@ -156,10 +173,8 @@ class DocumentationMerger( } private fun NodeResolver.update() { - if (this is NodeResolver.Exact) { - if (exactNode != null && exactNode!! in oldToNewNodeMap) { - exactNode = oldToNewNodeMap[exactNode!!] - } + if (this is NodeResolver.Exact && exactNode in oldToNewNodeMap) { + exactNode = oldToNewNodeMap[exactNode]!! } } } \ No newline at end of file diff --git a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt index c25a7069..e5bc32ab 100644 --- a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt +++ b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt @@ -1106,7 +1106,7 @@ fun DocumentationNode.generateAllTypesNode() { val allTypes = members(NodeKind.Package) .flatMap { it.members.filter { it.kind in NodeKind.classLike || it.kind == NodeKind.ExternalClass - || (it.kind == NodeKind.GroupNode && it.members.all { it.kind in NodeKind.classLike }) } } + || (it.kind == NodeKind.GroupNode && it.origins.all { it.kind in NodeKind.classLike }) } } .sortedBy { if (it.kind == NodeKind.ExternalClass) it.name.substringAfterLast('.').toLowerCase() else it.name.toLowerCase() } val allTypesNode = DocumentationNode("alltypes", Content.Empty, NodeKind.AllTypes) diff --git a/core/src/main/kotlin/Model/DocumentationNode.kt b/core/src/main/kotlin/Model/DocumentationNode.kt index 23137364..146c1e99 100644 --- a/core/src/main/kotlin/Model/DocumentationNode.kt +++ b/core/src/main/kotlin/Model/DocumentationNode.kt @@ -84,6 +84,9 @@ open class DocumentationNode(val name: String, get() = references(RefKind.Detail).map { it.to } val members: List get() = references(RefKind.Member).map { it.to } + val origins: List + get() = references(RefKind.Origin).map { it.to } + val inheritedMembers: List get() = references(RefKind.InheritedMember).map { it.to } val allInheritedMembers: List @@ -203,6 +206,7 @@ fun DocumentationNode.append(child: DocumentationNode, kind: RefKind) { RefKind.Detail -> child.addReferenceTo(this, RefKind.Owner) RefKind.Member -> child.addReferenceTo(this, RefKind.Owner) RefKind.Owner -> child.addReferenceTo(this, RefKind.Member) + RefKind.Origin -> child.addReferenceTo(this, RefKind.Owner) else -> { /* Do not add any links back for other types */ } } diff --git a/core/src/main/kotlin/Model/DocumentationReference.kt b/core/src/main/kotlin/Model/DocumentationReference.kt index 282d87d8..e10796d2 100644 --- a/core/src/main/kotlin/Model/DocumentationReference.kt +++ b/core/src/main/kotlin/Model/DocumentationReference.kt @@ -19,7 +19,8 @@ enum class RefKind { Deprecation, TopLevelPage, Platform, - ExternalType + ExternalType, + Origin } data class DocumentationReference(val from: DocumentationNode, val to: DocumentationNode, val kind: RefKind) { @@ -33,7 +34,7 @@ sealed class NodeResolver { } } - class Exact(var exactNode: DocumentationNode?) : NodeResolver() { + class Exact(var exactNode: DocumentationNode) : NodeResolver() { override fun resolve(nodeRephGraph: NodeReferenceGraph): DocumentationNode? { return exactNode } -- cgit From f7975495c64333cdf625dd970254cca2b796d576 Mon Sep 17 00:00:00 2001 From: Zubakov Date: Mon, 27 Aug 2018 16:35:47 +0300 Subject: TODO: remove unnecessary code block --- core/src/main/kotlin/Formats/StructuredFormatService.kt | 1 + 1 file changed, 1 insertion(+) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Formats/StructuredFormatService.kt b/core/src/main/kotlin/Formats/StructuredFormatService.kt index 1ca636ec..1d201677 100644 --- a/core/src/main/kotlin/Formats/StructuredFormatService.kt +++ b/core/src/main/kotlin/Formats/StructuredFormatService.kt @@ -329,6 +329,7 @@ abstract class StructuredOutputBuilder(val to: StringBuilder, } // All items have exactly the same documentation, so we can use any item to render it val item = items.first() + // TODO: remove this block cause there is no one node with OverloadGroupNote detail item.details(NodeKind.OverloadGroupNote).forEach { appendContent(it.content) } -- cgit From 6034c10de4f208484485e6a53daa48cf11800ef5 Mon Sep 17 00:00:00 2001 From: Zubakov Date: Mon, 27 Aug 2018 19:57:34 +0300 Subject: Change render for kotlin mpp signatures rendering --- .../main/kotlin/Formats/StructuredFormatService.kt | 244 +++++++++++++++------ .../main/kotlin/Kotlin/KotlinLanguageService.kt | 2 +- 2 files changed, 173 insertions(+), 73 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Formats/StructuredFormatService.kt b/core/src/main/kotlin/Formats/StructuredFormatService.kt index 1d201677..b57f21be 100644 --- a/core/src/main/kotlin/Formats/StructuredFormatService.kt +++ b/core/src/main/kotlin/Formats/StructuredFormatService.kt @@ -296,7 +296,12 @@ abstract class StructuredOutputBuilder(val to: StringBuilder, } private fun appendDocumentation(overloads: Iterable, isSingleNode: Boolean) { - val breakdownBySummary = overloads.groupByTo(LinkedHashMap()) { node -> node.content } + val breakdownBySummary = overloads.groupByTo(LinkedHashMap()) { node -> + when (node.kind) { + NodeKind.GroupNode -> node.origins.first().content + else -> node.content + } + } if (breakdownBySummary.size == 1) { formatOverloadGroup(breakdownBySummary.values.single(), isSingleNode) @@ -314,18 +319,13 @@ abstract class StructuredOutputBuilder(val to: StringBuilder, private fun formatOverloadGroup(items: List, isSingleNode: Boolean = false) { for ((index, item) in items.withIndex()) { if (index > 0) appendLine() - val rendered = languageService.render(item) - item.detailOrNull(NodeKind.Signature)?.let { - if (item.kind !in NodeKind.classLike || !isSingleNode) - appendAnchor(it.name) - } - appendAsSignature(rendered) { - appendCode { appendContent(rendered) } - item.appendSourceLink() + + if (item.kind == NodeKind.GroupNode) { + renderGroupNode(item, isSingleNode) + } else { + renderSimpleNode(item, isSingleNode) } - item.appendOverrides() - item.appendDeprecation() - item.appendPlatforms() + } // All items have exactly the same documentation, so we can use any item to render it val item = items.first() @@ -334,10 +334,75 @@ abstract class StructuredOutputBuilder(val to: StringBuilder, appendContent(it.content) } - appendContent(item.content.summary) + if (item.kind == NodeKind.GroupNode) { + for (origin in item.origins) { + if (origin.content.isEmpty()) continue + appendParagraph { + appendStrong { to.append("Platform and version requirements:") } + to.append(" " + origin.actualPlatforms) + appendContent(origin.summary) + } + } + } else { + if (!item.content.isEmpty()) { + appendStrong { to.append("Platform and version requirements:") } + to.append(" " + item.actualPlatforms) + appendContent(item.content.summary) + } + } + item.appendDescription() } + + fun renderSimpleNode(item: DocumentationNode, isSingleNode: Boolean) { + // TODO: use summarizesignatures + val rendered = languageService.render(item) + item.detailOrNull(NodeKind.Signature)?.let { + if (item.kind !in NodeKind.classLike || !isSingleNode) + appendAnchor(it.name) + } + appendAsSignature(rendered) { + appendCode { appendContent(rendered) } + item.appendSourceLink() + } + item.appendOverrides() + item.appendDeprecation() + item.appendPlatforms() + } + + fun renderGroupNode(item: DocumentationNode, isSingleNode: Boolean) { + // TODO: use summarizesignatures + val groupBySignature = item.origins.groupBy { + languageService.render(it) + } + + for ((sign, nodes) in groupBySignature) { + val first = nodes.first() + first.detailOrNull(NodeKind.Signature)?.let { + if (item.kind !in NodeKind.classLike || !isSingleNode) + appendAnchor(it.name) + } + + appendAsSignature(sign) { + appendCode { appendContent(sign) } + } + first.appendOverrides() + first.appendDeprecation() + + + appendParagraph { + appendStrong { to.append("Platform and version requirements:") } + to.append(" " + nodes + .flatMap { it.actualPlatforms } + .distinct() + .joinToString() + ) + } + + } + } + private fun DocumentationNode.appendSourceLink() { val sourceUrl = details(NodeKind.SourceUrl).firstOrNull() if (sourceUrl != null) { @@ -362,29 +427,29 @@ abstract class StructuredOutputBuilder(val to: StringBuilder, val deprecationParameter = deprecation!!.details(NodeKind.Parameter).firstOrNull() val deprecationValue = deprecationParameter?.details(NodeKind.Value)?.firstOrNull() appendLine() - if (deprecationValue != null) { - appendStrong { to.append("Deprecated:") } - appendText(" " + deprecationValue.name.removeSurrounding("\"")) - appendLine() - appendLine() - } else if (deprecation?.content != Content.Empty) { - appendStrong { to.append("Deprecated:") } - to.append(" ") - appendContent(deprecation!!.content) - } else { - appendStrong { to.append("Deprecated") } - appendLine() - appendLine() + when { + deprecationValue != null -> { + appendStrong { to.append("Deprecated:") } + appendText(" " + deprecationValue.name.removeSurrounding("\"")) + appendLine() + appendLine() + } + deprecation?.content != Content.Empty -> { + appendStrong { to.append("Deprecated:") } + to.append(" ") + appendContent(deprecation!!.content) + } + else -> { + appendStrong { to.append("Deprecated") } + appendLine() + appendLine() + } } } } private fun DocumentationNode.appendPlatforms() { - val platforms = if (isModuleOrPackage()) - platformsToShow.toSet() + platformsOfItems(members) - else - platformsToShow - + val platforms = actualPlatforms if (platforms.isEmpty()) return appendParagraph { @@ -393,10 +458,19 @@ abstract class StructuredOutputBuilder(val to: StringBuilder, } } + val DocumentationNode.actualPlatforms: Collection + get() = if (isModuleOrPackage()) + platformsToShow.toSet() + platformsOfItems(members) + else + platformsToShow + + + protected fun platformsOfItems(items: List): Set { val platforms = items.asSequence().map { when (it.kind) { - NodeKind.ExternalClass, NodeKind.Package, NodeKind.Module, NodeKind.GroupNode -> platformsOfItems(it.members) + NodeKind.ExternalClass, NodeKind.Package, NodeKind.Module -> platformsOfItems(it.members) + NodeKind.GroupNode -> platformsOfItems(it.origins) else -> it.platformsToShow.toSet() } } @@ -418,7 +492,7 @@ abstract class StructuredOutputBuilder(val to: StringBuilder, val resultVersion = when { allKotlinVersions.size == 1 -> allKotlinVersions.single() minVersion.endsWith("+") -> minVersion - else -> minVersion + "+" + else -> "$minVersion+" } result.intersect(otherPlatforms) + resultVersion @@ -460,6 +534,15 @@ abstract class StructuredOutputBuilder(val to: StringBuilder, } } + inner class SingleNodePageBuilder(val node: DocumentationNode, noHeader: Boolean = false) : + PageBuilder(listOf(node), noHeader) { + + override fun build() { + super.build() + SectionsBuilder(node).build() + } + } + inner class GroupNodePageBuilder(val node: DocumentationNode) : PageBuilder(listOf(node)) { override fun build() { @@ -470,39 +553,29 @@ abstract class StructuredOutputBuilder(val to: StringBuilder, appendLine() appendHeader { appendText(node.name) } - fun DocumentationNode.priority(): Int = when (kind) { - NodeKind.TypeAlias -> 1 - NodeKind.Class -> 2 - else -> 3 - } - - for (member in node.members.sortedBy(DocumentationNode::priority)) { - - appendAsOverloadGroup(to, platformsOfItems(listOf(member))) { - formatSubNodeOfGroup(member) - } + renderGroupNode(node, true) + for (origin in node.origins) { + if (origin.content.isEmpty()) continue + appendStrong { to.append("Platform and version requirements:") } + to.append(" " + origin.actualPlatforms) + appendContent(origin.content.summary) } - } - fun formatSubNodeOfGroup(member: DocumentationNode) { - SingleNodePageBuilder(member, true).build() + SectionsBuilder(node).build() } } - inner class SingleNodePageBuilder(val node: DocumentationNode, noHeader: Boolean = false) - : PageBuilder(listOf(node), noHeader) { + inner class SectionsBuilder(val node: DocumentationNode): PageBuilder(listOf(node)) { override fun build() { - super.build() - if (node.kind == NodeKind.ExternalClass) { appendSection("Extensions for ${node.name}", node.members) return } fun DocumentationNode.membersOrGroupMembers(predicate: (DocumentationNode) -> Boolean): List { - return members.filter(predicate) + members(NodeKind.GroupNode).flatMap { it.members.filter(predicate) } + return members.filter(predicate) + members(NodeKind.GroupNode).filter{ it.origins.isNotEmpty() && predicate(it.origins.first()) } } fun DocumentationNode.membersOrGroupMembers(kind: NodeKind): List { @@ -510,10 +583,9 @@ abstract class StructuredOutputBuilder(val to: StringBuilder, } appendSection("Packages", node.members(NodeKind.Package), platformsBasedOnMembers = true) - appendSection("Types", node.membersOrGroupMembers { it.kind in NodeKind.classLike && it.kind != NodeKind.TypeAlias && it.kind != NodeKind.AnnotationClass && it.kind != NodeKind.Exception }) + appendSection("Types", node.membersOrGroupMembers { it.kind in NodeKind.classLike /*&& it.kind != NodeKind.TypeAlias*/ && it.kind != NodeKind.AnnotationClass && it.kind != NodeKind.Exception }) appendSection("Annotations", node.membersOrGroupMembers(NodeKind.AnnotationClass)) appendSection("Exceptions", node.membersOrGroupMembers(NodeKind.Exception)) - appendSection("Type Aliases", node.membersOrGroupMembers(NodeKind.TypeAlias)) appendSection("Extensions for External Classes", node.members(NodeKind.ExternalClass)) appendSection("Enum Values", node.membersOrGroupMembers(NodeKind.EnumItem), sortMembers = false, omitSamePlatforms = true) appendSection("Constructors", node.membersOrGroupMembers(NodeKind.Constructor), omitSamePlatforms = true) @@ -558,7 +630,7 @@ abstract class StructuredOutputBuilder(val to: StringBuilder, if (node.kind == NodeKind.Module) { appendHeader(3) { to.append("Index") } node.members(NodeKind.AllTypes).singleOrNull()?.let { allTypes -> - appendLink(link(node, allTypes, { "All Types" })) + appendLink(link(node, allTypes) { "All Types" }) } } } @@ -594,11 +666,12 @@ abstract class StructuredOutputBuilder(val to: StringBuilder, } } appendTableCell { - val breakdownBySummary = members.groupBy { it.summary } - for ((summary, items) in breakdownBySummary) { - appendSummarySignatures(items) - appendContent(summary) + val nodesToAppend = if (members.all { it.kind == NodeKind.GroupNode }) { + members.flatMap { it.origins } + } else { + members } + appendSummarySignatures(nodesToAppend, platformsBasedOnMembers, omitSamePlatforms) } } } @@ -614,27 +687,48 @@ abstract class StructuredOutputBuilder(val to: StringBuilder, return emptySet() } - private fun appendSummarySignatures(items: List) { + private fun appendSummarySignatures(items: List, platformsBasedOnMembers: Boolean, omitSamePlatforms: Boolean) { val summarySignature = languageService.summarizeSignatures(items) if (summarySignature != null) { - appendAsSignature(summarySignature) { - summarySignature.appendSignature() - } + appendSummarySignature(summarySignature, items, platformsBasedOnMembers, omitSamePlatforms) return } - val renderedSignatures = items.map { languageService.render(it, RenderMode.SUMMARY) } - renderedSignatures.subList(0, renderedSignatures.size - 1).forEach { - appendAsSignature(it) { - it.appendSignature() - } - appendLine() + + + val groupBySignature = items.groupBy { + languageService.render(it, RenderMode.SUMMARY) } - appendAsSignature(renderedSignatures.last()) { - renderedSignatures.last().appendSignature() + for ((sign, node) in groupBySignature) { + appendSummarySignature(sign, node, platformsBasedOnMembers, omitSamePlatforms) } } + + private fun appendSummarySignature(signature: ContentNode, items: List, platformsBasedOnMembers: Boolean, omitSamePlatforms: Boolean) { + val elementPlatforms = platformsOfItems(items, omitSamePlatforms) + val platforms = if (platformsBasedOnMembers) + items.flatMapTo(mutableSetOf()) { platformsOfItems(it.members) } + elementPlatforms + else + elementPlatforms + + appendPlatforms(platforms) + appendAsSignature(signature) { + signature.appendSignature() + } + + appendContent(items.first().summary) + appendSoftLineBreak() + } } + private fun DocumentationNode.isClassLikeGroupNode(): Boolean { + if (kind != NodeKind.GroupNode) { + return false + } + + return origins.all { it.kind in NodeKind.classLike } + } + + inner class AllTypesNodeBuilder(val node: DocumentationNode) : PageBuilder(listOf(node)) { @@ -658,7 +752,13 @@ abstract class StructuredOutputBuilder(val to: StringBuilder, } } appendTableCell { - appendContent(type.summary) + val summary = if (type.isClassLikeGroupNode()) { + type.origins.first().summary + } else { + type.summary + } + + appendContent(summary) } } } diff --git a/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt b/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt index 6088d3a5..5b565464 100644 --- a/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt +++ b/core/src/main/kotlin/Kotlin/KotlinLanguageService.kt @@ -198,7 +198,7 @@ class KotlinLanguageService : CommonLanguageService() { nowrap: Boolean ) { when (node.name) { - "final", "public", "var" -> { + "final", "public", "var", "expect", "actual" -> { } else -> { if (node.name !in fullOnlyModifiers || renderMode == RenderMode.FULL) { -- cgit From a4ae451279b4f89b9994d333c6d6d88a0868c5e4 Mon Sep 17 00:00:00 2001 From: Zubakov Date: Mon, 27 Aug 2018 21:35:29 +0300 Subject: Drop unnecessary properties in SourceRoot --- core/src/main/kotlin/Generation/configurationImpl.kt | 15 ++------------- .../src/main/kotlin/org/jetbrains/dokka/configuration.kt | 2 -- runners/ant/src/main/kotlin/ant/dokka.kt | 8 +++----- runners/gradle-plugin/src/main/kotlin/main.kt | 8 +------- runners/maven-plugin/src/main/kotlin/DokkaMojo.kt | 7 ------- 5 files changed, 6 insertions(+), 34 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Generation/configurationImpl.kt b/core/src/main/kotlin/Generation/configurationImpl.kt index f2a91002..2aa0e0d7 100644 --- a/core/src/main/kotlin/Generation/configurationImpl.kt +++ b/core/src/main/kotlin/Generation/configurationImpl.kt @@ -18,22 +18,11 @@ data class SourceLinkDefinitionImpl(override val path: String, } } -class SourceRootImpl(path: String, override val platforms: List = emptyList(), - override val analysisPlatform: Platform = Platform.DEFAULT) : SourceRoot { +class SourceRootImpl(path: String) : SourceRoot { override val path: String = File(path).absolutePath companion object { - fun parseSourceRoot(sourceRoot: String): SourceRoot { - val components = sourceRoot.split("::", limit = 2) - - val platform = if (components.size == 1) { - Platform.DEFAULT - } else { - Platform.fromString(components[0]) - } - - return SourceRootImpl(components.last(), emptyList(), platform) - } + fun parseSourceRoot(sourceRoot: String): SourceRoot = SourceRootImpl(sourceRoot) } } diff --git a/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt b/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt index e0fa27d1..5f1f4bb0 100644 --- a/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt +++ b/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt @@ -73,8 +73,6 @@ interface DokkaConfiguration { interface SourceRoot { val path: String - val platforms: List - val analysisPlatform: Platform } interface SourceLinkDefinition { diff --git a/runners/ant/src/main/kotlin/ant/dokka.kt b/runners/ant/src/main/kotlin/ant/dokka.kt index 9428a7ce..8be9246f 100644 --- a/runners/ant/src/main/kotlin/ant/dokka.kt +++ b/runners/ant/src/main/kotlin/ant/dokka.kt @@ -17,11 +17,9 @@ class AntLogger(val task: Task): DokkaLogger { class AntSourceLinkDefinition(var path: String? = null, var url: String? = null, var lineSuffix: String? = null) -class AntSourceRoot(var path: String? = null, var platforms: String? = null, - var platform: Platform = Platform.DEFAULT) { - fun toSourceRoot(): SourceRootImpl? = path?.let { - path -> - SourceRootImpl(path, platforms?.split(',').orEmpty(), platform) +class AntSourceRoot(var path: String? = null) { + fun toSourceRoot(): SourceRootImpl? = path?.let { path -> + SourceRootImpl(path) } } diff --git a/runners/gradle-plugin/src/main/kotlin/main.kt b/runners/gradle-plugin/src/main/kotlin/main.kt index 9c8fd652..91639e11 100644 --- a/runners/gradle-plugin/src/main/kotlin/main.kt +++ b/runners/gradle-plugin/src/main/kotlin/main.kt @@ -403,13 +403,7 @@ class SourceRoot : DokkaConfiguration.SourceRoot, Serializable { field = File(value).absolutePath } - override var platforms: List = arrayListOf() - - override val analysisPlatform: Platform = Platform.DEFAULT - - override fun toString(): String { - return "${platforms.joinToString()}::$path" - } + override fun toString(): String = path } open class LinkMapping : Serializable, DokkaConfiguration.SourceLinkDefinition { diff --git a/runners/maven-plugin/src/main/kotlin/DokkaMojo.kt b/runners/maven-plugin/src/main/kotlin/DokkaMojo.kt index 78fd2d86..a2771306 100644 --- a/runners/maven-plugin/src/main/kotlin/DokkaMojo.kt +++ b/runners/maven-plugin/src/main/kotlin/DokkaMojo.kt @@ -36,13 +36,6 @@ abstract class AbstractDokkaMojo : AbstractMojo() { class SourceRoot : DokkaConfiguration.SourceRoot { @Parameter(required = true) override var path: String = "" - - @Parameter - override var platforms: List = emptyList() - - @Parameter - override var analysisPlatform: Platform = Platform.DEFAULT - } class PackageOptions : DokkaConfiguration.PackageOptions { -- cgit From 0df19264ccae3d294946caf634ee15eea0c4fe4a Mon Sep 17 00:00:00 2001 From: Zubakov Date: Thu, 6 Sep 2018 19:44:50 +0300 Subject: Minor refactoring, kotlin-website format change: add platforms to summary signatures, platform evaluating logic change --- .../Formats/KotlinWebsiteHtmlFormatService.kt | 7 ++ .../main/kotlin/Formats/StructuredFormatService.kt | 123 +++++++++++++++------ core/src/main/kotlin/Model/DocumentationNode.kt | 6 +- 3 files changed, 103 insertions(+), 33 deletions(-) (limited to 'core/src/main/kotlin') diff --git a/core/src/main/kotlin/Formats/KotlinWebsiteHtmlFormatService.kt b/core/src/main/kotlin/Formats/KotlinWebsiteHtmlFormatService.kt index 6ced75b5..16bec5a6 100644 --- a/core/src/main/kotlin/Formats/KotlinWebsiteHtmlFormatService.kt +++ b/core/src/main/kotlin/Formats/KotlinWebsiteHtmlFormatService.kt @@ -169,6 +169,13 @@ open class KotlinWebsiteHtmlOutputBuilder( appendContent(section) } } + + override fun appendAsBlockWithPlatforms(platforms: Set, block: () -> Unit) { + if (platforms.isNotEmpty()) + wrap("", "", block) + else + block() + } } class KotlinWebsiteHtmlFormatService @Inject constructor( diff --git a/core/src/main/kotlin/Formats/StructuredFormatService.kt b/core/src/main/kotlin/Formats/StructuredFormatService.kt index b57f21be..53172563 100644 --- a/core/src/main/kotlin/Formats/StructuredFormatService.kt +++ b/core/src/main/kotlin/Formats/StructuredFormatService.kt @@ -83,6 +83,10 @@ abstract class StructuredOutputBuilder(val to: StringBuilder, } } + open fun appendAsBlockWithPlatforms(platforms: Set, block: () -> Unit) { + block() + } + open fun appendSymbol(text: String) { appendText(text) } @@ -465,6 +469,18 @@ abstract class StructuredOutputBuilder(val to: StringBuilder, platformsToShow + protected fun mergeVersions(otherKotlinVersion: String, kotlinVersions: List): String { + val allKotlinVersions = (kotlinVersions + otherKotlinVersion).distinct() + + val minVersion = allKotlinVersions.min()!! + val resultVersion: String = when { + allKotlinVersions.size == 1 -> allKotlinVersions.single() + minVersion.endsWith("+") -> minVersion + else -> "$minVersion+" + } + + return resultVersion + } protected fun platformsOfItems(items: List): Set { val platforms = items.asSequence().map { @@ -486,19 +502,38 @@ abstract class StructuredOutputBuilder(val to: StringBuilder, // When no Kotlin version specified, it means that version is 1.0 if (otherKotlinVersion != null && kotlinVersions.isNotEmpty()) { - val allKotlinVersions = (kotlinVersions + otherKotlinVersion).distinct() + result.intersect(platformsOfItem) + mergeVersions(otherKotlinVersion, kotlinVersions) + } else { + result.intersect(platformsOfItem) + } + } + } - val minVersion = allKotlinVersions.min()!! - val resultVersion = when { - allKotlinVersions.size == 1 -> allKotlinVersions.single() - minVersion.endsWith("+") -> minVersion - else -> "$minVersion+" - } + protected fun unionPlatformsOfItems(items: List): Set { + val platforms = items.asSequence().map { + when (it.kind) { + NodeKind.GroupNode -> unionPlatformsOfItems(it.origins) + else -> it.platformsToShow.toSet() + } + } + + fun String.isKotlinVersion() = this.startsWith("Kotlin") + + if (platforms.count() == 0) return emptySet() + + // Calculating common platforms for items + return platforms.reduce { result, platformsOfItem -> + val otherKotlinVersion = result.find { it.isKotlinVersion() } + val (kotlinVersions, otherPlatforms) = platformsOfItem.partition { it.isKotlinVersion() } - result.intersect(otherPlatforms) + resultVersion + // When no Kotlin version specified, it means that version is 1.0 + if (otherKotlinVersion != null && kotlinVersions.isNotEmpty()) { + result.union(otherPlatforms) + mergeVersions(otherKotlinVersion, kotlinVersions) } else { - result.intersect(platformsOfItem) + result.union(otherPlatforms) } + }.let { + if (it.containsAll(impliedPlatforms)) it - impliedPlatforms else it } } @@ -566,6 +601,17 @@ abstract class StructuredOutputBuilder(val to: StringBuilder, } } + private fun unionPlatformsOfItems(items: List): Set { + val platforms = items.flatMapTo(mutableSetOf()) { + when (it.kind) { + NodeKind.GroupNode -> unionPlatformsOfItems(it.origins) + else -> it.platforms + } + } + + return platforms.let { if (it.containsAll(impliedPlatforms)) it - impliedPlatforms else it } + } + inner class SectionsBuilder(val node: DocumentationNode): PageBuilder(listOf(node)) { override fun build() { @@ -666,12 +712,7 @@ abstract class StructuredOutputBuilder(val to: StringBuilder, } } appendTableCell { - val nodesToAppend = if (members.all { it.kind == NodeKind.GroupNode }) { - members.flatMap { it.origins } - } else { - members - } - appendSummarySignatures(nodesToAppend, platformsBasedOnMembers, omitSamePlatforms) + appendSummarySignatures(members, platformsBasedOnMembers, omitSamePlatforms) } } } @@ -680,6 +721,10 @@ abstract class StructuredOutputBuilder(val to: StringBuilder, } private fun platformsOfItems(items: List, omitSamePlatforms: Boolean = true): Set { + if (items.all { it.kind != NodeKind.Package && it.kind != NodeKind.Module && it.kind != NodeKind.ExternalClass }) { + return unionPlatformsOfItems(items) + } + val platforms = platformsOfItems(items) if (platforms.isNotEmpty() && (platforms != node.platformsToShow.toSet() || !omitSamePlatforms)) { return platforms @@ -688,35 +733,49 @@ abstract class StructuredOutputBuilder(val to: StringBuilder, } private fun appendSummarySignatures(items: List, platformsBasedOnMembers: Boolean, omitSamePlatforms: Boolean) { - val summarySignature = languageService.summarizeSignatures(items) - if (summarySignature != null) { - appendSummarySignature(summarySignature, items, platformsBasedOnMembers, omitSamePlatforms) - return - } + val groupBySummary = items.groupBy { it.summary } + for ((summary, node) in groupBySummary) { + val nodesToAppend = if (node.all { it.kind == NodeKind.GroupNode }) { + node.flatMap { it.origins } + } else { + node + } - val groupBySignature = items.groupBy { - languageService.render(it, RenderMode.SUMMARY) - } - for ((sign, node) in groupBySignature) { - appendSummarySignature(sign, node, platformsBasedOnMembers, omitSamePlatforms) + val summarySignature = languageService.summarizeSignatures(nodesToAppend) + if (summarySignature != null) { + appendSignatures(summarySignature, items, platformsBasedOnMembers, omitSamePlatforms) + } else { + val groupBySignature = nodesToAppend.groupBy { + languageService.render(it, RenderMode.SUMMARY) + } + for ((sign, members) in groupBySignature) { + appendSignatures(sign, members, platformsBasedOnMembers, omitSamePlatforms) + } + } + + val platforms = platformsOfItems(node) + appendAsBlockWithPlatforms(platforms) { + appendContent(summary) + appendSoftLineBreak() + } } } - private fun appendSummarySignature(signature: ContentNode, items: List, platformsBasedOnMembers: Boolean, omitSamePlatforms: Boolean) { + private fun appendSignatures(signature: ContentNode, items: List, platformsBasedOnMembers: Boolean, omitSamePlatforms: Boolean) { val elementPlatforms = platformsOfItems(items, omitSamePlatforms) val platforms = if (platformsBasedOnMembers) items.flatMapTo(mutableSetOf()) { platformsOfItems(it.members) } + elementPlatforms else elementPlatforms - appendPlatforms(platforms) - appendAsSignature(signature) { - signature.appendSignature() + appendAsBlockWithPlatforms(platforms) { + appendPlatforms(platforms) + appendAsSignature(signature) { + signature.appendSignature() + } + appendSoftLineBreak() } - - appendContent(items.first().summary) - appendSoftLineBreak() } } diff --git a/core/src/main/kotlin/Model/DocumentationNode.kt b/core/src/main/kotlin/Model/DocumentationNode.kt index 146c1e99..f2b3a937 100644 --- a/core/src/main/kotlin/Model/DocumentationNode.kt +++ b/core/src/main/kotlin/Model/DocumentationNode.kt @@ -76,7 +76,11 @@ open class DocumentationNode(val name: String, var content: Content = content private set - val summary: ContentNode get() = content.summary + val summary: ContentNode get() = when (kind) { + NodeKind.GroupNode -> this.origins.first().summary + else -> content.summary + } + val owner: DocumentationNode? get() = references(RefKind.Owner).singleOrNull()?.to -- cgit