blob: baf449041c926652f4b7c7f081e31b32178b063a (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
package org.jetbrains.dokka.Samples
import com.google.inject.Inject
import com.intellij.psi.PsiElement
import org.jetbrains.dokka.*
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.ImportPath
open class KotlinWebsiteSampleProcessingService
@Inject constructor(options: DocumentationOptions,
logger: DokkaLogger,
resolutionFacade: DokkaResolutionFacade)
: DefaultSampleProcessingService(options, logger, resolutionFacade) {
private class SampleBuilder() : KtVisitorVoid() {
val builder = StringBuilder()
val text: String
get() = builder.toString()
fun convertAssertPrints(expression: KtCallExpression) {
val (argument, commentArgument) = expression.valueArguments
val comment = commentArgument.getArgumentExpression() as KtStringTemplateExpression
val commentText = comment.entries.joinToString("") { it.text }
builder.apply {
append("println(")
append(argument.text)
append(") // ")
append(commentText)
}
}
fun convertAssertTrue(expression: KtCallExpression) {
val (argument) = expression.valueArguments
builder.apply {
append("println(\"")
append(argument.text)
append(" is \${")
append(argument.text)
append("}\") // true")
}
}
override fun visitCallExpression(expression: KtCallExpression) {
when (expression.calleeExpression?.text) {
"assertPrints" -> convertAssertPrints(expression)
"assertTrue" -> convertAssertTrue(expression)
else -> super.visitCallExpression(expression)
}
}
override fun visitElement(element: PsiElement?) {
if (element != null) {
if (element.children.isEmpty())
builder.append(element.text)
else
element.acceptChildren(this)
}
}
}
private fun PsiElement.buildSampleText(): String {
val sampleBuilder = SampleBuilder()
this.accept(sampleBuilder)
return sampleBuilder.text
}
val importsToIgnore = arrayOf("samples.*").map(::ImportPath)
override fun processImports(psiElement: PsiElement): ContentBlockCode {
val psiFile = psiElement.containingFile
if (psiFile is KtFile) {
return ContentBlockCode("kotlin").apply {
psiFile.importList?.let {
it.children.filter {
it !is KtImportDirective || it.importPath !in importsToIgnore
}.forEach { append(ContentText(it.text)) }
}
}
}
return super.processImports(psiElement)
}
override fun processSampleBody(psiElement: PsiElement) = when (psiElement) {
is KtDeclarationWithBody -> {
val bodyExpression = psiElement.bodyExpression
val bodyExpressionText = bodyExpression!!.buildSampleText()
when (bodyExpression) {
is KtBlockExpression -> bodyExpressionText.removeSurrounding("{", "}")
else -> bodyExpressionText
}
}
else -> psiElement.buildSampleText()
}
}
|