forked from quarkusio/quarkus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
QuteProcessor.java
1402 lines (1287 loc) · 69.3 KB
/
QuteProcessor.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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package io.quarkus.qute.deployment;
import static io.quarkus.deployment.annotations.ExecutionTime.STATIC_INIT;
import static java.util.stream.Collectors.toMap;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationTarget;
import org.jboss.jandex.AnnotationTarget.Kind;
import org.jboss.jandex.AnnotationValue;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.FieldInfo;
import org.jboss.jandex.IndexView;
import org.jboss.jandex.MethodInfo;
import org.jboss.jandex.ParameterizedType;
import org.jboss.jandex.Type;
import org.jboss.jandex.TypeVariable;
import org.jboss.logging.Logger;
import io.quarkus.arc.deployment.AdditionalBeanBuildItem;
import io.quarkus.arc.deployment.BeanArchiveIndexBuildItem;
import io.quarkus.arc.deployment.BeanRegistrationPhaseBuildItem;
import io.quarkus.arc.deployment.BeanRegistrationPhaseBuildItem.BeanConfiguratorBuildItem;
import io.quarkus.arc.deployment.SyntheticBeanBuildItem;
import io.quarkus.arc.deployment.ValidationPhaseBuildItem;
import io.quarkus.arc.deployment.ValidationPhaseBuildItem.ValidationErrorBuildItem;
import io.quarkus.arc.processor.BeanInfo;
import io.quarkus.arc.processor.BuildExtension;
import io.quarkus.arc.processor.DotNames;
import io.quarkus.arc.processor.InjectionPointInfo;
import io.quarkus.bootstrap.classloading.QuarkusClassLoader;
import io.quarkus.deployment.ApplicationArchive;
import io.quarkus.deployment.Feature;
import io.quarkus.deployment.GeneratedClassGizmoAdaptor;
import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.annotations.Record;
import io.quarkus.deployment.builditem.ApplicationArchivesBuildItem;
import io.quarkus.deployment.builditem.BytecodeTransformerBuildItem;
import io.quarkus.deployment.builditem.CombinedIndexBuildItem;
import io.quarkus.deployment.builditem.FeatureBuildItem;
import io.quarkus.deployment.builditem.GeneratedClassBuildItem;
import io.quarkus.deployment.builditem.HotDeploymentWatchedFileBuildItem;
import io.quarkus.deployment.builditem.ServiceStartBuildItem;
import io.quarkus.deployment.builditem.nativeimage.NativeImageResourceBuildItem;
import io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem;
import io.quarkus.deployment.util.JandexUtil;
import io.quarkus.gizmo.ClassOutput;
import io.quarkus.qute.Engine;
import io.quarkus.qute.EngineBuilder;
import io.quarkus.qute.Expression;
import io.quarkus.qute.Expression.VirtualMethodPart;
import io.quarkus.qute.LoopSectionHelper;
import io.quarkus.qute.ParserHelper;
import io.quarkus.qute.ParserHook;
import io.quarkus.qute.ResultNode;
import io.quarkus.qute.SectionHelper;
import io.quarkus.qute.SectionHelperFactory;
import io.quarkus.qute.Template;
import io.quarkus.qute.TemplateException;
import io.quarkus.qute.TemplateExtension;
import io.quarkus.qute.TemplateInstance;
import io.quarkus.qute.TemplateLocator;
import io.quarkus.qute.UserTagSectionHelper;
import io.quarkus.qute.Variant;
import io.quarkus.qute.api.CheckedTemplate;
import io.quarkus.qute.api.ResourcePath;
import io.quarkus.qute.deployment.TemplatesAnalysisBuildItem.TemplateAnalysis;
import io.quarkus.qute.deployment.TypeCheckExcludeBuildItem.Check;
import io.quarkus.qute.deployment.TypeInfos.Info;
import io.quarkus.qute.generator.ExtensionMethodGenerator;
import io.quarkus.qute.generator.ExtensionMethodGenerator.NamespaceResolverCreator;
import io.quarkus.qute.generator.ExtensionMethodGenerator.NamespaceResolverCreator.ResolveCreator;
import io.quarkus.qute.generator.ValueResolverGenerator;
import io.quarkus.qute.runtime.ContentTypes;
import io.quarkus.qute.runtime.EngineProducer;
import io.quarkus.qute.runtime.QuteConfig;
import io.quarkus.qute.runtime.QuteRecorder;
import io.quarkus.qute.runtime.QuteRecorder.QuteContext;
import io.quarkus.qute.runtime.TemplateProducer;
import io.quarkus.qute.runtime.extensions.CollectionTemplateExtensions;
import io.quarkus.qute.runtime.extensions.MapTemplateExtensions;
import io.quarkus.qute.runtime.extensions.NumberTemplateExtensions;
public class QuteProcessor {
private static final Logger LOGGER = Logger.getLogger(QuteProcessor.class);
public static final DotName RESOURCE_PATH = DotName.createSimple(ResourcePath.class.getName());
public static final DotName TEMPLATE = DotName.createSimple(Template.class.getName());
static final DotName ITERABLE = DotName.createSimple(Iterable.class.getName());
static final DotName ITERATOR = DotName.createSimple(Iterator.class.getName());
static final DotName STREAM = DotName.createSimple(Stream.class.getName());
static final DotName MAP = DotName.createSimple(Map.class.getName());
static final DotName MAP_ENTRY = DotName.createSimple(Entry.class.getName());
static final DotName COLLECTION = DotName.createSimple(Collection.class.getName());
static final DotName STRING = DotName.createSimple(String.class.getName());
static final DotName DOTNAME_CHECKED_TEMPLATE = DotName.createSimple(CheckedTemplate.class.getName());
static final DotName DOTNAME_TEMPLATE_INSTANCE = DotName.createSimple(TemplateInstance.class.getName());
@BuildStep
FeatureBuildItem feature() {
return new FeatureBuildItem(Feature.QUTE);
}
@BuildStep
void processTemplateErrors(TemplatesAnalysisBuildItem analysis, List<IncorrectExpressionBuildItem> incorrectExpressions,
BuildProducer<ServiceStartBuildItem> serviceStart) {
List<String> errors = new ArrayList<>();
for (IncorrectExpressionBuildItem incorrectExpression : incorrectExpressions) {
if (incorrectExpression.reason != null) {
errors.add(String.format(
"Incorrect expression: %s\n\t- %s\n\t- found in template [%s] on line %s",
incorrectExpression.expression, incorrectExpression.reason,
findTemplatePath(analysis, incorrectExpression.templateId), incorrectExpression.line));
} else if (incorrectExpression.clazz != null) {
errors.add(String.format(
"Incorrect expression: %s\n\t- property/method [%s] not found on class [%s] nor handled by an extension method\n\t- found in template [%s] on line %s",
incorrectExpression.expression, incorrectExpression.property, incorrectExpression.clazz,
findTemplatePath(analysis, incorrectExpression.templateId), incorrectExpression.line));
} else {
errors.add(String.format(
"Incorrect expression %s\n\t @Named bean not found for [%s]\n\t- found in template [%s] on line %s",
incorrectExpression.expression, incorrectExpression.property,
findTemplatePath(analysis, incorrectExpression.templateId), incorrectExpression.line));
}
}
if (!errors.isEmpty()) {
StringBuilder message = new StringBuilder("Found template problems (").append(errors.size()).append("):");
int idx = 1;
for (String errorMessage : errors) {
message.append("\n").append("[").append(idx++).append("] ").append(errorMessage);
}
throw new TemplateException(message.toString());
}
}
@BuildStep
AdditionalBeanBuildItem additionalBeans() {
return AdditionalBeanBuildItem.builder()
.setUnremovable()
.addBeanClasses(EngineProducer.class, TemplateProducer.class, ContentTypes.class, ResourcePath.class,
Template.class, TemplateInstance.class, CollectionTemplateExtensions.class,
MapTemplateExtensions.class, NumberTemplateExtensions.class)
.build();
}
@BuildStep
List<CheckedTemplateBuildItem> collectTemplateTypeInfo(BeanArchiveIndexBuildItem index,
BuildProducer<BytecodeTransformerBuildItem> transformers,
List<TemplatePathBuildItem> templatePaths,
List<CheckedTemplateAdapterBuildItem> templateAdaptorBuildItems) {
List<CheckedTemplateBuildItem> ret = new ArrayList<>();
Map<DotName, CheckedTemplateAdapter> adaptors = new HashMap<>();
for (CheckedTemplateAdapterBuildItem templateAdaptorBuildItem : templateAdaptorBuildItems) {
adaptors.put(DotName.createSimple(templateAdaptorBuildItem.adapter.templateInstanceBinaryName().replace('/', '.')),
templateAdaptorBuildItem.adapter);
}
String supportedAdaptors;
if (adaptors.isEmpty()) {
supportedAdaptors = DOTNAME_TEMPLATE_INSTANCE + " is supported";
} else {
StringBuffer strbuf = new StringBuffer(DOTNAME_TEMPLATE_INSTANCE.toString());
List<String> adaptorsList = new ArrayList<>(adaptors.size());
for (DotName name : adaptors.keySet()) {
adaptorsList.add(name.toString());
}
Collections.sort(adaptorsList);
for (String name : adaptorsList) {
strbuf.append(", ").append(name);
}
supportedAdaptors = strbuf.append(" are supported").toString();
}
for (AnnotationInstance annotation : index.getIndex().getAnnotations(DOTNAME_CHECKED_TEMPLATE)) {
if (annotation.target().kind() != Kind.CLASS)
continue;
ClassInfo classInfo = annotation.target().asClass();
NativeCheckedTemplateEnhancer enhancer = new NativeCheckedTemplateEnhancer();
for (MethodInfo methodInfo : classInfo.methods()) {
// only keep native public static methods
if (!Modifier.isPublic(methodInfo.flags())
|| !Modifier.isStatic(methodInfo.flags())
|| !Modifier.isNative(methodInfo.flags()))
continue;
// check its return type
if (methodInfo.returnType().kind() != Type.Kind.CLASS) {
throw new TemplateException("Incompatible checked template return type: " + methodInfo.returnType()
+ " only " + supportedAdaptors);
}
DotName returnTypeName = methodInfo.returnType().asClassType().name();
CheckedTemplateAdapter adaptor = null;
// if it's not the default template instance, try to find an adapter
if (!returnTypeName.equals(DOTNAME_TEMPLATE_INSTANCE)) {
adaptor = adaptors.get(returnTypeName);
if (adaptor == null)
throw new TemplateException("Incompatible checked template return type: " + methodInfo.returnType()
+ " only " + supportedAdaptors);
}
String methodName = methodInfo.name();
String templatePath;
if (classInfo.enclosingClass() != null) {
ClassInfo enclosingClass = index.getIndex().getClassByName(classInfo.enclosingClass());
String className = enclosingClass.simpleName();
templatePath = className + "/" + methodName;
} else {
templatePath = methodName;
}
checkTemplatePath(templatePath, templatePaths, classInfo, methodInfo);
Map<String, String> bindings = new HashMap<>();
List<Type> parameters = methodInfo.parameters();
List<String> parameterNames = new ArrayList<>(parameters.size());
for (int i = 0; i < parameters.size(); i++) {
Type type = parameters.get(i);
String name = methodInfo.parameterName(i);
if (name == null) {
throw new TemplateException("Parameter names not recorded for " + classInfo.name()
+ ": compile the class with -parameters");
}
bindings.put(name, JandexUtil.getBoxedTypeName(type));
parameterNames.add(name);
}
ret.add(new CheckedTemplateBuildItem(templatePath, bindings));
enhancer.implement(methodInfo, templatePath, parameterNames, adaptor);
}
transformers.produce(new BytecodeTransformerBuildItem(classInfo.name().toString(),
enhancer));
}
return ret;
}
private void checkTemplatePath(String templatePath, List<TemplatePathBuildItem> templatePaths, ClassInfo enclosingClass,
MethodInfo methodInfo) {
for (TemplatePathBuildItem templatePathBuildItem : templatePaths) {
// perfect match
if (templatePathBuildItem.getPath().equals(templatePath)) {
return;
}
// if our templatePath is "Foo/hello", make it match "Foo/hello.txt"
// if they're not equal and they start with our path, there must be something left after
if (templatePathBuildItem.getPath().startsWith(templatePath)
// check that we have an extension, let variant matching work later
&& templatePathBuildItem.getPath().charAt(templatePath.length()) == '.') {
return;
}
}
throw new TemplateException(
"Declared template " + templatePath + " could not be found. Either add it or delete its declaration in "
+ enclosingClass.name().toString('.') + "." + methodInfo.name());
}
@BuildStep
TemplatesAnalysisBuildItem analyzeTemplates(List<TemplatePathBuildItem> templatePaths,
List<CheckedTemplateBuildItem> dynamicTemplates, List<MessageBundleMethodBuildItem> messageBundleMethods) {
long start = System.currentTimeMillis();
List<TemplateAnalysis> analysis = new ArrayList<>();
// A dummy engine instance is used to parse and validate all templates during the build
// The real engine instance is created at startup
EngineBuilder builder = Engine.builder().addDefaultSectionHelpers();
// Register user tags
for (TemplatePathBuildItem path : templatePaths) {
if (path.isTag()) {
String tagPath = path.getPath();
String tagName = tagPath.substring(TemplatePathBuildItem.TAGS.length(), tagPath.length());
if (tagName.contains(".")) {
tagName = tagName.substring(0, tagName.lastIndexOf('.'));
}
builder.addSectionHelper(new UserTagSectionHelper.Factory(tagName, tagPath));
}
}
builder.computeSectionHelper(name -> {
// Create a dummy section helper factory for an uknown section that could be potentially registered at runtime
return new SectionHelperFactory<SectionHelper>() {
@Override
public SectionHelper initialize(SectionInitContext context) {
return new SectionHelper() {
@Override
public CompletionStage<ResultNode> resolve(SectionResolutionContext context) {
return CompletableFuture.completedFuture(ResultNode.NOOP);
}
};
}
};
});
builder.addLocator(new TemplateLocator() {
@Override
public Optional<TemplateLocation> locate(String id) {
TemplatePathBuildItem found = templatePaths.stream().filter(p -> p.getPath().equals(id)).findAny().orElse(null);
if (found != null) {
try {
byte[] content = Files.readAllBytes(found.getFullPath());
return Optional.of(new TemplateLocation() {
@Override
public Reader read() {
return new StringReader(new String(content, StandardCharsets.UTF_8));
}
@Override
public Optional<Variant> getVariant() {
return Optional.empty();
}
});
} catch (IOException e) {
LOGGER.warn("Unable to read the template from path: " + found.getFullPath(), e);
}
}
return Optional.empty();
}
}).addParserHook(new ParserHook() {
@Override
public void beforeParsing(ParserHelper parserHelper, String id) {
if (id != null) {
for (CheckedTemplateBuildItem dynamicTemplate : dynamicTemplates) {
// FIXME: check for dot/extension?
if (id.startsWith(dynamicTemplate.templateId)) {
for (Entry<String, String> entry : dynamicTemplate.bindings.entrySet()) {
parserHelper.addParameter(entry.getKey(), entry.getValue());
}
}
}
// Add params to message bundle templates
for (MessageBundleMethodBuildItem messageBundleMethod : messageBundleMethods) {
if (id.equals(messageBundleMethod.getTemplateId())) {
MethodInfo method = messageBundleMethod.getMethod();
for (ListIterator<Type> it = method.parameters().listIterator(); it.hasNext();) {
Type paramType = it.next();
parserHelper.addParameter(method.parameterName(it.previousIndex()),
JandexUtil.getBoxedTypeName(paramType));
}
break;
}
}
}
}
}).build();
Engine dummyEngine = builder.build();
for (TemplatePathBuildItem path : templatePaths) {
Template template = dummyEngine.getTemplate(path.getPath());
if (template != null) {
analysis.add(new TemplateAnalysis(null, template.getGeneratedId(), template.getExpressions(), path.getPath()));
}
}
// Message bundle templates
for (MessageBundleMethodBuildItem messageBundleMethod : messageBundleMethods) {
Template template = dummyEngine.parse(messageBundleMethod.getTemplate(), null, messageBundleMethod.getTemplateId());
analysis.add(new TemplateAnalysis(messageBundleMethod.getTemplateId(), template.getGeneratedId(),
template.getExpressions(),
messageBundleMethod.getMethod().declaringClass().name() + "#" + messageBundleMethod.getMethod().name()
+ "()"));
}
LOGGER.debugf("Finished analysis of %s templates in %s ms", analysis.size(), System.currentTimeMillis() - start);
return new TemplatesAnalysisBuildItem(analysis);
}
@BuildStep
void validateExpressions(TemplatesAnalysisBuildItem templatesAnalysis, BeanArchiveIndexBuildItem beanArchiveIndex,
List<TemplateExtensionMethodBuildItem> templateExtensionMethods,
List<TypeCheckExcludeBuildItem> excludes,
BuildProducer<IncorrectExpressionBuildItem> incorrectExpressions,
BuildProducer<ImplicitValueResolverBuildItem> implicitClasses) {
IndexView index = beanArchiveIndex.getIndex();
Function<String, String> templateIdToPathFun = new Function<String, String>() {
@Override
public String apply(String id) {
return findTemplatePath(templatesAnalysis, id);
}
};
// Map implicit class -> true if methods were used
Map<ClassInfo, Boolean> implicitClassToMethodUsed = new HashMap<>();
for (TemplateAnalysis analysis : templatesAnalysis.getAnalysis()) {
for (Expression expression : analysis.expressions) {
if (expression.hasNamespace() || expression.isLiteral()) {
continue;
}
validateNestedExpressions(null, new HashMap<>(), templateExtensionMethods, excludes, incorrectExpressions,
expression, index, implicitClassToMethodUsed, templateIdToPathFun);
}
}
for (Entry<ClassInfo, Boolean> implicit : implicitClassToMethodUsed.entrySet()) {
implicitClasses.produce(implicit.getValue()
? new ImplicitValueResolverBuildItem(implicit.getKey(), new TemplateDataBuilder().properties(false).build())
: new ImplicitValueResolverBuildItem(implicit.getKey()));
}
}
static void validateNestedExpressions(ClassInfo rootClazz, Map<String, Match> results,
List<TemplateExtensionMethodBuildItem> templateExtensionMethods,
List<TypeCheckExcludeBuildItem> excludes,
BuildProducer<IncorrectExpressionBuildItem> incorrectExpressions, Expression expression, IndexView index,
Map<ClassInfo, Boolean> implicitClassToMethodUsed, Function<String, String> templateIdToPathFun) {
// First validate nested virtual methods
for (Expression.Part part : expression.getParts()) {
if (part.isVirtualMethod()) {
for (Expression param : part.asVirtualMethod().getParameters()) {
if (!results.containsKey(param.toOriginalString())) {
validateNestedExpressions(null, results, templateExtensionMethods, excludes, incorrectExpressions,
param, index, implicitClassToMethodUsed, templateIdToPathFun);
}
}
}
}
// Then validate the expression itself
Match match = new Match();
if (rootClazz == null && !expression.hasTypeInfo()) {
// No type info available or a namespace expression
results.put(expression.toOriginalString(), match);
return;
}
Iterator<Info> parts = TypeInfos.create(expression, index, templateIdToPathFun).iterator();
if (rootClazz == null) {
// {foo.name}
Info root = parts.next();
match.clazz = root.asTypeInfo().rawClass;
match.type = root.asTypeInfo().resolvedType;
if (root.asTypeInfo().hint != null) {
processHints(root.asTypeInfo().hint, match, index, expression);
}
} else {
// The first part is skipped, e.g. for {inject:foo.name} the first part is the name of the bean
parts.next();
match.clazz = rootClazz;
match.type = Type.create(rootClazz.name(), org.jboss.jandex.Type.Kind.CLASS);
}
while (parts.hasNext()) {
// Now iterate over all parts of the expression and check each part against the current "match class"
Info info = parts.next();
if (match.clazz != null) {
// By default, we only consider properties
implicitClassToMethodUsed.putIfAbsent(match.clazz, false);
AnnotationTarget member = null;
// First try to find java members
if (info.isVirtualMethod()) {
member = findMethod(info.part.asVirtualMethod(), match.clazz, expression, index, templateIdToPathFun,
results);
if (member != null) {
implicitClassToMethodUsed.put(match.clazz, true);
}
} else if (info.isProperty()) {
member = findProperty(info.asProperty().name, match.clazz, index);
}
// Java member not found - try extension methods
if (member == null) {
member = findTemplateExtensionMethod(info, match.clazz, templateExtensionMethods, expression, index,
templateIdToPathFun, results);
}
if (member == null) {
// Test whether the validation should be skipped
Check check = new Check(info.isProperty() ? info.asProperty().name : info.asVirtualMethod().name,
match.clazz, info.part.isVirtualMethod() ? info.part.asVirtualMethod().getParameters().size() : -1);
if (isExcluded(check, excludes)) {
LOGGER.debugf(
"Expression part [%s] excluded from validation of [%s] against class [%s]",
info.value,
expression.toOriginalString(), match.clazz);
match.clear();
break;
}
}
if (member == null) {
// No member found - incorrect expression
incorrectExpressions.produce(new IncorrectExpressionBuildItem(expression.toOriginalString(),
info.value, match.clazz.toString(), expression.getOrigin().getLine(),
expression.getOrigin().getTemplateGeneratedId()));
match.clear();
break;
} else {
match.type = resolveType(member, match, index);
if (match.type.kind() == org.jboss.jandex.Type.Kind.PRIMITIVE) {
break;
}
if (match.type.kind() == Type.Kind.CLASS || match.type.kind() == Type.Kind.PARAMETERIZED_TYPE) {
match.clazz = index.getClassByName(match.type.name());
}
if (info.isProperty()) {
String hint = info.asProperty().hint;
if (hint != null) {
// For example a loop section needs to validate the type of an element
processHints(hint, match, index, expression);
}
}
}
} else {
LOGGER.debugf(
"No match class available - skip further validation for [%s] in expression [%s] in template [%s] on line %s",
info.part, expression.toOriginalString(), expression.getOrigin().getTemplateId(),
expression.getOrigin().getLine());
match.clear();
break;
}
}
results.put(expression.toOriginalString(), match);
}
@BuildStep
void collectTemplateExtensionMethods(BeanArchiveIndexBuildItem beanArchiveIndex,
BuildProducer<TemplateExtensionMethodBuildItem> extensionMethods) {
IndexView index = beanArchiveIndex.getIndex();
Map<MethodInfo, AnnotationInstance> methods = new HashMap<>();
Map<ClassInfo, AnnotationInstance> classes = new HashMap<>();
for (AnnotationInstance templateExtension : index.getAnnotations(ExtensionMethodGenerator.TEMPLATE_EXTENSION)) {
if (templateExtension.target().kind() == Kind.METHOD) {
methods.put(templateExtension.target().asMethod(), templateExtension);
} else if (templateExtension.target().kind() == Kind.CLASS) {
classes.put(templateExtension.target().asClass(), templateExtension);
}
}
// Method-level annotations
for (Entry<MethodInfo, AnnotationInstance> entry : methods.entrySet()) {
MethodInfo method = entry.getKey();
AnnotationValue namespaceValue = entry.getValue().value(ExtensionMethodGenerator.NAMESPACE);
ExtensionMethodGenerator.validate(method, method.parameters(),
namespaceValue != null ? namespaceValue.asString() : null);
produceExtensionMethod(index, extensionMethods, method, entry.getValue());
LOGGER.debugf("Found template extension method %s declared on %s", method,
method.declaringClass().name());
}
// Class-level annotations
for (Entry<ClassInfo, AnnotationInstance> entry : classes.entrySet()) {
ClassInfo clazz = entry.getKey();
AnnotationValue namespaceValue = entry.getValue().value(ExtensionMethodGenerator.NAMESPACE);
String namespace = namespaceValue != null ? namespaceValue.asString() : null;
for (MethodInfo method : clazz.methods()) {
if (!Modifier.isStatic(method.flags()) || method.returnType().kind() == org.jboss.jandex.Type.Kind.VOID
|| Modifier.isPrivate(method.flags())
|| ValueResolverGenerator.isSynthetic(method.flags())) {
// Filter out non-static, synthetic, private and void methods
continue;
}
if ((namespace == null || namespace.isEmpty()) && method.parameters().isEmpty()) {
// Filter methods with no params for non-namespace extensions
continue;
}
if (methods.containsKey(method)) {
// Skip methods annotated with @TemplateExtension - method-level annotation takes precedence
continue;
}
produceExtensionMethod(index, extensionMethods, method, entry.getValue());
LOGGER.debugf("Found template extension method %s declared on %s", method,
method.declaringClass().name());
}
}
}
private void produceExtensionMethod(IndexView index, BuildProducer<TemplateExtensionMethodBuildItem> extensionMethods,
MethodInfo method, AnnotationInstance extensionAnnotation) {
// Analyze matchName and priority so that it could be used during validation
String matchName = null;
AnnotationValue matchNameValue = extensionAnnotation.value(ExtensionMethodGenerator.MATCH_NAME);
if (matchNameValue != null) {
matchName = matchNameValue.asString();
}
if (matchName == null) {
matchName = method.name();
}
int priority = TemplateExtension.DEFAULT_PRIORITY;
AnnotationValue priorityValue = extensionAnnotation.value(ExtensionMethodGenerator.PRIORITY);
if (priorityValue != null) {
priority = priorityValue.asInt();
}
String namespace = "";
AnnotationValue namespaceValue = extensionAnnotation.value(ExtensionMethodGenerator.NAMESPACE);
if (namespaceValue != null) {
namespace = namespaceValue.asString();
}
extensionMethods.produce(new TemplateExtensionMethodBuildItem(method, matchName,
index.getClassByName(method.parameters().get(0).name()), priority, namespace));
}
@BuildStep
void validateBeansInjectedInTemplates(TemplatesAnalysisBuildItem analysis, BeanArchiveIndexBuildItem beanArchiveIndex,
BuildProducer<IncorrectExpressionBuildItem> incorrectExpressions,
List<TemplateExtensionMethodBuildItem> templateExtensionMethods,
List<TypeCheckExcludeBuildItem> excludes,
BeanRegistrationPhaseBuildItem registrationPhase,
// This producer is needed to ensure the correct ordering, ie. this build step must be executed before the ArC validation step
BuildProducer<BeanConfiguratorBuildItem> configurators,
BuildProducer<ImplicitValueResolverBuildItem> implicitClasses) {
IndexView index = beanArchiveIndex.getIndex();
Function<String, String> templateIdToPathFun = new Function<String, String>() {
@Override
public String apply(String id) {
return findTemplatePath(analysis, id);
}
};
Set<Expression> injectExpressions = collectNamespaceExpressions(analysis, EngineProducer.INJECT_NAMESPACE);
if (!injectExpressions.isEmpty()) {
// IMPLEMENTATION NOTE:
// We do not support injection of synthetic beans with names
// Dependency on the ValidationPhaseBuildItem would result in a cycle in the build chain
Map<String, BeanInfo> namedBeans = registrationPhase.getContext().beans().withName()
.collect(toMap(BeanInfo::getName, Function.identity()));
// Map implicit class -> true if methods were used
Map<ClassInfo, Boolean> implicitClassToMethodUsed = new HashMap<>();
for (Expression expression : injectExpressions) {
Expression.Part firstPart = expression.getParts().get(0);
if (firstPart.isVirtualMethod()) {
incorrectExpressions.produce(new IncorrectExpressionBuildItem(expression.toOriginalString(),
"The inject: namespace must be followed by a bean name",
expression.getOrigin().getLine(),
expression.getOrigin().getTemplateGeneratedId()));
continue;
}
String beanName = firstPart.getName();
BeanInfo bean = namedBeans.get(beanName);
if (bean != null) {
if (expression.getParts().size() == 1) {
// Only the bean needs to be validated
continue;
}
validateNestedExpressions(bean.getImplClazz(), new HashMap<>(), templateExtensionMethods, excludes,
incorrectExpressions, expression, index, implicitClassToMethodUsed, templateIdToPathFun);
} else {
// User is injecting a non-existing bean
incorrectExpressions.produce(new IncorrectExpressionBuildItem(expression.toOriginalString(),
beanName, null, expression.getOrigin().getLine(),
expression.getOrigin().getTemplateGeneratedId()));
}
}
for (Entry<ClassInfo, Boolean> implicit : implicitClassToMethodUsed.entrySet()) {
implicitClasses.produce(implicit.getValue()
? new ImplicitValueResolverBuildItem(implicit.getKey(),
new TemplateDataBuilder().properties(false).build())
: new ImplicitValueResolverBuildItem(implicit.getKey()));
}
}
}
static String findTemplatePath(TemplatesAnalysisBuildItem analysis, String id) {
for (TemplateAnalysis templateAnalysis : analysis.getAnalysis()) {
if (templateAnalysis.generatedId.equals(id)) {
return templateAnalysis.path;
}
}
return null;
}
@BuildStep
void generateValueResolvers(QuteConfig config, BuildProducer<GeneratedClassBuildItem> generatedClasses,
CombinedIndexBuildItem combinedIndex, BeanArchiveIndexBuildItem beanArchiveIndex,
ApplicationArchivesBuildItem applicationArchivesBuildItem,
List<TemplatePathBuildItem> templatePaths,
List<TemplateExtensionMethodBuildItem> templateExtensionMethods,
List<ImplicitValueResolverBuildItem> implicitClasses,
TemplatesAnalysisBuildItem templatesAnalysis,
BuildProducer<GeneratedValueResolverBuildItem> generatedResolvers,
BuildProducer<ReflectiveClassBuildItem> reflectiveClass) {
IndexView index = beanArchiveIndex.getIndex();
ClassOutput classOutput = new GeneratedClassGizmoAdaptor(generatedClasses, new Predicate<String>() {
@Override
public boolean test(String name) {
int idx = name.lastIndexOf(ExtensionMethodGenerator.SUFFIX);
if (idx == -1) {
idx = name.lastIndexOf(ValueResolverGenerator.SUFFIX);
}
String className = name.substring(0, idx);
if (className.contains(ValueResolverGenerator.NESTED_SEPARATOR)) {
className = className.replace(ValueResolverGenerator.NESTED_SEPARATOR, "$");
}
//if the class is (directly) in the TCCL (and not its parent) then it is an application class
QuarkusClassLoader cl = (QuarkusClassLoader) Thread.currentThread().getContextClassLoader();
return !cl.getElementsWithResource(className + ".class", true).isEmpty();
}
});
Map<DotName, ClassInfo> nameToClass = new HashMap<>();
Set<DotName> controlled = new HashSet<>();
Map<DotName, AnnotationInstance> uncontrolled = new HashMap<>();
for (AnnotationInstance templateData : index.getAnnotations(ValueResolverGenerator.TEMPLATE_DATA)) {
processsTemplateData(index, templateData, templateData.target(), controlled, uncontrolled, nameToClass);
}
for (AnnotationInstance containerInstance : index.getAnnotations(ValueResolverGenerator.TEMPLATE_DATA_CONTAINER)) {
for (AnnotationInstance templateData : containerInstance.value().asNestedArray()) {
processsTemplateData(index, templateData, containerInstance.target(), controlled, uncontrolled, nameToClass);
}
}
for (ImplicitValueResolverBuildItem implicit : implicitClasses) {
if (controlled.contains(implicit.getClazz().name())) {
LOGGER.debugf("Implicit value resolver build item ignored: %s is annotated with @TemplateData");
continue;
}
AnnotationInstance templateData = uncontrolled.get(implicit.getClazz().name());
if (templateData != null) {
if (!templateData.equals(implicit.getTemplateData())) {
throw new IllegalStateException("Multiple implicit value resolver build items produced for "
+ implicit.getClazz() + " and the synthetic template data is not equal");
}
continue;
}
uncontrolled.put(implicit.getClazz().name(), implicit.getTemplateData());
nameToClass.put(implicit.getClazz().name(), implicit.getClazz());
}
ValueResolverGenerator generator = ValueResolverGenerator.builder().setIndex(index).setClassOutput(classOutput)
.setUncontrolled(uncontrolled)
.build();
// @TemplateData
for (DotName name : controlled) {
generator.generate(nameToClass.get(name));
}
// Uncontrolled classes
for (DotName name : uncontrolled.keySet()) {
generator.generate(nameToClass.get(name));
}
Set<String> generatedTypes = new HashSet<>();
generatedTypes.addAll(generator.getGeneratedTypes());
ExtensionMethodGenerator extensionMethodGenerator = new ExtensionMethodGenerator(classOutput);
Map<DotName, List<TemplateExtensionMethodBuildItem>> classToNamespaceExtensions = new HashMap<>();
Map<String, DotName> namespaceToClass = new HashMap<>();
for (TemplateExtensionMethodBuildItem templateExtension : templateExtensionMethods) {
if (templateExtension.hasNamespace()) {
// Group extension methods declared on the same class by namespace
DotName declaringClassName = templateExtension.getMethod().declaringClass().name();
DotName namespaceClassName = namespaceToClass.get(templateExtension.getNamespace());
if (namespaceClassName == null) {
namespaceToClass.put(templateExtension.getNamespace(), declaringClassName);
} else if (!namespaceClassName.equals(declaringClassName)) {
throw new IllegalStateException("Template extension methods that share the namespace "
+ templateExtension.getNamespace() + " must be declared on the same class; but declared on "
+ namespaceClassName + " and " + declaringClassName);
}
List<TemplateExtensionMethodBuildItem> namespaceMethods = classToNamespaceExtensions
.get(declaringClassName);
if (namespaceMethods == null) {
namespaceMethods = new ArrayList<>();
classToNamespaceExtensions.put(declaringClassName, namespaceMethods);
}
namespaceMethods.add(templateExtension);
} else {
// Generate ValueResolver per extension method
extensionMethodGenerator.generate(templateExtension.getMethod(), templateExtension.getMatchName(),
templateExtension.getPriority());
}
}
// Generate a namespace resolver for extension methods declared on the same class
for (Entry<DotName, List<TemplateExtensionMethodBuildItem>> entry : classToNamespaceExtensions.entrySet()) {
List<TemplateExtensionMethodBuildItem> methods = entry.getValue();
methods.sort(Comparator.comparingInt(TemplateExtensionMethodBuildItem::getPriority));
try (NamespaceResolverCreator namespaceResolverCreator = extensionMethodGenerator
.createNamespaceResolver(methods.get(0).getMethod().declaringClass(), methods.get(0).getNamespace())) {
try (ResolveCreator resolveCreator = namespaceResolverCreator.implementResolve()) {
for (TemplateExtensionMethodBuildItem method : methods) {
resolveCreator.addMethod(method.getMethod(), method.getMatchName());
}
}
}
}
generatedTypes.addAll(extensionMethodGenerator.getGeneratedTypes());
LOGGER.debugf("Generated types: %s", generatedTypes);
for (String generateType : generatedTypes) {
generatedResolvers.produce(new GeneratedValueResolverBuildItem(generateType));
reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, generateType));
}
}
@BuildStep
void collectTemplates(ApplicationArchivesBuildItem applicationArchivesBuildItem,
BuildProducer<HotDeploymentWatchedFileBuildItem> watchedPaths,
BuildProducer<TemplatePathBuildItem> templatePaths,
BuildProducer<NativeImageResourceBuildItem> nativeImageResources)
throws IOException {
ApplicationArchive applicationArchive = applicationArchivesBuildItem.getRootArchive();
String basePath = "templates";
Path templatesPath = applicationArchive.getChildPath(basePath);
if (templatesPath != null) {
scan(templatesPath, templatesPath, basePath + "/", watchedPaths, templatePaths, nativeImageResources);
}
}
@BuildStep
void validateTemplateInjectionPoints(QuteConfig config, List<TemplatePathBuildItem> templatePaths,
ValidationPhaseBuildItem validationPhase,
BuildProducer<ValidationErrorBuildItem> validationErrors) {
Set<String> filePaths = new HashSet<String>();
for (TemplatePathBuildItem templatePath : templatePaths) {
String path = templatePath.getPath();
filePaths.add(path);
// Also add version without suffix from the path
// For example for "items.html" also add "items"
for (String suffix : config.suffixes) {
if (path.endsWith(suffix)) {
filePaths.add(path.substring(0, path.length() - (suffix.length() + 1)));
}
}
}
for (InjectionPointInfo injectionPoint : validationPhase.getContext().get(BuildExtension.Key.INJECTION_POINTS)) {
if (injectionPoint.getRequiredType().name().equals(TEMPLATE)) {
AnnotationInstance resourcePath = injectionPoint.getRequiredQualifier(RESOURCE_PATH);
String name;
if (resourcePath != null) {
name = resourcePath.value().asString();
} else if (injectionPoint.hasDefaultedQualifier()) {
name = getName(injectionPoint);
} else {
name = null;
}
if (name != null) {
// For "@Inject Template items" we try to match "items"
// For "@ResourcePath("github/pulls") Template pulls" we try to match "github/pulls"
if (filePaths.stream().noneMatch(path -> path.endsWith(name))) {
validationErrors.produce(new ValidationErrorBuildItem(
new IllegalStateException("No template found for " + injectionPoint.getTargetInfo())));
}
}
}
}
}
@BuildStep
TemplateVariantsBuildItem collectTemplateVariants(List<TemplatePathBuildItem> templatePaths) throws IOException {
Set<String> allPaths = templatePaths.stream().map(TemplatePathBuildItem::getPath).collect(Collectors.toSet());
// item -> [item.html, item.txt]
// ItemResource/item -> -> [ItemResource/item.html, ItemResource/item.xml]
Map<String, List<String>> baseToVariants = new HashMap<>();
for (String path : allPaths) {
int idx = path.lastIndexOf('.');
if (idx != -1) {
String base = path.substring(0, idx);
List<String> variants = baseToVariants.get(base);
if (variants == null) {
variants = new ArrayList<>();
baseToVariants.put(base, variants);
}
variants.add(path);
}
}
LOGGER.debugf("Template variants found: %s", baseToVariants);
return new TemplateVariantsBuildItem(baseToVariants);
}
@BuildStep
void excludeTypeChecks(BuildProducer<TypeCheckExcludeBuildItem> excludes) {
// Exclude all checks that involve built-in value resolvers
// TODO we need a better way to exclude value resolvers that are not template extension methods
excludes.produce(new TypeCheckExcludeBuildItem(new Predicate<Check>() {
@Override
public boolean test(Check check) {
// RawString
if (check.isProperty() && check.nameIn("raw", "safe")) {
return true;
}
// Elvis and ternary operators
if (check.numberOfParameters == 1 && check.nameIn("?:", "or", ":", "?")) {
return true;
}
// Collection.contains()
if (check.numberOfParameters == 1 && check.classNameEquals(COLLECTION) && check.name.equals("contains")) {
return true;
}
return false;
}
}));
}
@BuildStep
@Record(value = STATIC_INIT)
void initialize(QuteConfig config, BuildProducer<SyntheticBeanBuildItem> syntheticBeans, QuteRecorder recorder,
List<GeneratedValueResolverBuildItem> generatedValueResolvers, List<TemplatePathBuildItem> templatePaths,
Optional<TemplateVariantsBuildItem> templateVariants) {
List<String> templates = new ArrayList<>();
List<String> tags = new ArrayList<>();
for (TemplatePathBuildItem templatePath : templatePaths) {
if (templatePath.isTag()) {
// tags/myTag.html -> myTag.html
String tagPath = templatePath.getPath();
tags.add(tagPath.substring(TemplatePathBuildItem.TAGS.length(), tagPath.length()));
} else {
templates.add(templatePath.getPath());
}
}
Map<String, List<String>> variants;
if (templateVariants.isPresent()) {
variants = templateVariants.get().getVariants();
} else {
variants = Collections.emptyMap();
}
syntheticBeans.produce(SyntheticBeanBuildItem.configure(QuteContext.class)
.supplier(recorder.createContext(config, generatedValueResolvers.stream()
.map(GeneratedValueResolverBuildItem::getClassName).collect(Collectors.toList()), templates,
tags, variants))
.done());
;
}
private static Type resolveType(AnnotationTarget member, Match match, IndexView index) {
Type matchType;
if (member.kind() == Kind.FIELD) {
matchType = member.asField().type();
} else if (member.kind() == Kind.METHOD) {
matchType = member.asMethod().returnType();
} else {
throw new IllegalStateException("Unsupported member type: " + member);
}
// If needed attempt to resolve the type variables using the declaring type
if (Types.containsTypeVariable(matchType)) {
// First get the type closure of the current match type
Set<Type> closure = Types.getTypeClosure(match.clazz, Types.buildResolvedMap(
match.getParameterizedTypeArguments(), match.getTypeParameters(),
new HashMap<>(), index), index);
DotName declaringClassName = member.kind() == Kind.METHOD ? member.asMethod().declaringClass().name()
: member.asField().declaringClass().name();
// Then find the declaring type with resolved type variables
Type declaringType = closure.stream()
.filter(t -> t.name().equals(declaringClassName)).findAny()
.orElse(null);
if (declaringType != null
&& declaringType.kind() == org.jboss.jandex.Type.Kind.PARAMETERIZED_TYPE) {
matchType = Types.resolveTypeParam(matchType,
Types.buildResolvedMap(declaringType.asParameterizedType().arguments(),
index.getClassByName(declaringType.name()).typeParameters(),
Collections.emptyMap(),
index),
index);
}
}