-
Notifications
You must be signed in to change notification settings - Fork 147
Expand file tree
/
Copy pathCachedCompiler.java
More file actions
251 lines (225 loc) · 10.9 KB
/
CachedCompiler.java
File metadata and controls
251 lines (225 loc) · 10.9 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
/*
* Copyright 2014 Higher Frequency Trading
*
* https://chronicle.software
*
* 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 net.openhft.compiler;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticListener;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;
import static net.openhft.compiler.CompilerUtils.*;
@SuppressWarnings("StaticNonFinalField")
public class CachedCompiler implements Closeable {
private static final Logger LOG = LoggerFactory.getLogger(CachedCompiler.class);
/** Writes to {@link System#err} */
private static final PrintWriter DEFAULT_WRITER = new PrintWriter(System.err);
private static final List<String> DEFAULT_OPTIONS = Arrays.asList("-g", "-nowarn");
private final Map<ClassLoader, Map<String, Class<?>>> loadedClassesMap = Collections.synchronizedMap(new WeakHashMap<>());
private final Map<ClassLoader, MyJavaFileManager> fileManagerMap = Collections.synchronizedMap(new WeakHashMap<>());
public Function<StandardJavaFileManager, MyJavaFileManager> fileManagerOverride;
@Nullable
private final File sourceDir;
@Nullable
private final File classDir;
@NotNull
private final List<String> options;
private final ConcurrentMap<String, JavaFileObject> javaFileObjects = new ConcurrentHashMap<>();
/**
* Delegates to {@link #CachedCompiler(File, File, List)} with default {@code javac} compilation
* options {@code -g} (generate debug information) and {@code -nowarn}.
*/
public CachedCompiler(@Nullable File sourceDir, @Nullable File classDir) {
this(sourceDir, classDir, DEFAULT_OPTIONS);
}
/**
* @param sourceDir where to write {@code .java} source code files to be compiled; {@code null}
* to not write them to the file system
* @param classDir where to write compiled {@code .class} files; {@code null} to not write them
* to the file system
* @param options {@code javac} compilation options
*/
public CachedCompiler(@Nullable File sourceDir, @Nullable File classDir, @NotNull List<String> options) {
this.sourceDir = sourceDir;
this.classDir = classDir;
this.options = options;
}
@Override
public void close() {
try {
for (MyJavaFileManager fileManager : fileManagerMap.values()) {
fileManager.close();
}
} catch (IOException e) {
throw new AssertionError(e);
}
}
/**
* Delegates to {@link #loadFromJava(ClassLoader, String, String, PrintWriter, DiagnosticListener)}.
* <ul>
* <li>The class loader of {@link CachedCompiler} is used for defining and loading the class
* <li>Only error diagnostics are collected, and are written to {@link System#err}
* </ul>
*/
public Class<?> loadFromJava(@NotNull String className, @NotNull String javaCode) throws ClassNotFoundException {
return loadFromJava(getClass().getClassLoader(), className, javaCode, DEFAULT_WRITER);
}
/**
* Delegates to {@link #loadFromJava(ClassLoader, String, String, PrintWriter, DiagnosticListener)}.
* Only error diagnostics are collected, and are written to {@link System#err}.
*/
public Class<?> loadFromJava(@NotNull ClassLoader classLoader,
@NotNull String className,
@NotNull String javaCode) throws ClassNotFoundException {
return loadFromJava(classLoader, className, javaCode, DEFAULT_WRITER);
}
/**
* Delegates to {@link #loadFromJava(ClassLoader, String, String, PrintWriter, DiagnosticListener)}.
* Only error diagnostics are collected, and are written to {@code writer}.
*/
public Class<?> loadFromJava(@NotNull ClassLoader classLoader,
@NotNull String className,
@NotNull String javaCode,
@Nullable PrintWriter writer) throws ClassNotFoundException {
return loadFromJava(classLoader, className, javaCode, writer, null);
}
/**
* Gets a previously compiled and loaded class, or compiles the given Java code and
* loads the class.
*
* @param classLoader class loader for defining and loading the class
* @param className binary name of the class to load, for example {@code com.example.MyClass$Nested}
* @param javaCode Java code to compile, in case the class had not been compiled and loaded before
* @param writer writer for compilation information and diagnostics (should be thread-safe);
* when {@code null} defaults to writing to {@link System#err}
* @param diagnosticListener listener for diagnostics emitted by the compiler (should be thread-safe);
* when {@code null}, error diagnostics are written to the {@code writer}, other diagnostics are ignored
* @return the loaded class
* @throws ClassNotFoundException if compiling or loading the class failed; inspect {@code writer} or
* {@code diagnosticListener} for additional details
*/
public Class<?> loadFromJava(@NotNull ClassLoader classLoader,
@NotNull String className,
@NotNull String javaCode,
@Nullable PrintWriter writer,
@Nullable DiagnosticListener<? super JavaFileObject> diagnosticListener) throws ClassNotFoundException {
Class<?> clazz = null;
Map<String, Class<?>> loadedClasses;
synchronized (loadedClassesMap) {
loadedClasses = loadedClassesMap.get(classLoader);
if (loadedClasses == null)
loadedClassesMap.put(classLoader, loadedClasses = new LinkedHashMap<>());
else
clazz = loadedClasses.get(className);
}
if (clazz != null)
return clazz;
PrintWriter printWriter = writer == null ? DEFAULT_WRITER : writer;
if (diagnosticListener == null) {
diagnosticListener = new DiagnosticListener<JavaFileObject>() {
@Override
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
if (diagnostic.getKind() == Diagnostic.Kind.ERROR) {
printWriter.println(diagnostic);
}
}
};
}
MyJavaFileManager fileManager = fileManagerMap.get(classLoader);
if (fileManager == null) {
StandardJavaFileManager standardJavaFileManager = s_compiler.getStandardFileManager(null, null, null);
fileManager = getFileManager(standardJavaFileManager);
fileManagerMap.put(classLoader, fileManager);
}
final Map<String, byte[]> compiled = compileFromJava(className, javaCode, printWriter, diagnosticListener, fileManager);
for (Map.Entry<String, byte[]> entry : compiled.entrySet()) {
String className2 = entry.getKey();
synchronized (loadedClassesMap) {
if (loadedClasses.containsKey(className2))
continue;
}
byte[] bytes = entry.getValue();
if (classDir != null) {
String filename = className2.replaceAll("\\.", '\\' + File.separator) + ".class";
boolean changed = writeBytes(new File(classDir, filename), bytes);
if (changed) {
LOG.info("Updated {} in {}", className2, classDir);
}
}
synchronized (className2.intern()) { // To prevent duplicate class definition error
synchronized (loadedClassesMap) {
if (loadedClasses.containsKey(className2))
continue;
}
Class<?> clazz2 = CompilerUtils.defineClass(classLoader, className2, bytes);
synchronized (loadedClassesMap) {
loadedClasses.put(className2, clazz2);
}
}
}
synchronized (loadedClassesMap) {
loadedClasses.put(className, clazz = classLoader.loadClass(className));
}
return clazz;
}
@NotNull
Map<String, byte[]> compileFromJava(@NotNull String className,
@NotNull String javaCode,
@NotNull PrintWriter writer,
@NotNull DiagnosticListener<? super JavaFileObject> diagnosticListener,
MyJavaFileManager fileManager) {
Iterable<? extends JavaFileObject> compilationUnits;
if (sourceDir != null) {
String filename = className.replaceAll("\\.", '\\' + File.separator) + ".java";
File file = new File(sourceDir, filename);
writeText(file, javaCode);
if (s_standardJavaFileManager == null)
s_standardJavaFileManager = s_compiler.getStandardFileManager(null, null, null);
compilationUnits = s_standardJavaFileManager.getJavaFileObjects(file);
} else {
javaFileObjects.put(className, new JavaSourceFromString(className, javaCode));
compilationUnits = new ArrayList<>(javaFileObjects.values()); // To prevent CME from compiler code
}
// reuse the same file manager to allow caching of jar files
boolean ok = s_compiler.getTask(writer, fileManager, diagnosticListener, options, null, compilationUnits).call();
if (!ok) {
// compilation error, so we want to exclude this file from future compilation passes
if (sourceDir == null)
javaFileObjects.remove(className);
// nothing to return due to compiler error
return Collections.emptyMap();
} else {
Map<String, byte[]> result = fileManager.getAllBuffers();
return result;
}
}
private @NotNull MyJavaFileManager getFileManager(StandardJavaFileManager fm) {
return fileManagerOverride != null
? fileManagerOverride.apply(fm)
: new MyJavaFileManager(fm);
}
}