/
generateTestDataForReservedWords.kt
398 lines (308 loc) · 11.4 KB
/
generateTestDataForReservedWords.kt
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
/*
* Copyright 2010-2015 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.
*/
package org.jetbrains.kotlin.generators.tests.reservedWords
import com.google.dart.compiler.backend.js.ast.JsFunctionScope
import org.jetbrains.kotlin.generators.util.GeneratorsFileUtil
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.renderer.KeywordStringsGenerated
import java.io.File
val MODIFIER_KEYWORDS = KtTokens.MODIFIER_KEYWORDS_ARRAY.map { it.getValue() }.toSet()
val commonCases: CaseBuilder.(String, String) -> Unit = { testByName, testByRef ->
case("val", "val $KEYWORD_MARKER: Int", " = 0", testByName)
case("var", "var $KEYWORD_MARKER: Int", " = 0", testByName)
case("fun", "fun $KEYWORD_MARKER()", " { $KEYWORD_MARKER() }", testByRef)
case("funParam",
"fun foo($KEYWORD_MARKER: String)", """ {
assertEquals("123", $KEYWORD_MARKER)
$testRenamedByName
}""", "foo(\"123\")")
case("label", "val t: Int", " = 0", "testRenamed(\"$KEYWORD_MARKER\", { $KEYWORD_MARKER@ while (false) {} })")
}
val commonCasesWithTestNotRenamed: CaseBuilder.() -> Unit = { commonCases(testNotRenamedByName, testNotRenamedByRef) }
fun main(args: Array<String>) {
generateTestDataForReservedWords()
}
val TEST_DATA_DIR_FOR_RESERVED_WORDS = "js/js.translator/testData/reservedWords/cases"
fun generateTestDataForReservedWords() {
generate(TEST_DATA_DIR_FOR_RESERVED_WORDS) {
suite("toplevel",
"""
$DEFINITION_MARKER
fun box(): String {
$TEST_BLOCK_MARKER
return "OK"
}"""
) {
commonCasesWithTestNotRenamed()
case("class", "class $KEYWORD_MARKER { companion object {} }", "", testNotRenamedByName)
case("interface", "interface $KEYWORD_MARKER { companion object {} }", "", testNotRenamedByName)
case("enum", "enum class $KEYWORD_MARKER { foo }", "", testNotRenamed("$KEYWORD_MARKER.foo"))
case("object", "object $KEYWORD_MARKER {}", "", testNotRenamedByName)
}
// -------------------------
suite("local",
"""
fun box(): String {
$DEFINITION_MARKER
$TEST_BLOCK_MARKER
return "OK"
}"""
) {
commonCases(testRenamedByName, testRenamedByRef)
case("catch", "", "",
"""
try {
throw Exception()
}
catch($KEYWORD_MARKER: Exception) {
$testRenamedByName
}""")
}
// -------------------------
suite("insideClass",
"""
class TestClass {
$DEFINITION_MARKER
fun test() {
$TEST_BLOCK_MARKER
}
}
fun box(): String {
TestClass().test()
return "OK"
}""", commonCasesWithTestNotRenamed)
// -------------------------
suite("insideClassObject",
"""
class TestClass {
companion object {
$DEFINITION_MARKER
fun test() {
$TEST_BLOCK_MARKER
}
}
}
fun box(): String {
TestClass.test()
return "OK"
}""", commonCasesWithTestNotRenamed)
// -------------------------
suite("insideObject",
"""
object TestObject {
$DEFINITION_MARKER
fun test() {
$TEST_BLOCK_MARKER
}
}
fun box(): String {
TestObject.test()
return "OK"
}""", commonCasesWithTestNotRenamed)
// -------------------------
suite("dataClass",
"""
data class DataClass($DEFINITION_MARKER: String) {
init {
$TEST_BLOCK_MARKER
}
}
fun box(): String {
DataClass("123")
return "OK"
}"""
) {
case("val", "val $KEYWORD_MARKER", "", testNotRenamedByName)
case("var", "var $KEYWORD_MARKER", "", testNotRenamedByName)
case("param", "$KEYWORD_MARKER", "", testRenamedByName, ignore = true)
}
// -------------------------
suite("delegated",
"""
interface Trait {
$DECLARATION_MARKER
}
class TraitImpl : Trait {
override $DEFINITION_MARKER
}
class TestDelegate : Trait by TraitImpl() {
fun test() {
$TEST_BLOCK_MARKER
}
}
fun box(): String {
TestDelegate().test()
return "OK"
}""", commonCasesWithTestNotRenamed)
// -------------------------
suite("enum",
"""
enum class Foo {
BAR;
$DEFINITION_MARKER
fun test() {
$TEST_BLOCK_MARKER
}
}
fun box(): String {
Foo.BAR.test()
return "OK"
}""", commonCasesWithTestNotRenamed)
// -------------------------
suite("enum",
"""
enum class Foo {
$KEYWORD_MARKER
}
fun box(): String {
${testNotRenamed("Foo.$KEYWORD_MARKER")}
return "OK"
}"""
) {
case("entry", "", "", "", additionalShouldBeEscaped = MODIFIER_KEYWORDS)
}
// -------------------------
}
}
// DSL
class Case(
val name: String,
val testDeclaration: String,
val testDeclarationInit: String,
val testBlock: String,
val ignore: Boolean,
val additionalShouldBeEscaped: Set<String>
)
class Suite(
val name: String,
val code: String,
val cases: List<Case>
)
class CaseBuilder {
val cases = arrayListOf<Case>()
fun case(name: String, testDeclaration: String, testDeclarationInit: String, testBlock: String,
ignore: Boolean = false, additionalShouldBeEscaped: Set<String> = setOf()) {
cases.add(Case(name, testDeclaration, testDeclarationInit, testBlock, ignore, additionalShouldBeEscaped))
}
}
class TestDataBuilder() {
val suites = arrayListOf<Suite>()
fun suite(name: String, code: String, f: CaseBuilder.() -> Unit) {
val builder = CaseBuilder()
builder.f()
suites.add(Suite(name, PREAMBLE + code, builder.cases))
}
fun generate(testDataDirPath: String) {
fun File.readLinesOrNull() = if (!exists()) null else readLines()
val testDataDir = File(testDataDirPath)
val cases = suites.flatMap { suite -> suite.cases.map { case -> suite.name + " / " + case.name } }.sorted()
val shouldBeEscapedFile = File("$testDataDirPath/SHOULD_BE_ESCAPED.txt")
val shouldNotBeEscapedFile = File("$testDataDirPath/SHOULD_NOT_BE_ESCAPED.txt")
val casesFile = File("$testDataDirPath/CASES.txt")
val shouldBeEscapedFromFile = shouldBeEscapedFile.readLinesOrNull()?.drop(1)
val shouldNotBeEscapedFromFile = shouldNotBeEscapedFile.readLinesOrNull()?.drop(1)
val casesFromFile = casesFile.readLinesOrNull()?.drop(1)
val isCreatingFromScratch = shouldBeEscapedFromFile != SHOULD_BE_ESCAPED || shouldNotBeEscapedFromFile != SHOULD_NOT_BE_ESCAPED || casesFromFile != cases
if (!testDataDir.exists() && !testDataDir.mkdirs()) {
error("Unable to find or create test data directory: '$testDataDirPath'.")
}
else if (isCreatingFromScratch) {
if (testDataDir.listFiles()?.all { it.delete() } ?: true) {
println("Create testdata files from scratch.")
}
else {
error("Can not clean testdata directory.")
}
}
for (suite in suites) {
for (case in suite.cases) {
// Uses small portions of keywords instead of ALL_KEYWORDS to avoid a combinatorial explosion
// Each portion contains at least one keyword which should be escaped and at least one which should not.
for (keyword in nextKeywordPortion()) {
if (case.ignore) {
continue
}
val shouldBeEscaped = keyword in SHOULD_BE_ESCAPED || keyword in case.additionalShouldBeEscaped
val keywordWithEscapeIfNeed = if (shouldBeEscaped) "`$keyword`" else keyword
val out = suite.code
.replace(DEFINITION_MARKER, case.testDeclaration + case.testDeclarationInit)
.replace(DECLARATION_MARKER, case.testDeclaration)
.replace(DECLARATION_INIT_MARKER, case.testDeclarationInit)
.replace(TEST_BLOCK_MARKER, case.testBlock)
.replace("\"$KEYWORD_MARKER\"", "\"$keyword\"")
.replace(KEYWORD_MARKER, keywordWithEscapeIfNeed)
val fileName = "${suite.name.decapitalize()}${case.name.capitalize()}${keyword.capitalize()}.kt"
val testDataFile = File(testDataDirPath + "/" + fileName)
if (testDataFile.exists()) {
if (isCreatingFromScratch) {
error("The file '$fileName' unexpectedly exists when create test data from scratch.")
}
} else if (!isCreatingFromScratch) {
error("Unexpected new testdata file: '$fileName'. It may cause for example because of bug in stdlib.")
}
GeneratorsFileUtil.writeFileIfContentChanged(testDataFile, out, false)
}
}
}
if (isCreatingFromScratch) {
shouldBeEscapedFile.writeText("$PREAMBLE_MESSAGE\n${SHOULD_BE_ESCAPED.joinToString("\n")}")
shouldNotBeEscapedFile.writeText("$PREAMBLE_MESSAGE\n${SHOULD_NOT_BE_ESCAPED.joinToString("\n")}")
casesFile.writeText("$PREAMBLE_MESSAGE\n${cases.joinToString("\n")}")
}
}
}
fun generate(testDataDirPath: String, f: TestDataBuilder.() -> Unit) {
val builder = TestDataBuilder()
builder.f()
builder.generate(testDataDirPath)
}
val DEFINITION_MARKER = "DEFINITION"
val DECLARATION_MARKER = "DECLARATION"
val DECLARATION_INIT_MARKER = "DECLARATION_INIT"
val TEST_BLOCK_MARKER = "TEST_BLOCK"
val KEYWORD_MARKER = "KEYWORD"
val PREAMBLE_MESSAGE = "NOTE THIS FILE IS AUTO-GENERATED by the generateTestDataForReservedWords.kt. DO NOT EDIT!"
val PREAMBLE = """package foo
// $PREAMBLE_MESSAGE
"""
fun testRenamed(reference: String = "$KEYWORD_MARKER") = "testRenamed(\"$KEYWORD_MARKER\", { $reference })"
fun testNotRenamed(reference: String = "$KEYWORD_MARKER") = "testNotRenamed(\"$KEYWORD_MARKER\", { $reference })"
val testRenamedByName = testRenamed()
val testRenamedByRef = testRenamed("$KEYWORD_MARKER()")
val testNotRenamedByName = testNotRenamed()
val testNotRenamedByRef = testNotRenamed("$KEYWORD_MARKER()")
// KEYWORDS
val SHOULD_BE_ESCAPED = JsFunctionScope.RESERVED_WORDS.filter { it in KeywordStringsGenerated.KEYWORDS }.sorted()
val SHOULD_NOT_BE_ESCAPED = JsFunctionScope.RESERVED_WORDS.filter { it !in SHOULD_BE_ESCAPED }.sorted()
// all keywords by portions
// cyclic keyword streams
val s1 = SHOULD_BE_ESCAPED.cyclicSequence()
val s2 = SHOULD_NOT_BE_ESCAPED.cyclicSequence()
val PORTION_PART_SIZE = 2;
fun nextKeywordPortion() = s1.take(PORTION_PART_SIZE).toList() + s2.take(PORTION_PART_SIZE).toList()
// CyclicStream
fun <T> List<T>.cyclicSequence() = CyclicSequence(this)
class CyclicSequence<T>(val c: List<T>) : Sequence<T> {
var i = 0
val iterator = object : Iterator<T> {
override fun next(): T {
i = if (i >= c.size()) 0 else i
return c[i++]
}
override fun hasNext(): Boolean = true
}
override fun iterator(): Iterator<T> = iterator
}