-
-
Notifications
You must be signed in to change notification settings - Fork 55
/
ScriptCompiler.java
322 lines (287 loc) · 11.7 KB
/
ScriptCompiler.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
package net.citizensnpcs.api.scripting;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.lang.ref.WeakReference;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.Invocable;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.script.SimpleBindings;
import javax.script.SimpleScriptContext;
import com.google.common.base.Function;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import com.google.common.collect.MapMaker;
import com.google.common.collect.Maps;
import com.google.common.io.Closeables;
import net.citizensnpcs.api.util.Messaging;
/**
* Compiles files into {@link ScriptFactory}s. Intended for use as a separate thread - {@link ScriptCompiler#run()} will
* block while waiting for new tasks to compile.
*/
public class ScriptCompiler {
private final WeakReference<ClassLoader> classLoader;
private final ScriptEngineManager engineManager;
private final Map<String, ScriptEngine> engines = Maps.newHashMap();
private final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactory() {
int n = 1;
@Override
public Thread newThread(Runnable r) {
Thread created = new Thread(r, "Citizens Script Compiler #" + n++);
return created;
}
});
private final Function<File, ScriptSource> fileEngineConverter = new Function<File, ScriptSource>() {
@Override
public ScriptSource apply(File file) {
if (!file.isFile())
return null;
String fileName = file.getName();
String extension = fileName.substring(fileName.lastIndexOf('.') + 1);
ScriptEngine engine = loadEngine(extension);
if (engine == null)
return null;
return new ScriptSource(file, engine);
}
};
private final List<ContextProvider> globalContextProviders = Lists.newArrayList();
public ScriptCompiler(ClassLoader overrideClassLoader) {
engineManager = new ScriptEngineManager(overrideClassLoader);
classLoader = new WeakReference<ClassLoader>(overrideClassLoader);
}
public boolean canCompile(File file) {
return fileEngineConverter.apply(file) != null;
}
/**
* Create a builder to compile the given files.
*
* @param files
* The files to compile
* @return The {@link CompileTaskBuilder}
*/
public CompileTaskBuilder compile(File file) {
if (file == null)
throw new IllegalArgumentException("file should not be null");
ScriptSource source = fileEngineConverter.apply(file);
if (source == null)
throw new IllegalArgumentException("could not recognise file");
return new CompileTaskBuilder(source);
}
/**
* Create a builder to compile the given source code.
*
* @param src
* The source code to compile
* @param identifier
* A unique identifier of the source code
* @param extension
* The source code externsion
* @return The {@link CompileTaskBuilder}
*/
public CompileTaskBuilder compile(String src, String identifier, String extension) {
if (src == null)
throw new IllegalArgumentException("source must not be null");
return new CompileTaskBuilder(new ScriptSource(src, identifier, loadEngine(extension)));
}
public void interrupt() {
executor.shutdownNow();
}
private ScriptEngine loadEngine(String extension) {
ScriptEngine engine = engines.get(extension);
if (engine != null)
return engine;
ScriptEngine search = null;
if (extension.equals("js") || extension.equals("javascript")) {
search = engineManager.getEngineByName("nashorn");
}
if (search == null) {
search = engineManager.getEngineByExtension(extension);
}
if (search != null && (!(search instanceof Compilable) || !(search instanceof Invocable))) {
search = null;
} else if (search != null) {
search = tryUpdateClassLoader(search);
}
engines.put(extension, search);
ClassLoader cl = classLoader.get();
if (cl != null) {
updateSunClassLoader(cl);
}
return search;
}
/**
* Registers a global {@link ContextProvider}, which will be invoked on all scripts created by this ScriptCompiler.
*
* @param provider
* The global provider
*/
public void registerGlobalContextProvider(ContextProvider provider) {
if (!globalContextProviders.contains(provider)) {
globalContextProviders.add(provider);
}
}
public void run(String code, String extension) throws ScriptException {
run(code, extension, null);
}
public void run(String code, String extension, Map<String, Object> vars) throws ScriptException {
ScriptEngine engine = loadEngine(extension);
if (engine == null)
throw new ScriptException("Couldn't load engine with extension " + extension);
ScriptContext context = new SimpleScriptContext();
if (vars != null) {
context.setBindings(new SimpleBindings(vars), ScriptContext.ENGINE_SCOPE);
}
engine.eval(extension, context);
}
private ScriptEngine tryUpdateClassLoader(ScriptEngine search) {
ScriptEngineFactory factory = search.getFactory();
try {
Method method = factory.getClass().getMethod("getScriptEngine", ClassLoader.class);
ClassLoader loader = classLoader.get();
if (loader == null)
return search;
return (ScriptEngine) method.invoke(factory, classLoader.get());
} catch (Exception e) {
return search;
}
}
private void updateSunClassLoader(ClassLoader cl) {
if (!CLASSLOADER_OVERRIDE_ENABLED)
return;
try {
Object global = GET_GLOBAL.invoke(null);
if (GET_APPLICATION_CLASS_LOADER.invoke(global) == null) {
INIT_APPLICATION_CLASS_LOADER.invoke(global, cl);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private class CompileTask implements Callable<ScriptFactory> {
private final boolean cache;
private final CompileCallback[] callbacks;
private final ContextProvider[] contextProviders;
private final ScriptSource engine;
public CompileTask(CompileTaskBuilder builder) {
List<ContextProvider> copy = Lists.newArrayList(builder.contextProviders);
copy.addAll(globalContextProviders);
this.contextProviders = copy.toArray(new ContextProvider[copy.size()]);
this.callbacks = builder.callbacks.toArray(new CompileCallback[builder.callbacks.size()]);
this.engine = builder.engine;
this.cache = builder.cache;
}
@Override
public ScriptFactory call() {
if (cache && CACHE.containsKey(engine.getIdentifier()))
return CACHE.get(engine.getIdentifier());
Compilable compiler = (Compilable) engine.engine;
Reader reader = null;
try {
CompiledScript src = compiler.compile(reader = engine.getReader());
ScriptFactory compiled = new SimpleScriptFactory(src, contextProviders);
if (cache) {
CACHE.put(engine.getIdentifier(), compiled);
}
for (CompileCallback callback : callbacks) {
callback.onScriptCompiled(engine.getIdentifier(), compiled);
}
return compiled;
} catch (IOException e) {
Messaging.severe("IO error while reading a file for scripting.");
e.printStackTrace();
} catch (ScriptException e) {
Messaging.severe("Compile error while parsing script.");
Throwables.getRootCause(e).printStackTrace();
} catch (Throwable t) {
Messaging.severe("Unexpected error while parsing script.");
t.printStackTrace();
} finally {
Closeables.closeQuietly(reader);
}
return null;
}
}
public class CompileTaskBuilder {
private boolean cache;
private final List<CompileCallback> callbacks = Lists.newArrayList();
private final List<ContextProvider> contextProviders = Lists.newArrayList();
private final ScriptSource engine;
private CompileTaskBuilder(ScriptSource engine) {
this.engine = engine;
}
public Future<ScriptFactory> beginWithFuture() {
CompileTask task = new CompileTask(this);
return executor.submit(task);
}
public CompileTaskBuilder cache(boolean cache) {
this.cache = cache;
return this;
}
public CompileTaskBuilder withCallback(CompileCallback callback) {
callbacks.add(callback);
return this;
}
public CompileTaskBuilder withContextProvider(ContextProvider provider) {
contextProviders.add(provider);
return this;
}
}
private static class ScriptSource {
private final ScriptEngine engine;
private final File file;
private final String identifier;
private final String src;
private ScriptSource(File file, ScriptEngine engine) {
this.file = file;
this.identifier = file.getAbsolutePath();
this.engine = engine;
this.src = null;
}
private ScriptSource(String src, String identifier, ScriptEngine engine) {
this.src = src;
this.identifier = identifier;
this.engine = engine;
this.file = null;
}
public String getIdentifier() {
return identifier;
}
public Reader getReader() throws FileNotFoundException {
return file == null ? new StringReader(src) : new FileReader(file);
}
}
private static final Map<String, ScriptFactory> CACHE = new MapMaker().weakValues().makeMap();
private static boolean CLASSLOADER_OVERRIDE_ENABLED;
private static Method GET_APPLICATION_CLASS_LOADER, GET_GLOBAL, INIT_APPLICATION_CLASS_LOADER;
static {
try {
Class<?> CONTEXT_FACTORY = Class.forName("sun.org.mozilla.javascript.internal.ContextFactory");
GET_APPLICATION_CLASS_LOADER = CONTEXT_FACTORY.getDeclaredMethod("getApplicationClassLoader");
GET_APPLICATION_CLASS_LOADER.setAccessible(true);
GET_GLOBAL = CONTEXT_FACTORY.getDeclaredMethod("getGlobal");
GET_GLOBAL.setAccessible(true);
INIT_APPLICATION_CLASS_LOADER = CONTEXT_FACTORY.getDeclaredMethod("initApplicationClassLoader",
ClassLoader.class);
INIT_APPLICATION_CLASS_LOADER.setAccessible(true);
CLASSLOADER_OVERRIDE_ENABLED = true;
} catch (Exception e) {
Messaging.debug("Unable to find Rhino classes - javascript scripts won't see non-CraftBukkit classes");
}
}
}