Skip to content

Commit 9c0ce27

Browse files
committed
Switch a few more places to use Java 17 features
New ErrorProne hint, and one which is actually pretty useful!
1 parent c458360 commit 9c0ce27

File tree

19 files changed

+58
-59
lines changed

19 files changed

+58
-59
lines changed

projects/common/src/main/java/dan200/computercraft/impl/network/wired/WiredNetworkImpl.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -437,8 +437,8 @@ public int compareTo(TransmitPoint o) {
437437
}
438438

439439
private static WiredNodeImpl checkNode(WiredNode node) {
440-
if (node instanceof WiredNodeImpl) {
441-
return (WiredNodeImpl) node;
440+
if (node instanceof WiredNodeImpl n) {
441+
return n;
442442
} else {
443443
throw new IllegalArgumentException("Unknown implementation of IWiredNode: " + node);
444444
}

projects/common/src/main/java/dan200/computercraft/shared/command/builder/HelpingArgumentBuilder.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,8 @@ public LiteralArgumentBuilder<CommandSourceStack> executes(final Command<Command
6666
public LiteralArgumentBuilder<CommandSourceStack> then(final ArgumentBuilder<CommandSourceStack, ?> argument) {
6767
if (getRedirect() != null) throw new IllegalStateException("Cannot add children to a redirected node");
6868

69-
if (argument instanceof HelpingArgumentBuilder) {
70-
children.add((HelpingArgumentBuilder) argument);
69+
if (argument instanceof HelpingArgumentBuilder child) {
70+
children.add(child);
7171
} else if (argument instanceof LiteralArgumentBuilder) {
7272
super.then(argument);
7373
} else {

projects/common/src/main/java/dan200/computercraft/shared/peripheral/modem/wireless/WirelessModemBlockEntity.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ public Vec3 getPosition() {
3838

3939
@Override
4040
public boolean equals(@Nullable IPeripheral other) {
41-
return this == other || (other instanceof Peripheral && entity == ((Peripheral) other).entity);
41+
return this == other || (other instanceof Peripheral o && entity == o.entity);
4242
}
4343

4444
@Override

projects/common/src/main/java/dan200/computercraft/shared/peripheral/monitor/MonitorPeripheral.java

+1-2
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,6 @@
4040
* monitor.setCursorPos(1, 1)
4141
* monitor.write("Hello, world!")
4242
* }</pre>
43-
*
4443
* @cc.see monitor_resize Queued when a monitor is resized.
4544
* @cc.see monitor_touch Queued when an advanced monitor is clicked.
4645
*/
@@ -95,7 +94,7 @@ public void detach(IComputerAccess computer) {
9594

9695
@Override
9796
public boolean equals(@Nullable IPeripheral other) {
98-
return other instanceof MonitorPeripheral && monitor == ((MonitorPeripheral) other).monitor;
97+
return other instanceof MonitorPeripheral o && monitor == o.monitor;
9998
}
10099

101100
private ServerMonitor getMonitor() throws LuaException {

projects/common/src/main/java/dan200/computercraft/shared/peripheral/monitor/MonitorWatcher.java

+3-4
Original file line numberDiff line numberDiff line change
@@ -57,11 +57,10 @@ public static void onTick() {
5757
if (monitor == null) continue;
5858

5959
var pos = tile.getBlockPos();
60-
var world = tile.getLevel();
61-
if (!(world instanceof ServerLevel)) continue;
60+
if (!(tile.getLevel() instanceof ServerLevel level)) continue;
6261

63-
var chunk = world.getChunkAt(pos);
64-
if (((ServerLevel) world).getChunkSource().chunkMap.getPlayers(chunk.getPos(), false).isEmpty()) {
62+
var chunk = level.getChunkAt(pos);
63+
if (level.getChunkSource().chunkMap.getPlayers(chunk.getPos(), false).isEmpty()) {
6564
continue;
6665
}
6766

projects/common/src/main/java/dan200/computercraft/shared/peripheral/speaker/SpeakerBlockEntity.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ public SpeakerPosition getPosition() {
5353

5454
@Override
5555
public boolean equals(@Nullable IPeripheral other) {
56-
return this == other || (other instanceof Peripheral && speaker == ((Peripheral) other).speaker);
56+
return this == other || (other instanceof Peripheral o && speaker == o.speaker);
5757
}
5858
}
5959
}

projects/common/src/main/java/dan200/computercraft/shared/pocket/peripherals/PocketSpeaker.java

+1-2
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@ public IPeripheral createPeripheral(IPocketAccess access) {
2525

2626
@Override
2727
public void update(IPocketAccess access, @Nullable IPeripheral peripheral) {
28-
if (!(peripheral instanceof PocketSpeakerPeripheral)) return;
29-
((PocketSpeakerPeripheral) peripheral).update();
28+
if (peripheral instanceof PocketSpeakerPeripheral speaker) speaker.update();
3029
}
3130
}

projects/common/src/main/java/dan200/computercraft/shared/turtle/core/TurtleDropCommand.java

+7-8
Original file line numberDiff line numberDiff line change
@@ -62,14 +62,13 @@ public TurtleCommandResult execute(ITurtleAccess turtle) {
6262
}
6363
}
6464

65-
switch (transferred) {
66-
case ContainerTransfer.NO_SPACE:
67-
return TurtleCommandResult.failure("No space for items");
68-
case ContainerTransfer.NO_ITEMS:
69-
return TurtleCommandResult.failure("No items to drop");
70-
default:
65+
return switch (transferred) {
66+
case ContainerTransfer.NO_SPACE -> TurtleCommandResult.failure("No space for items");
67+
case ContainerTransfer.NO_ITEMS -> TurtleCommandResult.failure("No items to drop");
68+
default -> {
7169
turtle.playAnimation(TurtleAnimation.WAIT);
72-
return TurtleCommandResult.success();
73-
}
70+
yield TurtleCommandResult.success();
71+
}
72+
};
7473
}
7574
}

projects/common/src/main/java/dan200/computercraft/shared/turtle/core/TurtleSuckCommand.java

+7-8
Original file line numberDiff line numberDiff line change
@@ -50,15 +50,14 @@ public TurtleCommandResult execute(ITurtleAccess turtle) {
5050
if (inventory != null) {
5151
// Take from inventory of thing in front
5252
var transferred = inventory.moveTo(TurtleUtil.getOffsetInventory(turtle), quantity);
53-
switch (transferred) {
54-
case ContainerTransfer.NO_SPACE:
55-
return TurtleCommandResult.failure("No space for items");
56-
case ContainerTransfer.NO_ITEMS:
57-
return TurtleCommandResult.failure("No items to take");
58-
default:
53+
return switch (transferred) {
54+
case ContainerTransfer.NO_SPACE -> TurtleCommandResult.failure("No space for items");
55+
case ContainerTransfer.NO_ITEMS -> TurtleCommandResult.failure("No items to take");
56+
default -> {
5957
turtle.playAnimation(TurtleAnimation.WAIT);
60-
return TurtleCommandResult.success();
61-
}
58+
yield TurtleCommandResult.success();
59+
}
60+
};
6261
} else {
6362
// Suck up loose items off the ground
6463
var aabb = new AABB(

projects/common/src/main/java/dan200/computercraft/shared/util/DropConsumer.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -70,9 +70,9 @@ private static void handleDrops(ItemStack stack) {
7070

7171
public static boolean onEntitySpawn(Entity entity) {
7272
// Capture any nearby item spawns
73-
if (dropWorld == entity.level() && entity instanceof ItemEntity
73+
if (dropWorld == entity.level() && entity instanceof ItemEntity item
7474
&& assertNonNull(dropBounds).contains(entity.position())) {
75-
handleDrops(((ItemEntity) entity).getItem());
75+
handleDrops(item.getItem());
7676
return true;
7777
}
7878

projects/common/src/main/java/dan200/computercraft/shared/util/PrettyJsonWriter.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -79,8 +79,8 @@ private void pushValue(Object object) throws IOException {
7979

8080
// Otherwise we either need to push to our list or finish a record pair.
8181
var head = stack.getLast();
82-
if (head instanceof DocList) {
83-
((DocList) head).add(object);
82+
if (head instanceof DocList headList) {
83+
headList.add(object);
8484
} else {
8585
stack.removeLast();
8686
((DocList) stack.getLast()).add(new Pair((String) head, object));

projects/common/src/testMod/kotlin/dan200/computercraft/gametest/core/ClientTestHooks.kt

+1-1
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ object ClientTestHooks {
8383

8484
if (minecraft.levelSource.levelExists(LEVEL_NAME)) {
8585
LOG.info("World already exists, opening.")
86-
minecraft.createWorldOpenFlows().loadLevel(minecraft.screen, LEVEL_NAME)
86+
minecraft.createWorldOpenFlows().loadLevel(minecraft.screen!!, LEVEL_NAME)
8787
} else {
8888
LOG.info("World does not exist, creating it.")
8989
val rules = GameRules()

projects/core/src/main/java/dan200/computercraft/core/apis/LuaDateTime.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ static long fromTable(Map<?, ?> table) throws LuaException {
112112

113113
private static int getField(Map<?, ?> table, String field, int def) throws LuaException {
114114
var value = table.get(field);
115-
if (value instanceof Number) return ((Number) value).intValue();
115+
if (value instanceof Number n) return n.intValue();
116116
if (def < 0) throw new LuaException("field \"" + field + "\" missing in date table");
117117
return def;
118118
}

projects/core/src/main/java/dan200/computercraft/core/apis/OSAPI.java

+5-5
Original file line numberDiff line numberDiff line change
@@ -110,14 +110,14 @@ private static float getTimeForCalendar(Calendar c) {
110110
return time;
111111
}
112112

113-
private static int getDayForCalendar(Calendar c) {
114-
var g = c instanceof GregorianCalendar ? (GregorianCalendar) c : new GregorianCalendar();
115-
var year = c.get(Calendar.YEAR);
113+
private static int getDayForCalendar(Calendar calendar) {
114+
var g = calendar instanceof GregorianCalendar c ? c : new GregorianCalendar();
115+
var year = calendar.get(Calendar.YEAR);
116116
var day = 0;
117117
for (var y = 1970; y < year; y++) {
118118
day += g.isLeapYear(y) ? 366 : 365;
119119
}
120-
day += c.get(Calendar.DAY_OF_YEAR);
120+
day += calendar.get(Calendar.DAY_OF_YEAR);
121121
return day;
122122
}
123123

@@ -133,7 +133,7 @@ private static long getEpochForCalendar(Calendar c) {
133133
* @param args The parameters of the event.
134134
* @cc.tparam string name The name of the event to queue.
135135
* @cc.param ... The parameters of the event. These can be any primitive type (boolean, number, string) as well as
136-
* tables. Other types (like functions), as well as metatables, will not be preserved.
136+
* tables. Other types (like functions), as well as metatables, will not be preserved.
137137
* @cc.see os.pullEvent To pull the event queued
138138
*/
139139
@LuaFunction

projects/core/src/main/java/dan200/computercraft/core/apis/handles/AbstractHandle.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -265,8 +265,8 @@ public void write(IArguments arguments) throws LuaException {
265265
checkOpen();
266266
try {
267267
var arg = arguments.get(0);
268-
if (binary && arg instanceof Number) {
269-
var number = ((Number) arg).intValue();
268+
if (binary && arg instanceof Number n) {
269+
var number = n.intValue();
270270
writeSingle((byte) number);
271271
} else {
272272
channel.write(arguments.getBytesCoerced(0));

projects/core/src/main/java/dan200/computercraft/core/lua/TableImpl.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -58,8 +58,8 @@ public boolean isEmpty() {
5858

5959
private LuaValue getImpl(Object o) {
6060
checkValid();
61-
if (o instanceof String) return table.rawget((String) o);
62-
if (o instanceof Integer) return table.rawget((Integer) o);
61+
if (o instanceof String s) return table.rawget(s);
62+
if (o instanceof Integer i) return table.rawget(i);
6363
return Constants.NIL;
6464
}
6565

projects/core/src/main/java/dan200/computercraft/core/lua/VarargArguments.java

+5-4
Original file line numberDiff line numberDiff line change
@@ -181,8 +181,8 @@ public Optional<ByteBuffer> optBytes(int index) throws LuaException {
181181
if (isClosed()) throw new IllegalStateException("Cannot use getTableUnsafe after IArguments has been closed.");
182182

183183
var value = varargs.arg(index + 1);
184-
if (!(value instanceof LuaTable)) throw LuaValues.badArgument(index, "table", value.typeName());
185-
return new TableImpl(this, (LuaTable) value);
184+
if (!(value instanceof LuaTable table)) throw LuaValues.badArgument(index, "table", value.typeName());
185+
return new TableImpl(this, table);
186186
}
187187

188188
@Override
@@ -191,8 +191,8 @@ public Optional<ByteBuffer> optBytes(int index) throws LuaException {
191191

192192
var value = varargs.arg(index + 1);
193193
if (value.isNil()) return Optional.empty();
194-
if (!(value instanceof LuaTable)) throw LuaValues.badArgument(index, "table", value.typeName());
195-
return Optional.of(new TableImpl(this, (LuaTable) value));
194+
if (!(value instanceof LuaTable table)) throw LuaValues.badArgument(index, "table", value.typeName());
195+
return Optional.of(new TableImpl(this, table));
196196
}
197197

198198
@Override
@@ -237,6 +237,7 @@ void close() {
237237
return metatable != null && metatable.rawget(NAME) instanceof LuaString s ? s.toString() : null;
238238
}
239239

240+
@SuppressWarnings("ArrayRecordComponent")
240241
private record ArraySlice<T>(T[] array, int offset) {
241242
// FIXME: We should be able to remove the @Nullables if we update NullAway.
242243

projects/core/src/test/java/dan200/computercraft/core/asm/MethodTest.java

+12-10
Original file line numberDiff line numberDiff line change
@@ -48,9 +48,10 @@ public void testDynamic() {
4848
@Test
4949
public void testDynamicPeripheral() {
5050
ComputerBootstrap.run(
51-
"local dynamic = peripheral.wrap('top')\n" +
52-
"assert(dynamic.foo() == 123, 'foo: ' .. tostring(dynamic.foo()))\n" +
53-
"assert(dynamic.bar() == 321, 'bar: ' .. tostring(dynamic.bar()))",
51+
"""
52+
local dynamic = peripheral.wrap('top')
53+
assert(dynamic.foo() == 123, 'foo: ' .. tostring(dynamic.foo()))
54+
assert(dynamic.bar() == 321, 'bar: ' .. tostring(dynamic.bar()))""",
5455
x -> x.getEnvironment().setPeripheral(ComputerSide.TOP, new Dynamic()),
5556
50
5657
);
@@ -66,9 +67,10 @@ public void testExtra() {
6667
@Test
6768
public void testPeripheralThrow() {
6869
ComputerBootstrap.run(
69-
"local throw = peripheral.wrap('top')\n" +
70-
"local _, err = pcall(function() throw.thisThread() end) assert(err == '/test.lua:2: !', (\"thisThread: %q\"):format(err))\n" +
71-
"local _, err = pcall(function() throw.mainThread() end) assert(err == '/test.lua:3: !', (\"mainThread: %q\"):format(err))\n",
70+
"""
71+
local throw = peripheral.wrap('top')
72+
local _, err = pcall(function() throw.thisThread() end) assert(err == '/test.lua:2: !', ("thisThread: %q"):format(err))
73+
local _, err = pcall(function() throw.mainThread() end) assert(err == '/test.lua:3: !', ("mainThread: %q"):format(err))""",
7274
x -> x.getEnvironment().setPeripheral(ComputerSide.TOP, new PeripheralThrow()),
7375
50
7476
);
@@ -77,8 +79,9 @@ public void testPeripheralThrow() {
7779
@Test
7880
public void testMany() {
7981
ComputerBootstrap.run(
80-
"assert(many.method_0)\n" +
81-
"assert(many.method_39)",
82+
"""
83+
assert(many.method_0)
84+
assert(many.method_39)""",
8285
x -> x.addApi(new ManyMethods()), 50);
8386
}
8487

@@ -94,8 +97,7 @@ public void testFunction() {
9497
public void testModule() {
9598
ComputerBootstrap.run(
9699
"""
97-
assert(require "test.module".func() == 123)
98-
""",
100+
assert(require "test.module".func() == 123)""",
99101
x -> x.addApi(new IsModule()), 50);
100102
}
101103

projects/web/src/builder/java/cc/tweaked/web/builder/TransformingClassLoader.java

+1
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,7 @@ private static URL toURL(Path path) {
168168
}
169169
}
170170

171+
@SuppressWarnings("ArrayRecordComponent")
171172
private record TransformedClass(String name, byte[] contents) {
172173
}
173174
}

0 commit comments

Comments
 (0)