/
KotlinCodeGenerator.java
594 lines (487 loc) · 19.8 KB
/
KotlinCodeGenerator.java
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
package gg.jte.compiler.kotlin;
import gg.jte.ContentType;
import gg.jte.TemplateConfig;
import gg.jte.TemplateException;
import gg.jte.compiler.*;
import gg.jte.runtime.ClassInfo;
import gg.jte.runtime.Constants;
import gg.jte.runtime.DebugInfo;
import gg.jte.compiler.TemplateType;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import static gg.jte.runtime.Constants.TEXT_PART_BINARY;
@SuppressWarnings("unused") // Used by TemplateCompiler
public class KotlinCodeGenerator implements CodeGenerator {
private final TemplateCompiler compiler;
private final TemplateConfig config;
private final ConcurrentHashMap<String, List<ParamInfo>> paramOrder;
private final ClassInfo classInfo;
private final CodeBuilder kotlinCode = new CodeBuilder(CodeType.Kotlin);
private final LinkedHashSet<ClassDefinition> classDefinitions;
private final LinkedHashSet<TemplateDependency> templateDependencies;
private final List<ParamInfo> parameters = new ArrayList<>();
private final List<byte[]> binaryTextParts = new ArrayList<>();
private boolean hasWrittenPackage;
private boolean hasWrittenClass;
public KotlinCodeGenerator(TemplateCompiler compiler, TemplateConfig config, ConcurrentHashMap<String, List<ParamInfo>> paramOrder, ClassInfo classInfo, LinkedHashSet<ClassDefinition> classDefinitions, LinkedHashSet<TemplateDependency> templateDependencies) {
this.compiler = compiler;
this.config = config;
this.paramOrder = paramOrder;
this.classInfo = classInfo;
this.classDefinitions = classDefinitions;
this.templateDependencies = templateDependencies;
}
@Override
public void onImport(String importClass) {
writePackageIfRequired();
kotlinCode.append("import ").append(importClass).append("\n");
}
private void writePackageIfRequired() {
if (!hasWrittenPackage) {
kotlinCode.append("@file:Suppress(\"ktlint\")\n");
kotlinCode.append("package " + classInfo.packageName + "\n");
hasWrittenPackage = true;
}
}
@Override
public void onParam(String parameter) {
ParamInfo paramInfo = KotlinParamInfo.parse(parameter, this, getCurrentTemplateLine());
writePackageIfRequired();
if (!hasWrittenClass) {
writeClass();
}
kotlinCode.append(", ");
if (paramInfo.varargs) {
kotlinCode.append("vararg ");
}
kotlinCode.append(paramInfo.name).append(':').append(paramInfo.type);
parameters.add(paramInfo);
}
private void writeClass() {
kotlinCode.append("@Suppress(\"UNCHECKED_CAST\", \"UNUSED_PARAMETER\")").append('\n');
kotlinCode.append("class ").append(classInfo.className).append(" {\n");
kotlinCode.append("companion object {\n");
kotlinCode.markFieldsIndex();
kotlinCode.append("\t@JvmStatic fun render(");
writeTemplateOutputParam();
kotlinCode.append(", jteHtmlInterceptor:gg.jte.html.HtmlInterceptor?");
hasWrittenClass = true;
}
private String getContentClass() {
if (config.contentType == ContentType.Html) {
return "gg.jte.html.HtmlContent";
} else {
return "gg.jte.Content";
}
}
private void writeTemplateOutputParam() {
if (config.contentType == ContentType.Html) {
kotlinCode.append("jteOutput:gg.jte.html.HtmlTemplateOutput");
} else {
kotlinCode.append("jteOutput:gg.jte.TemplateOutput");
}
}
@Override
public void onParamsComplete() {
writePackageIfRequired();
if (!hasWrittenClass) {
writeClass();
}
kotlinCode.append(") {\n");
paramOrder.put(classInfo.name, parameters);
}
@Override
public void onLineFinished() {
kotlinCode.finishTemplateLine();
}
@Override
public void onComplete() {
int lineCount = 2;
if (!binaryTextParts.isEmpty()) {
lineCount += binaryTextParts.size() + 1;
}
kotlinCode.insertFieldLines(lineCount);
StringBuilder fields = new StringBuilder(64 + 32 * lineCount);
addNameField(fields, classInfo.name);
addLineInfoField(fields);
writeBinaryTextParts(fields);
kotlinCode.insertFields(fields);
kotlinCode.append("\t}\n");
kotlinCode.append("\t@JvmStatic fun renderMap(");
writeTemplateOutputParam();
kotlinCode.append(", jteHtmlInterceptor:gg.jte.html.HtmlInterceptor?");
kotlinCode.append(", params:Map<String, Any?>) {\n");
for (ParamInfo parameter : parameters) {
if (parameter.varargs) {
continue;
}
kotlinCode.setCurrentTemplateLine(parameter.templateLine);
kotlinCode.append("\t\tval ").append(parameter.name).append(" = params[\"").append(parameter.name).append("\"] as ").append(parameter.type);
if (parameter.defaultValue != null) {
kotlinCode.append("? ?: ");
writeCodeWithContentSupport(0, parameter.defaultValue);
}
kotlinCode.append('\n');
}
kotlinCode.append("\t\trender(jteOutput, jteHtmlInterceptor");
for (ParamInfo parameter : parameters) {
if (parameter.varargs) {
continue;
}
kotlinCode.append(", ").append(parameter.name);
}
kotlinCode.append(");\n");
kotlinCode.append("\t}\n");
kotlinCode.append("}\n");
kotlinCode.append("}\n");
this.classInfo.lineInfo = kotlinCode.getLineInfo();
}
private void addNameField(StringBuilder fields, String name) {
fields.append("\t@JvmField val ").append(Constants.NAME_FIELD).append(" = \"");
fields.append(name);
fields.append("\"\n");
}
private void addLineInfoField(StringBuilder fields) {
fields.append("\t@JvmField val ").append(Constants.LINE_INFO_FIELD).append(" = intArrayOf(");
for (int i = 0; i < kotlinCode.getCurrentCodeLine(); ++i) {
if (i > 0) {
fields.append(',');
}
fields.append(kotlinCode.getLineInfo(i));
}
fields.append(")\n");
}
private void writeBinaryTextParts(StringBuilder fields) {
if (binaryTextParts.isEmpty()) {
return;
}
writeBinaryTextPartsContent(fields);
writeBinaryTextPartsConstants(fields);
}
private void writeBinaryTextPartsContent(StringBuilder fields) {
String contentFileName = new ClassDefinition(classInfo.className, "kt").getBinaryTextPartsFileName();
fields.append("\t@JvmStatic val BINARY_CONTENT = gg.jte.runtime.BinaryContent.load(")
.append(classInfo.className)
.append(".javaClass, \"")
.append(contentFileName)
.append("\", ");
for (int i = 0; i < binaryTextParts.size(); ++i) {
if (i > 0) {
fields.append(',');
}
fields.append(binaryTextParts.get(i).length);
}
fields.append(");\n");
}
private void writeBinaryTextPartsConstants(StringBuilder fields) {
for (int i = 0; i < binaryTextParts.size(); ++i) {
fields.append("\t@JvmStatic val ").append(TEXT_PART_BINARY).append(i).append(" = BINARY_CONTENT.get(").append(i).append(")\n");
}
}
@Override
public void onError( String message ) {
DebugInfo debugInfo = getCurrentDebugInfo();
throw new TemplateException("Failed to compile " + debugInfo.name + ", error at line " + debugInfo.line + ": " + message);
}
@Override
public void onError(String message, int templateLine) {
DebugInfo debugInfo = getDebugInfo(templateLine);
throw new TemplateException("Failed to compile " + debugInfo.name + ", error at line " + debugInfo.line + ": " + message);
}
@Override
public void onTextPart(int depth, String textPart) {
if (textPart.isEmpty()) {
return;
}
if (config.binaryStaticContent) {
writeTextBinary(depth, textPart);
} else {
writeTextString(depth, textPart);
}
}
private void writeTextBinary(int depth, String textPart) {
writeIndentation(depth);
kotlinCode.append("jteOutput.writeBinaryContent(");
kotlinCode.append(TEXT_PART_BINARY).append(binaryTextParts.size());
kotlinCode.append(")\n");
byte[] bytes = textPart.getBytes(StandardCharsets.UTF_8);
binaryTextParts.add(bytes);
}
private void writeTextString(int depth, String textPart) {
final int length = textPart.length();
if (length < 65535 / 6) {
// Optimization for strings that definitely fit into a single string literal
writeText(depth, textPart);
} else {
int modifiedUtf8Length = 0;
int chunkOffset = 0;
for (int i = 0; i < length; i++) {
int c = textPart.charAt(i);
if (c >= 0x80 || c == 0) {
modifiedUtf8Length += c >= 0x800 ? 2 : 1;
}
// low surrogate: c >= 0xdc00 && c <= 0xdfff
// high surrogate: c >= 0xd800 && c <= 0xdbff
if (c >= 0xd800 && c <= 0xdbff) {
continue; // don't split low and high surrogates
}
if (modifiedUtf8Length + (i - chunkOffset + 1) > 65529) {
writeText(depth, textPart.substring(chunkOffset, i + 1));
modifiedUtf8Length = 0;
chunkOffset = i + 1;
}
}
if (chunkOffset < length) {
writeText(depth, textPart.substring(chunkOffset));
}
}
}
private void writeText(int depth, String text) {
writeIndentation(depth);
kotlinCode.append("jteOutput.writeContent(\"");
kotlinCode.appendEscaped(text);
kotlinCode.append("\")\n");
}
@Override
public void onCodePart(int depth, String codePart) {
writeCodePart(depth, codePart);
}
@Override
public void onHtmlTagBodyCodePart(int depth, String codePart, String tagName) {
writeIndentation(depth);
kotlinCode.append("jteOutput.setContext(\"").append(tagName).append("\", null)\n");
writeCodePart(depth, codePart);
}
@Override
public void onHtmlTagAttributeCodePart(int depth, String codePart, String tagName, String attributeName) {
writeIndentation(depth);
kotlinCode.append("jteOutput.setContext(\"").append(tagName).append("\", \"").append(attributeName).append("\")\n");
writeCodePart(depth, codePart);
writeIndentation(depth + 1);
kotlinCode.append("jteOutput.setContext(\"").append(tagName).append("\", null)\n");
}
@Override
public void onUnsafeCodePart(int depth, String codePart) {
writeIndentation(depth);
kotlinCode.append("jteOutput.writeUnsafeContent(");
kotlinCode.append(codePart);
kotlinCode.append(")\n");
}
private void writeCodePart(int depth, String codePart) {
writeIndentation(depth);
kotlinCode.append("jteOutput.writeUserContent(");
writeCodeWithContentSupport(depth, codePart);
kotlinCode.append(")\n");
}
@Override
public void onCodeStatement(int depth, String codePart) {
writeIndentation(depth);
writeCodeWithContentSupport(depth, codePart);
kotlinCode.append("\n");
}
@Override
public void onConditionStart(int depth, String condition) {
writeIndentation(depth);
kotlinCode.append("if (");
kotlinCode.append(condition);
kotlinCode.append(") {\n");
}
@Override
public void onConditionElse(int depth, String condition) {
writeIndentation(depth);
kotlinCode.append("} else if (");
kotlinCode.append(condition);
kotlinCode.append(") {\n");
}
@Override
public void onConditionElse(int depth) {
writeIndentation(depth);
kotlinCode.append("} else {\n");
}
@Override
public void onConditionEnd(int depth) {
writeIndentation(depth);
kotlinCode.append("}\n");
}
@Override
public void onForLoopStart(int depth, String codePart) {
writeIndentation(depth);
kotlinCode.append("for (").append(codePart).append(") {\n");
}
@Override
public void onForLoopEnd(int depth) {
writeIndentation(depth);
kotlinCode.append("}\n");
}
@Override
public void onTemplateCall(int depth, String name, List<String> params) {
ClassInfo tagInfo = compiler.generateTemplateCall(name, "kte", classDefinitions, templateDependencies, getCurrentDebugInfo());
writeIndentation(depth);
kotlinCode.append(tagInfo.fullName).append(".render(jteOutput, jteHtmlInterceptor");
appendParams(depth, tagInfo.name, params);
kotlinCode.append(");\n");
}
@Override
public void onInterceptHtmlTagOpened(int depth, TemplateParser.HtmlTag htmlTag) {
writeIndentation(depth);
kotlinCode.append("jteHtmlInterceptor?.onHtmlTagOpened(\"").append(htmlTag.name).append("\", ");
writeAttributeMap(htmlTag);
kotlinCode.append(", jteOutput)\n");
}
@Override
public void onInterceptHtmlTagClosed(int depth, TemplateParser.HtmlTag htmlTag) {
writeIndentation(depth);
kotlinCode.append("jteHtmlInterceptor?.onHtmlTagClosed(\"").append(htmlTag.name).append("\", jteOutput)\n");
}
@Override
public void onHtmlAttributeOutput(int depth, TemplateParser.HtmlTag currentHtmlTag, TemplateParser.HtmlAttribute htmlAttribute) {
String javaExpression = CodeGenerator.extractSingleOutputTemplateExpression(htmlAttribute.value);
if (htmlAttribute.bool) {
onConditionStart(depth, javaExpression);
onTextPart(depth, " " + htmlAttribute.name);
} else {
onConditionStart(depth, "gg.jte.runtime.TemplateUtils.isAttributeRendered(" + javaExpression + ")");
onTextPart(depth + 1, " " + htmlAttribute.name + "=" + htmlAttribute.quotes);
onHtmlTagAttributeCodePart(depth + 1, javaExpression, currentHtmlTag.name, htmlAttribute.name);
onTextPart(depth + 1, "" + htmlAttribute.quotes);
}
onConditionEnd(depth);
}
private void writeAttributeMap(TemplateParser.HtmlTag htmlTag) {
CodeGenerator.writeAttributeMap(kotlinCode, htmlTag);
}
private void writeCodeWithContentSupport(int depth, String code) {
if (code.contains("@`")) {
new KotlinContentProcessor(depth, code).process();
} else {
kotlinCode.append(code);
}
}
private DebugInfo getCurrentDebugInfo() {
return getDebugInfo(getCurrentTemplateLine());
}
private DebugInfo getDebugInfo(int templateLine) {
return new DebugInfo(classInfo.name, templateLine + 1);
}
@Override
public int getCurrentTemplateLine() {
return kotlinCode.getCurrentTemplateLine();
}
private void appendParams(int depth, String name, List<String> params) {
List<ParamInfo> paramInfos = paramOrder.get(name);
if (paramInfos == null) {
throw new IllegalStateException("No parameter information for " + name);
}
int index = 0;
ParamCallInfo[] paramCallInfos = new ParamCallInfo[Math.max(params.size(), paramInfos.size())];
for (String param : params) {
ParamCallInfo paramCallInfo = new ParamCallInfo(param);
int parameterIndex = getParameterIndex(name, paramInfos, paramCallInfo);
if (parameterIndex == -1) {
parameterIndex = index;
}
paramCallInfos[parameterIndex] = paramCallInfo;
++index;
}
for (int i = 0; i < paramCallInfos.length; i++) {
ParamCallInfo paramCallInfo = paramCallInfos[i];
if (paramCallInfo != null) {
appendParam(depth, paramCallInfo.data);
} else {
ParamInfo paramInfo = paramInfos.get(i);
if (paramInfo.defaultValue != null) {
appendParam(depth, paramInfo.defaultValue);
}
}
}
}
private void appendParam(int depth, String param) {
kotlinCode.append(", ");
writeCodeWithContentSupport(depth, param);
}
private int getParameterIndex(String name, List<ParamInfo> paramInfos, ParamCallInfo paramCallInfo) {
if (paramCallInfo.name == null) {
return -1;
}
for (int i = 0; i < paramInfos.size(); ++i) {
if (paramInfos.get(i).name.equals(paramCallInfo.name)) {
return i;
}
}
throw new TemplateException("Failed to compile template, error at " + classInfo.name + ":" + getCurrentTemplateLine() + ". No parameter with name " + paramCallInfo.name + " is defined in " + name);
}
private void writeIndentation(int depth) {
for (int i = 0; i < depth + 2; ++i) {
kotlinCode.append('\t');
}
}
@Override
public String getCode() {
return kotlinCode.getCode();
}
@Override
public List<byte[]> getBinaryTextParts() {
return binaryTextParts;
}
class KotlinContentProcessor extends ContentProcessor {
KotlinContentProcessor(int depth, String param) {
super(depth, param);
}
@Override
protected void onContentBlock( int depth, String code, int lastWrittenIndex, int startIndex, int endIndex ) {
kotlinCode.append(code, lastWrittenIndex + 1, startIndex - 2);
kotlinCode.append("object : ").append(getContentClass()).append(" {\n");
writeIndentation(depth + 1);
kotlinCode.append("override fun writeTo(");
writeTemplateOutputParam();
kotlinCode.append(") {\n");
TemplateParser parser = new TemplateParser(code, TemplateType.Content, KotlinCodeGenerator.this, config);
parser.setStartIndex(startIndex);
parser.setEndIndex(endIndex);
parser.setParamsComplete(true);
parser.parse(depth + 2);
writeIndentation(depth + 1);
kotlinCode.append("}\n");
writeIndentation(depth);
kotlinCode.append("}");
}
@Override
protected void onRemainingCode( String code, int startIndex, int endIndex ) {
kotlinCode.append(code, startIndex, endIndex);
}
}
private static final class ParamCallInfo {
final String name;
final String data;
public ParamCallInfo(String param) {
param = param.trim();
int nameEndIndex = -1;
int dataStartIndex = -1;
for (int i = 0; i < param.length(); ++i) {
char character = param.charAt(i);
if (nameEndIndex == -1) {
if (character == '"' || character == '\'') {
break;
}
if (character == '=') {
nameEndIndex = i;
}
} else if (dataStartIndex == -1) {
if (!Character.isWhitespace(character)) {
dataStartIndex = i;
}
}
}
if (nameEndIndex != -1 && dataStartIndex != -1) {
name = param.substring(0, nameEndIndex).trim();
data = param.substring(dataStartIndex).trim();
} else {
name = null;
data = param;
}
}
}
}