-
Notifications
You must be signed in to change notification settings - Fork 519
Expand file tree
/
Copy pathGroovyParserVisitor.java
More file actions
4147 lines (3825 loc) · 213 KB
/
GroovyParserVisitor.java
File metadata and controls
4147 lines (3825 loc) · 213 KB
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
/*
* Copyright 2021 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite.groovy;
import groovy.lang.GroovySystem;
import groovy.transform.Canonical;
import groovy.transform.Field;
import groovy.transform.Generated;
import groovy.transform.Immutable;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Value;
import org.codehaus.groovy.ast.*;
import org.codehaus.groovy.ast.expr.*;
import org.codehaus.groovy.ast.stmt.*;
import org.codehaus.groovy.control.SourceUnit;
import org.codehaus.groovy.syntax.Token;
import org.codehaus.groovy.syntax.Types;
import org.codehaus.groovy.transform.stc.StaticTypesMarker;
import org.jspecify.annotations.NonNull;
import org.jspecify.annotations.Nullable;
import org.openrewrite.Cursor;
import org.openrewrite.ExecutionContext;
import org.openrewrite.FileAttributes;
import org.openrewrite.groovy.internal.Delimiter;
import org.openrewrite.groovy.marker.*;
import org.openrewrite.groovy.tree.G;
import org.openrewrite.internal.EncodingDetectingInputStream;
import org.openrewrite.internal.ListUtils;
import org.openrewrite.internal.StringUtils;
import org.openrewrite.java.internal.JavaTypeCache;
import org.openrewrite.java.internal.JavaTypeFactory;
import org.openrewrite.java.marker.ImplicitReturn;
import org.openrewrite.java.marker.OmitParentheses;
import org.openrewrite.java.marker.Semicolon;
import org.openrewrite.java.marker.TrailingComma;
import org.openrewrite.java.tree.*;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.Statement;
import org.openrewrite.marker.Markers;
import java.lang.annotation.Annotation;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import static java.lang.Character.isJavaIdentifierPart;
import static java.lang.Character.isWhitespace;
import static java.util.Collections.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import static org.openrewrite.Tree.randomId;
import static org.openrewrite.groovy.internal.Delimiter.*;
import static org.openrewrite.internal.StringUtils.indexOfNextNonWhitespace;
import static org.openrewrite.java.tree.Space.EMPTY;
import static org.openrewrite.java.tree.Space.format;
/**
* See the <a href="https://groovy-lang.org/syntax.html">language syntax reference</a>.
*/
public class GroovyParserVisitor {
private final Path sourcePath;
@Nullable
private final FileAttributes fileAttributes;
private final String source;
private final int[] sourceLineNumberOffsets;
private final Charset charset;
private final boolean charsetBomMarked;
private final GroovyTypeMapping typeMapping;
private int cursor = 0;
/** Maps a trait class name to its synthetic Groovy-generated {@code $Trait$Helper} class. */
private final Map<String, ClassNode> traitHelpers = new HashMap<>();
/** Maps a trait class name to its synthetic Groovy-generated {@code $Trait$FieldHelper} class. */
private final Map<String, ClassNode> traitFieldHelpers = new HashMap<>();
private static final Pattern MULTILINE_COMMENT_REGEX = Pattern.compile("(?s)/\\*.*?\\*/");
private static final Pattern whitespacePrefixPattern = Pattern.compile("^\\s*");
@SuppressWarnings("RegExpSimplifiable")
private static final Pattern whitespaceSuffixPattern = Pattern.compile("\\s*[^\\s]+(\\s*)");
/**
* Elements within GString expressions which omit curly braces have column positions which are incorrect.
* The column positions act like there *is* a curly brace.
*/
private int columnOffset;
@Nullable
private static Boolean olderThanGroovy3;
@Nullable
private static Boolean groovy4OrLater;
@SuppressWarnings("unused")
public GroovyParserVisitor(Path sourcePath, @Nullable FileAttributes fileAttributes, EncodingDetectingInputStream source, JavaTypeCache typeCache, ExecutionContext ctx) {
this(sourcePath, fileAttributes, source, typeCache, null, ctx);
}
@SuppressWarnings("unused")
public GroovyParserVisitor(Path sourcePath, @Nullable FileAttributes fileAttributes, EncodingDetectingInputStream source, JavaTypeCache typeCache, @Nullable JavaTypeFactory typeFactory, ExecutionContext ctx) {
this.sourcePath = sourcePath;
this.fileAttributes = fileAttributes;
this.source = source.readFully();
AtomicInteger counter = new AtomicInteger(1);
AtomicInteger offsetCursor = new AtomicInteger(0);
this.sourceLineNumberOffsets = Arrays.stream(this.source.split("\n")).mapToInt(it -> {
int saveCursor = offsetCursor.get();
offsetCursor.set(saveCursor + it.length() + 1); // + 1 for the `\n` char
return saveCursor;
}).toArray();
this.charset = source.getCharset();
this.charsetBomMarked = source.isCharsetBomMarked();
JavaTypeFactory factory = typeFactory != null ? typeFactory : new org.openrewrite.java.internal.DefaultJavaTypeFactory(typeCache);
this.typeMapping = new GroovyTypeMapping(factory);
}
private static int groovyMajorVersion() {
String groovyVersionText = GroovySystem.getVersion();
return Integer.parseInt(groovyVersionText.substring(0, groovyVersionText.indexOf('.')));
}
private static boolean isOlderThanGroovy3() {
if (olderThanGroovy3 == null) {
olderThanGroovy3 = groovyMajorVersion() < 3;
}
return olderThanGroovy3;
}
private static boolean isGroovy4OrLater() {
if (groovy4OrLater == null) {
groovy4OrLater = groovyMajorVersion() >= 4;
}
return groovy4OrLater;
}
public G.CompilationUnit visit(SourceUnit unit, ModuleNode ast) throws GroovyParsingException {
NavigableMap<LineColumn, ASTNode> sortedByPosition = new TreeMap<>();
for (org.codehaus.groovy.ast.stmt.Statement s : ast.getStatementBlock().getStatements()) {
if (!isSynthetic(s)) {
sortedByPosition.put(pos(s), s);
}
}
String shebang = null;
if (source.startsWith("#!")) {
int i = 0;
while (i < source.length() && source.charAt(i) != '\n' && source.charAt(i) != '\r') {
i++;
}
shebang = source.substring(0, i);
cursor += i;
}
Space prefix = EMPTY;
JRightPadded<J.Package> pkg = null;
if (ast.getPackage() != null) {
prefix = whitespace();
skip("package");
pkg = maybeSemicolon(new J.Package(randomId(), EMPTY, Markers.EMPTY, typeTree(null), emptyList()));
}
for (ImportNode anImport : ast.getImports()) {
sortedByPosition.put(pos(anImport), anImport);
}
for (ImportNode anImport : ast.getStarImports()) {
sortedByPosition.put(pos(anImport), anImport);
}
for (ImportNode anImport : ast.getStaticImports().values()) {
sortedByPosition.put(pos(anImport), anImport);
}
for (ImportNode anImport : getStaticStarImports(ast)) {
sortedByPosition.put(pos(anImport), anImport);
}
for (ClassNode aClass : ast.getClasses()) {
// skip over the synthetic script class
if (!aClass.getName().equals(ast.getMainClassName()) || !aClass.getName().endsWith("doesntmatter")) {
// synthetic helper classes Groovy generates for traits hold the bodies of trait methods/fields;
// record them by their owning trait so we can merge bodies back when visiting the trait
String name = aClass.getName();
int helperIdx = name.indexOf("$Trait$Helper");
if (helperIdx > 0) {
traitHelpers.put(name.substring(0, helperIdx), aClass);
continue;
}
int fieldHelperIdx = name.indexOf("$Trait$FieldHelper");
if (fieldHelperIdx > 0) {
traitFieldHelpers.put(name.substring(0, fieldHelperIdx), aClass);
continue;
}
sortedByPosition.put(pos(aClass), aClass);
}
}
for (MethodNode method : ast.getMethods()) {
sortedByPosition.put(pos(method), method);
}
List<JRightPadded<Statement>> statements = new ArrayList<>(sortedByPosition.size());
for (Map.Entry<LineColumn, ASTNode> entry : sortedByPosition.entrySet()) {
if (entry.getKey().getLine() == -1) {
// default import
continue;
}
try {
if (entry.getValue() instanceof InnerClassNode) {
// Inner classes will be visited as part of visiting their containing class
continue;
}
JRightPadded<Statement> statement = convertTopLevelStatement(unit, entry.getValue());
if (statements.isEmpty() && pkg == null && statement.getElement() instanceof J.Import) {
prefix = statement.getElement().getPrefix();
statement = statement.withElement(statement.getElement().withPrefix(EMPTY));
}
statements.add(statement);
} catch (Throwable t) {
if (t instanceof StringIndexOutOfBoundsException) {
throw new GroovyParsingException("Failed to parse " + sourcePath + ", cursor position likely inaccurate.", t);
}
throw new GroovyParsingException(
"Failed to parse " + sourcePath + " at cursor position " + cursor +
". The surrounding characters in the original source are:\n" +
source.substring(Math.max(0, cursor - 250), cursor) + "~cursor~>" +
source.substring(cursor, Math.min(source.length(), cursor + 250)), t);
}
}
return new G.CompilationUnit(
randomId(),
shebang,
prefix,
Markers.EMPTY,
sourcePath,
fileAttributes,
charset.name(),
charsetBomMarked,
null,
pkg,
statements,
format(source, cursor, source.length())
);
}
@RequiredArgsConstructor
private class RewriteGroovyClassVisitor extends ClassCodeVisitorSupport {
@Getter
private final SourceUnit sourceUnit;
private final Queue<Object> queue = new LinkedList<>();
@Override
public void visitClass(ClassNode clazz) {
Space fmt = whitespace();
List<J.Annotation> leadingAnnotations = visitAndGetAnnotations(clazz, this);
List<J.Modifier> modifiers = getModifiers();
Space kindPrefix = whitespace();
J.ClassDeclaration.Kind.Type kindType;
Markers kindMarkers = Markers.EMPTY;
if (sourceStartsWith("class")) {
kindType = J.ClassDeclaration.Kind.Type.Class;
skip("class");
} else if (sourceStartsWith("trait")) {
kindType = J.ClassDeclaration.Kind.Type.Interface;
kindMarkers = kindMarkers.addIfAbsent(new Trait(randomId()));
skip("trait");
} else if (clazz.isAnnotationDefinition()) {
kindType = J.ClassDeclaration.Kind.Type.Annotation;
skip("@interface");
} else if (clazz.isInterface()) {
kindType = J.ClassDeclaration.Kind.Type.Interface;
skip("interface");
} else if (clazz.isEnum()) {
kindType = J.ClassDeclaration.Kind.Type.Enum;
skip("enum");
} else if (isGroovy4OrLater() && clazz.isRecord()) {
kindType = J.ClassDeclaration.Kind.Type.Record;
skip("record");
} else {
throw new IllegalStateException("Unexpected class type: " + name());
}
J.ClassDeclaration.Kind kind = new J.ClassDeclaration.Kind(randomId(), kindPrefix, kindMarkers, emptyList(), kindType);
J.Identifier name = new J.Identifier(randomId(), whitespace(), Markers.EMPTY, emptyList(), name(), typeMapping.type(clazz), null);
JContainer<J.TypeParameter> typeParameterContainer = null;
if (clazz.isUsingGenerics() && clazz.getGenericsTypes() != null) {
typeParameterContainer = visitTypeParameters(clazz.getGenericsTypes());
}
JContainer<Statement> primaryConstructor = null;
if (kindType == J.ClassDeclaration.Kind.Type.Record) {
Space pcPrefix = sourceBefore("(");
List<RecordComponentNode> components = clazz.getRecordComponents();
if (components == null || components.isEmpty()) {
primaryConstructor = JContainer.build(pcPrefix,
singletonList(JRightPadded.build((Statement) new J.Empty(randomId(), sourceBefore(")"), Markers.EMPTY))),
Markers.EMPTY);
} else {
List<JRightPadded<Statement>> componentDecls = new ArrayList<>(components.size());
for (int i = 0; i < components.size(); i++) {
RecordComponentNode rc = components.get(i);
Space compPrefix = whitespace();
TypeTree typeExpr = visitTypeTree(rc.getType());
J.Identifier compName = new J.Identifier(randomId(), sourceBefore(rc.getName()), Markers.EMPTY,
emptyList(), rc.getName(), typeMapping.type(rc.getType()), null);
J.VariableDeclarations.NamedVariable namedVar = new J.VariableDeclarations.NamedVariable(
randomId(), compName.getPrefix(), Markers.EMPTY,
compName.withPrefix(EMPTY), emptyList(), null, typeMapping.variableType(compName.getSimpleName(), rc.getType()));
J.VariableDeclarations varDecl = new J.VariableDeclarations(randomId(), compPrefix, Markers.EMPTY,
emptyList(), emptyList(), typeExpr, null, emptyList(), singletonList(JRightPadded.build(namedVar)));
componentDecls.add(JRightPadded.build((Statement) varDecl)
.withAfter(i == components.size() - 1 ? sourceBefore(")") : sourceBefore(",")));
}
primaryConstructor = JContainer.build(pcPrefix, componentDecls, Markers.EMPTY);
}
}
JLeftPadded<TypeTree> extendings = null;
if (kindType == J.ClassDeclaration.Kind.Type.Class) {
if (sourceStartsWith("extends")) {
extendings = padLeft(sourceBefore("extends"), visitTypeTree(clazz.getSuperClass()));
}
}
JContainer<TypeTree> implementings = null;
Markers implementingsMarkers = Markers.EMPTY;
if (clazz.getInterfaces().length > 0) {
Space implPrefix;
boolean isTrait = kindMarkers.findFirst(Trait.class).isPresent();
// Traits can have either "extends" (extending another trait) or "implements" (implementing a regular interface)
boolean traitImplements = false;
if (isTrait) {
int saveCursor = cursor;
whitespace();
traitImplements = source.startsWith("implements", cursor);
cursor = saveCursor;
implPrefix = traitImplements ? sourceBefore("implements") : sourceBefore("extends");
} else if (kindType == J.ClassDeclaration.Kind.Type.Interface || kindType == J.ClassDeclaration.Kind.Type.Annotation) {
implPrefix = sourceBefore("extends");
} else {
implPrefix = sourceBefore("implements");
}
if (traitImplements) {
implementingsMarkers = implementingsMarkers.addIfAbsent(new TraitImplementsKeyword(randomId()));
}
List<JRightPadded<TypeTree>> implTypes = new ArrayList<>(clazz.getInterfaces().length);
ClassNode[] interfaces = clazz.getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
ClassNode anInterface = interfaces[i];
// Any annotation @interface is listed as extending java.lang.annotation.Annotation, although it doesn't appear in source
if (kindType == J.ClassDeclaration.Kind.Type.Annotation && Annotation.class.getName().equals(anInterface.getName())) {
continue;
}
implTypes.add(JRightPadded.build(visitTypeTree(anInterface))
.withAfter(i == interfaces.length - 1 ? EMPTY : sourceBefore(",")));
}
// Can be empty for an annotation @interface which only implements Annotation
if (!implTypes.isEmpty()) {
implementings = JContainer.build(implPrefix, implTypes, implementingsMarkers);
}
}
JContainer<TypeTree> permitting = null;
if (isGroovy4OrLater() && clazz.isSealed() && clazz.getPermittedSubclasses() != null && !clazz.getPermittedSubclasses().isEmpty()) {
Space permitsPrefix = sourceBefore("permits");
List<ClassNode> permitted = clazz.getPermittedSubclasses();
List<JRightPadded<TypeTree>> permitTypes = new ArrayList<>(permitted.size());
for (int i = 0; i < permitted.size(); i++) {
permitTypes.add(JRightPadded.build(visitTypeTree(permitted.get(i)))
.withAfter(i == permitted.size() - 1 ? EMPTY : sourceBefore(",")));
}
permitting = JContainer.build(permitsPrefix, permitTypes, Markers.EMPTY);
}
queue.add(new J.ClassDeclaration(randomId(), fmt, Markers.EMPTY,
leadingAnnotations,
modifiers,
kind,
name,
typeParameterContainer,
primaryConstructor,
extendings,
implementings,
permitting,
visitClassBlock(clazz),
TypeUtils.asFullyQualified(typeMapping.type(clazz))));
}
/**
* Find the helper method on a trait's {@code $Trait$Helper} class that corresponds to {@code traitMethod}.
* The helper version has the trait instance prepended as a synthetic {@code $self} parameter.
*/
private @Nullable MethodNode findTraitHelperMethod(ClassNode helper, MethodNode traitMethod) {
for (MethodNode candidate : helper.getMethods(traitMethod.getName())) {
Parameter[] params = candidate.getParameters();
if (params.length == traitMethod.getParameters().length + 1 &&
("$self".equals(params[0].getName()) || "$static$self".equals(params[0].getName()))) {
return candidate;
}
}
return null;
}
/**
* Recover trait field declarations whose source positions were lost by Groovy's trait AST transformation.
* The transformation strips fields from the trait class and exposes them only as abstract accessors on a
* {@code $Trait$FieldHelper} interface. Walk the helper for accessor methods to learn each field's name,
* type, and modifiers, scan the trait body source for the matching declaration, then synthesize a
* {@link FieldNode} with valid source positions and add it to {@code sortedByPosition} so the existing
* field-printing path picks it up.
*/
private void recoverTraitFields(ClassNode clazz, ClassNode fieldHelper, NavigableMap<LineColumn, ASTNode> sortedByPosition, int blockBodyStart) {
String traitName = clazz.getNameWithoutPackage();
String accessorPrefix = traitName + "__";
// fieldName -> getter (carries return type + modifiers)
Map<String, MethodNode> getters = new LinkedHashMap<>();
for (MethodNode m : fieldHelper.getMethods()) {
String name = m.getName();
if (name.startsWith(accessorPrefix) && name.endsWith("$get")) {
getters.put(name.substring(accessorPrefix.length(), name.length() - 4), m);
}
}
// Backing fields on the helper carry the original type and initial expression even when their own
// positions are -1. Static-only fields don't get $get/$set accessors, so the backing fields are also
// the only place to discover their names.
Map<String, FieldNode> backingFields = new LinkedHashMap<>();
for (FieldNode bf : fieldHelper.getFields()) {
int idx = bf.getName().indexOf(accessorPrefix);
if (idx >= 0) {
String fieldName = bf.getName().substring(idx + accessorPrefix.length());
FieldNode existing = backingFields.get(fieldName);
if (existing == null || (existing.getInitialExpression() == null && bf.getInitialExpression() != null)) {
backingFields.put(fieldName, bf);
}
}
}
// Trait field initializers are stored on the trait helper as setter calls inside $init$ / $static$init$:
// ((TraitName$Trait$FieldHelper) $self).TraitName__field$set((castedType) <init expr>)
// Walk those bodies to recover the original initial expression for each field.
Map<String, org.codehaus.groovy.ast.expr.Expression> initialExpressions = new HashMap<>();
ClassNode traitHelperClass = traitHelpers.get(clazz.getName());
if (traitHelperClass != null) {
for (MethodNode m : traitHelperClass.getMethods()) {
if (("$init$".equals(m.getName()) || "$static$init$".equals(m.getName())) && m.getCode() instanceof BlockStatement) {
for (org.codehaus.groovy.ast.stmt.Statement s : ((BlockStatement) m.getCode()).getStatements()) {
if (!(s instanceof org.codehaus.groovy.ast.stmt.ExpressionStatement)) {
continue;
}
org.codehaus.groovy.ast.expr.Expression e = ((org.codehaus.groovy.ast.stmt.ExpressionStatement) s).getExpression();
if (!(e instanceof MethodCallExpression)) {
continue;
}
MethodCallExpression mce = (MethodCallExpression) e;
String methodName = mce.getMethodAsString();
if (methodName == null || !(mce.getArguments() instanceof org.codehaus.groovy.ast.expr.TupleExpression)) {
continue;
}
List<org.codehaus.groovy.ast.expr.Expression> args = ((org.codehaus.groovy.ast.expr.TupleExpression) mce.getArguments()).getExpressions();
String fieldName = null;
org.codehaus.groovy.ast.expr.Expression initArg = null;
if (methodName.startsWith(accessorPrefix) && methodName.endsWith("$set") && !args.isEmpty()) {
// Direct setter call: ((FieldHelper) $self).TraitName__field$set(<initExpr>)
fieldName = methodName.substring(accessorPrefix.length(), methodName.length() - 4);
initArg = args.get(0);
} else if ("invokeStaticMethod".equals(methodName) && args.size() >= 3 &&
args.get(1) instanceof ConstantExpression &&
((ConstantExpression) args.get(1)).getValue() instanceof String) {
// Reflective static setter: InvokerHelper.invokeStaticMethod($static$self, "TraitName__field$set", <initExpr>)
String setterName = (String) ((ConstantExpression) args.get(1)).getValue();
if (setterName.startsWith(accessorPrefix) && setterName.endsWith("$set")) {
fieldName = setterName.substring(accessorPrefix.length(), setterName.length() - 4);
initArg = args.get(2);
}
}
if (fieldName != null && initArg != null) {
if (initArg instanceof CastExpression) {
initArg = ((CastExpression) initArg).getExpression();
}
initialExpressions.put(fieldName, initArg);
}
}
}
}
}
Set<String> fieldNames = new LinkedHashSet<>(getters.keySet());
fieldNames.addAll(backingFields.keySet());
if (fieldNames.isEmpty()) {
return;
}
Map<String, Integer> declarationStarts = scanTraitBodyForFieldDeclarations(blockBodyStart, fieldNames);
for (Map.Entry<String, Integer> e : declarationStarts.entrySet()) {
String fieldName = e.getKey();
int declStart = e.getValue();
MethodNode getter = getters.get(fieldName);
FieldNode backing = backingFields.get(fieldName);
int modifiers;
ClassNode fieldType;
if (getter != null) {
modifiers = getter.getModifiers() & ~java.lang.reflect.Modifier.ABSTRACT;
fieldType = getter.getReturnType();
} else {
// Static-only fields lack accessors; reconstruct modifiers from the backing field.
modifiers = backing.getModifiers() & ~java.lang.reflect.Modifier.PRIVATE & ~java.lang.reflect.Modifier.FINAL;
fieldType = backing.getOriginType();
}
org.codehaus.groovy.ast.expr.Expression initExpr = initialExpressions.get(fieldName);
if (initExpr == null && backing != null) {
initExpr = backing.getInitialExpression();
}
FieldNode synth = new FieldNode(
fieldName,
modifiers,
fieldType,
clazz,
initExpr
);
int line = lineOf(declStart);
int column = declStart - sourceLineNumberOffsets[line - 1] + 1;
synth.setLineNumber(line);
synth.setColumnNumber(column);
synth.setLastLineNumber(line);
synth.setLastColumnNumber(column + fieldName.length());
sortedByPosition.put(pos(synth), synth);
}
}
/**
* Scan from {@code start} (just past the trait body's opening {@code {}) to the matching {@code }},
* skipping nested braces, strings, comments, and regex/slashy literals. Return the start position of
* each top-level declaration whose name appears in {@code fieldNames}.
*/
private Map<String, Integer> scanTraitBodyForFieldDeclarations(int start, Set<String> fieldNames) {
Map<String, Integer> result = new LinkedHashMap<>();
int len = source.length();
int depth = 1;
// Tracks where the next top-level statement *could* start (after a separator, just past whitespace).
int statementStart = start;
int i = start;
while (i < len && depth > 0) {
char c = source.charAt(i);
if (depth == 1) {
Delimiter d = getDelimiter(null, i);
if (d != null && d != CLOSURE && d != ARRAY) {
// Skip past string/comment/regex
i += d.open.length();
while (i < len && !source.startsWith(d.close, i)) {
i++;
}
i += d.close.length();
continue;
}
}
if (c == '{') {
depth++;
i++;
continue;
}
if (c == '}') {
depth--;
i++;
if (depth == 1) {
statementStart = i;
}
continue;
}
if (depth > 1) {
i++;
continue;
}
if (c == ';' || c == '\n') {
i++;
statementStart = i;
continue;
}
if (Character.isJavaIdentifierStart(c)) {
int idStart = i;
while (i < len && Character.isJavaIdentifierPart(source.charAt(i))) {
i++;
}
String id = source.substring(idStart, i);
if (fieldNames.contains(id) && !result.containsKey(id)) {
// Verify this looks like a declaration: after the identifier, the next non-whitespace
// is one of `=`, `;`, `\n`, `}` (i.e., ends a simple declaration), not `(` (method),
// `.` (chained access), or operators that would indicate a reference.
int j = i;
while (j < len && (source.charAt(j) == ' ' || source.charAt(j) == '\t')) {
j++;
}
if (j < len) {
char next = source.charAt(j);
if (next == '=' || next == '\n' || next == ';' || next == '}' || next == '\r') {
// Find first non-whitespace from statementStart - that's the declaration start
int declStart = statementStart;
while (declStart < idStart && Character.isWhitespace(source.charAt(declStart))) {
declStart++;
}
if (declStart <= idStart) {
result.put(id, declStart);
}
}
}
}
continue;
}
i++;
}
return result;
}
private int lineOf(int position) {
int line = Arrays.binarySearch(sourceLineNumberOffsets, position);
return line >= 0 ? line + 1 : -line - 1;
}
J.Block visitClassBlock(ClassNode clazz) {
NavigableMap<LineColumn, ASTNode> sortedByPosition = new TreeMap<>();
List<FieldNode> enumConstants = new ArrayList<>();
// Groovy's trait AST transformation strips method bodies from the trait and moves them to a synthetic
// $Trait$Helper class, leaving the trait class with only abstract method signatures. Substitute each
// trait method with its helper counterpart so we can recover the original body when visiting it.
ClassNode helperForTrait = traitHelpers.get(clazz.getName());
for (MethodNode method : clazz.getMethods()) {
// Most synthetic methods do not appear in source code and should be skipped entirely.
if (method.isSynthetic()) {
// Static initializer blocks show up as a synthetic method with name <clinit>
// The part that actually appears in source code is a block statement inside the method declaration
if ("<clinit>".equals(method.getName()) && method.getCode() instanceof BlockStatement && ((BlockStatement) method.getCode()).getStatements().size() == 1) {
org.codehaus.groovy.ast.stmt.Statement statement = ((BlockStatement) method.getCode()).getStatements().get(0);
sortedByPosition.put(pos(statement), statement);
}
} else if (method.getAnnotations(new ClassNode(Generated.class)).isEmpty() && appearsInSource(method)) {
MethodNode toAdd = method;
if (helperForTrait != null) {
MethodNode helperMethod = findTraitHelperMethod(helperForTrait, method);
if (helperMethod != null) {
toAdd = helperMethod;
}
}
sortedByPosition.put(pos(toAdd), toAdd);
}
}
// For traits, the AST transformation may move static methods entirely to the $Trait$Helper class,
// leaving the trait class with no source-positioned counterpart. Pick those up from the helper.
if (helperForTrait != null) {
for (MethodNode helperMethod : helperForTrait.getMethods()) {
if (helperMethod.isSynthetic() || !appearsInSource(helperMethod)) {
continue;
}
Parameter[] params = helperMethod.getParameters();
if (params.length == 0 || !"$static$self".equals(params[0].getName())) {
continue;
}
sortedByPosition.put(pos(helperMethod), helperMethod);
}
}
for (org.codehaus.groovy.ast.stmt.Statement objectInitializer : clazz.getObjectInitializerStatements()) {
if (!(objectInitializer instanceof BlockStatement)) {
continue;
}
// A class initializer BlockStatement will be wrapped in an otherwise empty BlockStatement with the same source positions
// No idea why, except speculation that it is for consistency with static intiializers, but we can skip the wrapper and just visit its contents
BlockStatement s = (BlockStatement) objectInitializer;
if (s.getStatements().size() == 1 && pos(s).equals(pos(s.getStatements().get(0)))) {
s = (BlockStatement) s.getStatements().get(0);
}
sortedByPosition.put(pos(s), s);
}
/*
In certain circumstances the same AST node may appear in multiple places.
class A {
def a = new Object() {
// this anonymous class is both part of the initializing expression for the variable "a"
// And appears in the list of inner classes of "A"
}
}
So keep track of inner classes that are part of field initializers so that they don't get parsed twice
*/
Set<InnerClassNode> fieldInitializers = new HashSet<>();
Set<String> recordComponentNames = new HashSet<>();
if (isGroovy4OrLater() && clazz.getRecordComponents() != null) {
for (RecordComponentNode rc : clazz.getRecordComponents()) {
recordComponentNames.add(rc.getName());
}
}
for (FieldNode field : clazz.getFields()) {
if (!appearsInSource(field)) {
continue;
}
if (field.isEnum()) {
enumConstants.add(field);
continue;
}
// Record component backing fields are synthetic but have source positions; skip them
if (field.isSynthetic() && recordComponentNames.contains(field.getName())) {
continue;
}
if (field.getInitialExpression() instanceof ConstructorCallExpression) {
ConstructorCallExpression cce = (ConstructorCallExpression) field.getInitialExpression();
if (cce.isUsingAnonymousInnerClass() && cce.getType() instanceof InnerClassNode) {
fieldInitializers.add((InnerClassNode) cce.getType());
}
}
sortedByPosition.put(pos(field), field);
}
for (ConstructorNode ctor : clazz.getDeclaredConstructors()) {
if (!appearsInSource(ctor)) {
continue;
}
sortedByPosition.put(pos(ctor), ctor);
}
Iterator<InnerClassNode> innerClassIterator = clazz.getInnerClasses();
while (innerClassIterator.hasNext()) {
InnerClassNode icn = innerClassIterator.next();
if (icn.isSynthetic() || fieldInitializers.contains(icn) || icn.getName().contains("$Trait$") || !appearsInSource(icn)) {
continue;
}
sortedByPosition.put(pos(icn), icn);
}
Space blockPrefix = sourceBefore("{");
// The trait AST transformation strips fields entirely from the trait class and synthesizes them on the
// $Trait$FieldHelper interface with no source positions. Recover them by reading source between the
// trait's `{` and matching `}` for declarations matching the field names exposed by the helper getters.
ClassNode fieldHelperForTrait = traitFieldHelpers.get(clazz.getName());
if (fieldHelperForTrait != null) {
recoverTraitFields(clazz, fieldHelperForTrait, sortedByPosition, cursor);
}
List<JRightPadded<Statement>> statements = new ArrayList<>();
if (!enumConstants.isEmpty()) {
enumConstants.sort(Comparator.comparing(GroovyParserVisitor::pos));
List<JRightPadded<J.EnumValue>> enumValues = new ArrayList<>();
for (int i = 0; i < enumConstants.size(); i++) {
J.EnumValue enumValue = visitEnumField(enumConstants.get(i));
JRightPadded<J.EnumValue> paddedEnumValue = JRightPadded.build(enumValue).withAfter(whitespace());
if (sourceStartsWith(",")) {
skip(",");
if (i == enumConstants.size() - 1) {
paddedEnumValue = paddedEnumValue.withMarkers(Markers.build(singleton(new TrailingComma(randomId(), whitespace()))));
}
}
enumValues.add(paddedEnumValue);
}
J.EnumValueSet enumValueSet = new J.EnumValueSet(randomId(), EMPTY, Markers.EMPTY, enumValues, sourceStartsWith(";"));
if (enumValueSet.isTerminatedWithSemicolon()) {
skip(";");
}
statements.add(JRightPadded.build(enumValueSet));
}
return new J.Block(randomId(), blockPrefix, Markers.EMPTY,
JRightPadded.build(false),
ListUtils.concatAll(statements, sortedByPosition.values().stream()
// anonymous classes will be visited as part of visiting the ConstructorCallExpression
.filter(ast -> !(ast instanceof InnerClassNode && ((InnerClassNode) ast).isAnonymous()))
.map(ast -> {
if (ast instanceof FieldNode) {
visitField((FieldNode) ast);
} else if (ast instanceof MethodNode) {
visitMethod((MethodNode) ast);
} else if (ast instanceof ClassNode) {
visitClass((ClassNode) ast);
} else if (ast instanceof BlockStatement) {
visitBlockStatement((BlockStatement) ast);
}
Statement stat = pollQueue();
return maybeSemicolon(stat);
})
.collect(toList())),
sourceBefore("}"));
}
@Override
public void visitBlockStatement(BlockStatement statement) {
queue.add(new RewriteGroovyVisitor(statement, this)
.doVisit(statement));
}
@Override
public void visitField(FieldNode field) {
if (field.isEnum()) {
// Enum constants are handled separately in visitClassBlock, thus should be skipped here
return;
}
visitVariableField(field);
}
private J.EnumValue visitEnumField(FieldNode field) {
Space prefix = whitespace();
List<J.Annotation> annotations = visitAndGetAnnotations(field, this);
Space namePrefix = whitespace();
String enumName = skip(field.getName());
J.Identifier name = new J.Identifier(randomId(), namePrefix, Markers.EMPTY, emptyList(), enumName, typeMapping.type(field.getType()), typeMapping.variableType(field));
// Groovy 4 represents enum constants with anonymous class bodies by appending a
// ClassExpression as the last element of the ListExpression initializer
InnerClassNode anonymousClassNode = null;
if (field.getInitialExpression() instanceof ListExpression) {
ListExpression listExpr = (ListExpression) field.getInitialExpression();
List<org.codehaus.groovy.ast.expr.Expression> allExprs = listExpr.getExpressions();
if (!allExprs.isEmpty() && allExprs.get(allExprs.size() - 1) instanceof ClassExpression) {
ClassExpression classExpr = (ClassExpression) allExprs.get(allExprs.size() - 1);
if (classExpr.getType() instanceof InnerClassNode && ((InnerClassNode) classExpr.getType()).isAnonymous()) {
anonymousClassNode = (InnerClassNode) classExpr.getType();
}
}
}
J.NewClass initializer = null;
if (sourceStartsWith("(")) {
Space prefixNewClass = whitespace();
skip("(");
RewriteGroovyVisitor visitor = new RewriteGroovyVisitor(field, this);
ListExpression arguments = (ListExpression) field.getInitialExpression();
// Filter out the trailing ClassExpression that represents the anonymous class body
List<org.codehaus.groovy.ast.expr.Expression> realArgs = anonymousClassNode != null ?
arguments.getExpressions().subList(0, arguments.getExpressions().size() - 1) :
arguments.getExpressions();
List<JRightPadded<Expression>> list;
if (realArgs.isEmpty()) {
list = singletonList(JRightPadded.build((Expression) new J.Empty(randomId(), sourceBefore(")"), Markers.EMPTY)));
} else {
list = visitor.convertAll(realArgs, n -> sourceBefore(","), n -> whitespace(), n -> {
if (n == realArgs.get(realArgs.size() - 1) && source.charAt(cursor) == ',') {
cursor++;
return Markers.build(singleton(new TrailingComma(randomId(), whitespace())));
}
return Markers.EMPTY;
});
skip(")");
}
MethodNode ctor = null;
for (ConstructorNode constructor : field.getOwner().getDeclaredConstructors()) {
if (constructor.getParameters().length == realArgs.size()) {
ctor = constructor;
}
}
J.Block body = anonymousClassNode != null ? visitClassBlock(anonymousClassNode) : null;
initializer = new J.NewClass(randomId(), prefixNewClass, Markers.EMPTY, null, EMPTY, null, JContainer.build(list), body, typeMapping.methodType(ctor));
} else if (anonymousClassNode != null) {
// Enum constant with anonymous body but no constructor args, e.g. `A2 { ... }`
MethodNode ctor = null;
for (ConstructorNode constructor : field.getOwner().getDeclaredConstructors()) {
if (constructor.getParameters().length == 0) {
ctor = constructor;
}
}
JContainer<Expression> args = JContainer.<Expression>empty()
.withMarkers(Markers.build(singleton(new OmitParentheses(randomId()))));
J.Block body = visitClassBlock(anonymousClassNode);
initializer = new J.NewClass(randomId(), EMPTY, Markers.EMPTY, null, EMPTY, null, args, body, typeMapping.methodType(ctor));
}
return new J.EnumValue(randomId(), prefix, Markers.EMPTY, annotations, name, initializer);
}
private void visitVariableField(FieldNode field) {
RewriteGroovyVisitor visitor = new RewriteGroovyVisitor(field, this);
// Groovy emits a separate FieldNode per variable in a multi-variable declaration (e.g. `final String a, b`);
// continuation fields have no modifiers or type keyword in the source, so skip past just the comma.
Optional<MultiVariable> multiVariable = visitor.maybeMultiVariable();
List<J.Annotation> annotations = multiVariable.isPresent() ? emptyList() : visitAndGetAnnotations(field, this);
List<J.Modifier> modifiers = multiVariable.isPresent() ? emptyList() : getModifiers();
TypeTree typeExpr;
if (field.isDynamicTyped()) {
typeExpr = null;
} else if (multiVariable.isPresent()) {
typeExpr = new J.Identifier(randomId(), EMPTY, Markers.EMPTY, emptyList(), "", typeMapping.type(field.getOriginType()), null);
} else {
typeExpr = visitTypeTree(field.getOriginType());
}
J.Identifier name = new J.Identifier(randomId(), sourceBefore(field.getName()), Markers.EMPTY,
emptyList(), field.getName(), typeMapping.type(field.getOriginType()), typeMapping.variableType(field));
J.VariableDeclarations.NamedVariable namedVariable = new J.VariableDeclarations.NamedVariable(
randomId(),
name.getPrefix(),
Markers.EMPTY,
name.withPrefix(EMPTY),
emptyList(),
null,
typeMapping.variableType(field)
);
if (field.getInitialExpression() != null) {
Space beforeAssign = sourceBefore("=");
Expression initializer = visitor.doVisit(field.getInitialExpression());
namedVariable = namedVariable.getPadding().withInitializer(padLeft(beforeAssign, initializer));
}
J.VariableDeclarations variableDeclarations = new J.VariableDeclarations(
randomId(),
EMPTY,
multiVariable.<Markers>map(mv -> Markers.build(singleton(mv))).orElse(Markers.EMPTY),
annotations,
modifiers,
typeExpr,
null,
singletonList(JRightPadded.build(namedVariable))
);
queue.add(variableDeclarations);
}
@Override
protected void visitAnnotation(AnnotationNode annotation) {
GroovyParserVisitor.this.visitAnnotation(annotation, this);
}
@Override
public void visitMethod(MethodNode method) {
Space fmt = whitespace();
List<J.Annotation> annotations = visitAndGetAnnotations(method, this);
List<J.Modifier> modifiers = getModifiers();
boolean isConstructorOfEnum = false;
boolean isConstructorOfInnerNonStaticClass = false;
J.TypeParameters typeParameters = null;
if (method.getGenericsTypes() != null) {
Space prefix = sourceBefore("<");
GenericsType[] genericsTypes = method.getGenericsTypes();
List<JRightPadded<J.TypeParameter>> typeParametersList = new ArrayList<>(genericsTypes.length);
for (int i = 0; i < genericsTypes.length; i++) {
typeParametersList.add(JRightPadded.build(visitTypeParameter(genericsTypes[i]))
.withAfter(i < genericsTypes.length - 1 ? sourceBefore(",") : sourceBefore(">")));
}
typeParameters = new J.TypeParameters(randomId(), prefix, Markers.EMPTY, emptyList(), typeParametersList);
}
TypeTree returnType = method instanceof ConstructorNode || method.isDynamicReturnType() ? null : visitTypeTree(method.getReturnType());
Space namePrefix = whitespace();
String methodName;
if (method instanceof ConstructorNode) {
// To support special constructors well, the groovy compiler adds extra parameters and statements to the constructor under the hood.
// In our LST, we don't need this internal logic.
if (method.getDeclaringClass().isEnum()) {
/*
For enums, there are two extra parameters and wraps the block in a super call:
enum A { enum A {
A1 A1
A(String s) { => A(String __str, int __int, String s) {
println "ss" => super() { println "ss" }
} }
} }
*/
isConstructorOfEnum = true;
} else {
/*
For Java syntax for non-static inner classes, there's an extra parameter with a reference to its parent class and two statements (ConstructorCallExpression and BlockStatement):
class A { class A {
class B { class B {
String s String s
B(String s) { => B(A $p$, String s) {
=> new Object().this$0 = $p$
this.s = s => this.s = s
} }
} }
}
See also: https://groovy-lang.org/differences.html#_creating_instances_of_non_static_inner_classes
*/
isConstructorOfInnerNonStaticClass = method.getDeclaringClass() instanceof InnerClassNode && (method.getDeclaringClass().getModifiers() & Modifier.STATIC) == 0;
}
methodName = method.getDeclaringClass().getNameWithoutPackage().replaceFirst(".*\\$", "");
} else if (source.startsWith(method.getName(), cursor)) {
methodName = method.getName();
} else {
// Method name might be in quotes