From 158850be0925dae101b98bdf4306aecd55e9c9f9 Mon Sep 17 00:00:00 2001 From: Jonathan Coates Date: Tue, 25 Oct 2022 22:58:31 +0100 Subject: [PATCH] Some Java-17ification I might just stick on 1.18 for the rest of these refactors. Porting across the mojmap boundary is painful. --- .../api/filesystem/FileAttributes.java | 26 ++----------- .../computercraft/api/lua/IArguments.java | 32 ++++++++-------- .../computercraft/api/lua/LuaTable.java | 6 +-- .../client/gui/OptionScreen.java | 2 +- .../client/pocket/ClientPocketComputers.java | 2 +- .../dan200/computercraft/core/apis/OSAPI.java | 11 +----- .../core/apis/http/options/AddressRule.java | 4 +- .../apis/http/websocket/WebsocketHandler.java | 4 +- .../computercraft/core/asm/GenericMethod.java | 5 +-- .../computercraft/core/asm/ObjectSource.java | 4 +- .../computercraft/core/asm/Reflect.java | 4 +- .../core/computer/ComputerExecutor.java | 12 +----- .../core/filesystem/MountWrapper.java | 4 +- .../core/lua/CobaltLuaMachine.java | 22 +++++------ .../core/lua/MachineEnvironment.java | 35 +++-------------- .../computercraft/data/PrettyJsonWriter.java | 38 ++++++------------- .../dan200/computercraft/shared/Registry.java | 2 +- .../shared/TurtlePermissions.java | 2 +- .../arguments/ComputersArgumentType.java | 6 +-- .../command/arguments/RepeatArgumentType.java | 2 +- .../arguments/TrackingFieldArgumentType.java | 4 +- .../shared/computer/core/ServerContext.java | 9 +---- .../metrics/basic/AggregatedMetric.java | 24 ++---------- .../computer/recipe/ComputerFamilyRecipe.java | 2 +- .../shared/computer/upload/FileSlice.java | 28 +------------- .../integration/UpgradeRecipeGenerator.java | 7 +--- .../client/ComputerTerminalClientMessage.java | 4 +- .../network/server/UploadFileMessage.java | 6 +-- .../commandblock/CommandBlockPeripheral.java | 4 +- .../peripheral/generic/data/ItemData.java | 3 +- .../peripheral/monitor/MonitorWatcher.java | 13 +------ .../peripheral/monitor/TileMonitor.java | 14 +++---- .../shared/peripheral/monitor/XYPair.java | 11 +----- .../shared/turtle/core/TurtleBrain.java | 4 +- .../turtle/core/TurtleCommandQueueEntry.java | 10 +---- .../computercraft/shared/util/RecipeUtil.java | 12 +----- .../core/computer/FakeComputerManager.java | 2 +- 37 files changed, 106 insertions(+), 274 deletions(-) diff --git a/src/main/java/dan200/computercraft/api/filesystem/FileAttributes.java b/src/main/java/dan200/computercraft/api/filesystem/FileAttributes.java index fec198d98..16a709749 100644 --- a/src/main/java/dan200/computercraft/api/filesystem/FileAttributes.java +++ b/src/main/java/dan200/computercraft/api/filesystem/FileAttributes.java @@ -11,20 +11,14 @@ import java.time.Instant; /** * A simple version of {@link BasicFileAttributes}, which provides what information a {@link IMount} already exposes. + * + * @param isDirectory Whether this filesystem entry is a directory. + * @param size The size of the file. */ -final class FileAttributes implements BasicFileAttributes +record FileAttributes(boolean isDirectory, long size) implements BasicFileAttributes { private static final FileTime EPOCH = FileTime.from( Instant.EPOCH ); - private final boolean isDirectory; - private final long size; - - FileAttributes( boolean isDirectory, long size ) - { - this.isDirectory = isDirectory; - this.size = size; - } - @Override public FileTime lastModifiedTime() { @@ -49,12 +43,6 @@ final class FileAttributes implements BasicFileAttributes return !isDirectory; } - @Override - public boolean isDirectory() - { - return isDirectory; - } - @Override public boolean isSymbolicLink() { @@ -67,12 +55,6 @@ final class FileAttributes implements BasicFileAttributes return false; } - @Override - public long size() - { - return size; - } - @Override public Object fileKey() { diff --git a/src/main/java/dan200/computercraft/api/lua/IArguments.java b/src/main/java/dan200/computercraft/api/lua/IArguments.java index 4809cfc77..faf47011c 100644 --- a/src/main/java/dan200/computercraft/api/lua/IArguments.java +++ b/src/main/java/dan200/computercraft/api/lua/IArguments.java @@ -69,8 +69,8 @@ public interface IArguments default double getDouble( int index ) throws LuaException { Object value = get( index ); - if( !(value instanceof Number) ) throw LuaValues.badArgumentOf( index, "number", value ); - return ((Number) value).doubleValue(); + if( !(value instanceof Number number) ) throw LuaValues.badArgumentOf( index, "number", value ); + return number.doubleValue(); } /** @@ -95,8 +95,8 @@ public interface IArguments default long getLong( int index ) throws LuaException { Object value = get( index ); - if( !(value instanceof Number) ) throw LuaValues.badArgumentOf( index, "number", value ); - return LuaValues.checkFiniteNum( index, (Number) value ).longValue(); + if( !(value instanceof Number number) ) throw LuaValues.badArgumentOf( index, "number", value ); + return LuaValues.checkFiniteNum( index, number ).longValue(); } /** @@ -121,8 +121,8 @@ public interface IArguments default boolean getBoolean( int index ) throws LuaException { Object value = get( index ); - if( !(value instanceof Boolean) ) throw LuaValues.badArgumentOf( index, "boolean", value ); - return (Boolean) value; + if( !(value instanceof Boolean bool) ) throw LuaValues.badArgumentOf( index, "boolean", value ); + return bool; } /** @@ -136,8 +136,8 @@ public interface IArguments default String getString( int index ) throws LuaException { Object value = get( index ); - if( !(value instanceof String) ) throw LuaValues.badArgumentOf( index, "string", value ); - return (String) value; + if( !(value instanceof String string) ) throw LuaValues.badArgumentOf( index, "string", value ); + return string; } /** @@ -213,8 +213,8 @@ public interface IArguments { Object value = get( index ); if( value == null ) return Optional.empty(); - if( !(value instanceof Number) ) throw LuaValues.badArgumentOf( index, "number", value ); - return Optional.of( ((Number) value).doubleValue() ); + if( !(value instanceof Number number) ) throw LuaValues.badArgumentOf( index, "number", value ); + return Optional.of( number.doubleValue() ); } /** @@ -241,8 +241,8 @@ public interface IArguments { Object value = get( index ); if( value == null ) return Optional.empty(); - if( !(value instanceof Number) ) throw LuaValues.badArgumentOf( index, "number", value ); - return Optional.of( LuaValues.checkFiniteNum( index, (Number) value ).longValue() ); + if( !(value instanceof Number number) ) throw LuaValues.badArgumentOf( index, "number", value ); + return Optional.of( LuaValues.checkFiniteNum( index, number ).longValue() ); } /** @@ -270,8 +270,8 @@ public interface IArguments { Object value = get( index ); if( value == null ) return Optional.empty(); - if( !(value instanceof Boolean) ) throw LuaValues.badArgumentOf( index, "boolean", value ); - return Optional.of( (Boolean) value ); + if( !(value instanceof Boolean bool) ) throw LuaValues.badArgumentOf( index, "boolean", value ); + return Optional.of( bool ); } /** @@ -285,8 +285,8 @@ public interface IArguments { Object value = get( index ); if( value == null ) return Optional.empty(); - if( !(value instanceof String) ) throw LuaValues.badArgumentOf( index, "string", value ); - return Optional.of( (String) value ); + if( !(value instanceof String string) ) throw LuaValues.badArgumentOf( index, "string", value ); + return Optional.of( string ); } /** diff --git a/src/main/java/dan200/computercraft/api/lua/LuaTable.java b/src/main/java/dan200/computercraft/api/lua/LuaTable.java index 7362747d7..46313f1f0 100644 --- a/src/main/java/dan200/computercraft/api/lua/LuaTable.java +++ b/src/main/java/dan200/computercraft/api/lua/LuaTable.java @@ -35,9 +35,8 @@ public interface LuaTable extends Map default long getLong( int index ) throws LuaException { Object value = get( (double) index ); - if( !(value instanceof Number) ) throw badTableItem( index, "number", getType( value ) ); + if( !(value instanceof Number number) ) throw badTableItem( index, "number", getType( value ) ); - Number number = (Number) value; double asDouble = number.doubleValue(); if( !Double.isFinite( asDouble ) ) throw badTableItem( index, "number", getNumericType( asDouble ) ); return number.longValue(); @@ -53,9 +52,8 @@ public interface LuaTable extends Map default long getLong( String key ) throws LuaException { Object value = get( key ); - if( !(value instanceof Number) ) throw badField( key, "number", getType( value ) ); + if( !(value instanceof Number number) ) throw badField( key, "number", getType( value ) ); - Number number = (Number) value; double asDouble = number.doubleValue(); if( !Double.isFinite( asDouble ) ) throw badField( key, "number", getNumericType( asDouble ) ); return number.longValue(); diff --git a/src/main/java/dan200/computercraft/client/gui/OptionScreen.java b/src/main/java/dan200/computercraft/client/gui/OptionScreen.java index a02df3952..bb438f85d 100644 --- a/src/main/java/dan200/computercraft/client/gui/OptionScreen.java +++ b/src/main/java/dan200/computercraft/client/gui/OptionScreen.java @@ -56,7 +56,7 @@ public final class OptionScreen extends Screen public static Screen unwrap( Screen screen ) { - return screen instanceof OptionScreen ? ((OptionScreen) screen).getOriginalScreen() : screen; + return screen instanceof OptionScreen option ? option.getOriginalScreen() : screen; } @Override diff --git a/src/main/java/dan200/computercraft/client/pocket/ClientPocketComputers.java b/src/main/java/dan200/computercraft/client/pocket/ClientPocketComputers.java index ff9d4f20c..36c17bdc2 100644 --- a/src/main/java/dan200/computercraft/client/pocket/ClientPocketComputers.java +++ b/src/main/java/dan200/computercraft/client/pocket/ClientPocketComputers.java @@ -57,7 +57,7 @@ public final class ClientPocketComputers @Nonnull public static PocketComputerData get( ItemStack stack ) { - ComputerFamily family = stack.getItem() instanceof ItemComputer ? ((ItemComputer) stack.getItem()).getFamily() : ComputerFamily.NORMAL; + ComputerFamily family = stack.getItem() instanceof ItemComputer computer ? computer.getFamily() : ComputerFamily.NORMAL; return get( ItemPocketComputer.getInstanceID( stack ), family != ComputerFamily.NORMAL ); } } diff --git a/src/main/java/dan200/computercraft/core/apis/OSAPI.java b/src/main/java/dan200/computercraft/core/apis/OSAPI.java index 9b7b0c943..538a306f1 100644 --- a/src/main/java/dan200/computercraft/core/apis/OSAPI.java +++ b/src/main/java/dan200/computercraft/core/apis/OSAPI.java @@ -39,17 +39,8 @@ public class OSAPI implements ILuaAPI private int nextAlarmToken = 0; - private static class Alarm implements Comparable + private record Alarm(double time, int day) implements Comparable { - final double time; - final int day; - - Alarm( double time, int day ) - { - this.time = time; - this.day = day; - } - @Override public int compareTo( @Nonnull Alarm o ) { diff --git a/src/main/java/dan200/computercraft/core/apis/http/options/AddressRule.java b/src/main/java/dan200/computercraft/core/apis/http/options/AddressRule.java index 71cc61076..33fb1f250 100644 --- a/src/main/java/dan200/computercraft/core/apis/http/options/AddressRule.java +++ b/src/main/java/dan200/computercraft/core/apis/http/options/AddressRule.java @@ -85,8 +85,8 @@ public final class AddressRule int port = socketAddress.getPort(); InetAddress address = socketAddress.getAddress(); - Inet4Address ipv4Address = address instanceof Inet6Address && InetAddresses.is6to4Address( (Inet6Address) address ) - ? InetAddresses.get6to4IPv4Address( (Inet6Address) address ) : null; + Inet4Address ipv4Address = address instanceof Inet6Address inet6 && InetAddresses.is6to4Address( inet6 ) + ? InetAddresses.get6to4IPv4Address( inet6 ) : null; for( AddressRule rule : rules ) { diff --git a/src/main/java/dan200/computercraft/core/apis/http/websocket/WebsocketHandler.java b/src/main/java/dan200/computercraft/core/apis/http/websocket/WebsocketHandler.java index e5e277a13..98de5ac8f 100644 --- a/src/main/java/dan200/computercraft/core/apis/http/websocket/WebsocketHandler.java +++ b/src/main/java/dan200/computercraft/core/apis/http/websocket/WebsocketHandler.java @@ -61,9 +61,9 @@ public class WebsocketHandler extends SimpleChannelInboundHandler } WebSocketFrame frame = (WebSocketFrame) msg; - if( frame instanceof TextWebSocketFrame ) + if( frame instanceof TextWebSocketFrame textFrame ) { - String data = ((TextWebSocketFrame) frame).text(); + String data = textFrame.text(); websocket.environment().observe( Metrics.WEBSOCKET_INCOMING, data.length() ); websocket.environment().queueEvent( MESSAGE_EVENT, websocket.address(), data, false ); diff --git a/src/main/java/dan200/computercraft/core/asm/GenericMethod.java b/src/main/java/dan200/computercraft/core/asm/GenericMethod.java index 85205ee1a..43b99501c 100644 --- a/src/main/java/dan200/computercraft/core/asm/GenericMethod.java +++ b/src/main/java/dan200/computercraft/core/asm/GenericMethod.java @@ -19,7 +19,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; -import java.util.stream.Collectors; import java.util.stream.Stream; /** @@ -51,7 +50,7 @@ public class GenericMethod static List all() { if( cache != null ) return cache; - return cache = sources.stream().flatMap( GenericMethod::getMethods ).collect( Collectors.toList() ); + return cache = sources.stream().flatMap( GenericMethod::getMethods ).toList(); } public static synchronized void register( @Nonnull GenericSource source ) @@ -69,7 +68,7 @@ public class GenericMethod private static Stream getMethods( GenericSource source ) { Class klass = source.getClass(); - PeripheralType type = source instanceof GenericPeripheral ? ((GenericPeripheral) source).getType() : null; + PeripheralType type = source instanceof GenericPeripheral generic ? generic.getType() : null; return Arrays.stream( klass.getDeclaredMethods() ) .map( method -> { diff --git a/src/main/java/dan200/computercraft/core/asm/ObjectSource.java b/src/main/java/dan200/computercraft/core/asm/ObjectSource.java index b47c862e8..f88701a04 100644 --- a/src/main/java/dan200/computercraft/core/asm/ObjectSource.java +++ b/src/main/java/dan200/computercraft/core/asm/ObjectSource.java @@ -21,9 +21,9 @@ public interface ObjectSource { for( NamedMethod method : generator.getMethods( object.getClass() ) ) accept.accept( object, method ); - if( object instanceof ObjectSource ) + if( object instanceof ObjectSource source ) { - for( Object extra : ((ObjectSource) object).getExtra() ) + for( Object extra : source.getExtra() ) { for( NamedMethod method : generator.getMethods( extra.getClass() ) ) accept.accept( extra, method ); } diff --git a/src/main/java/dan200/computercraft/core/asm/Reflect.java b/src/main/java/dan200/computercraft/core/asm/Reflect.java index 7b37a6eb8..7fc4b6ff5 100644 --- a/src/main/java/dan200/computercraft/core/asm/Reflect.java +++ b/src/main/java/dan200/computercraft/core/asm/Reflect.java @@ -52,7 +52,7 @@ final class Reflect Type underlying = root; while( true ) { - if( underlying instanceof Class ) return (Class) underlying; + if( underlying instanceof Class klass ) return klass; if( underlying instanceof ParameterizedType type ) { @@ -61,7 +61,7 @@ final class Reflect for( java.lang.reflect.Type arg : type.getActualTypeArguments() ) { if( arg instanceof WildcardType ) continue; - if( arg instanceof TypeVariable && ((TypeVariable) arg).getName().startsWith( "capture#" ) ) + if( arg instanceof TypeVariable var && var.getName().startsWith( "capture#" ) ) { continue; } diff --git a/src/main/java/dan200/computercraft/core/computer/ComputerExecutor.java b/src/main/java/dan200/computercraft/core/computer/ComputerExecutor.java index d5bbe84cf..5794be0f0 100644 --- a/src/main/java/dan200/computercraft/core/computer/ComputerExecutor.java +++ b/src/main/java/dan200/computercraft/core/computer/ComputerExecutor.java @@ -408,7 +408,7 @@ final class ComputerExecutor ) ); // Add the APIs. We unwrap them (yes, this is horrible) to get access to the underlying object. - for( ILuaAPI api : apis ) machine.addAPI( api instanceof ApiWrapper ? ((ApiWrapper) api).getDelegate() : api ); + for( ILuaAPI api : apis ) machine.addAPI( api instanceof ApiWrapper wrapper ? wrapper.getDelegate() : api ); // Start the machine running the bios resource MachineResult result = machine.loadBios( biosStream ); @@ -680,15 +680,7 @@ final class ComputerExecutor ERROR, } - private static final class Event + private record Event(String name, Object[] args) { - final String name; - final Object[] args; - - private Event( String name, Object[] args ) - { - this.name = name; - this.args = args; - } } } diff --git a/src/main/java/dan200/computercraft/core/filesystem/MountWrapper.java b/src/main/java/dan200/computercraft/core/filesystem/MountWrapper.java index ecb848b1a..fb1d84c8a 100644 --- a/src/main/java/dan200/computercraft/core/filesystem/MountWrapper.java +++ b/src/main/java/dan200/computercraft/core/filesystem/MountWrapper.java @@ -298,11 +298,11 @@ class MountWrapper if( ex.getFilename() != null ) return localExceptionOf( ex.getFilename(), ex.getMessage() ); } - if( e instanceof java.nio.file.FileSystemException ) + if( e instanceof java.nio.file.FileSystemException ex ) { // This error will contain the absolute path, leaking information about where MC is installed. We drop that, // just taking the reason. We assume that the error refers to the input path. - String message = ((java.nio.file.FileSystemException) e).getReason().trim(); + String message = ex.getReason().trim(); return localPath == null ? new FileSystemException( message ) : localExceptionOf( localPath, message ); } diff --git a/src/main/java/dan200/computercraft/core/lua/CobaltLuaMachine.java b/src/main/java/dan200/computercraft/core/lua/CobaltLuaMachine.java index a1b0d366b..c17e3cd41 100644 --- a/src/main/java/dan200/computercraft/core/lua/CobaltLuaMachine.java +++ b/src/main/java/dan200/computercraft/core/lua/CobaltLuaMachine.java @@ -63,12 +63,12 @@ public class CobaltLuaMachine implements ILuaMachine public CobaltLuaMachine( MachineEnvironment environment ) { - timeout = environment.timeout; - context = environment.context; + timeout = environment.timeout(); + context = environment.context(); debug = new TimeoutDebugHandler(); // Create an environment to run in - MetricsObserver metrics = environment.metrics; + MetricsObserver metrics = environment.metrics(); LuaState state = this.state = LuaState.builder() .resourceManipulator( new VoidResourceManipulator() ) .debug( debug ) @@ -108,7 +108,7 @@ public class CobaltLuaMachine implements ILuaMachine // Add version globals globals.rawset( "_VERSION", valueOf( "Lua 5.1" ) ); - globals.rawset( "_HOST", valueOf( environment.hostString ) ); + globals.rawset( "_HOST", valueOf( environment.hostString() ) ); globals.rawset( "_CC_DEFAULT_SETTINGS", valueOf( ComputerCraft.defaultComputerSettings ) ); if( ComputerCraft.disableLua51Features ) { @@ -241,8 +241,8 @@ public class CobaltLuaMachine implements ILuaMachine @Nullable private LuaTable wrapLuaObject( Object object ) { - String[] dynamicMethods = object instanceof IDynamicLuaObject - ? Objects.requireNonNull( ((IDynamicLuaObject) object).getMethodNames(), "Methods cannot be null" ) + String[] dynamicMethods = object instanceof IDynamicLuaObject dynamic + ? Objects.requireNonNull( dynamic.getMethodNames(), "Methods cannot be null" ) : LuaMethod.EMPTY_METHODS; LuaTable table = new LuaTable(); @@ -272,9 +272,9 @@ public class CobaltLuaMachine implements ILuaMachine private LuaValue toValue( @Nullable Object object, @Nullable Map values ) { if( object == null ) return Constants.NIL; - if( object instanceof Number ) return valueOf( ((Number) object).doubleValue() ); - if( object instanceof Boolean ) return valueOf( (Boolean) object ); - if( object instanceof String ) return valueOf( object.toString() ); + if( object instanceof Number num ) return valueOf( num.doubleValue() ); + if( object instanceof Boolean bool ) return valueOf( bool ); + if( object instanceof String str ) return valueOf( str ); if( object instanceof byte[] b ) { return valueOf( Arrays.copyOf( b, b.length ) ); @@ -303,12 +303,12 @@ public class CobaltLuaMachine implements ILuaMachine return wrapped; } - if( object instanceof Map ) + if( object instanceof Map map ) { LuaTable table = new LuaTable(); values.put( object, table ); - for( Map.Entry pair : ((Map) object).entrySet() ) + for( Map.Entry pair : map.entrySet() ) { LuaValue key = toValue( pair.getKey(), values ); LuaValue value = toValue( pair.getValue(), values ); diff --git a/src/main/java/dan200/computercraft/core/lua/MachineEnvironment.java b/src/main/java/dan200/computercraft/core/lua/MachineEnvironment.java index 2462c3886..dca489136 100644 --- a/src/main/java/dan200/computercraft/core/lua/MachineEnvironment.java +++ b/src/main/java/dan200/computercraft/core/lua/MachineEnvironment.java @@ -14,36 +14,13 @@ import dan200.computercraft.core.metrics.MetricsObserver; /** * Arguments used to construct a {@link ILuaMachine}. * + * @param context The Lua context to execute main-thread tasks with. + * @param metrics A sink to submit metrics to. You do not need to submit task timings here, it should only be for additional + * metrics such as {@link Metrics#COROUTINES_CREATED} + * @param timeout The current timeout state. This should be used by the machine to interrupt its execution. + * @param hostString A {@linkplain GlobalEnvironment#getHostString() host string} to identify the current environment. * @see ILuaMachine.Factory */ -public class MachineEnvironment +public record MachineEnvironment(ILuaContext context, MetricsObserver metrics, TimeoutState timeout, String hostString) { - /** - * The Lua context to execute main-thread tasks with. - */ - public final ILuaContext context; - - /** - * A sink to submit metrics to. You do not need to submit task timings here, it should only be for additional - * metrics such as {@link Metrics#COROUTINES_CREATED} - */ - public final MetricsObserver metrics; - - /** - * The current timeout state. This should be used by the machine to interrupt its execution. - */ - public final TimeoutState timeout; - - /** - * A {@linkplain GlobalEnvironment#getHostString() host string} to identify the current environment. - */ - public final String hostString; - - public MachineEnvironment( ILuaContext context, MetricsObserver metrics, TimeoutState timeout, String hostString ) - { - this.context = context; - this.metrics = metrics; - this.timeout = timeout; - this.hostString = hostString; - } } diff --git a/src/main/java/dan200/computercraft/data/PrettyJsonWriter.java b/src/main/java/dan200/computercraft/data/PrettyJsonWriter.java index 3a1863063..1393a276d 100644 --- a/src/main/java/dan200/computercraft/data/PrettyJsonWriter.java +++ b/src/main/java/dan200/computercraft/data/PrettyJsonWriter.java @@ -217,25 +217,12 @@ public class PrettyJsonWriter extends JsonWriter /** * A key/value pair inside a JSON object. + * + * @param key The escaped object key. + * @param value The object value. */ - private static final class Pair + private record Pair(String key, Object value) { - /** - * The escaped object key. - */ - final String key; - - /** - * The object value. - */ - final Object value; - - private Pair( String key, Object value ) - { - this.key = key; - this.value = value; - } - int width() { return key.length() + 2 + PrettyJsonWriter.width( value ); @@ -328,9 +315,9 @@ public class PrettyJsonWriter extends JsonWriter */ private static int width( Object object ) { - if( object instanceof String ) return ((String) object).length(); - if( object instanceof DocList ) return ((DocList) object).width; - if( object instanceof Pair ) return ((Pair) object).width(); + if( object instanceof String string ) return string.length(); + if( object instanceof DocList list ) return list.width; + if( object instanceof Pair pair ) return pair.width(); throw new IllegalArgumentException( "Not a valid document" ); } @@ -346,19 +333,18 @@ public class PrettyJsonWriter extends JsonWriter */ private static int write( Writer writer, Object object, int space, int indent ) throws IOException { - if( object instanceof String ) + if( object instanceof String str ) { - String str = (String) object; writer.write( str ); return space - str.length(); } - else if( object instanceof DocList ) + else if( object instanceof DocList list ) { - return ((DocList) object).write( writer, space, indent ); + return list.write( writer, space, indent ); } - else if( object instanceof Pair ) + else if( object instanceof Pair pair ) { - return ((Pair) object).write( writer, space, indent ); + return pair.write( writer, space, indent ); } else { diff --git a/src/main/java/dan200/computercraft/shared/Registry.java b/src/main/java/dan200/computercraft/shared/Registry.java index 29df1505e..d49a88732 100644 --- a/src/main/java/dan200/computercraft/shared/Registry.java +++ b/src/main/java/dan200/computercraft/shared/Registry.java @@ -376,7 +376,7 @@ public final class Registry // Register media providers ComputerCraftAPI.registerMediaProvider( stack -> { Item item = stack.getItem(); - if( item instanceof IMedia ) return (IMedia) item; + if( item instanceof IMedia media ) return media; if( item instanceof RecordItem ) return RecordMedia.INSTANCE; return null; } ); diff --git a/src/main/java/dan200/computercraft/shared/TurtlePermissions.java b/src/main/java/dan200/computercraft/shared/TurtlePermissions.java index b5ac38b2e..32493a173 100644 --- a/src/main/java/dan200/computercraft/shared/TurtlePermissions.java +++ b/src/main/java/dan200/computercraft/shared/TurtlePermissions.java @@ -16,7 +16,7 @@ public final class TurtlePermissions public static boolean isBlockEnterable( Level world, BlockPos pos, Player player ) { MinecraftServer server = world.getServer(); - return server == null || world.isClientSide || (world instanceof ServerLevel && !server.isUnderSpawnProtection( (ServerLevel) world, pos, player )); + return server == null || world.isClientSide || (world instanceof ServerLevel serverLevel && !server.isUnderSpawnProtection( serverLevel, pos, player )); } public static boolean isBlockEditable( Level world, BlockPos pos, Player player ) diff --git a/src/main/java/dan200/computercraft/shared/command/arguments/ComputersArgumentType.java b/src/main/java/dan200/computercraft/shared/command/arguments/ComputersArgumentType.java index 87f5dc1fa..adca49b81 100644 --- a/src/main/java/dan200/computercraft/shared/command/arguments/ComputersArgumentType.java +++ b/src/main/java/dan200/computercraft/shared/command/arguments/ComputersArgumentType.java @@ -24,7 +24,6 @@ import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import java.util.function.Predicate; -import java.util.stream.Collectors; import static dan200.computercraft.shared.command.CommandUtils.suggest; import static dan200.computercraft.shared.command.CommandUtils.suggestOnServer; @@ -163,12 +162,11 @@ public final class ComputersArgumentType implements ArgumentType predicate ) { - return s -> Collections.unmodifiableList( ServerContext.get( s.getServer() ).registry() + return s -> ServerContext.get( s.getServer() ).registry() .getComputers() .stream() .filter( predicate ) - .collect( Collectors.toList() ) - ); + .toList(); } public static class Serializer implements ArgumentSerializer diff --git a/src/main/java/dan200/computercraft/shared/command/arguments/RepeatArgumentType.java b/src/main/java/dan200/computercraft/shared/command/arguments/RepeatArgumentType.java index 7c94c4317..a651be169 100644 --- a/src/main/java/dan200/computercraft/shared/command/arguments/RepeatArgumentType.java +++ b/src/main/java/dan200/computercraft/shared/command/arguments/RepeatArgumentType.java @@ -158,7 +158,7 @@ public final class RepeatArgumentType implements ArgumentType> private static Component getMessage( RepeatArgumentType arg ) { Message message = arg.some.create().getRawMessage(); - if( message instanceof Component ) return (Component) message; + if( message instanceof Component component ) return component; return new TextComponent( message.getString() ); } } diff --git a/src/main/java/dan200/computercraft/shared/command/arguments/TrackingFieldArgumentType.java b/src/main/java/dan200/computercraft/shared/command/arguments/TrackingFieldArgumentType.java index b683703fb..16bdfa03e 100644 --- a/src/main/java/dan200/computercraft/shared/command/arguments/TrackingFieldArgumentType.java +++ b/src/main/java/dan200/computercraft/shared/command/arguments/TrackingFieldArgumentType.java @@ -8,8 +8,6 @@ package dan200.computercraft.shared.command.arguments; import dan200.computercraft.shared.command.Exceptions; import dan200.computercraft.shared.computer.metrics.basic.AggregatedMetric; -import java.util.stream.Collectors; - public final class TrackingFieldArgumentType extends ChoiceArgumentType { private static final TrackingFieldArgumentType INSTANCE = new TrackingFieldArgumentType(); @@ -17,7 +15,7 @@ public final class TrackingFieldArgumentType extends ChoiceArgumentType aggregatedMetrics() { Metrics.init(); diff --git a/src/main/java/dan200/computercraft/shared/computer/recipe/ComputerFamilyRecipe.java b/src/main/java/dan200/computercraft/shared/computer/recipe/ComputerFamilyRecipe.java index 5b6d36b43..2161259ec 100644 --- a/src/main/java/dan200/computercraft/shared/computer/recipe/ComputerFamilyRecipe.java +++ b/src/main/java/dan200/computercraft/shared/computer/recipe/ComputerFamilyRecipe.java @@ -47,7 +47,7 @@ public abstract class ComputerFamilyRecipe extends ComputerConvertRecipe RecipeUtil.ShapedTemplate template = RecipeUtil.getTemplate( json ); ItemStack result = itemStackFromJson( GsonHelper.getAsJsonObject( json, "result" ) ); - return create( identifier, group, template.width, template.height, template.ingredients, result, family ); + return create( identifier, group, template.width(), template.height(), template.ingredients(), result, family ); } @Nonnull diff --git a/src/main/java/dan200/computercraft/shared/computer/upload/FileSlice.java b/src/main/java/dan200/computercraft/shared/computer/upload/FileSlice.java index 4451f2922..aaa014bc4 100644 --- a/src/main/java/dan200/computercraft/shared/computer/upload/FileSlice.java +++ b/src/main/java/dan200/computercraft/shared/computer/upload/FileSlice.java @@ -10,34 +10,8 @@ import dan200.computercraft.ComputerCraft; import java.nio.ByteBuffer; import java.util.List; -public class FileSlice +public record FileSlice(int fileId, int offset, ByteBuffer bytes) { - private final int fileId; - private final int offset; - private final ByteBuffer bytes; - - public FileSlice( int fileId, int offset, ByteBuffer bytes ) - { - this.fileId = fileId; - this.offset = offset; - this.bytes = bytes; - } - - public int getFileId() - { - return fileId; - } - - public int getOffset() - { - return offset; - } - - public ByteBuffer getBytes() - { - return bytes; - } - public void apply( List files ) { if( fileId < 0 || fileId >= files.size() ) diff --git a/src/main/java/dan200/computercraft/shared/integration/UpgradeRecipeGenerator.java b/src/main/java/dan200/computercraft/shared/integration/UpgradeRecipeGenerator.java index 0bdc96337..2c49721b1 100644 --- a/src/main/java/dan200/computercraft/shared/integration/UpgradeRecipeGenerator.java +++ b/src/main/java/dan200/computercraft/shared/integration/UpgradeRecipeGenerator.java @@ -120,10 +120,8 @@ public class UpgradeRecipeGenerator { setupCache(); - if( stack.getItem() instanceof ItemTurtle ) + if( stack.getItem() instanceof ItemTurtle item ) { - ItemTurtle item = (ItemTurtle) stack.getItem(); - // Suggest possible upgrades which can be applied to this turtle ITurtleUpgrade left = item.getUpgrade( stack, TurtleSide.LEFT ); ITurtleUpgrade right = item.getUpgrade( stack, TurtleSide.RIGHT ); @@ -206,9 +204,8 @@ public class UpgradeRecipeGenerator public List findRecipesWithOutput( ItemStack stack ) { // Find which upgrade this item currently has, and so how we could build it. - if( stack.getItem() instanceof ItemTurtle ) + if( stack.getItem() instanceof ItemTurtle item ) { - ItemTurtle item = (ItemTurtle) stack.getItem(); List recipes = new ArrayList<>( 0 ); ITurtleUpgrade left = item.getUpgrade( stack, TurtleSide.LEFT ); diff --git a/src/main/java/dan200/computercraft/shared/network/client/ComputerTerminalClientMessage.java b/src/main/java/dan200/computercraft/shared/network/client/ComputerTerminalClientMessage.java index f4d257229..bdcedb696 100644 --- a/src/main/java/dan200/computercraft/shared/network/client/ComputerTerminalClientMessage.java +++ b/src/main/java/dan200/computercraft/shared/network/client/ComputerTerminalClientMessage.java @@ -46,9 +46,9 @@ public class ComputerTerminalClientMessage implements NetworkMessage public void handle( NetworkEvent.Context context ) { Player player = Minecraft.getInstance().player; - if( player != null && player.containerMenu.containerId == containerId && player.containerMenu instanceof ComputerMenu ) + if( player != null && player.containerMenu.containerId == containerId && player.containerMenu instanceof ComputerMenu menu ) { - ((ComputerMenu) player.containerMenu).updateTerminal( terminal ); + menu.updateTerminal( terminal ); } } } diff --git a/src/main/java/dan200/computercraft/shared/network/server/UploadFileMessage.java b/src/main/java/dan200/computercraft/shared/network/server/UploadFileMessage.java index 6e55a13db..aadee4596 100644 --- a/src/main/java/dan200/computercraft/shared/network/server/UploadFileMessage.java +++ b/src/main/java/dan200/computercraft/shared/network/server/UploadFileMessage.java @@ -120,10 +120,10 @@ public class UploadFileMessage extends ComputerServerMessage buf.writeVarInt( slices.size() ); for( FileSlice slice : slices ) { - buf.writeByte( slice.getFileId() ); - buf.writeVarInt( slice.getOffset() ); + buf.writeByte( slice.fileId() ); + buf.writeVarInt( slice.offset() ); - ByteBuffer bytes = slice.getBytes().duplicate(); + ByteBuffer bytes = slice.bytes().duplicate(); buf.writeShort( bytes.remaining() ); buf.writeBytes( bytes ); } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/commandblock/CommandBlockPeripheral.java b/src/main/java/dan200/computercraft/shared/peripheral/commandblock/CommandBlockPeripheral.java index f5158c82f..cba968edc 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/commandblock/CommandBlockPeripheral.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/commandblock/CommandBlockPeripheral.java @@ -128,9 +128,9 @@ public class CommandBlockPeripheral implements IPeripheral, ICapabilityProvider public static void onCapability( AttachCapabilitiesEvent event ) { BlockEntity tile = event.getObject(); - if( ComputerCraft.enableCommandBlock && tile instanceof CommandBlockEntity ) + if( ComputerCraft.enableCommandBlock && tile instanceof CommandBlockEntity commandBlock ) { - CommandBlockPeripheral peripheral = new CommandBlockPeripheral( (CommandBlockEntity) tile ); + CommandBlockPeripheral peripheral = new CommandBlockPeripheral( commandBlock ); event.addCapability( CAP_ID, peripheral ); event.addListener( peripheral::invalidate ); } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/generic/data/ItemData.java b/src/main/java/dan200/computercraft/shared/peripheral/generic/data/ItemData.java index b9d5fee69..3015a17d3 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/generic/data/ItemData.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/generic/data/ItemData.java @@ -19,7 +19,6 @@ import net.minecraft.world.item.enchantment.EnchantmentHelper; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.*; -import java.util.stream.Collectors; /** * Data providers for items. @@ -71,7 +70,7 @@ public class ItemData .map( ItemData::parseTextComponent ) .filter( Objects::nonNull ) .map( Component::getString ) - .collect( Collectors.toList() ) ); + .toList() ); } } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/monitor/MonitorWatcher.java b/src/main/java/dan200/computercraft/shared/peripheral/monitor/MonitorWatcher.java index fc9733697..9d920a58b 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/monitor/MonitorWatcher.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/monitor/MonitorWatcher.java @@ -126,15 +126,6 @@ public final class MonitorWatcher return state; } - private static final class PlayerUpdate - { - final ServerPlayer player; - final TileMonitor monitor; - - private PlayerUpdate( ServerPlayer player, TileMonitor monitor ) - { - this.player = player; - this.monitor = monitor; - } - } + private record PlayerUpdate(ServerPlayer player, TileMonitor monitor) + {} } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/monitor/TileMonitor.java b/src/main/java/dan200/computercraft/shared/peripheral/monitor/TileMonitor.java index 9c782c927..3743bc410 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/monitor/TileMonitor.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/monitor/TileMonitor.java @@ -241,9 +241,9 @@ public class TileMonitor extends TileGeneric // Otherwise fetch the origin and attempt to get its monitor // Note this may load chunks, but we don't really have a choice here. BlockEntity te = level.getBlockEntity( toWorldPos( 0, 0 ) ); - if( !(te instanceof TileMonitor) ) return null; + if( !(te instanceof TileMonitor monitor) ) return null; - return serverMonitor = ((TileMonitor) te).createServerMonitor(); + return serverMonitor = monitor.createServerMonitor(); } } @@ -253,9 +253,9 @@ public class TileMonitor extends TileGeneric if( clientMonitor != null ) return clientMonitor; BlockEntity te = level.getBlockEntity( toWorldPos( 0, 0 ) ); - if( !(te instanceof TileMonitor) ) return null; + if( !(te instanceof TileMonitor monitor) ) return null; - return clientMonitor = ((TileMonitor) te).clientMonitor; + return clientMonitor = monitor.clientMonitor; } // Networking stuff @@ -578,7 +578,7 @@ public class TileMonitor extends TileGeneric .of( xPos, yPos, zPos, getDirection(), getOrientation() ) .add( xIndex, height - yIndex - 1 ); - if( pair.x > width - RENDER_BORDER || pair.y > height - RENDER_BORDER || pair.x < RENDER_BORDER || pair.y < RENDER_BORDER ) + if( pair.x() > width - RENDER_BORDER || pair.y() > height - RENDER_BORDER || pair.x() < RENDER_BORDER || pair.y() < RENDER_BORDER ) { return; } @@ -592,8 +592,8 @@ public class TileMonitor extends TileGeneric double xCharWidth = (width - (RENDER_BORDER + RENDER_MARGIN) * 2.0) / originTerminal.getWidth(); double yCharHeight = (height - (RENDER_BORDER + RENDER_MARGIN) * 2.0) / originTerminal.getHeight(); - int xCharPos = (int) Math.min( originTerminal.getWidth(), Math.max( (pair.x - RENDER_BORDER - RENDER_MARGIN) / xCharWidth + 1.0, 1.0 ) ); - int yCharPos = (int) Math.min( originTerminal.getHeight(), Math.max( (pair.y - RENDER_BORDER - RENDER_MARGIN) / yCharHeight + 1.0, 1.0 ) ); + int xCharPos = (int) Math.min( originTerminal.getWidth(), Math.max( (pair.x() - RENDER_BORDER - RENDER_MARGIN) / xCharWidth + 1.0, 1.0 ) ); + int yCharPos = (int) Math.min( originTerminal.getHeight(), Math.max( (pair.y() - RENDER_BORDER - RENDER_MARGIN) / yCharHeight + 1.0, 1.0 ) ); eachComputer( c -> c.queueEvent( "monitor_touch", c.getAttachmentName(), xCharPos, yCharPos ) ); } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/monitor/XYPair.java b/src/main/java/dan200/computercraft/shared/peripheral/monitor/XYPair.java index 7e08ced69..5e716e000 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/monitor/XYPair.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/monitor/XYPair.java @@ -7,17 +7,8 @@ package dan200.computercraft.shared.peripheral.monitor; import net.minecraft.core.Direction; -public class XYPair +public record XYPair(float x, float y) { - public final float x; - public final float y; - - public XYPair( float x, float y ) - { - this.x = x; - this.y = y; - } - public XYPair add( float x, float y ) { return new XYPair( this.x + x, this.y + y ); diff --git a/src/main/java/dan200/computercraft/shared/turtle/core/TurtleBrain.java b/src/main/java/dan200/computercraft/shared/turtle/core/TurtleBrain.java index 7053ab67f..bdef60b58 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/core/TurtleBrain.java +++ b/src/main/java/dan200/computercraft/shared/turtle/core/TurtleBrain.java @@ -786,13 +786,13 @@ public class TurtleBrain implements ITurtleAccess // Execute the command long start = System.nanoTime(); - TurtleCommandResult result = nextCommand.command.execute( this ); + TurtleCommandResult result = nextCommand.command().execute( this ); long end = System.nanoTime(); // Dispatch the callback if( computer == null ) return; computer.getComputer().getMainThreadMonitor().trackWork( end - start, TimeUnit.NANOSECONDS ); - int callbackID = nextCommand.callbackID; + int callbackID = nextCommand.callbackID(); if( callbackID < 0 ) return; if( result != null && result.isSuccess() ) diff --git a/src/main/java/dan200/computercraft/shared/turtle/core/TurtleCommandQueueEntry.java b/src/main/java/dan200/computercraft/shared/turtle/core/TurtleCommandQueueEntry.java index 12614f9a5..f8f8dc3e5 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/core/TurtleCommandQueueEntry.java +++ b/src/main/java/dan200/computercraft/shared/turtle/core/TurtleCommandQueueEntry.java @@ -7,14 +7,6 @@ package dan200.computercraft.shared.turtle.core; import dan200.computercraft.api.turtle.ITurtleCommand; -public class TurtleCommandQueueEntry +public record TurtleCommandQueueEntry(int callbackID, ITurtleCommand command) { - public final int callbackID; - public final ITurtleCommand command; - - public TurtleCommandQueueEntry( int callbackID, ITurtleCommand command ) - { - this.callbackID = callbackID; - this.command = command; - } } diff --git a/src/main/java/dan200/computercraft/shared/util/RecipeUtil.java b/src/main/java/dan200/computercraft/shared/util/RecipeUtil.java index c456fd63a..c6c17039a 100644 --- a/src/main/java/dan200/computercraft/shared/util/RecipeUtil.java +++ b/src/main/java/dan200/computercraft/shared/util/RecipeUtil.java @@ -25,18 +25,8 @@ public final class RecipeUtil { private RecipeUtil() {} - public static class ShapedTemplate + public record ShapedTemplate(int width, int height, NonNullList ingredients) { - public final int width; - public final int height; - public final NonNullList ingredients; - - public ShapedTemplate( int width, int height, NonNullList ingredients ) - { - this.width = width; - this.height = height; - this.ingredients = ingredients; - } } public static ShapedTemplate getTemplate( JsonObject json ) diff --git a/src/test/java/dan200/computercraft/core/computer/FakeComputerManager.java b/src/test/java/dan200/computercraft/core/computer/FakeComputerManager.java index e2a9e7fb6..2db1052bc 100644 --- a/src/test/java/dan200/computercraft/core/computer/FakeComputerManager.java +++ b/src/test/java/dan200/computercraft/core/computer/FakeComputerManager.java @@ -38,7 +38,7 @@ public class FakeComputerManager implements AutoCloseable new BasicEnvironment(), new ComputerThread( 1 ), new FakeMainThreadScheduler(), - args -> new DummyLuaMachine( args.timeout ) + args -> new DummyLuaMachine( args.timeout() ) ); private final Lock errorLock = new ReentrantLock();