Browse Source

Change import hoisting to only hoist imports in Kotlin blocks

Prevents imports in plain text (e.g. a code sample) from unintentionally being hoisted)
master
Shadowfacts 4 years ago
parent
commit
c52b10bea3
Signed by: shadowfacts GPG Key ID: 94A5AB95422746E5
  1. 11
      src/main/kotlin/net/shadowfacts/ekt/EKT.kt
  2. 16
      src/test/kotlin/net/shadowfacts/ekt/Test.kt
  3. 4
      src/test/resources/templates/template.ekt

11
src/main/kotlin/net/shadowfacts/ekt/EKT.kt

@ -52,6 +52,13 @@ _result.toString()
@Suppress("NAME_SHADOWING")
var template = template
val lines = template.split("\n")
val isImport: (String) -> Boolean = {
val trimmed = it.trim()
trimmed.startsWith("[: import") || trimmed.startsWith("[:import")
}
val imports = lines.filter(isImport).joinToString("\n") { it.substring(2, it.length - 2) }
template = lines.filterNot(isImport).joinToString("\n")
template = template.replace("$", "\${'$'}")
template = ":]$template[:"
template = template.replace(startStringRegex, {
@ -71,10 +78,6 @@ _result.toString()
}
})
val lines = template.split("\n")
val imports = lines.filter { it.trim().startsWith("import") }.joinToString("\n")
template = lines.filterNot { it.trim().startsWith("import") }.joinToString("\n")
val script = imports + scriptPrefix + template + scriptSuffix
if (env.cacheDir != null) {

16
src/test/kotlin/net/shadowfacts/ekt/Test.kt

@ -8,14 +8,16 @@ import kotlin.concurrent.thread
* @author shadowfacts
*/
fun main(args: Array<String>) {
println(ManagementFactory.getRuntimeMXBean().name)
File("output.txt").writeText(render())
for (i in 0..99) {
println("Rendering $i")
render()
}
println("done")
// println(ManagementFactory.getRuntimeMXBean().name)
//
// for (i in 0..99) {
// println("Rendering $i")
// render()
// }
//
// println("done")
// thread {
// for (i in 0..30) {

4
src/test/resources/templates/template.ekt

@ -8,6 +8,10 @@ Environment type: [= _env::class.simpleName =]
Sum: [= list.sum() =]
<pre>
import a.b.c;
</pre>
[:
include("include") {
"foo" to "bar"

Loading…
Cancel
Save