-
Notifications
You must be signed in to change notification settings - Fork 914
/
RubyContext.java
407 lines (318 loc) · 13.9 KB
/
RubyContext.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
/*
* Copyright (c) 2013, 2014 Oracle and/or its affiliates. All rights reserved. This
* code is released under a tri EPL/GPL/LGPL license. You can use it,
* redistribute it and/or modify it under the terms of the:
*
* Eclipse Public License version 1.0
* GNU General Public License version 2
* GNU Lesser General Public License version 2.1
*/
package org.jruby.truffle.runtime;
import com.oracle.truffle.api.*;
import com.oracle.truffle.api.frame.MaterializedFrame;
import com.oracle.truffle.api.object.Shape;
import com.oracle.truffle.api.source.BytesDecoder;
import com.oracle.truffle.api.source.Source;
import org.jcodings.Encoding;
import org.jcodings.specific.UTF8Encoding;
import org.jruby.Ruby;
import org.jruby.RubyNil;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.truffle.TruffleHooks;
import org.jruby.truffle.nodes.RubyNode;
import org.jruby.truffle.nodes.RubyRootNode;
import org.jruby.truffle.nodes.methods.SetFrameVisibilityNode;
import org.jruby.truffle.runtime.control.RaiseException;
import org.jruby.truffle.runtime.core.*;
import org.jruby.truffle.runtime.subsystems.*;
import org.jruby.truffle.translator.NodeWrapper;
import org.jruby.truffle.translator.TranslatorDriver;
import org.jruby.util.ByteList;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
/**
* The global state of a running Ruby system.
*/
public class RubyContext extends ExecutionContext {
private final Ruby runtime;
private final TranslatorDriver translator;
private final CoreLibrary coreLibrary;
private final FeatureManager featureManager;
private final TraceManager traceManager;
private final ObjectSpaceManager objectSpaceManager;
private final ThreadManager threadManager;
private final FiberManager fiberManager;
private final AtExitManager atExitManager;
private final RubySymbol.SymbolTable symbolTable = new RubySymbol.SymbolTable(this);
private final Shape emptyShape;
private final Warnings warnings;
private final SafepointManager safepointManager;
private final Random random = new Random();
private final LexicalScope rootLexicalScope;
private final CompilerOptions compilerOptions;
private final AtomicLong nextObjectID = new AtomicLong(ObjectIDOperations.FIRST_OBJECT_ID);
private final ThreadLocal<Queue<Object>> throwTags = new ThreadLocal<Queue<Object>>() {
@Override
protected Queue<Object> initialValue() {
return new ArrayDeque<>();
}
};
public RubyContext(Ruby runtime) {
assert runtime != null;
compilerOptions = Truffle.getRuntime().createCompilerOptions();
if (compilerOptions.supportsOption("MinTimeThreshold")) {
compilerOptions.setOption("MinTimeThreshold", 100000000);
}
if (compilerOptions.supportsOption("MinInliningMaxCallerSize")) {
compilerOptions.setOption("MinInliningMaxCallerSize", 5000);
}
safepointManager = new SafepointManager(this);
this.runtime = runtime;
translator = new TranslatorDriver();
warnings = new Warnings(this);
// Object space manager needs to come early before we create any objects
objectSpaceManager = new ObjectSpaceManager(this);
emptyShape = RubyBasicObject.LAYOUT.createShape(new RubyOperations(this));
// See note in CoreLibrary#initialize to see why we need to break this into two statements
coreLibrary = new CoreLibrary(this);
coreLibrary.initialize();
featureManager = new FeatureManager(this);
traceManager = new TraceManager();
atExitManager = new AtExitManager();
// Must initialize threads before fibers
threadManager = new ThreadManager(this);
fiberManager = new FiberManager(this);
rootLexicalScope = new LexicalScope(null, coreLibrary.getObjectClass());
}
public Shape getEmptyShape() {
return emptyShape;
}
public static String checkInstanceVariableName(RubyContext context, String name, RubyNode currentNode) {
RubyNode.notDesignedForCompilation();
if (!name.startsWith("@")) {
throw new RaiseException(context.getCoreLibrary().nameErrorInstanceNameNotAllowable(name, currentNode));
}
return name;
}
public static String checkClassVariableName(RubyContext context, String name, RubyNode currentNode) {
RubyNode.notDesignedForCompilation();
if (!name.startsWith("@@")) {
throw new RaiseException(context.getCoreLibrary().nameErrorInstanceNameNotAllowable(name, currentNode));
}
return name;
}
public void loadFile(String fileName, RubyNode currentNode) {
if (new File(fileName).isAbsolute()) {
loadFileAbsolute(fileName, currentNode);
} else {
loadFileAbsolute(this.getRuntime().getCurrentDirectory() + File.separator + fileName, currentNode);
}
}
private void loadFileAbsolute(String fileName, RubyNode currentNode) {
final byte[] bytes;
try {
bytes = Files.readAllBytes(Paths.get(fileName));
} catch (IOException e) {
throw new RuntimeException(e);
}
// Assume UTF-8 for the moment
final Source source = Source.fromBytes(bytes, fileName, new BytesDecoder.UTF8BytesDecoder());
load(source, currentNode, SetFrameVisibilityNode.PRIVATE_VISIBILITY_WRAPPER);
}
public void load(Source source, RubyNode currentNode) {
load(source, currentNode, NodeWrapper.IDENTITY);
}
public void load(Source source, RubyNode currentNode, NodeWrapper nodeWrapper) {
execute(this, source, UTF8Encoding.INSTANCE, TranslatorDriver.ParserContext.TOP_LEVEL, coreLibrary.getMainObject(), null, currentNode, nodeWrapper);
}
public RubySymbol.SymbolTable getSymbolTable() {
return symbolTable;
}
@CompilerDirectives.TruffleBoundary
public RubySymbol newSymbol(String name) {
return symbolTable.getSymbol(name);
}
@CompilerDirectives.TruffleBoundary
public RubySymbol newSymbol(ByteList name) {
return symbolTable.getSymbol(name);
}
public Object eval(ByteList code, RubyNode currentNode) {
final Source source = Source.fromText(code, "(eval)");
return execute(this, source, code.getEncoding(), TranslatorDriver.ParserContext.TOP_LEVEL, coreLibrary.getMainObject(), null, currentNode);
}
public Object eval(ByteList code, Object self, RubyNode currentNode) {
final Source source = Source.fromText(code, "(eval)");
return execute(this, source, code.getEncoding(), TranslatorDriver.ParserContext.TOP_LEVEL, self, null, currentNode);
}
public Object eval(ByteList code, RubyBinding binding, RubyNode currentNode) {
final Source source = Source.fromText(code, "(eval)");
return execute(this, source, code.getEncoding(), TranslatorDriver.ParserContext.TOP_LEVEL, binding.getSelf(), binding.getFrame(), currentNode);
}
public Object execute(RubyContext context, Source source, Encoding defaultEncoding, TranslatorDriver.ParserContext parserContext, Object self, MaterializedFrame parentFrame, RubyNode currentNode) {
return execute(context, source, defaultEncoding, parserContext, self, parentFrame, currentNode, NodeWrapper.IDENTITY);
}
public Object execute(RubyContext context, Source source, Encoding defaultEncoding, TranslatorDriver.ParserContext parserContext, Object self, MaterializedFrame parentFrame, RubyNode currentNode, NodeWrapper wrapper) {
final RubyRootNode rootNode = translator.parse(context, source, defaultEncoding, parserContext, parentFrame, currentNode, wrapper);
final CallTarget callTarget = Truffle.getRuntime().createCallTarget(rootNode);
// TODO(CS): we really need a method here - it's causing problems elsewhere
return callTarget.call(RubyArguments.pack(null, parentFrame, self, null, new Object[]{}));
}
public long getNextObjectID() {
// TODO(CS): We can theoretically run out of long values
final long id = nextObjectID.getAndAdd(2);
if (id < 0) {
nextObjectID.set(Long.MIN_VALUE);
throw new RuntimeException("Object IDs exhausted");
}
return id;
}
public void shutdown() {
atExitManager.run();
threadManager.leaveGlobalLock();
objectSpaceManager.shutdown();
if (fiberManager != null) {
fiberManager.shutdown();
}
}
public RubyString makeString(String string) {
return RubyString.fromJavaString(coreLibrary.getStringClass(), string);
}
public RubyString makeString(char string) {
return makeString(Character.toString(string));
}
public RubyString makeString(ByteList bytes) {
return RubyString.fromByteList(coreLibrary.getStringClass(), bytes);
}
public IRubyObject toJRuby(Object object) {
RubyNode.notDesignedForCompilation();
if (object instanceof RubyNilClass) {
return runtime.getNil();
} else if (object == getCoreLibrary().getKernelModule()) {
return runtime.getKernel();
} else if (object == getCoreLibrary().getMainObject()) {
return runtime.getTopSelf();
} else if (object instanceof Boolean) {
return runtime.newBoolean((boolean) object);
} else if (object instanceof Integer) {
return runtime.newFixnum((int) object);
} else if (object instanceof Long) {
return runtime.newFixnum((long) object);
} else if (object instanceof Double) {
return runtime.newFloat((double) object);
} else if (object instanceof RubyString) {
return toJRuby((RubyString) object);
} else if (object instanceof RubyArray) {
return toJRuby((RubyArray) object);
} else {
throw getRuntime().newRuntimeError("cannot pass " + object + " to JRuby");
}
}
public org.jruby.RubyArray toJRuby(RubyArray array) {
RubyNode.notDesignedForCompilation();
final Object[] objects = array.slowToArray();
final IRubyObject[] store = new IRubyObject[objects.length];
for (int n = 0; n < objects.length; n++) {
store[n] = toJRuby(objects[n]);
}
return runtime.newArray(store);
}
public org.jruby.RubyString toJRuby(RubyString string) {
return runtime.newString(string.getBytes().dup());
}
public Object toTruffle(IRubyObject object) {
RubyNode.notDesignedForCompilation();
if (object == runtime.getTopSelf()) {
return getCoreLibrary().getMainObject();
} else if (object == runtime.getKernel()) {
return getCoreLibrary().getKernelModule();
} else if (object instanceof RubyNil) {
return getCoreLibrary().getNilObject();
} else if (object instanceof org.jruby.RubyBoolean.True) {
return true;
} else if (object instanceof org.jruby.RubyBoolean.False) {
return false;
} else if (object instanceof org.jruby.RubyFixnum) {
final long value = ((org.jruby.RubyFixnum) object).getLongValue();
if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) {
throw new UnsupportedOperationException();
}
return (int) value;
} else if (object instanceof org.jruby.RubyFloat) {
return ((org.jruby.RubyFloat) object).getDoubleValue();
} else if (object instanceof org.jruby.RubyString) {
return toTruffle((org.jruby.RubyString) object);
} else if (object instanceof org.jruby.RubySymbol) {
return getSymbolTable().getSymbol(object.toString());
} else if (object instanceof org.jruby.RubyArray) {
final org.jruby.RubyArray jrubyArray = (org.jruby.RubyArray) object;
final Object[] truffleArray = new Object[jrubyArray.size()];
for (int n = 0; n < truffleArray.length; n++) {
truffleArray[n] = toTruffle((IRubyObject) jrubyArray.get(n));
}
return new RubyArray(coreLibrary.getArrayClass(), truffleArray, truffleArray.length);
} else {
throw object.getRuntime().newRuntimeError("cannot pass " + object.inspect() + " to Truffle");
}
}
public RubyString toTruffle(org.jruby.RubyString string) {
return new RubyString(getCoreLibrary().getStringClass(), string.getByteList().dup());
}
public Ruby getRuntime() {
return runtime;
}
public CoreLibrary getCoreLibrary() {
return coreLibrary;
}
public FeatureManager getFeatureManager() {
return featureManager;
}
public ObjectSpaceManager getObjectSpaceManager() {
return objectSpaceManager;
}
public FiberManager getFiberManager() {
return fiberManager;
}
public ThreadManager getThreadManager() {
return threadManager;
}
public TranslatorDriver getTranslator() {
return translator;
}
public AtExitManager getAtExitManager() {
return atExitManager;
}
@Override
public String getLanguageShortName() {
return "ruby";
}
public TruffleHooks getHooks() {
return (TruffleHooks) runtime.getInstanceConfig().getTruffleHooks();
}
public TraceManager getTraceManager() {
return traceManager;
}
public Warnings getWarnings() {
return warnings;
}
public Queue<Object> getThrowTags() {
return throwTags.get();
}
public SafepointManager getSafepointManager() {
return safepointManager;
}
public Random getRandom() {
return random;
}
public LexicalScope getRootLexicalScope() {
return rootLexicalScope;
}
public CompilerOptions getCompilerOptions() {
return compilerOptions;
}
}