1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
|
package org.jetbrains.dokka.Samples
import com.google.inject.Inject
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.*
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,
logger: DokkaLogger,
resolutionFacade: DokkaResolutionFacade)
: DefaultSampleProcessingService(dokkaConfiguration, logger, resolutionFacade) {
private class SampleBuilder : KtTreeVisitorVoid() {
val builder = StringBuilder()
val text: String
get() = builder.toString()
val errors = mutableListOf<ConvertError>()
data class ConvertError(val e: Exception, val text: String, val loc: String)
fun KtValueArgument.extractStringArgumentValue() =
(getArgumentExpression() as KtStringTemplateExpression)
.entries.joinToString("") { it.text }
fun convertAssertPrints(expression: KtCallExpression) {
val (argument, commentArgument) = expression.valueArguments
builder.apply {
append("println(")
append(argument.text)
append(") // ")
append(commentArgument.extractStringArgumentValue())
}
}
fun convertAssertTrueFalse(expression: KtCallExpression, expectedResult: Boolean) {
val (argument) = expression.valueArguments
builder.apply {
expression.valueArguments.getOrNull(1)?.let {
append("// ${it.extractStringArgumentValue()}")
val ws = expression.prevLeaf { it is PsiWhiteSpace }
append(ws?.text ?: "\n")
}
append("println(\"")
append(argument.text)
append(" is \${")
append(argument.text)
append("}\") // $expectedResult")
}
}
fun convertAssertFails(expression: KtCallExpression) {
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 = funcArgument.extractFunctionalArgumentText()
append(argument.lines().joinToString(separator = "\n") { "// $it" })
append(" // ")
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 = funcArgument.extractFunctionalArgumentText()
append(argument.lines().joinToString(separator = "\n") { "// $it" })
append(" // will fail with ")
append(exceptionType.text)
}
}
override fun visitCallExpression(expression: KtCallExpression) {
when (expression.calleeExpression?.text) {
"assertPrints" -> convertAssertPrints(expression)
"assertTrue" -> convertAssertTrueFalse(expression, expectedResult = true)
"assertFalse" -> convertAssertTrueFalse(expression, expectedResult = false)
"assertFails" -> convertAssertFails(expression)
"assertFailsWith" -> convertAssertFailsWith(expression)
else -> super.visitCallExpression(expression)
}
}
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)
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
}
val importsToIgnore = arrayOf("samples.*").map { ImportPath.fromString(it) }
override fun processImports(psiElement: PsiElement): ContentBlockCode {
val psiFile = psiElement.containingFile
if (psiFile is KtFile) {
return ContentBlockCode("kotlin").apply {
append(ContentText("\n"))
psiFile.importList?.let {
it.allChildren.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()
}
}
|