1
0
mirror of https://github.com/SquidDev-CC/CC-Tweaked synced 2025-04-07 19:26:42 +00:00

Switch a few more places to use Java 17 features

New ErrorProne hint, and one which is actually pretty useful!
This commit is contained in:
Jonathan Coates 2025-03-22 09:39:47 +00:00
parent c458360b18
commit 9c0ce27ce6
No known key found for this signature in database
GPG Key ID: B9E431FF07C98D06
19 changed files with 58 additions and 59 deletions

View File

@ -437,8 +437,8 @@ final class WiredNetworkImpl implements WiredNetwork {
}
private static WiredNodeImpl checkNode(WiredNode node) {
if (node instanceof WiredNodeImpl) {
return (WiredNodeImpl) node;
if (node instanceof WiredNodeImpl n) {
return n;
} else {
throw new IllegalArgumentException("Unknown implementation of IWiredNode: " + node);
}

View File

@ -66,8 +66,8 @@ public final class HelpingArgumentBuilder extends LiteralArgumentBuilder<Command
public LiteralArgumentBuilder<CommandSourceStack> then(final ArgumentBuilder<CommandSourceStack, ?> argument) {
if (getRedirect() != null) throw new IllegalStateException("Cannot add children to a redirected node");
if (argument instanceof HelpingArgumentBuilder) {
children.add((HelpingArgumentBuilder) argument);
if (argument instanceof HelpingArgumentBuilder child) {
children.add(child);
} else if (argument instanceof LiteralArgumentBuilder) {
super.then(argument);
} else {

View File

@ -38,7 +38,7 @@ public class WirelessModemBlockEntity extends BlockEntity {
@Override
public boolean equals(@Nullable IPeripheral other) {
return this == other || (other instanceof Peripheral && entity == ((Peripheral) other).entity);
return this == other || (other instanceof Peripheral o && entity == o.entity);
}
@Override

View File

@ -40,7 +40,6 @@ import org.jspecify.annotations.Nullable;
* monitor.setCursorPos(1, 1)
* monitor.write("Hello, world!")
* }</pre>
*
* @cc.see monitor_resize Queued when a monitor is resized.
* @cc.see monitor_touch Queued when an advanced monitor is clicked.
*/
@ -95,7 +94,7 @@ public class MonitorPeripheral extends TermMethods implements IPeripheral {
@Override
public boolean equals(@Nullable IPeripheral other) {
return other instanceof MonitorPeripheral && monitor == ((MonitorPeripheral) other).monitor;
return other instanceof MonitorPeripheral o && monitor == o.monitor;
}
private ServerMonitor getMonitor() throws LuaException {

View File

@ -57,11 +57,10 @@ public final class MonitorWatcher {
if (monitor == null) continue;
var pos = tile.getBlockPos();
var world = tile.getLevel();
if (!(world instanceof ServerLevel)) continue;
if (!(tile.getLevel() instanceof ServerLevel level)) continue;
var chunk = world.getChunkAt(pos);
if (((ServerLevel) world).getChunkSource().chunkMap.getPlayers(chunk.getPos(), false).isEmpty()) {
var chunk = level.getChunkAt(pos);
if (level.getChunkSource().chunkMap.getPlayers(chunk.getPos(), false).isEmpty()) {
continue;
}

View File

@ -53,7 +53,7 @@ public class SpeakerBlockEntity extends BlockEntity {
@Override
public boolean equals(@Nullable IPeripheral other) {
return this == other || (other instanceof Peripheral && speaker == ((Peripheral) other).speaker);
return this == other || (other instanceof Peripheral o && speaker == o.speaker);
}
}
}

View File

@ -25,7 +25,6 @@ public class PocketSpeaker extends AbstractPocketUpgrade {
@Override
public void update(IPocketAccess access, @Nullable IPeripheral peripheral) {
if (!(peripheral instanceof PocketSpeakerPeripheral)) return;
((PocketSpeakerPeripheral) peripheral).update();
if (peripheral instanceof PocketSpeakerPeripheral speaker) speaker.update();
}
}

View File

@ -62,14 +62,13 @@ public class TurtleDropCommand implements TurtleCommand {
}
}
switch (transferred) {
case ContainerTransfer.NO_SPACE:
return TurtleCommandResult.failure("No space for items");
case ContainerTransfer.NO_ITEMS:
return TurtleCommandResult.failure("No items to drop");
default:
return switch (transferred) {
case ContainerTransfer.NO_SPACE -> TurtleCommandResult.failure("No space for items");
case ContainerTransfer.NO_ITEMS -> TurtleCommandResult.failure("No items to drop");
default -> {
turtle.playAnimation(TurtleAnimation.WAIT);
return TurtleCommandResult.success();
}
yield TurtleCommandResult.success();
}
};
}
}

View File

@ -50,15 +50,14 @@ public class TurtleSuckCommand implements TurtleCommand {
if (inventory != null) {
// Take from inventory of thing in front
var transferred = inventory.moveTo(TurtleUtil.getOffsetInventory(turtle), quantity);
switch (transferred) {
case ContainerTransfer.NO_SPACE:
return TurtleCommandResult.failure("No space for items");
case ContainerTransfer.NO_ITEMS:
return TurtleCommandResult.failure("No items to take");
default:
return switch (transferred) {
case ContainerTransfer.NO_SPACE -> TurtleCommandResult.failure("No space for items");
case ContainerTransfer.NO_ITEMS -> TurtleCommandResult.failure("No items to take");
default -> {
turtle.playAnimation(TurtleAnimation.WAIT);
return TurtleCommandResult.success();
}
yield TurtleCommandResult.success();
}
};
} else {
// Suck up loose items off the ground
var aabb = new AABB(

View File

@ -70,9 +70,9 @@ public final class DropConsumer {
public static boolean onEntitySpawn(Entity entity) {
// Capture any nearby item spawns
if (dropWorld == entity.level() && entity instanceof ItemEntity
if (dropWorld == entity.level() && entity instanceof ItemEntity item
&& assertNonNull(dropBounds).contains(entity.position())) {
handleDrops(((ItemEntity) entity).getItem());
handleDrops(item.getItem());
return true;
}

View File

@ -79,8 +79,8 @@ public class PrettyJsonWriter extends JsonWriter {
// Otherwise we either need to push to our list or finish a record pair.
var head = stack.getLast();
if (head instanceof DocList) {
((DocList) head).add(object);
if (head instanceof DocList headList) {
headList.add(object);
} else {
stack.removeLast();
((DocList) stack.getLast()).add(new Pair((String) head, object));

View File

@ -83,7 +83,7 @@ object ClientTestHooks {
if (minecraft.levelSource.levelExists(LEVEL_NAME)) {
LOG.info("World already exists, opening.")
minecraft.createWorldOpenFlows().loadLevel(minecraft.screen, LEVEL_NAME)
minecraft.createWorldOpenFlows().loadLevel(minecraft.screen!!, LEVEL_NAME)
} else {
LOG.info("World does not exist, creating it.")
val rules = GameRules()

View File

@ -112,7 +112,7 @@ final class LuaDateTime {
private static int getField(Map<?, ?> table, String field, int def) throws LuaException {
var value = table.get(field);
if (value instanceof Number) return ((Number) value).intValue();
if (value instanceof Number n) return n.intValue();
if (def < 0) throw new LuaException("field \"" + field + "\" missing in date table");
return def;
}

View File

@ -110,14 +110,14 @@ public class OSAPI implements ILuaAPI {
return time;
}
private static int getDayForCalendar(Calendar c) {
var g = c instanceof GregorianCalendar ? (GregorianCalendar) c : new GregorianCalendar();
var year = c.get(Calendar.YEAR);
private static int getDayForCalendar(Calendar calendar) {
var g = calendar instanceof GregorianCalendar c ? c : new GregorianCalendar();
var year = calendar.get(Calendar.YEAR);
var day = 0;
for (var y = 1970; y < year; y++) {
day += g.isLeapYear(y) ? 366 : 365;
}
day += c.get(Calendar.DAY_OF_YEAR);
day += calendar.get(Calendar.DAY_OF_YEAR);
return day;
}
@ -133,7 +133,7 @@ public class OSAPI implements ILuaAPI {
* @param args The parameters of the event.
* @cc.tparam string name The name of the event to queue.
* @cc.param ... The parameters of the event. These can be any primitive type (boolean, number, string) as well as
* tables. Other types (like functions), as well as metatables, will not be preserved.
* tables. Other types (like functions), as well as metatables, will not be preserved.
* @cc.see os.pullEvent To pull the event queued
*/
@LuaFunction

View File

@ -265,8 +265,8 @@ public abstract class AbstractHandle {
checkOpen();
try {
var arg = arguments.get(0);
if (binary && arg instanceof Number) {
var number = ((Number) arg).intValue();
if (binary && arg instanceof Number n) {
var number = n.intValue();
writeSingle((byte) number);
} else {
channel.write(arguments.getBytesCoerced(0));

View File

@ -58,8 +58,8 @@ class TableImpl implements dan200.computercraft.api.lua.LuaTable<Object, Object>
private LuaValue getImpl(Object o) {
checkValid();
if (o instanceof String) return table.rawget((String) o);
if (o instanceof Integer) return table.rawget((Integer) o);
if (o instanceof String s) return table.rawget(s);
if (o instanceof Integer i) return table.rawget(i);
return Constants.NIL;
}

View File

@ -181,8 +181,8 @@ final class VarargArguments implements IArguments {
if (isClosed()) throw new IllegalStateException("Cannot use getTableUnsafe after IArguments has been closed.");
var value = varargs.arg(index + 1);
if (!(value instanceof LuaTable)) throw LuaValues.badArgument(index, "table", value.typeName());
return new TableImpl(this, (LuaTable) value);
if (!(value instanceof LuaTable table)) throw LuaValues.badArgument(index, "table", value.typeName());
return new TableImpl(this, table);
}
@Override
@ -191,8 +191,8 @@ final class VarargArguments implements IArguments {
var value = varargs.arg(index + 1);
if (value.isNil()) return Optional.empty();
if (!(value instanceof LuaTable)) throw LuaValues.badArgument(index, "table", value.typeName());
return Optional.of(new TableImpl(this, (LuaTable) value));
if (!(value instanceof LuaTable table)) throw LuaValues.badArgument(index, "table", value.typeName());
return Optional.of(new TableImpl(this, table));
}
@Override
@ -237,6 +237,7 @@ final class VarargArguments implements IArguments {
return metatable != null && metatable.rawget(NAME) instanceof LuaString s ? s.toString() : null;
}
@SuppressWarnings("ArrayRecordComponent")
private record ArraySlice<T>(T[] array, int offset) {
// FIXME: We should be able to remove the @Nullables if we update NullAway.

View File

@ -48,9 +48,10 @@ public class MethodTest {
@Test
public void testDynamicPeripheral() {
ComputerBootstrap.run(
"local dynamic = peripheral.wrap('top')\n" +
"assert(dynamic.foo() == 123, 'foo: ' .. tostring(dynamic.foo()))\n" +
"assert(dynamic.bar() == 321, 'bar: ' .. tostring(dynamic.bar()))",
"""
local dynamic = peripheral.wrap('top')
assert(dynamic.foo() == 123, 'foo: ' .. tostring(dynamic.foo()))
assert(dynamic.bar() == 321, 'bar: ' .. tostring(dynamic.bar()))""",
x -> x.getEnvironment().setPeripheral(ComputerSide.TOP, new Dynamic()),
50
);
@ -66,9 +67,10 @@ public class MethodTest {
@Test
public void testPeripheralThrow() {
ComputerBootstrap.run(
"local throw = peripheral.wrap('top')\n" +
"local _, err = pcall(function() throw.thisThread() end) assert(err == '/test.lua:2: !', (\"thisThread: %q\"):format(err))\n" +
"local _, err = pcall(function() throw.mainThread() end) assert(err == '/test.lua:3: !', (\"mainThread: %q\"):format(err))\n",
"""
local throw = peripheral.wrap('top')
local _, err = pcall(function() throw.thisThread() end) assert(err == '/test.lua:2: !', ("thisThread: %q"):format(err))
local _, err = pcall(function() throw.mainThread() end) assert(err == '/test.lua:3: !', ("mainThread: %q"):format(err))""",
x -> x.getEnvironment().setPeripheral(ComputerSide.TOP, new PeripheralThrow()),
50
);
@ -77,8 +79,9 @@ public class MethodTest {
@Test
public void testMany() {
ComputerBootstrap.run(
"assert(many.method_0)\n" +
"assert(many.method_39)",
"""
assert(many.method_0)
assert(many.method_39)""",
x -> x.addApi(new ManyMethods()), 50);
}
@ -94,8 +97,7 @@ public class MethodTest {
public void testModule() {
ComputerBootstrap.run(
"""
assert(require "test.module".func() == 123)
""",
assert(require "test.module".func() == 123)""",
x -> x.addApi(new IsModule()), 50);
}

View File

@ -168,6 +168,7 @@ public class TransformingClassLoader extends ClassLoader {
}
}
@SuppressWarnings("ArrayRecordComponent")
private record TransformedClass(String name, byte[] contents) {
}
}