1
0
mirror of https://github.com/SquidDev-CC/CC-Tweaked synced 2024-12-14 20:20:30 +00:00

Some Java-17ification

I might just stick on 1.18 for the rest of these refactors. Porting
across the mojmap boundary is painful.
This commit is contained in:
Jonathan Coates 2022-10-25 22:58:31 +01:00
parent be827a21db
commit 158850be09
No known key found for this signature in database
GPG Key ID: B9E431FF07C98D06
37 changed files with 106 additions and 274 deletions

View File

@ -11,20 +11,14 @@ import java.time.Instant;
/** /**
* A simple version of {@link BasicFileAttributes}, which provides what information a {@link IMount} already exposes. * 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 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 @Override
public FileTime lastModifiedTime() public FileTime lastModifiedTime()
{ {
@ -49,12 +43,6 @@ final class FileAttributes implements BasicFileAttributes
return !isDirectory; return !isDirectory;
} }
@Override
public boolean isDirectory()
{
return isDirectory;
}
@Override @Override
public boolean isSymbolicLink() public boolean isSymbolicLink()
{ {
@ -67,12 +55,6 @@ final class FileAttributes implements BasicFileAttributes
return false; return false;
} }
@Override
public long size()
{
return size;
}
@Override @Override
public Object fileKey() public Object fileKey()
{ {

View File

@ -69,8 +69,8 @@ public interface IArguments
default double getDouble( int index ) throws LuaException default double getDouble( int index ) throws LuaException
{ {
Object value = get( index ); Object value = get( index );
if( !(value instanceof Number) ) throw LuaValues.badArgumentOf( index, "number", value ); if( !(value instanceof Number number) ) throw LuaValues.badArgumentOf( index, "number", value );
return ((Number) value).doubleValue(); return number.doubleValue();
} }
/** /**
@ -95,8 +95,8 @@ public interface IArguments
default long getLong( int index ) throws LuaException default long getLong( int index ) throws LuaException
{ {
Object value = get( index ); Object value = get( index );
if( !(value instanceof Number) ) throw LuaValues.badArgumentOf( index, "number", value ); if( !(value instanceof Number number) ) throw LuaValues.badArgumentOf( index, "number", value );
return LuaValues.checkFiniteNum( index, (Number) value ).longValue(); return LuaValues.checkFiniteNum( index, number ).longValue();
} }
/** /**
@ -121,8 +121,8 @@ public interface IArguments
default boolean getBoolean( int index ) throws LuaException default boolean getBoolean( int index ) throws LuaException
{ {
Object value = get( index ); Object value = get( index );
if( !(value instanceof Boolean) ) throw LuaValues.badArgumentOf( index, "boolean", value ); if( !(value instanceof Boolean bool) ) throw LuaValues.badArgumentOf( index, "boolean", value );
return (Boolean) value; return bool;
} }
/** /**
@ -136,8 +136,8 @@ public interface IArguments
default String getString( int index ) throws LuaException default String getString( int index ) throws LuaException
{ {
Object value = get( index ); Object value = get( index );
if( !(value instanceof String) ) throw LuaValues.badArgumentOf( index, "string", value ); if( !(value instanceof String string) ) throw LuaValues.badArgumentOf( index, "string", value );
return (String) value; return string;
} }
/** /**
@ -213,8 +213,8 @@ public interface IArguments
{ {
Object value = get( index ); Object value = get( index );
if( value == null ) return Optional.empty(); if( value == null ) return Optional.empty();
if( !(value instanceof Number) ) throw LuaValues.badArgumentOf( index, "number", value ); if( !(value instanceof Number number) ) throw LuaValues.badArgumentOf( index, "number", value );
return Optional.of( ((Number) value).doubleValue() ); return Optional.of( number.doubleValue() );
} }
/** /**
@ -241,8 +241,8 @@ public interface IArguments
{ {
Object value = get( index ); Object value = get( index );
if( value == null ) return Optional.empty(); if( value == null ) return Optional.empty();
if( !(value instanceof Number) ) throw LuaValues.badArgumentOf( index, "number", value ); if( !(value instanceof Number number) ) throw LuaValues.badArgumentOf( index, "number", value );
return Optional.of( LuaValues.checkFiniteNum( index, (Number) value ).longValue() ); return Optional.of( LuaValues.checkFiniteNum( index, number ).longValue() );
} }
/** /**
@ -270,8 +270,8 @@ public interface IArguments
{ {
Object value = get( index ); Object value = get( index );
if( value == null ) return Optional.empty(); if( value == null ) return Optional.empty();
if( !(value instanceof Boolean) ) throw LuaValues.badArgumentOf( index, "boolean", value ); if( !(value instanceof Boolean bool) ) throw LuaValues.badArgumentOf( index, "boolean", value );
return Optional.of( (Boolean) value ); return Optional.of( bool );
} }
/** /**
@ -285,8 +285,8 @@ public interface IArguments
{ {
Object value = get( index ); Object value = get( index );
if( value == null ) return Optional.empty(); if( value == null ) return Optional.empty();
if( !(value instanceof String) ) throw LuaValues.badArgumentOf( index, "string", value ); if( !(value instanceof String string) ) throw LuaValues.badArgumentOf( index, "string", value );
return Optional.of( (String) value ); return Optional.of( string );
} }
/** /**

View File

@ -35,9 +35,8 @@ public interface LuaTable<K, V> extends Map<K, V>
default long getLong( int index ) throws LuaException default long getLong( int index ) throws LuaException
{ {
Object value = get( (double) index ); 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(); double asDouble = number.doubleValue();
if( !Double.isFinite( asDouble ) ) throw badTableItem( index, "number", getNumericType( asDouble ) ); if( !Double.isFinite( asDouble ) ) throw badTableItem( index, "number", getNumericType( asDouble ) );
return number.longValue(); return number.longValue();
@ -53,9 +52,8 @@ public interface LuaTable<K, V> extends Map<K, V>
default long getLong( String key ) throws LuaException default long getLong( String key ) throws LuaException
{ {
Object value = get( key ); 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(); double asDouble = number.doubleValue();
if( !Double.isFinite( asDouble ) ) throw badField( key, "number", getNumericType( asDouble ) ); if( !Double.isFinite( asDouble ) ) throw badField( key, "number", getNumericType( asDouble ) );
return number.longValue(); return number.longValue();

View File

@ -56,7 +56,7 @@ public final class OptionScreen extends Screen
public static Screen unwrap( Screen screen ) public static Screen unwrap( Screen screen )
{ {
return screen instanceof OptionScreen ? ((OptionScreen) screen).getOriginalScreen() : screen; return screen instanceof OptionScreen option ? option.getOriginalScreen() : screen;
} }
@Override @Override

View File

@ -57,7 +57,7 @@ public final class ClientPocketComputers
@Nonnull @Nonnull
public static PocketComputerData get( ItemStack stack ) 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 ); return get( ItemPocketComputer.getInstanceID( stack ), family != ComputerFamily.NORMAL );
} }
} }

View File

@ -39,17 +39,8 @@ public class OSAPI implements ILuaAPI
private int nextAlarmToken = 0; private int nextAlarmToken = 0;
private static class Alarm implements Comparable<Alarm> private record Alarm(double time, int day) implements Comparable<Alarm>
{ {
final double time;
final int day;
Alarm( double time, int day )
{
this.time = time;
this.day = day;
}
@Override @Override
public int compareTo( @Nonnull Alarm o ) public int compareTo( @Nonnull Alarm o )
{ {

View File

@ -85,8 +85,8 @@ public final class AddressRule
int port = socketAddress.getPort(); int port = socketAddress.getPort();
InetAddress address = socketAddress.getAddress(); InetAddress address = socketAddress.getAddress();
Inet4Address ipv4Address = address instanceof Inet6Address && InetAddresses.is6to4Address( (Inet6Address) address ) Inet4Address ipv4Address = address instanceof Inet6Address inet6 && InetAddresses.is6to4Address( inet6 )
? InetAddresses.get6to4IPv4Address( (Inet6Address) address ) : null; ? InetAddresses.get6to4IPv4Address( inet6 ) : null;
for( AddressRule rule : rules ) for( AddressRule rule : rules )
{ {

View File

@ -61,9 +61,9 @@ public class WebsocketHandler extends SimpleChannelInboundHandler<Object>
} }
WebSocketFrame frame = (WebSocketFrame) msg; 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().observe( Metrics.WEBSOCKET_INCOMING, data.length() );
websocket.environment().queueEvent( MESSAGE_EVENT, websocket.address(), data, false ); websocket.environment().queueEvent( MESSAGE_EVENT, websocket.address(), data, false );

View File

@ -19,7 +19,6 @@ import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
/** /**
@ -51,7 +50,7 @@ public class GenericMethod
static List<GenericMethod> all() static List<GenericMethod> all()
{ {
if( cache != null ) return cache; 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 ) public static synchronized void register( @Nonnull GenericSource source )
@ -69,7 +68,7 @@ public class GenericMethod
private static Stream<GenericMethod> getMethods( GenericSource source ) private static Stream<GenericMethod> getMethods( GenericSource source )
{ {
Class<?> klass = source.getClass(); 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() ) return Arrays.stream( klass.getDeclaredMethods() )
.map( method -> { .map( method -> {

View File

@ -21,9 +21,9 @@ public interface ObjectSource
{ {
for( NamedMethod<T> method : generator.getMethods( object.getClass() ) ) accept.accept( object, method ); for( NamedMethod<T> 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<T> method : generator.getMethods( extra.getClass() ) ) accept.accept( extra, method ); for( NamedMethod<T> method : generator.getMethods( extra.getClass() ) ) accept.accept( extra, method );
} }

View File

@ -52,7 +52,7 @@ final class Reflect
Type underlying = root; Type underlying = root;
while( true ) while( true )
{ {
if( underlying instanceof Class<?> ) return (Class<?>) underlying; if( underlying instanceof Class<?> klass ) return klass;
if( underlying instanceof ParameterizedType type ) if( underlying instanceof ParameterizedType type )
{ {
@ -61,7 +61,7 @@ final class Reflect
for( java.lang.reflect.Type arg : type.getActualTypeArguments() ) for( java.lang.reflect.Type arg : type.getActualTypeArguments() )
{ {
if( arg instanceof WildcardType ) continue; if( arg instanceof WildcardType ) continue;
if( arg instanceof TypeVariable && ((TypeVariable<?>) arg).getName().startsWith( "capture#" ) ) if( arg instanceof TypeVariable<?> var && var.getName().startsWith( "capture#" ) )
{ {
continue; continue;
} }

View File

@ -408,7 +408,7 @@ final class ComputerExecutor
) ); ) );
// Add the APIs. We unwrap them (yes, this is horrible) to get access to the underlying object. // 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 // Start the machine running the bios resource
MachineResult result = machine.loadBios( biosStream ); MachineResult result = machine.loadBios( biosStream );
@ -680,15 +680,7 @@ final class ComputerExecutor
ERROR, 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;
}
} }
} }

View File

@ -298,11 +298,11 @@ class MountWrapper
if( ex.getFilename() != null ) return localExceptionOf( ex.getFilename(), ex.getMessage() ); 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, // 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. // 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 ); return localPath == null ? new FileSystemException( message ) : localExceptionOf( localPath, message );
} }

View File

@ -63,12 +63,12 @@ public class CobaltLuaMachine implements ILuaMachine
public CobaltLuaMachine( MachineEnvironment environment ) public CobaltLuaMachine( MachineEnvironment environment )
{ {
timeout = environment.timeout; timeout = environment.timeout();
context = environment.context; context = environment.context();
debug = new TimeoutDebugHandler(); debug = new TimeoutDebugHandler();
// Create an environment to run in // Create an environment to run in
MetricsObserver metrics = environment.metrics; MetricsObserver metrics = environment.metrics();
LuaState state = this.state = LuaState.builder() LuaState state = this.state = LuaState.builder()
.resourceManipulator( new VoidResourceManipulator() ) .resourceManipulator( new VoidResourceManipulator() )
.debug( debug ) .debug( debug )
@ -108,7 +108,7 @@ public class CobaltLuaMachine implements ILuaMachine
// Add version globals // Add version globals
globals.rawset( "_VERSION", valueOf( "Lua 5.1" ) ); 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 ) ); globals.rawset( "_CC_DEFAULT_SETTINGS", valueOf( ComputerCraft.defaultComputerSettings ) );
if( ComputerCraft.disableLua51Features ) if( ComputerCraft.disableLua51Features )
{ {
@ -241,8 +241,8 @@ public class CobaltLuaMachine implements ILuaMachine
@Nullable @Nullable
private LuaTable wrapLuaObject( Object object ) private LuaTable wrapLuaObject( Object object )
{ {
String[] dynamicMethods = object instanceof IDynamicLuaObject String[] dynamicMethods = object instanceof IDynamicLuaObject dynamic
? Objects.requireNonNull( ((IDynamicLuaObject) object).getMethodNames(), "Methods cannot be null" ) ? Objects.requireNonNull( dynamic.getMethodNames(), "Methods cannot be null" )
: LuaMethod.EMPTY_METHODS; : LuaMethod.EMPTY_METHODS;
LuaTable table = new LuaTable(); LuaTable table = new LuaTable();
@ -272,9 +272,9 @@ public class CobaltLuaMachine implements ILuaMachine
private LuaValue toValue( @Nullable Object object, @Nullable Map<Object, LuaValue> values ) private LuaValue toValue( @Nullable Object object, @Nullable Map<Object, LuaValue> values )
{ {
if( object == null ) return Constants.NIL; if( object == null ) return Constants.NIL;
if( object instanceof Number ) return valueOf( ((Number) object).doubleValue() ); if( object instanceof Number num ) return valueOf( num.doubleValue() );
if( object instanceof Boolean ) return valueOf( (Boolean) object ); if( object instanceof Boolean bool ) return valueOf( bool );
if( object instanceof String ) return valueOf( object.toString() ); if( object instanceof String str ) return valueOf( str );
if( object instanceof byte[] b ) if( object instanceof byte[] b )
{ {
return valueOf( Arrays.copyOf( b, b.length ) ); return valueOf( Arrays.copyOf( b, b.length ) );
@ -303,12 +303,12 @@ public class CobaltLuaMachine implements ILuaMachine
return wrapped; return wrapped;
} }
if( object instanceof Map ) if( object instanceof Map<?, ?> map )
{ {
LuaTable table = new LuaTable(); LuaTable table = new LuaTable();
values.put( object, table ); values.put( object, table );
for( Map.Entry<?, ?> pair : ((Map<?, ?>) object).entrySet() ) for( Map.Entry<?, ?> pair : map.entrySet() )
{ {
LuaValue key = toValue( pair.getKey(), values ); LuaValue key = toValue( pair.getKey(), values );
LuaValue value = toValue( pair.getValue(), values ); LuaValue value = toValue( pair.getValue(), values );

View File

@ -14,36 +14,13 @@ import dan200.computercraft.core.metrics.MetricsObserver;
/** /**
* Arguments used to construct a {@link ILuaMachine}. * 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 * @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;
}
} }

View File

@ -217,25 +217,12 @@ public class PrettyJsonWriter extends JsonWriter
/** /**
* A key/value pair inside a JSON object. * 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() int width()
{ {
return key.length() + 2 + PrettyJsonWriter.width( value ); return key.length() + 2 + PrettyJsonWriter.width( value );
@ -328,9 +315,9 @@ public class PrettyJsonWriter extends JsonWriter
*/ */
private static int width( Object object ) private static int width( Object object )
{ {
if( object instanceof String ) return ((String) object).length(); if( object instanceof String string ) return string.length();
if( object instanceof DocList ) return ((DocList) object).width; if( object instanceof DocList list ) return list.width;
if( object instanceof Pair ) return ((Pair) object).width(); if( object instanceof Pair pair ) return pair.width();
throw new IllegalArgumentException( "Not a valid document" ); 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 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 ); writer.write( str );
return space - str.length(); 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 else
{ {

View File

@ -376,7 +376,7 @@ public final class Registry
// Register media providers // Register media providers
ComputerCraftAPI.registerMediaProvider( stack -> { ComputerCraftAPI.registerMediaProvider( stack -> {
Item item = stack.getItem(); 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; if( item instanceof RecordItem ) return RecordMedia.INSTANCE;
return null; return null;
} ); } );

View File

@ -16,7 +16,7 @@ public final class TurtlePermissions
public static boolean isBlockEnterable( Level world, BlockPos pos, Player player ) public static boolean isBlockEnterable( Level world, BlockPos pos, Player player )
{ {
MinecraftServer server = world.getServer(); 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 ) public static boolean isBlockEditable( Level world, BlockPos pos, Player player )

View File

@ -24,7 +24,6 @@ import java.util.*;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.function.Function; import java.util.function.Function;
import java.util.function.Predicate; 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.suggest;
import static dan200.computercraft.shared.command.CommandUtils.suggestOnServer; import static dan200.computercraft.shared.command.CommandUtils.suggestOnServer;
@ -163,12 +162,11 @@ public final class ComputersArgumentType implements ArgumentType<ComputersArgume
private static ComputersSupplier getComputers( Predicate<ServerComputer> predicate ) private static ComputersSupplier getComputers( Predicate<ServerComputer> predicate )
{ {
return s -> Collections.unmodifiableList( ServerContext.get( s.getServer() ).registry() return s -> ServerContext.get( s.getServer() ).registry()
.getComputers() .getComputers()
.stream() .stream()
.filter( predicate ) .filter( predicate )
.collect( Collectors.toList() ) .toList();
);
} }
public static class Serializer implements ArgumentSerializer<ComputersArgumentType> public static class Serializer implements ArgumentSerializer<ComputersArgumentType>

View File

@ -158,7 +158,7 @@ public final class RepeatArgumentType<T, U> implements ArgumentType<List<T>>
private static Component getMessage( RepeatArgumentType<?, ?> arg ) private static Component getMessage( RepeatArgumentType<?, ?> arg )
{ {
Message message = arg.some.create().getRawMessage(); 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() ); return new TextComponent( message.getString() );
} }
} }

View File

@ -8,8 +8,6 @@ package dan200.computercraft.shared.command.arguments;
import dan200.computercraft.shared.command.Exceptions; import dan200.computercraft.shared.command.Exceptions;
import dan200.computercraft.shared.computer.metrics.basic.AggregatedMetric; import dan200.computercraft.shared.computer.metrics.basic.AggregatedMetric;
import java.util.stream.Collectors;
public final class TrackingFieldArgumentType extends ChoiceArgumentType<AggregatedMetric> public final class TrackingFieldArgumentType extends ChoiceArgumentType<AggregatedMetric>
{ {
private static final TrackingFieldArgumentType INSTANCE = new TrackingFieldArgumentType(); private static final TrackingFieldArgumentType INSTANCE = new TrackingFieldArgumentType();
@ -17,7 +15,7 @@ public final class TrackingFieldArgumentType extends ChoiceArgumentType<Aggregat
private TrackingFieldArgumentType() private TrackingFieldArgumentType()
{ {
super( super(
AggregatedMetric.aggregatedMetrics().collect( Collectors.toList() ), AggregatedMetric.aggregatedMetrics().toList(),
AggregatedMetric::name, AggregatedMetric::displayName, Exceptions.TRACKING_FIELD_ARG_NONE AggregatedMetric::name, AggregatedMetric::displayName, Exceptions.TRACKING_FIELD_ARG_NONE
); );
} }

View File

@ -183,15 +183,8 @@ public final class ServerContext
return metrics; return metrics;
} }
private static final class Environment implements GlobalEnvironment private record Environment(MinecraftServer server) implements GlobalEnvironment
{ {
private final MinecraftServer server;
Environment( MinecraftServer server )
{
this.server = server;
}
@Override @Override
public IMount createResourceMount( String domain, String subPath ) public IMount createResourceMount( String domain, String subPath )
{ {

View File

@ -15,30 +15,14 @@ import java.util.stream.Stream;
/** /**
* An aggregate of a specific metric. * An aggregate of a specific metric.
*
* @param metric The metric we're aggregating.
* @param aggregate The aggregate to use.
*/ */
public class AggregatedMetric public record AggregatedMetric(Metric metric, Aggregate aggregate)
{ {
private static final String TRANSLATION_PREFIX = "tracking_field.computercraft."; private static final String TRANSLATION_PREFIX = "tracking_field.computercraft.";
private final Metric metric;
private final Aggregate aggregate;
public AggregatedMetric( Metric metric, Aggregate aggregate )
{
this.metric = metric;
this.aggregate = aggregate;
}
public Metric metric()
{
return metric;
}
public Aggregate aggregate()
{
return aggregate;
}
public static Stream<AggregatedMetric> aggregatedMetrics() public static Stream<AggregatedMetric> aggregatedMetrics()
{ {
Metrics.init(); Metrics.init();

View File

@ -47,7 +47,7 @@ public abstract class ComputerFamilyRecipe extends ComputerConvertRecipe
RecipeUtil.ShapedTemplate template = RecipeUtil.getTemplate( json ); RecipeUtil.ShapedTemplate template = RecipeUtil.getTemplate( json );
ItemStack result = itemStackFromJson( GsonHelper.getAsJsonObject( json, "result" ) ); 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 @Nonnull

View File

@ -10,34 +10,8 @@ import dan200.computercraft.ComputerCraft;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.util.List; 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<FileUpload> files ) public void apply( List<FileUpload> files )
{ {
if( fileId < 0 || fileId >= files.size() ) if( fileId < 0 || fileId >= files.size() )

View File

@ -120,10 +120,8 @@ public class UpgradeRecipeGenerator<T>
{ {
setupCache(); 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 // Suggest possible upgrades which can be applied to this turtle
ITurtleUpgrade left = item.getUpgrade( stack, TurtleSide.LEFT ); ITurtleUpgrade left = item.getUpgrade( stack, TurtleSide.LEFT );
ITurtleUpgrade right = item.getUpgrade( stack, TurtleSide.RIGHT ); ITurtleUpgrade right = item.getUpgrade( stack, TurtleSide.RIGHT );
@ -206,9 +204,8 @@ public class UpgradeRecipeGenerator<T>
public List<T> findRecipesWithOutput( ItemStack stack ) public List<T> findRecipesWithOutput( ItemStack stack )
{ {
// Find which upgrade this item currently has, and so how we could build it. // 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<T> recipes = new ArrayList<>( 0 ); List<T> recipes = new ArrayList<>( 0 );
ITurtleUpgrade left = item.getUpgrade( stack, TurtleSide.LEFT ); ITurtleUpgrade left = item.getUpgrade( stack, TurtleSide.LEFT );

View File

@ -46,9 +46,9 @@ public class ComputerTerminalClientMessage implements NetworkMessage
public void handle( NetworkEvent.Context context ) public void handle( NetworkEvent.Context context )
{ {
Player player = Minecraft.getInstance().player; 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 );
} }
} }
} }

View File

@ -120,10 +120,10 @@ public class UploadFileMessage extends ComputerServerMessage
buf.writeVarInt( slices.size() ); buf.writeVarInt( slices.size() );
for( FileSlice slice : slices ) for( FileSlice slice : slices )
{ {
buf.writeByte( slice.getFileId() ); buf.writeByte( slice.fileId() );
buf.writeVarInt( slice.getOffset() ); buf.writeVarInt( slice.offset() );
ByteBuffer bytes = slice.getBytes().duplicate(); ByteBuffer bytes = slice.bytes().duplicate();
buf.writeShort( bytes.remaining() ); buf.writeShort( bytes.remaining() );
buf.writeBytes( bytes ); buf.writeBytes( bytes );
} }

View File

@ -128,9 +128,9 @@ public class CommandBlockPeripheral implements IPeripheral, ICapabilityProvider
public static void onCapability( AttachCapabilitiesEvent<BlockEntity> event ) public static void onCapability( AttachCapabilitiesEvent<BlockEntity> event )
{ {
BlockEntity tile = event.getObject(); 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.addCapability( CAP_ID, peripheral );
event.addListener( peripheral::invalidate ); event.addListener( peripheral::invalidate );
} }

View File

@ -19,7 +19,6 @@ import net.minecraft.world.item.enchantment.EnchantmentHelper;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.util.*; import java.util.*;
import java.util.stream.Collectors;
/** /**
* Data providers for items. * Data providers for items.
@ -71,7 +70,7 @@ public class ItemData
.map( ItemData::parseTextComponent ) .map( ItemData::parseTextComponent )
.filter( Objects::nonNull ) .filter( Objects::nonNull )
.map( Component::getString ) .map( Component::getString )
.collect( Collectors.toList() ) ); .toList() );
} }
} }

View File

@ -126,15 +126,6 @@ public final class MonitorWatcher
return state; return state;
} }
private static final class PlayerUpdate private record PlayerUpdate(ServerPlayer player, TileMonitor monitor)
{ {}
final ServerPlayer player;
final TileMonitor monitor;
private PlayerUpdate( ServerPlayer player, TileMonitor monitor )
{
this.player = player;
this.monitor = monitor;
}
}
} }

View File

@ -241,9 +241,9 @@ public class TileMonitor extends TileGeneric
// Otherwise fetch the origin and attempt to get its monitor // Otherwise fetch the origin and attempt to get its monitor
// Note this may load chunks, but we don't really have a choice here. // Note this may load chunks, but we don't really have a choice here.
BlockEntity te = level.getBlockEntity( toWorldPos( 0, 0 ) ); 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; if( clientMonitor != null ) return clientMonitor;
BlockEntity te = level.getBlockEntity( toWorldPos( 0, 0 ) ); 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 // Networking stuff
@ -578,7 +578,7 @@ public class TileMonitor extends TileGeneric
.of( xPos, yPos, zPos, getDirection(), getOrientation() ) .of( xPos, yPos, zPos, getDirection(), getOrientation() )
.add( xIndex, height - yIndex - 1 ); .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; return;
} }
@ -592,8 +592,8 @@ public class TileMonitor extends TileGeneric
double xCharWidth = (width - (RENDER_BORDER + RENDER_MARGIN) * 2.0) / originTerminal.getWidth(); double xCharWidth = (width - (RENDER_BORDER + RENDER_MARGIN) * 2.0) / originTerminal.getWidth();
double yCharHeight = (height - (RENDER_BORDER + RENDER_MARGIN) * 2.0) / originTerminal.getHeight(); 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 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 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 ) ); eachComputer( c -> c.queueEvent( "monitor_touch", c.getAttachmentName(), xCharPos, yCharPos ) );
} }

View File

@ -7,17 +7,8 @@ package dan200.computercraft.shared.peripheral.monitor;
import net.minecraft.core.Direction; 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 ) public XYPair add( float x, float y )
{ {
return new XYPair( this.x + x, this.y + y ); return new XYPair( this.x + x, this.y + y );

View File

@ -786,13 +786,13 @@ public class TurtleBrain implements ITurtleAccess
// Execute the command // Execute the command
long start = System.nanoTime(); long start = System.nanoTime();
TurtleCommandResult result = nextCommand.command.execute( this ); TurtleCommandResult result = nextCommand.command().execute( this );
long end = System.nanoTime(); long end = System.nanoTime();
// Dispatch the callback // Dispatch the callback
if( computer == null ) return; if( computer == null ) return;
computer.getComputer().getMainThreadMonitor().trackWork( end - start, TimeUnit.NANOSECONDS ); computer.getComputer().getMainThreadMonitor().trackWork( end - start, TimeUnit.NANOSECONDS );
int callbackID = nextCommand.callbackID; int callbackID = nextCommand.callbackID();
if( callbackID < 0 ) return; if( callbackID < 0 ) return;
if( result != null && result.isSuccess() ) if( result != null && result.isSuccess() )

View File

@ -7,14 +7,6 @@ package dan200.computercraft.shared.turtle.core;
import dan200.computercraft.api.turtle.ITurtleCommand; 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;
}
} }

View File

@ -25,18 +25,8 @@ public final class RecipeUtil
{ {
private RecipeUtil() {} private RecipeUtil() {}
public static class ShapedTemplate public record ShapedTemplate(int width, int height, NonNullList<Ingredient> ingredients)
{ {
public final int width;
public final int height;
public final NonNullList<Ingredient> ingredients;
public ShapedTemplate( int width, int height, NonNullList<Ingredient> ingredients )
{
this.width = width;
this.height = height;
this.ingredients = ingredients;
}
} }
public static ShapedTemplate getTemplate( JsonObject json ) public static ShapedTemplate getTemplate( JsonObject json )

View File

@ -38,7 +38,7 @@ public class FakeComputerManager implements AutoCloseable
new BasicEnvironment(), new BasicEnvironment(),
new ComputerThread( 1 ), new ComputerThread( 1 ),
new FakeMainThreadScheduler(), new FakeMainThreadScheduler(),
args -> new DummyLuaMachine( args.timeout ) args -> new DummyLuaMachine( args.timeout() )
); );
private final Lock errorLock = new ReentrantLock(); private final Lock errorLock = new ReentrantLock();