-
Notifications
You must be signed in to change notification settings - Fork 371
/
Copy pathGroovyParserVisitor.java
2563 lines (2344 loc) · 123 KB
/
GroovyParserVisitor.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
/*
* 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 groovyjarjarasm.asm.Opcodes;
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.transform.stc.StaticTypesMarker;
import org.openrewrite.Cursor;
import org.openrewrite.ExecutionContext;
import org.openrewrite.FileAttributes;
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.lang.NonNull;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.java.internal.JavaTypeCache;
import org.openrewrite.java.marker.ImplicitReturn;
import org.openrewrite.java.marker.Semicolon;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.Statement;
import org.openrewrite.java.tree.*;
import org.openrewrite.marker.Markers;
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.Collectors;
import java.util.stream.Stream;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.openrewrite.Tree.randomId;
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 Charset charset;
private final boolean charsetBomMarked;
private final GroovyTypeMapping typeMapping;
private int cursor = 0;
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;
@SuppressWarnings("unused")
public GroovyParserVisitor(Path sourcePath, @Nullable FileAttributes fileAttributes, EncodingDetectingInputStream source, JavaTypeCache typeCache, ExecutionContext ctx) {
this.sourcePath = sourcePath;
this.fileAttributes = fileAttributes;
this.source = source.readFully();
this.charset = source.getCharset();
this.charsetBomMarked = source.isCharsetBomMarked();
this.typeMapping = new GroovyTypeMapping(typeCache);
}
public G.CompilationUnit visit(SourceUnit unit, ModuleNode ast) throws GroovyParsingException {
NavigableMap<LineColumn, List<ASTNode>> sortedByPosition = new TreeMap<>();
for (org.codehaus.groovy.ast.stmt.Statement s : ast.getStatementBlock().getStatements()) {
if (!isSynthetic(s)) {
sortedByPosition.computeIfAbsent(pos(s), i -> new ArrayList<>()).add(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();
cursor += "package".length();
pkg = JRightPadded.build(new J.Package(randomId(), EMPTY, Markers.EMPTY,
typeTree(null), emptyList()));
}
for (ImportNode anImport : ast.getImports()) {
sortedByPosition.computeIfAbsent(pos(anImport), i -> new ArrayList<>()).add(anImport);
}
for (ImportNode anImport : ast.getStarImports()) {
sortedByPosition.computeIfAbsent(pos(anImport), i -> new ArrayList<>()).add(anImport);
}
for (ImportNode anImport : ast.getStaticImports().values()) {
sortedByPosition.computeIfAbsent(pos(anImport), i -> new ArrayList<>()).add(anImport);
}
for (ImportNode anImport : ast.getStaticStarImports().values()) {
sortedByPosition.computeIfAbsent(pos(anImport), i -> new ArrayList<>()).add(anImport);
}
for (ClassNode aClass : ast.getClasses()) {
if (aClass.getSuperClass() == null
|| !("groovy.lang.Script".equals(aClass.getSuperClass().getName())
|| "RewriteGradleProject".equals(aClass.getSuperClass().getName())
|| "RewriteSettings".equals(aClass.getSuperClass().getName()))) {
sortedByPosition.computeIfAbsent(pos(aClass), i -> new ArrayList<>()).add(aClass);
}
}
for (MethodNode method : ast.getMethods()) {
sortedByPosition.computeIfAbsent(pos(method), i -> new ArrayList<>()).add(method);
}
List<JRightPadded<Statement>> statements = new ArrayList<>(sortedByPosition.size());
for (Map.Entry<LineColumn, List<ASTNode>> entry : sortedByPosition.entrySet()) {
if (entry.getKey().getLine() == -1) {
// default import
continue;
}
try {
for (ASTNode value : entry.getValue()) {
if (value instanceof InnerClassNode) {
// Inner classes will be visited as part of visiting their containing class
continue;
}
JRightPadded<Statement> statement = convertTopLevelStatement(unit, value);
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 next 10 characters in the original source are `" +
source.substring(cursor, Math.min(source.length(), cursor + 10)) + "`", t);
}
}
return new G.CompilationUnit(
randomId(),
shebang,
prefix,
Markers.EMPTY,
sourcePath,
fileAttributes,
charset.name(),
charsetBomMarked,
null,
pkg,
statements,
format(source.substring(cursor))
);
}
@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;
if (clazz.getAnnotations().isEmpty()) {
leadingAnnotations = emptyList();
} else {
leadingAnnotations = new ArrayList<>(clazz.getAnnotations().size());
for (AnnotationNode annotation : clazz.getAnnotations()) {
visitAnnotation(annotation);
leadingAnnotations.add(pollQueue());
}
}
List<J.Modifier> modifiers = visitModifiers(clazz.getModifiers());
Space kindPrefix = whitespace();
J.ClassDeclaration.Kind.Type kindType = null;
if (source.startsWith("class", cursor)) {
kindType = J.ClassDeclaration.Kind.Type.Class;
cursor += "class".length();
} else if (source.startsWith("interface", cursor)) {
kindType = J.ClassDeclaration.Kind.Type.Interface;
cursor += "interface".length();
} else if (source.startsWith("@interface", cursor)) {
kindType = J.ClassDeclaration.Kind.Type.Annotation;
cursor += "@interface".length();
} else if (source.startsWith("enum", cursor)) {
kindType = J.ClassDeclaration.Kind.Type.Enum;
cursor += "enum".length();
}
assert kindType != null;
J.ClassDeclaration.Kind kind = new J.ClassDeclaration.Kind(randomId(), kindPrefix, Markers.EMPTY, emptyList(), kindType);
Space namePrefix = whitespace();
String simpleName = name();
J.Identifier name = new J.Identifier(randomId(), namePrefix, Markers.EMPTY, emptyList(), simpleName, typeMapping.type(clazz), null);
JContainer<J.TypeParameter> typeParameterContainer = null;
if (clazz.isUsingGenerics() && clazz.getGenericsTypes() != null) {
typeParameterContainer = visitTypeParameters(clazz.getGenericsTypes());
}
JLeftPadded<TypeTree> extendings = null;
if (clazz.getSuperClass().getLineNumber() >= 0) {
extendings = padLeft(sourceBefore("extends"), visitTypeTree(clazz.getSuperClass()));
}
JContainer<TypeTree> implementings = null;
if (clazz.getInterfaces().length > 0) {
Space implPrefix;
if (kindType == J.ClassDeclaration.Kind.Type.Interface || kindType == J.ClassDeclaration.Kind.Type.Annotation) {
implPrefix = sourceBefore("extends");
} else {
implPrefix = sourceBefore("implements");
}
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 && "java.lang.annotation.Annotation".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, Markers.EMPTY);
}
}
queue.add(new J.ClassDeclaration(randomId(), fmt, Markers.EMPTY,
leadingAnnotations,
modifiers,
kind,
name,
typeParameterContainer,
null,
extendings,
implementings,
null,
visitClassBlock(clazz),
TypeUtils.asFullyQualified(typeMapping.type(clazz))));
}
J.Block visitClassBlock(ClassNode clazz) {
NavigableMap<LineColumn, List<ASTNode>> sortedByPosition = new TreeMap<>();
for (MethodNode method : clazz.getMethods()) {
if (method.isSynthetic()) {
continue;
}
sortedByPosition.computeIfAbsent(pos(method), i -> new ArrayList<>()).add(method);
}
/*
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<>();
for (FieldNode field : clazz.getFields()) {
if (!appearsInSource(field)) {
continue;
}
if (field.hasInitialExpression() && field.getInitialExpression() instanceof ConstructorCallExpression) {
ConstructorCallExpression cce = (ConstructorCallExpression) field.getInitialExpression();
if (cce.isUsingAnonymousInnerClass() && cce.getType() instanceof InnerClassNode) {
fieldInitializers.add((InnerClassNode) cce.getType());
}
}
sortedByPosition.computeIfAbsent(pos(field), i -> new ArrayList<>()).add(field);
}
Iterator<InnerClassNode> innerClassIterator = clazz.getInnerClasses();
while (innerClassIterator.hasNext()) {
InnerClassNode icn = innerClassIterator.next();
if (icn.isSynthetic() || fieldInitializers.contains(icn)) {
continue;
}
sortedByPosition.computeIfAbsent(pos(icn), i -> new ArrayList<>()).add(icn);
}
return new J.Block(randomId(), sourceBefore("{"), Markers.EMPTY,
JRightPadded.build(false),
sortedByPosition.values().stream()
.flatMap(asts -> asts.stream()
.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);
}
Statement stat = pollQueue();
return maybeSemicolon(stat);
}))
.collect(Collectors.toList()),
sourceBefore("}"));
}
@Override
public void visitField(FieldNode field) {
if ((field.getModifiers() & Opcodes.ACC_ENUM) != 0) {
visitEnumField(field);
} else {
visitVariableField(field);
}
}
private void visitEnumField(@SuppressWarnings("unused") FieldNode fieldNode) {
// Requires refactoring visitClass to use a similar pattern as Java11ParserVisitor.
// Currently, each field is visited one at a time, so we cannot construct the EnumValueSet.
throw new UnsupportedOperationException("enum fields are not implemented.");
}
private void visitVariableField(FieldNode field) {
RewriteGroovyVisitor visitor = new RewriteGroovyVisitor(field, this);
List<J.Annotation> annotations = field.getAnnotations().stream()
.map(a -> {
visitAnnotation(a);
return (J.Annotation) pollQueue();
})
.collect(Collectors.toList());
List<J.Modifier> modifiers = visitModifiers(field.getModifiers());
TypeTree 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.visit(field.getInitialExpression());
namedVariable = namedVariable.getPadding().withInitializer(padLeft(beforeAssign, initializer));
}
J.VariableDeclarations variableDeclarations = new J.VariableDeclarations(
randomId(),
EMPTY,
Markers.EMPTY,
annotations,
modifiers,
typeExpr,
null,
emptyList(),
singletonList(JRightPadded.build(namedVariable))
);
queue.add(variableDeclarations);
}
@Override
protected void visitAnnotation(AnnotationNode annotation) {
RewriteGroovyVisitor bodyVisitor = new RewriteGroovyVisitor(annotation, this);
String lastArgKey = annotation.getMembers().keySet().stream().reduce("", (k1, k2) -> k2);
Space prefix = sourceBefore("@");
NameTree annotationType = visitTypeTree(annotation.getClassNode());
JContainer<Expression> arguments = null;
if (!annotation.getMembers().isEmpty()) {
// This doesn't handle the case where an annotation has empty arguments like @Foo(), but that is rare
arguments = JContainer.build(
sourceBefore("("),
annotation.getMembers().entrySet().stream()
.map(arg -> {
Space argPrefix;
if ("value".equals(arg.getKey())) {
// Determine whether the value is implicit or explicit
int saveCursor = cursor;
argPrefix = whitespace();
if (!source.startsWith("value", cursor)) {
return new JRightPadded<Expression>(
((Expression) bodyVisitor.visit(arg.getValue())).withPrefix(argPrefix),
arg.getKey().equals(lastArgKey) ? sourceBefore(")") : sourceBefore(","),
Markers.EMPTY);
}
cursor = saveCursor;
}
argPrefix = sourceBefore(arg.getKey());
J.Identifier argName = new J.Identifier(randomId(), EMPTY, Markers.EMPTY, emptyList(), arg.getKey(), null, null);
J.Assignment assign = new J.Assignment(randomId(), argPrefix, Markers.EMPTY,
argName, padLeft(sourceBefore("="), bodyVisitor.visit(arg.getValue())),
null);
return JRightPadded.build((Expression) assign)
.withAfter(arg.getKey().equals(lastArgKey) ? sourceBefore(")") : sourceBefore(","));
})
.collect(Collectors.toList()),
Markers.EMPTY
);
}
queue.add(new J.Annotation(randomId(), prefix, Markers.EMPTY, annotationType, arguments));
}
@Override
public void visitMethod(MethodNode method) {
Space fmt = whitespace();
List<J.Annotation> annotations = method.getAnnotations().stream()
.map(a -> {
visitAnnotation(a);
return (J.Annotation) pollQueue();
})
.collect(Collectors.toList());
List<J.Modifier> modifiers = visitModifiers(method.getModifiers());
TypeTree returnType = visitTypeTree(method.getReturnType());
// Method name might be in quotes
Space namePrefix = whitespace();
String methodName;
if(source.startsWith(method.getName(), cursor)) {
methodName = method.getName();
} else {
char openingQuote = source.charAt(cursor);
methodName = openingQuote + method.getName() + openingQuote;
}
cursor += methodName.length();
J.Identifier name = new J.Identifier(randomId(),
namePrefix,
Markers.EMPTY,
emptyList(),
methodName,
null, null);
RewriteGroovyVisitor bodyVisitor = new RewriteGroovyVisitor(method, this);
// Parameter has no visit implementation, so we've got to do this by hand
Space beforeParen = sourceBefore("(");
List<JRightPadded<Statement>> params = new ArrayList<>(method.getParameters().length);
Parameter[] unparsedParams = method.getParameters();
for (int i = 0; i < unparsedParams.length; i++) {
Parameter param = unparsedParams[i];
List<J.Annotation> paramAnnotations = param.getAnnotations().stream()
.map(a -> {
visitAnnotation(a);
return (J.Annotation) pollQueue();
})
.collect(Collectors.toList());
TypeTree paramType;
if (param.isDynamicTyped()) {
paramType = new J.Identifier(randomId(), EMPTY, Markers.EMPTY, emptyList(), "", JavaType.ShallowClass.build("java.lang.Object"), null);
} else {
paramType = visitTypeTree(param.getOriginType());
}
JRightPadded<J.VariableDeclarations.NamedVariable> paramName = JRightPadded.build(
new J.VariableDeclarations.NamedVariable(randomId(), EMPTY, Markers.EMPTY,
new J.Identifier(randomId(), whitespace(), Markers.EMPTY, emptyList(), param.getName(), null, null),
emptyList(), null, null)
);
cursor += param.getName().length();
org.codehaus.groovy.ast.expr.Expression defaultValue = param.getInitialExpression();
if (defaultValue != null) {
paramName = paramName.withElement(paramName.getElement().getPadding()
.withInitializer(new JLeftPadded<>(
sourceBefore("="),
new RewriteGroovyVisitor(defaultValue, this).visit(defaultValue),
Markers.EMPTY)));
}
Space rightPad = sourceBefore(i == unparsedParams.length - 1 ? ")" : ",");
params.add(JRightPadded.build((Statement) new J.VariableDeclarations(randomId(), EMPTY,
Markers.EMPTY, paramAnnotations, emptyList(), paramType,
null, emptyList(),
singletonList(paramName))).withAfter(rightPad));
}
if (unparsedParams.length == 0) {
params.add(JRightPadded.build(new J.Empty(randomId(), sourceBefore(")"), Markers.EMPTY)));
}
JContainer<NameTree> throws_ = method.getExceptions().length == 0 ? null : JContainer.build(
sourceBefore("throws"),
bodyVisitor.visitRightPadded(method.getExceptions(), null),
Markers.EMPTY
);
J.Block body = method.getCode() == null ? null :
bodyVisitor.visit(method.getCode());
queue.add(new J.MethodDeclaration(
randomId(), fmt, Markers.EMPTY,
annotations,
modifiers,
null,
returnType,
new J.MethodDeclaration.IdentifierWithAnnotations(name, emptyList()),
JContainer.build(beforeParen, params, Markers.EMPTY),
throws_,
body,
null,
typeMapping.methodType(method)
));
}
@SuppressWarnings({"ConstantConditions", "unchecked"})
private <T> T pollQueue() {
return (T) queue.poll();
}
}
private class RewriteGroovyVisitor extends CodeVisitorSupport {
private Cursor nodeCursor;
private final Queue<Object> queue = new LinkedList<>();
private final RewriteGroovyClassVisitor classVisitor;
public RewriteGroovyVisitor(ASTNode root, RewriteGroovyClassVisitor classVisitor) {
this.nodeCursor = new Cursor(null, root);
this.classVisitor = classVisitor;
}
private <T> T visit(ASTNode node) {
nodeCursor = new Cursor(nodeCursor, node);
node.visit(this);
nodeCursor = nodeCursor.getParentOrThrow();
return pollQueue();
}
private <T> List<JRightPadded<T>> visitRightPadded(ASTNode[] nodes, @Nullable String afterLast) {
List<JRightPadded<T>> ts = new ArrayList<>(nodes.length);
for (int i = 0; i < nodes.length; i++) {
ASTNode node = nodes[i];
@SuppressWarnings("unchecked") JRightPadded<T> converted = JRightPadded.build(
node instanceof ClassNode ? (T) visitTypeTree((ClassNode) node) : visit(node));
if (i == nodes.length - 1) {
converted = converted.withAfter(whitespace());
if (',' == source.charAt(cursor)) {
// In Groovy trailing "," are allowed
cursor += 1;
converted = converted.withMarkers(Markers.EMPTY.add(new org.openrewrite.java.marker.TrailingComma(randomId(), whitespace())));
}
ts.add(converted);
if (afterLast != null && source.startsWith(afterLast, cursor)) {
cursor += afterLast.length();
}
} else {
ts.add(converted.withAfter(sourceBefore(",")));
}
}
return ts;
}
private Expression insideParentheses(ASTNode node, Function<Space, Expression> parenthesizedTree) {
Integer insideParenthesesLevel;
Object rawIpl = node.getNodeMetaData("_INSIDE_PARENTHESES_LEVEL");
if(rawIpl instanceof AtomicInteger) {
// On Java 11 and newer _INSIDE_PARENTHESES_LEVEL is an AtomicInteger
insideParenthesesLevel = ((AtomicInteger) rawIpl).get();
} else {
// On Java 8 _INSIDE_PARENTHESES_LEVEL is a regular Integer
insideParenthesesLevel = (Integer) rawIpl;
}
if (insideParenthesesLevel != null) {
Stack<Space> openingParens = new Stack<>();
for (int i = 0; i < insideParenthesesLevel; i++) {
openingParens.push(sourceBefore("("));
}
Expression parenthesized = parenthesizedTree.apply(whitespace());
for (int i = 0; i < insideParenthesesLevel; i++) {
parenthesized = new J.Parentheses<>(randomId(), openingParens.pop(), Markers.EMPTY,
padRight(parenthesized, sourceBefore(")")));
}
return parenthesized;
}
return parenthesizedTree.apply(whitespace());
}
private Statement labeled(org.codehaus.groovy.ast.stmt.Statement statement, Supplier<Statement> labeledTree) {
List<J.Label> labels = null;
if (statement.getStatementLabels() != null && !statement.getStatementLabels().isEmpty()) {
labels = new ArrayList<>(statement.getStatementLabels().size());
// Labels appear in statement.getStatementLabels() in reverse order of their appearance in source code
// Could iterate over those in reverse order, but feels safer to just take the count and go off source code alone
for (int i = 0; i < statement.getStatementLabels().size(); i++) {
labels.add(new J.Label(randomId(), whitespace(), Markers.EMPTY, JRightPadded.build(
new J.Identifier(randomId(), EMPTY, Markers.EMPTY, emptyList(), name(), null, null)).withAfter(sourceBefore(":")),
new J.Empty(randomId(), EMPTY, Markers.EMPTY)));
}
}
Statement s = labeledTree.get();
if (labels != null) {
//noinspection ConstantConditions
return condenseLabels(labels, s);
}
return s;
}
@Override
public void visitArgumentlistExpression(ArgumentListExpression expression) {
List<JRightPadded<Expression>> args = new ArrayList<>(expression.getExpressions().size());
int saveCursor = cursor;
Space beforeOpenParen = whitespace();
org.openrewrite.java.marker.OmitParentheses omitParentheses = null;
if (source.charAt(cursor) == '(') {
cursor++;
} else {
omitParentheses = new org.openrewrite.java.marker.OmitParentheses(randomId());
beforeOpenParen = EMPTY;
cursor = saveCursor;
}
List<org.codehaus.groovy.ast.expr.Expression> unparsedArgs = expression.getExpressions().stream()
.filter(GroovyParserVisitor::appearsInSource)
.collect(Collectors.toList());
// If the first parameter to a function is a Map, then groovy allows "named parameters" style invocations, see:
// https://docs.groovy-lang.org/latest/html/documentation/#_named_parameters_2
// When named parameters are in use they may appear before, after, or intermixed with any positional arguments
if (unparsedArgs.size() > 1 && unparsedArgs.get(0) instanceof MapExpression
&& (unparsedArgs.get(0).getLastLineNumber() > unparsedArgs.get(1).getLastLineNumber()
|| (unparsedArgs.get(0).getLastLineNumber() == unparsedArgs.get(1).getLastLineNumber()
&& unparsedArgs.get(0).getLastColumnNumber() > unparsedArgs.get(1).getLastColumnNumber()))) {
// Figure out the source-code ordering of the expressions
MapExpression namedArgExpressions = (MapExpression) unparsedArgs.get(0);
unparsedArgs =
Stream.concat(
namedArgExpressions.getMapEntryExpressions().stream(),
unparsedArgs.subList(1, unparsedArgs.size()).stream())
.sorted(Comparator.comparing(ASTNode::getLastLineNumber)
.thenComparing(ASTNode::getLastColumnNumber))
.collect(Collectors.toList());
} else if (!unparsedArgs.isEmpty() && unparsedArgs.get(0) instanceof MapExpression) {
// The map literal may or may not be wrapped in "[]"
// If it is wrapped in "[]" then this isn't a named arguments situation and we should not lift the parameters out of the enclosing MapExpression
saveCursor = cursor;
whitespace();
boolean isOpeningBracketPresent = '[' == source.charAt(cursor);
cursor = saveCursor;
if (!isOpeningBracketPresent) {
// Bring named parameters out of their containing MapExpression so that they can be parsed correctly
MapExpression namedArgExpressions = (MapExpression) unparsedArgs.get(0);
unparsedArgs =
Stream.concat(
namedArgExpressions.getMapEntryExpressions().stream(),
unparsedArgs.subList(1, unparsedArgs.size()).stream())
.collect(Collectors.toList());
}
}
if(unparsedArgs.isEmpty()) {
args.add(JRightPadded.build((Expression)new J.Empty(randomId(), whitespace(), Markers.EMPTY))
.withAfter(omitParentheses == null ? sourceBefore(")") : EMPTY));
} else {
for (int i = 0; i < unparsedArgs.size(); i++) {
org.codehaus.groovy.ast.expr.Expression rawArg = unparsedArgs.get(i);
Expression arg = visit(rawArg);
if (omitParentheses != null) {
arg = arg.withMarkers(arg.getMarkers().add(omitParentheses));
}
Space after = EMPTY;
if (i == unparsedArgs.size() - 1) {
if (omitParentheses == null) {
after = sourceBefore(")");
}
} else {
after = whitespace();
if (source.charAt(cursor) == ')') {
// the next argument will have an OmitParentheses marker
omitParentheses = new org.openrewrite.java.marker.OmitParentheses(randomId());
}
cursor++;
}
args.add(JRightPadded.build(arg).withAfter(after));
}
}
queue.add(JContainer.build(beforeOpenParen, args, Markers.EMPTY));
}
@Override
public void visitClassExpression(ClassExpression clazz) {
queue.add(TypeTree.build(clazz.getType().getUnresolvedName())
.withType(typeMapping.type(clazz.getType()))
.withPrefix(sourceBefore(clazz.getType().getUnresolvedName())));
}
@Override
public void visitAssertStatement(AssertStatement statement) {
Space prefix = whitespace();
skip("assert");
Expression condition = visit(statement.getBooleanExpression());
JLeftPadded<Expression> message = null;
if (!(statement.getMessageExpression() instanceof ConstantExpression) || !((ConstantExpression) statement.getMessageExpression()).isNullExpression()) {
Space messagePrefix = whitespace();
skip(":");
message = padLeft(messagePrefix, visit(statement.getMessageExpression()));
}
queue.add(new J.Assert(randomId(), prefix, Markers.EMPTY, condition, message));
}
@Override
public void visitBinaryExpression(BinaryExpression binary) {
queue.add(insideParentheses(binary, fmt -> {
Expression left = visit(binary.getLeftExpression());
Space opPrefix = whitespace();
boolean assignment = false;
boolean instanceOf = false;
J.AssignmentOperation.Type assignOp = null;
J.Binary.Type binaryOp = null;
G.Binary.Type gBinaryOp = null;
switch (binary.getOperation().getText()) {
case "+":
binaryOp = J.Binary.Type.Addition;
break;
case "&&":
binaryOp = J.Binary.Type.And;
break;
case "&":
binaryOp = J.Binary.Type.BitAnd;
break;
case "|":
binaryOp = J.Binary.Type.BitOr;
break;
case "^":
binaryOp = J.Binary.Type.BitXor;
break;
case "/":
binaryOp = J.Binary.Type.Division;
break;
case "==":
binaryOp = J.Binary.Type.Equal;
break;
case ">":
binaryOp = J.Binary.Type.GreaterThan;
break;
case ">=":
binaryOp = J.Binary.Type.GreaterThanOrEqual;
break;
case "<<":
binaryOp = J.Binary.Type.LeftShift;
break;
case "<":
binaryOp = J.Binary.Type.LessThan;
break;
case "<=":
binaryOp = J.Binary.Type.LessThanOrEqual;
break;
case "%":
binaryOp = J.Binary.Type.Modulo;
break;
case "*":
binaryOp = J.Binary.Type.Multiplication;
break;
case "!=":
binaryOp = J.Binary.Type.NotEqual;
break;
case "||":
binaryOp = J.Binary.Type.Or;
break;
case ">>":
binaryOp = J.Binary.Type.RightShift;
break;
case "-":
binaryOp = J.Binary.Type.Subtraction;
break;
case ">>>":
binaryOp = J.Binary.Type.UnsignedRightShift;
break;
case "instanceof":
instanceOf = true;
break;
case "=":
assignment = true;
break;
case "+=":
assignOp = J.AssignmentOperation.Type.Addition;
break;
case "-=":
assignOp = J.AssignmentOperation.Type.Subtraction;
break;
case "&=":
assignOp = J.AssignmentOperation.Type.BitAnd;
break;
case "|=":
assignOp = J.AssignmentOperation.Type.BitOr;
break;
case "^=":
assignOp = J.AssignmentOperation.Type.BitXor;
break;
case "/=":
assignOp = J.AssignmentOperation.Type.Division;
break;
case "<<=":
assignOp = J.AssignmentOperation.Type.LeftShift;
break;
case "%=":
assignOp = J.AssignmentOperation.Type.Modulo;
break;
case "*=":
assignOp = J.AssignmentOperation.Type.Multiplication;
break;
case ">>=":
assignOp = J.AssignmentOperation.Type.RightShift;
break;
case ">>>=":
assignOp = J.AssignmentOperation.Type.UnsignedRightShift;
break;
case "=~":
gBinaryOp = G.Binary.Type.Find;
break;
case "==~":
gBinaryOp = G.Binary.Type.Match;
break;
case "[":
gBinaryOp = G.Binary.Type.Access;
break;
case "in":
gBinaryOp = G.Binary.Type.In;
break;
}
cursor += binary.getOperation().getText().length();
Expression right = visit(binary.getRightExpression());
if (assignment) {
return new J.Assignment(randomId(), fmt, Markers.EMPTY,
left, JLeftPadded.build(right).withBefore(opPrefix),
typeMapping.type(binary.getType()));
} else if (instanceOf) {
return new J.InstanceOf(randomId(), fmt, Markers.EMPTY,
JRightPadded.build(left).withAfter(opPrefix), right, null,
typeMapping.type(binary.getType()));
} else if (assignOp != null) {
return new J.AssignmentOperation(randomId(), fmt, Markers.EMPTY,
left, JLeftPadded.build(assignOp).withBefore(opPrefix),
right, typeMapping.type(binary.getType()));
} else if (binaryOp != null) {
return new J.Binary(randomId(), fmt, Markers.EMPTY,
left, JLeftPadded.build(binaryOp).withBefore(opPrefix),
right, typeMapping.type(binary.getType()));
} else if (gBinaryOp != null) {
Space after = EMPTY;
if (gBinaryOp == G.Binary.Type.Access) {
after = sourceBefore("]");
}
return new G.Binary(randomId(), fmt, Markers.EMPTY,
left, JLeftPadded.build(gBinaryOp).withBefore(opPrefix),
right, after, typeMapping.type(binary.getType()));
}
throw new IllegalStateException("Unknown binary expression " + binary.getClass().getSimpleName());
}));
}
@Override
public void visitBlockStatement(BlockStatement block) {
Space fmt = EMPTY;
Object parent = nodeCursor.getParentOrThrow().getValue();
if (!(parent instanceof ClosureExpression)) {
fmt = sourceBefore("{");
}
List<JRightPadded<Statement>> statements = new ArrayList<>(block.getStatements().size());
List<org.codehaus.groovy.ast.stmt.Statement> blockStatements = block.getStatements();
for (int i = 0; i < blockStatements.size(); i++) {
ASTNode statement = blockStatements.get(i);
J expr = visit(statement);
if (i == blockStatements.size() - 1 && (expr instanceof Expression)) {
if (parent instanceof ClosureExpression || (parent instanceof MethodNode &&
!JavaType.Primitive.Void.equals(typeMapping.type(((MethodNode) parent).getReturnType())))) {
expr = new J.Return(randomId(), expr.getPrefix(), Markers.EMPTY,
expr.withPrefix(EMPTY));
expr = expr.withMarkers(expr.getMarkers().add(new ImplicitReturn(randomId())));
}
}
JRightPadded<Statement> stat = JRightPadded.build((Statement) expr);
int saveCursor = cursor;
Space beforeSemicolon = whitespace();
if (cursor < source.length() && source.charAt(cursor) == ';') {
stat = stat
.withMarkers(stat.getMarkers().add(new Semicolon(randomId())))
.withAfter(beforeSemicolon);
cursor++;
} else {
cursor = saveCursor;
}
statements.add(stat);
}
Space beforeBrace = whitespace();
queue.add(new J.Block(randomId(), fmt, Markers.EMPTY, JRightPadded.build(false), statements, beforeBrace));
if (!(parent instanceof ClosureExpression)) {
sourceBefore("}");
}
}
@Override
public void visitCatchStatement(CatchStatement node) {
Space prefix = sourceBefore("catch");
Space parenPrefix = sourceBefore("(");
// This does not handle multi-catch statements like catch(ExceptionTypeA | ExceptionTypeB e)
// The Groovy AST seems to only record the first type in the list, so some extra hacking is required to get the others
Parameter param = node.getVariable();
TypeTree paramType;
Space paramPrefix = whitespace();
// Groovy allows catch variables to omit their type, shorthand for being of type java.lang.Exception
// Can't use isSynthetic() here because groovy doesn't record the line number on the Parameter
if ("java.lang.Exception".equals(param.getType().getName())
&& !source.startsWith("Exception", cursor)
&& !source.startsWith("java.lang.Exception", cursor)) {
paramType = new J.Identifier(randomId(), paramPrefix, Markers.EMPTY, emptyList(), "",
JavaType.ShallowClass.build("java.lang.Exception"), null);
} else {
paramType = visitTypeTree(param.getOriginType()).withPrefix(paramPrefix);
}
JRightPadded<J.VariableDeclarations.NamedVariable> paramName = JRightPadded.build(
new J.VariableDeclarations.NamedVariable(randomId(), whitespace(), Markers.EMPTY,
new J.Identifier(randomId(), EMPTY, Markers.EMPTY, emptyList(), param.getName(), null, null),
emptyList(), null, null)
);
cursor += param.getName().length();
Space rightPad = whitespace();
cursor += 1; // skip )
JRightPadded<J.VariableDeclarations> variable = JRightPadded.build(new J.VariableDeclarations(randomId(), paramType.getPrefix(),
Markers.EMPTY, emptyList(), emptyList(), paramType.withPrefix(EMPTY),
null, emptyList(),
singletonList(paramName))
).withAfter(rightPad);
J.ControlParentheses<J.VariableDeclarations> catchControl = new J.ControlParentheses<>(randomId(), parenPrefix, Markers.EMPTY, variable);
queue.add(new J.Try.Catch(randomId(), prefix, Markers.EMPTY, catchControl, visit(node.getCode())));
}
@Override
public void visitBreakStatement(BreakStatement statement) {
queue.add(new J.Break(randomId(),
sourceBefore("break"),
Markers.EMPTY,
(statement.getLabel() == null) ?
null :
new J.Identifier(randomId(),
sourceBefore(statement.getLabel()),
Markers.EMPTY, emptyList(), statement.getLabel(), null, null))
);
}