Skip to content

Commit

Permalink
Various cleanups
Browse files Browse the repository at this point in the history
  • Loading branch information
fniephaus committed Oct 10, 2023
1 parent 4a39a58 commit afc6085
Show file tree
Hide file tree
Showing 23 changed files with 56 additions and 80 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public static String findImage(final String userImage, final boolean isQuiet) {
}
final String[] selectedEntry = supportedImages[selection];
if (!isQuiet) {
out.println(String.format("Downloading %s...", selectedEntry[0]));
out.printf("Downloading %s...%n", selectedEntry[0]);
}
downloadAndUnzip(selectedEntry[1], resourcesDirectory);
return Objects.requireNonNull(findImageFile(resourcesDirectory));
Expand All @@ -64,7 +64,7 @@ private static int askUserToChooseImage(final String[][] supportedImages, final
int selection;
final Scanner userInput = new Scanner(System.in);
for (int i = 0; i < supportedImages.length; i++) {
out.println(String.format("%s) %s", i + 1, supportedImages[i][0]));
out.printf("%s) %s%n", i + 1, supportedImages[i][0]);
}
out.print("Choose Smalltalk image: ");
selection = -1;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ private static void loadTestImage(final boolean retry) {
executor = Executors.newSingleThreadExecutor();
final String imagePath = getPathToTestImage();
try {
runWithTimeout(imagePath, value -> loadImageContext(value), TEST_IMAGE_LOAD_TIMEOUT_SECONDS);
runWithTimeout(imagePath, AbstractSqueakTestCase::loadImageContext, TEST_IMAGE_LOAD_TIMEOUT_SECONDS);
println("Test image loaded from " + imagePath + "...");
patchImageForTesting();
} catch (final InterruptedException e) {
Expand Down Expand Up @@ -176,7 +176,7 @@ protected static TestResult runTestCase(final TestRequest request) {
throw new IllegalStateException("The previous test case has not finished yet");
}
try {
return runWithTimeout(request, value -> extractFailuresAndErrorsFromTestResult(value), TIMEOUT_SECONDS);
return runWithTimeout(request, AbstractSqueakTestCaseWithImage::extractFailuresAndErrorsFromTestResult, TIMEOUT_SECONDS);
} catch (final TimeoutException e) {
return TestResult.fromException("did not terminate in " + TIMEOUT_SECONDS + "s", e);
} catch (final InterruptedException e) {
Expand Down Expand Up @@ -239,14 +239,7 @@ private static String shouldPassCommand(final TestRequest request) {
return String.format("[(%s selector: #%s) shouldPass] on: Error do: [:e | false]", request.testCase, request.testSelector);
}

protected static final class TestRequest {
protected final String testCase;
protected final String testSelector;

protected TestRequest(final String testCase, final String testSelector) {
this.testCase = testCase;
this.testSelector = testSelector;
}
protected record TestRequest(String testCase, String testSelector) {
}

protected static final class TestResult {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,18 +121,20 @@ public void test11InteropJavaStringConversion() {

@Test
public void test12CannotReturnAtStart() {
assertEquals("'bla2'", evaluate("| result | \n" +
"[ result := [^'bla1'] on: BlockCannotReturn do: [:e | 'bla2' ]] fork. \n" +
"Processor yield.\n" +
"result").toString());
assertEquals("'bla2'", evaluate("""
| result |
[ result := [^'bla1'] on: BlockCannotReturn do: [:e | 'bla2' ]] fork.
Processor yield.
result""").toString());
}

@Test
public void test13CannotReturnInTheMiddle() {
assertEquals("'bla2'", evaluate("| result | \n" +
"[ result := [thisContext yourself. ^'bla1'] on: BlockCannotReturn do: [:e | 'bla2' ]] fork. \n" +
"Processor yield.\n" +
"result").toString());
assertEquals("'bla2'", evaluate("""
| result |
[ result := [thisContext yourself. ^'bla1'] on: BlockCannotReturn do: [:e | 'bla2' ]] fork.
Processor yield.
result""").toString());
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ protected static Stream<SqueakTest> allTests() {
final Properties properties = loadProperties();
return properties.stringPropertyNames().stream() //
.map(test -> parseTest(test, properties.getProperty(test))) //
.sorted(Comparator.comparing((final SqueakTest t) -> t.type).thenComparing((final SqueakTest t) -> t.qualifiedName()));
.sorted(Comparator.comparing((final SqueakTest t) -> t.type).thenComparing(SqueakTest::qualifiedName));
}
// Checkstyle: resume

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ protected void finalizeContext(final SqueakImageContext context) {
}

@Override
protected CallTarget parse(final ParsingRequest request) throws Exception {
protected CallTarget parse(final ParsingRequest request) {
final SqueakImageContext image = SqueakImageContext.getSlow();
final Source source = request.getSource();
final String imageOrSourcePath = source.getCharacters().toString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ private Object run() {
if (!truffleFile.isRegularFile()) {
throw SqueakException.create(MiscUtils.format("Image at '%s' does not exist.", image.getImagePath()));
}
try (BufferedInputStream inputStream = new BufferedInputStream(truffleFile.newInputStream());) {
try (BufferedInputStream inputStream = new BufferedInputStream(truffleFile.newInputStream())) {
readHeader(inputStream);
readBody(inputStream);
} catch (final IOException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,15 +162,13 @@ private boolean ignoredForAOT(final Method method) {
return true;
}
final String classSimpleName = method.getDeclaringClass().getSimpleName();
switch (classSimpleName) {
case "Class":
if (methodName.contains("Annotation")) {
return true;
}
return !ArrayUtils.containsEqual(new String[]{"getCanonicalName", "getName", "getSimpleName", "isInstance", "toString"}, methodName);
default:
return false;
if ("Class".equals(classSimpleName)) {
if (methodName.contains("Annotation")) {
return true;
}
return !ArrayUtils.containsEqual(new String[]{"getCanonicalName", "getName", "getSimpleName", "isInstance", "toString"}, methodName);
}
return false;
}
};
private static final ClassValue<InteropArray> CLASSES_TO_MEMBERS = new ClassValue<>() {
Expand Down Expand Up @@ -233,7 +231,7 @@ public static Object wrap(final Object object) {
} else if (object instanceof final Float o) {
return (double) o;
} else {
return CACHE.computeIfAbsent(object, o -> new JavaObjectWrapper(o));
return CACHE.computeIfAbsent(object, JavaObjectWrapper::new);
}
}

Expand Down Expand Up @@ -351,7 +349,6 @@ protected Object invokeMember(final String member, final Object... arguments) th

@ExportMessage
@TruffleBoundary
@SuppressWarnings("deprecation") // isAccessible deprecated in Java 11
protected void writeMember(final String key, final Object value) {
final Field field = lookupFields().get(key);
if (field != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
*/
package de.hpi.swa.trufflesqueak.interop;

import java.io.IOException;
import java.nio.charset.Charset;

import com.oracle.truffle.api.TruffleFile;
Expand All @@ -16,7 +15,7 @@
public final class SqueakFileDetector implements TruffleFile.FileTypeDetector {

@Override
public String findMimeType(final TruffleFile file) throws IOException {
public String findMimeType(final TruffleFile file) {
final String fileName = file.getName();
if (fileName == null) {
return null;
Expand All @@ -30,7 +29,7 @@ public String findMimeType(final TruffleFile file) throws IOException {
}

@Override
public Charset findEncoding(final TruffleFile file) throws IOException {
public Charset findEncoding(final TruffleFile file) {
return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -297,9 +297,7 @@ public void setCursor(final int[] cursorWords, final int[] mask, final int width
final Point hotSpot = new Point(Math.min(Math.max(offsetX, 1), width - 1), Math.min(Math.max(offsetY, 1), height - 1));
cursor = Toolkit.getDefaultToolkit().createCustomCursor(bufferedImage, hotSpot, "TruffleSqueak Cursor");
}
EventQueue.invokeLater(() -> {
frame.setCursor(cursor);
});
EventQueue.invokeLater(() -> frame.setCursor(cursor));
}

private static int[] mergeCursorWithMask(final int[] cursorWords, final int[] maskWords) {
Expand Down Expand Up @@ -365,9 +363,7 @@ public boolean getDeferUpdates() {

@TruffleBoundary
public void setWindowTitle(final String title) {
EventQueue.invokeLater(() -> {
frame.setTitle(title);
});
EventQueue.invokeLater(() -> frame.setTitle(title));
}

public void setInputSemaphoreIndex(final int interruptSemaphoreIndex) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,11 @@ protected AbstractSqueakObjectWithClassAndHash(final long header, final ClassObj
}

protected AbstractSqueakObjectWithClassAndHash(final SqueakImageContext image, final ClassObject klass) {
this(image.getCurrentMarkingFlag(), HASH_UNINITIALIZED, klass);
this(image.getCurrentMarkingFlag(), klass);
}

private AbstractSqueakObjectWithClassAndHash(final boolean markingFlag, final int hash, final ClassObject klass) {
squeahHashAndBits = hash;
private AbstractSqueakObjectWithClassAndHash(final boolean markingFlag, final ClassObject klass) {
squeahHashAndBits = AbstractSqueakObjectWithClassAndHash.HASH_UNINITIALIZED;
squeakClass = klass;
if (markingFlag) {
toggleMarkingFlag();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,7 @@ public int getStackPointer() {
}

public void setStackPointer(final int value) {
assert 0 <= value && value <= getCodeObject().getSqueakContextSize() : value + " not between 0 and " + getCodeObject().getSqueakContextSize() + " in " + toString();
assert 0 <= value && value <= getCodeObject().getSqueakContextSize() : value + " not between 0 and " + getCodeObject().getSqueakContextSize() + " in " + this;
FrameAccess.setStackPointer(getOrCreateTruffleFrame(), value);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ protected boolean isMemberModifiable(@SuppressWarnings("unused") final String me

@SuppressWarnings("unused")
@ExportMessage
protected void writeMember(final String member, final Object value) throws UnknownIdentifierException, UnsupportedMessageException {
protected void writeMember(final String member, final Object value) {
// TODO: allow modifications
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,10 @@ public DoItRootNode(final SqueakImageContext image, final TruffleLanguage<?> lan

@Override
public Object execute(final VirtualFrame frame) {
if (!(maybeClosure instanceof BlockClosureObject)) {
if (!(maybeClosure instanceof BlockClosureObject closure)) {
return NilObject.SINGLETON;

}
final BlockClosureObject closure = (BlockClosureObject) maybeClosure;
if (closure.getNumArgs() != frame.getArguments().length) {
return NilObject.SINGLETON;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ protected ConditionalJumpNode(final CompiledCodeObject code, final int index, fi

@Override
public final void executeVoid(final VirtualFrame frame) {
CompilerDirectives.shouldNotReachHere();
throw CompilerDirectives.shouldNotReachHere();
}

public final boolean executeCondition(final VirtualFrame frame) {
Expand Down Expand Up @@ -131,7 +131,7 @@ public static UnconditionalJumpNode createLongExtended(final CompiledCodeObject

@Override
public void executeVoid(final VirtualFrame frame) {
CompilerDirectives.shouldNotReachHere();
throw CompilerDirectives.shouldNotReachHere();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -239,8 +239,8 @@ protected static final NativeObject doNormalize(final NativeObject receiver) {
final long[] words = receiver.getLongStorage();
final int length = words.length;
double len = 0.0D;
for (int i = 0; i < length; i++) {
final double value = Double.longBitsToDouble(words[i]);
for (long word : words) {
final double value = Double.longBitsToDouble(word);
len += value * value;
}
if (len <= 0.0D) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -241,8 +241,8 @@ protected static final NativeObject doNormalize(final NativeObject receiver) {
final int[] ints = receiver.getIntStorage();
final int length = ints.length;
float len = 0.0F;
for (int i = 0; i < length; i++) {
final float value = Float.intBitsToFloat(ints[i]);
for (int anInt : ints) {
final float value = Float.intBitsToFloat(anInt);
len += value * value;
}
if (len <= 0.0F) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ protected final ArrayObject doGet(@SuppressWarnings("unused") final Object recei
final SqueakImageContext image = getContext();
if (cachedList == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
cachedList = image.env.getPublicLanguages().values().stream().map(l -> JavaObjectWrapper.wrap(l)).toArray();
cachedList = image.env.getPublicLanguages().values().stream().map(JavaObjectWrapper::wrap).toArray();
}
return image.asArrayOfObjects(cachedList.clone());
}
Expand All @@ -284,7 +284,7 @@ protected final ArrayObject doGet(@SuppressWarnings("unused") final Object recei
final SqueakImageContext image = getContext();
if (cachedList == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
cachedList = image.env.getInternalLanguages().values().stream().map(l -> JavaObjectWrapper.wrap(l)).toArray();
cachedList = image.env.getInternalLanguages().values().stream().map(JavaObjectWrapper::wrap).toArray();
}
return image.asArrayOfObjects(cachedList.clone());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -154,11 +154,7 @@ private static TrustManagerFactory prepareSystemTrustMangerFactory()
return factory;
}

private static final class CertificateInfo {

private final Certificate certificate;
private final PrivateKey privateKey;

private record CertificateInfo(Certificate certificate, PrivateKey privateKey) {
private CertificateInfo(final Certificate certificate, final PrivateKey privateKey) {
this.certificate = Objects.requireNonNull(certificate, "No certificate in PEM");
this.privateKey = Objects.requireNonNull(privateKey, "No private key in PEM");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,9 @@
import com.oracle.truffle.api.dsl.ImportStatic;
import com.oracle.truffle.api.dsl.NodeFactory;
import com.oracle.truffle.api.dsl.Specialization;

import com.oracle.truffle.api.nodes.DirectCallNode;
import com.oracle.truffle.api.nodes.Node;
import com.oracle.truffle.api.nodes.NodeVisitor;
import com.oracle.truffle.api.nodes.RootNode;

import de.hpi.swa.trufflesqueak.exceptions.PrimitiveFailed;
import de.hpi.swa.trufflesqueak.image.SqueakImageContext;
import de.hpi.swa.trufflesqueak.interop.JavaObjectWrapper;
Expand Down Expand Up @@ -92,14 +90,11 @@ protected final Object doGet(@SuppressWarnings("unused") final Object receiver,
final Object wrappedObject = target.unwrap();
if (wrappedObject instanceof RootNode rootNode) {
final List<DirectCallNode> callNodes = new ArrayList<>();
rootNode.accept(new NodeVisitor() {
@Override
public boolean visit(final Node node) {
if (node instanceof DirectCallNode) {
callNodes.add((DirectCallNode) node);
}
return true;
rootNode.accept(node -> {
if (node instanceof DirectCallNode) {
callNodes.add((DirectCallNode) node);
}
return true;
});
return JavaObjectWrapper.wrap(callNodes.toArray(new DirectCallNode[0]));
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -627,9 +627,9 @@ private int sendBlockwithwithwith(final PointersObject literalStream, final Poin
} else {
/* match */
sum = sum + Byte.toUnsignedInt(lit) + DeflateMinMatch;
if (Byte.toUnsignedInt(lit) >= 256) {
throw PrimitiveFailed.GENERIC_ERROR;
}
// if (Byte.toUnsignedInt(lit) >= 256) {
// throw PrimitiveFailed.GENERIC_ERROR;
// }
int code = zipMatchLengthCodes[Byte.toUnsignedInt(lit)];
if (code >= litBlCount) {
throw PrimitiveFailed.GENERIC_ERROR;
Expand Down Expand Up @@ -896,7 +896,7 @@ private static int shr(final int a, final int b) {
}

private static int div(final int a, final int b) {
return (int) Math.floor(a / b);
return (int) ((double) a / b);
}

private static int mod(final int a, final int b) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ private void terminateBetween(final ContextObject start, final ContextObject end
private void terminateBetween(final FrameMarker start, final ContextObject end) {
assert start != null : "Unexpected `null` value";
final ContextObject[] bottomContextOnTruffleStack = new ContextObject[1];
final ContextObject result = Truffle.getRuntime().iterateFrames(new FrameInstanceVisitor<ContextObject>() {
final ContextObject result = Truffle.getRuntime().iterateFrames(new FrameInstanceVisitor<>() {
boolean foundMyself;

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
*/
package de.hpi.swa.trufflesqueak.nodes.primitives.impl;

import java.util.Arrays;
import java.util.List;

import com.oracle.truffle.api.CompilerDirectives;
Expand Down Expand Up @@ -878,6 +877,6 @@ public List<NodeFactory<? extends AbstractPrimitiveNode>> getFactories() {

@Override
public List<Class<? extends AbstractSingletonPrimitiveNode>> getSingletonPrimitives() {
return Arrays.asList(PrimScreenSizeNode.class);
return List.of(PrimScreenSizeNode.class);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ public static void printSqStackTrace(final ContextObject context) {
CompilerAsserts.neverPartOfCompilation("For debugging purposes only");
final StringBuilder b = new StringBuilder();
printSqMaterializedStackTraceOn(b, context);
SqueakImageContext.getSlow().getOutput().println(b.toString());
SqueakImageContext.getSlow().getOutput().println(b);
}

private static void printSemaphoreOrNil(final StringBuilder b, final String label, final Object semaphoreOrNil, final boolean printIfNil) {
Expand Down

0 comments on commit afc6085

Please sign in to comment.