-
Notifications
You must be signed in to change notification settings - Fork 280
/
GroovyParser.java
300 lines (264 loc) · 12.6 KB
/
GroovyParser.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
/*
* 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.GroovyClassLoader;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.ModuleNode;
import org.codehaus.groovy.control.*;
import org.codehaus.groovy.control.io.InputStreamReaderSource;
import org.codehaus.groovy.control.messages.WarningMessage;
import org.codehaus.groovy.transform.stc.StaticTypeCheckingVisitor;
import org.intellij.lang.annotations.Language;
import org.openrewrite.*;
import org.openrewrite.groovy.tree.G;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.java.JavaParser;
import org.openrewrite.java.internal.JavaTypeCache;
import org.openrewrite.marker.Markers;
import org.openrewrite.style.NamedStyles;
import org.openrewrite.tree.ParseError;
import org.openrewrite.tree.ParsingExecutionContextView;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.toList;
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class GroovyParser implements Parser {
@Nullable
private final Collection<Path> classpath;
private final List<NamedStyles> styles;
private final boolean logCompilationWarningsAndErrors;
private final JavaTypeCache typeCache;
private final List<Consumer<CompilerConfiguration>> compilerCustomizers;
@Override
public Stream<SourceFile> parse(@Language("groovy") String... sources) {
Pattern packagePattern = Pattern.compile("^package\\s+([^;]+);");
Pattern classPattern = Pattern.compile("(class|interface|enum)\\s*(<[^>]*>)?\\s+(\\w+)");
Function<String, String> simpleName = sourceStr -> {
Matcher classMatcher = classPattern.matcher(sourceStr);
return classMatcher.find() ? classMatcher.group(3) : null;
};
return parseInputs(
Arrays.stream(sources)
.map(sourceFile -> {
Matcher packageMatcher = packagePattern.matcher(sourceFile);
String pkg = packageMatcher.find() ? packageMatcher.group(1).replace('.', '/') + "/" : "";
String className = Optional.ofNullable(simpleName.apply(sourceFile))
.orElse(Long.toString(System.nanoTime())) + ".java";
Path path = Paths.get(pkg + className);
return new Input(
path, null,
() -> new ByteArrayInputStream(sourceFile.getBytes(StandardCharsets.UTF_8)),
true
);
})
.collect(toList()),
null,
new InMemoryExecutionContext()
);
}
@Override
public Stream<SourceFile> parseInputs(Iterable<Input> sources, @Nullable Path relativeTo, ExecutionContext ctx) {
CompilerConfiguration configuration = new CompilerConfiguration();
configuration.setTolerance(Integer.MAX_VALUE);
configuration.setWarningLevel(WarningMessage.NONE);
configuration.setClasspathList(classpath == null ? emptyList() : classpath.stream()
.flatMap(cp -> {
try {
return Stream.of(cp.toFile().toString());
} catch (UnsupportedOperationException e) {
// can happen e.g. in the case of jdk.internal.jrtfs.JrtPath
return Stream.empty();
}
})
.collect(toList()));
for (Consumer<CompilerConfiguration> compilerCustomizer : compilerCustomizers) {
compilerCustomizer.accept(configuration);
}
ParsingExecutionContextView pctx = ParsingExecutionContextView.view(ctx);
return StreamSupport.stream(sources.spliterator(), false)
.map(input -> {
ParseWarningCollector errorCollector = new ParseWarningCollector(configuration, this);
try (GroovyClassLoader classLoader = new GroovyClassLoader(getClass().getClassLoader(), configuration, true)) {
SourceUnit unit = new SourceUnit(
"doesntmatter",
new InputStreamReaderSource(input.getSource(ctx), configuration),
configuration,
classLoader,
errorCollector
);
pctx.getParsingListener().startedParsing(input);
CompilationUnit compUnit = new CompilationUnit(configuration, null, classLoader, classLoader);
compUnit.addSource(unit);
compUnit.compile(Phases.CANONICALIZATION);
ModuleNode ast = unit.getAST();
for (ClassNode aClass : ast.getClasses()) {
try {
StaticTypeCheckingVisitor staticTypeCheckingVisitor = new StaticTypeCheckingVisitor(unit, aClass);
staticTypeCheckingVisitor.setCompilationUnit(compUnit);
staticTypeCheckingVisitor.visitClass(aClass);
} catch (NoClassDefFoundError ignored) {
}
}
CompiledGroovySource compiled = new CompiledGroovySource(input, unit, ast);
List<ParseWarning> warnings = errorCollector.getWarningMarkers();
GroovyParserVisitor mappingVisitor = new GroovyParserVisitor(
compiled.getInput().getRelativePath(relativeTo),
compiled.getInput().getFileAttributes(),
compiled.getInput().getSource(ctx),
typeCache,
ctx
);
G.CompilationUnit gcu = mappingVisitor.visit(compiled.getSourceUnit(), compiled.getModule());
if (warnings.size() > 0) {
Markers m = gcu.getMarkers();
for (ParseWarning warning : warnings) {
m = m.add(warning);
}
gcu = gcu.withMarkers(m);
}
pctx.getParsingListener().parsed(compiled.getInput(), gcu);
return requirePrintEqualsInput(gcu, input, relativeTo, ctx);
} catch (Throwable t) {
ctx.getOnError().accept(t);
return ParseError.build(this, input, relativeTo, ctx, t);
} finally {
if (logCompilationWarningsAndErrors && (errorCollector.hasErrors() || errorCollector.hasWarnings())) {
try (StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw)) {
errorCollector.write(pw, new Janitor());
org.slf4j.LoggerFactory.getLogger(GroovyParser.class).warn(sw.toString());
} catch (IOException ignored) {
// unreachable
}
}
}
});
}
@Override
public boolean accept(Path path) {
return path.toString().endsWith(".groovy") ||
path.toFile().getName().startsWith("Jenkinsfile");
}
@Override
public GroovyParser reset() {
typeCache.clear();
return this;
}
@Override
public Path sourcePathFromSourceText(Path prefix, String sourceCode) {
return prefix.resolve("file.groovy");
}
public static GroovyParser.Builder builder() {
return new Builder();
}
public static GroovyParser.Builder builder(Builder base) {
return new Builder(base);
}
@SuppressWarnings("unused")
public static class Builder extends Parser.Builder {
@Nullable
private Collection<Path> classpath = Collections.emptyList();
@Nullable
protected Collection<String> artifactNames = Collections.emptyList();
private JavaTypeCache typeCache = new JavaTypeCache();
private boolean logCompilationWarningsAndErrors = false;
private final List<NamedStyles> styles = new ArrayList<>();
private final List<Consumer<CompilerConfiguration>> compilerCustomizers = new ArrayList<>();
public Builder() {
super(G.CompilationUnit.class);
}
public Builder(Builder base) {
super(G.CompilationUnit.class);
this.classpath = base.classpath;
this.artifactNames = base.artifactNames;
this.typeCache = base.typeCache;
this.logCompilationWarningsAndErrors = base.logCompilationWarningsAndErrors;
this.styles.addAll(base.styles);
this.compilerCustomizers.addAll(base.compilerCustomizers);
}
public Builder logCompilationWarningsAndErrors(boolean logCompilationWarningsAndErrors) {
this.logCompilationWarningsAndErrors = logCompilationWarningsAndErrors;
return this;
}
public Builder classpath(@Nullable Collection<Path> classpath) {
this.artifactNames = null;
this.classpath = classpath;
return this;
}
public Builder classpath(@Nullable String... artifactNames) {
this.artifactNames = Arrays.asList(artifactNames);
this.classpath = null;
return this;
}
public Builder classpathFromResource(ExecutionContext ctx, String... artifactNamesWithVersions) {
this.artifactNames = null;
this.classpath = JavaParser.dependenciesFromResources(ctx, artifactNamesWithVersions);
return this;
}
@SuppressWarnings("unused")
public Builder typeCache(JavaTypeCache typeCache) {
this.typeCache = typeCache;
return this;
}
public Builder styles(Iterable<? extends NamedStyles> styles) {
for (NamedStyles style : styles) {
this.styles.add(style);
}
return this;
}
@SafeVarargs
public final GroovyParser.Builder compilerCustomizers(Consumer<CompilerConfiguration>... compilerCustomizers) {
return compilerCustomizers(Arrays.asList(compilerCustomizers));
}
public GroovyParser.Builder compilerCustomizers(Iterable<Consumer<CompilerConfiguration>> compilerCustomizers) {
for (Consumer<CompilerConfiguration> compilerCustomizer : compilerCustomizers) {
this.compilerCustomizers.add(compilerCustomizer);
}
return this;
}
@Nullable
private Collection<Path> resolvedClasspath() {
if (artifactNames != null && !artifactNames.isEmpty()) {
classpath = JavaParser.dependenciesFromClasspath(artifactNames.toArray(new String[0]));
artifactNames = null;
}
return classpath;
}
@Override
public GroovyParser build() {
return new GroovyParser(resolvedClasspath(), styles, logCompilationWarningsAndErrors, typeCache, compilerCustomizers);
}
@Override
public String getDslName() {
return "groovy";
}
}
}